From 97f70b0b29eb2a574f0c35e127797469654aa97f Mon Sep 17 00:00:00 2001 From: HugoXK Date: Tue, 24 Nov 2026 14:02:47 +0000 Subject: [PATCH 1/2] test: pin pending, newest-settled and the ci-ok-head rename (#1273) The publisher reported `missing` for a job object the API answers with `status: in_progress` beside a `conclusion` (jobs 138082842033 and 138086900960 in run 45286143428), which sends a reader to look for a job that did run. The fixture expects `pending`, states that absent stays `missing`, pins two settled conclusions to the newest one with both recorded, and drives the real CLI against a fake API to prove an unsettled set creates no check run. The eleven call sites that resolve the in-run aggregate by its literal job id move to `ci-ok-head` in the same commit as the rename, each keeping its assertion, together with the four readers the Lead named (`gateBaseTree.test.ts`, both `mainHealth.test.ts` fixtures, and `gateCompare.test.ts`'s constant). Red on the unbroken tip: 5 of 21 in `test/ciOkPublish.test.ts`, including the CLI fixture, which posts a red check run for an unsettled context. --- test/ciChanges.test.ts | 4 +- test/ciNodeMatrix.test.ts | 6 +- test/ciOk.test.ts | 6 +- test/ciOkPublish.test.ts | 196 +++++++++++++++++++++++++++++++--- test/codeqlRequired.test.ts | 8 +- test/gateBaseTree.test.ts | 2 +- test/gateCompare.test.ts | 40 +++---- test/mainHealth.test.ts | 16 +-- test/reservedContexts.test.ts | 24 +++-- test/visualJobCeiling.test.ts | 4 +- 10 files changed, 238 insertions(+), 68 deletions(-) diff --git a/test/ciChanges.test.ts b/test/ciChanges.test.ts index 3b45eb56..8d0054b5 100644 --- a/test/ciChanges.test.ts +++ b/test/ciChanges.test.ts @@ -213,8 +213,8 @@ test('the deploy job starts only on a deploy flag, runs the syntax checks, and c const changes = jobBlock(workflow, 'changes') assert.match(changes, /deploy: \$\{\{ steps\.classify\.outputs\.deploy \}\}/, 'the changes job must publish the deploy flag') - const ciOk = jobBlock(workflow, 'ci-ok') - assert.match(ciOk, /needs: \[[^\]]*\bdeploy-check\b/, 'ci-ok must accept a skipped deploy-check only through the flag') + const ciOk = jobBlock(workflow, 'ci-ok-head') + assert.match(ciOk, /needs: \[[^\]]*\bdeploy-check\b/, 'ci-ok-head must accept a skipped deploy-check only through the flag') }) test('an empty diff runs everything, because an unreadable diff must not shrink the gate', () => { diff --git a/test/ciNodeMatrix.test.ts b/test/ciNodeMatrix.test.ts index d8e5c36d..aa573932 100644 --- a/test/ciNodeMatrix.test.ts +++ b/test/ciNodeMatrix.test.ts @@ -103,9 +103,9 @@ test('the removed Node 22 leg does not leave a job that a source diff can skip', } }) -test('ci-ok still requires both remaining full-suite jobs', () => { +test('ci-ok-head still requires both remaining full-suite jobs', () => { const text = read('.github/workflows/ci.yml') - const needs = /^ {4}needs:\s*\[([^\]]+)\]$/m.exec(job(text, 'ci-ok').body)?.[1] ?? '' + const needs = /^ {4}needs:\s*\[([^\]]+)\]$/m.exec(job(text, 'ci-ok-head').body)?.[1] ?? '' const names = needs.split(',').map((value) => value.trim()) - for (const id of ['test', 'coverage']) assert.ok(names.includes(id), `ci-ok must still need ${id}; a job dropped from the aggregate would make the gate vacuous`) + for (const id of ['test', 'coverage']) assert.ok(names.includes(id), `ci-ok-head must still need ${id}; a job dropped from the aggregate would make the gate vacuous`) }) diff --git a/test/ciOk.test.ts b/test/ciOk.test.ts index 582a75d4..7b2cae16 100644 --- a/test/ciOk.test.ts +++ b/test/ciOk.test.ts @@ -235,8 +235,8 @@ test('ci runs nightly and can be dispatched by hand, and only a pull request can test('the needs list in ci.yml and the required list in the script agree', async () => { const required = await requiredJobs() const workflow = readFileSync(workflowPath, 'utf8') - const start = workflow.indexOf('\n ci-ok:') - assert.ok(start !== -1, 'ci.yml must declare the ci-ok job') + const start = workflow.indexOf('\n ci-ok-head:') + assert.ok(start !== -1, 'ci.yml must declare the ci-ok-head job') const match = /needs:\s*\[([^\]]*)\]/.exec(workflow.slice(start)) assert.ok(match !== null, 'the ci-ok job must declare needs as an inline list so it can be read here') const listed = match[1]!.split(',').map((entry) => entry.trim()).filter((entry) => entry !== '') @@ -265,7 +265,7 @@ test('the UI mock snapshot is a required pull-request job', async () => { assert.ok(match !== null, `the ${job} job must declare needs as an inline list so it can be read here`) return match[1]!.split(',').map((entry) => entry.trim()).filter((entry) => entry !== '') } - assert.ok(needsOf('ci-ok').includes('mock-check'), 'ci-ok must wait on mock-check, or the required context never sees it') + assert.ok(needsOf('ci-ok-head').includes('mock-check'), 'ci-ok-head must wait on mock-check, or the required context never sees it') assert.ok(needsOf('main-health').includes('mock-check'), 'main-health mirrors ci-ok so the tracker can name the job that failed') const jobStart = workflow.indexOf('\n mock-check:') diff --git a/test/ciOkPublish.test.ts b/test/ciOkPublish.test.ts index 18bb7211..b546e395 100644 --- a/test/ciOkPublish.test.ts +++ b/test/ciOkPublish.test.ts @@ -1,6 +1,11 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { readFileSync } from 'node:fs' +import { spawn, spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { createServer } from 'node:http' +import type { AddressInfo } from 'node:net' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { REQUIRED_JOBS } from '../scripts/ci-ok.mjs' @@ -12,6 +17,7 @@ import { checkRunPayload, jobKey, needsFromJobs, + pendingRequired, runIdFrom, shouldPublish, verdict, @@ -82,15 +88,12 @@ test('the verdict is published by a workflow_run workflow, never by the pull req test('the required context gains a default-branch producer, and the head aggregate cannot retire it', () => { assert.equal(REQUIRED_CHECK, 'ci-ok') assert.equal(HEAD_AGGREGATE_JOB, 'ci-ok-head') - // The in-run aggregate keeps the required name while the publisher is being - // installed: GitHub loads a `workflow_run` file from the default branch, so on - // the pull request that adds it there would otherwise be no `ci-ok` at all and - // the change could never merge. Two producers of one context are safe here - // because every check run at the head sha counts (#175): the publisher's red - // cannot be retired by the head's green. The follow-up renames this job to - // `ci-ok-head`, leaving exactly one producer. - const aggregate = jobBlock(ci, 'ci-ok') - assert.match(aggregate, /^ {4}name: ci-ok$/m, 'the in-run aggregate publishes the required context until the publisher is on the default branch') + // #1273 lands the rename the publisher's comment promised: the in-run + // aggregate is `ci-ok-head`, so `ci-ok` has exactly one producer — the + // publisher's verdict. The case is rewritten rather than deleted because it is + // what pins the single-producer property after the rename. + const aggregate = jobBlock(ci, HEAD_AGGREGATE_JOB) + assert.match(aggregate, /^ {4}name: ci-ok-head$/m, 'the in-run aggregate publishes its own id, not the required context') assert.match(aggregate, /node base\/scripts\/ci-ok\.mjs/, 'the in-run aggregate still evaluates the base tree') const publishers = declaredNames(publish) assert.ok(publishers.includes('publish ci-ok'), 'the workflow publishes a job named for its check') @@ -143,10 +146,85 @@ test('a matrix leg reports under the needs key, and the worse leg wins', () => { assert.equal(both.test?.result, 'failure', 'one green leg must not hide a red one') }) -test('an unfinished job is missing, never a pass', () => { - const needs = needsFromJobs([{ name: 'lint', status: 'in_progress', conclusion: null }]) - assert.equal(needs.lint?.result, 'missing') - assert.equal(verdict({ jobs: [{ name: 'lint', status: 'in_progress', conclusion: null }], eventName: 'pull_request', changes: { source: true } }).ok, false) +// #1273: the API can return `status: in_progress` beside a `conclusion` and a +// `completed_at` (jobs 138082842033 and 138086900960 in run 45286143428). The +// reader printed `missing` for that shape, which sends a reviewer looking for a +// job that did run. An unsettled object is `pending` — still red, and the +// publisher returns before it creates any check run. +test('an unfinished job object is pending, never missing and never a pass', () => { + const jobs = successJobs().map((job) => ({ ...job, id: 1, completed_at: '2026-11-23T23:00:00Z' })) + jobs[jobs.findIndex((job) => job.name === 'changelog')] = { + id: 138082842033, + name: 'changelog', + status: 'in_progress', + conclusion: 'success', + completed_at: '2026-11-23T23:08:29Z', + } + const result = verdict({ jobs, eventName: 'pull_request', changes: { source: true } }) + assert.equal(result.needs.changelog?.result, 'pending', 'an unsettled object is pending, whatever conclusion it names') + assert.equal(result.ok, false, 'pending is red: the merge gate stays fail-closed') + assert.ok( + result.problems.some((problem) => problem.includes('changelog') && problem.includes('pending')), + `the problem names the context and the word pending, got ${result.problems.join('; ')}`, + ) + assert.ok(!result.problems.some((problem) => problem.includes('missing')), 'the job exists; calling it missing sends the reader to the wrong place') + assert.deepEqual(pendingRequired(result.needs), ['changelog'], 'the publisher sees one context it must not publish for') +}) + +test('a context with no job object at all is still missing, not pending', () => { + const jobs = successJobs().filter((job) => job.name !== 'lint').map((job) => ({ ...job, id: 2, completed_at: '2026-11-23T23:00:00Z' })) + const result = verdict({ jobs, eventName: 'pull_request', changes: { source: true } }) + assert.equal(result.needs.lint, undefined, 'an absent job stays absent from needs') + assert.ok( + result.problems.some((problem) => problem.includes('lint') && problem.includes('missing')), + 'absence is still the red word missing, with its own fixture so pending cannot widen to "nothing is missing"', + ) + assert.deepEqual(pendingRequired(result.needs), []) +}) + +test('two settled conclusions for one context: the newest wins and both are listed', () => { + const jobs = successJobs().map((job) => ({ ...job, id: 10, completed_at: '2026-11-24T00:00:00Z' })) + jobs[jobs.findIndex((job) => job.name === 'changelog')] = { + id: 501, + name: 'changelog', + status: 'completed', + conclusion: 'failure', + completed_at: '2026-11-24T00:00:10Z', + } + jobs.push({ id: 502, name: 'changelog', status: 'completed', conclusion: 'success', completed_at: '2026-11-24T00:00:20Z' }) + const result = verdict({ jobs, eventName: 'pull_request', changes: { source: true } }) + assert.equal(result.needs.changelog?.result, 'success', 'the newest settled conclusion is the reading') + const payload = checkRunPayload({ headSha: 'b'.repeat(40), result, runId: 7 }) + assert.match(payload.output.summary, /502/, 'the summary records the conclusion it read') + assert.match(payload.output.summary, /501/, 'and the one it superseded, so two conclusions can be told from none') + assert.match(payload.output.summary, /changelog/) + assert.match(payload.output.summary, /failure/) + assert.match(payload.output.summary, /success/) +}) + +// The card asks for one fixture on one axis: absent, unsettled and settled must +// read as three different things, not as one bucket. The zero-POST half of the +// unsettled case is the CLI fixture below, because "no check run was created" is +// a fact about a request log rather than about a return value. +test('one axis separates absent, unsettled and settled', () => { + const settled = successJobs().map((job) => ({ ...job, id: 21, completed_at: '2026-11-24T00:00:00Z' })) + const context = 'changelog' + + const absent = verdict({ jobs: settled.filter((job) => job.name !== context), eventName: 'pull_request', changes: { source: true } }) + assert.equal(absent.needs[context], undefined, 'absent: no job object, so the key is absent') + assert.ok(absent.problems.some((problem) => problem.includes(context) && problem.includes('missing')), 'absent reads missing and is red') + assert.equal(absent.ok, false) + + const unsettledJobs = settled.map((job) => (job.name === context ? { ...job, status: 'in_progress', conclusion: 'success' } : job)) + const unsettled = verdict({ jobs: unsettledJobs, eventName: 'pull_request', changes: { source: true } }) + assert.equal(unsettled.needs[context]?.result, 'pending', 'unsettled reads pending') + assert.equal(unsettled.ok, false, 'pending is still red') + assert.deepEqual(pendingRequired(unsettled.needs), [context], 'the publisher returns before any POST') + + const settledJobs = [...settled, { id: 22, name: context, status: 'completed', conclusion: 'success', completed_at: '2026-11-24T00:00:30Z' }] + const newest = verdict({ jobs: settledJobs, eventName: 'pull_request', changes: { source: true } }) + assert.equal(newest.needs[context]?.result, 'success', 'settled: the newest settled conclusion wins') + assert.equal(newest.ok, true) }) test('a skipped conditional job passes only when the base classifier says the category is absent', () => { @@ -276,3 +354,93 @@ test('the published body carries only whitelisted enums and a validated head', ( const odd = checkRunPayload({ headSha: 'f'.repeat(40), result: red, runId: 11, runUrl: 'javascript:alert(1)' }) assert.doesNotMatch(odd.output.summary, /javascript:/, 'a URL that is not plain https is not quoted') }) + +// Shape 1 of #1273: while any required context is unsettled the publish job +// creates no `ci-ok` check run at all — not a red one, none. The assertion is +// the request log of a fake API the real CLI talks to, so the count is what the +// job actually did rather than "no run had appeared yet". +test('an unsettled required job makes the publisher create no check run at all', async () => { + const requests: Array<{ method: string; path: string; body: string }> = [] + const headSha = 'f'.repeat(40) + const runId = 4242 + const jobs = successJobs().map((job) => ({ ...job, id: 1, completed_at: '2026-11-24T00:00:00Z' })) + jobs[jobs.findIndex((job) => job.name === 'changelog')] = { + id: 77, + name: 'changelog', + status: 'in_progress', + conclusion: 'success', + completed_at: '2026-11-24T00:00:05Z', + } + const server = createServer((request, response) => { + let body = '' + request.on('data', (chunk) => { + body += String(chunk) + }) + request.on('end', () => { + requests.push({ method: request.method ?? '', path: request.url ?? '', body }) + response.setHeader('content-type', 'application/json') + if (request.method === 'GET' && request.url === `/repos/o/r/actions/runs/${String(runId)}`) { + response.end(JSON.stringify({ + id: runId, + head_sha: headSha, + event: 'push', + conclusion: 'success', + html_url: `https://example.test/runs/${String(runId)}`, + pull_requests: [], + })) + return + } + if (request.method === 'GET' && (request.url ?? '').startsWith(`/repos/o/r/actions/runs/${String(runId)}/jobs`)) { + response.end(JSON.stringify({ jobs })) + return + } + response.statusCode = 404 + response.end(JSON.stringify({ message: 'unexpected route' })) + }) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', () => resolve())) + const checkout = mkdtempSync(join(tmpdir(), 'ci-ok-run-')) + try { + // `gateBlob()` reads the policy blob from the checkout's `base/` tree, so + // the fixture must be a real git repository rather than a directory. + const base = join(checkout, 'base') + mkdirSync(join(base, 'scripts'), { recursive: true }) + writeFileSync(join(base, 'scripts', 'ci-ok.mjs'), '// the policy blob only has to exist\n') + const git = (...args: string[]) => spawnSync('git', ['-C', base, '-c', 'user.name=t', '-c', 'user.email=t@t', ...args], { encoding: 'utf8' }) + assert.equal(git('init', '-q').status, 0) + assert.equal(git('add', 'scripts/ci-ok.mjs').status, 0) + assert.equal(git('commit', '-q', '-m', 'gate').status, 0) + + const { port } = server.address() as AddressInfo + const child = spawn(process.execPath, [fileURLToPath(new URL('../scripts/ci-ok-run.mjs', import.meta.url)), '--repo', checkout], { + env: { + ...process.env, + GITHUB_TOKEN: 'fixture-token', + GITHUB_REPOSITORY: 'o/r', + GITHUB_API_URL: `http://127.0.0.1:${String(port)}`, + CI_OK_RUN_ID: String(runId), + }, + stdio: ['ignore', 'pipe', 'pipe'], + }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (chunk) => { + stdout += String(chunk) + }) + child.stderr.on('data', (chunk) => { + stderr += String(chunk) + }) + const code = await new Promise((resolve) => child.on('close', resolve)) + assert.equal(code, 0, stderr) + assert.match(stdout, /pending/, 'the publisher says pending in its own log, which is where a reader can see it') + assert.match(stdout, /changelog/, 'and names the context that is still unsettled') + assert.deepEqual( + requests.filter((request) => request.method === 'POST'), + [], + 'zero check-run POST: an unsettled required set publishes nothing', + ) + } finally { + server.close() + rmSync(checkout, { recursive: true, force: true }) + } +}) diff --git a/test/codeqlRequired.test.ts b/test/codeqlRequired.test.ts index 3de0d188..5c30aa6e 100644 --- a/test/codeqlRequired.test.ts +++ b/test/codeqlRequired.test.ts @@ -227,16 +227,16 @@ test('codeql-required is in ci-ok needs, is never skippable, and adds no merge_g ) const ci = readFileSync(ciWorkflowPath, 'utf8') - const start = ci.indexOf('\n ci-ok:') - assert.ok(start !== -1, 'ci.yml must declare the ci-ok job') + const start = ci.indexOf('\n ci-ok-head:') + assert.ok(start !== -1, 'ci.yml must declare the ci-ok-head job') const needs = /needs:\s*\[([^\]]*)\]/.exec(ci.slice(start)) - assert.ok(needs !== null, 'the ci-ok job must declare needs as an inline list so it can be read here') + assert.ok(needs !== null, 'the ci-ok-head job must declare needs as an inline list so it can be read here') const listed = needs[1]!.split(',').map((entry) => entry.trim()).filter((entry) => entry !== '') assert.ok(listed.includes('codeql-required'), `ci-ok needs must include codeql-required, found ${listed.join(', ')}`) const jobStart = ci.indexOf('\n codeql-required:') assert.ok(jobStart !== -1, 'ci.yml must declare the codeql-required job') - const job = ci.slice(jobStart, ci.indexOf('\n ci-ok:', jobStart)) + const job = ci.slice(jobStart, ci.indexOf('\n ci-ok-head:', jobStart)) // #640: the decision script runs from the base branch tree, so a pull request // cannot edit the code that reads its own analysis. assert.match(job, /run: node base\/scripts\/codeql-required\.mjs/, 'the job must run the base branch copy of the decision script') diff --git a/test/gateBaseTree.test.ts b/test/gateBaseTree.test.ts index bcb0cef9..2d8f9b68 100644 --- a/test/gateBaseTree.test.ts +++ b/test/gateBaseTree.test.ts @@ -39,7 +39,7 @@ const evaluators: Array<[string, string]> = [ ['workflow-lint', 'base/scripts/workflow-injection.mjs'], ['reserved-contexts', 'base/scripts/reserved-contexts.mjs'], ['codeql-required', 'base/scripts/codeql-required.mjs'], - ['ci-ok', 'base/scripts/ci-ok.mjs'], + ['ci-ok-head', 'base/scripts/ci-ok.mjs'], ] for (const [job, script] of evaluators) { diff --git a/test/gateCompare.test.ts b/test/gateCompare.test.ts index 4716fb89..a96c4188 100644 --- a/test/gateCompare.test.ts +++ b/test/gateCompare.test.ts @@ -66,7 +66,7 @@ function withJob(text: string, id: string, body: string[]): string { const STUB_ROWS = [' runs-on: ubuntu-latest', ' steps:', ' - run: true'] -// A head that renames the aggregate away from `ci-ok`. `ci-ok` is not in +// A head that renames the aggregate away from `ci-ok-head`. The aggregate is not in // `REQUIRED_JOBS` — it is the aggregate, looked up on its own — so moving the id // is the shape that used to lose the `needs:`/evaluator/`path: base` checks. function aggregateRename(id: string): string { @@ -148,7 +148,7 @@ test('the checked-in workflow is its own base, so an untouched pull request is a assert.equal(result.lines.length, 1) assert.match(result.lines[0]!, /gate-compare/) assert.match(result.lines[0]!, new RegExp(String(REQUIRED_JOBS.length))) - assert.match(result.lines[0]!, /`ci-ok` runs `node base\/scripts\/ci-ok\.mjs`/, 'the line names the id it checked') + assert.match(result.lines[0]!, /`ci-ok-head` runs `node base\/scripts\/ci-ok\.mjs`/, 'the line names the id it checked') }) test('the accepted aggregate ids are explicit data, and the publisher reads the same two names', async () => { @@ -157,7 +157,7 @@ test('the accepted aggregate ids are explicit data, and the publisher reads the // acceptance cases below. const module: Record = await import('../scripts/lib/gate-compare.mjs') assert.deepEqual(module.AGGREGATE_JOBS, ['ci-ok-head', 'ci-ok'], 'the transition set is exact: nothing outside it may pass') - assert.equal(AGGREGATE_JOB, 'ci-ok', 'the base tree declares `ci-ok` today; #1273 moves it to `ci-ok-head`') + assert.equal(AGGREGATE_JOB, 'ci-ok-head', 'the base tree declares `ci-ok-head` after #1273 renamed the in-run aggregate') const publisher = read('scripts/lib/ci-ok-run.mjs') assert.match(publisher, /export const HEAD_AGGREGATE_JOB = 'ci-ok-head'/, 'the publisher and the comparator agree on the new id') assert.match(publisher, /export const REQUIRED_CHECK = 'ci-ok'/, 'and on the old one') @@ -177,13 +177,13 @@ test('acceptance 2: an aggregate step that no longer runs the base evaluator is assert.equal(result.ok, false) const text = result.problems.join('\n') assert.match(text, new RegExp(`does not run the base evaluator \`${REQUIRED_EVALUATOR.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\``)) - assert.match(text, /`ci-ok`/) + assert.match(text, /`ci-ok-head`/) }) test('acceptance 3: a head that adds its own job and waits on it is allowed', () => { const withExtraJob = ci.replace( - ' ci-ok:\n', - ' extra-gate:\n name: extra-gate\n runs-on: ubuntu-latest\n steps:\n - run: true\n\n ci-ok:\n', + ` ${AGGREGATE_JOB}:\n`, + ` extra-gate:\n name: extra-gate\n runs-on: ubuntu-latest\n steps:\n - run: true\n\n ${AGGREGATE_JOB}:\n`, ) assert.notEqual(withExtraJob, ci, 'the fixture inserted a job') const head = editJob(withExtraJob, AGGREGATE_JOB, (block) => @@ -291,13 +291,13 @@ test('no top-level block may change, be added or be lost', () => { assert.doesNotMatch(text, /NODE_OPTIONS|--require/, 'an env value is not echoed into the refusal') }) -test('a required job missing from `ci-ok.needs` is refused, naming the dependency', () => { +test('a required job missing from `ci-ok-head.needs` is refused, naming the dependency', () => { const head = editJob(ci, AGGREGATE_JOB, (block) => block.map((line) => (line.startsWith(' needs: ') ? line.replace('mock-check, ', '') : line)), ) const result = compareGate({ base: ci, head }) assert.equal(result.ok, false) - assert.match(result.problems.join('\n'), /`ci-ok` does not depend on required job `mock-check`/) + assert.match(result.problems.join('\n'), /`ci-ok-head` does not depend on required job `mock-check`/) }) test('the `path: base` checkout is pinned: removing it is a refusal', () => { @@ -327,7 +327,7 @@ test('acceptance 1: an aggregate id outside the accepted set is refused, naming }) test('acceptance 2: a head declaring both accepted aggregate ids is refused, naming both', () => { - const head = withJob(ci, 'ci-ok-head', [' name: ci-ok-head', ...STUB_ROWS]) + const head = withJob(ci, 'ci-ok', [' name: ci-ok', ...STUB_ROWS]) assert.notEqual(head, ci, 'the fixture added the second candidate') const result = compareGate({ base: ci, head }) assert.equal(result.ok, false, 'two candidates for one aggregate is not a pass') @@ -337,29 +337,29 @@ test('acceptance 2: a head declaring both accepted aggregate ids is refused, nam assert.equal(result.lines.length, 0) }) -test('acceptance 3: a head with exactly one accepted aggregate id passes, and the line names the id it checked', () => { - const head = aggregateRename('ci-ok-head') +test('acceptance 3: a head that still declares the old id while the base declares ci-ok-head is checked under it', () => { + const head = aggregateRename('ci-ok') const result = compareGate({ base: ci, head }) assert.equal(result.ok, true, result.problems.join('\n')) assert.equal(result.lines.length, 1) - assert.match(result.lines[0]!, /`ci-ok-head` runs `node base\/scripts\/ci-ok\.mjs`/, 'the green line names the id it read') - assert.doesNotMatch(result.lines[0]!, /`ci-ok` runs /, 'a green line cannot credit an id that was not read') + assert.match(result.lines[0]!, /`ci-ok` runs `node base\/scripts\/ci-ok\.mjs`/, 'the green line names the id it read') + assert.doesNotMatch(result.lines[0]!, /`ci-ok-head` runs /, 'a green line cannot credit an id that was not read') }) test('acceptance 4: the three aggregate checks follow the accepted id the head declares', () => { - const renamed = aggregateRename('ci-ok-head') - const droppedNeeds = editJob(renamed, 'ci-ok-head', (block) => + const renamed = aggregateRename('ci-ok') + const droppedNeeds = editJob(renamed, 'ci-ok', (block) => block.map((line) => (line.startsWith(' needs: ') ? line.replace('mock-check, ', '') : line)), ) - const noEvaluator = editJob(renamed, 'ci-ok-head', (block) => + const noEvaluator = editJob(renamed, 'ci-ok', (block) => block.map((line) => (line.trim() === `run: ${REQUIRED_EVALUATOR}` ? ' run: exit 0' : line)), ) - const noCheckout = editJob(renamed, 'ci-ok-head', (block) => block.filter((line) => line.trim() !== 'path: base')) + const noCheckout = editJob(renamed, 'ci-ok', (block) => block.filter((line) => line.trim() !== 'path: base')) for (const [label, head, expected] of [ - ['needs', droppedNeeds, /`ci-ok-head` does not depend on required job `mock-check`/], - ['evaluator', noEvaluator, /`ci-ok-head` does not run the base evaluator/], - ['path: base', noCheckout, /`ci-ok-head` does not check the gate out under `path: base`/], + ['needs', droppedNeeds, /`ci-ok` does not depend on required job `mock-check`/], + ['evaluator', noEvaluator, /`ci-ok` does not run the base evaluator/], + ['path: base', noCheckout, /`ci-ok` does not check the gate out under `path: base`/], ] as const) { const result = compareGate({ base: ci, head }) assert.equal(result.ok, false, `${label} must still be refused when the aggregate id is renamed`) diff --git a/test/mainHealth.test.ts b/test/mainHealth.test.ts index 462c2f86..ebcbd911 100644 --- a/test/mainHealth.test.ts +++ b/test/mainHealth.test.ts @@ -152,7 +152,7 @@ test('the newest tracker is the one commented on and closed', () => { test('the reporter selection names failures and ignores the aggregate', () => { const needs = { - 'ci-ok': { result: 'failure' }, + 'ci-ok-head': { result: 'failure' }, lint: { result: 'success' }, test: { result: 'failure' }, coverage: { result: 'cancelled' }, @@ -240,11 +240,11 @@ test('only the reporter job holds issues: write', () => { } }) -test('the reporter is gated to main, depends on ci-ok and is not itself required', () => { +test('the reporter is gated to main, depends on the aggregate and is not itself required', () => { const block = jobBlock(ci, 'main-health') assert.match(block, /^ {4}if: .*refs\/heads\/main/m, 'the condition must name the default branch, not a wildcard') - assert.match(block, /^ {4}needs: .*\bci-ok\b/m, 'the reporter reads the aggregate result') - assert.doesNotMatch(jobBlock(ci, 'ci-ok'), /^ {4}needs:.*\bmain-health\b/m, 'the reporter must never become a required check: a red reporter would block merges') + assert.match(block, /^ {4}needs: .*\bci-ok-head\b/m, 'the reporter reads the aggregate result') + assert.doesNotMatch(jobBlock(ci, 'ci-ok-head'), /^ {4}needs:.*\bmain-health\b/m, 'the reporter must never become a required check: a red reporter would block merges') }) test('the reporter serialises per red state and searches by label', () => { @@ -278,16 +278,16 @@ function needsOf(job: string): string[] { } test('the reporter depends on the jobs it must name, not only the aggregate', () => { - const required = needsOf('ci-ok') + const required = needsOf('ci-ok-head') const reporter = needsOf('main-health') - assert.ok(required.length > 1, 'ci-ok gates on the individual jobs') + assert.ok(required.length > 1, 'ci-ok-head gates on the individual jobs') for (const job of required) { assert.ok( reporter.includes(job), `main-health must depend on ${job} to name it as failing; it depends on ${reporter.join(', ')}`, ) } - assert.ok(reporter.includes('ci-ok'), 'the aggregate result still decides green or red') + assert.ok(reporter.includes('ci-ok-head'), 'the aggregate result still decides green or red') }) // --- #343: the label bootstrap belongs to the create path ------------------- @@ -339,7 +339,7 @@ function runReporter(env: Record) { } const GREEN_RUN = { - NEEDS: JSON.stringify({ 'ci-ok': { result: 'success' } }), + NEEDS: JSON.stringify({ 'ci-ok-head': { result: 'success' } }), GITHUB_EVENT_NAME: 'push', GITHUB_REF: MAIN_REF, GITHUB_SHA: CLEARING_SHA, diff --git a/test/reservedContexts.test.ts b/test/reservedContexts.test.ts index 613b3fa4..044f3d52 100644 --- a/test/reservedContexts.test.ts +++ b/test/reservedContexts.test.ts @@ -63,14 +63,13 @@ const SHADOW_NAME = [ '', ].join('\n') -test('the reserved table allows ci-ok in both canonical producers and the other contexts only in their own file', async () => { +test('the reserved table allows ci-ok only in the publisher and the other contexts only in their own file', async () => { const { RESERVED_CONTEXTS } = await lib() - const ciOk = RESERVED_CONTEXTS['ci-ok'] ?? [] - assert.ok(ciOk.includes('ci.yml'), 'the in-run aggregate at ci.yml:808 publishes ci-ok today') - assert.ok( - ciOk.includes('ci-ok-publish.yml'), - 'the recorded producer is ci-ok-publish.yml (.github/agent/required-checks.md); an honest sample must not be judged red', - ) + // #1273 renamed the in-run aggregate to `ci-ok-head`, so allowing `ci.yml` + // here would let an honest tree be judged red and would keep a second + // producer legal after the rename. The entry is the publisher alone. + assert.deepEqual(RESERVED_CONTEXTS['ci-ok'], ['ci-ok-publish.yml']) + assert.equal(RESERVED_CONTEXTS['ci-ok-head'], undefined, 'the head aggregate is not a required context and must not be reserved') assert.deepEqual(RESERVED_CONTEXTS['review-gate'], ['review-gate.yml']) assert.deepEqual(RESERVED_CONTEXTS['pr-lint'], ['pr-lint.yml']) }) @@ -108,12 +107,15 @@ test('the repository\'s own workflows are the honest sample and produce no findi assert.ok(report.files.length >= 10, `every workflow file is read, got ${String(report.files.length)}`) }) -test('a canonical file is allowed and every other file is not', async () => { +test('ci.yml no longer publishes the required context, and any other file that does is a finding', async () => { const { scanWorkflowText } = await lib() const ci = readFileSync(ciPath, 'utf8') const inCi = scanWorkflowText(ci, 'ci.yml') - assert.deepEqual(inCi.filter((finding) => finding.context === 'ci-ok'), [], 'ci.yml publishes ci-ok legitimately') - const renamed = scanWorkflowText(ci, 'review-gate.yml') + // #1273 renamed the in-run aggregate to `ci-ok-head`, which is not a reserved + // context; the publisher writes `ci-ok` through the API, not as a job name. + assert.deepEqual(inCi.filter((finding) => finding.context === 'ci-ok'), [], 'ci.yml no longer produces the required context') + const shadow = ['jobs:', ' ci-ok:', ' name: ci-ok', ' runs-on: ubuntu-latest', ''].join('\n') + const renamed = scanWorkflowText(shadow, 'review-gate.yml') assert.deepEqual( renamed.filter((finding) => finding.context === 'ci-ok').map((finding) => finding.kind).sort(), ['job-id', 'name'], @@ -226,7 +228,7 @@ test('ci.yml runs the base-tree scanner over the head workflows and ci-ok requir const { REQUIRED_JOBS } = (await import('../scripts/ci-ok.mjs')) as { REQUIRED_JOBS: string[] } assert.ok(REQUIRED_JOBS.includes('reserved-contexts'), 'ci-ok must fail when the new job fails') - const ciOkStart = workflow.indexOf('\n ci-ok:') + const ciOkStart = workflow.indexOf('\n ci-ok-head:') const needsMatch = /needs:\s*\[([^\]]*)\]/.exec(workflow.slice(ciOkStart)) assert.ok(needsMatch !== null, 'ci-ok must declare needs as an inline list') assert.ok( diff --git a/test/visualJobCeiling.test.ts b/test/visualJobCeiling.test.ts index 509c0149..5bec3403 100644 --- a/test/visualJobCeiling.test.ts +++ b/test/visualJobCeiling.test.ts @@ -59,8 +59,8 @@ test('the visual job keeps its name and its place in the required set', () => { assert.match(workflow, /\n {2}visual:\n/, 'the visual job was renamed or removed') assert.match( workflow, - /needs: \[ci-ok,[^\]]*\bvisual\b[^\]]*\]/, - 'the visual job is not in the aggregate ci-ok needs, so a red matrix would not fail the required check', + /needs: \[ci-ok-head,[^\]]*\bvisual\b[^\]]*\]/, + 'the visual job is not in the aggregate ci-ok-head needs, so a red matrix would not fail the required check', ) }) From 379293b85b5f070515070d7f3524850d1669201f Mon Sep 17 00:00:00 2001 From: HugoXK Date: Tue, 24 Nov 2026 14:02:58 +0000 Subject: [PATCH 2/2] ci: report an unsettled context as pending and give ci-ok one producer (#1273) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `resultOf` in `scripts/lib/ci-ok-run.mjs` returned `missing` for every job object that was not `completed`, so the contradiction the API allows — `status: in_progress` with a `conclusion` and a `completed_at` — was resolved to the one word that sends a reviewer looking for a job that did run. An unsettled object is now `pending`; a context with no object at all is still `missing`, and both are red. Two settled conclusions for one display name are read newest-first, and every object seen for a required context is recorded in the published summary with id, status, conclusion and `completed_at`, so "two conclusions" can be told from "no conclusions". While any required context is unsettled the publisher creates no check run at all: the word goes to its own log and the absent context stays red. The check lands after `loadJobs` and before `publish`, because the run-level skip only inspects the run object and a concluded run can still carry an `in_progress` job. The in-run aggregate is renamed to `ci-ok-head` in both the job id and its `name:`, with `main-health`'s `needs` list and key, the reserved-contexts table (now `ci-ok-publish.yml` alone) and the comparator's base id following it. The accepted set `['ci-ok-head', 'ci-ok']` is unchanged, so a branch still carrying the old id is checked under it and a head declaring both is refused. The scanner's blind spot for the refresh producer is written beside the rule in `docs/code-standards.md`. --- .github/workflows/ci-ok-publish.yml | 9 +- .github/workflows/ci.yml | 20 +++-- changelog.d/1273.fixed.md | 1 + docs/autonomous-dev.md | 29 +++--- docs/code-standards.md | 17 ++++ scripts/ci-ok-run.mjs | 23 ++++- scripts/lib/ci-ok-run.d.mts | 22 +++++ scripts/lib/ci-ok-run.mjs | 132 +++++++++++++++++++++++++--- scripts/lib/gate-compare.mjs | 10 ++- scripts/lib/main-health.mjs | 5 +- scripts/lib/reserved-contexts.mjs | 15 ++-- scripts/main-health.mjs | 3 +- 12 files changed, 231 insertions(+), 55 deletions(-) create mode 100644 changelog.d/1273.fixed.md diff --git a/.github/workflows/ci-ok-publish.yml b/.github/workflows/ci-ok-publish.yml index 40706135..ef654377 100644 --- a/.github/workflows/ci-ok-publish.yml +++ b/.github/workflows/ci-ok-publish.yml @@ -10,11 +10,10 @@ name: CI verdict # GitHub always loads a `workflow_run` workflow from the default branch. This # one reads the finished `CI` run's job results, evaluates them with the default # branch's required list and classifier, and publishes the `ci-ok` check run -# itself. The in-run aggregate inside `ci.yml` keeps publishing `ci-ok` for one -# step, because on the pull request that adds this file there would otherwise be -# no `ci-ok` at all and the change could never merge. Every check run at the head -# sha counts, so the head's green cannot retire this red one; a follow-up renames -# the in-run job to `ci-ok-head`, leaving one producer. +# itself. #1273 renamed the in-run aggregate inside `ci.yml` to `ci-ok-head`, so +# `ci-ok` has exactly one producer — this verdict — and every check run at the +# head sha still counts: no green can retire a red one. While a required context +# is still unsettled this job publishes nothing at all and logs `pending`. on: workflow_run: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cfeafc58..34182ab0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -850,8 +850,8 @@ jobs: fi exit "$status" - ci-ok: - name: ci-ok + ci-ok-head: + name: ci-ok-head if: always() needs: [changes, lint, typecheck, test, coverage, build, visual, docker, audit, dependency-review, changelog, version, risk, restore-drill, action-pins, workflow-lint, reserved-contexts, secret-scan, codeql-required, mock-check, deploy-check] runs-on: ubuntu-latest @@ -886,22 +886,24 @@ jobs: GITHUB_EVENT_NAME: ${{ github.event_name }} run: node base/scripts/ci-ok.mjs - # #305: a red `main` used to be invisible. `ci-ok` computed the commit's + # #305: a red `main` used to be invisible. The aggregate computed the commit's # health and stopped, no job held a write scope on issues, and the branch was # noticed only by a person who went and looked. This is the one job allowed to write, # and it writes one issue: create it, comment on it, or close it. Every # decision is `scripts/lib/main-health.mjs`; the job only gathers the input. # - # It is deliberately not in `ci-ok`'s `needs`: a reporter that fails must not - # be able to fail the merge gate as well. + # It is deliberately not in `ci-ok-head`'s `needs`: a reporter that fails must + # not be able to fail the merge gate as well. # - # Its `needs` mirrors `ci-ok`'s so the tracker can name the jobs that actually - # failed. With only `ci-ok` in the list the reporter saw the aggregate and - # nothing else, and every tracker said "ci-ok did not report success". + # Its `needs` mirrors `ci-ok-head`'s so the tracker can name the jobs that + # actually failed. With only the aggregate in the list the reporter saw the + # aggregate and nothing else, and every tracker said it did not report success. + # The reporter reads the aggregate by the job id it has here, so #1273's + # rename moves both sides together. main-health: name: main-health if: always() && github.ref == 'refs/heads/main' - needs: [ci-ok, changes, lint, typecheck, test, coverage, build, visual, docker, audit, dependency-review, changelog, version, risk, restore-drill, action-pins, workflow-lint, reserved-contexts, secret-scan, codeql-required, mock-check, deploy-check] + needs: [ci-ok-head, changes, lint, typecheck, test, coverage, build, visual, docker, audit, dependency-review, changelog, version, risk, restore-drill, action-pins, workflow-lint, reserved-contexts, secret-scan, codeql-required, mock-check, deploy-check] runs-on: ubuntu-latest timeout-minutes: 5 permissions: diff --git a/changelog.d/1273.fixed.md b/changelog.d/1273.fixed.md new file mode 100644 index 00000000..5ea0f597 --- /dev/null +++ b/changelog.d/1273.fixed.md @@ -0,0 +1 @@ +A required context that GitHub reports as still running is now `pending` instead of `missing`: the publisher creates no `ci-ok` check run while any required job is unsettled, and the published summary lists every conclusion it saw per context so a re-run can be told from a job that never reported. The in-run aggregate is renamed to `ci-ok-head`, leaving `ci-ok` with one producer. diff --git a/docs/autonomous-dev.md b/docs/autonomous-dev.md index 73e45e01..d8694e5b 100644 --- a/docs/autonomous-dev.md +++ b/docs/autonomous-dev.md @@ -300,13 +300,11 @@ as the checks API reports them, in [`.github/agent/required-checks.md`](../.github/agent/required-checks.md); that file is the record and not the gate — branch protection is an owner action. -`ci-ok` is also published by `ci-ok-publish.yml`, a `workflow_run` workflow that +`ci-ok` is published by `ci-ok-publish.yml`, a `workflow_run` workflow that GitHub always takes from the default branch, so the copy that judges a change is -never the one under test. The aggregate job inside `ci.yml` keeps publishing the -same context for one step — the pull request that adds the publisher would -otherwise carry no `ci-ok` and could never merge; every check run at the head sha -counts, so the head's green cannot retire the publisher's red — and a follow-up -renames it to `ci-ok-head`. See +never the one under test. The aggregate job inside `ci.yml` is `ci-ok-head` since +`#1273`, so the required context has one producer; every check run at the head sha +counts, so the head's green cannot retire the publisher's red. See [Gate integrity](#gate-integrity-the-evaluator-runs-from-the-base-branch). `ci-ok` is green only when all of these are green at the same tip: @@ -443,7 +441,7 @@ the base branch into `base/` and executed from there: | `workflow-lint` | `node base/scripts/workflow-injection.mjs --workflows .github/workflows --allowlist base/.github/agent/workflow-injection-allowlist.json` | | `reserved-contexts` | `node base/scripts/reserved-contexts.mjs --workflows .github/workflows` | | `codeql-required` | `node base/scripts/codeql-required.mjs` | -| `ci-ok` / `ci-ok-head` (the in-run aggregate; `#1273` renames it and both ids are accepted meanwhile) | `node base/scripts/ci-ok.mjs` | +| `ci-ok-head` (the in-run aggregate; a branch still carrying the pre-`#1273` id `ci-ok` is accepted while the transition runs) | `node base/scripts/ci-ok.mjs` | | `ci-ok` (the publisher's verdict) | `node base/scripts/ci-ok-run.mjs`, run by `ci-ok-publish.yml` | | CodeQL gate | `node base/scripts/codeql-gate.mjs --sarif codeql-results --baseline base/.github/agent/codeql-baseline.json` | @@ -489,12 +487,11 @@ always loads a `workflow_run` workflow from the default branch, so the file that decides is never the one under test. It reads the finished run's job results from the API, re-derives the change flags with the default branch's `ci-changes.mjs` over the same diff, evaluates the default branch's `REQUIRED_JOBS` and -`SKIP_WHEN`, and creates the `ci-ok` check run itself. The in-run aggregate still -publishes the same context in this step, but it is never read as evidence — the -publisher matches required jobs by name and answers `null` for both `ci-ok` and -`ci-ok-head` — so a head that rewrites its `run:` line to `exit 0` changes only -that job's own result, and every check run at the head sha counts, so the -publisher's red still blocks. A required job the head deletes or renames is +`SKIP_WHEN`, and creates the `ci-ok` check run itself. The in-run aggregate +publishes `ci-ok-head`, and it is never read as evidence — the publisher matches +required jobs by name and answers `null` for both `ci-ok` and `ci-ok-head` — so a +head that rewrites its `run:` line to `exit 0` changes only that job's own result, +and every check run at the head sha counts, so the publisher's red still blocks. A required job the head deletes or renames is reported missing by name, which is red — the same answer as dropping it from `needs` inside the run. A run the platform `cancelled` publishes nothing, because the run that replaced it owns the verdict. A `pull_request` run whose payload no @@ -558,9 +555,9 @@ enumerates the open pull request heads and publishes a red `ci-ok` where the newest verdict that names a policy was computed under a different policy, so a green verdict does not outlive the required set it was computed under — a head whose verdict predates a newly required job stops being satisfying the moment that -job reaches `main`. Two shapes are deliberately not verdicts. The in-run `ci-ok` -job in `.github/workflows/ci.yml` publishes the same check name, finishes before -the publisher and names no policy (it is the aggregate #855 removed as evidence); +job reaches `main`. Two shapes are deliberately not verdicts. The in-run +`ci-ok-head` job in `.github/workflows/ci.yml` finishes before the publisher and +names no policy (it is the aggregate #855 removed as evidence); while a `ci-ok-publish.yml` run for the head is queued or in progress the sweep skips that head, because its verdict is imminent and a red published against the aggregate would be permanent. Once the CI workflow has finished and no publisher diff --git a/docs/code-standards.md b/docs/code-standards.md index 9469a080..f0b4783c 100644 --- a/docs/code-standards.md +++ b/docs/code-standards.md @@ -120,6 +120,23 @@ not a conclusion. - Never admin-merge, never bypass a required check, never force-push `main`. - One PR per issue. Push to the existing branch instead of opening a duplicate. +## Required contexts + +A required context is green only when its latest **settled** conclusion is +`success`. `status != completed` is `pending`, never `missing`: a context whose +only job object is unsettled after the run finished is reported as `pending` and +stays red, and the publisher creates no check run at all while any required +context is unsettled. A context with no job object at all is `missing` and stays +red — the two words are distinct on purpose, because `missing` sends a reader to +look for a job that did run. When one context carries several conclusions at one +commit, the newest settled one decides, and every conclusion seen is recorded in +the published summary, so "two conclusions" can be told from "no conclusions" +without re-querying the API. `ci-ok` has one workflow-file producer, +`ci-ok-publish.yml`; `ci-ok-refresh.yml` posts a red `ci-ok` through the API on +every push to `main`, and `scripts/lib/reserved-contexts.mjs` reads job ids and +job-level `name:` values, so that producer sits outside the scanner's view by +design and must keep blocking — deleting it would let a stale green stand. + ## The issue tie in a PR body `pr-lint` requires every pull request to name the issue it belongs to, in one of diff --git a/scripts/ci-ok-run.mjs b/scripts/ci-ok-run.mjs index 290518f7..873026a7 100644 --- a/scripts/ci-ok-run.mjs +++ b/scripts/ci-ok-run.mjs @@ -6,9 +6,16 @@ // // `ci-ok-publish.yml` runs this on `workflow_run`, after a `CI` run completes, // so the file that decides the merge is the default branch's and not the pull -// request's. The aggregate inside `ci.yml` keeps publishing `ci-ok` until the -// follow-up renames it to `ci-ok-head`; every check run at the head sha counts, -// so the head's green cannot retire this verdict. +// request's. #1273 renamed the in-run aggregate to `ci-ok-head`, so the +// required context `ci-ok` has one producer — this verdict — and every check +// run at the head sha still counts: no green can retire a red. +// +// A concluded run can still carry an unsettled job object (`status: +// in_progress` beside a `conclusion`, jobs 138082842033 and 138086900960). +// While any required context is unsettled this publishes nothing at all: the +// word `pending` goes to this log, and the absent context stays red through +// the reader's `missing` branch. A red check run that invented a conclusion +// would keep the duplicate-producer shape #863 removed. // // The trigger names the finished run as an integer (`CI_OK_RUN_ID`, set from // `github.event.workflow_run.id`), and every fact about that run is then read @@ -60,6 +67,7 @@ import { checkRunPayload, lostItsBase, mergedPullRequestOf, + pendingRequired, runIdFrom, skipDetail, skipReason, @@ -290,6 +298,15 @@ async function main() { } catch (error) { result = failingResult(`ci-ok could not be computed from run ${String(run.id)}: ${error.message}`) } + // #1273, shape 1: a required context that has not settled is not a verdict. + // This lands after `loadJobs` (`:273`) and before `publish` (`:301`) on + // purpose — the run-level skip above inspects only the run object, so a + // concluded run carrying an `in_progress` job walks past it. + const pending = pendingRequired(result.needs) + if (pending.length > 0) { + console.log(`ci-ok-run: pending — run ${String(run.id)} has unsettled required job(s): ${pending.join(', ')}; no check run is created`) + return + } const payload = checkRunPayload({ headSha: String(run.head_sha), result, diff --git a/scripts/lib/ci-ok-run.d.mts b/scripts/lib/ci-ok-run.d.mts index f404828b..a94d4b96 100644 --- a/scripts/lib/ci-ok-run.d.mts +++ b/scripts/lib/ci-ok-run.d.mts @@ -2,9 +2,23 @@ // finished `CI` run's job list and publishes the `ci-ok` check run itself, so // the suite needs the pure half to assert what a head cannot do. export interface FinishedJob { + id?: number name?: string status?: string conclusion?: string | null + completed_at?: string | null +} + +/** One job object seen for a required context, as the published summary quotes + * it (#1273). `status` and `conclusion` are whitelisted values or `unknown`. */ +export interface SeenConclusion { + key: string + name: string + id: number | null + status: string + conclusion: string + completedAt: string + result: string } export interface JobResult { @@ -16,6 +30,8 @@ export interface AggregateVerdict { lines: string[] problems: string[] ok: boolean + /** Present on a verdict built from a job list; a hand-built red may omit it. */ + seen?: SeenConclusion[] } export interface AggregateInput { @@ -49,9 +65,15 @@ export declare const HEAD_AGGREGATE_JOB: string export declare const CHECK_STATUS: string export declare const CHECK_CONCLUSIONS: Readonly<{ pass: string; fail: string }> export declare const SKIP_REASONS: Readonly<{ superseded: string; merged: string; notARun: string }> +/** #1273: the word an unsettled job object gets; red, and not `missing`. */ +export declare const PENDING: string export declare function runIdFrom(input?: { args?: string[]; env?: Record }): number export declare function jobKey(name: string, required?: string[]): string | null +export declare function conclusionsSeen(jobs: FinishedJob[], required?: string[]): SeenConclusion[] export declare function needsFromJobs(jobs: FinishedJob[], required?: string[]): Record +/** The required contexts whose evidence is unsettled; non-empty means the + * publisher creates no check run. */ +export declare function pendingRequired(needs: Record | null | undefined | unknown, required?: string[]): string[] export declare function verdict(input: AggregateInput): AggregateVerdict export declare function baseShas(run: FinishedRun | null): string[] export declare function lostItsBase(run: FinishedRun | null): boolean diff --git a/scripts/lib/ci-ok-run.mjs b/scripts/lib/ci-ok-run.mjs index d750514b..63fec7f9 100644 --- a/scripts/lib/ci-ok-run.mjs +++ b/scripts/lib/ci-ok-run.mjs @@ -76,11 +76,62 @@ export function jobKey(name, required = REQUIRED_JOBS) { return null } -// A job that has not finished, or reports no conclusion, is not a pass. +/** The word an unsettled job object gets. `pending` is red, and it is not + * `missing`: the job exists and the API has not settled it, so a reader must + * not go looking for a job that did run (#1273). `missing` is reserved for a + * required context with no job object at all. */ +export const PENDING = 'pending' + +const SETTLED = 'completed' + +// A job object that has not settled is pending; one that settled with no +// conclusion is pending too, because no conclusion is not a pass. `missing` is +// left to `needsFromJobs`, which omits a context it saw no object for. function resultOf(job) { if (job === null || typeof job !== 'object') return 'missing' - if (job.status !== 'completed') return 'missing' - return typeof job.conclusion === 'string' && job.conclusion !== '' ? job.conclusion : 'missing' + if (job.status !== SETTLED) return PENDING + return typeof job.conclusion === 'string' && job.conclusion !== '' ? job.conclusion : PENDING +} + +// The values a check-run summary may quote. Anything else the API returns is +// named `unknown`, so the request body never carries an unvalidated job string. +const JOB_STATUSES = new Set(['queued', 'in_progress', 'completed', 'waiting', 'requested', 'pending']) +const JOB_CONCLUSIONS = new Set([ + 'success', + 'failure', + 'neutral', + 'cancelled', + 'skipped', + 'timed_out', + 'action_required', + 'stale', + 'startup_failure', +]) +const COMPLETED_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/ + +function summaryWord(value, allowed) { + return typeof value === 'string' && allowed.has(value) ? value : 'unknown' +} + +/** Every job object seen for a required context, in the order the API returned + * them. The published summary quotes this list, so "two conclusions" can be + * told from "no conclusions" without re-querying the API (#1273). */ +export function conclusionsSeen(jobs, required = REQUIRED_JOBS) { + const seen = [] + for (const job of Array.isArray(jobs) ? jobs : []) { + const key = jobKey(job?.name, required) + if (key === null) continue + seen.push({ + key, + name: typeof job?.name === 'string' ? job.name : '', + id: Number.isSafeInteger(job?.id) && job.id > 0 ? job.id : null, + status: summaryWord(job?.status, JOB_STATUSES), + conclusion: summaryWord(job?.conclusion, JOB_CONCLUSIONS), + completedAt: typeof job?.completed_at === 'string' && COMPLETED_AT.test(job.completed_at) ? job.completed_at : '', + result: resultOf(job), + }) + } + return seen } // Two legs of one required job must not be able to hide each other's red: the @@ -94,22 +145,63 @@ function worse(left, right) { return left } +// Two objects for one display name are two attempts at the same context: the +// newest settled conclusion is the reading (#1273). When the two cannot be +// ordered, the worse result stands — an unreadable pair is never resolved to +// the greener one. +function newest(first, second) { + const left = Date.parse(first.completedAt) + const right = Date.parse(second.completedAt) + if (Number.isFinite(left) && Number.isFinite(right) && left !== right) return left > right ? first : second + return { ...first, result: worse(first.result, second.result) } +} + /** * Build the `needs` shape `scripts/ci-ok.mjs` evaluates from a finished run's * job list. A required job absent from the list stays absent, which the * evaluator already reports as missing. */ export function needsFromJobs(jobs, required = REQUIRED_JOBS) { + const perKey = new Map() + for (const entry of conclusionsSeen(jobs, required)) { + let perName = perKey.get(entry.key) + if (perName === undefined) { + perName = new Map() + perKey.set(entry.key, perName) + } + const current = perName.get(entry.name) + if (current === undefined) { + perName.set(entry.name, entry) + continue + } + // A settled object cannot outvote an unsettled one for the same context: + // the run has not decided what that job did yet. + if (current.result === PENDING || entry.result === PENDING) { + perName.set(entry.name, { ...current, result: PENDING }) + continue + } + perName.set(entry.name, newest(current, entry)) + } const needs = {} - for (const job of Array.isArray(jobs) ? jobs : []) { - const key = jobKey(job?.name, required) - if (key === null) continue - const result = resultOf(job) - needs[key] = { result: needs[key] === undefined ? result : worse(needs[key].result, result) } + for (const [key, perName] of perKey) { + let result + for (const entry of perName.values()) { + if (result === undefined) result = entry.result + else result = result === PENDING || entry.result === PENDING ? PENDING : worse(result, entry.result) + } + needs[key] = { result } } return needs } +/** The required contexts whose evidence is unsettled. The publisher creates no + * check run while this is non-empty: an unsettled context is not a verdict + * (#1273, shape 1). */ +export function pendingRequired(needs, required = REQUIRED_JOBS) { + const object = needs !== null && typeof needs === 'object' ? needs : {} + return required.filter((name) => object[name]?.result === PENDING) +} + /** * The verdict itself: the base branch's required list over the finished run's * job results, with the base branch's classifier deciding whether a skipped @@ -117,7 +209,9 @@ export function needsFromJobs(jobs, required = REQUIRED_JOBS) { */ export function verdict(input) { const required = input.required ?? REQUIRED_JOBS - const needs = needsFromJobs(input.jobs, required) + const jobs = Array.isArray(input.jobs) ? input.jobs : [] + const seen = conclusionsSeen(jobs, required) + const needs = needsFromJobs(jobs, required) const { lines, problems } = evaluate(needs, { required, skippable: SKIPPABLE_ON, @@ -125,7 +219,7 @@ export function verdict(input) { eventName: typeof input.eventName === 'string' ? input.eventName : '', changes: input.changes ?? {}, }) - return { needs, lines, problems, ok: problems.length === 0 } + return { needs, lines, problems, ok: problems.length === 0, seen } } /** The base shas a `pull_request` run says it was measured against. A run that @@ -222,6 +316,21 @@ export function checkRunPayload({ headSha, result, runId, runUrl, required = REQ ? `every required job passed (${String(required.length)} required)` : `${String(result.problems.length)} required job(s) did not pass` const source = typeof runUrl === 'string' && RUN_URL.test(runUrl) ? runUrl : undefined + const seen = Array.isArray(result.seen) ? result.seen : [] + // #1273: a reader must be able to tell "two conclusions" from "no + // conclusions" by reading the check run, so every object seen for a required + // context is listed with the four fields the API answered. + const seenLines = required.map((name) => { + const entries = seen.filter((entry) => entry.key === name) + if (entries.length === 0) return `- ${name}: no job object seen (missing)` + return entries + .map((entry) => { + const id = entry.id === null ? 'unknown' : String(entry.id) + const at = entry.completedAt === '' ? '' : ` completed ${entry.completedAt}` + return `- ${name}: job ${id} ${entry.status}/${entry.conclusion}${at}` + }) + .join('\n') + }) const summary = [ `Verdict computed from the default branch's copy of the gate, not from the pull request's \`ci.yml\` (run #${String(runId)}${source === undefined ? '' : `, ${source}`}).`, '', @@ -232,6 +341,9 @@ export function checkRunPayload({ headSha, result, runId, runUrl, required = REQ ...result.lines, ...result.problems, '```', + '', + 'Conclusions seen for each required context (id, status, conclusion, completed_at); the newest settled one decides:', + ...seenLines, ].join('\n') return { name: REQUIRED_CHECK, diff --git a/scripts/lib/gate-compare.mjs b/scripts/lib/gate-compare.mjs index 43cf50f8..f7d797f9 100644 --- a/scripts/lib/gate-compare.mjs +++ b/scripts/lib/gate-compare.mjs @@ -27,7 +27,7 @@ // so widening that surface has to break `test/gateCompare.test.ts` rather than // silently widen the gate. // -// The `ci-ok` job's `needs:` may *grow* — a head that adds a job of its own and +// The aggregate job's `needs:` may *grow* — a head that adds a job of its own and // waits on it is not weakening the aggregate — but every base dependency and // every required job must still be in it, and the evaluator step must still be // exactly `node base/scripts/ci-ok.mjs` with the gate checked out under @@ -39,7 +39,7 @@ // reason, never a skipped comparison. // // #1282: the aggregate is found by an accepted id set, never by one literal. -// `#1273` renames `ci-ok` to `ci-ok-head`, so while branches still carry the old +// `#1273` renamed `ci-ok` to `ci-ok-head`, so while branches still carry the old // id the set is `['ci-ok-head', 'ci-ok']`. A head that declares none of them has // removed the job the three checks below read, and a head that declares two has // two candidates for one context: both are refusals naming what was looked for @@ -62,8 +62,10 @@ export const GATE_COMPARE_ALLOWED_KEYS = Object.freeze(['timeout-minutes']) /** The step the aggregate must run, as the base tree spells it. */ export const REQUIRED_EVALUATOR = 'node base/scripts/ci-ok.mjs' -/** The aggregate id the base tree declares today; `#1273` moves it to `ci-ok-head`. */ -export const AGGREGATE_JOB = 'ci-ok' +/** The aggregate id the base tree declares today. #1273 renamed it from + * `ci-ok`; the accepted set below keeps both while branches still carry the + * old id. */ +export const AGGREGATE_JOB = 'ci-ok-head' /** * Every aggregate id a head may declare while `#1273` moves the job from diff --git a/scripts/lib/main-health.mjs b/scripts/lib/main-health.mjs index 516a6c4e..bd3d1881 100644 --- a/scripts/lib/main-health.mjs +++ b/scripts/lib/main-health.mjs @@ -39,6 +39,9 @@ export const MAIN_EVENTS = ['push', 'schedule', 'workflow_dispatch'] export const RED_LABEL_COLOR = 'b60205' export const RED_LABEL_DESCRIPTION = 'a red default branch' +/** The `needs` key of the in-run aggregate (`ci.yml` job id, #1273). */ +export const AGGREGATE_JOB = 'ci-ok-head' + function text(value) { return String(value ?? '') } @@ -50,7 +53,7 @@ function text(value) { export function failingJobsFrom(needs) { const entries = needs !== null && typeof needs === 'object' && !Array.isArray(needs) ? Object.entries(needs) : [] return entries - .filter(([name, value]) => name !== 'ci-ok' && ['failure', 'cancelled'].includes(text(value?.result))) + .filter(([name, value]) => name !== AGGREGATE_JOB && ['failure', 'cancelled'].includes(text(value?.result))) .map(([name]) => name) } diff --git a/scripts/lib/reserved-contexts.mjs b/scripts/lib/reserved-contexts.mjs index 4ee90c66..4a038403 100644 --- a/scripts/lib/reserved-contexts.mjs +++ b/scripts/lib/reserved-contexts.mjs @@ -13,11 +13,14 @@ // and runs from the base tree, while the workflows are the diff under test and // come from the head, which is why the CLI takes a directory argument. // -// `ci-ok` has two canonical producers on purpose: `ci-ok-publish.yml` publishes -// the verdict from the default branch (#855) and the in-run aggregate inside -// `ci.yml` keeps publishing the same context until the documented follow-up -// renames it to `ci-ok-head`. A table that allowed only one of them would judge -// the honest tree red. +// `ci-ok` has one workflow-file producer: `ci-ok-publish.yml` publishes the +// verdict from the default branch (#855). #1273 renamed the in-run aggregate in +// `ci.yml` to `ci-ok-head`, so the old entry no longer has to allow two files — +// and the scanner cannot see the third producer at all: `ci-ok-refresh.yml` +// posts a red `ci-ok` through the API from `scripts/ci-ok-refresh.mjs`, and this +// scanner reads job ids and job-level `name:` values, not API posts. That blind +// spot is written down beside the rule in `docs/code-standards.md`; the red it +// posts still blocks a merge. // // Line-based parsing, like `scripts/lib/workflow-injection.mjs`: the repository // carries no YAML dependency. Two rules keep the line parser from skipping the @@ -40,7 +43,7 @@ import { readFileSync, readdirSync } from 'node:fs' import { basename, join } from 'node:path' export const RESERVED_CONTEXTS = { - 'ci-ok': ['ci.yml', 'ci-ok-publish.yml'], + 'ci-ok': ['ci-ok-publish.yml'], 'review-gate': ['review-gate.yml'], 'pr-lint': ['pr-lint.yml'], } diff --git a/scripts/main-health.mjs b/scripts/main-health.mjs index 22a434c2..e6ce954b 100644 --- a/scripts/main-health.mjs +++ b/scripts/main-health.mjs @@ -37,7 +37,8 @@ function runUrlOf(repository, serverUrl, runId) { async function main() { const repository = process.env.GITHUB_REPOSITORY ?? '' const needs = readNeeds() - const aggregate = needs['ci-ok'] + // #1273 renamed the in-run aggregate; the `needs` key moves with the job id. + const aggregate = needs['ci-ok-head'] const failingJobs = failingJobsFrom(needs) const listed = gh(issueListArgs())