From 06b0ed736060cafd86a2bf081fb7d5131cb43e6c Mon Sep 17 00:00:00 2001 From: Jon Gallant Date: Tue, 24 Nov 2026 09:02:46 -0800 Subject: [PATCH 1/7] feat(ci): add keyless pin automation Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/dependabot.yml | 12 + .github/scripts/pin-validation.mjs | 168 ++++ .github/scripts/pin-validation.test.mjs | 227 ++++++ .github/scripts/update-pins.mjs | 443 +++------- .github/scripts/update-pins.test.mjs | 760 +++++------------- .github/workflows/complete-pin-validation.yml | 26 + .github/workflows/skill-eval-comparison.yml | 6 +- .github/workflows/update-pins.yml | 148 +--- README.md | 6 +- docs/checks-and-evals.md | 125 +-- plugins/marketplace-maintainer/CHANGELOG.md | 2 +- .../references/remote-pins.md | 42 +- 12 files changed, 841 insertions(+), 1124 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/scripts/pin-validation.mjs create mode 100644 .github/scripts/pin-validation.test.mjs create mode 100644 .github/workflows/complete-pin-validation.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..bcf1657 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: daily + allow: + - dependency-name: github/evals-action + groups: + evals-action: + patterns: + - github/evals-action diff --git a/.github/scripts/pin-validation.mjs b/.github/scripts/pin-validation.mjs new file mode 100644 index 0000000..8c428e8 --- /dev/null +++ b/.github/scripts/pin-validation.mjs @@ -0,0 +1,168 @@ +import { spawnSync } from "node:child_process"; +import { realpathSync } from "node:fs"; +import { resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { githubApi } from "./check-remote-pins.mjs"; + +const canonical = "github/plugin-marketplace-starter"; +const pluginBranch = "automation/update-plugin-pin"; +const actionBranchPrefix = "dependabot/github_actions/github/evals-action-"; +const actionFiles = new Set([".github/workflows/evals.yml", ".github/workflows/skill-eval-comparison.yml"]); +const pin = /^([+-])([ \t]*- uses: github\/evals-action@)([0-9a-f]{40}) # (v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\s*$/; + +function parseStableVersion(version) { + const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(version); + if (!match) throw new Error("Pin tag must be a stable semantic version."); + return match.slice(1).map((part) => BigInt(part)); +} + +function compareVersions(left, right) { + const a = parseStableVersion(left), b = parseStableVersion(right); + for (let index = 0; index < a.length; index += 1) { + if (a[index] !== b[index]) return a[index] < b[index] ? -1 : 1; + } + return 0; +} + +function getJson(api, endpoint) { + const result = api(endpoint); + if (result.status !== 200) throw new Error(`${endpoint}: GitHub API returned HTTP ${result.status}.`); + return JSON.parse(result.body); +} + +function validPr(pr, repo, defaultBranch, author) { + return pr.state === "open" && !pr.draft && + pr.user?.login === author && pr.user?.type === "Bot" && + pr.head?.repo?.full_name === repo && + pr.base?.repo?.full_name === repo && pr.base?.ref === defaultBranch; +} + +function verifyActionPins(api, files, changedFiles) { + if (!Number.isInteger(changedFiles) || changedFiles < 1 || changedFiles > actionFiles.size) throw new Error("Unexpected changed-file count."); + if (!Array.isArray(files) || files.length !== changedFiles) throw new Error("Incomplete changed-file list."); + let candidate; + const oldPins = []; + for (const file of files) { + if (!actionFiles.has(file.filename) || file.status !== "modified" || typeof file.patch !== "string") throw new Error("Unexpected changed file or missing patch."); + const removed = [], added = []; + for (const line of file.patch.split("\n")) { + if (!line.startsWith("+") && !line.startsWith("-")) continue; + const match = pin.exec(line); + if (!match) throw new Error("PR changes more than evals-action pins."); + (match[1] === "-" ? removed : added).push(match); + } + if (!removed.length || removed.length !== added.length || file.additions !== added.length || file.deletions !== removed.length || removed.some((entry, index) => entry[2] !== added[index][2])) throw new Error("Incomplete or unpaired action pin changes."); + oldPins.push(...removed.map((entry) => ({ sha: entry[3], tag: entry[4] }))); + for (const entry of added) { + const next = `${entry[3]} ${entry[4]}`; + if (candidate && candidate !== next) throw new Error("Action pins do not agree."); + candidate = next; + } + } + const [sha, tag] = candidate.split(" "); + if (oldPins.some((old) => compareVersions(tag.slice(1), old.tag.slice(1)) <= 0)) throw new Error("Action tag must advance to a newer stable semantic version."); + if (getJson(api, `repos/github/evals-action/commits/${encodeURIComponent(tag)}`).sha !== sha) throw new Error("Action tag does not resolve to the proposed pin."); + for (const old of oldPins) { + if (getJson(api, `repos/github/evals-action/compare/${old.sha}...${sha}`).status !== "ahead") throw new Error("Action pin is not a forward update."); + } +} + +function verifyPluginPin(api, repo, pr, head, files) { + if (pr.changed_files !== 1 || files.length !== 1 || files[0].filename !== "marketplace.json" || files[0].status !== "modified") { + throw new Error("Plugin pin PR must change only marketplace.json."); + } + const baseEndpoint = `repos/${repo}/contents/marketplace.json?ref=${pr.base.sha}`; + const headEndpoint = `repos/${repo}/contents/marketplace.json?ref=${head}`; + const before = getJson(api, baseEndpoint); + const after = getJson(api, headEndpoint); + const findPin = (data) => { + const matches = data.plugins?.filter((plugin) => plugin.name === "eval" && plugin.source?.repo === "github/evals"); + if (matches?.length !== 1) throw new Error("marketplace.json must contain exactly one github/evals eval plugin."); + return matches[0]; + }; + const oldPin = findPin(before); + const newPin = findPin(after); + const parsePin = (entry) => { + const match = /^copilot-evals-v(\d+\.\d+\.\d+)$/.exec(entry.source?.ref ?? ""); + if (!match || entry.version !== match[1] || !/^[0-9a-f]{40}$/.test(entry.source?.sha ?? "")) throw new Error("Plugin pin must contain a matching release tag, version, and full SHA."); + return { tag: entry.source.ref, version: entry.version, sha: entry.source.sha }; + }; + const old = parsePin(oldPin), next = parsePin(newPin); + if (compareVersions(next.version, old.version) <= 0 || old.tag === next.tag || old.sha === next.sha) throw new Error("Plugin pin did not advance."); + const clone = (value) => JSON.parse(JSON.stringify(value)); + const expected = clone(before); + const expectedPin = findPin(expected); + expectedPin.source.ref = next.tag; + expectedPin.source.sha = next.sha; + expectedPin.version = next.version; + if (JSON.stringify(expected) !== JSON.stringify(after)) throw new Error("Plugin PR changes more than the github/evals release pin."); + if (getJson(api, `repos/github/evals/commits/${encodeURIComponent(next.tag)}`).sha !== next.sha) throw new Error("Plugin release tag does not resolve to the proposed pin."); + if (getJson(api, `repos/github/evals/compare/${old.sha}...${next.sha}`).status !== "ahead") throw new Error("Plugin pin is not a forward update."); +} + +function getPullRequest(api, repo, branch) { + const owner = repo.split("/")[0]; + const matches = getJson(api, `repos/${repo}/pulls?state=open&head=${owner}:${encodeURIComponent(branch)}`); + if (matches.length > 1) throw new Error("More than one open PR uses the automation branch."); + return matches[0]; +} + +export function completePinValidation({ api = githubApi, repo, runId, execute = run }) { + if (repo !== canonical || !/^\d+$/.test(String(runId ?? ""))) throw new Error("Invalid repository or workflow run ID."); + const workflow = getJson(api, `repos/${repo}/actions/workflows/validate.yml`); + if (workflow.path !== ".github/workflows/validate.yml") throw new Error("Unexpected Validate workflow path."); + const runData = getJson(api, `repos/${repo}/actions/runs/${runId}`); + if (runData.workflow_id !== workflow.id || runData.path !== workflow.path) throw new Error("Validate run did not come from the expected workflow."); + let author, kind; + if (runData.event === "workflow_dispatch" && runData.head_branch === pluginBranch) { + author = "github-actions[bot]"; + kind = "plugin"; + } else if (runData.event === "pull_request" && typeof runData.head_branch === "string" && runData.head_branch.startsWith(actionBranchPrefix)) { + author = "dependabot[bot]"; + kind = "action"; + } else { + return "Skipped a Validate run unrelated to pin automation."; + } + if (runData.repository?.full_name !== repo || runData.head_repository?.full_name !== repo || !/^[0-9a-f]{40}$/.test(runData.head_sha ?? "")) { + return "Skipped a Validate run that is not for a commit in the canonical repository."; + } + if (runData.status !== "completed" || runData.conclusion !== "success") return "Skipped an unsuccessful Validate run."; + const defaultBranch = getJson(api, `repos/${repo}`).default_branch; + const jobs = getJson(api, `repos/${repo}/actions/runs/${runId}/jobs?per_page=100&page=1`).jobs; + if (!Array.isArray(jobs) || !jobs.some((job) => job.name === "lint" && job.conclusion === "success") || jobs.some((job) => job.conclusion !== "success")) throw new Error("Validate did not finish with every job, including lint, successful."); + const pr = getPullRequest(api, repo, runData.head_branch); + if (!pr || !validPr(pr, repo, defaultBranch, author)) return "Skipped because no matching open automation PR exists."; + if (pr.head?.ref !== runData.head_branch || pr.head?.sha !== runData.head_sha) return "Skipped a stale Validate run for an older PR head."; + const commit = getJson(api, `repos/${repo}/commits/${runData.head_sha}`); + if (commit.author?.login !== author || commit.committer?.login !== author) throw new Error("PR head commit was not authored and committed by the expected automation bot."); + const number = pr.number; + const endpoint = `repos/${repo}/pulls/${number}`; + const files = getJson(api, `${endpoint}/files?per_page=100&page=1`); + if (kind === "plugin") verifyPluginPin(api, repo, pr, runData.head_sha, files); + else verifyActionPins(api, files, pr.changed_files); + const current = getJson(api, endpoint); + if (!validPr(current, repo, defaultBranch, author) || current.head?.sha !== runData.head_sha || current.head?.ref !== runData.head_branch) throw new Error("PR head changed during inspection."); + if (kind === "plugin") { + execute("gh", [ + "api", "--method", "POST", `repos/${repo}/statuses/${runData.head_sha}`, + "-f", "state=success", "-f", "context=lint", "-f", `target_url=${runData.html_url}`, + "-f", "description=Validate passed for the exact plugin pin PR head.", + ]); + } + execute("gh", ["pr", "merge", String(number), "-R", repo, "--auto", "--squash", "--match-head-commit", runData.head_sha]); + return `Enabled auto-merge for verified ${kind} pin PR #${number} at ${runData.head_sha}.`; +} + +function run(command, args) { + const result = spawnSync(command, args, { stdio: "inherit" }); + if (result.error || result.status !== 0) throw new Error(`${command} failed (exit ${result.status ?? result.error?.code}).`); +} + +if (process.argv[1] && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(resolve(process.argv[1]))) { + try { + console.log(completePinValidation({ repo: process.env.GITHUB_REPOSITORY, runId: process.env.WORKFLOW_RUN_ID })); + } catch (error) { + console.error(`::error::${error.message}`); + process.exitCode = 1; + } +} diff --git a/.github/scripts/pin-validation.test.mjs b/.github/scripts/pin-validation.test.mjs new file mode 100644 index 0000000..ceae86a --- /dev/null +++ b/.github/scripts/pin-validation.test.mjs @@ -0,0 +1,227 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { parse } from "yaml"; +import { completePinValidation } from "./pin-validation.mjs"; + +const repo = "github/plugin-marketplace-starter"; +const baseSha = "a".repeat(40); +const headSha = "b".repeat(40); +const oldPinSha = "c".repeat(40); +const newPinSha = "d".repeat(40); +const branch = "dependabot/github_actions/github/evals-action-v0.2.1"; +const workflowPath = ".github/workflows/validate.yml"; +const actionFile = { + filename: ".github/workflows/skill-eval-comparison.yml", + status: "modified", + additions: 1, + deletions: 1, + patch: `@@ -1 +1 @@\n- - uses: github/evals-action@${oldPinSha} # v0.2.0\n+ - uses: github/evals-action@${newPinSha} # v0.2.1`, +}; +const beforeMarketplace = { + plugins: [{ + name: "eval", + source: { source: "github", repo: "github/evals", path: "packages/plugin", ref: "copilot-evals-v0.24.60", sha: oldPinSha }, + version: "0.24.60", + }], +}; +const afterMarketplace = structuredClone(beforeMarketplace); +afterMarketplace.plugins[0].source.ref = "copilot-evals-v0.24.68"; +afterMarketplace.plugins[0].source.sha = newPinSha; +afterMarketplace.plugins[0].version = "0.24.68"; + +function fixture({ kind = "action", change = {}, failStatus = false } = {}) { + const isPlugin = kind === "plugin"; + const prBranch = isPlugin ? "automation/update-plugin-pin" : branch; + const author = isPlugin ? "github-actions[bot]" : "dependabot[bot]"; + const pr = { + state: "open", + draft: false, + number: 42, + changed_files: isPlugin ? 1 : 1, + user: { login: author, type: "Bot" }, + head: { ref: prBranch, sha: headSha, repo: { full_name: repo } }, + base: { ref: "main", sha: baseSha, repo: { full_name: repo, default_branch: "main" } }, + }; + const activePr = change.pr ?? pr; + const workflowRun = { + workflow_id: 77, + path: workflowPath, + status: "completed", + conclusion: "success", + event: isPlugin ? "workflow_dispatch" : "pull_request", + repository: { full_name: repo }, + head_repository: { full_name: repo }, + head_branch: prBranch, + head_sha: headSha, + html_url: "https://github.com/github/plugin-marketplace-starter/actions/runs/99", + }; + const routes = { + [`repos/${repo}/actions/workflows/validate.yml`]: { id: 77, path: workflowPath }, + [`repos/${repo}/actions/runs/99`]: workflowRun, + [`repos/${repo}/actions/runs/99/jobs?per_page=100&page=1`]: { jobs: [{ name: "lint", conclusion: "success" }] }, + [`repos/${repo}`]: { default_branch: "main" }, + [`repos/${repo}/pulls?state=open&head=github:${encodeURIComponent(prBranch)}`]: change.noPr ? [] : change.multiplePrs ? [activePr, { ...activePr, number: 43 }] : [activePr], + [`repos/${repo}/pulls/42`]: activePr, + [`repos/${repo}/commits/${headSha}`]: { author: { login: author }, committer: { login: author } }, + [`repos/${repo}/pulls/42/files?per_page=100&page=1`]: isPlugin ? [{ filename: "marketplace.json", status: "modified" }] : [actionFile], + "repos/github/evals-action/commits/v0.2.1": { sha: newPinSha }, + [`repos/github/evals-action/compare/${oldPinSha}...${newPinSha}`]: { status: "ahead" }, + [`repos/github/evals/commits/copilot-evals-v0.24.68`]: { sha: newPinSha }, + [`repos/github/evals/compare/${oldPinSha}...${newPinSha}`]: { status: "ahead" }, + [`repos/${repo}/contents/marketplace.json?ref=${baseSha}`]: beforeMarketplace, + [`repos/${repo}/contents/marketplace.json?ref=${headSha}`]: afterMarketplace, + }; + const calls = []; + const api = (path) => { + let data = routes[path]; + if (path === `repos/${repo}/pulls/42` && change.staleHead) { + data = { ...pr, head: { ...pr.head, sha: oldPinSha } }; + } + if (path === `repos/${repo}/actions/runs/99` && change.run) data = { ...workflowRun, ...change.run }; + if (path === `repos/${repo}/actions/runs/99/jobs?per_page=100&page=1` && change.jobs) data = change.jobs; + if (path === `repos/${repo}/commits/${headSha}` && change.commit) data = change.commit; + if (path === `repos/${repo}/pulls/42/files?per_page=100&page=1` && change.files) data = change.files; + if (path === "repos/github/evals-action/compare/" + oldPinSha + "..." + newPinSha && change.comparison) data = change.comparison; + if (path === "repos/github/evals-action/commits/v0.2.1" && change.resolved) data = { sha: change.resolved }; + if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplace) data = change.marketplace; + if (data === undefined) return { status: 404, body: "{}" }; + return { status: 200, body: JSON.stringify(data) }; + }; + const execute = (command, args) => { + calls.push([command, ...args]); + if (failStatus && args[0] === "api" && args[1] === "--method") throw new Error("status write denied"); + return ""; + }; + return { api, calls, execute }; +} + +test("enables Dependabot auto-merge only after successful Validate and forward action pins", () => { + const f = fixture(); + completePinValidation({ repo, runId: 99, ...f }); + assert.deepEqual(f.calls, [["gh", "pr", "merge", "42", "-R", repo, "--auto", "--squash", "--match-head-commit", headSha]]); +}); + +test("publishes GitHub Actions lint status for plugin dispatch before enabling exact-head auto-merge", () => { + const f = fixture({ kind: "plugin" }); + completePinValidation({ repo, runId: 99, ...f }); + const runUrl = JSON.parse(f.api(`repos/${repo}/actions/runs/99`).body).html_url; + assert.deepEqual(f.calls, [ + ["gh", "api", "--method", "POST", `repos/${repo}/statuses/${headSha}`, "-f", "state=success", "-f", "context=lint", "-f", `target_url=${runUrl}`, "-f", "description=Validate passed for the exact plugin pin PR head."], + ["gh", "pr", "merge", "42", "-R", repo, "--auto", "--squash", "--match-head-commit", headSha], + ]); +}); + +test("requires exact workflow provenance, successful jobs, the automation author, and current PR head", () => { + const invalidCases = [ + { repo: "other/repository" }, + { run: { workflow_id: 78 } }, + { run: { path: "untrusted.yml" } }, + { commit: { author: { login: "human" }, committer: { login: "human" } } }, + { jobs: { jobs: [{ name: "lint", conclusion: "failure" }] } }, + { staleHead: true }, + ]; + for (const change of invalidCases) { + const f = fixture({ change }); + assert.throws(() => completePinValidation({ repo: change.repo ?? repo, runId: 99, ...f })); + assert.deepEqual(f.calls, []); + } + assert.throws(() => completePinValidation({ repo, runId: "not-a-number", ...fixture() }), /workflow run ID/); + const invalidPath = fixture(); + assert.throws(() => completePinValidation({ repo, runId: 99, ...invalidPath, api: (path) => + path === `repos/${repo}/actions/workflows/validate.yml` + ? { status: 200, body: JSON.stringify({ id: 77, path: "untrusted.yml" }) } + : invalidPath.api(path) }), /Unexpected Validate workflow path/); +}); + +test("ignores unrelated, stale, and absent PR runs without mutation", () => { + const samplePr = JSON.parse(fixture().api(`repos/${repo}/pulls/42`).body); + const cases = [ + { run: { event: "push" } }, + { run: { status: "in_progress" } }, + { run: { conclusion: "failure" } }, + { run: { head_repository: { full_name: "attacker/fork" } } }, + { run: { head_sha: "malformed" } }, + { noPr: true }, + { pr: { ...samplePr, user: { login: "someone", type: "User" } } }, + { pr: { ...samplePr, head: { ref: branch, sha: oldPinSha, repo: { full_name: repo } } } }, + ]; + for (const change of cases) { + const f = fixture({ change }); + const result = completePinValidation({ repo, runId: 99, ...f }); + assert.match(result, /Skipped/); + assert.deepEqual(f.calls, []); + } + const multiple = fixture({ change: { multiplePrs: true } }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...multiple }), /More than one open PR/); + assert.deepEqual(multiple.calls, []); +}); + +test("rejects untrusted action PRs, malformed edits, invalid tags, and non-forward pins", () => { + const secondFile = { + ...actionFile, + filename: ".github/workflows/evals.yml", + patch: actionFile.patch.replace(".github/workflows/skill-eval-comparison.yml", ".github/workflows/evals.yml"), + }; + const invalid = [ + { files: [{ ...actionFile, filename: "marketplace.json" }] }, + { files: [{ ...actionFile, patch: `${actionFile.patch}\n+ - run: malicious` }] }, + { files: [{ ...actionFile, patch: undefined }] }, + { files: [{ ...actionFile, additions: 2 }] }, + { files: [{ ...actionFile, patch: actionFile.patch.replace("v0.2.1", "v0.1.9") }] }, + { files: [{ ...actionFile, patch: actionFile.patch.replace("v0.2.1", "v0.2.0") }] }, + { files: [{ ...actionFile, patch: actionFile.patch.replace("v0.2.1", "v0.2.1-rc.1") }] }, + { resolved: oldPinSha }, + { comparison: { status: "behind" } }, + { files: [actionFile, { ...secondFile, patch: secondFile.patch.replace(newPinSha, "e".repeat(40)) }], pr: { ...JSON.parse(fixture().api(`repos/${repo}/pulls/42`).body), changed_files: 2 } }, + ]; + for (const change of invalid) { + const f = fixture({ change }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f })); + assert.deepEqual(f.calls, []); + } + const grouped = fixture({ change: { files: [actionFile, secondFile], pr: { ...JSON.parse(fixture().api(`repos/${repo}/pulls/42`).body), changed_files: 2 } } }); + completePinValidation({ repo, runId: 99, ...grouped }); + assert.equal(grouped.calls.filter((call) => call[1] === "pr" && call[2] === "merge").length, 1); +}); + +test("rejects plugin PRs that alter anything beyond the verified forward pin", () => { + const badMarketplace = structuredClone(afterMarketplace); + badMarketplace.plugins[0].description = "unexpected"; + const badPin = structuredClone(afterMarketplace); + badPin.plugins[0].source.ref = "unknown"; + const lowerVersionPin = structuredClone(afterMarketplace); + lowerVersionPin.plugins[0].source.ref = "copilot-evals-v0.24.59"; + lowerVersionPin.plugins[0].version = "0.24.59"; + const sameCommit = structuredClone(afterMarketplace); + sameCommit.plugins[0].source.sha = oldPinSha; + for (const [marketplace, match] of [ + [badMarketplace, /more than the github\/evals release pin/], + [badPin, /matching release tag/], + [lowerVersionPin, /did not advance/], + [sameCommit, /did not advance/], + ]) { + const f = fixture({ kind: "plugin", change: { marketplace } }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f }), match); + assert.deepEqual(f.calls, []); + } +}); + +test("stops if status publication fails and does not enqueue a merge", () => { + const f = fixture({ kind: "plugin", failStatus: true }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f }), /status write denied/); + assert.equal(f.calls.some((call) => call[1] === "pr" && call[2] === "merge"), false); +}); + +test("workflow runs trusted default-branch code with scoped permissions", () => { + const workflow = parse(readFileSync(new URL("../workflows/complete-pin-validation.yml", import.meta.url), "utf8")); + assert.deepEqual(workflow.on.workflow_run, { workflows: ["Validate"], types: ["completed"] }); + assert.deepEqual(workflow.permissions, { actions: "read", contents: "write", "pull-requests": "write", statuses: "write" }); + assert.equal(workflow.on.pull_request_target, undefined); + assert.match(workflow.jobs.validate.if, /github\.repository == 'github\/plugin-marketplace-starter'/); + assert.match(workflow.jobs.validate.if, /vars\.PIN_AUTOMATION == 'true'/); + const checkout = workflow.jobs.validate.steps.find((step) => step.uses?.startsWith("actions/checkout@")); + assert.equal(checkout.with.ref, "${{ github.event.repository.default_branch }}"); + assert.equal(checkout.with["persist-credentials"], false); + assert.equal(workflow.jobs.validate.steps.at(-1).run, "node .github/scripts/pin-validation.mjs"); +}); diff --git a/.github/scripts/update-pins.mjs b/.github/scripts/update-pins.mjs index 035ba4b..3a48cb5 100644 --- a/.github/scripts/update-pins.mjs +++ b/.github/scripts/update-pins.mjs @@ -1,24 +1,17 @@ import { spawnSync } from "node:child_process"; -import { appendFileSync, existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; +import { appendFileSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { githubApi } from "./check-remote-pins.mjs"; -// Moves remote marketplace pins and github/evals-action pins to their newest -// releases, and decides whether the resulting bot PR may merge. Run by -// .github/workflows/update-pins.yml; see docs/checks-and-evals.md#automatic-pin-updates. -export const BRANCH = "automation/update-pins"; -export const ACTION_REPO = "github/evals-action"; -export const ACTION_FILES = [".github/workflows/skill-eval-comparison.yml", "docs/checks-and-evals.md"]; -export const ALLOWED_FILES = new Set(["marketplace.json", ...ACTION_FILES]); -const actionUses = /^(\s*(?:-\s+)?uses:\s*github\/evals-action@)([0-9a-f]{40})(?:[ \t]+#[ \t]*([^\n]*))?$/gm; -const settled = new Set(["success", "neutral", "skipped"]); -const copilotReviewer = "copilot-pull-request-reviewer[bot]"; +export const BRANCH = "automation/update-plugin-pin"; +const bot = "github-actions[bot]"; const safeReleaseTag = (tag) => typeof tag === "string" && /^[A-Za-z0-9._-]+$/.test(tag); +class PinBlocked extends Error {} function getJson(api, endpoint) { const response = api(endpoint); - if (response.status !== 200) throw new Error(`${endpoint}: GitHub API returned HTTP ${response.status}.`); + if (response.status !== 200) throw new PinBlocked(`${endpoint}: GitHub API returned HTTP ${response.status}.`); return JSON.parse(response.body); } @@ -36,150 +29,57 @@ export function newestRelease(releases, prefix, allowPrerelease) { .sort((a, b) => compareSemver(semver(b.tag_name, prefix), semver(a.tag_name, prefix)))[0]; } -function listReleases(api, repo) { - const releases = []; - for (let page = 1; ; page += 1) { - const batch = getJson(api, `repos/${repo}/releases?per_page=100&page=${page}`); - releases.push(...batch); - if (batch.length < 100) return releases; - } -} - -// A pin stays on its channel: stable pins only move to stable releases. -function candidate(api, repo, currentTag, prefix, notes) { - const releases = listReleases(api, repo); - let allowPrerelease = true; - if (currentTag) { - let current = releases.find((release) => release.tag_name === currentTag); +export function planUpdate({ text, api = githubApi }) { + const data = JSON.parse(text); + if (`${JSON.stringify(data, null, 2)}\n` !== text) throw new Error("marketplace.json isn't in canonical 2-space JSON format."); + const entry = data.plugins?.find((plugin) => plugin.name === "eval" && plugin.source?.repo === "github/evals"); + if (!entry || !safeReleaseTag(entry.source.ref)) return { blocked: "The github/evals plugin release pin is missing or invalid." }; + const match = /^(.*?)(\d+\.\d+\.\d+)$/.exec(entry.source.ref); + if (!match || !/^[0-9a-f]{40}$/.test(entry.source.sha ?? "")) return { blocked: "The github/evals plugin pin must have a semver ref and full SHA." }; + const { ref, sha } = entry.source; + const read = (endpoint) => { + try { + return api(endpoint); + } catch (error) { + if (!(error instanceof Error)) throw error; + throw new PinBlocked(`${endpoint}: ${error.message}`); + } + }; + try { + const releases = []; + for (let page = 1; ; page++) { + const batch = getJson(read, `repos/github/evals/releases?per_page=100&page=${page}`); + if (!Array.isArray(batch)) throw new PinBlocked("github/evals: releases response is not an array."); + releases.push(...batch); + if (batch.length < 100) break; + } + let current = releases.find((release) => release.tag_name === ref); if (!current) { - const endpoint = `repos/${repo}/releases/tags/${encodeURIComponent(currentTag)}`; - const response = api(endpoint); - if (response.status === 404) { - notes.push(`${repo}: no release for ${currentTag}, so its channel is unknown; left unchanged.`); - return undefined; - } - if (response.status !== 200) throw new Error(`${endpoint}: GitHub API returned HTTP ${response.status}.`); + const endpoint = `repos/github/evals/releases/tags/${encodeURIComponent(ref)}`; + const response = read(endpoint); + if (response.status === 404) throw new PinBlocked(`github/evals: no release for ${ref}, so its channel is unknown.`); + if (response.status !== 200) throw new PinBlocked(`${endpoint}: GitHub API returned HTTP ${response.status}.`); current = JSON.parse(response.body); } - allowPrerelease = current.prerelease; - } - const release = newestRelease(releases, prefix, allowPrerelease); - if (!release) return undefined; - if (currentTag && compareSemver(semver(release.tag_name, prefix), semver(currentTag, prefix)) <= 0) return undefined; - return { tag: release.tag_name, sha: getJson(api, `repos/${repo}/commits/${encodeURIComponent(release.tag_name)}`).sha }; -} - -function updatePlugins(text, api, changes, notes) { - const data = JSON.parse(text); - if (`${JSON.stringify(data, null, 2)}\n` !== text) throw new Error("marketplace.json isn't in canonical 2-space JSON format."); - for (const entry of data.plugins ?? []) { - const source = entry.source; - const match = typeof source === "object" && safeReleaseTag(source.ref) - ? /^(.*?)(\d+\.\d+\.\d+)$/.exec(source.ref) - : null; - if (!match) continue; - const next = candidate(api, source.repo, source.ref, match[1], notes); - if (!next) continue; - changes.push({ name: entry.name, repo: source.repo, from: { tag: source.ref, sha: source.sha }, to: next }); - if (entry.version === match[2]) entry.version = next.tag.slice(match[1].length); - Object.assign(source, { ref: next.tag, sha: next.sha }); - } - return `${JSON.stringify(data, null, 2)}\n`; -} - -function updateAction(files, actionFiles, api, changes, notes) { - const pins = actionFiles.flatMap((file) => [...files[file].matchAll(actionUses)]); - if (!pins.length) return; - const shas = new Set(pins.map((pin) => pin[2])); - if (shas.size > 1) throw new Error(`Found more than one github/evals-action commit (${[...shas].join(", ")}); align them first.`); - const [currentSha] = shas; - const tags = new Set(pins.map((pin) => (/^v\d+\.\d+\.\d+$/.test(pin[3] ?? "") ? pin[3] : undefined))); - const currentTag = tags.size === 1 ? [...tags][0] : undefined; - const next = candidate(api, ACTION_REPO, currentTag, "v", notes); - if (!next || (next.sha === currentSha && pins.every((pin) => pin[3] === next.tag))) return; - const { status } = getJson(api, `repos/${ACTION_REPO}/compare/${currentSha}...${next.sha}`); - if (status !== "ahead" && status !== "identical") { - notes.push(`${ACTION_REPO}: ${next.tag} is ${status} the pinned ${currentSha}; left unchanged.`); - return; - } - changes.push({ name: ACTION_REPO, repo: ACTION_REPO, from: { tag: currentTag, sha: currentSha }, to: next }); - for (const file of actionFiles) { - files[file] = files[file].replace(actionUses, (_, prefix) => `${prefix}${next.sha} # ${next.tag}`); - } -} - -export function planUpdate({ files, actionFiles = ACTION_FILES, api = githubApi }) { - const next = { ...files }; - const changes = []; - const notes = []; - next["marketplace.json"] = updatePlugins(files["marketplace.json"], api, changes, notes); - updateAction(next, actionFiles.filter((file) => file in next), api, changes, notes); - const title = `chore(deps): update pins to ${changes.map((change) => `${change.name} ${change.to.tag}`).join(" and ")}`; - const body = [ - "Moves these pins to their newest published releases on the same channel:", - "", - ...changes.map(({ name, repo, from, to }) => - `- **${name}**: ${from.tag ?? from.sha.slice(0, 12)} → ${to.tag} ([changes](https://github.com/${repo}/compare/${from.sha}...${to.sha}))`), - ...notes.map((note) => `- ${note}`), - "", - "Opened by the [Update pins](../blob/main/.github/workflows/update-pins.yml) workflow. It enqueues this PR only after GitHub", - "records a required approval and Copilot submits a GitHub `APPROVED` review on the current head; a comment-only review", - "doesn't qualify. It", - "replaces the PR when a newer release appears. Set the `PIN_AUTOMATION` variable to anything but `true` to pause it.", - "", - ].join("\n"); - return { files: next, changes, notes, title, body }; -} - -// A check bound to a GitHub App counts only when that App reported it; commit statuses can't prove their App. -const passed = ({ context, app }, checkRuns, status) => - checkRuns.check_runs.some((run) => run.name === context && (!(app > 0) || run.app?.id === app) && run.status === "completed" && settled.has(run.conclusion)) || - (!(app > 0) && (status.statuses ?? []).some((entry) => entry.context === context && entry.state === "success")); - -export function evaluateMergeGate({ pr, commits, files, checkRuns, status, compare, required = [], stale = [], bot, expectHead, trustedLintPassed = false, reviewDecision, isInMergeQueue = false, automatedReviewApproved = false }) { - const result = (decision, reason) => ({ decision, reason, pr: pr?.number, prNodeId: pr?.node_id, head: pr?.head?.sha }); - if (!pr) return result("none", "No open pin update PR."); - const author = pr.user?.login; - if (pr.state !== "open" || pr.draft) return result("block", "PR is closed or a draft."); - if (pr.head?.ref !== BRANCH || pr.head?.repo?.full_name !== pr.base?.repo?.full_name) return result("block", "PR head isn't this repository's pin branch."); - if (pr.base?.ref !== pr.base?.repo?.default_branch) return result("block", "PR doesn't target the default branch."); - if (pr.user?.type !== "Bot" || (bot && author !== bot)) return result("block", `PR author ${author} isn't the pin app.`); - if (!commits.length || commits.length !== pr.commits || commits.some((commit) => commit.author?.login !== author || commit.committer?.login !== author)) return result("block", `Commits aren't all authored and committed by ${author}.`); - const unexpected = files.filter((file) => file.status !== "modified" || !ALLOWED_FILES.has(file.filename)); - if (!files.length || files.length !== pr.changed_files || unexpected.length) return result("block", `Unexpected file changes: ${unexpected.map((file) => file.filename).join(", ") || "none"}.`); - if (pr.mergeable === null || pr.mergeable_state === "unknown") return result("wait", "GitHub is still computing mergeability."); - if (pr.mergeable_state === "dirty") return result("block", "PR has merge conflicts."); - if (checkRuns.total_count !== checkRuns.check_runs.length) return result("block", "Too many check runs to verify in one page."); - const failed = checkRuns.check_runs.filter((run) => run.status === "completed" && !settled.has(run.conclusion)); - if (failed.length) return result("block", `Checks failed: ${failed.map((run) => run.name).join(", ")}.`); - if (status.total_count > 0 && ["failure", "error"].includes(status.state)) return result("block", "A commit status failed."); - if (expectHead && pr.head.sha !== expectHead) return result("wait", "PR head changed since the gate ran."); - if (isInMergeQueue) return result("wait", "PR is already in the merge queue."); - if (compare.behind_by !== 0) return result("wait", "PR is behind the default branch; the next update rebases it."); - if (!trustedLintPassed) return result("wait", "The Validate workflow's lint job hasn't passed on this head yet."); - if (reviewDecision === "CHANGES_REQUESTED") return result("block", "A reviewer requested changes."); - if (reviewDecision !== "APPROVED") return result("wait", "GitHub hasn't recorded a required approval on this head yet."); - if (!automatedReviewApproved) return result("wait", "Copilot hasn't submitted an APPROVED review on this head yet."); - // Git attribution can be set by anyone who can push, so the content itself must match a fresh update. - if (stale.length) return result("wait", `Doesn't match a fresh pin update: ${stale.join(", ")}; the next update replaces it.`); - if (checkRuns.check_runs.some((run) => run.status !== "completed")) return result("wait", "Checks are still running."); - const missing = [{ context: "lint" }, ...required].filter((check) => !passed(check, checkRuns, status)); - if (missing.length) return result("wait", `Required checks haven't passed on this head yet: ${[...new Set(missing.map((check) => check.context))].join(", ")}.`); - if (status.total_count > 0 && status.state !== "success") return result("wait", "Commit statuses are pending."); - return result("merge", "Every gate passed."); -} - -export function planPublish({ main, localTree, remote, bot }) { - if (!remote) return "push"; - const others = remote.authors.filter((login) => login !== bot); - if (others.length) throw new Error(`${BRANCH} has commits not authored by ${bot} (${others.join(", ")}); leaving it alone.`); - const current = remote.tree === localTree && remote.aheadBy === 1 && remote.behindBy === 0 && remote.parents.length === 1 && remote.parents[0] === main; - return current ? "skip" : "push"; -} - -export function assertBotPr(pr, bot) { - if (pr && (pr.user?.type !== "Bot" || pr.user?.login !== bot)) { - throw new Error(`Open PR #${pr.number} on ${BRANCH} isn't authored by ${bot}; leaving it alone.`); + if (typeof current.prerelease !== "boolean") throw new PinBlocked(`github/evals: release channel for ${ref} is unknown.`); + const next = newestRelease(releases, match[1], current.prerelease); + if (!next || compareSemver(semver(next.tag_name, match[1]), semver(ref, match[1])) <= 0) return { text, changes: [], title: "", body: "" }; + const nextSha = getJson(read, `repos/github/evals/commits/${encodeURIComponent(next.tag_name)}`).sha; + if (!/^[0-9a-f]{40}$/.test(nextSha ?? "")) throw new PinBlocked(`github/evals: ${next.tag_name} did not resolve to a full commit SHA.`); + const comparison = getJson(read, `repos/github/evals/compare/${sha}...${nextSha}`); + if (comparison.status !== "ahead") throw new PinBlocked(`github/evals: ${next.tag_name} is ${comparison.status} relative to the pinned commit.`); + entry.source.ref = next.tag_name; + entry.source.sha = nextSha; + if (entry.version === match[2]) entry.version = next.tag_name.slice(match[1].length); + return { + text: `${JSON.stringify(data, null, 2)}\n`, + changes: [{ from: { tag: ref, sha }, to: { tag: next.tag_name, sha: nextSha } }], + title: `chore(deps): update eval plugin to ${next.tag_name}`, + body: `Updates the eval plugin from ${ref} to ${next.tag_name} ([changes](https://github.com/github/evals/compare/${sha}...${nextSha})).\n\nA CodeOwner review and required checks are needed before auto-merge.\n`, + }; + } catch (error) { + if (!(error instanceof PinBlocked)) throw error; + return { blocked: error.message }; } } @@ -189,22 +89,21 @@ function run(command, args, options = {}) { return result.stdout.trim(); } -export function getMergeState(repo, number, execute = run) { - const [owner, name] = repo.split("/"); - const query = "query($owner:String!,$name:String!,$number:Int!){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewDecision isInMergeQueue}}}"; - return JSON.parse(execute("gh", [ - "api", "graphql", - "-f", `query=${query}`, - "-f", `owner=${owner}`, - "-f", `name=${name}`, - "-F", `number=${number}`, - "--jq", ".data.repository.pullRequest", - ])); +export function planPublish({ main, localTree, remote }) { + if (!remote) return "push"; + if (remote.authors.some((author) => author !== bot)) throw new Error(`${BRANCH} contains commits not authored and committed by ${bot}.`); + return remote.tree === localTree && remote.aheadBy === 1 && remote.behindBy === 0 && remote.parents.length === 1 && remote.parents[0] === main ? "skip" : "push"; } function openPr(api, repo) { const [owner] = repo.split("/"); - return getJson(api, `repos/${repo}/pulls?state=open&head=${owner}:${encodeURIComponent(BRANCH)}`)[0]; + const prs = getJson(api, `repos/${repo}/pulls?state=open&head=${owner}:${encodeURIComponent(BRANCH)}`); + if (prs.length > 1) throw new Error(`More than one open PR uses ${BRANCH}.`); + const pr = prs[0]; + if (pr && (pr.user?.login !== bot || pr.user?.type !== "Bot" || pr.head?.repo?.full_name !== repo || pr.base?.ref !== pr.base?.repo?.default_branch)) { + throw new Error(`Open PR #${pr.number} is not the expected ${bot} PR against the default branch.`); + } + return pr; } function remoteBranch(api, repo, main) { @@ -212,177 +111,41 @@ function remoteBranch(api, repo, main) { if (response.status === 404) return undefined; if (response.status !== 200) throw new Error(`${BRANCH}: GitHub API returned HTTP ${response.status}.`); const { commit } = JSON.parse(response.body); - const compare = getJson(api, `repos/${repo}/compare/${main}...${commit.sha}`); - if (compare.commits.length !== compare.ahead_by) throw new Error(`${BRANCH} has too many commits to verify their authors; leaving it alone.`); - return { - sha: commit.sha, - tree: commit.commit.tree.sha, - parents: commit.parents.map((parent) => parent.sha), - authors: compare.commits.flatMap((entry) => [entry.author?.login, entry.committer?.login]), - aheadBy: compare.ahead_by, - behindBy: compare.behind_by, - }; -} - -function output(values) { - const lines = Object.entries(values).map(([key, value]) => `${key}=${value ?? ""}`); - if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${lines.join("\n")}\n`); - console.log(lines.join("\n")); -} - -function summary(text) { - if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n`); + const comparison = getJson(api, `repos/${repo}/compare/${main}...${commit.sha}`); + if (comparison.commits.length !== comparison.ahead_by) throw new Error(`${BRANCH} has too many commits to verify.`); + return { sha: commit.sha, tree: commit.commit.tree.sha, parents: commit.parents.map((parent) => parent.sha), aheadBy: comparison.ahead_by, behindBy: comparison.behind_by, authors: comparison.commits.flatMap((entry) => [entry.author?.login, entry.committer?.login]) }; } -const readFiles = () => - Object.fromEntries(["marketplace.json", ...ACTION_FILES].filter((file) => existsSync(file)).map((file) => [file, readFileSync(file, "utf8")])); - -export function requiredChecks(api, repo, branch) { - const rules = []; - for (let page = 1; ; page++) { - const response = api(`repos/${repo}/rules/branches/${encodeURIComponent(branch)}?per_page=100&page=${page}`); - if (response.status === 403 && /Upgrade to GitHub Pro or make this repository public to enable this feature/i.test(response.body)) break; - if (response.status !== 200) throw new Error(`repos/${repo}/rules/branches/${encodeURIComponent(branch)}: GitHub API returned HTTP ${response.status}.`); - const batch = JSON.parse(response.body); - rules.push(...batch); - if (batch.length < 100) break; - } - const classic = getJson(api, `repos/${repo}/branches/${encodeURIComponent(branch)}`).protection?.required_status_checks; - return [ - ...rules - .filter((rule) => rule.type === "required_status_checks") - .flatMap((rule) => rule.parameters.required_status_checks.map((check) => ({ context: check.context, app: check.integration_id }))), - ...(classic?.checks ?? (classic?.contexts ?? []).map((context) => ({ context }))).map((check) => ({ context: check.context, app: check.app_id })), - ]; -} - -function paged(api, endpoint, key) { - const items = []; - const separator = endpoint.includes("?") ? "&" : "?"; - for (let page = 1; ; page++) { - const response = getJson(api, `${endpoint}${separator}per_page=100&page=${page}`); - const batch = key ? response[key] : response; - if (!Array.isArray(batch)) throw new Error(`${endpoint}: GitHub API response is missing ${key ?? "an array"}.`); - items.push(...batch); - if (batch.length < 100) return items; - } -} - -export function trustedValidateLint(api, repo, head) { - const runs = paged(api, `repos/${repo}/actions/runs?head_sha=${encodeURIComponent(head)}`, "workflow_runs") - .filter((run) => run.name === "Validate" && run.path === ".github/workflows/validate.yml" && run.event === "pull_request" && run.head_sha === head) - .sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at) || b.run_attempt - a.run_attempt); - const latest = runs[0]; - if (!latest || latest.status !== "completed" || latest.conclusion !== "success") return false; - const jobs = paged(api, `repos/${repo}/actions/runs/${latest.id}/jobs`, "jobs"); - return jobs.some((job) => job.name === "lint" && job.status === "completed" && job.conclusion === "success"); -} - -export function approvedCopilotReview(api, repo, number, head) { - const reviews = paged(api, `repos/${repo}/pulls/${number}/reviews`) - .filter((review) => review.user?.login === copilotReviewer && review.commit_id === head && Number.isFinite(Date.parse(review.submitted_at))) - .sort((a, b) => Date.parse(a.submitted_at) - Date.parse(b.submitted_at)); - return reviews.length > 0 && reviews[reviews.length - 1].state === "APPROVED"; -} - -export function requestCopilotReview(api, request, repo, bot) { +export function publish(api, repo, { title, bodyFile, execute = run }) { + if (!title || !bodyFile || !process.env.GH_TOKEN) throw new Error("Publication requires a title, body file, and GH_TOKEN."); const pr = openPr(api, repo); - if (!pr) return { state: "none" }; - assertBotPr(pr, bot); - const head = pr.head?.sha; - if (!head) throw new Error(`PR #${pr.number} doesn't have a head SHA.`); - const reviews = paged(api, `repos/${repo}/pulls/${pr.number}/reviews`); - if (reviews.some((review) => - review.user?.login === copilotReviewer && - review.commit_id === head && - Number.isFinite(Date.parse(review.submitted_at)))) { - return { state: "completed", pr: pr.number, head }; - } - - const endpoint = `repos/${repo}/pulls/${pr.number}/copilot-code-review`; - const response = request(endpoint); - if (response.status === 409) return { state: "pending", pr: pr.number, head }; - if (response.status !== 201) { - let reason; - try { - reason = JSON.parse(response.body).failure_reason; - } catch {} - throw new Error(`${endpoint}: GitHub API returned HTTP ${response.status}${reason ? ` (${reason})` : ""}.`); - } - let review; - try { - review = JSON.parse(response.body); - } catch { - throw new Error(`${endpoint}: GitHub API response isn't valid JSON.`); - } - if (review.state !== "PENDING") throw new Error(`${endpoint}: Copilot review request didn't enter the pending state.`); - return { state: "requested", pr: pr.number, head }; -} - -// Files on the PR head that differ from what `update` produces on this checkout of the default branch. -function staleFiles(api, repo, head) { - const expected = planUpdate({ files: readFiles(), actionFiles: ACTION_FILES, api }).files; - return [...ALLOWED_FILES].filter((file) => { - const response = api(`repos/${repo}/contents/${file.split("/").map(encodeURIComponent).join("/")}?ref=${head}`); - if (response.status !== 200 && response.status !== 404) throw new Error(`${file}@${head}: GitHub API returned HTTP ${response.status}.`); - return (response.status === 200 ? response.body : undefined) !== expected[file]; - }); -} - -function readGate(api, repo, { bot, expectHead }) { - const listed = openPr(api, repo); - if (!listed) return evaluateMergeGate({}); - const pr = getJson(api, `repos/${repo}/pulls/${listed.number}`); - const head = pr.head.sha; - const { reviewDecision, isInMergeQueue } = getMergeState(repo, pr.number); - return evaluateMergeGate({ - required: requiredChecks(api, repo, pr.base.ref), - trustedLintPassed: trustedValidateLint(api, repo, head), - reviewDecision, - isInMergeQueue, - automatedReviewApproved: approvedCopilotReview(api, repo, pr.number, head), - stale: staleFiles(api, repo, head), - pr, - commits: getJson(api, `repos/${repo}/pulls/${pr.number}/commits?per_page=100`), - files: getJson(api, `repos/${repo}/pulls/${pr.number}/files?per_page=100`), - checkRuns: getJson(api, `repos/${repo}/commits/${head}/check-runs?per_page=100`), - status: getJson(api, `repos/${repo}/commits/${head}/status?per_page=100`), - compare: getJson(api, `repos/${repo}/compare/${encodeURIComponent(pr.base.ref)}...${head}`), - bot, - expectHead, - }); -} - -export function publish(api, repo, { title, bodyFile, bot, requestReview, mergeState = getMergeState }) { - const pr = openPr(api, repo); - assertBotPr(pr, bot); - if (pr && mergeState(repo, pr.number).isInMergeQueue) return `#${pr.number} is already in the merge queue; leaving it unchanged`; - const main = run("git", ["rev-parse", "HEAD"]); + const base = pr?.base.ref ?? getJson(api, `repos/${repo}`).default_branch; + const main = execute("git", ["rev-parse", "HEAD"]); const remote = remoteBranch(api, repo, main); - const paths = [...ALLOWED_FILES].filter((file) => existsSync(file)); - if (!run("git", ["status", "--porcelain", "--", ...paths])) { - if (remote) planPublish({ main, localTree: "", remote, bot }); - if (pr) run("gh", ["pr", "close", String(pr.number), "-R", repo, "--delete-branch", "--comment", "The default branch already has these pins or newer ones."]); - return pr ? `closed #${pr.number}` : "nothing to publish"; - } - const id = getJson(api, `users/${encodeURIComponent(bot)}`).id; - run("git", ["add", "--", ...paths]); - run("git", ["-c", `user.name=${bot}`, "-c", `user.email=${id}+${bot}@users.noreply.github.com`, "commit", "--quiet", "-m", title]); - const decision = planPublish({ main, localTree: run("git", ["rev-parse", "HEAD^{tree}"]), remote, bot }); + if (!execute("git", ["status", "--porcelain", "--", "marketplace.json"])) throw new Error("No plugin pin change to publish."); + if (remote) planPublish({ main, localTree: "", remote }); + execute("git", ["add", "--", "marketplace.json"]); + execute("git", ["-c", `user.name=${bot}`, "-c", "user.email=41898282+github-actions[bot]@users.noreply.github.com", "commit", "--quiet", "--only", "-m", title, "--", "marketplace.json"]); + const decision = planPublish({ main, localTree: execute("git", ["rev-parse", "HEAD^{tree}"]), remote }); if (decision === "push") { const auth = Buffer.from(`x-access-token:${process.env.GH_TOKEN}`).toString("base64"); console.log(`::add-mask::${auth}`); - run("git", ["push", "--quiet", `--force-with-lease=refs/heads/${BRANCH}:${remote?.sha ?? ""}`, "origin", `HEAD:refs/heads/${BRANCH}`], { + execute("git", ["push", "--quiet", `--force-with-lease=refs/heads/${BRANCH}:${remote?.sha ?? ""}`, "origin", `HEAD:refs/heads/${BRANCH}`], { env: { ...process.env, GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.https://github.com/.extraheader", GIT_CONFIG_VALUE_0: `AUTHORIZATION: basic ${auth}` }, }); } - if (pr) run("gh", ["pr", "edit", String(pr.number), "-R", repo, "--title", title, "--body-file", bodyFile]); - else run("gh", ["pr", "create", "-R", repo, "--base", getJson(api, `repos/${repo}`).default_branch, "--head", BRANCH, "--title", title, "--body-file", bodyFile]); - const review = requestCopilotReview(api, requestReview, repo, bot); - const reviewSummary = review.state === "none" - ? "no open PR for Copilot review" - : `${review.state === "completed" ? "already completed" : review.state === "pending" ? "already pending" : "requested"} for #${review.pr} at ${review.head.slice(0, 12)}`; - return `${decision === "push" ? `pushed ${BRANCH}` : `${BRANCH} already current`}; Copilot review ${reviewSummary}`; + if (pr) execute("gh", ["api", "--method", "PATCH", `repos/${repo}/pulls/${pr.number}`, "-f", `title=${title}`, "-F", `body=@${bodyFile}`]); + else execute("gh", ["pr", "create", "-R", repo, "--base", base, "--head", BRANCH, "--title", title, "--body-file", bodyFile]); + const current = openPr(api, repo); + if (!current) throw new Error(`No open PR found for ${BRANCH} after publication.`); + execute("gh", ["workflow", "run", "validate.yml", "-R", repo, "--ref", BRANCH]); + return `Plugin pin PR #${current.number} is awaiting Validate and CodeOwner approval.`; +} + +function output(values) { + const lines = Object.entries(values).map(([key, value]) => `${key}=${value ?? ""}`); + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${lines.join("\n")}\n`); + console.log(lines.join("\n")); } export function main(argv, api = githubApi) { @@ -392,25 +155,21 @@ export function main(argv, api = githubApi) { const repo = process.env.GITHUB_REPOSITORY; if (!repo) throw new Error("GITHUB_REPOSITORY must name this repository."); if (command === "update") { - const files = readFiles(); - const plan = planUpdate({ files, actionFiles: ACTION_FILES, api }); - for (const [file, text] of Object.entries(plan.files)) if (text !== files[file]) writeFileSync(file, text); + const text = readFileSync("marketplace.json", "utf8"); + const plan = planUpdate({ text, api }); + if (plan.blocked) { + output({ blocked: true, reason: plan.blocked.replace(/[\r\n]+/g, " ") }); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Pin update blocked\n\n${plan.blocked}\n`); + throw new Error(`Pin update blocked: ${plan.blocked}`); + } + if (plan.text !== text) writeFileSync("marketplace.json", plan.text); if (args["body-file"]) writeFileSync(args["body-file"], plan.body); - const pr = openPr(api, repo); - output({ changed: plan.changes.length > 0, title: plan.title, open_pr: pr?.number }); - summary(plan.changes.length ? `### Pin update\n\n${plan.body}` : `### Pin update\n\nPins are current.${plan.notes.map((note) => `\n- ${note}`).join("")}`); + output({ blocked: false, changed: plan.changes.length > 0, title: plan.title }); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, plan.changes.length ? `### Pin update\n\n${plan.body}` : "### Pin update\n\nPin is current.\n"); } else if (command === "publish") { - const requestReview = (endpoint) => api(endpoint, spawnSync, "POST"); - const result = publish(api, repo, { title: args.title, bodyFile: args["body-file"], bot: args.bot, requestReview }); - console.log(result); - summary(`### Publish\n\n${result}`); - } else if (command === "gate") { - const gate = readGate(api, repo, { bot: args.bot, expectHead: args["expect-head"] }); - output({ decision: gate.decision, pr: gate.pr, pr_node_id: gate.prNodeId, head: gate.head }); - summary(`### Merge gate\n\n**${gate.decision}**${gate.pr ? ` for #${gate.pr}` : ""}: ${gate.reason}`); - if (gate.decision === "block") throw new Error(gate.reason); + console.log(publish(api, repo, { title: args.title, bodyFile: args["body-file"] })); } else { - throw new Error("Usage: update-pins.mjs update [--body-file F] | publish --title T --body-file F --bot LOGIN | gate [--bot LOGIN] [--expect-head SHA]"); + throw new Error("Usage: update-pins.mjs update [--body-file F] | publish --title T --body-file F"); } } diff --git a/.github/scripts/update-pins.test.mjs b/.github/scripts/update-pins.test.mjs index ce56143..19f0156 100644 --- a/.github/scripts/update-pins.test.mjs +++ b/.github/scripts/update-pins.test.mjs @@ -1,53 +1,25 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; import { runInNewContext } from "node:vm"; import { parse } from "yaml"; -import { - BRANCH, - assertBotPr, - approvedCopilotReview, - evaluateMergeGate, - getMergeState, - main, - newestRelease, - planPublish, - planUpdate, - publish, - requestCopilotReview, - requiredChecks, - trustedValidateLint, -} from "./update-pins.mjs"; +import { BRANCH, main, newestRelease, planPublish, planUpdate, publish } from "./update-pins.mjs"; const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const sha = (digit) => digit.repeat(40); -const bot = "pins-app[bot]"; - const marketplace = `${JSON.stringify({ name: "demo", plugins: [ { name: "local", source: "./plugins/local" }, - { - name: "eval", - source: { source: "github", repo: "github/evals", path: "packages/plugin", ref: "copilot-evals-v0.24.60", sha: sha("1") }, - version: "0.24.60", - }, + { name: "eval", source: { source: "github", repo: "github/evals", path: "packages/plugin", ref: "copilot-evals-v0.24.60", sha: sha("1") }, version: "0.24.60" }, ], }, null, 2)}\n`; -const workflow = [ - "steps:", - ` - uses: github/evals-action@${sha("a")}`, - " with:", - ` - uses: github/evals-action@${sha("a")} # github/evals-action#34`, - ` - uses: other/action@${sha("a")}`, - "", -].join("\n"); - const release = (tag_name, extra = {}) => ({ tag_name, draft: false, prerelease: true, ...extra }); +const bot = "github-actions[bot]"; function fakeApi(routes) { const calls = []; @@ -59,572 +31,274 @@ function fakeApi(routes) { return Object.assign(api, { calls }); } -function upstream({ evalsReleases, actionReleases, actionCompare = "ahead" }) { +function upstream(status = "ahead") { return fakeApi({ - "repos/github/evals/releases?per_page=100&page=1": evalsReleases, - "repos/github/evals-action/releases?per_page=100&page=1": actionReleases, + "repos/github/evals/releases?per_page=100&page=1": [release("copilot-evals-v0.24.68"), release("copilot-evals-v0.24.60")], "repos/github/evals/commits/copilot-evals-v0.24.68": { sha: sha("2") }, - "repos/github/evals-action/commits/v0.3.0": { sha: sha("b") }, - [`repos/github/evals-action/compare/${sha("a")}...${sha("b")}`]: { status: actionCompare }, - }); -} - -function commandWorkspace(t) { - const directory = mkdtempSync(join(tmpdir(), "update-pins-test-")); - const previousDirectory = process.cwd(); - const keys = ["GITHUB_REPOSITORY", "GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY"]; - const previousEnvironment = Object.fromEntries(keys.map((key) => [key, process.env[key]])); - process.chdir(directory); - execFileSync("git", ["init", "--quiet"]); - execFileSync("git", ["config", "user.name", "test"]); - execFileSync("git", ["config", "user.email", "test@example.invalid"]); - for (const [file, contents] of Object.entries({ - "marketplace.json": marketplace, - ".github/workflows/skill-eval-comparison.yml": workflow, - "docs/checks-and-evals.md": "", - })) { - mkdirSync(dirname(resolve(directory, file)), { recursive: true }); - writeFileSync(file, contents); - } - execFileSync("git", ["add", "."]); - execFileSync("git", ["commit", "--quiet", "-m", "fixture"]); - - const output = join(directory, "github-output"); - const summary = join(directory, "step-summary"); - process.env.GITHUB_REPOSITORY = "o/r"; - process.env.GITHUB_OUTPUT = output; - process.env.GITHUB_STEP_SUMMARY = summary; - t.after(() => { - process.chdir(previousDirectory); - for (const key of keys) { - if (previousEnvironment[key] === undefined) delete process.env[key]; - else process.env[key] = previousEnvironment[key]; - } - rmSync(directory, { recursive: true, force: true }); + [`repos/github/evals/compare/${sha("1")}...${sha("2")}`]: { status }, }); - return { directory, output, summary }; } -test("newestRelease picks the highest matching semver on the current channel and skips drafts", () => { - const releases = [ - release("copilot-evals-v0.24.9"), - release("copilot-evals-v0.24.70", { draft: true }), - release("copilot-evals-v0.24.10"), - release("copilot-evals-v1.0.0", { prerelease: false }), - release("other-v9.9.9"), - ]; - assert.equal(newestRelease(releases, "copilot-evals-v", true).tag_name, "copilot-evals-v1.0.0"); - assert.equal(newestRelease(releases.slice(0, 3), "copilot-evals-v", true).tag_name, "copilot-evals-v0.24.10"); - assert.equal(newestRelease(releases.slice(0, 3), "copilot-evals-v", false), undefined, "stable pins never move to prereleases"); -}); - -test("planUpdate moves both pins forward and rewrites only evals-action uses lines", () => { - const api = upstream({ - evalsReleases: [release("copilot-evals-v0.24.68"), release("copilot-evals-v0.24.60")], - actionReleases: [release("v0.3.0"), release("v0.2.0")], - }); - const plan = planUpdate({ files: { "marketplace.json": marketplace, "w.yml": workflow }, actionFiles: ["w.yml"], api }); - const entry = JSON.parse(plan.files["marketplace.json"]).plugins[1]; +test("planner updates only the plugin pin to a newer forward release", () => { + const plan = planUpdate({ text: marketplace, api: upstream() }); + const entry = JSON.parse(plan.text).plugins[1]; assert.deepEqual([entry.source.ref, entry.source.sha, entry.version], ["copilot-evals-v0.24.68", sha("2"), "0.24.68"]); - assert.equal(plan.files["marketplace.json"].endsWith("}\n"), true); - assert.equal(plan.files["w.yml"], workflow - .replace(`evals-action@${sha("a")}\n`, `evals-action@${sha("b")} # v0.3.0\n`) - .replace(`evals-action@${sha("a")} # github/evals-action#34`, `evals-action@${sha("b")} # v0.3.0`)); - assert.match(plan.title, /copilot-evals-v0\.24\.68.*evals-action v0\.3\.0/); + assert.deepEqual(JSON.parse(plan.text).plugins[0], JSON.parse(marketplace).plugins[0]); assert.match(plan.body, new RegExp(`compare/${sha("1")}\\.\\.\\.${sha("2")}`)); + assert.match(plan.title, /copilot-evals-v0\.24\.68/); }); -test("planUpdate never downgrades or sidegrades the action pin", () => { - for (const actionCompare of ["behind", "diverged"]) { - const plan = planUpdate({ - files: { "marketplace.json": marketplace, "w.yml": workflow }, - actionFiles: ["w.yml"], - api: upstream({ evalsReleases: [release("copilot-evals-v0.24.60")], actionReleases: [release("v0.3.0")], actionCompare }), - }); - assert.equal(plan.changes.length, 0, actionCompare); - assert.equal(plan.files["w.yml"], workflow); - } -}); - -test("planUpdate rejects unsafe release tags before building review-facing text", () => { - const injection = "![review](https://example.invalid/)-"; - const data = JSON.parse(marketplace); - data.plugins[1].source.ref = `${injection}0.24.60`; - const api = fakeApi({}); - const plan = planUpdate({ - files: { "marketplace.json": `${JSON.stringify(data, null, 2)}\n` }, - actionFiles: [], - api, - }); - - assert.equal(plan.changes.length, 0); - assert.deepEqual(api.calls, []); - assert.doesNotMatch(plan.body, /example\.invalid/); - assert.equal(newestRelease([release(`${injection}0.24.68`)], `${injection}`, true), undefined); +test("release selection respects channel, numeric ordering, and drafts", () => { + assert.equal(newestRelease([release("v0.24.9"), release("v0.24.10"), release("v1.0.0", { draft: true })], "v", true).tag_name, "v0.24.10"); + assert.equal(newestRelease([release("v1.0.0"), release("v0.9.0", { prerelease: false })], "v", false).tag_name, "v0.9.0"); }); -test("planUpdate fails closed on inconsistent action pins or unreadable releases", () => { - const mixed = `${workflow} - uses: github/evals-action@${sha("c")}\n`; - const api = upstream({ evalsReleases: [], actionReleases: [] }); - assert.throws(() => planUpdate({ files: { "marketplace.json": marketplace, "w.yml": mixed }, actionFiles: ["w.yml"], api }), /more than one github\/evals-action commit/); - assert.throws(() => planUpdate({ files: { "marketplace.json": marketplace, "w.yml": workflow }, actionFiles: ["w.yml"], api: fakeApi({}) }), /HTTP 404/); - const rateLimited = (endpoint) => (endpoint.includes("/releases/tags/") ? { status: 403, body: "{}" } : api(endpoint)); - assert.throws(() => planUpdate({ files: { "marketplace.json": marketplace }, api: rateLimited }), /releases\/tags\/copilot-evals-v0\.24\.60: GitHub API returned HTTP 403/); +test("planner blocks unknown channels, failed requests and non-forward commits", () => { + assert.match(planUpdate({ text: marketplace, api: fakeApi({ "repos/github/evals/releases?per_page=100&page=1": [] }) }).blocked, /channel is unknown/); + assert.match(planUpdate({ text: marketplace, api: () => ({ status: 403, body: "{}" }) }).blocked, /HTTP 403/); + assert.match(planUpdate({ text: marketplace, api: () => { throw new Error("network unavailable"); } }).blocked, /network unavailable/); + for (const status of ["behind", "diverged"]) { + assert.match(planUpdate({ text: marketplace, api: upstream(status) }).blocked, new RegExp(status)); + } + assert.match(planUpdate({ text: marketplace, api: upstream("identical") }).blocked, /identical/); }); -test("planUpdate reads every release page before choosing", () => { +test("planner reads every release page and does not downgrade", () => { const filler = Array.from({ length: 100 }, (_, index) => release(`other-v0.0.${index}`)); const api = fakeApi({ "repos/github/evals/releases?per_page=100&page=1": filler, - "repos/github/evals/releases?per_page=100&page=2": [release("copilot-evals-v0.24.68"), release("copilot-evals-v0.24.60")], - "repos/github/evals/commits/copilot-evals-v0.24.68": { sha: sha("2") }, + "repos/github/evals/releases?per_page=100&page=2": [release("copilot-evals-v0.24.60"), release("copilot-evals-v0.24.59")], }); - const plan = planUpdate({ files: { "marketplace.json": marketplace }, api }); - assert.equal(JSON.parse(plan.files["marketplace.json"]).plugins[1].source.ref, "copilot-evals-v0.24.68"); + assert.equal(planUpdate({ text: marketplace, api }).text, marketplace); + assert.equal(api.calls.length, 2); }); -test("requiredChecks reads every rules page and keeps app bindings", () => { - const filler = Array.from({ length: 100 }, () => ({ type: "deletion" })); +test("planner resolves the current tag separately when it is absent from the release listing", () => { const api = fakeApi({ - "repos/o/r/rules/branches/main?per_page=100&page=1": filler, - "repos/o/r/rules/branches/main?per_page=100&page=2": [ - { type: "required_status_checks", parameters: { required_status_checks: [{ context: "evals", integration_id: 42 }] } }, - ], - "repos/o/r/branches/main": { protection: { required_status_checks: { checks: [{ context: "ci/legacy", app_id: null }] } } }, - }); - assert.deepEqual(requiredChecks(api, "o/r", "main"), [{ context: "evals", app: 42 }, { context: "ci/legacy", app: null }]); -}); - -test("requiredChecks treats only the GitHub Free rulesets entitlement error as no rules", () => { - const api = (endpoint) => endpoint.includes("/rules/branches/") - ? { status: 403, body: JSON.stringify({ message: "Upgrade to GitHub Pro or make this repository public to enable this feature." }) } - : { status: 200, body: JSON.stringify({ protection: { required_status_checks: null } }) }; - assert.deepEqual(requiredChecks(api, "o/r", "main"), []); - assert.throws(() => requiredChecks(() => ({ status: 403, body: '{"message":"Resource not accessible by integration"}' }), "o/r", "main"), /HTTP 403/); -}); - -test("trusted Validate lint is required from a successful pull_request run on the exact head", () => { - const head = sha("d"); - const runsEndpoint = `repos/o/r/actions/runs?head_sha=${head}&per_page=100&page=1`; - const jobsEndpoint = "repos/o/r/actions/runs/10/jobs?per_page=100&page=1"; - const validRun = { id: 10, name: "Validate", path: ".github/workflows/validate.yml", event: "pull_request", head_sha: head, status: "completed", conclusion: "success", created_at: "2026-01-01T00:00:00Z", run_attempt: 1 }; - const api = fakeApi({ - [runsEndpoint]: { workflow_runs: [validRun] }, - [jobsEndpoint]: { jobs: [{ name: "lint", status: "completed", conclusion: "success" }] }, - }); - assert.equal(trustedValidateLint(api, "o/r", head), true); - - const untrusted = fakeApi({ - [runsEndpoint]: { workflow_runs: [{ ...validRun, name: "Unrelated workflow" }] }, - }); - assert.equal(trustedValidateLint(untrusted, "o/r", head), false); - const wrongHead = fakeApi({ - [runsEndpoint]: { workflow_runs: [{ ...validRun, head_sha: sha("e") }] }, - }); - assert.equal(trustedValidateLint(wrongHead, "o/r", head), false); -}); - -test("approvedCopilotReview requires Copilot's latest approval on the exact head and reads every page", () => { - const head = sha("d"); - const endpoint = "repos/o/r/pulls/7/reviews"; - const firstPage = `${endpoint}?per_page=100&page=1`; - const secondPage = `${endpoint}?per_page=100&page=2`; - const filler = Array.from({ length: 100 }, () => ({ user: { login: "other[bot]" }, state: "COMMENTED" })); - const copilot = "copilot-pull-request-reviewer[bot]"; - const api = fakeApi({ - [firstPage]: filler, - [secondPage]: [ - { user: { login: copilot }, state: "COMMENTED", commit_id: head, submitted_at: "2026-01-01T00:00:00Z" }, - { user: { login: copilot }, state: "APPROVED", commit_id: head, submitted_at: "2026-01-02T00:00:00Z" }, - ], - }); - assert.equal(approvedCopilotReview(api, "o/r", 7, head), true); - assert.deepEqual(api.calls, [firstPage, secondPage]); - - const commentOnly = fakeApi({ - [firstPage]: [ - { user: { login: "wbreza" }, state: "APPROVED", commit_id: head, submitted_at: "2026-01-01T00:00:00Z" }, - { user: { login: copilot }, state: "COMMENTED", commit_id: head, submitted_at: "2026-01-02T00:00:00Z" }, - ], - }); - assert.equal(approvedCopilotReview(commentOnly, "o/r", 7, head), false); - - const supersededApproval = fakeApi({ - [firstPage]: [ - { user: { login: copilot }, state: "APPROVED", commit_id: head, submitted_at: "2026-01-01T00:00:00Z" }, - { user: { login: copilot }, state: "COMMENTED", commit_id: head, submitted_at: "2026-01-02T00:00:00Z" }, - ], - }); - assert.equal(approvedCopilotReview(supersededApproval, "o/r", 7, head), false); - - const staleApproval = fakeApi({ - [firstPage]: [{ user: { login: copilot }, state: "APPROVED", commit_id: sha("e"), submitted_at: "2026-01-02T00:00:00Z" }], + "repos/github/evals/releases?per_page=100&page=1": [release("copilot-evals-v0.24.68")], + "repos/github/evals/releases/tags/copilot-evals-v0.24.60": release("copilot-evals-v0.24.60"), + "repos/github/evals/commits/copilot-evals-v0.24.68": { sha: sha("2") }, + [`repos/github/evals/compare/${sha("1")}...${sha("2")}`]: { status: "ahead" }, }); - assert.equal(approvedCopilotReview(staleApproval, "o/r", 7, head), false); + assert.equal(JSON.parse(planUpdate({ text: marketplace, api }).text).plugins[1].source.ref, "copilot-evals-v0.24.68"); + assert.ok(api.calls.includes("repos/github/evals/releases/tags/copilot-evals-v0.24.60")); }); -test("requestCopilotReview requests only when the current App PR head lacks a Copilot review", () => { - const head = sha("d"); - const prList = "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins"; - const reviews = "repos/o/r/pulls/7/reviews?per_page=100&page=1"; - const pinPr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: head } }; - let requests = 0; - const requested = requestCopilotReview(fakeApi({ - [prList]: [pinPr], - [reviews]: [], - }), (endpoint) => { - requests += 1; - assert.equal(endpoint, "repos/o/r/pulls/7/copilot-code-review"); - return { status: 201, body: JSON.stringify({ state: "PENDING" }) }; - }, "o/r", bot); - assert.deepEqual(requested, { state: "requested", pr: 7, head }); - assert.equal(requests, 1); - - const commentOnly = fakeApi({ - [prList]: [pinPr], - [reviews]: [{ - user: { login: "copilot-pull-request-reviewer[bot]" }, - state: "COMMENTED", - commit_id: head, - submitted_at: "2026-01-01T00:00:00Z", - }], +test("blocked update reports its reason without modifying the marketplace", (t) => { + const directory = mkdtempSync(join(tmpdir(), "pin-test-")); + const previous = process.cwd(); + const saved = { repo: process.env.GITHUB_REPOSITORY, output: process.env.GITHUB_OUTPUT, summary: process.env.GITHUB_STEP_SUMMARY }; + t.after(() => { + process.chdir(previous); + for (const [key, value] of Object.entries({ GITHUB_REPOSITORY: saved.repo, GITHUB_OUTPUT: saved.output, GITHUB_STEP_SUMMARY: saved.summary })) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + rmSync(directory, { recursive: true, force: true }); }); - const alreadyReviewed = requestCopilotReview(commentOnly, () => { - throw new Error("must not request another review for the same head"); - }, "o/r", bot); - assert.deepEqual(alreadyReviewed, { state: "completed", pr: 7, head }); - - const pending = requestCopilotReview(fakeApi({ - [prList]: [pinPr], - [reviews]: [], - }), () => ({ status: 409, body: "{}" }), "o/r", bot); - assert.deepEqual(pending, { state: "pending", pr: 7, head }); - - assert.throws(() => requestCopilotReview(fakeApi({ - [prList]: [pinPr], - [reviews]: [], - }), () => ({ status: 422, body: JSON.stringify({ failure_reason: "NOT_ELIGIBLE" }) }), "o/r", bot), /HTTP 422 \(NOT_ELIGIBLE\)/); -}); - -const pr = (overrides = {}) => ({ - number: 7, - state: "open", - draft: false, - user: { login: bot, type: "Bot" }, - head: { ref: BRANCH, sha: sha("d"), repo: { full_name: "o/r" } }, - node_id: "PR_kwDOAAA", - base: { ref: "main", repo: { full_name: "o/r", default_branch: "main" } }, - mergeable_state: "blocked", - mergeable: true, - commits: 1, - changed_files: 1, - ...overrides, -}); -const ready = (overrides = {}) => ({ - pr: pr(), - commits: [{ author: { login: bot }, committer: { login: bot } }], - files: [{ filename: "marketplace.json", status: "modified" }], - checkRuns: { total_count: 2, check_runs: [{ name: "lint", status: "completed", conclusion: "success" }, { name: "Copilot", status: "completed", conclusion: "neutral" }] }, - status: { state: "pending", total_count: 0 }, - compare: { behind_by: 0 }, - trustedLintPassed: true, - reviewDecision: "APPROVED", - automatedReviewApproved: true, - bot, - ...overrides, -}); - -test("merge gate merges only a current, bot-only, allowlisted PR with every check settled", () => { - assert.equal(evaluateMergeGate(ready()).decision, "merge"); - assert.equal(evaluateMergeGate(ready()).prNodeId, "PR_kwDOAAA"); - assert.equal(evaluateMergeGate({ ...ready(), pr: undefined }).decision, "none"); - const waits = { - "lint missing": { checkRuns: { total_count: 0, check_runs: [] } }, - "check running": { checkRuns: { total_count: 1, check_runs: [{ name: "lint", status: "in_progress", conclusion: null }] } }, - "status pending": { status: { state: "pending", total_count: 1 } }, - "behind main": { compare: { behind_by: 1 } }, - "head moved": { expectHead: sha("e") }, - "trusted lint missing": { trustedLintPassed: false }, - "GitHub approval missing": { reviewDecision: "REVIEW_REQUIRED" }, - "Copilot approval missing": { automatedReviewApproved: false }, - "GitHub doesn't recognize the Copilot approval": { reviewDecision: "REVIEW_REQUIRED", automatedReviewApproved: true }, - "mergeability pending": { pr: pr({ mergeable: null, mergeable_state: "unknown" }) }, - "content not generated": { stale: ["marketplace.json"] }, - "required check missing": { required: [{ context: "evals" }] }, - "required status pending": { required: [{ context: "ci/legacy" }], status: { state: "pending", total_count: 1, statuses: [{ context: "ci/legacy", state: "pending" }] } }, - "required check from another app": { required: [{ context: "Copilot", app: 42 }] }, - "app-bound status": { required: [{ context: "ci/legacy", app: 42 }], status: { state: "success", total_count: 1, statuses: [{ context: "ci/legacy", state: "success" }] } }, - }; - for (const [label, overrides] of Object.entries(waits)) { - assert.equal(evaluateMergeGate(ready(overrides)).decision, "wait", label); - } - assert.equal(evaluateMergeGate(ready({ reviewDecision: "CHANGES_REQUESTED" })).decision, "block"); - assert.equal(evaluateMergeGate(ready({ required: [{ context: "Copilot" }] })).decision, "merge", "a settled required check run counts"); - const appRun = { checkRuns: { total_count: 2, check_runs: [{ name: "lint", status: "completed", conclusion: "success" }, { name: "Copilot", status: "completed", conclusion: "neutral", app: { id: 42 } }] } }; - assert.equal(evaluateMergeGate(ready({ ...appRun, required: [{ context: "Copilot", app: 42 }] })).decision, "merge", "the bound app's check run counts"); - assert.equal(evaluateMergeGate(ready({ required: [{ context: "ci/legacy" }], status: { state: "success", total_count: 1, statuses: [{ context: "ci/legacy", state: "success" }] } })).decision, "merge", "a successful required status counts"); - assert.equal(evaluateMergeGate(ready({ - checkRuns: { total_count: 0, check_runs: [] }, - status: { state: "success", total_count: 1, statuses: [{ context: "lint", state: "success" }] }, - trustedLintPassed: false, - })).decision, "wait", "a same-named commit status cannot substitute for Validate's lint job"); - const blocks = { - "human author": { pr: pr({ user: { login: "someone", type: "User" } }) }, - "other app": { pr: pr({ user: { login: "other[bot]", type: "Bot" } }) }, - "human commit": { pr: pr({ commits: 2 }), commits: [{ author: { login: bot }, committer: { login: bot } }, { author: { login: "someone" }, committer: { login: bot } }] }, - "amended bot commit": { commits: [{ author: { login: bot }, committer: { login: "someone" } }] }, - "truncated commits": { pr: pr({ commits: 101 }) }, - "truncated files": { pr: pr({ changed_files: 101 }) }, - "unexpected file": { files: [{ filename: ".github/workflows/validate.yml", status: "modified" }] }, - "added file": { files: [{ filename: "marketplace.json", status: "added" }] }, - "fork head": { pr: pr({ head: { ref: BRANCH, sha: sha("d"), repo: { full_name: "fork/r" } } }) }, - draft: { pr: pr({ draft: true }) }, - "failed check": { checkRuns: { total_count: 1, check_runs: [{ name: "lint", status: "completed", conclusion: "failure" }] } }, - "truncated checks": { checkRuns: { total_count: 101, check_runs: [{ name: "lint", status: "completed", conclusion: "success" }] } }, - "failed status": { status: { state: "failure", total_count: 1 } }, - conflict: { pr: pr({ mergeable_state: "dirty" }) }, - }; - for (const [label, overrides] of Object.entries(blocks)) { - assert.equal(evaluateMergeGate(ready(overrides)).decision, "block", label); + process.chdir(directory); + process.env.GITHUB_REPOSITORY = "o/r"; + process.env.GITHUB_OUTPUT = join(directory, "output"); + process.env.GITHUB_STEP_SUMMARY = join(directory, "summary"); + writeFileSync("marketplace.json", marketplace); + for (const [api, reason] of [[fakeApi({ "repos/github/evals/releases?per_page=100&page=1": [] }), /channel is unknown/], [() => ({ status: 403, body: "{}" }), /HTTP 403/], [upstream("diverged"), /diverged/]]) { + assert.throws(() => main(["update"], api), reason); + assert.match(readFileSync(process.env.GITHUB_OUTPUT, "utf8"), /blocked=true/); + assert.match(readFileSync(process.env.GITHUB_OUTPUT, "utf8"), reason); + assert.equal(readFileSync("marketplace.json", "utf8"), marketplace); } }); -test("planPublish creates, skips identical current branches, and refuses human commits", () => { - const base = { main: sha("1"), localTree: sha("2"), bot }; - assert.equal(planPublish({ ...base, remote: undefined }), "push"); - const remote = { sha: sha("3"), tree: sha("2"), parents: [sha("1")], authors: [bot], aheadBy: 1, behindBy: 0 }; - assert.equal(planPublish({ ...base, remote }), "skip"); - assert.equal(planPublish({ ...base, remote: { ...remote, tree: sha("4") } }), "push"); - assert.equal(planPublish({ ...base, remote: { ...remote, behindBy: 2 } }), "push"); - assert.throws(() => planPublish({ ...base, remote: { ...remote, authors: [bot, "someone"] } }), /not authored by/); -}); - -test("merge gate leaves already-queued PRs in the queue without another enqueue", () => { - const queued = ready({ isInMergeQueue: true }); - const result = evaluateMergeGate(queued); - assert.equal(result.decision, "wait"); - assert.match(result.reason, /already in the merge queue/); - assert.equal(evaluateMergeGate(ready({ isInMergeQueue: false })).decision, "merge"); - assert.equal(evaluateMergeGate({ ...queued, expectHead: sha("e") }).reason, "PR head changed since the gate ran."); - assert.equal(evaluateMergeGate({ ...queued, pr: pr({ user: { login: "someone", type: "User" } }) }).decision, "block"); -}); - -test("merge state reads both GitHub approval and queue membership", () => { - const state = { reviewDecision: "APPROVED", isInMergeQueue: true }; - assert.deepEqual(getMergeState("o/r", 7, (command, args) => { - assert.equal(command, "gh"); - assert.deepEqual(args.slice(0, 2), ["api", "graphql"]); - assert.match(args[3], /pullRequest\(number:\$number\)\{reviewDecision isInMergeQueue\}/); - assert.deepEqual(args.slice(4), ["-f", "owner=o", "-f", "name=r", "-F", "number=7", "--jq", ".data.repository.pullRequest"]); - return JSON.stringify(state); - }), state); +test("publication preserves bot ownership and avoids replacing identical branch", () => { + const mainSha = sha("3"); + const remote = { sha: sha("4"), tree: sha("5"), parents: [mainSha], aheadBy: 1, behindBy: 0, authors: [bot] }; + assert.equal(planPublish({ main: mainSha, localTree: sha("5"), remote }), "skip"); + for (const change of [ + { tree: sha("6") }, + { aheadBy: 2 }, + { behindBy: 1 }, + { parents: [] }, + { parents: [sha("7")] }, + ]) assert.equal(planPublish({ main: mainSha, localTree: sha("5"), remote: { ...remote, ...change } }), "push"); + assert.throws(() => planPublish({ main: mainSha, localTree: sha("5"), remote: { ...remote, authors: ["human"] } }), /not authored/); }); -test("publication leaves a queued App PR untouched before git, branch updates, or review requests", () => { - const endpoint = "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins"; - const api = fakeApi({ [endpoint]: [pr()] }); - const result = publish(api, "o/r", { - bot, - mergeState: (repo, number) => { - assert.equal(repo, "o/r"); - assert.equal(number, 7); - return { reviewDecision: "APPROVED", isInMergeQueue: true }; - }, - requestReview: () => assert.fail("queued PRs must not request another review"), - }); - assert.match(result, /already in the merge queue; leaving it unchanged/); - assert.deepEqual(api.calls, [endpoint]); +test("publication dispatches Validate and leaves auto-merge to the trusted completion gate", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const api = fakeApi({ [endpoint]: [pr] }); + const calls = []; + const execute = (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? sha("3") : sha("4"); + if (args[0] === "status") return " M marketplace.json"; + if (args[0] === "pr" && args[1] === "view") return JSON.stringify({ autoMergeRequest: null }); + return ""; + }; + assert.match(publish(api, "o/r", { title: "update", bodyFile: "body", execute }), /awaiting Validate/); + const dispatch = calls.findIndex((call) => call[1] === "workflow"); + const merge = calls.findIndex((call) => call[1] === "pr" && call[2] === "merge"); + assert.ok(dispatch >= 0); + assert.equal(merge, -1); + assert.deepEqual(calls[dispatch].slice(-2), ["--ref", BRANCH]); + assert.ok(calls.some((call) => call[1] === "api" && call[4] === "repos/o/r/pulls/7")); + assert.ok(calls.some((call) => call[1] === "add" && call.at(-1) === "marketplace.json")); + assert.throws(() => publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + if (args[0] === "workflow") throw new Error("dispatch failed"); + if (args[0] === "pr" && args[1] === "merge") assert.fail("must not enable auto-merge in the publisher"); + return execute(command, args); + } }), /dispatch failed/); }); -test("update CLI reports the unchanged plan and writes its step outputs", (t) => { - const { output, summary } = commandWorkspace(t); +test("publisher dispatches validation without enabling auto-merge when the push is skipped", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; const api = fakeApi({ - "repos/github/evals/releases?per_page=100&page=1": [], - "repos/github/evals-action/releases?per_page=100&page=1": [], - "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins": [], + [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], + [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, + [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, }); - - main(["update"], api); - - assert.match(readFileSync(output, "utf8"), /changed=false/); - assert.match(readFileSync(output, "utf8"), /open_pr=/); - assert.match(readFileSync(summary, "utf8"), /Pins are current/); - assert.deepEqual(api.calls, [ - "repos/github/evals/releases?per_page=100&page=1", - "repos/github/evals/releases/tags/copilot-evals-v0.24.60", - "repos/github/evals-action/releases?per_page=100&page=1", - "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins", - ]); + const calls = []; + publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? mainSha : tree; + if (args[0] === "status") return " M marketplace.json"; + if (args[0] === "pr" && args[1] === "view") return JSON.stringify({ autoMergeRequest: null }); + return ""; + } }); + assert.equal(calls.some((call) => call[1] === "push"), false); + assert.ok(calls.some((call) => call[1] === "workflow" && call[2] === "run")); + assert.equal(calls.some((call) => call[1] === "pr" && call[2] === "merge"), false); }); -test("publish CLI reports no changes without pushing or creating a PR", (t) => { - const { summary } = commandWorkspace(t); - const api = fakeApi({ - "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins": [], - }); - - main(["publish", "--title", "test", "--body-file", "body.md", "--bot", bot], api); - - assert.match(readFileSync(summary, "utf8"), /nothing to publish/); - assert.deepEqual(api.calls, [ - "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins", - "repos/o/r/branches/automation%2Fupdate-pins", - ]); +test("publication refuses non-bot PRs", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + assert.throws(() => publish(fakeApi({ [endpoint]: [{ number: 7, user: { login: "human", type: "User" } }] }), "o/r", { title: "update", bodyFile: "body", execute: () => assert.fail("no writes") }), /not the expected/); }); -test("publish refuses a pin branch with more commits than one compare page lists", (t) => { - commandWorkspace(t); - const baseSha = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); - const api = fakeApi({ - "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins": [], - "repos/o/r/branches/automation%2Fupdate-pins": { commit: { sha: sha("9"), commit: { tree: { sha: sha("8") } }, parents: [] } }, - [`repos/o/r/compare/${baseSha}...${sha("9")}`]: { ahead_by: 251, behind_by: 0, commits: [] }, - }); - - assert.throws(() => main(["publish", "--title", "test", "--body-file", "body.md", "--bot", bot], api), /too many commits to verify/); +test("publication refuses duplicate automation PRs", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + const pr = { number: 7, user: { login: bot, type: "Bot" } }; + assert.throws(() => publish(fakeApi({ [endpoint]: [pr, { ...pr, number: 8 }] }), "o/r", { + title: "update", + bodyFile: "body", + execute: () => assert.fail("must not execute with duplicate PRs"), + }), /More than one open PR/); }); -test("gate CLI reports no PR as a non-blocking result", (t) => { - const { output, summary } = commandWorkspace(t); - const api = fakeApi({ - "repos/o/r/pulls?state=open&head=o:automation%2Fupdate-pins": [], - }); - - main(["gate"], api); - - assert.match(readFileSync(output, "utf8"), /decision=none/); - assert.match(readFileSync(summary, "utf8"), /\*\*none\*\*: No open pin update PR/); +test("publisher rejects missing credentials and does not continue after an upstream API denial", (t) => { + const savedToken = process.env.GH_TOKEN; + delete process.env.GH_TOKEN; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + assert.throws(() => publish(fakeApi({}), "o/r", { title: "update", bodyFile: "body", execute: () => assert.fail("must not execute") }), /GH_TOKEN/); + process.env.GH_TOKEN = "synthetic-token"; + const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + const api = (path) => path === endpoint + ? { status: 200, body: JSON.stringify([]) } + : path === "repos/o/r" ? { status: 200, body: JSON.stringify({ default_branch: "main" }) } + : path === `repos/o/r/branches/${encodeURIComponent(BRANCH)}` ? { status: 403, body: "{}" } + : { status: 404, body: "{}" }; + assert.throws(() => publish(api, "o/r", { + title: "update", + bodyFile: "body", + execute: (command, args) => args[0] === "rev-parse" ? sha("3") : assert.fail("must stop before writes"), + }), /HTTP 403/); }); -test("CLI requires a repository and rejects unknown commands", (t) => { - commandWorkspace(t); - const previous = process.env.GITHUB_REPOSITORY; - delete process.env.GITHUB_REPOSITORY; +test("CLI rejects missing repository configuration and unsupported commands", () => { + const savedRepo = process.env.GITHUB_REPOSITORY; try { - assert.throws(() => main(["gate"], fakeApi({})), /GITHUB_REPOSITORY must name this repository/); + delete process.env.GITHUB_REPOSITORY; + assert.throws(() => main(["unknown"]), /GITHUB_REPOSITORY/); + process.env.GITHUB_REPOSITORY = "o/r"; + assert.throws(() => main(["unknown"]), /Usage:/); } finally { - if (previous === undefined) delete process.env.GITHUB_REPOSITORY; - else process.env.GITHUB_REPOSITORY = previous; + if (savedRepo === undefined) delete process.env.GITHUB_REPOSITORY; else process.env.GITHUB_REPOSITORY = savedRepo; } - assert.throws(() => main(["unknown"], fakeApi({})), /Usage: update-pins\.mjs/); -}); - -test("pin publication refuses to close or edit a PR not opened by its App", () => { - assert.doesNotThrow(() => assertBotPr({ number: 7, user: { login: bot, type: "Bot" } }, bot)); - assert.throws(() => assertBotPr({ number: 7, user: { login: "maintainer", type: "User" } }, bot), /isn't authored by/); - assert.throws(() => assertBotPr({ number: 7, user: { login: "other-app[bot]", type: "Bot" } }, bot), /isn't authored by/); + const result = spawnSync(process.execPath, [resolve(root, ".github/scripts/update-pins.mjs"), "unknown"], { + encoding: "utf8", + env: { ...process.env, GITHUB_REPOSITORY: "o/r" }, + }); + assert.equal(result.status, 1); + assert.match(result.stderr, /::error::Usage:/); }); -test("workflow-run planning requires opt-in and a successful same-repository PR run", () => { - const { jobs } = parse(readFileSync(resolve(root, ".github/workflows/update-pins.yml"), "utf8")); - const evaluate = (eventName, enabled, run) => Boolean(runInNewContext(jobs.plan.if, { - github: { event_name: eventName, repository: "o/r", event: { workflow_run: run } }, - vars: { PIN_AUTOMATION: enabled }, - })); - const trusted = { conclusion: "success", event: "pull_request", head_repository: { full_name: "o/r" } }; - assert.equal(evaluate("workflow_run", "true", trusted), true); - for (const enabled of ["false", "", undefined]) { - assert.equal(evaluate("workflow_run", enabled, trusted), false, `opt-in ${enabled}`); - } - for (const conclusion of ["failure", "cancelled", "skipped"]) { - assert.equal(evaluate("workflow_run", "true", { ...trusted, conclusion }), false, conclusion); - } - for (const event of ["push", "workflow_dispatch", "merge_group", undefined]) { - assert.equal(evaluate("workflow_run", "true", { ...trusted, event }), false, event); - } - assert.equal(evaluate("workflow_run", "true", { ...trusted, head_repository: { full_name: "fork/r" } }), false); - assert.equal(evaluate("workflow_run", "true", { ...trusted, head_repository: {} }), false); - assert.equal(evaluate("schedule", "true"), true); - assert.equal(evaluate("schedule", "false"), false); - assert.equal(evaluate("workflow_dispatch", "false"), true, "manual runs remain available while automation is paused"); - assert.equal(jobs.publish.needs, "plan", "publication cannot run when planning is skipped"); - - const gateCondition = jobs.gate.if.replaceAll("needs.*.result", "[needs.plan.result, needs.publish.result]"); - for (const result of ["skipped", "failure", "cancelled"]) { - assert.equal(runInNewContext(gateCondition, { - always: () => true, - contains: (values, value) => values.includes(value), - needs: { plan: { result }, publish: { result: "skipped" } }, - github: { event_name: "workflow_dispatch" }, - }), false, `gate cannot run after planning is ${result}`); - } +test("publication creates one PR and fails closed if creation fails", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + let created = false; + const api = (path) => path === endpoint + ? { status: 200, body: JSON.stringify(created ? [pr] : []) } + : path === "repos/o/r" ? { status: 200, body: JSON.stringify({ default_branch: "main" }) } + : { status: 404, body: "{}" }; + const calls = []; + const execute = (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return sha("3"); + if (args[0] === "status") return " M marketplace.json"; + if (args[0] === "pr" && args[1] === "create") created = true; + if (args[0] === "pr" && args[1] === "view") return JSON.stringify({ autoMergeRequest: null }); + return ""; + }; + publish(api, "o/r", { title: "update", bodyFile: "body", execute }); + assert.equal(calls.filter((call) => call[1] === "pr" && call[2] === "create").length, 1); + assert.ok(calls.findIndex((call) => call[1] === "workflow") > calls.findIndex((call) => call[1] === "pr" && call[2] === "create")); + created = false; + assert.throws(() => publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + if (args[0] === "pr" && args[1] === "create") throw new Error("creation failed"); + if (args[0] === "workflow" || (args[0] === "pr" && args[1] === "merge")) assert.fail("must not dispatch or merge after failed creation"); + return execute(command, args); + } }), /creation failed/); }); -test("enqueue uses nested GraphQL input and narrowly scoped App permissions", () => { - const { jobs } = parse(readFileSync(resolve(root, ".github/workflows/update-pins.yml"), "utf8")); - const app = jobs.enqueue.steps.find((step) => step.id === "app"); - assert.deepEqual(Object.fromEntries(Object.entries(app.with).filter(([key]) => key.startsWith("permission-"))), { - "permission-contents": "write", - "permission-pull-requests": "write", - "permission-workflows": "write", - }); - const recheck = jobs.enqueue.steps.find((step) => step.id === "recheck"); - assert.equal(recheck.env.HEAD_SHA, "${{ needs.gate.outputs.head }}"); - assert.match(recheck.run, /gate --bot "\$BOT" --expect-head "\$HEAD_SHA"/); - const mutation = jobs.enqueue.steps.at(-1); - assert.equal(mutation.if, "steps.recheck.outputs.decision == 'merge'"); - assert.equal(mutation.env.PR_NODE_ID, "${{ steps.recheck.outputs.pr_node_id }}"); - assert.equal(mutation.env.HEAD_SHA, "${{ steps.recheck.outputs.head }}"); - assert.match(mutation.run, /enqueuePullRequest\(input: \$input\)/); - assert.match(mutation.run, /-F "input\[pullRequestId\]=\$PR_NODE_ID"/); - assert.match(mutation.run, /-F "input\[expectedHeadOid\]=\$HEAD_SHA"/); - assert.match(mutation.run, /-F 'input\[jump\]=false'/); - assert.doesNotMatch(mutation.run, /-F input\./); +test("workflow is canonical-only, keyless, and dry-run by default", () => { + const workflow = parse(readFileSync(resolve(root, ".github/workflows/update-pins.yml"), "utf8")); + assert.deepEqual(Object.keys(workflow.jobs), ["update"]); + assert.deepEqual(workflow.permissions, { contents: "write", "pull-requests": "write", actions: "write" }); + assert.equal(workflow.on.workflow_dispatch.inputs.dry_run.default, true); + assert.equal(workflow.on.workflow_run, undefined); + const condition = workflow.jobs.update.if; + const allowed = (repo, event, enabled) => Boolean(runInNewContext(condition, { github: { repository: repo, event_name: event }, vars: { PIN_AUTOMATION: enabled } })); + assert.equal(allowed("github/plugin-marketplace-starter", "schedule", "true"), true); + assert.equal(allowed("github/plugin-marketplace-starter", "schedule", "false"), false); + assert.equal(allowed("github/plugin-marketplace-starter", "workflow_dispatch", "false"), true); + assert.equal(allowed("other/template", "workflow_dispatch", "true"), false); + const text = JSON.stringify(workflow); + assert.doesNotMatch(text, /secrets\.|create-github-app-token|environment|enqueue/); + assert.match(text, /inputs\.dry_run/); }); -test("update-pins workflow keeps secrets out of read-only and dry-run jobs", () => { - const text = readFileSync(resolve(root, ".github/workflows/update-pins.yml"), "utf8"); - const workflow = parse(text); - const validate = parse(readFileSync(resolve(root, ".github/workflows/validate.yml"), "utf8")); - assert.deepEqual(workflow.permissions, { contents: "read" }); - assert.match(workflow.jobs.plan.if, /workflow_run/); - assert.match(workflow.jobs.plan.if, /conclusion == 'success'/); - assert.deepEqual(validate.on.merge_group, { types: ["checks_requested"] }); - assert.equal(workflow.concurrency["cancel-in-progress"], false); - assert.deepEqual(workflow.on.workflow_run.branches, [BRANCH]); - for (const [name, job] of Object.entries(workflow.jobs)) { - const usesSecret = JSON.stringify(job).includes("secrets."); - assert.equal(usesSecret, Boolean(job.environment), `${name}: secrets only in environment jobs`); - if (job.environment) assert.match(job.if, /dry_run/, `${name}: secret jobs honor dry_run`); - for (const step of job.steps) { - if (step.uses) assert.match(step.uses, /@[0-9a-f]{40}\b/, `${name}: ${step.uses} is SHA-pinned`); - if (step.uses?.startsWith("actions/checkout@")) { - assert.equal(step.with["persist-credentials"], false, `${name}: checkout drops credentials`); - assert.equal(step.with.ref, undefined, `${name}: always the default branch`); - } - assert.doesNotMatch(step.run ?? "", /npm (ci|install)/, `${name}: no dependency scripts`); - } - } - const enqueue = workflow.jobs.enqueue; - assert.equal(workflow.jobs.publish.steps.find((step) => step.uses?.startsWith("actions/create-github-app-token@")).with["permission-pull-requests"], "write"); - assert.deepEqual(enqueue.needs, "gate"); - assert.equal(JSON.stringify(enqueue).includes("inputs.dry_run"), true); - assert.equal(JSON.stringify(enqueue).includes("expectedHeadOid"), true); - assert.equal(JSON.stringify(enqueue).includes("pullRequestId"), true); - assert.equal(JSON.stringify(enqueue).includes("/pulls/$PR/merge"), false); - assert.doesNotMatch(text, /pull_request_target|github\.event\.workflow_run\.head_sha/); +test("Dependabot is restricted and grouped for evals-action", () => { + const config = parse(readFileSync(resolve(root, ".github/dependabot.yml"), "utf8")); + assert.deepEqual(config.updates, [{ "package-ecosystem": "github-actions", directory: "/", schedule: { interval: "daily" }, allow: [{ "dependency-name": "github/evals-action" }], groups: { "evals-action": { patterns: ["github/evals-action"] } } }]); + const comparison = readFileSync(resolve(root, ".github/workflows/skill-eval-comparison.yml"), "utf8"); + assert.equal([...comparison.matchAll(/uses: github\/evals-action@[0-9a-f]{40} # v\d+\.\d+\.\d+/g)].length, 3); }); test("comparison cancels superseded PR runs without cancelling manual runs or the serialized report", () => { const workflow = parse(readFileSync(resolve(root, ".github/workflows/skill-eval-comparison.yml"), "utf8")); - assert.equal(workflow.concurrency, undefined, "workflow-level cancellation would also cancel an active report"); - const expectedGroups = { - select: "skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-select", - "run-baseline": "skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-run-baseline", - run: "skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-run", - }; - for (const [job, group] of Object.entries(expectedGroups)) { + assert.equal(workflow.concurrency, undefined); + for (const job of ["select", "run-baseline", "run"]) { const concurrency = workflow.jobs[job].concurrency; - assert.equal(concurrency.group, group); - const cancelExpression = concurrency["cancel-in-progress"].replace(/^\$\{\{\s*|\s*\}\}$/g, ""); - const cancels = (eventName) => Boolean(runInNewContext(cancelExpression, { github: { event_name: eventName } })); - assert.equal(cancels("pull_request"), true, `${job} cancels its superseded PR job`); - assert.equal(cancels("workflow_dispatch"), false, `${job} does not cancel manual runs`); + const expression = concurrency["cancel-in-progress"].replace(/^\$\{\{\s*|\s*\}\}$/g, ""); + assert.equal(Boolean(runInNewContext(expression, { github: { event_name: "pull_request" } })), true); + assert.equal(Boolean(runInNewContext(expression, { github: { event_name: "workflow_dispatch" } })), false); } assert.match(workflow.jobs.report.if, /needs\.run-baseline\.result != 'cancelled'/); assert.match(workflow.jobs.report.if, /needs\.run\.result != 'cancelled'/); - assert.deepEqual(workflow.jobs.report.concurrency, { - group: "evals-${{ github.workflow_ref }}", - "cancel-in-progress": false, - }); + assert.equal(workflow.jobs.report.concurrency["cancel-in-progress"], false); }); diff --git a/.github/workflows/complete-pin-validation.yml b/.github/workflows/complete-pin-validation.yml new file mode 100644 index 0000000..a872bad --- /dev/null +++ b/.github/workflows/complete-pin-validation.yml @@ -0,0 +1,26 @@ +name: Complete pin validation +on: + workflow_run: + workflows: [Validate] + types: [completed] +permissions: + actions: read + contents: write + pull-requests: write + statuses: write +jobs: + validate: + if: github.repository == 'github/plugin-marketplace-starter' && vars.PIN_AUTOMATION == 'true' + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - name: Complete trusted pin validation + env: + GH_TOKEN: ${{ github.token }} + GITHUB_REPOSITORY: ${{ github.repository }} + WORKFLOW_RUN_ID: ${{ github.event.workflow_run.id }} + run: node .github/scripts/pin-validation.mjs diff --git a/.github/workflows/skill-eval-comparison.yml b/.github/workflows/skill-eval-comparison.yml index 8c9c3c6..056e999 100644 --- a/.github/workflows/skill-eval-comparison.yml +++ b/.github/workflows/skill-eval-comparison.yml @@ -92,7 +92,7 @@ jobs: git checkout "$BASE_SHA" -- "$dir" fi done <<< "$SKILL_DIRS" - - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb + - uses: github/evals-action@cd81fcdd4c5c9155d7324ff2e4e77ad805bc8d46 # v0.2.1 continue-on-error: true env: VALLY_TELEMETRY_OPTOUT: '1' @@ -119,7 +119,7 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb + - uses: github/evals-action@cd81fcdd4c5c9155d7324ff2e4e77ad805bc8d46 # v0.2.1 env: VALLY_TELEMETRY_OPTOUT: '1' with: @@ -144,7 +144,7 @@ jobs: group: evals-${{ github.workflow_ref }} cancel-in-progress: false steps: - - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb + - uses: github/evals-action@cd81fcdd4c5c9155d7324ff2e4e77ad805bc8d46 # v0.2.1 with: command: report report-id: evals diff --git a/.github/workflows/update-pins.yml b/.github/workflows/update-pins.yml index 7fdf7ce..e735cdc 100644 --- a/.github/workflows/update-pins.yml +++ b/.github/workflows/update-pins.yml @@ -1,161 +1,41 @@ -name: Update pins -# Moves remote marketplace pins and github/evals-action pins to their newest releases in one bot PR, -# then enqueues it after required checks pass. Setup: docs/checks-and-evals.md#automatic-pin-updates. +name: Update plugin pin on: schedule: - cron: '7,37 * * * *' workflow_dispatch: inputs: dry_run: - description: Report what would change without pushing, opening, or merging a PR. + description: Report the proposed update without publishing a PR. type: boolean default: true - workflow_run: - workflows: [Validate] - types: [completed] - branches: [automation/update-pins] permissions: - contents: read + contents: write + pull-requests: write + actions: write concurrency: - group: update-pins + group: update-plugin-pin cancel-in-progress: false jobs: - plan: + update: if: >- - github.event_name == 'workflow_dispatch' || - (github.event_name == 'schedule' && vars.PIN_AUTOMATION == 'true') || - (github.event_name == 'workflow_run' && vars.PIN_AUTOMATION == 'true' && - github.event.workflow_run.conclusion == 'success' && - github.event.workflow_run.event == 'pull_request' && - github.event.workflow_run.head_repository.full_name == github.repository) + github.repository == 'github/plugin-marketplace-starter' && + (github.event_name == 'workflow_dispatch' || vars.PIN_AUTOMATION == 'true') runs-on: ubuntu-latest timeout-minutes: 10 - permissions: - contents: read - pull-requests: read - outputs: - changed: ${{ steps.update.outputs.changed }} - open_pr: ${{ steps.update.outputs.open_pr }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: + ref: ${{ github.event.repository.default_branch }} persist-credentials: false - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 with: node-version: 24 - - id: update + - id: plan env: GH_TOKEN: ${{ github.token }} - run: node .github/scripts/update-pins.mjs update - - publish: - needs: plan - if: (needs.plan.outputs.changed == 'true' || needs.plan.outputs.open_pr != '') && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) - environment: pin-automation - runs-on: ubuntu-latest - timeout-minutes: 10 - steps: - - id: app - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 - with: - client-id: ${{ vars.PIN_APP_CLIENT_ID }} - private-key: ${{ secrets.PIN_APP_PRIVATE_KEY }} - permission-contents: write - permission-pull-requests: write - permission-workflows: write - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 - with: - node-version: 24 - - id: update - env: - GH_TOKEN: ${{ steps.app.outputs.token }} run: node .github/scripts/update-pins.mjs update --body-file "$RUNNER_TEMP/pin-pr.md" - - name: Check remote pins - env: - GH_TOKEN: ${{ steps.app.outputs.token }} - run: node .github/scripts/check-remote-pins.mjs - - env: - GH_TOKEN: ${{ steps.app.outputs.token }} - TITLE: ${{ steps.update.outputs.title }} - BOT: ${{ steps.app.outputs.app-slug }}[bot] - run: node .github/scripts/update-pins.mjs publish --title "$TITLE" --body-file "$RUNNER_TEMP/pin-pr.md" --bot "$BOT" - - gate: - needs: [plan, publish] - if: >- - always() && needs.plan.result == 'success' && - !contains(needs.*.result, 'failure') && !contains(needs.*.result, 'cancelled') && - (github.event_name == 'workflow_dispatch' || (vars.PIN_AUTOMATION == 'true' && - (github.event_name == 'schedule' || github.event.workflow_run.event == 'pull_request'))) - runs-on: ubuntu-latest - timeout-minutes: 10 - permissions: - contents: read - pull-requests: read - checks: read - statuses: read - actions: read - outputs: - decision: ${{ steps.gate.outputs.decision }} - pr_node_id: ${{ steps.gate.outputs.pr_node_id }} - head: ${{ steps.gate.outputs.head }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 - with: - node-version: 24 - - id: gate + - if: steps.plan.outputs.changed == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) env: GH_TOKEN: ${{ github.token }} - run: node .github/scripts/update-pins.mjs gate - - enqueue: - needs: gate - if: ${{ !cancelled() && needs.gate.result == 'success' && needs.gate.outputs.decision == 'merge' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) }} - environment: pin-automation - runs-on: ubuntu-latest - timeout-minutes: 10 - permissions: - contents: read - pull-requests: read - checks: read - statuses: read - actions: read - steps: - - id: app - uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 - with: - client-id: ${{ vars.PIN_APP_CLIENT_ID }} - private-key: ${{ secrets.PIN_APP_PRIVATE_KEY }} - permission-contents: write - permission-pull-requests: write - permission-workflows: write - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 - with: - node-version: 24 - # Recheck with the run's own token (the app can't read checks), pinned to the head the gate approved. - - id: recheck - env: - GH_TOKEN: ${{ github.token }} - BOT: ${{ steps.app.outputs.app-slug }}[bot] - HEAD_SHA: ${{ needs.gate.outputs.head }} - run: node .github/scripts/update-pins.mjs gate --bot "$BOT" --expect-head "$HEAD_SHA" - - if: steps.recheck.outputs.decision == 'merge' - env: - GH_TOKEN: ${{ steps.app.outputs.token }} - PR_NODE_ID: ${{ steps.recheck.outputs.pr_node_id }} - HEAD_SHA: ${{ steps.recheck.outputs.head }} - run: | - gh api graphql \ - -f query='mutation($input: EnqueuePullRequestInput!) { enqueuePullRequest(input: $input) { mergeQueueEntry { state } } }' \ - -F "input[pullRequestId]=$PR_NODE_ID" \ - -F "input[expectedHeadOid]=$HEAD_SHA" \ - -F 'input[jump]=false' + TITLE: ${{ steps.plan.outputs.title }} + run: node .github/scripts/update-pins.mjs publish --title "$TITLE" --body-file "$RUNNER_TEMP/pin-pr.md" diff --git a/README.md b/README.md index d913581..ddee544 100644 --- a/README.md +++ b/README.md @@ -211,9 +211,9 @@ and per-case transitions) without calling a model. On same-repository pull requests (`head.repo.full_name == github.repository`, excluding fork PRs), [Skill eval comparison](.github/workflows/skill-eval-comparison.yml) uses `github/evals-action` (`report-id: evals-baseline` and -`baseline-report-id: evals-baseline`, pinned to a full commit SHA that -[Update pins](docs/checks-and-evals.md#automatic-pin-updates) advances to each new release) so any changed skill under -`plugins//skills//` with a matching +`baseline-report-id: evals-baseline`), pinned to a full commit SHA. Daily +[Dependabot](docs/checks-and-evals.md#automatic-pin-updates) PRs propose +updating the workflow pin. A changed skill under `plugins//skills//` with a matching `evals//skills//eval.yaml` automatically runs Baseline vs. Candidate and updates one sticky PR comparison comment; see [automatic PR skill comparison](docs/checks-and-evals.md#automatic-pr-skill-comparison). diff --git a/docs/checks-and-evals.md b/docs/checks-and-evals.md index aac61ca..dafca00 100644 --- a/docs/checks-and-evals.md +++ b/docs/checks-and-evals.md @@ -64,85 +64,46 @@ authenticated `gh` CLI. Neither starts a model. ### Automatic pin updates -[Update pins](../.github/workflows/update-pins.yml) keeps remote marketplace -pins and the `github/evals-action` pins current without manual edits: - -- **Plugin pins:** each remote `marketplace.json` entry whose `source.ref` is a - semantic-version tag (for example `v1.2.3` or `eval-v1.2.3`) moves to the - newest strictly newer release from the same repository. Pins on releases - marked stable move only to stable releases; pins on releases marked - prerelease may also move to newer prereleases. - `source.sha` is set to the - tag's commit, and `version` follows only when it matched the old tag. -- **Action pins:** every `uses: github/evals-action@` line in - [skill-eval-comparison.yml](../.github/workflows/skill-eval-comparison.yml) - and this guide moves to the newest release commit, written as - `@ # `. A candidate that is not ahead of the current commit is - skipped. - -With `PIN_AUTOMATION` set to `true`, the workflow checks for releases every -30 minutes and rechecks after a successful Validate `pull_request` run on its -same-repository pin branch. Fork-originated and non-PR `workflow_run` events -cannot reach publication or enqueue. It also supports manual dispatch. It opens or updates -one pull request from `automation/update-pins`, closes it when -nothing remains to change, and enqueues it pinned to the checked head only -when the PR changes nothing beyond the allowlisted files, contains only bot -commits, matches what a fresh update would write, is mergeable and up to date, -every check (including Validate's `lint` and any status check your branch rules -require) has passed, GitHub records a required approval, and Copilot has -submitted a GitHub `APPROVED` review on the exact head. A `COMMENTED` Copilot -review, including one that says “No open issues,” is not approval. The required -merge queue then runs `Validate` again for the combined merge-group head before -merging. Once its ruleset is enabled, direct merges are blocked. Any failure -leaves the PR open for a maintainer. A PR already in the queue is left unchanged: -publication won't replace its head, close it, or request another review, and -the gate won't enqueue it again. -After each publish/update, the trusted job requests one Copilot review when no -Copilot review exists for the current head. Pending or completed reviews prevent -the 30-minute reconciliation from issuing duplicate requests; a new head gets a -new request. Each request can consume Copilot AI credits. If a review completes -as `COMMENTED`, it is not retried for that head and the PR remains open. -The workflow doesn't review upstream changes: enabling it means you trust each -pinned repository's published releases. Keep a pin you want reviewed by hand -off a release tag, or leave the workflow disabled and follow +[Update plugin pin](../.github/workflows/update-pins.yml) proposes newer +`github/evals` plugin releases for this repository only. It preserves the +stable/prerelease channel, requires the candidate commit to be forward of the +current pin, and changes only `marketplace.json`. Unknown release channels, +unreadable upstream data, and non-forward candidates block the plan. + +The workflow uses only `GITHUB_TOKEN`; no App key or environment is needed. +When `PIN_AUTOMATION` is `true`, it checks every 30 minutes. Manual dispatch +defaults to a dry run. A non-dry run opens or updates one PR from +`automation/update-plugin-pin` and dispatches `Validate` on that branch. The +separate [Complete pin validation](../.github/workflows/complete-pin-validation.yml) +workflow runs trusted code from the default branch after Validate completes. It +confirms the exact successful workflow run and PR head, publishes the required +`lint` commit status from GitHub Actions for that SHA, and enables squash +auto-merge. GitHub still requires the checks and one human CodeOwner approval +before merging. + +[Dependabot](../.github/dependabot.yml) separately proposes daily grouped +updates for `github/evals-action` references in workflow files. Dependabot's +handling of prerelease tags has not been verified live. Each PR still requires +one human CodeOwner approval and required checks. The same trusted +default-branch completion workflow verifies the successful Validate run, +Dependabot author, base and exact head, action-only file changes, release tag, +strictly increasing stable version, and forward commit ancestry before enabling +auto-merge. It never checks out or executes PR-head code and does not approve the +PR. Non-stable action tags are not auto-enabled; Dependabot's prerelease-tag +representation has not been verified live. + +An administrator must allow Actions to create pull requests and enable +auto-merge, require the `lint` status check specifically from the **GitHub +Actions** integration (App ID `15368`), require one CodeOwner approval in the +pull-request ruleset, dismiss stale approvals on new commits, and only then set +repository variable `PIN_AUTOMATION` to `true`. GitHub's protected-branch rules +enforce the check and approval before merging; the workflows do not change or +bypass those rules. Configure the rules before enabling the variable; the +keyless workflow does not inspect or change ruleset settings. The +workflow-dispatch status bridge has not been verified live. The automation does +not review upstream releases for you; see [remote pin rules](../plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md). -Manual dispatch works even when `PIN_AUTOMATION` is disabled and defaults to -`dry_run`, which only reports the planned update. Turning off `dry_run` permits -publication and enqueue, subject to all the same review and check gates. -To enable automatic pin-update proposals: - -1. Create a GitHub App, or reuse one, with **Contents**, **Pull requests**, - and **Workflows** read and write access, installed on this repository. - Both write jobs request only these permissions: **Contents** to update - branches and merge, **Pull requests** to manage the PR and queue, and - **Workflows** because action-pin updates change a workflow file. Checks - are read separately using the workflow's read-only `GITHUB_TOKEN`. -2. Create an environment named `pin-automation` limited to the default branch, - with the variable `PIN_APP_CLIENT_ID` (the App's client ID) and the secret - `PIN_APP_PRIVATE_KEY`. -3. Keep the required-review rule enabled, require a human approval, and do not - add the App as a bypass actor. The automation waits for both GitHub's - required approval and an explicit Copilot `APPROVED` review on the current - head. Copilot approvals must not count toward the human approval requirement. - If Copilot only submits `COMMENTED`, the PR remains open; the pin App never - approves its own pull request. The organization or enterprise must allow - Copilot to submit an approving review; otherwise this gate remains closed. -4. Add a separate, active ruleset for the default branch with strict required - status check `lint` from GitHub Actions and a required squash merge queue. - Do not add a bypass actor to this ruleset. `Validate` must include the - `merge_group` event so the queue receives the check result for its combined - head. [Merge queues](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/configuring-pull-request-merges/managing-a-merge-queue) - are available for public repositories owned by organizations and private - repositories owned by organizations using GitHub Enterprise Cloud, not - personal-account repositories. Confirm availability for your repository - before enabling this automation. Without a queue, automatic enqueue fails - closed; it never falls back to a direct merge. -5. Set the repository variable `PIN_AUTOMATION` to `true`. - -Pull requests created with an App token trigger Validate normally; the default -`GITHUB_TOKEN` would not. - Remote checks prefer a root manifest declaring a supported Agent Plugins schema (1.0.0 or 1.1.0); unsupported Agent Plugins versions fail. Otherwise they use Copilot CLI's legacy order: `.plugin/plugin.json`, `plugin.json`, @@ -404,8 +365,8 @@ non-canceling lock. Manual dispatches do not cancel in-progress runs. > top-level **Ship / No-ship** verdict table need a `github/evals-action` release > that includes [github/evals-action#34](https://github.com/github/evals-action/pull/34) > and [github/evals-action#35](https://github.com/github/evals-action/pull/35). -> The workflow pins a full commit SHA, and [Update pins](#automatic-pin-updates) -> moves it to each newer release. +> The workflow file is authoritative for the current full commit SHA. +> [Dependabot](#automatic-pin-updates) updates workflow files, not this example. ```yaml name: Skill eval comparison @@ -483,7 +444,7 @@ jobs: git checkout "$BASE_SHA" -- "$dir" fi done <<< "$SKILL_DIRS" - - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb + - uses: github/evals-action@cd81fcdd4c5c9155d7324ff2e4e77ad805bc8d46 # v0.2.1 continue-on-error: true env: VALLY_TELEMETRY_OPTOUT: '1' @@ -510,7 +471,7 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb + - uses: github/evals-action@cd81fcdd4c5c9155d7324ff2e4e77ad805bc8d46 # v0.2.1 env: VALLY_TELEMETRY_OPTOUT: '1' with: @@ -534,7 +495,7 @@ jobs: group: evals-${{ github.workflow_ref }} cancel-in-progress: false steps: - - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb + - uses: github/evals-action@cd81fcdd4c5c9155d7324ff2e4e77ad805bc8d46 # v0.2.1 with: command: report report-id: evals diff --git a/plugins/marketplace-maintainer/CHANGELOG.md b/plugins/marketplace-maintainer/CHANGELOG.md index 528e466..89b749d 100644 --- a/plugins/marketplace-maintainer/CHANGELOG.md +++ b/plugins/marketplace-maintainer/CHANGELOG.md @@ -3,7 +3,7 @@ ## 0.2.0 - Route confirmed first-release note requests through the release skill even when no files need changing. -- Document the approval and merge-queue requirements for automated remote pin updates. +- Document keyless pin automation with a trusted Validate completion gate, required checks, and human CodeOwner review. ## 0.1.0 diff --git a/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md b/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md index 65e52b1..b99654f 100644 --- a/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md +++ b/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md @@ -76,22 +76,32 @@ pin; don't change the SHA just to make the check pass. ## Keep pins current -If a maintainer enables the marketplace's opt-in Update pins workflow -(`.github/workflows/update-pins.yml`, gated by the `PIN_AUTOMATION` variable), -it proposes newer published releases from the same upstream repository for -release-tagged pins. It enqueues the checked head only after CI passes, -GitHub records a required approval, and Copilot submits an `APPROVED` review -on that exact head; a `COMMENTED` review isn't approval. The required merge -queue reruns checks on the combined head before merging, without bypasses or -a direct-merge fallback. Merge queues are available for public -organization-owned repositories and private organization-owned repositories -on GitHub Enterprise Cloud, not personal-account repositories. Confirm queue -availability before enabling automation; otherwise keep updates manual. -Enabling it is the maintainer's decision to trust those upstream release -channels; it doesn't review upstream changes. Without it, or for a pin it -doesn't manage (a new entry, a branch or untagged ref, or a different -channel), update pins manually on a regular cadence, or when upstream announces -a release: +The starter provides opt-in, keyless pin automation through +`.github/workflows/update-pins.yml`, gated by the `PIN_AUTOMATION` repository +variable. It proposes newer published `github/evals` releases on a dedicated +pull request. The publisher dispatches `Validate`; the trusted +`.github/workflows/complete-pin-validation.yml` workflow runs from the default +branch after Validate completes, verifies the run and exact PR head, publishes +the `lint` status from GitHub Actions for that SHA, and enables squash +auto-merge. Dependabot separately proposes daily grouped +`github/evals-action` workflow-pin updates. The same completion workflow +verifies the Dependabot author, base and head, action-only file changes, release +tag, strictly increasing stable version, forward commit ancestry, and +successful Validate run before enabling auto-merge. Non-stable action tags +aren't auto-enabled; Dependabot's prerelease-tag representation has not been +verified live. Neither path checks out PR-head code, approves a pull request, +or bypasses branch protection. Before setting `PIN_AUTOMATION`, an +administrator must require `lint` from the GitHub Actions integration and one +CodeOwner approval on the default branch, dismiss stale approvals on new +commits, allow Actions to create pull requests, and enable auto-merge. The +workflow-dispatch status bridge has not been verified live, and the keyless +workflow doesn't inspect or change ruleset settings. These automations do not +review upstream changes for you. + +The starter's automation is specific to its own catalog and workflow files. +Other marketplaces, new remote entries, branch or untagged refs, and different +release channels should be updated manually on a regular cadence, or when +upstream announces a release: 1. Check each pin as described above. 2. Review what changed upstream between the pinned SHA and the new one. From c499277fbc1ee4abadeea1634057271580d2baf5 Mon Sep 17 00:00:00 2001 From: Jon Gallant Date: Tue, 24 Nov 2026 09:44:25 -0800 Subject: [PATCH 2/7] fix(ci): reduce pin validation permissions Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/scripts/pin-validation.test.mjs | 2 +- .github/workflows/complete-pin-validation.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/scripts/pin-validation.test.mjs b/.github/scripts/pin-validation.test.mjs index ceae86a..481051f 100644 --- a/.github/scripts/pin-validation.test.mjs +++ b/.github/scripts/pin-validation.test.mjs @@ -216,7 +216,7 @@ test("stops if status publication fails and does not enqueue a merge", () => { test("workflow runs trusted default-branch code with scoped permissions", () => { const workflow = parse(readFileSync(new URL("../workflows/complete-pin-validation.yml", import.meta.url), "utf8")); assert.deepEqual(workflow.on.workflow_run, { workflows: ["Validate"], types: ["completed"] }); - assert.deepEqual(workflow.permissions, { actions: "read", contents: "write", "pull-requests": "write", statuses: "write" }); + assert.deepEqual(workflow.permissions, { actions: "read", contents: "read", "pull-requests": "write", statuses: "write" }); assert.equal(workflow.on.pull_request_target, undefined); assert.match(workflow.jobs.validate.if, /github\.repository == 'github\/plugin-marketplace-starter'/); assert.match(workflow.jobs.validate.if, /vars\.PIN_AUTOMATION == 'true'/); diff --git a/.github/workflows/complete-pin-validation.yml b/.github/workflows/complete-pin-validation.yml index a872bad..777b929 100644 --- a/.github/workflows/complete-pin-validation.yml +++ b/.github/workflows/complete-pin-validation.yml @@ -5,7 +5,7 @@ on: types: [completed] permissions: actions: read - contents: write + contents: read pull-requests: write statuses: write jobs: From 148aeaa97289023e89352a64ab4c385bfd1f0c07 Mon Sep 17 00:00:00 2001 From: Jon Gallant Date: Tue, 24 Nov 2026 10:26:22 -0800 Subject: [PATCH 3/7] fix keyless pin validation gate Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/scripts/pin-validation.mjs | 23 +++- .github/scripts/pin-validation.test.mjs | 50 ++++++++- .github/scripts/update-pins.mjs | 25 ++++- .github/scripts/update-pins.test.mjs | 106 +++++++++++++++++- .github/workflows/complete-pin-validation.yml | 2 +- docs/checks-and-evals.md | 17 ++- plugins/marketplace-maintainer/CHANGELOG.md | 2 +- .../references/remote-pins.md | 13 ++- 8 files changed, 209 insertions(+), 29 deletions(-) diff --git a/.github/scripts/pin-validation.mjs b/.github/scripts/pin-validation.mjs index 8c428e8..86da8ba 100644 --- a/.github/scripts/pin-validation.mjs +++ b/.github/scripts/pin-validation.mjs @@ -6,7 +6,7 @@ import { githubApi } from "./check-remote-pins.mjs"; const canonical = "github/plugin-marketplace-starter"; const pluginBranch = "automation/update-plugin-pin"; -const actionBranchPrefix = "dependabot/github_actions/github/evals-action-"; +const actionBranch = "dependabot/github_actions/evals-action"; const actionFiles = new Set([".github/workflows/evals.yml", ".github/workflows/skill-eval-comparison.yml"]); const pin = /^([+-])([ \t]*- uses: github\/evals-action@)([0-9a-f]{40}) # (v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\s*$/; @@ -89,6 +89,16 @@ function verifyPluginPin(api, repo, pr, head, files) { }; const old = parsePin(oldPin), next = parsePin(newPin); if (compareVersions(next.version, old.version) <= 0 || old.tag === next.tag || old.sha === next.sha) throw new Error("Plugin pin did not advance."); + const release = (tag) => { + const result = getJson(api, `repos/github/evals/releases/tags/${encodeURIComponent(tag)}`); + if (result.tag_name !== tag || result.draft !== false || typeof result.prerelease !== "boolean") { + throw new Error(`Plugin pin release ${tag} is missing, unpublished, or has an unknown channel.`); + } + return result; + }; + const oldRelease = release(old.tag); + const nextRelease = release(next.tag); + if (oldRelease.prerelease !== nextRelease.prerelease) throw new Error("Plugin pin release changed channels."); const clone = (value) => JSON.parse(JSON.stringify(value)); const expected = clone(before); const expectedPin = findPin(expected); @@ -103,8 +113,9 @@ function verifyPluginPin(api, repo, pr, head, files) { function getPullRequest(api, repo, branch) { const owner = repo.split("/")[0]; const matches = getJson(api, `repos/${repo}/pulls?state=open&head=${owner}:${encodeURIComponent(branch)}`); + if (!Array.isArray(matches)) throw new Error("Pull request list response is not an array."); if (matches.length > 1) throw new Error("More than one open PR uses the automation branch."); - return matches[0]; + return matches.length ? getJson(api, `repos/${repo}/pulls/${matches[0].number}`) : undefined; } export function completePinValidation({ api = githubApi, repo, runId, execute = run }) { @@ -117,7 +128,7 @@ export function completePinValidation({ api = githubApi, repo, runId, execute = if (runData.event === "workflow_dispatch" && runData.head_branch === pluginBranch) { author = "github-actions[bot]"; kind = "plugin"; - } else if (runData.event === "pull_request" && typeof runData.head_branch === "string" && runData.head_branch.startsWith(actionBranchPrefix)) { + } else if (runData.event === "pull_request" && runData.head_branch === actionBranch) { author = "dependabot[bot]"; kind = "action"; } else { @@ -134,7 +145,11 @@ export function completePinValidation({ api = githubApi, repo, runId, execute = if (!pr || !validPr(pr, repo, defaultBranch, author)) return "Skipped because no matching open automation PR exists."; if (pr.head?.ref !== runData.head_branch || pr.head?.sha !== runData.head_sha) return "Skipped a stale Validate run for an older PR head."; const commit = getJson(api, `repos/${repo}/commits/${runData.head_sha}`); - if (commit.author?.login !== author || commit.committer?.login !== author) throw new Error("PR head commit was not authored and committed by the expected automation bot."); + const expectedCommitter = commit.committer?.login === author || + (kind === "action" && commit.committer?.login === "web-flow" && commit.commit?.verification?.verified === true); + if (commit.author?.login !== author || !expectedCommitter) { + throw new Error("PR head commit was not authored and committed by the expected verified automation identity."); + } const number = pr.number; const endpoint = `repos/${repo}/pulls/${number}`; const files = getJson(api, `${endpoint}/files?per_page=100&page=1`); diff --git a/.github/scripts/pin-validation.test.mjs b/.github/scripts/pin-validation.test.mjs index 481051f..0727b50 100644 --- a/.github/scripts/pin-validation.test.mjs +++ b/.github/scripts/pin-validation.test.mjs @@ -9,8 +9,10 @@ const baseSha = "a".repeat(40); const headSha = "b".repeat(40); const oldPinSha = "c".repeat(40); const newPinSha = "d".repeat(40); -const branch = "dependabot/github_actions/github/evals-action-v0.2.1"; +const branch = "dependabot/github_actions/evals-action"; const workflowPath = ".github/workflows/validate.yml"; +const currentReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.60"; +const nextReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.68"; const actionFile = { filename: ".github/workflows/skill-eval-comparison.yml", status: "modified", @@ -44,6 +46,11 @@ function fixture({ kind = "action", change = {}, failStatus = false } = {}) { base: { ref: "main", sha: baseSha, repo: { full_name: repo, default_branch: "main" } }, }; const activePr = change.pr ?? pr; + const listedPr = { ...activePr }; + delete listedPr.changed_files; + const commit = isPlugin + ? { author: { login: author }, committer: { login: author } } + : { author: { login: author }, committer: { login: "web-flow" }, commit: { verification: { verified: true, reason: "valid" } } }; const workflowRun = { workflow_id: 77, path: workflowPath, @@ -61,13 +68,15 @@ function fixture({ kind = "action", change = {}, failStatus = false } = {}) { [`repos/${repo}/actions/runs/99`]: workflowRun, [`repos/${repo}/actions/runs/99/jobs?per_page=100&page=1`]: { jobs: [{ name: "lint", conclusion: "success" }] }, [`repos/${repo}`]: { default_branch: "main" }, - [`repos/${repo}/pulls?state=open&head=github:${encodeURIComponent(prBranch)}`]: change.noPr ? [] : change.multiplePrs ? [activePr, { ...activePr, number: 43 }] : [activePr], + [`repos/${repo}/pulls?state=open&head=github:${encodeURIComponent(prBranch)}`]: change.noPr ? [] : change.multiplePrs ? [listedPr, { ...listedPr, number: 43 }] : [listedPr], [`repos/${repo}/pulls/42`]: activePr, - [`repos/${repo}/commits/${headSha}`]: { author: { login: author }, committer: { login: author } }, + [`repos/${repo}/commits/${headSha}`]: commit, [`repos/${repo}/pulls/42/files?per_page=100&page=1`]: isPlugin ? [{ filename: "marketplace.json", status: "modified" }] : [actionFile], "repos/github/evals-action/commits/v0.2.1": { sha: newPinSha }, [`repos/github/evals-action/compare/${oldPinSha}...${newPinSha}`]: { status: "ahead" }, [`repos/github/evals/commits/copilot-evals-v0.24.68`]: { sha: newPinSha }, + [currentReleaseEndpoint]: { tag_name: "copilot-evals-v0.24.60", draft: false, prerelease: true }, + [nextReleaseEndpoint]: { tag_name: "copilot-evals-v0.24.68", draft: false, prerelease: true }, [`repos/github/evals/compare/${oldPinSha}...${newPinSha}`]: { status: "ahead" }, [`repos/${repo}/contents/marketplace.json?ref=${baseSha}`]: beforeMarketplace, [`repos/${repo}/contents/marketplace.json?ref=${headSha}`]: afterMarketplace, @@ -82,6 +91,9 @@ function fixture({ kind = "action", change = {}, failStatus = false } = {}) { if (path === `repos/${repo}/actions/runs/99/jobs?per_page=100&page=1` && change.jobs) data = change.jobs; if (path === `repos/${repo}/commits/${headSha}` && change.commit) data = change.commit; if (path === `repos/${repo}/pulls/42/files?per_page=100&page=1` && change.files) data = change.files; + if (path === currentReleaseEndpoint && change.currentRelease) data = change.currentRelease; + if (path === nextReleaseEndpoint && change.nextRelease) data = change.nextRelease; + if (path === change.releaseFailure?.endpoint) return { status: change.releaseFailure.status, body: "{}" }; if (path === "repos/github/evals-action/compare/" + oldPinSha + "..." + newPinSha && change.comparison) data = change.comparison; if (path === "repos/github/evals-action/commits/v0.2.1" && change.resolved) data = { sha: change.resolved }; if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplace) data = change.marketplace; @@ -102,6 +114,23 @@ test("enables Dependabot auto-merge only after successful Validate and forward a assert.deepEqual(f.calls, [["gh", "pr", "merge", "42", "-R", repo, "--auto", "--squash", "--match-head-commit", headSha]]); }); +test("revalidates both plugin releases and their channel before enabling auto-merge", () => { + const invalidCases = [ + { currentRelease: { tag_name: "copilot-evals-v0.24.60", draft: true, prerelease: true } }, + { nextRelease: { tag_name: "copilot-evals-v0.24.68", draft: true, prerelease: true } }, + { currentRelease: { tag_name: "copilot-evals-v0.24.60", draft: false, prerelease: false } }, + { nextRelease: { tag_name: "copilot-evals-v0.24.68", draft: false, prerelease: false } }, + { currentRelease: { tag_name: "copilot-evals-v0.24.59", draft: false, prerelease: true } }, + { releaseFailure: { endpoint: currentReleaseEndpoint, status: 404 } }, + { releaseFailure: { endpoint: nextReleaseEndpoint, status: 503 } }, + ]; + for (const change of invalidCases) { + const f = fixture({ kind: "plugin", change }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f })); + assert.deepEqual(f.calls, []); + } +}); + test("publishes GitHub Actions lint status for plugin dispatch before enabling exact-head auto-merge", () => { const f = fixture({ kind: "plugin" }); completePinValidation({ repo, runId: 99, ...f }); @@ -119,7 +148,6 @@ test("requires exact workflow provenance, successful jobs, the automation author { run: { path: "untrusted.yml" } }, { commit: { author: { login: "human" }, committer: { login: "human" } } }, { jobs: { jobs: [{ name: "lint", conclusion: "failure" }] } }, - { staleHead: true }, ]; for (const change of invalidCases) { const f = fixture({ change }); @@ -140,8 +168,8 @@ test("ignores unrelated, stale, and absent PR runs without mutation", () => { { run: { event: "push" } }, { run: { status: "in_progress" } }, { run: { conclusion: "failure" } }, - { run: { head_repository: { full_name: "attacker/fork" } } }, { run: { head_sha: "malformed" } }, + { run: { head_branch: "dependabot/github_actions/github/evals-action-v0.2.1" } }, { noPr: true }, { pr: { ...samplePr, user: { login: "someone", type: "User" } } }, { pr: { ...samplePr, head: { ref: branch, sha: oldPinSha, repo: { full_name: repo } } } }, @@ -157,6 +185,16 @@ test("ignores unrelated, stale, and absent PR runs without mutation", () => { assert.deepEqual(multiple.calls, []); }); +test("accepts web-flow as Dependabot committer only for a verified commit", () => { + const f = fixture({ change: { commit: { + author: { login: "dependabot[bot]" }, + committer: { login: "web-flow" }, + commit: { verification: { verified: false, reason: "unsigned" } }, + } } }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f }), /verified/); + assert.deepEqual(f.calls, []); +}); + test("rejects untrusted action PRs, malformed edits, invalid tags, and non-forward pins", () => { const secondFile = { ...actionFile, @@ -216,7 +254,7 @@ test("stops if status publication fails and does not enqueue a merge", () => { test("workflow runs trusted default-branch code with scoped permissions", () => { const workflow = parse(readFileSync(new URL("../workflows/complete-pin-validation.yml", import.meta.url), "utf8")); assert.deepEqual(workflow.on.workflow_run, { workflows: ["Validate"], types: ["completed"] }); - assert.deepEqual(workflow.permissions, { actions: "read", contents: "read", "pull-requests": "write", statuses: "write" }); + assert.deepEqual(workflow.permissions, { actions: "read", contents: "write", "pull-requests": "write", statuses: "write" }); assert.equal(workflow.on.pull_request_target, undefined); assert.match(workflow.jobs.validate.if, /github\.repository == 'github\/plugin-marketplace-starter'/); assert.match(workflow.jobs.validate.if, /vars\.PIN_AUTOMATION == 'true'/); diff --git a/.github/scripts/update-pins.mjs b/.github/scripts/update-pins.mjs index 3a48cb5..9eeecb0 100644 --- a/.github/scripts/update-pins.mjs +++ b/.github/scripts/update-pins.mjs @@ -116,18 +116,36 @@ function remoteBranch(api, repo, main) { return { sha: commit.sha, tree: commit.commit.tree.sha, parents: commit.parents.map((parent) => parent.sha), aheadBy: comparison.ahead_by, behindBy: comparison.behind_by, authors: comparison.commits.flatMap((entry) => [entry.author?.login, entry.committer?.login]) }; } +function currentValidationRun(api, repo, head) { + const result = getJson(api, `repos/${repo}/actions/workflows/validate.yml/runs?branch=${encodeURIComponent(BRANCH)}&event=workflow_dispatch&per_page=100`); + if (!Array.isArray(result.workflow_runs)) throw new Error("Validate workflow-runs response is not an array."); + return result.workflow_runs.find((run) => + run.event === "workflow_dispatch" && + run.head_branch === BRANCH && + run.head_sha === head && + (["queued", "in_progress", "waiting"].includes(run.status) || (run.status === "completed" && run.conclusion === "success")), + ); +} + export function publish(api, repo, { title, bodyFile, execute = run }) { if (!title || !bodyFile || !process.env.GH_TOKEN) throw new Error("Publication requires a title, body file, and GH_TOKEN."); const pr = openPr(api, repo); const base = pr?.base.ref ?? getJson(api, `repos/${repo}`).default_branch; const main = execute("git", ["rev-parse", "HEAD"]); const remote = remoteBranch(api, repo, main); + if (pr && (!remote || pr.head?.sha !== remote.sha)) throw new Error(`Open PR #${pr.number} does not match the current ${BRANCH} head.`); if (!execute("git", ["status", "--porcelain", "--", "marketplace.json"])) throw new Error("No plugin pin change to publish."); if (remote) planPublish({ main, localTree: "", remote }); execute("git", ["add", "--", "marketplace.json"]); execute("git", ["-c", `user.name=${bot}`, "-c", "user.email=41898282+github-actions[bot]@users.noreply.github.com", "commit", "--quiet", "--only", "-m", title, "--", "marketplace.json"]); + const localHead = execute("git", ["rev-parse", "HEAD"]); const decision = planPublish({ main, localTree: execute("git", ["rev-parse", "HEAD^{tree}"]), remote }); if (decision === "push") { + if (pr) { + const currentPr = getJson(api, `repos/${repo}/pulls/${pr.number}`); + if (currentPr.state !== "open" || currentPr.head?.sha !== remote.sha) throw new Error(`Open PR #${pr.number} changed during publication.`); + if (currentPr.auto_merge) execute("gh", ["pr", "merge", String(pr.number), "-R", repo, "--disable-auto"]); + } const auth = Buffer.from(`x-access-token:${process.env.GH_TOKEN}`).toString("base64"); console.log(`::add-mask::${auth}`); execute("git", ["push", "--quiet", `--force-with-lease=refs/heads/${BRANCH}:${remote?.sha ?? ""}`, "origin", `HEAD:refs/heads/${BRANCH}`], { @@ -137,8 +155,11 @@ export function publish(api, repo, { title, bodyFile, execute = run }) { if (pr) execute("gh", ["api", "--method", "PATCH", `repos/${repo}/pulls/${pr.number}`, "-f", `title=${title}`, "-F", `body=@${bodyFile}`]); else execute("gh", ["pr", "create", "-R", repo, "--base", base, "--head", BRANCH, "--title", title, "--body-file", bodyFile]); const current = openPr(api, repo); - if (!current) throw new Error(`No open PR found for ${BRANCH} after publication.`); - execute("gh", ["workflow", "run", "validate.yml", "-R", repo, "--ref", BRANCH]); + const publishedHead = decision === "push" ? localHead : remote.sha; + if (!current || current.head?.sha !== publishedHead) throw new Error(`No open PR found at the published ${BRANCH} head.`); + const existingValidation = decision === "skip" && pr ? currentValidationRun(api, repo, publishedHead) : undefined; + if (!existingValidation) execute("gh", ["workflow", "run", "validate.yml", "-R", repo, "--ref", BRANCH]); + if (existingValidation) return `Plugin pin PR #${current.number} already has a current-head Validate run and is awaiting CodeOwner approval.`; return `Plugin pin PR #${current.number} is awaiting Validate and CodeOwner approval.`; } diff --git a/.github/scripts/update-pins.test.mjs b/.github/scripts/update-pins.test.mjs index 19f0156..8c892ee 100644 --- a/.github/scripts/update-pins.test.mjs +++ b/.github/scripts/update-pins.test.mjs @@ -11,6 +11,7 @@ import { BRANCH, main, newestRelease, planPublish, planUpdate, publish } from ". const root = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); const sha = (digit) => digit.repeat(40); +const validationRunsEndpoint = `repos/o/r/actions/workflows/validate.yml/runs?branch=${encodeURIComponent(BRANCH)}&event=workflow_dispatch&per_page=100`; const marketplace = `${JSON.stringify({ name: "demo", plugins: [ @@ -127,14 +128,24 @@ test("publication dispatches Validate and leaves auto-merge to the trusted compl process.env.GH_TOKEN = "synthetic-token"; t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; - const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; - const api = fakeApi({ [endpoint]: [pr] }); + const mainSha = sha("3"), remoteSha = sha("4"), localHead = sha("6"), localTree = sha("7"); + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + let pushed = false; + const api = (path) => { + if (path === endpoint) return { status: 200, body: JSON.stringify([{ ...pr, head: { ...pr.head, sha: pushed ? localHead : remoteSha } }]) }; + if (path === "repos/o/r/pulls/7") return { status: 200, body: JSON.stringify({ state: "open", head: { sha: remoteSha }, auto_merge: null }) }; + if (path === `repos/o/r/branches/${encodeURIComponent(BRANCH)}`) return { status: 200, body: JSON.stringify({ commit: { sha: remoteSha, commit: { tree: { sha: sha("5") } }, parents: [{ sha: mainSha }] } }) }; + if (path === `repos/o/r/compare/${mainSha}...${remoteSha}`) return { status: 200, body: JSON.stringify({ ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }) }; + return { status: 404, body: "{}" }; + }; const calls = []; + let headReads = 0; const execute = (command, args) => { calls.push([command, ...args]); - if (args[0] === "rev-parse") return args[1] === "HEAD" ? sha("3") : sha("4"); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? (++headReads === 1 ? mainSha : localHead) : localTree; if (args[0] === "status") return " M marketplace.json"; if (args[0] === "pr" && args[1] === "view") return JSON.stringify({ autoMergeRequest: null }); + if (args[0] === "push") pushed = true; return ""; }; assert.match(publish(api, "o/r", { title: "update", bodyFile: "body", execute }), /awaiting Validate/); @@ -145,6 +156,8 @@ test("publication dispatches Validate and leaves auto-merge to the trusted compl assert.deepEqual(calls[dispatch].slice(-2), ["--ref", BRANCH]); assert.ok(calls.some((call) => call[1] === "api" && call[4] === "repos/o/r/pulls/7")); assert.ok(calls.some((call) => call[1] === "add" && call.at(-1) === "marketplace.json")); + pushed = false; + headReads = 0; assert.throws(() => publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { if (args[0] === "workflow") throw new Error("dispatch failed"); if (args[0] === "pr" && args[1] === "merge") assert.fail("must not enable auto-merge in the publisher"); @@ -157,11 +170,12 @@ test("publisher dispatches validation without enabling auto-merge when the push process.env.GH_TOKEN = "synthetic-token"; t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); - const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; const api = fakeApi({ [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, + [validationRunsEndpoint]: { workflow_runs: [] }, }); const calls = []; publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { @@ -176,6 +190,88 @@ test("publisher dispatches validation without enabling auto-merge when the push assert.equal(calls.some((call) => call[1] === "pr" && call[2] === "merge"), false); }); +test("publisher disables auto-merge before pushing a replacement PR head", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const mainSha = sha("3"), remoteSha = sha("4"), remoteTree = sha("5"), localHead = sha("6"), localTree = sha("7"); + const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + let pushed = false; + const api = (path) => path === endpoint + ? { status: 200, body: JSON.stringify([{ ...pr, head: { ...pr.head, sha: pushed ? localHead : remoteSha } }]) } + : path === "repos/o/r/pulls/7" + ? { status: 200, body: JSON.stringify({ state: "open", head: { sha: remoteSha }, auto_merge: { enabled_at: "now" } }) } + : path === `repos/o/r/branches/${encodeURIComponent(BRANCH)}` + ? { status: 200, body: JSON.stringify({ commit: { sha: remoteSha, commit: { tree: { sha: remoteTree } }, parents: [{ sha: mainSha }] } }) } + : path === `repos/o/r/compare/${mainSha}...${remoteSha}` + ? { status: 200, body: JSON.stringify({ ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }) } + : { status: 404, body: "{}" }; + const calls = []; + let headReads = 0; + publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? (++headReads === 1 ? mainSha : localHead) : localTree; + if (args[0] === "status") return " M marketplace.json"; + if (args[0] === "push") pushed = true; + return ""; + } }); + const disable = calls.findIndex((call) => call[1] === "pr" && call[2] === "merge" && call.at(-1) === "--disable-auto"); + const push = calls.findIndex((call) => call[1] === "push"); + const dispatch = calls.findIndex((call) => call[1] === "workflow"); + assert.ok(disable >= 0); + assert.ok(disable < push); + assert.ok(push < dispatch); + assert.equal(calls.some((call) => call[1] === "pr" && call[2] === "merge" && call.includes("--auto")), false); +}); + +test("publisher skips duplicate Validate dispatch for a successfully validated unchanged PR head", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const api = fakeApi({ + [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], + [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, + [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, + [validationRunsEndpoint]: { workflow_runs: [{ event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status: "completed", conclusion: "success" }] }, + }); + const calls = []; + publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? mainSha : tree; + if (args[0] === "status") return " M marketplace.json"; + if (args[0] === "pr" && args[1] === "view") return JSON.stringify({ autoMergeRequest: null }); + return ""; + } }); + assert.equal(calls.some((call) => call[1] === "workflow" && call[2] === "run"), false); +}); + +test("publisher avoids duplicate Validate dispatch while the current-head run is active", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + for (const status of ["queued", "in_progress", "waiting"]) { + const api = fakeApi({ + [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], + [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, + [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, + [validationRunsEndpoint]: { workflow_runs: [{ event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status }] }, + }); + const calls = []; + publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? mainSha : tree; + if (args[0] === "status") return " M marketplace.json"; + return ""; + } }); + assert.equal(calls.some((call) => call[1] === "workflow" && call[2] === "run"), false, `unexpected dispatch for ${status} run`); + } +}); + test("publication refuses non-bot PRs", (t) => { const savedToken = process.env.GH_TOKEN; process.env.GH_TOKEN = "synthetic-token"; @@ -239,7 +335,7 @@ test("publication creates one PR and fails closed if creation fails", (t) => { process.env.GH_TOKEN = "synthetic-token"; t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); const endpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; - const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: sha("3"), repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; let created = false; const api = (path) => path === endpoint ? { status: 200, body: JSON.stringify(created ? [pr] : []) } diff --git a/.github/workflows/complete-pin-validation.yml b/.github/workflows/complete-pin-validation.yml index 777b929..a872bad 100644 --- a/.github/workflows/complete-pin-validation.yml +++ b/.github/workflows/complete-pin-validation.yml @@ -5,7 +5,7 @@ on: types: [completed] permissions: actions: read - contents: read + contents: write pull-requests: write statuses: write jobs: diff --git a/docs/checks-and-evals.md b/docs/checks-and-evals.md index dafca00..8747f97 100644 --- a/docs/checks-and-evals.md +++ b/docs/checks-and-evals.md @@ -92,14 +92,21 @@ auto-merge. It never checks out or executes PR-head code and does not approve th PR. Non-stable action tags are not auto-enabled; Dependabot's prerelease-tag representation has not been verified live. +The embedded workflow example later on this page contains three +`github/evals-action` pins. The workflow files are authoritative for current +pins; Dependabot updates workflow files only, not this documentation example. + An administrator must allow Actions to create pull requests and enable auto-merge, require the `lint` status check specifically from the **GitHub Actions** integration (App ID `15368`), require one CodeOwner approval in the -pull-request ruleset, dismiss stale approvals on new commits, and only then set -repository variable `PIN_AUTOMATION` to `true`. GitHub's protected-branch rules -enforce the check and approval before merging; the workflows do not change or -bypass those rules. Configure the rules before enabling the variable; the -keyless workflow does not inspect or change ruleset settings. The +pull-request ruleset, require branches to be up to date before merging, dismiss +stale approvals on new commits, and only then set repository variable +`PIN_AUTOMATION` to `true`. The completion workflow needs `contents: write` +because `gh pr merge --auto` can merge immediately once every requirement is +satisfied; it uses no admin or bypass option. GitHub's protected-branch rules +enforce the check, freshness, and human approval before merging; the workflows +do not change or bypass those rules. Configure the rules before enabling the +variable; the keyless workflow does not inspect or change ruleset settings. The workflow-dispatch status bridge has not been verified live. The automation does not review upstream releases for you; see [remote pin rules](../plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md). diff --git a/plugins/marketplace-maintainer/CHANGELOG.md b/plugins/marketplace-maintainer/CHANGELOG.md index 89b749d..6a4b6b9 100644 --- a/plugins/marketplace-maintainer/CHANGELOG.md +++ b/plugins/marketplace-maintainer/CHANGELOG.md @@ -3,7 +3,7 @@ ## 0.2.0 - Route confirmed first-release note requests through the release skill even when no files need changing. -- Document keyless pin automation with a trusted Validate completion gate, required checks, and human CodeOwner review. +- Document keyless pin automation with a trusted Validate completion gate, up-to-date checks, and required human CodeOwner approval. ## 0.1.0 diff --git a/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md b/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md index b99654f..09ea30b 100644 --- a/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md +++ b/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md @@ -92,11 +92,14 @@ aren't auto-enabled; Dependabot's prerelease-tag representation has not been verified live. Neither path checks out PR-head code, approves a pull request, or bypasses branch protection. Before setting `PIN_AUTOMATION`, an administrator must require `lint` from the GitHub Actions integration and one -CodeOwner approval on the default branch, dismiss stale approvals on new -commits, allow Actions to create pull requests, and enable auto-merge. The -workflow-dispatch status bridge has not been verified live, and the keyless -workflow doesn't inspect or change ruleset settings. These automations do not -review upstream changes for you. +CodeOwner approval on the default branch, require branches to be up to date +before merging, dismiss stale approvals on new commits, allow Actions to create +pull requests, and enable auto-merge. The completion workflow needs +`contents: write` because `gh pr merge --auto` can merge immediately once every +requirement is satisfied; it uses no admin or bypass option. The workflow- +dispatch status bridge has not been verified live, and the keyless workflow +doesn't inspect or change ruleset settings. These automations do not review +upstream changes for you. The starter's automation is specific to its own catalog and workflow files. Other marketplaces, new remote entries, branch or untagged refs, and different From 029e55957081889b1100d72cf3875a2530214f74 Mon Sep 17 00:00:00 2001 From: Jon Gallant Date: Tue, 24 Nov 2026 13:55:05 -0800 Subject: [PATCH 4/7] Fix pin automation review gaps Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/scripts/pin-validation.mjs | 28 ++++-- .github/scripts/pin-validation.test.mjs | 24 +++++- .github/scripts/update-pins.mjs | 24 +++++- .github/scripts/update-pins.test.mjs | 85 ++++++++++++++++++- .github/workflows/complete-pin-validation.yml | 3 + 5 files changed, 150 insertions(+), 14 deletions(-) diff --git a/.github/scripts/pin-validation.mjs b/.github/scripts/pin-validation.mjs index 86da8ba..481b16a 100644 --- a/.github/scripts/pin-validation.mjs +++ b/.github/scripts/pin-validation.mjs @@ -6,7 +6,7 @@ import { githubApi } from "./check-remote-pins.mjs"; const canonical = "github/plugin-marketplace-starter"; const pluginBranch = "automation/update-plugin-pin"; -const actionBranch = "dependabot/github_actions/evals-action"; +const actionBranch = /^dependabot\/github_actions\/evals-action-[0-9a-f]{10}$/; const actionFiles = new Set([".github/workflows/evals.yml", ".github/workflows/skill-eval-comparison.yml"]); const pin = /^([+-])([ \t]*- uses: github\/evals-action@)([0-9a-f]{40}) # (v\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\s*$/; @@ -44,14 +44,30 @@ function verifyActionPins(api, files, changedFiles) { const oldPins = []; for (const file of files) { if (!actionFiles.has(file.filename) || file.status !== "modified" || typeof file.patch !== "string") throw new Error("Unexpected changed file or missing patch."); - const removed = [], added = []; + const blocks = []; + let block = []; for (const line of file.patch.split("\n")) { - if (!line.startsWith("+") && !line.startsWith("-")) continue; + if (!line.startsWith("+") && !line.startsWith("-")) { + if (block.length) blocks.push(block); + block = []; + continue; + } const match = pin.exec(line); if (!match) throw new Error("PR changes more than evals-action pins."); - (match[1] === "-" ? removed : added).push(match); + block.push(match); + } + if (block.length) blocks.push(block); + const removed = [], added = []; + for (const changes of blocks) { + const blockRemoved = changes.filter((entry) => entry[1] === "-"); + const blockAdded = changes.filter((entry) => entry[1] === "+"); + if (!blockRemoved.length || blockRemoved.length !== blockAdded.length || blockRemoved.some((entry, index) => entry[2] !== blockAdded[index][2])) { + throw new Error("Action pin replacements must be in-place and paired."); + } + removed.push(...blockRemoved); + added.push(...blockAdded); } - if (!removed.length || removed.length !== added.length || file.additions !== added.length || file.deletions !== removed.length || removed.some((entry, index) => entry[2] !== added[index][2])) throw new Error("Incomplete or unpaired action pin changes."); + if (!removed.length || file.additions !== added.length || file.deletions !== removed.length) throw new Error("Incomplete or unpaired action pin changes."); oldPins.push(...removed.map((entry) => ({ sha: entry[3], tag: entry[4] }))); for (const entry of added) { const next = `${entry[3]} ${entry[4]}`; @@ -128,7 +144,7 @@ export function completePinValidation({ api = githubApi, repo, runId, execute = if (runData.event === "workflow_dispatch" && runData.head_branch === pluginBranch) { author = "github-actions[bot]"; kind = "plugin"; - } else if (runData.event === "pull_request" && runData.head_branch === actionBranch) { + } else if (runData.event === "pull_request" && actionBranch.test(runData.head_branch ?? "")) { author = "dependabot[bot]"; kind = "action"; } else { diff --git a/.github/scripts/pin-validation.test.mjs b/.github/scripts/pin-validation.test.mjs index 0727b50..bc3ef40 100644 --- a/.github/scripts/pin-validation.test.mjs +++ b/.github/scripts/pin-validation.test.mjs @@ -9,7 +9,7 @@ const baseSha = "a".repeat(40); const headSha = "b".repeat(40); const oldPinSha = "c".repeat(40); const newPinSha = "d".repeat(40); -const branch = "dependabot/github_actions/evals-action"; +const branch = "dependabot/github_actions/evals-action-a1b2c3d4e5"; const workflowPath = ".github/workflows/validate.yml"; const currentReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.60"; const nextReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.68"; @@ -20,6 +20,15 @@ const actionFile = { deletions: 1, patch: `@@ -1 +1 @@\n- - uses: github/evals-action@${oldPinSha} # v0.2.0\n+ - uses: github/evals-action@${newPinSha} # v0.2.1`, }; +const movedActionFile = { + ...actionFile, + patch: `@@ -1,4 +1,4 @@ + - name: previous step + run: echo ok +- - uses: github/evals-action@${oldPinSha} # v0.2.0 + continue-on-error: true ++ - uses: github/evals-action@${newPinSha} # v0.2.1`, +}; const beforeMarketplace = { plugins: [{ name: "eval", @@ -34,7 +43,7 @@ afterMarketplace.plugins[0].version = "0.24.68"; function fixture({ kind = "action", change = {}, failStatus = false } = {}) { const isPlugin = kind === "plugin"; - const prBranch = isPlugin ? "automation/update-plugin-pin" : branch; + const prBranch = isPlugin ? "automation/update-plugin-pin" : change.branch ?? branch; const author = isPlugin ? "github-actions[bot]" : "dependabot[bot]"; const pr = { state: "open", @@ -170,6 +179,8 @@ test("ignores unrelated, stale, and absent PR runs without mutation", () => { { run: { conclusion: "failure" } }, { run: { head_sha: "malformed" } }, { run: { head_branch: "dependabot/github_actions/github/evals-action-v0.2.1" } }, + { run: { head_branch: "dependabot/github_actions/evals-action-a1b2c3d4e" } }, + { run: { head_branch: "dependabot/github_actions/evals-action-a1b2c3d4e5-extra" } }, { noPr: true }, { pr: { ...samplePr, user: { login: "someone", type: "User" } } }, { pr: { ...samplePr, head: { ref: branch, sha: oldPinSha, repo: { full_name: repo } } } }, @@ -223,6 +234,12 @@ test("rejects untrusted action PRs, malformed edits, invalid tags, and non-forwa assert.equal(grouped.calls.filter((call) => call[1] === "pr" && call[2] === "merge").length, 1); }); +test("rejects action pin replacements that move step settings", () => { + const f = fixture({ change: { files: [movedActionFile] } }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f }), /in-place/); + assert.deepEqual(f.calls, []); +}); + test("rejects plugin PRs that alter anything beyond the verified forward pin", () => { const badMarketplace = structuredClone(afterMarketplace); badMarketplace.plugins[0].description = "unexpected"; @@ -253,8 +270,11 @@ test("stops if status publication fails and does not enqueue a merge", () => { test("workflow runs trusted default-branch code with scoped permissions", () => { const workflow = parse(readFileSync(new URL("../workflows/complete-pin-validation.yml", import.meta.url), "utf8")); + const publisher = parse(readFileSync(new URL("../workflows/update-pins.yml", import.meta.url), "utf8")); assert.deepEqual(workflow.on.workflow_run, { workflows: ["Validate"], types: ["completed"] }); assert.deepEqual(workflow.permissions, { actions: "read", contents: "write", "pull-requests": "write", statuses: "write" }); + assert.deepEqual(workflow.concurrency, publisher.concurrency); + assert.deepEqual(workflow.concurrency, { group: "update-plugin-pin", "cancel-in-progress": false }); assert.equal(workflow.on.pull_request_target, undefined); assert.match(workflow.jobs.validate.if, /github\.repository == 'github\/plugin-marketplace-starter'/); assert.match(workflow.jobs.validate.if, /vars\.PIN_AUTOMATION == 'true'/); diff --git a/.github/scripts/update-pins.mjs b/.github/scripts/update-pins.mjs index 9eeecb0..4988e19 100644 --- a/.github/scripts/update-pins.mjs +++ b/.github/scripts/update-pins.mjs @@ -23,9 +23,9 @@ const semver = (tag, prefix) => { }; const compareSemver = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]; -export function newestRelease(releases, prefix, allowPrerelease) { +export function newestRelease(releases, prefix, prerelease) { return releases - .filter((release) => !release.draft && (allowPrerelease || !release.prerelease) && semver(release.tag_name, prefix)) + .filter((release) => !release.draft && release.prerelease === prerelease && semver(release.tag_name, prefix)) .sort((a, b) => compareSemver(semver(b.tag_name, prefix), semver(a.tag_name, prefix)))[0]; } @@ -127,6 +127,20 @@ function currentValidationRun(api, repo, head) { ); } +function completionHasTakenEffect(api, repo, pr, head, validation) { + const current = getJson(api, `repos/${repo}/pulls/${pr.number}`); + if (current.state !== "open" || current.head?.sha !== head) throw new Error(`Open PR #${pr.number} changed during completion verification.`); + if (!current.auto_merge || typeof validation.html_url !== "string" || !validation.html_url) return false; + const statuses = getJson(api, `repos/${repo}/commits/${head}/statuses?per_page=100`); + if (!Array.isArray(statuses)) throw new Error("Commit statuses response is not an array."); + return statuses.some((status) => + status.context === "lint" && + status.state === "success" && + status.target_url === validation.html_url && + status.creator?.login === bot, + ); +} + export function publish(api, repo, { title, bodyFile, execute = run }) { if (!title || !bodyFile || !process.env.GH_TOKEN) throw new Error("Publication requires a title, body file, and GH_TOKEN."); const pr = openPr(api, repo); @@ -158,8 +172,10 @@ export function publish(api, repo, { title, bodyFile, execute = run }) { const publishedHead = decision === "push" ? localHead : remote.sha; if (!current || current.head?.sha !== publishedHead) throw new Error(`No open PR found at the published ${BRANCH} head.`); const existingValidation = decision === "skip" && pr ? currentValidationRun(api, repo, publishedHead) : undefined; - if (!existingValidation) execute("gh", ["workflow", "run", "validate.yml", "-R", repo, "--ref", BRANCH]); - if (existingValidation) return `Plugin pin PR #${current.number} already has a current-head Validate run and is awaiting CodeOwner approval.`; + const validationActive = existingValidation && ["queued", "in_progress", "waiting"].includes(existingValidation.status); + const completionApplied = existingValidation?.status === "completed" && completionHasTakenEffect(api, repo, current, publishedHead, existingValidation); + if (!validationActive && !completionApplied) execute("gh", ["workflow", "run", "validate.yml", "-R", repo, "--ref", BRANCH]); + if (validationActive || completionApplied) return `Plugin pin PR #${current.number} already has a current-head Validate run and is awaiting CodeOwner approval.`; return `Plugin pin PR #${current.number} is awaiting Validate and CodeOwner approval.`; } diff --git a/.github/scripts/update-pins.test.mjs b/.github/scripts/update-pins.test.mjs index 8c892ee..25efde6 100644 --- a/.github/scripts/update-pins.test.mjs +++ b/.github/scripts/update-pins.test.mjs @@ -49,6 +49,24 @@ test("planner updates only the plugin pin to a newer forward release", () => { assert.match(plan.title, /copilot-evals-v0\.24\.68/); }); +test("planner keeps prerelease pins in their current channel when a stable release is newer", () => { + const prereleaseTag = "copilot-evals-v0.24.68"; + const stableTag = "copilot-evals-v1.0.0"; + const api = fakeApi({ + "repos/github/evals/releases?per_page=100&page=1": [ + release(prereleaseTag), + release(stableTag, { prerelease: false }), + release("copilot-evals-v0.24.60"), + ], + [`repos/github/evals/commits/${prereleaseTag}`]: { sha: sha("2") }, + [`repos/github/evals/commits/${stableTag}`]: { sha: sha("3") }, + [`repos/github/evals/compare/${sha("1")}...${sha("2")}`]: { status: "ahead" }, + [`repos/github/evals/compare/${sha("1")}...${sha("3")}`]: { status: "ahead" }, + }); + const plan = planUpdate({ text: marketplace, api }); + assert.equal(JSON.parse(plan.text).plugins[1].source.ref, prereleaseTag); +}); + test("release selection respects channel, numeric ordering, and drafts", () => { assert.equal(newestRelease([release("v0.24.9"), release("v0.24.10"), release("v1.0.0", { draft: true })], "v", true).tag_name, "v0.24.10"); assert.equal(newestRelease([release("v1.0.0"), release("v0.9.0", { prerelease: false })], "v", false).tag_name, "v0.9.0"); @@ -230,12 +248,15 @@ test("publisher skips duplicate Validate dispatch for a successfully validated u process.env.GH_TOKEN = "synthetic-token"; t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); - const pr = { number: 7, user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const pr = { number: 7, state: "open", user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const validationUrl = "https://github.com/o/r/actions/runs/99"; const api = fakeApi({ [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], + "repos/o/r/pulls/7": { ...pr, auto_merge: { enabled_at: "now" } }, [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, - [validationRunsEndpoint]: { workflow_runs: [{ event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status: "completed", conclusion: "success" }] }, + [validationRunsEndpoint]: { workflow_runs: [{ event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status: "completed", conclusion: "success", html_url: validationUrl }] }, + [`repos/o/r/commits/${remoteSha}/statuses?per_page=100`]: [{ context: "lint", state: "success", target_url: validationUrl, creator: { login: bot } }], }); const calls = []; publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { @@ -248,6 +269,66 @@ test("publisher skips duplicate Validate dispatch for a successfully validated u assert.equal(calls.some((call) => call[1] === "workflow" && call[2] === "run"), false); }); +test("publisher retries Validate when completion did not bridge status and enable auto-merge", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); + const pr = { number: 7, state: "open", user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const validationUrl = "https://github.com/o/r/actions/runs/99"; + const successfulRun = { event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status: "completed", conclusion: "success", html_url: validationUrl }; + const validStatus = { context: "lint", state: "success", target_url: validationUrl, creator: { login: bot } }; + const cases = [ + { autoMerge: null, statuses: [] }, + { autoMerge: { enabled_at: "now" }, statuses: [] }, + { autoMerge: null, statuses: [validStatus] }, + { autoMerge: { enabled_at: "now" }, statuses: [{ ...validStatus, target_url: "https://github.com/o/r/actions/runs/other" }] }, + { autoMerge: { enabled_at: "now" }, statuses: [{ ...validStatus, creator: { login: "human" } }] }, + { autoMerge: { enabled_at: "now" }, statuses: [{ context: "lint", state: "success", creator: { login: bot } }], run: { ...successfulRun, html_url: undefined } }, + ]; + for (const { autoMerge, statuses, run = successfulRun } of cases) { + const api = fakeApi({ + [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], + "repos/o/r/pulls/7": { ...pr, auto_merge: autoMerge }, + [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, + [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, + [validationRunsEndpoint]: { workflow_runs: [run] }, + [`repos/o/r/commits/${remoteSha}/statuses?per_page=100`]: statuses, + }); + const calls = []; + publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? mainSha : tree; + if (args[0] === "status") return " M marketplace.json"; + return ""; + } }); + assert.ok(calls.some((call) => call[1] === "workflow" && call[2] === "run"), "expected a retry when completion effects are missing"); + } +}); + +test("publisher refuses completed validation reuse if the PR head changed during verification", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); + const pr = { number: 7, state: "open", user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const api = fakeApi({ + [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], + "repos/o/r/pulls/7": { ...pr, head: { ...pr.head, sha: sha("a") }, auto_merge: { enabled_at: "now" } }, + [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, + [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, + [validationRunsEndpoint]: { workflow_runs: [{ event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status: "completed", conclusion: "success", html_url: "https://github.com/o/r/actions/runs/99" }] }, + }); + const calls = []; + assert.throws(() => publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? mainSha : tree; + if (args[0] === "status") return " M marketplace.json"; + return ""; + } }), /changed during completion verification/); + assert.equal(calls.some((call) => call[1] === "workflow" && call[2] === "run"), false); +}); + test("publisher avoids duplicate Validate dispatch while the current-head run is active", (t) => { const savedToken = process.env.GH_TOKEN; process.env.GH_TOKEN = "synthetic-token"; diff --git a/.github/workflows/complete-pin-validation.yml b/.github/workflows/complete-pin-validation.yml index a872bad..28eb79c 100644 --- a/.github/workflows/complete-pin-validation.yml +++ b/.github/workflows/complete-pin-validation.yml @@ -8,6 +8,9 @@ permissions: contents: write pull-requests: write statuses: write +concurrency: + group: update-plugin-pin + cancel-in-progress: false jobs: validate: if: github.repository == 'github/plugin-marketplace-starter' && vars.PIN_AUTOMATION == 'true' From 8532f586ededb3173ab8acb4c743025400105cf2 Mon Sep 17 00:00:00 2001 From: Jon Gallant Date: Tue, 24 Nov 2026 18:14:24 -0800 Subject: [PATCH 5/7] fix: harden pin validation completion Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/scripts/pin-validation.mjs | 17 ++- .github/scripts/pin-validation.test.mjs | 45 ++++++- .github/scripts/update-pins.mjs | 34 +++++- .github/scripts/update-pins.test.mjs | 113 +++++++++++++++++- .github/workflows/complete-pin-validation.yml | 2 +- .github/workflows/update-pins.yml | 1 + docs/checks-and-evals.md | 15 ++- 7 files changed, 207 insertions(+), 20 deletions(-) diff --git a/.github/scripts/pin-validation.mjs b/.github/scripts/pin-validation.mjs index 481b16a..073074a 100644 --- a/.github/scripts/pin-validation.mjs +++ b/.github/scripts/pin-validation.mjs @@ -78,19 +78,32 @@ function verifyActionPins(api, files, changedFiles) { const [sha, tag] = candidate.split(" "); if (oldPins.some((old) => compareVersions(tag.slice(1), old.tag.slice(1)) <= 0)) throw new Error("Action tag must advance to a newer stable semantic version."); if (getJson(api, `repos/github/evals-action/commits/${encodeURIComponent(tag)}`).sha !== sha) throw new Error("Action tag does not resolve to the proposed pin."); + const release = getJson(api, `repos/github/evals-action/releases/tags/${encodeURIComponent(tag)}`); + if (release.tag_name !== tag || release.draft !== false || release.prerelease !== false) { + throw new Error("Action pin must target a published stable release."); + } for (const old of oldPins) { if (getJson(api, `repos/github/evals-action/compare/${old.sha}...${sha}`).status !== "ahead") throw new Error("Action pin is not a forward update."); } } +function marketplaceContent(api, endpoint) { + const file = getJson(api, endpoint); + if (file.encoding !== "base64" || typeof file.content !== "string") throw new Error(`${endpoint}: marketplace content is not base64 encoded.`); + const text = Buffer.from(file.content.replace(/\s/g, ""), "base64").toString("utf8"); + const data = JSON.parse(text); + if (`${JSON.stringify(data, null, 2)}\n` !== text) throw new Error("marketplace.json isn't in canonical 2-space JSON format."); + return data; +} + function verifyPluginPin(api, repo, pr, head, files) { if (pr.changed_files !== 1 || files.length !== 1 || files[0].filename !== "marketplace.json" || files[0].status !== "modified") { throw new Error("Plugin pin PR must change only marketplace.json."); } const baseEndpoint = `repos/${repo}/contents/marketplace.json?ref=${pr.base.sha}`; const headEndpoint = `repos/${repo}/contents/marketplace.json?ref=${head}`; - const before = getJson(api, baseEndpoint); - const after = getJson(api, headEndpoint); + const before = marketplaceContent(api, baseEndpoint); + const after = marketplaceContent(api, headEndpoint); const findPin = (data) => { const matches = data.plugins?.filter((plugin) => plugin.name === "eval" && plugin.source?.repo === "github/evals"); if (matches?.length !== 1) throw new Error("marketplace.json must contain exactly one github/evals eval plugin."); diff --git a/.github/scripts/pin-validation.test.mjs b/.github/scripts/pin-validation.test.mjs index bc3ef40..a9cbd8b 100644 --- a/.github/scripts/pin-validation.test.mjs +++ b/.github/scripts/pin-validation.test.mjs @@ -11,8 +11,11 @@ const oldPinSha = "c".repeat(40); const newPinSha = "d".repeat(40); const branch = "dependabot/github_actions/evals-action-a1b2c3d4e5"; const workflowPath = ".github/workflows/validate.yml"; +const actionReleaseEndpoint = "repos/github/evals-action/releases/tags/v0.2.1"; const currentReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.60"; const nextReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.68"; +const contentFile = (text) => ({ encoding: "base64", content: Buffer.from(text).toString("base64") }); +const marketplaceFile = (value) => contentFile(`${JSON.stringify(value, null, 2)}\n`); const actionFile = { filename: ".github/workflows/skill-eval-comparison.yml", status: "modified", @@ -82,13 +85,14 @@ function fixture({ kind = "action", change = {}, failStatus = false } = {}) { [`repos/${repo}/commits/${headSha}`]: commit, [`repos/${repo}/pulls/42/files?per_page=100&page=1`]: isPlugin ? [{ filename: "marketplace.json", status: "modified" }] : [actionFile], "repos/github/evals-action/commits/v0.2.1": { sha: newPinSha }, + [actionReleaseEndpoint]: { tag_name: "v0.2.1", draft: false, prerelease: false }, [`repos/github/evals-action/compare/${oldPinSha}...${newPinSha}`]: { status: "ahead" }, [`repos/github/evals/commits/copilot-evals-v0.24.68`]: { sha: newPinSha }, [currentReleaseEndpoint]: { tag_name: "copilot-evals-v0.24.60", draft: false, prerelease: true }, [nextReleaseEndpoint]: { tag_name: "copilot-evals-v0.24.68", draft: false, prerelease: true }, [`repos/github/evals/compare/${oldPinSha}...${newPinSha}`]: { status: "ahead" }, - [`repos/${repo}/contents/marketplace.json?ref=${baseSha}`]: beforeMarketplace, - [`repos/${repo}/contents/marketplace.json?ref=${headSha}`]: afterMarketplace, + [`repos/${repo}/contents/marketplace.json?ref=${baseSha}`]: marketplaceFile(beforeMarketplace), + [`repos/${repo}/contents/marketplace.json?ref=${headSha}`]: marketplaceFile(afterMarketplace), }; const calls = []; const api = (path) => { @@ -100,12 +104,14 @@ function fixture({ kind = "action", change = {}, failStatus = false } = {}) { if (path === `repos/${repo}/actions/runs/99/jobs?per_page=100&page=1` && change.jobs) data = change.jobs; if (path === `repos/${repo}/commits/${headSha}` && change.commit) data = change.commit; if (path === `repos/${repo}/pulls/42/files?per_page=100&page=1` && change.files) data = change.files; + if (path === actionReleaseEndpoint && change.actionRelease) data = change.actionRelease; if (path === currentReleaseEndpoint && change.currentRelease) data = change.currentRelease; if (path === nextReleaseEndpoint && change.nextRelease) data = change.nextRelease; if (path === change.releaseFailure?.endpoint) return { status: change.releaseFailure.status, body: "{}" }; if (path === "repos/github/evals-action/compare/" + oldPinSha + "..." + newPinSha && change.comparison) data = change.comparison; if (path === "repos/github/evals-action/commits/v0.2.1" && change.resolved) data = { sha: change.resolved }; - if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplace) data = change.marketplace; + if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplace) data = marketplaceFile(change.marketplace); + if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplaceText) data = contentFile(change.marketplaceText); if (data === undefined) return { status: 404, body: "{}" }; return { status: 200, body: JSON.stringify(data) }; }; @@ -240,6 +246,20 @@ test("rejects action pin replacements that move step settings", () => { assert.deepEqual(f.calls, []); }); +test("rejects missing, draft, or prerelease action releases", () => { + const invalidCases = [ + { actionRelease: { tag_name: "v0.2.1", draft: true, prerelease: false } }, + { actionRelease: { tag_name: "v0.2.1", draft: false, prerelease: true } }, + { actionRelease: { tag_name: "v0.2.0", draft: false, prerelease: false } }, + { releaseFailure: { endpoint: actionReleaseEndpoint, status: 404 } }, + ]; + for (const change of invalidCases) { + const f = fixture({ change }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f }), /release|HTTP 404/i); + assert.deepEqual(f.calls, []); + } +}); + test("rejects plugin PRs that alter anything beyond the verified forward pin", () => { const badMarketplace = structuredClone(afterMarketplace); badMarketplace.plugins[0].description = "unexpected"; @@ -262,6 +282,19 @@ test("rejects plugin PRs that alter anything beyond the verified forward pin", ( } }); +test("rejects noncanonical marketplace JSON with duplicate properties", () => { + const canonical = `${JSON.stringify(afterMarketplace, null, 2)}\n`; + const duplicate = canonical.replace( + ' "version": "0.24.68"\n', + ' "version": "0.24.68",\n "version": "0.24.68"\n', + ); + assert.notEqual(duplicate, canonical); + assert.deepEqual(JSON.parse(duplicate), afterMarketplace); + const f = fixture({ kind: "plugin", change: { marketplaceText: duplicate } }); + assert.throws(() => completePinValidation({ repo, runId: 99, ...f }), /canonical/i); + assert.deepEqual(f.calls, []); +}); + test("stops if status publication fails and does not enqueue a merge", () => { const f = fixture({ kind: "plugin", failStatus: true }); assert.throws(() => completePinValidation({ repo, runId: 99, ...f }), /status write denied/); @@ -273,8 +306,10 @@ test("workflow runs trusted default-branch code with scoped permissions", () => const publisher = parse(readFileSync(new URL("../workflows/update-pins.yml", import.meta.url), "utf8")); assert.deepEqual(workflow.on.workflow_run, { workflows: ["Validate"], types: ["completed"] }); assert.deepEqual(workflow.permissions, { actions: "read", contents: "write", "pull-requests": "write", statuses: "write" }); - assert.deepEqual(workflow.concurrency, publisher.concurrency); - assert.deepEqual(workflow.concurrency, { group: "update-plugin-pin", "cancel-in-progress": false }); + assert.match(workflow.concurrency.group, /github\.event\.workflow_run\.head_branch == 'automation\/update-plugin-pin'/); + assert.match(workflow.concurrency.group, /format\('complete-pin-validation-\{0\}', github\.event\.workflow_run\.id\)/); + assert.equal(workflow.concurrency["cancel-in-progress"], false); + assert.deepEqual(publisher.concurrency, { group: "update-plugin-pin", "cancel-in-progress": false }); assert.equal(workflow.on.pull_request_target, undefined); assert.match(workflow.jobs.validate.if, /github\.repository == 'github\/plugin-marketplace-starter'/); assert.match(workflow.jobs.validate.if, /vars\.PIN_AUTOMATION == 'true'/); diff --git a/.github/scripts/update-pins.mjs b/.github/scripts/update-pins.mjs index 4988e19..aa63eaf 100644 --- a/.github/scripts/update-pins.mjs +++ b/.github/scripts/update-pins.mjs @@ -106,6 +106,21 @@ function openPr(api, repo) { return pr; } +function reconcileOpenPr(api, repo, execute, { blocked, dryRun }) { + if (dryRun) return; + const pr = openPr(api, repo); + if (!pr) return; + const endpoint = `repos/${repo}/pulls/${pr.number}`; + const current = getJson(api, endpoint); + if (current.state !== "open" || current.head?.sha !== pr.head?.sha) throw new Error(`Open PR #${pr.number} changed during pin-plan reconciliation.`); + if (current.auto_merge) execute("gh", ["pr", "merge", String(pr.number), "-R", repo, "--disable-auto"]); + if (blocked) return `Disabled auto-merge for plugin pin PR #${pr.number} because the release plan is blocked.`; + const beforeClose = getJson(api, endpoint); + if (beforeClose.state !== "open" || beforeClose.head?.sha !== pr.head?.sha) throw new Error(`Open PR #${pr.number} changed before stale pin-plan cleanup.`); + execute("gh", ["pr", "close", String(pr.number), "-R", repo, "--comment", "Closing obsolete plugin pin PR because the current release plan has no update."]); + return `Closed obsolete plugin pin PR #${pr.number}.`; +} + function remoteBranch(api, repo, main) { const response = api(`repos/${repo}/branches/${encodeURIComponent(BRANCH)}`); if (response.status === 404) return undefined; @@ -119,12 +134,17 @@ function remoteBranch(api, repo, main) { function currentValidationRun(api, repo, head) { const result = getJson(api, `repos/${repo}/actions/workflows/validate.yml/runs?branch=${encodeURIComponent(BRANCH)}&event=workflow_dispatch&per_page=100`); if (!Array.isArray(result.workflow_runs)) throw new Error("Validate workflow-runs response is not an array."); - return result.workflow_runs.find((run) => + const matching = result.workflow_runs.filter((run) => run.event === "workflow_dispatch" && run.head_branch === BRANCH && - run.head_sha === head && - (["queued", "in_progress", "waiting"].includes(run.status) || (run.status === "completed" && run.conclusion === "success")), + run.head_sha === head, ); + if (matching.length < 2) return matching[0]; + const timestamps = matching.map((run) => Date.parse(run.created_at ?? "")); + if (timestamps.some((timestamp) => !Number.isFinite(timestamp))) throw new Error("Matching Validate runs are missing valid creation timestamps."); + return matching + .map((run, index) => ({ run, timestamp: timestamps[index] })) + .sort((a, b) => b.timestamp - a.timestamp || Number(b.run.run_number ?? b.run.id) - Number(a.run.run_number ?? a.run.id))[0].run; } function completionHasTakenEffect(api, repo, pr, head, validation) { @@ -185,7 +205,7 @@ function output(values) { console.log(lines.join("\n")); } -export function main(argv, api = githubApi) { +export function main(argv, api = githubApi, execute = run) { const [command, ...rest] = argv; const args = {}; for (let index = 0; index < rest.length; index += 2) args[rest[index].replace(/^--/, "")] = rest[index + 1]; @@ -194,15 +214,19 @@ export function main(argv, api = githubApi) { if (command === "update") { const text = readFileSync("marketplace.json", "utf8"); const plan = planUpdate({ text, api }); + const dryRun = process.env.PIN_AUTOMATION_DRY_RUN === "true"; if (plan.blocked) { output({ blocked: true, reason: plan.blocked.replace(/[\r\n]+/g, " ") }); if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `### Pin update blocked\n\n${plan.blocked}\n`); + const reconciliation = reconcileOpenPr(api, repo, execute, { blocked: true, dryRun }); + if (reconciliation) console.log(reconciliation); throw new Error(`Pin update blocked: ${plan.blocked}`); } if (plan.text !== text) writeFileSync("marketplace.json", plan.text); + const reconciliation = plan.changes.length ? undefined : reconcileOpenPr(api, repo, execute, { blocked: false, dryRun }); if (args["body-file"]) writeFileSync(args["body-file"], plan.body); output({ blocked: false, changed: plan.changes.length > 0, title: plan.title }); - if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, plan.changes.length ? `### Pin update\n\n${plan.body}` : "### Pin update\n\nPin is current.\n"); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, plan.changes.length ? `### Pin update\n\n${plan.body}` : `### Pin update\n\nPin is current.${reconciliation ? ` ${reconciliation}` : ""}\n`); } else if (command === "publish") { console.log(publish(api, repo, { title: args.title, bodyFile: args["body-file"] })); } else { diff --git a/.github/scripts/update-pins.test.mjs b/.github/scripts/update-pins.test.mjs index 25efde6..86850c8 100644 --- a/.github/scripts/update-pins.test.mjs +++ b/.github/scripts/update-pins.test.mjs @@ -119,7 +119,9 @@ test("blocked update reports its reason without modifying the marketplace", (t) process.env.GITHUB_OUTPUT = join(directory, "output"); process.env.GITHUB_STEP_SUMMARY = join(directory, "summary"); writeFileSync("marketplace.json", marketplace); - for (const [api, reason] of [[fakeApi({ "repos/github/evals/releases?per_page=100&page=1": [] }), /channel is unknown/], [() => ({ status: 403, body: "{}" }), /HTTP 403/], [upstream("diverged"), /diverged/]]) { + const noPrEndpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + for (const [sourceApi, reason] of [[fakeApi({ "repos/github/evals/releases?per_page=100&page=1": [] }), /channel is unknown/], [() => ({ status: 403, body: "{}" }), /HTTP 403/], [upstream("diverged"), /diverged/]]) { + const api = (endpoint) => endpoint === noPrEndpoint ? { status: 200, body: "[]" } : sourceApi(endpoint); assert.throws(() => main(["update"], api), reason); assert.match(readFileSync(process.env.GITHUB_OUTPUT, "utf8"), /blocked=true/); assert.match(readFileSync(process.env.GITHUB_OUTPUT, "utf8"), reason); @@ -306,6 +308,34 @@ test("publisher retries Validate when completion did not bridge status and enabl } }); +test("publisher selects the newest matching Validate run before inspecting its status", (t) => { + const savedToken = process.env.GH_TOKEN; + process.env.GH_TOKEN = "synthetic-token"; + t.after(() => { if (savedToken === undefined) delete process.env.GH_TOKEN; else process.env.GH_TOKEN = savedToken; }); + const mainSha = sha("3"), remoteSha = sha("4"), tree = sha("5"); + const pr = { number: 7, state: "open", user: { login: bot, type: "Bot" }, head: { sha: remoteSha, repo: { full_name: "o/r" } }, base: { ref: "main", repo: { default_branch: "main" } } }; + const validationUrl = "https://github.com/o/r/actions/runs/99"; + const api = fakeApi({ + [`repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`]: [pr], + "repos/o/r/pulls/7": { ...pr, auto_merge: { enabled_at: "now" } }, + [`repos/o/r/branches/${encodeURIComponent(BRANCH)}`]: { commit: { sha: remoteSha, commit: { tree: { sha: tree } }, parents: [{ sha: mainSha }] } }, + [`repos/o/r/compare/${mainSha}...${remoteSha}`]: { ahead_by: 1, behind_by: 0, commits: [{ author: { login: bot }, committer: { login: bot } }] }, + [validationRunsEndpoint]: { workflow_runs: [ + { event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status: "completed", conclusion: "failure", html_url: "https://github.com/o/r/actions/runs/100", created_at: "2026-02-02T00:00:00Z" }, + { event: "workflow_dispatch", head_branch: BRANCH, head_sha: remoteSha, status: "completed", conclusion: "success", html_url: validationUrl, created_at: "2026-02-01T00:00:00Z" }, + ] }, + [`repos/o/r/commits/${remoteSha}/statuses?per_page=100`]: [{ context: "lint", state: "success", target_url: validationUrl, creator: { login: bot } }], + }); + const calls = []; + publish(api, "o/r", { title: "update", bodyFile: "body", execute: (command, args) => { + calls.push([command, ...args]); + if (args[0] === "rev-parse") return args[1] === "HEAD" ? mainSha : tree; + if (args[0] === "status") return " M marketplace.json"; + return ""; + } }); + assert.ok(calls.some((call) => call[1] === "workflow" && call[2] === "run"), "a newer failed run must not be masked by an older successful run"); +}); + test("publisher refuses completed validation reuse if the PR head changed during verification", (t) => { const savedToken = process.env.GH_TOKEN; process.env.GH_TOKEN = "synthetic-token"; @@ -374,6 +404,85 @@ test("publication refuses duplicate automation PRs", (t) => { }), /More than one open PR/); }); +test("plan reconciles existing plugin PRs unless workflow_dispatch is a dry run", (t) => { + const directory = mkdtempSync(join(tmpdir(), "pin-test-")); + const previous = process.cwd(); + const env = ["GITHUB_REPOSITORY", "GITHUB_OUTPUT", "GITHUB_STEP_SUMMARY", "PIN_AUTOMATION_DRY_RUN"]; + const saved = Object.fromEntries(env.map((key) => [key, process.env[key]])); + t.after(() => { + process.chdir(previous); + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } + rmSync(directory, { recursive: true, force: true }); + }); + process.chdir(directory); + process.env.GITHUB_REPOSITORY = "o/r"; + process.env.GITHUB_OUTPUT = join(directory, "output"); + process.env.GITHUB_STEP_SUMMARY = join(directory, "summary"); + const prListEndpoint = `repos/o/r/pulls?state=open&head=o:${encodeURIComponent(BRANCH)}`; + const pr = { + number: 7, + state: "open", + user: { login: bot, type: "Bot" }, + head: { ref: BRANCH, sha: sha("2"), repo: { full_name: "o/r" } }, + base: { ref: "main", repo: { full_name: "o/r", default_branch: "main" } }, + }; + const currentPr = { ...pr, auto_merge: { enabled_at: "now" } }; + const releasesEndpoint = "repos/github/evals/releases?per_page=100&page=1"; + const runScenario = ({ blocked = false, dryRun = false, headChange } = {}) => { + writeFileSync("marketplace.json", marketplace); + writeFileSync(process.env.GITHUB_OUTPUT, ""); + writeFileSync(process.env.GITHUB_STEP_SUMMARY, ""); + process.env.PIN_AUTOMATION_DRY_RUN = String(dryRun); + const calls = []; + const requests = []; + let prReads = 0; + const api = (endpoint) => { + requests.push(endpoint); + if (endpoint === releasesEndpoint) { + return blocked ? { status: 503, body: "{}" } : { status: 200, body: JSON.stringify([release("copilot-evals-v0.24.60")]) }; + } + if (endpoint === prListEndpoint) return { status: 200, body: JSON.stringify([pr]) }; + if (endpoint === "repos/o/r/pulls/7") { + prReads += 1; + const changed = headChange === "before-disable" || (headChange === "before-close" && prReads > 1); + const value = changed ? { ...currentPr, head: { ...currentPr.head, sha: sha("a") } } : currentPr; + return { status: 200, body: JSON.stringify(value) }; + } + return { status: 404, body: "{}" }; + }; + const execute = (command, args) => { calls.push([command, ...args]); return ""; }; + if (headChange === "before-disable") assert.throws(() => main(["update"], api, execute), /changed during pin-plan reconciliation/); + else if (headChange === "before-close") assert.throws(() => main(["update"], api, execute), /changed before stale pin-plan cleanup/); + else if (blocked) assert.throws(() => main(["update"], api, execute), /Pin update blocked/); + else main(["update"], api, execute); + return { calls, requests, output: readFileSync(process.env.GITHUB_OUTPUT, "utf8") }; + }; + + const unchanged = runScenario(); + assert.ok(unchanged.requests.includes(prListEndpoint)); + assert.ok(unchanged.calls.some((call) => call[1] === "pr" && call[2] === "merge" && call.at(-1) === "--disable-auto")); + assert.ok(unchanged.calls.some((call) => call[1] === "pr" && call[2] === "close")); + + const blocked = runScenario({ blocked: true }); + assert.match(blocked.output, /blocked=true/); + assert.ok(blocked.requests.includes(prListEndpoint)); + assert.ok(blocked.calls.some((call) => call[1] === "pr" && call[2] === "merge" && call.at(-1) === "--disable-auto")); + assert.equal(blocked.calls.some((call) => call[1] === "pr" && call[2] === "close"), false); + + const changedBeforeDisable = runScenario({ headChange: "before-disable" }); + assert.deepEqual(changedBeforeDisable.calls, []); + const changedBeforeClose = runScenario({ headChange: "before-close" }); + assert.ok(changedBeforeClose.calls.some((call) => call[1] === "pr" && call[2] === "merge" && call.at(-1) === "--disable-auto")); + assert.equal(changedBeforeClose.calls.some((call) => call[1] === "pr" && call[2] === "close"), false); + + const dryRun = runScenario({ dryRun: true }); + assert.match(dryRun.output, /changed=false/); + assert.equal(dryRun.requests.includes(prListEndpoint), false); + assert.deepEqual(dryRun.calls, []); +}); + test("publisher rejects missing credentials and does not continue after an upstream API denial", (t) => { const savedToken = process.env.GH_TOKEN; delete process.env.GH_TOKEN; @@ -454,6 +563,8 @@ test("workflow is canonical-only, keyless, and dry-run by default", () => { assert.equal(allowed("github/plugin-marketplace-starter", "schedule", "false"), false); assert.equal(allowed("github/plugin-marketplace-starter", "workflow_dispatch", "false"), true); assert.equal(allowed("other/template", "workflow_dispatch", "true"), false); + const planStep = workflow.jobs.update.steps.find((step) => step.id === "plan"); + assert.equal(planStep.env.PIN_AUTOMATION_DRY_RUN, "${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }}"); const text = JSON.stringify(workflow); assert.doesNotMatch(text, /secrets\.|create-github-app-token|environment|enqueue/); assert.match(text, /inputs\.dry_run/); diff --git a/.github/workflows/complete-pin-validation.yml b/.github/workflows/complete-pin-validation.yml index 28eb79c..eb20515 100644 --- a/.github/workflows/complete-pin-validation.yml +++ b/.github/workflows/complete-pin-validation.yml @@ -9,7 +9,7 @@ permissions: pull-requests: write statuses: write concurrency: - group: update-plugin-pin + group: ${{ github.event.workflow_run.head_branch == 'automation/update-plugin-pin' && 'update-plugin-pin' || format('complete-pin-validation-{0}', github.event.workflow_run.id) }} cancel-in-progress: false jobs: validate: diff --git a/.github/workflows/update-pins.yml b/.github/workflows/update-pins.yml index e735cdc..8add114 100644 --- a/.github/workflows/update-pins.yml +++ b/.github/workflows/update-pins.yml @@ -33,6 +33,7 @@ jobs: - id: plan env: GH_TOKEN: ${{ github.token }} + PIN_AUTOMATION_DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} run: node .github/scripts/update-pins.mjs update --body-file "$RUNNER_TEMP/pin-pr.md" - if: steps.plan.outputs.changed == 'true' && !(github.event_name == 'workflow_dispatch' && inputs.dry_run) env: diff --git a/docs/checks-and-evals.md b/docs/checks-and-evals.md index 8747f97..c3209ba 100644 --- a/docs/checks-and-evals.md +++ b/docs/checks-and-evals.md @@ -78,8 +78,10 @@ separate [Complete pin validation](../.github/workflows/complete-pin-validation. workflow runs trusted code from the default branch after Validate completes. It confirms the exact successful workflow run and PR head, publishes the required `lint` commit status from GitHub Actions for that SHA, and enables squash -auto-merge. GitHub still requires the checks and one human CodeOwner approval -before merging. +auto-merge. A blocked plan disables auto-merge on an existing plugin-pin PR; an +empty plan disables auto-merge and closes the obsolete PR. Manual dry runs do +not reconcile existing PRs. GitHub still requires the checks and one human +CodeOwner approval before merging. [Dependabot](../.github/dependabot.yml) separately proposes daily grouped updates for `github/evals-action` references in workflow files. Dependabot's @@ -87,10 +89,11 @@ handling of prerelease tags has not been verified live. Each PR still requires one human CodeOwner approval and required checks. The same trusted default-branch completion workflow verifies the successful Validate run, Dependabot author, base and exact head, action-only file changes, release tag, -strictly increasing stable version, and forward commit ancestry before enabling -auto-merge. It never checks out or executes PR-head code and does not approve the -PR. Non-stable action tags are not auto-enabled; Dependabot's prerelease-tag -representation has not been verified live. +that the tag resolves to a published stable release, strictly increasing +version, and forward commit ancestry before enabling auto-merge. It never checks +out or executes PR-head code and does not approve the PR. Non-stable action tags +are not auto-enabled; Dependabot's prerelease-tag representation has not been +verified live. The embedded workflow example later on this page contains three `github/evals-action` pins. The workflow files are authoritative for current From c2d24d22a103e08dac0c5027c9576f284d0df419 Mon Sep 17 00:00:00 2001 From: Jon Gallant Date: Tue, 24 Nov 2026 19:54:56 -0800 Subject: [PATCH 6/7] Gate pin PRs before lint succeeds Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/scripts/pin-validation.mjs | 75 ++++++++++++++---- .github/scripts/pin-validation.test.mjs | 101 ++++++++++++++++++++++-- .github/workflows/validate.yml | 34 ++++++++ docs/checks-and-evals.md | 5 +- 4 files changed, 192 insertions(+), 23 deletions(-) diff --git a/.github/scripts/pin-validation.mjs b/.github/scripts/pin-validation.mjs index 073074a..a7677b4 100644 --- a/.github/scripts/pin-validation.mjs +++ b/.github/scripts/pin-validation.mjs @@ -88,9 +88,10 @@ function verifyActionPins(api, files, changedFiles) { } function marketplaceContent(api, endpoint) { - const file = getJson(api, endpoint); - if (file.encoding !== "base64" || typeof file.content !== "string") throw new Error(`${endpoint}: marketplace content is not base64 encoded.`); - const text = Buffer.from(file.content.replace(/\s/g, ""), "base64").toString("utf8"); + const response = api(endpoint); + if (response.status !== 200) throw new Error(`${endpoint}: GitHub API returned HTTP ${response.status}.`); + if (typeof response.body !== "string") throw new Error(`${endpoint}: marketplace content isn't text.`); + const text = response.body; const data = JSON.parse(text); if (`${JSON.stringify(data, null, 2)}\n` !== text) throw new Error("marketplace.json isn't in canonical 2-space JSON format."); return data; @@ -147,6 +148,48 @@ function getPullRequest(api, repo, branch) { return matches.length ? getJson(api, `repos/${repo}/pulls/${matches[0].number}`) : undefined; } +function verifyPinPr(api, repo, pr, headBranch, headSha, kind, defaultBranch) { + const author = kind === "plugin" ? "github-actions[bot]" : "dependabot[bot]"; + if (!validPr(pr, repo, defaultBranch, author)) throw new Error("Pin PR isn't open from the expected automation identity and base."); + if (pr.head?.ref !== headBranch || pr.head?.sha !== headSha) throw new Error("Pin PR head doesn't match the inspected head."); + const commit = getJson(api, `repos/${repo}/commits/${headSha}`); + const expectedCommitter = commit.committer?.login === author || + (kind === "action" && commit.committer?.login === "web-flow" && commit.commit?.verification?.verified === true); + if (commit.author?.login !== author || !expectedCommitter) { + throw new Error("PR head commit was not authored and committed by the expected verified automation identity."); + } + const endpoint = `repos/${repo}/pulls/${pr.number}`; + const files = getJson(api, `${endpoint}/files?per_page=100&page=1`); + if (kind === "plugin") verifyPluginPin(api, repo, pr, headSha, files); + else verifyActionPins(api, files, pr.changed_files); + const current = getJson(api, endpoint); + if (!validPr(current, repo, defaultBranch, author) || current.head?.sha !== headSha || current.head?.ref !== headBranch) { + throw new Error("PR head changed during inspection."); + } + return current; +} + +export function verifyCurrentPinPr({ api = githubApi, repo, event, prNumber, branch, headSha }) { + if (repo !== canonical) throw new Error("Invalid repository."); + let kind, pr; + if (event === "pull_request" && branch?.startsWith("dependabot/github_actions/evals-action-")) { + if (!actionBranch.test(branch)) throw new Error("Unexpected Dependabot action-pin branch."); + if (!/^\d+$/.test(String(prNumber ?? ""))) throw new Error("Invalid pull request number."); + kind = "action"; + pr = getJson(api, `repos/${repo}/pulls/${prNumber}`); + } else if (event === "workflow_dispatch" && branch === pluginBranch) { + kind = "plugin"; + pr = getPullRequest(api, repo, branch); + } else { + return "Skipped a Validate run unrelated to pin automation."; + } + if (!/^[0-9a-f]{40}$/.test(headSha ?? "")) throw new Error("Invalid pin PR head SHA."); + if (!pr) throw new Error("No open pin PR exists for the validated head."); + const defaultBranch = getJson(api, `repos/${repo}`).default_branch; + verifyPinPr(api, repo, pr, branch, headSha, kind, defaultBranch); + return `Validated ${kind} pin PR #${pr.number} at ${headSha}.`; +} + export function completePinValidation({ api = githubApi, repo, runId, execute = run }) { if (repo !== canonical || !/^\d+$/.test(String(runId ?? ""))) throw new Error("Invalid repository or workflow run ID."); const workflow = getJson(api, `repos/${repo}/actions/workflows/validate.yml`); @@ -173,19 +216,8 @@ export function completePinValidation({ api = githubApi, repo, runId, execute = const pr = getPullRequest(api, repo, runData.head_branch); if (!pr || !validPr(pr, repo, defaultBranch, author)) return "Skipped because no matching open automation PR exists."; if (pr.head?.ref !== runData.head_branch || pr.head?.sha !== runData.head_sha) return "Skipped a stale Validate run for an older PR head."; - const commit = getJson(api, `repos/${repo}/commits/${runData.head_sha}`); - const expectedCommitter = commit.committer?.login === author || - (kind === "action" && commit.committer?.login === "web-flow" && commit.commit?.verification?.verified === true); - if (commit.author?.login !== author || !expectedCommitter) { - throw new Error("PR head commit was not authored and committed by the expected verified automation identity."); - } - const number = pr.number; - const endpoint = `repos/${repo}/pulls/${number}`; - const files = getJson(api, `${endpoint}/files?per_page=100&page=1`); - if (kind === "plugin") verifyPluginPin(api, repo, pr, runData.head_sha, files); - else verifyActionPins(api, files, pr.changed_files); - const current = getJson(api, endpoint); - if (!validPr(current, repo, defaultBranch, author) || current.head?.sha !== runData.head_sha || current.head?.ref !== runData.head_branch) throw new Error("PR head changed during inspection."); + const current = verifyPinPr(api, repo, pr, runData.head_branch, runData.head_sha, kind, defaultBranch); + const number = current.number; if (kind === "plugin") { execute("gh", [ "api", "--method", "POST", `repos/${repo}/statuses/${runData.head_sha}`, @@ -204,7 +236,16 @@ function run(command, args) { if (process.argv[1] && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(resolve(process.argv[1]))) { try { - console.log(completePinValidation({ repo: process.env.GITHUB_REPOSITORY, runId: process.env.WORKFLOW_RUN_ID })); + const result = process.argv[2] === "verify-current-pr" + ? verifyCurrentPinPr({ + repo: process.env.GITHUB_REPOSITORY, + event: process.env.PIN_VALIDATION_EVENT, + prNumber: process.env.PIN_PR_NUMBER, + branch: process.env.PIN_PR_BRANCH, + headSha: process.env.PIN_PR_HEAD_SHA, + }) + : completePinValidation({ repo: process.env.GITHUB_REPOSITORY, runId: process.env.WORKFLOW_RUN_ID }); + console.log(result); } catch (error) { console.error(`::error::${error.message}`); process.exitCode = 1; diff --git a/.github/scripts/pin-validation.test.mjs b/.github/scripts/pin-validation.test.mjs index a9cbd8b..4d96697 100644 --- a/.github/scripts/pin-validation.test.mjs +++ b/.github/scripts/pin-validation.test.mjs @@ -2,7 +2,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { parse } from "yaml"; -import { completePinValidation } from "./pin-validation.mjs"; +import { completePinValidation, verifyCurrentPinPr } from "./pin-validation.mjs"; const repo = "github/plugin-marketplace-starter"; const baseSha = "a".repeat(40); @@ -14,8 +14,7 @@ const workflowPath = ".github/workflows/validate.yml"; const actionReleaseEndpoint = "repos/github/evals-action/releases/tags/v0.2.1"; const currentReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.60"; const nextReleaseEndpoint = "repos/github/evals/releases/tags/copilot-evals-v0.24.68"; -const contentFile = (text) => ({ encoding: "base64", content: Buffer.from(text).toString("base64") }); -const marketplaceFile = (value) => contentFile(`${JSON.stringify(value, null, 2)}\n`); +const marketplaceFile = (value) => `${JSON.stringify(value, null, 2)}\n`; const actionFile = { filename: ".github/workflows/skill-eval-comparison.yml", status: "modified", @@ -111,9 +110,12 @@ function fixture({ kind = "action", change = {}, failStatus = false } = {}) { if (path === "repos/github/evals-action/compare/" + oldPinSha + "..." + newPinSha && change.comparison) data = change.comparison; if (path === "repos/github/evals-action/commits/v0.2.1" && change.resolved) data = { sha: change.resolved }; if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplace) data = marketplaceFile(change.marketplace); - if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplaceText) data = contentFile(change.marketplaceText); + if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplaceText) data = change.marketplaceText; + if (path === `repos/${repo}/contents/marketplace.json?ref=${headSha}` && change.marketplaceFailure) { + return { status: change.marketplaceFailure, body: "unavailable" }; + } if (data === undefined) return { status: 404, body: "{}" }; - return { status: 200, body: JSON.stringify(data) }; + return { status: 200, body: typeof data === "string" ? data : JSON.stringify(data) }; }; const execute = (command, args) => { calls.push([command, ...args]); @@ -129,6 +131,83 @@ test("enables Dependabot auto-merge only after successful Validate and forward a assert.deepEqual(f.calls, [["gh", "pr", "merge", "42", "-R", repo, "--auto", "--squash", "--match-head-commit", headSha]]); }); +test("Validate verifies current action and plugin heads before the required lint job can pass", () => { + const action = fixture(); + assert.match(verifyCurrentPinPr({ + repo, + event: "pull_request", + prNumber: 42, + branch, + headSha, + ...action, + }), /Validated action pin PR #42/); + assert.deepEqual(action.calls, []); + + const plugin = fixture({ kind: "plugin" }); + assert.match(verifyCurrentPinPr({ + repo, + event: "workflow_dispatch", + branch: "automation/update-plugin-pin", + headSha, + ...plugin, + }), /Validated plugin pin PR #42/); + assert.deepEqual(plugin.calls, []); + + const unavailable = fixture({ kind: "plugin", change: { marketplaceFailure: 503 } }); + assert.throws(() => verifyCurrentPinPr({ + repo, + event: "workflow_dispatch", + branch: "automation/update-plugin-pin", + headSha, + ...unavailable, + }), /HTTP 503/); + assert.deepEqual(unavailable.calls, []); +}); + +test("read-only pin validation rejects stale, malformed, or untrusted PR inputs", () => { + const stale = fixture({ change: { staleHead: true } }); + assert.throws(() => verifyCurrentPinPr({ + repo, + event: "pull_request", + prNumber: 42, + branch, + headSha, + ...stale, + }), /head doesn't match/); + assert.deepEqual(stale.calls, []); + + const untrusted = fixture({ change: { pr: { + ...JSON.parse(fixture().api(`repos/${repo}/pulls/42`).body), + user: { login: "someone", type: "User" }, + } } }); + assert.throws(() => verifyCurrentPinPr({ + repo, + event: "pull_request", + prNumber: 42, + branch, + headSha, + ...untrusted, + }), /expected automation identity/); + assert.deepEqual(untrusted.calls, []); + + assert.throws(() => verifyCurrentPinPr({ + repo, + event: "pull_request", + prNumber: 42, + branch: "dependabot/github_actions/evals-action-a1b2c3d4e", + headSha, + ...fixture(), + }), /Unexpected Dependabot action-pin branch/); + assert.match(verifyCurrentPinPr({ + repo, + event: "pull_request", + prNumber: 42, + branch: "dependabot/github_actions/setup-node-1a2b3c4d5e", + headSha, + ...fixture(), + }), /Skipped/); +}); + test("revalidates both plugin releases and their channel before enabling auto-merge", () => { const invalidCases = [ { currentRelease: { tag_name: "copilot-evals-v0.24.60", draft: true, prerelease: true } }, @@ -304,6 +383,7 @@ test("stops if status publication fails and does not enqueue a merge", () => { test("workflow runs trusted default-branch code with scoped permissions", () => { const workflow = parse(readFileSync(new URL("../workflows/complete-pin-validation.yml", import.meta.url), "utf8")); const publisher = parse(readFileSync(new URL("../workflows/update-pins.yml", import.meta.url), "utf8")); + const validate = parse(readFileSync(new URL("../workflows/validate.yml", import.meta.url), "utf8")); assert.deepEqual(workflow.on.workflow_run, { workflows: ["Validate"], types: ["completed"] }); assert.deepEqual(workflow.permissions, { actions: "read", contents: "write", "pull-requests": "write", statuses: "write" }); assert.match(workflow.concurrency.group, /github\.event\.workflow_run\.head_branch == 'automation\/update-plugin-pin'/); @@ -317,4 +397,15 @@ test("workflow runs trusted default-branch code with scoped permissions", () => assert.equal(checkout.with.ref, "${{ github.event.repository.default_branch }}"); assert.equal(checkout.with["persist-credentials"], false); assert.equal(workflow.jobs.validate.steps.at(-1).run, "node .github/scripts/pin-validation.mjs"); + + const pinJob = validate.jobs["validate-pin"]; + assert.match(pinJob.if, /github\.repository == 'github\/plugin-marketplace-starter'/); + assert.deepEqual(pinJob.permissions, { contents: "read", "pull-requests": "read" }); + const pinCheckout = pinJob.steps.find((step) => step.uses?.startsWith("actions/checkout@")); + assert.equal(pinCheckout.with.ref, "${{ github.event.repository.default_branch }}"); + assert.equal(pinCheckout.with["persist-credentials"], false); + assert.equal(pinJob.steps.at(-1).run, "node .github/scripts/pin-validation.mjs verify-current-pr"); + assert.equal(validate.jobs.lint.needs, "validate-pin"); + assert.equal(validate.jobs.lint.if, "always()"); + assert.match(validate.jobs.lint.steps[0].if, /needs\.validate-pin\.result/); }); diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index daf22de..0a37862 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -13,10 +13,44 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: + validate-pin: + if: >- + github.repository == 'github/plugin-marketplace-starter' && + ( + (github.event_name == 'pull_request' && startsWith(github.head_ref, 'dependabot/github_actions/evals-action-')) || + (github.event_name == 'workflow_dispatch' && github.ref_name == 'automation/update-plugin-pin') + ) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24 + - name: Validate exact pin PR head + env: + GH_TOKEN: ${{ github.token }} + GITHUB_REPOSITORY: ${{ github.repository }} + PIN_VALIDATION_EVENT: ${{ github.event_name }} + PIN_PR_NUMBER: ${{ github.event.pull_request.number }} + PIN_PR_BRANCH: ${{ github.event_name == 'pull_request' && github.head_ref || github.ref_name }} + PIN_PR_HEAD_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + run: node .github/scripts/pin-validation.mjs verify-current-pr lint: + needs: validate-pin + if: always() runs-on: ubuntu-latest timeout-minutes: 15 steps: + - name: Require pin validation + if: needs.validate-pin.result != 'success' && needs.validate-pin.result != 'skipped' + run: exit 1 - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false diff --git a/docs/checks-and-evals.md b/docs/checks-and-evals.md index c3209ba..4fed961 100644 --- a/docs/checks-and-evals.md +++ b/docs/checks-and-evals.md @@ -81,7 +81,10 @@ confirms the exact successful workflow run and PR head, publishes the required auto-merge. A blocked plan disables auto-merge on an existing plugin-pin PR; an empty plan disables auto-merge and closes the obsolete PR. Manual dry runs do not reconcile existing PRs. GitHub still requires the checks and one human -CodeOwner approval before merging. +CodeOwner approval before merging. Validate's required `lint` check waits for a +trusted, read-only pin-validation job that rechecks the exact plugin or +Dependabot head, release, and forward ancestry. This prevents a previously +enabled auto-merge request from merging a new head before its pin is verified. [Dependabot](../.github/dependabot.yml) separately proposes daily grouped updates for `github/evals-action` references in workflow files. Dependabot's From f349ec6ea255700eae7a36d9167c939ed832863f Mon Sep 17 00:00:00 2001 From: Jon Gallant Date: Wed, 25 Nov 2026 07:06:03 -0800 Subject: [PATCH 7/7] Fix prerelease pin validation gate Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/scripts/pin-validation.mjs | 22 ++++++++---- .github/scripts/pin-validation.test.mjs | 36 +++++++++++++++++-- .github/workflows/validate.yml | 2 +- docs/checks-and-evals.md | 12 ++++--- .../references/remote-pins.md | 13 ++++--- 5 files changed, 64 insertions(+), 21 deletions(-) diff --git a/.github/scripts/pin-validation.mjs b/.github/scripts/pin-validation.mjs index a7677b4..d59f4b7 100644 --- a/.github/scripts/pin-validation.mjs +++ b/.github/scripts/pin-validation.mjs @@ -79,12 +79,13 @@ function verifyActionPins(api, files, changedFiles) { if (oldPins.some((old) => compareVersions(tag.slice(1), old.tag.slice(1)) <= 0)) throw new Error("Action tag must advance to a newer stable semantic version."); if (getJson(api, `repos/github/evals-action/commits/${encodeURIComponent(tag)}`).sha !== sha) throw new Error("Action tag does not resolve to the proposed pin."); const release = getJson(api, `repos/github/evals-action/releases/tags/${encodeURIComponent(tag)}`); - if (release.tag_name !== tag || release.draft !== false || release.prerelease !== false) { - throw new Error("Action pin must target a published stable release."); + if (release.tag_name !== tag || release.draft !== false || typeof release.prerelease !== "boolean") { + throw new Error("Action pin must target a published release with a known channel."); } for (const old of oldPins) { if (getJson(api, `repos/github/evals-action/compare/${old.sha}...${sha}`).status !== "ahead") throw new Error("Action pin is not a forward update."); } + return release.prerelease === false; } function marketplaceContent(api, endpoint) { @@ -160,13 +161,14 @@ function verifyPinPr(api, repo, pr, headBranch, headSha, kind, defaultBranch) { } const endpoint = `repos/${repo}/pulls/${pr.number}`; const files = getJson(api, `${endpoint}/files?per_page=100&page=1`); + let autoMergeEligible = true; if (kind === "plugin") verifyPluginPin(api, repo, pr, headSha, files); - else verifyActionPins(api, files, pr.changed_files); + else autoMergeEligible = verifyActionPins(api, files, pr.changed_files); const current = getJson(api, endpoint); if (!validPr(current, repo, defaultBranch, author) || current.head?.sha !== headSha || current.head?.ref !== headBranch) { throw new Error("PR head changed during inspection."); } - return current; + return { pr: current, autoMergeEligible }; } export function verifyCurrentPinPr({ api = githubApi, repo, event, prNumber, branch, headSha }) { @@ -211,13 +213,19 @@ export function completePinValidation({ api = githubApi, repo, runId, execute = } if (runData.status !== "completed" || runData.conclusion !== "success") return "Skipped an unsuccessful Validate run."; const defaultBranch = getJson(api, `repos/${repo}`).default_branch; - const jobs = getJson(api, `repos/${repo}/actions/runs/${runId}/jobs?per_page=100&page=1`).jobs; - if (!Array.isArray(jobs) || !jobs.some((job) => job.name === "lint" && job.conclusion === "success") || jobs.some((job) => job.conclusion !== "success")) throw new Error("Validate did not finish with every job, including lint, successful."); const pr = getPullRequest(api, repo, runData.head_branch); if (!pr || !validPr(pr, repo, defaultBranch, author)) return "Skipped because no matching open automation PR exists."; if (pr.head?.ref !== runData.head_branch || pr.head?.sha !== runData.head_sha) return "Skipped a stale Validate run for an older PR head."; - const current = verifyPinPr(api, repo, pr, runData.head_branch, runData.head_sha, kind, defaultBranch); + const jobs = getJson(api, `repos/${repo}/actions/runs/${runId}/jobs?per_page=100&page=1`).jobs; + if (!Array.isArray(jobs) || !jobs.some((job) => job.name === "lint" && job.conclusion === "success") || jobs.some((job) => job.conclusion !== "success")) throw new Error("Validate did not finish with every job, including lint, successful."); + const { pr: current, autoMergeEligible } = verifyPinPr(api, repo, pr, runData.head_branch, runData.head_sha, kind, defaultBranch); const number = current.number; + if (!autoMergeEligible) { + if (current.auto_merge?.enabled_by?.login === "github-actions[bot]") { + execute("gh", ["pr", "merge", String(number), "-R", repo, "--disable-auto"]); + } + return `Validated action pin PR #${number} at ${runData.head_sha}; prerelease release is not eligible for auto-merge.`; + } if (kind === "plugin") { execute("gh", [ "api", "--method", "POST", `repos/${repo}/statuses/${runData.head_sha}`, diff --git a/.github/scripts/pin-validation.test.mjs b/.github/scripts/pin-validation.test.mjs index 4d96697..31cc297 100644 --- a/.github/scripts/pin-validation.test.mjs +++ b/.github/scripts/pin-validation.test.mjs @@ -99,6 +99,9 @@ function fixture({ kind = "action", change = {}, failStatus = false } = {}) { if (path === `repos/${repo}/pulls/42` && change.staleHead) { data = { ...pr, head: { ...pr.head, sha: oldPinSha } }; } + if (path === `repos/${repo}/pulls/42` && change.autoMerge !== undefined) { + data = { ...data, auto_merge: change.autoMerge }; + } if (path === `repos/${repo}/actions/runs/99` && change.run) data = { ...workflowRun, ...change.run }; if (path === `repos/${repo}/actions/runs/99/jobs?per_page=100&page=1` && change.jobs) data = change.jobs; if (path === `repos/${repo}/commits/${headSha}` && change.commit) data = change.commit; @@ -164,6 +167,32 @@ test("Validate verifies current action and plugin heads before the required lint assert.deepEqual(unavailable.calls, []); }); +test("allows published action prereleases through required validation without enabling auto-merge", () => { + const prerelease = { + actionRelease: { tag_name: "v0.2.1", draft: false, prerelease: true }, + }; + const f = fixture({ change: prerelease }); + assert.match(verifyCurrentPinPr({ + repo, + event: "pull_request", + prNumber: 42, + branch, + headSha, + ...f, + }), /Validated action pin PR #42/); + assert.match(completePinValidation({ repo, runId: 99, ...f }), /not eligible for auto-merge/); + assert.deepEqual(f.calls, []); + + const previouslyEnabled = fixture({ change: { + ...prerelease, + autoMerge: { enabled_by: { login: "github-actions[bot]" } }, + } }); + assert.match(completePinValidation({ repo, runId: 99, ...previouslyEnabled }), /not eligible for auto-merge/); + assert.deepEqual(previouslyEnabled.calls, [ + ["gh", "pr", "merge", "42", "-R", repo, "--disable-auto"], + ]); +}); + test("read-only pin validation rejects stale, malformed, or untrusted PR inputs", () => { const stale = fixture({ change: { staleHead: true } }); assert.throws(() => verifyCurrentPinPr({ @@ -325,10 +354,11 @@ test("rejects action pin replacements that move step settings", () => { assert.deepEqual(f.calls, []); }); -test("rejects missing, draft, or prerelease action releases", () => { +test("rejects draft, unknown-channel, or mismatched action releases", () => { const invalidCases = [ { actionRelease: { tag_name: "v0.2.1", draft: true, prerelease: false } }, - { actionRelease: { tag_name: "v0.2.1", draft: false, prerelease: true } }, + { actionRelease: { tag_name: "v0.2.1", draft: false } }, + { actionRelease: { tag_name: "v0.2.1", draft: false, prerelease: "true" } }, { actionRelease: { tag_name: "v0.2.0", draft: false, prerelease: false } }, { releaseFailure: { endpoint: actionReleaseEndpoint, status: 404 } }, ]; @@ -406,6 +436,6 @@ test("workflow runs trusted default-branch code with scoped permissions", () => assert.equal(pinCheckout.with["persist-credentials"], false); assert.equal(pinJob.steps.at(-1).run, "node .github/scripts/pin-validation.mjs verify-current-pr"); assert.equal(validate.jobs.lint.needs, "validate-pin"); - assert.equal(validate.jobs.lint.if, "always()"); + assert.equal(validate.jobs.lint.if, "${{ !cancelled() }}"); assert.match(validate.jobs.lint.steps[0].if, /needs\.validate-pin\.result/); }); diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 0a37862..c0cc026 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -44,7 +44,7 @@ jobs: run: node .github/scripts/pin-validation.mjs verify-current-pr lint: needs: validate-pin - if: always() + if: ${{ !cancelled() }} runs-on: ubuntu-latest timeout-minutes: 15 steps: diff --git a/docs/checks-and-evals.md b/docs/checks-and-evals.md index 4fed961..caf6d1d 100644 --- a/docs/checks-and-evals.md +++ b/docs/checks-and-evals.md @@ -92,11 +92,13 @@ handling of prerelease tags has not been verified live. Each PR still requires one human CodeOwner approval and required checks. The same trusted default-branch completion workflow verifies the successful Validate run, Dependabot author, base and exact head, action-only file changes, release tag, -that the tag resolves to a published stable release, strictly increasing -version, and forward commit ancestry before enabling auto-merge. It never checks -out or executes PR-head code and does not approve the PR. Non-stable action tags -are not auto-enabled; Dependabot's prerelease-tag representation has not been -verified live. +that the tag resolves to a published release with a known channel, a strictly +increasing version, and forward commit ancestry. Published prerelease pins pass +required validation so they can be merged after CodeOwner approval, but aren't +auto-enabled; an existing auto-merge request from this workflow is withdrawn +when a successfully validated candidate is a prerelease. Dependabot's +prerelease-tag representation has not been verified live. The workflow never +checks out or executes PR-head code and does not approve the PR. The embedded workflow example later on this page contains three `github/evals-action` pins. The workflow files are authoritative for current diff --git a/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md b/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md index 09ea30b..67074ef 100644 --- a/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md +++ b/plugins/marketplace-maintainer/skills/update-remote-pins/references/remote-pins.md @@ -86,11 +86,14 @@ the `lint` status from GitHub Actions for that SHA, and enables squash auto-merge. Dependabot separately proposes daily grouped `github/evals-action` workflow-pin updates. The same completion workflow verifies the Dependabot author, base and head, action-only file changes, release -tag, strictly increasing stable version, forward commit ancestry, and -successful Validate run before enabling auto-merge. Non-stable action tags -aren't auto-enabled; Dependabot's prerelease-tag representation has not been -verified live. Neither path checks out PR-head code, approves a pull request, -or bypasses branch protection. Before setting `PIN_AUTOMATION`, an +tag, known release channel, strictly increasing version, forward commit +ancestry, and successful Validate run. Published prerelease pins pass required +validation so they can be merged after CodeOwner approval, but aren't +auto-enabled; an existing auto-merge request from this workflow is withdrawn +for a successfully validated prerelease candidate. Dependabot's prerelease-tag +representation has not been verified live. Neither path checks out PR-head +code, approves a pull request, or bypasses branch protection. Before setting +`PIN_AUTOMATION`, an administrator must require `lint` from the GitHub Actions integration and one CodeOwner approval on the default branch, require branches to be up to date before merging, dismiss stale approvals on new commits, allow Actions to create