diff --git a/README.md b/README.md index 2f36f60..5831e19 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Add the package at a tag and install its hooks when the repository installs: ```json { "scripts": { "prepare": "standard install" }, - "devDependencies": { "@mapringg/standard": "github:mapringg/standard#v0.5.0" } + "devDependencies": { "@mapringg/standard": "github:mapringg/standard#v0.5.3" } } ``` @@ -22,7 +22,7 @@ Add the package at a tag and install its hooks when the repository installs: | `standard hook commit-msg ` | Checks the commit message. | | `standard hook pre-commit` | Runs the `hooks.pre-commit` lines. | | `standard hook pre-push` | Refuses a merge commit that `origin/develop` lacks, then runs the `hooks.pre-push` lines. | -| `standard merge [--admin]` | Squash-merges a pull request into `develop` once its `Check` run is green. See [Merge](#merge). | +| `standard merge [--admin]` | Squash-merges a pull request into `develop` once its newest `Check` run is green. See [Merge](#merge). | | `standard score [...] [--remote] [--json]` | Reports how far each repository follows the standard. See [Score](#score). | ## Checks @@ -62,7 +62,7 @@ Add the package at a tag and install its hooks when the repository installs: | `size:XL` | 500 to 999 | | `size:XXL` | 1000 or more | -When `GH_TOKEN` and `GITHUB_REPOSITORY` are set, `pr-size` also creates the label if the repository lacks it, removes any other `size:` label and sets its own. The token needs `issues: write`. A label it cannot set is a warning. +When `GH_TOKEN` and `GITHUB_REPOSITORY` are set, `pr-size` also creates the label if the repository lacks it, removes any other `size:` label and sets its own. The token needs both `issues: write` and `pull-requests: write`: GitHub returns 403 when a token with only `issues: write` reads a pull request's labels. A label it cannot set is a warning. `baseline-growth` fails a pull request that adds a check to `pending`, or creates or grows a file under `.standard/baselines/`. The one exception is the pull request that removes that check from `pending`: it turns the check on and may start its baseline. It also fails when the head commit tracks a symlink under `.standard`, such as `.standard/config.json`. When the base commit has no `.standard/config.json`, it reads the base's `pending` from a root `standard.json`, so the pull request that moves the config adds nothing to `pending`. @@ -82,15 +82,28 @@ Each finding's fix names the change, such as `Delete scripts/merge-pr.mjs, which ## Merge -`standard merge ` is the one way to merge a pull request. It reads the pull request and its head commit's check runs live through `gh`, and refuses unless all of these hold: +`standard merge ` is the one way to merge a pull request. It reads the pull request, its `ready_for_review` events, the head commit's workflow runs, its check runs, and its workflow runs again, live through `gh`, and refuses unless all of these hold: - The pull request is open and not a draft. - Its base is `develop`. - Its title passes the `pr-title` rules with ` (#)` added. -- A check run named `Check` from GitHub Actions on the exact head commit has concluded `success`. A missing run, a run on an older commit, or a run in any other state refuses, and the message names the runs it found. +- The newest `Check` run on the exact head commit has concluded `success`. The gate counts only check runs named `Check` from GitHub Actions whose workflow run came from a `pull_request` event, so a `push` run on the same commit does not count. Among the `pull_request` runs of the workflow that holds `Check`, the newest is the one whose latest attempt started last (`run_started_at`, then the higher run id). A re-run moves that time forward, and a run that waits in a concurrency group has it before its `Check` run exists, so an older success cannot stand in for a newer run. If the newest run's id, attempt or status differs between the two workflow run reads, the gate refuses with `retry:`, because the check runs it read between them may belong to another attempt. When both reads show the same completed attempt, that attempt ended before the check runs were read, so its `Check` run is the one GitHub lists. A `Check` that did not conclude `success` refuses and names its conclusion. Older runs on the same commit, such as one that `cancel-in-progress` cancelled or one skipped on a `closed` event, do not block. A missing run or a run on an older commit refuses, and the message names the runs it found and the event of each. +- Every `pull_request` workflow run on the head commit has completed, in both workflow run reads. Until then the gate refuses with `wait:`. This covers a run of a workflow whose `Check` run does not exist yet and a re-run that carries a green `Check` from an earlier attempt. So a merge waits for every `pull_request` workflow on the head to finish, not only the one that holds `Check`. Runs from other events, such as `push`, do not hold it. +- That `Check` run started after the pull request last left draft, as its `ready_for_review` events show. The gate reads the start of the `Check` run itself, which a re-run of failed jobs copies from the earlier attempt, so a draft-time result cannot pass through a later attempt. A draft-time run refuses until `Check` runs again. Then it runs `gh pr merge --squash --match-head-commit --subject " (#<number>)" --body ""`, so a push after the check cannot be merged unseen. `--admin` passes GitHub's admin flag through for required reviews and still needs a green `Check`. Name the CI job `Check` so the gate can find it. +Because only the newest run decides, the CI workflow can cancel a run that a newer one replaces. Add `ready_for_review` so leaving draft runs `Check` again, and `edited` so a title or description fix runs it again: + +```yaml +on: + pull_request: + types: [opened, synchronize, reopened, edited, ready_for_review] +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true +``` + ## Score `standard score` reports how far a repository follows the standard. With no path it scores the repository it runs in. With several paths it prints one column per repository, named by its folder. It runs no check; it reads the files git tracks, `.standard/config.json` and the pin. diff --git a/package.json b/package.json index 078a58b..bd89dcd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@mapringg/standard", - "version": "0.5.2", + "version": "0.5.3", "description": "One repository standard for every project, run by one command.", "license": "MIT", "repository": "github:mapringg/standard", diff --git a/src/merge.mjs b/src/merge.mjs index 64a0d78..207cbbe 100644 --- a/src/merge.mjs +++ b/src/merge.mjs @@ -5,7 +5,12 @@ import { subjectNotes } from "./checks/support/subject-rules.mjs"; const BASE = "develop"; const GATE = "Check"; const GATE_APP = "github-actions"; +const EVENT = "pull_request"; const PR_FIELDS = "number,title,state,isDraft,baseRefName,headRefOid"; +const CHECK_FIELDS = ".check_runs[] | {name, head_sha, status, conclusion, started_at, app: {slug: .app.slug}, check_suite: {id: .check_suite.id}}"; +const RUN_FIELDS = ".workflow_runs[] | {id, workflow_id, event, head_sha, check_suite_id, run_attempt, run_started_at, status, conclusion}"; +const READY_FIELDS = '.[] | select(.event == "ready_for_review") | {created_at}'; +const OUTPUT_LIMIT = 256 * 1024 * 1024; export const retired = ["scripts/merge-pr.mjs", "scripts/merge-pr.test.mjs"]; @@ -23,27 +28,108 @@ export const retired = ["scripts/merge-pr.mjs", "scripts/merge-pr.test.mjs"]; * @property {string} head_sha * @property {string} status * @property {string | null} conclusion + * @property {string | null} started_at * @property {{ slug: string } | null} app + * @property {{ id: number }} check_suite + * + * @typedef {object} WorkflowRun + * @property {number} id + * @property {number} workflow_id + * @property {string} event + * @property {string} head_sha + * @property {number} check_suite_id + * @property {number} run_attempt + * @property {string} run_started_at + * @property {string} status + * @property {string | null} conclusion + * + * @typedef {object} HeadRuns + * @property {readonly CheckRun[]} checkRuns + * @property {readonly [readonly WorkflowRun[], readonly WorkflowRun[]]} workflowReads + * @property {string | null} readyAt * * @typedef {{ merge: true, args: string[] } | { merge: false, reasons: string[] }} Decision */ /** * @param {CheckRun} run + * @param {ReadonlyMap<number, WorkflowRun>} bySuite * @returns {string} */ -function describe(run) { +function describe(run, bySuite) { const state = run.status === "completed" ? `concluded ${run.conclusion}` : `is ${run.status}`; - return `${run.name} from ${run.app?.slug ?? "an unknown app"} on ${run.head_sha.slice(0, 7)} ${state}`; + const event = bySuite.get(run.check_suite.id)?.event; + const source = event ? `a ${event} run` : "no workflow run"; + return `${run.name} from ${run.app?.slug ?? "an unknown app"} on ${run.head_sha.slice(0, 7)} in ${source} ${state}`; +} + +/** + * @param {WorkflowRun} a + * @param {WorkflowRun} b + */ +function byStart(a, b) { + return Date.parse(a.run_started_at) - Date.parse(b.run_started_at) || a.id - b.id; +} + +/** + * @param {readonly WorkflowRun[]} workflowRuns + * @param {string} head + * @param {ReadonlySet<number | undefined>} workflows + */ +function newestRun(workflowRuns, head, workflows) { + return workflowRuns + .filter((run) => run.event === EVENT && run.head_sha === head && workflows.has(run.workflow_id)) + .toSorted(byStart) + .at(-1); +} + +/** + * @param {WorkflowRun | undefined} run + */ +function attempt(run) { + return run ? `run ${run.id} attempt ${run.run_attempt} ${run.status}` : "no run"; +} + +/** + * @param {string} head + * @param {HeadRuns} runs + * @returns {string | null} The reason to refuse. + */ +function gateRefusal(head, { checkRuns, workflowReads: [before, after], readyAt }) { + const unfinished = [...after, ...before].find((run) => run.event === EVENT && run.head_sha === head && run.status !== "completed"); + if (unfinished) { + return `wait: ${EVENT} run ${unfinished.id} attempt ${unfinished.run_attempt} of workflow ${unfinished.workflow_id} on ${head.slice(0, 7)} is ${unfinished.status}.`; + } + const bySuite = new Map(after.map((run) => [run.check_suite_id, run])); + const gates = checkRuns.filter((run) => run.name === GATE && run.app?.slug === GATE_APP && run.head_sha === head); + const workflows = new Set(gates.map((run) => bySuite.get(run.check_suite.id)?.workflow_id)); + const newest = newestRun(after, head, workflows); + if (!newest) { + const found = checkRuns.length === 0 ? "no check runs" : checkRuns.map((run) => describe(run, bySuite)).join("; "); + return `no ${GATE} run from ${GATE_APP} in a ${EVENT} run on head ${head}. Found ${found}.`; + } + const earlier = newestRun(before, head, workflows); + if (attempt(earlier) !== attempt(newest)) { + return `retry: the newest ${EVENT} run on ${head.slice(0, 7)} changed from ${attempt(earlier)} to ${attempt(newest)} while standard merge read the runs. Run standard merge again.`; + } + const where = `${EVENT} run ${newest.id} attempt ${newest.run_attempt}, the newest on ${head.slice(0, 7)},`; + const gate = gates.find((run) => run.check_suite.id === newest.check_suite_id); + if (!gate) return `${where} concluded ${newest.conclusion} without a ${GATE} run.`; + if (gate.status !== "completed") return `${GATE} in ${where} is ${gate.status}.`; + if (gate.conclusion !== "success") return `${GATE} in ${where} concluded ${gate.conclusion}.`; + if (readyAt && !(Date.parse(gate.started_at ?? "") >= Date.parse(readyAt))) { + return `${GATE} in ${where} started at ${gate.started_at}, before the pull request left draft at ${readyAt}. Rerun ${GATE}, or add ready_for_review to on.pull_request.types.`; + } + return null; } /** * @param {MergeTarget} pr - * @param {readonly CheckRun[]} checkRuns + * @param {HeadRuns} runs * @param {boolean} admin * @returns {Decision} */ -export function mergeDecision(pr, checkRuns, admin) { +export function mergeDecision(pr, runs, admin) { const reasons = []; if (pr.state !== "OPEN") reasons.push(`it is ${pr.state.toLowerCase()}, not open.`); if (pr.isDraft) reasons.push("it is a draft."); @@ -53,16 +139,8 @@ export function mergeDecision(pr, checkRuns, admin) { const suffix = ` (#${pr.number})`; for (const note of subjectNotes(title, suffix)) reasons.push(`its title breaks a subject rule. ${note}`); - const gates = checkRuns.filter( - (run) => run.name === GATE && run.app?.slug === GATE_APP && run.head_sha === pr.headRefOid, - ); - if (gates.length === 0) { - const found = checkRuns.length === 0 ? "no check runs" : checkRuns.map(describe).join("; "); - reasons.push(`no ${GATE} run from ${GATE_APP} on head ${pr.headRefOid}. Found ${found}.`); - } - for (const run of gates) { - if (run.status !== "completed" || run.conclusion !== "success") reasons.push(`${describe(run)}.`); - } + const refusal = gateRefusal(pr.headRefOid, runs); + if (refusal) reasons.push(refusal); if (reasons.length > 0) return { merge: false, reasons }; return { @@ -86,17 +164,30 @@ export function mergeDecision(pr, checkRuns, admin) { /** * @param {string} cwd * @param {string[]} args - * @returns {any} + * @returns {string} */ -function ghJson(cwd, args) { +function gh(cwd, args) { try { - return JSON.parse(execFileSync("gh", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] })); + return execFileSync("gh", args, { cwd, encoding: "utf8", maxBuffer: OUTPUT_LIMIT, stdio: ["ignore", "pipe", "pipe"] }); } catch (error) { const { stderr = "", message } = /** @type {Error & { stderr?: string }} */ (error); throw new Error(`gh ${args.join(" ")} failed. ${stderr.trim() || message}`); } } +/** + * @param {string} cwd + * @param {string} path + * @param {string} fields + * @returns {any[]} + */ +function ghItems(cwd, path, fields) { + return gh(cwd, ["api", "--paginate", "--jq", fields, `repos/{owner}/{repo}/${path}`]) + .split("\n") + .filter((line) => line !== "") + .map((line) => JSON.parse(line)); +} + /** * @param {string} arg * @returns {string} @@ -106,7 +197,7 @@ function quote(arg) { } /** - * Reads the pull request and its head's check runs live, so a push after review cannot slip in. + * Reads the pull request, its head's runs and its events live, so a push after review cannot slip in. * @param {string} cwd * @param {number} number * @param {boolean} admin @@ -114,15 +205,17 @@ function quote(arg) { */ export function merge(cwd, number, admin) { /** @type {MergeTarget} */ - const pr = ghJson(cwd, ["pr", "view", String(number), "--json", PR_FIELDS]); - /** @type {{ check_runs: CheckRun[] }[]} */ - const pages = ghJson(cwd, [ - "api", - "--paginate", - "--slurp", - `repos/{owner}/{repo}/commits/${pr.headRefOid}/check-runs?per_page=100`, - ]); - const decision = mergeDecision(pr, pages.flatMap((page) => page.check_runs), admin); + const pr = JSON.parse(gh(cwd, ["pr", "view", String(number), "--json", PR_FIELDS])); + /** @type {{ created_at: string }[]} */ + const readyEvents = ghItems(cwd, `issues/${number}/events?per_page=100`, READY_FIELDS); + /** @type {() => WorkflowRun[]} */ + const readWorkflowRuns = () => ghItems(cwd, `actions/runs?head_sha=${pr.headRefOid}&per_page=100`, RUN_FIELDS); + const before = readWorkflowRuns(); + /** @type {CheckRun[]} */ + const checkRuns = ghItems(cwd, `commits/${pr.headRefOid}/check-runs?filter=latest&per_page=100`, CHECK_FIELDS); + const after = readWorkflowRuns(); + const readyAt = readyEvents.map((event) => event.created_at).sort().at(-1) ?? null; + const decision = mergeDecision(pr, { checkRuns, workflowReads: [before, after], readyAt }, admin); if (!decision.merge) { console.error(`standard merge: refusing #${number}, because`); for (const reason of decision.reasons) console.error(` ${reason}`); diff --git a/test/helpers.mjs b/test/helpers.mjs index 5751cfb..c9866ae 100644 --- a/test/helpers.mjs +++ b/test/helpers.mjs @@ -114,7 +114,7 @@ export const WIRED = { ".standard/config.json": {}, "package.json": { scripts: { prepare: "standard install" }, - devDependencies: { "@mapringg/standard": "github:mapringg/standard#v0.5.2" }, + devDependencies: { "@mapringg/standard": "github:mapringg/standard#v0.5.3" }, }, ".github/workflows/ci.yml": [ "on:", diff --git a/test/merge.test.mjs b/test/merge.test.mjs index 0a841f3..dce8ef1 100644 --- a/test/merge.test.mjs +++ b/test/merge.test.mjs @@ -10,17 +10,53 @@ const OLDER = "b".repeat(40); const TITLE = "Keep environment examples complete across every app"; const pr = { number: 194, title: TITLE, state: "OPEN", isDraft: false, baseRefName: "develop", headRefOid: HEAD }; -const green = { name: "Check", head_sha: HEAD, status: "completed", conclusion: "success", app: { slug: "github-actions" } }; +const CI = 7; -function fakeGh(t, view, runs) { +function run(id, { event = "pull_request", started = "2026-11-10T10:00:00Z", attempt = 1, status = "completed", conclusion = "success", check = {}, sha = HEAD, workflow = CI } = {}) { + const workflowRun = { id, workflow_id: workflow, event, head_sha: sha, check_suite_id: id * 10, run_attempt: attempt, run_started_at: started, status, conclusion }; + const checkRun = check && { + name: "Check", + head_sha: sha, + status, + conclusion, + started_at: started, + app: { slug: "github-actions" }, + check_suite: { id: id * 10 }, + ...check, + }; + return { workflowRun, checkRun }; +} + +const green = run(1); + +function lines(items) { + return items.map((item) => JSON.stringify(item)).join("\n"); +} + +function fakeGh(t, view, { runs, before = runs, events, mergeFails = false }) { const bin = tempDir(t, "bin"); const calls = join(bin, "calls"); + const answers = { + "check-runs": lines(runs.flatMap((r) => (r.checkRun ? [r.checkRun] : []))), + "actions/runs": [lines(before.flatMap((r) => (r.workflowRun ? [r.workflowRun] : []))), lines(runs.flatMap((r) => (r.workflowRun ? [r.workflowRun] : [])))], + "/events": lines(events.filter((e) => e.event === "ready_for_review").map(({ created_at }) => ({ created_at }))), + }; const script = `#!/usr/bin/env node -const { appendFileSync } = process.getBuiltinModule("node:fs"); +const { appendFileSync, readFileSync } = process.getBuiltinModule("node:fs"); const args = process.argv.slice(2); appendFileSync(${JSON.stringify(calls)}, JSON.stringify(args) + "\\n"); +const answers = ${JSON.stringify(answers)}; if (args[0] === "pr" && args[1] === "view") console.log(${JSON.stringify(JSON.stringify(view))}); -if (args[0] === "api") console.log(${JSON.stringify(JSON.stringify([{ total_count: runs.length, check_runs: runs }]))}); +if (args[0] === "pr" && args[1] === "merge" && ${mergeFails}) { + console.error("Head branch was modified. Review and try the merge again."); + process.exit(1); +} +if (args[0] === "api") { + const path = args.at(-1); + const answer = Object.entries(answers).find(([key]) => path.includes(key))[1]; + const reads = readFileSync(${JSON.stringify(calls)}, "utf8").split("\\n").filter((line) => line.includes(path)).length; + console.log(Array.isArray(answer) ? answer[Math.min(reads, answer.length) - 1] : answer); +} `; writeFileSync(join(bin, "gh"), script); chmodSync(join(bin, "gh"), 0o755); @@ -30,8 +66,8 @@ if (args[0] === "api") console.log(${JSON.stringify(JSON.stringify([{ total_coun }; } -function mergeWith(t, { view = {}, runs = [green], args = [] } = {}) { - const gh = fakeGh(t, { ...pr, ...view }, runs); +function mergeWith(t, { view = {}, runs = [green], before, events = [], mergeFails, args = [] } = {}) { + const gh = fakeGh(t, { ...pr, ...view }, { runs, before, events, mergeFails }); const result = standard(tempRepo(t), ["merge", "194", ...args], { env: gh.env }); return { ...result, merged: gh.calls().filter(([command, sub]) => command === "pr" && sub === "merge") }; } @@ -55,18 +91,25 @@ test("merge squashes a green pull request with the reviewed head, the numbered t assert.equal(status, 0); }); -test("merge reads the pull request and its head's check runs live through gh", (t) => { - const gh = fakeGh(t, pr, [green]); +test("merge reads the pull request, its events, then the workflow runs on both sides of the check runs, live through gh", (t) => { + const gh = fakeGh(t, pr, { runs: [green], events: [] }); standard(tempRepo(t), ["merge", "194"], { env: gh.env }); - assert.deepEqual(gh.calls().slice(0, 2), [ - ["pr", "view", "194", "--json", "number,title,state,isDraft,baseRefName,headRefOid"], - ["api", "--paginate", "--slurp", `repos/{owner}/{repo}/commits/${HEAD}/check-runs?per_page=100`], - ]); + const [view, ...reads] = gh.calls().slice(0, 5); + assert.deepEqual(view, ["pr", "view", "194", "--json", "number,title,state,isDraft,baseRefName,headRefOid"]); + assert.deepEqual( + reads.map(([api, paginate, jq, filter, path]) => [api, paginate, jq, typeof filter, path]), + [ + "repos/{owner}/{repo}/issues/194/events?per_page=100", + `repos/{owner}/{repo}/actions/runs?head_sha=${HEAD}&per_page=100`, + `repos/{owner}/{repo}/commits/${HEAD}/check-runs?filter=latest&per_page=100`, + `repos/{owner}/{repo}/actions/runs?head_sha=${HEAD}&per_page=100`, + ].map((path) => ["api", "--paginate", "--jq", "string", path]), + ); }); test("merge passes --admin through and still needs a green Check", (t) => { assert.equal(mergeWith(t, { args: ["--admin"] }).merged[0].at(-1), "--admin"); - assertRefused(mergeWith(t, { args: ["--admin"], runs: [] }), /no Check run from github-actions/); + assertRefused(mergeWith(t, { args: ["--admin"], runs: [] }), /no Check run from github-actions in a pull_request run/); }); test("merge replaces a stale number at the end of the title", (t) => { @@ -86,29 +129,139 @@ test("merge refuses a base of main", (t) => { assertRefused(mergeWith(t, { view: { baseRefName: "main" } }), /^ {2}its base is main, not develop\.$/m); }); -test("merge refuses a red Check, naming its conclusion", (t) => { - const runs = [{ ...green, conclusion: "failure" }]; - assertRefused(mergeWith(t, { runs }), /^ {2}Check from github-actions on aaaaaaa concluded failure\.$/m); +test("merge refuses when the newest Check concluded anything but success, naming the conclusion", (t) => { + for (const conclusion of ["failure", "cancelled", "skipped", "timed_out"]) { + const runs = [green, run(2, { started: "2026-11-10T11:00:00Z", conclusion })]; + assertRefused( + mergeWith(t, { runs }), + new RegExp(`^ {2}Check in pull_request run 2 attempt 1, the newest on aaaaaaa, concluded ${conclusion}\\.$`, "m"), + ); + } +}); + +test("merge waits for a newer Check that has not finished, even after an older success", (t) => { + for (const status of ["queued", "in_progress"]) { + const runs = [green, run(2, { started: "2026-11-10T11:00:00Z", status, conclusion: null })]; + assertRefused( + mergeWith(t, { runs }), + new RegExp(`^ {2}wait: pull_request run 2 attempt 1 of workflow 7 on aaaaaaa is ${status}\\.$`, "m"), + ); + } +}); + +test("merge waits for a newer workflow run that has no Check run yet", (t) => { + const runs = [green, run(2, { started: "2026-11-10T11:00:00Z", status: "pending", conclusion: null, check: null })]; + assertRefused( + mergeWith(t, { runs }), + /^ {2}wait: pull_request run 2 attempt 1 of workflow 7 on aaaaaaa is pending\.$/m, + ); +}); + +test("merge refuses when the newest workflow run ended without a Check run", (t) => { + const runs = [green, run(2, { started: "2026-11-10T11:00:00Z", conclusion: "startup_failure", check: null })]; + assertRefused( + mergeWith(t, { runs }), + /^ {2}pull_request run 2 attempt 1, the newest on aaaaaaa, concluded startup_failure without a Check run\.$/m, + ); +}); + +test("merge ignores older cancelled and skipped Check runs once the newest is green", (t) => { + const runs = [ + run(1, { started: "2026-11-10T09:00:00Z", conclusion: "skipped" }), + run(2, { started: "2026-11-10T10:00:00Z", conclusion: "cancelled" }), + run(3, { started: "2026-11-10T11:00:00Z" }), + ]; + assert.equal(mergeWith(t, { runs }).merged.length, 1); }); -test("merge refuses a Check that is still running", (t) => { - const runs = [{ ...green, status: "in_progress", conclusion: null }]; - assertRefused(mergeWith(t, { runs }), /^ {2}Check from github-actions on aaaaaaa is in_progress\.$/m); +test("merge orders runs by when their latest attempt started, so a rerun of an older run is the newest", (t) => { + const rerun = run(1, { attempt: 2, started: "2026-11-10T12:00:00Z", conclusion: "failure" }); + const runs = [rerun, run(2, { started: "2026-11-10T11:00:00Z" })]; + assertRefused(mergeWith(t, { runs }), /Check in pull_request run 1 attempt 2, the newest on aaaaaaa, concluded failure\./); + const failedOlder = [run(1, { attempt: 2, started: "2026-11-10T10:00:00Z", conclusion: "failure" }), run(2, { started: "2026-11-10T11:00:00Z" })]; + assert.equal(mergeWith(t, { runs: failedOlder }).merged.length, 1); +}); + +test("merge breaks a tie in start time by the later workflow run", (t) => { + const runs = [run(3, { conclusion: "cancelled" }), run(2)]; + assertRefused(mergeWith(t, { runs }), /Check in pull_request run 3 attempt 1, the newest on aaaaaaa, concluded cancelled\./); +}); + +test("merge ignores runs of workflows that hold no Check", (t) => { + const runs = [green, run(2, { started: "2026-11-10T11:00:00Z", workflow: 9, conclusion: "failure", check: { name: "lint" } })]; + assert.equal(mergeWith(t, { runs }).merged.length, 1); +}); + +test("merge counts only Check runs from pull_request workflow runs, naming the event of the rest", (t) => { + const runs = [run(1, { event: "push" }), run(2, { event: "pull_request_target", started: "2026-11-10T11:00:00Z" })]; + assertRefused( + mergeWith(t, { runs }), + /no Check run from github-actions in a pull_request run on head a{40}\. Found Check from github-actions on aaaaaaa in a push run concluded success; Check from github-actions on aaaaaaa in a pull_request_target run concluded success\./, + ); + const runsWithPush = [green, run(2, { event: "push", started: "2026-11-10T11:00:00Z", conclusion: "failure" })]; + assert.equal(mergeWith(t, { runs: runsWithPush }).merged.length, 1); +}); + +test("merge refuses a Check that started before the pull request last left draft", (t) => { + const events = [ + { event: "ready_for_review", created_at: "2026-11-10T09:00:00Z" }, + { event: "convert_to_draft", created_at: "2026-11-10T09:30:00Z" }, + { event: "ready_for_review", created_at: "2026-11-10T10:30:00Z" }, + ]; + assertRefused( + mergeWith(t, { events }), + /^ {2}Check in pull_request run 1 attempt 1, the newest on aaaaaaa, started at 2026-11-10T10:00:00Z, before the pull request left draft at 2026-11-10T10:30:00Z\. Rerun Check, or add ready_for_review to on.pull_request.types\.$/m, + ); + const after = [green, run(2, { started: "2026-11-10T10:31:00Z" })]; + assert.equal(mergeWith(t, { runs: after, events }).merged.length, 1); +}); + +test("merge keeps the start of a Check that a partial rerun copied from a draft-time attempt", (t) => { + const events = [{ event: "ready_for_review", created_at: "2026-11-10T10:30:00Z" }]; + const copied = run(1, { attempt: 2, started: "2026-11-10T11:00:00Z", check: { started_at: "2026-11-10T10:00:00Z" } }); + assertRefused(mergeWith(t, { runs: [copied], events }), /started at 2026-11-10T10:00:00Z, before the pull request left draft/); +}); + +test("merge waits for a re-run attempt that carries a green Check from the earlier attempt", (t) => { + for (const status of ["queued", "in_progress"]) { + const carried = run(1, { attempt: 2, started: "2026-11-10T11:00:00Z", status, conclusion: null, check: { status: "completed", conclusion: "success" } }); + assertRefused(mergeWith(t, { runs: [carried] }), new RegExp(`^ {2}wait: pull_request run 1 attempt 2 of workflow 7 on aaaaaaa is ${status}\\.$`, "m")); + } +}); + +test("merge refuses with retry when the newest run changes between the reads around the check runs", (t) => { + const rerun = run(1, { attempt: 2, started: "2026-11-10T11:00:00Z", conclusion: "failure" }); + assertRefused( + mergeWith(t, { before: [green], runs: [{ ...rerun, checkRun: green.checkRun }] }), + /^ {2}retry: the newest pull_request run on aaaaaaa changed from run 1 attempt 1 completed to run 1 attempt 2 completed while standard merge read the runs\. Run standard merge again\.$/m, + ); + const newer = run(2, { started: "2026-11-10T11:00:00Z" }); + assertRefused(mergeWith(t, { before: [green], runs: [green, newer] }), /retry: .* from run 1 attempt 1 completed to run 2 attempt 1 completed/); + assertRefused(mergeWith(t, { before: [], runs: [green] }), /retry: .* from no run to run 1 attempt 1 completed/); +}); + +test("merge reads workflow runs larger than the default output buffer", (t) => { + const padding = "x".repeat(12_000); + const runs = Array.from({ length: 106 }, (_, i) => { + const r = run(i + 1, { started: i === 105 ? "2026-11-10T12:00:00Z" : "2026-11-10T10:00:00Z", conclusion: i === 105 ? "success" : "cancelled" }); + return { ...r, workflowRun: { ...r.workflowRun, padding } }; + }); + assert.equal(mergeWith(t, { runs }).merged.length, 1); }); test("merge refuses a missing Check, naming the runs it found", (t) => { - assertRefused(mergeWith(t, { runs: [] }), new RegExp(`no Check run from github-actions on head ${HEAD}\\. Found no check runs\\.`)); - const others = [{ ...green, name: "lint" }, { ...green, app: { slug: "some-app" } }]; + assertRefused(mergeWith(t, { runs: [] }), new RegExp(`no Check run from github-actions in a pull_request run on head ${HEAD}\\. Found no check runs\\.`)); + const others = [run(1, { check: { name: "lint" } }), run(2, { check: { app: { slug: "some-app" } } })]; assertRefused( mergeWith(t, { runs: others }), - /Found lint from github-actions on aaaaaaa concluded success; Check from some-app on aaaaaaa concluded success\./, + /Found lint from github-actions on aaaaaaa in a pull_request run concluded success; Check from some-app on aaaaaaa in a pull_request run concluded success\./, ); }); test("merge refuses a green Check on an older commit", (t) => { assertRefused( - mergeWith(t, { runs: [{ ...green, head_sha: OLDER }] }), - /no Check run from github-actions on head a{40}\. Found Check from github-actions on bbbbbbb concluded success\./, + mergeWith(t, { runs: [run(1, { sha: OLDER })] }), + /no Check run from github-actions in a pull_request run on head a{40}\. Found Check from github-actions on bbbbbbb in a pull_request run concluded success\./, ); }); @@ -125,3 +278,75 @@ test("merge needs a pull request number and takes only --admin", (t) => { assert.equal(status, 1); } }); + +const OLD = "2026-11-16T10:00:00Z"; +const MID = "2026-11-16T11:00:00Z"; +const NEW = "2026-11-16T12:00:00Z"; +const ready = (time) => ({ event: "ready_for_review", created_at: time }); +const at = (id, options = {}) => run(id, { started: OLD, ...options }); +const carried = (status) => at(1, { started: NEW, attempt: 2, status, conclusion: null, check: { status: "completed", conclusion: "success", started_at: OLD } }); +const fork = at(1); +fork.workflowRun.head_repository = { fork: true }; +const manyCancelled = Array.from({ length: 105 }, (_, i) => at(i + 1, { conclusion: "cancelled" })); +const unrelated = Array.from({ length: 105 }, (_, i) => ({ workflowRun: null, checkRun: { ...at(1).checkRun, name: `job-${i}` } })); + +const verifierCases = [ + ["normal-green", true, [at(1)]], + ["never-drafted", true, [at(1)]], + ["cancelled-then-green", true, [at(1, { conclusion: "cancelled" }), at(2, { started: NEW })]], + ["skipped-then-green", true, [at(1, { conclusion: "skipped" }), at(2, { started: NEW })]], + ["newer-queued-no-check", false, [at(1), at(2, { started: NEW, status: "queued", conclusion: null, check: null })]], + ["newer-running-no-check", false, [at(1), at(2, { started: NEW, status: "in_progress", conclusion: null, check: null })]], + ["old-id-rerun-newest-failure", false, [at(2, { started: MID }), at(1, { started: NEW, attempt: 2, conclusion: "failure" })]], + ["old-id-rerun-newest-green", true, [at(2, { started: MID, conclusion: "failure" }), at(1, { started: NEW, attempt: 2 })]], + ["same-time-id-tie", false, [at(1), at(2, { conclusion: "failure" })]], + ["two-workflows-pr-green-push-failed", true, [at(1), at(2, { workflow: 8, event: "push", started: NEW, conclusion: "failure" })]], + ["two-workflows-pr-failed-push-green", false, [at(1, { conclusion: "failure" }), at(2, { workflow: 8, event: "push", started: NEW })]], + ["fork-pull-request", true, [fork]], + ["pull-request-target", false, [at(1, { event: "pull_request_target" })]], + ["non-actions-app", false, [at(1, { check: { app: { slug: "other-app" } } })]], + ["two-ready-events-stale", false, [at(1, { started: MID })], { events: [ready(OLD), { event: "convert_to_draft", created_at: MID }, ready(NEW)] }], + ["two-ready-events-fresh", true, [at(1, { started: NEW })], { events: [ready(OLD), { event: "convert_to_draft", created_at: MID }, ready(MID)] }], + ["partial-rerun-copies-draft-time", false, [at(1, { started: NEW, attempt: 2, check: { started_at: OLD } })], { events: [ready(MID)] }], + ["rerun-in-progress-copied-green-check", false, [carried("in_progress")]], + ["rerun-queued-copied-green-check", false, [carried("queued")]], + ["rerun-starts-between-check-and-workflow-reads", false, [{ ...at(1, { started: NEW, attempt: 2, status: "in_progress", conclusion: null }), checkRun: at(1).checkRun }]], + ["rerun-starts-between-the-workflow-reads", false, [{ ...at(1, { started: NEW, attempt: 2, status: "queued", conclusion: null }), checkRun: at(1).checkRun }], { before: [at(1)] }], + ["head-moved-after-reads", false, [at(1)], { mergeFails: true }], + ["over-100-checks-newest-green-on-page-2", true, [...manyCancelled, at(106, { started: NEW })]], + ["over-100-checks-newest-failure-on-page-2", false, [...manyCancelled, at(106, { started: NEW, conclusion: "failure" })]], + ["over-100-events-latest-ready-on-page-2", false, [at(1, { started: MID })], { events: [...Array.from({ length: 101 }, () => ({ event: "labeled", created_at: OLD })), ready(NEW)] }], + ["over-100-checks-one-workflow", true, [...unrelated, at(1)]], + ...["cancelled", "skipped", "neutral", "timed_out", "action_required", "failure", "stale"].map((conclusion) => [`latest-${conclusion}`, false, [at(1, { conclusion })]]), +]; + +test("merge waits for every pull_request workflow run on the head, even one whose Check run does not exist yet", (t) => { + const otherWorkflow = run(2, { workflow: 8, started: "2026-11-10T11:00:00Z", status: "queued", conclusion: null, check: null }); + assertRefused(mergeWith(t, { before: [green], runs: [green, otherWorkflow] }), /^ {2}wait: pull_request run 2 attempt 1 of workflow 8 on aaaaaaa is queued\.$/m); + assertRefused(mergeWith(t, { before: [green, otherWorkflow], runs: [green] }), /wait: pull_request run 2 attempt 1 of workflow 8 on aaaaaaa is queued\./); + const pushRun = run(3, { event: "push", started: "2026-11-10T11:00:00Z", status: "in_progress", conclusion: null, check: null }); + assert.equal(mergeWith(t, { runs: [green, pushRun] }).merged.length, 1); +}); + +const newer = (options = {}) => at(2, { started: NEW, ...options }); +const manyCancelledLater = Array.from({ length: 6000 }, (_, i) => at(i + 100, { started: "2026-11-16T09:00:00Z", conclusion: "cancelled", check: null })); +const freshCases = [ + ["new-id-completed-between-reads", false, [at(1), newer({ check: null })], { before: [at(1)] }], + ["new-id-queued-between-reads", false, [at(1), newer({ status: "queued", conclusion: null, check: null })], { before: [at(1)] }], + ["same-tuple-changed-start-time", true, [at(1, { started: NEW, check: { started_at: OLD } })], { before: [at(1)] }], + ["completed-newest-check-missing", false, [at(1), newer({ check: null })]], + ["only-completed-check-missing", false, [at(1, { check: null })]], + ["check-success-later-job-failure", true, [{ ...at(1), workflowRun: { ...at(1).workflowRun, conclusion: "failure" } }, { workflowRun: null, checkRun: { ...at(1).checkRun, name: "Deploy", conclusion: "failure" } }]], + ["jq-two-pages-multiple-documents", true, [{ workflowRun: null, checkRun: { ...at(1).checkRun, name: "Lint" } }, at(1)], { events: [{ event: "labeled", created_at: "2026-11-16T13:00:00Z" }, ready("2026-11-16T09:00:00Z"), ready("2026-11-16T09:30:00Z")] }], + ["projection-large-raw-responses", true, [{ ...at(1), workflowRun: { ...at(1).workflowRun, padding: "x".repeat(2 * 1024 * 1024) } }]], + ["projected-output-over-one-mib", true, [...manyCancelledLater, at(1)]], + ["brand-new-check-workflow-between-reads", false, [at(1), newer({ workflow: 8, status: "queued", conclusion: null, check: null })], { before: [at(1)] }], +]; + +test("merge decides every case of the independent verifier", (t) => { + const mismatches = [...verifierCases, ...freshCases].flatMap(([name, merges, runs, options = {}]) => { + const { status, merged } = mergeWith(t, { runs, ...options }); + return (merges ? status === 0 && merged.length === 1 : status !== 0) ? [] : [name]; + }); + assert.deepEqual(mismatches, []); +}); diff --git a/test/score.test.mjs b/test/score.test.mjs index 7d5c7c9..a66ff78 100644 --- a/test/score.test.mjs +++ b/test/score.test.mjs @@ -168,7 +168,7 @@ test("hooks fails until standard install writes the three shims and unsets core. test("installed fails when package.json pins a version other than the one that runs", (t) => { const pinned = { ...WIRED, "package.json": { scripts: { prepare: "standard install" }, devDependencies: { "@mapringg/standard": "9.9.9" } } }; const cwd = repoWith(t, pinned); - const fix = "Run pnpm install, so the installed 0.5.2 becomes the @mapringg/standard 9.9.9 that package.json pins."; + const fix = "Run pnpm install, so the installed 0.5.3 becomes the @mapringg/standard 9.9.9 that package.json pins."; assert.equal(standard(cwd, ["check", "wiring"]).stdout, `wiring: installed: ${fix}\n`); const { status, repos } = scoreJson(cwd, []); assert.deepEqual(repos[0].cells.find((cell) => cell.row === "installed").notes, [fix]); @@ -277,7 +277,7 @@ test("--remote fails current when a newer release tag than the pin exists", (t) row: "current", status: "fail", pass: false, - notes: ["Bump @mapringg/standard to v0.10.0, the latest release; the repo pins 0.5.2."], + notes: ["Bump @mapringg/standard to v0.10.0, the latest release; the repo pins 0.5.3."], }); assert.equal(status, 1); }); diff --git a/test/wiring.test.mjs b/test/wiring.test.mjs index d700f77..1d78781 100644 --- a/test/wiring.test.mjs +++ b/test/wiring.test.mjs @@ -190,20 +190,20 @@ test("pin passes an exact version or tag and fails anything else", (t) => { const manifest = (spec) => ({ "package.json": { scripts: { prepare: "standard install" }, devDependencies: { "@mapringg/standard": spec } }, }); - for (const spec of ["0.5.2", "github:mapringg/standard#v0.5.2", "git+https://github.com/mapringg/standard.git#v0.5.2"]) { + for (const spec of ["0.5.3", "github:mapringg/standard#v0.5.3", "git+https://github.com/mapringg/standard.git#v0.5.3"]) { assertPasses(wiredRepo(t, manifest(spec))); } assertFails( wiredRepo(t, manifest("^0.4.0")), - 'pin: Pin @mapringg/standard to an exact version or tag such as "github:mapringg/standard#v0.5.2" in place of "^0.4.0", so every clone runs the same checks.', + 'pin: Pin @mapringg/standard to an exact version or tag such as "github:mapringg/standard#v0.5.3" in place of "^0.4.0", so every clone runs the same checks.', ); assertFails( wiredRepo(t, manifest("github:mapringg/standard")), - 'pin: Pin @mapringg/standard to an exact version or tag such as "github:mapringg/standard#v0.5.2" in place of "github:mapringg/standard", so every clone runs the same checks.', + 'pin: Pin @mapringg/standard to an exact version or tag such as "github:mapringg/standard#v0.5.3" in place of "github:mapringg/standard", so every clone runs the same checks.', ); const { stdout, status } = wiring(wiredRepo(t, { "package.json": { scripts: { prepare: "standard install" } } })); - assert.equal(stdout.trim(), 'wiring: pin: Add @mapringg/standard to devDependencies in package.json at "github:mapringg/standard#v0.5.2".'); + assert.equal(stdout.trim(), 'wiring: pin: Add @mapringg/standard to devDependencies in package.json at "github:mapringg/standard#v0.5.3".'); assert.equal(status, 1); }); @@ -211,7 +211,7 @@ test("prepare passes when it starts with standard install and names what it runs const manifest = (prepare) => ({ "package.json": { ...(prepare ? { scripts: { prepare } } : {}), - devDependencies: { "@mapringg/standard": "0.5.2" }, + devDependencies: { "@mapringg/standard": "0.5.3" }, }, }); for (const prepare of ["standard install", "standard install && node scripts/link.mjs", "pnpm exec standard install"]) { @@ -247,7 +247,7 @@ test("installed fails when package.json pins another version than the one instal for (const spec of ["9.9.9", "github:mapringg/standard#v9.9.9"]) { assertFails( wiredRepo(t, manifest(spec)), - "installed: Run pnpm install, so the installed 0.5.2 becomes the @mapringg/standard 9.9.9 that package.json pins.", + "installed: Run pnpm install, so the installed 0.5.3 becomes the @mapringg/standard 9.9.9 that package.json pins.", ); } }); @@ -256,7 +256,7 @@ test("installed fails when node_modules does not hold the package, whatever vers const cwd = tempRepo(t); write(cwd, WIRED); git(cwd, "add", "-A"); - assertFails(cwd, "installed: Run pnpm install, so node_modules becomes the @mapringg/standard 0.5.2 that package.json pins."); + assertFails(cwd, "installed: Run pnpm install, so node_modules becomes the @mapringg/standard 0.5.3 that package.json pins."); }); test("a repo without package.json fails pin and prepare", (t) => { @@ -264,7 +264,7 @@ test("a repo without package.json fails pin and prepare", (t) => { assert.equal( stdout.trim(), [ - 'wiring: pin: Add a package.json whose devDependencies pin @mapringg/standard to "github:mapringg/standard#v0.5.2".', + 'wiring: pin: Add a package.json whose devDependencies pin @mapringg/standard to "github:mapringg/standard#v0.5.3".', 'wiring: prepare: Make package.json scripts.prepare start with "standard install", chaining anything else after it with &&, so every install writes the hooks.', ].join("\n"), );