diff --git a/.github/scripts/check-remote-pins.mjs b/.github/scripts/check-remote-pins.mjs index 7fb520e..0e27f8b 100644 --- a/.github/scripts/check-remote-pins.mjs +++ b/.github/scripts/check-remote-pins.mjs @@ -8,10 +8,14 @@ const supportedSchemas = new Set(["1.0.0", "1.1.0"].map((version) => `https://ag // Copilot CLI's plugin reference (github/docs@8e7396e); legacy order also tested in d838c30^. const legacyManifestPaths = [".plugin/plugin.json", "plugin.json", ".github/plugin/plugin.json", ".claude-plugin/plugin.json"]; -export function githubApi(endpoint, run = spawnSync) { - const result = run("gh", ["api", endpoint, "--include", "-H", "Accept: application/vnd.github.raw+json"], { +export function githubApi(endpoint, run = spawnSync, method = "GET") { + if (!["GET", "POST"].includes(method)) throw new Error(`Unsupported GitHub API method ${method}.`); + const args = ["api", endpoint, "--include", "-H", `Accept: ${method === "POST" ? "application/vnd.github+json" : "application/vnd.github.raw+json"}`]; + if (method === "POST") args.push("-X", method, "-H", "X-GitHub-Api-Version: 2026-03-10"); + const result = run("gh", args, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], + maxBuffer: 16 * 1024 * 1024, }); if (result.error) throw new Error(`Couldn't run gh api (${result.error.code ?? "process error"}).`); const response = /^HTTP\/[\d.]+\s+(\d{3})[^\r\n]*\r?\n[\s\S]*?\r?\n\r?\n([\s\S]*)$/.exec(result.stdout ?? ""); @@ -19,8 +23,8 @@ export function githubApi(endpoint, run = spawnSync) { throw new Error(`GitHub API request failed for ${endpoint} (exit ${result.status}; no HTTP response).`); } const status = Number(response[1]); - if (result.status !== 0 && status === 200) { - throw new Error(`gh api failed for ${endpoint} (exit ${result.status}) despite HTTP 200.`); + if (result.status !== 0 && status >= 200 && status < 300) { + throw new Error(`gh api failed for ${endpoint} (exit ${result.status}) despite HTTP ${status}.`); } return { status, body: response[2] }; } diff --git a/.github/scripts/update-pins.mjs b/.github/scripts/update-pins.mjs new file mode 100644 index 0000000..035ba4b --- /dev/null +++ b/.github/scripts/update-pins.mjs @@ -0,0 +1,424 @@ +import { spawnSync } from "node:child_process"; +import { appendFileSync, existsSync, 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]"; +const safeReleaseTag = (tag) => typeof tag === "string" && /^[A-Za-z0-9._-]+$/.test(tag); + +function getJson(api, endpoint) { + const response = api(endpoint); + if (response.status !== 200) throw new Error(`${endpoint}: GitHub API returned HTTP ${response.status}.`); + return JSON.parse(response.body); +} + +const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +const semver = (tag, prefix) => { + if (!safeReleaseTag(tag)) return null; + const match = new RegExp(`^${escapeRegExp(prefix)}(\\d+)\\.(\\d+)\\.(\\d+)$`).exec(tag ?? ""); + return match && match.slice(1).map(Number); +}; +const compareSemver = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]; + +export function newestRelease(releases, prefix, allowPrerelease) { + return releases + .filter((release) => !release.draft && (allowPrerelease || !release.prerelease) && semver(release.tag_name, prefix)) + .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); + 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}.`); + 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.`); + } +} + +function run(command, args, options = {}) { + const result = spawnSync(command, args, { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], ...options }); + if (result.error || result.status !== 0) throw new Error(`${command} ${args[0]} failed (exit ${result.status ?? result.error?.code}).`); + 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", + ])); +} + +function openPr(api, repo) { + const [owner] = repo.split("/"); + return getJson(api, `repos/${repo}/pulls?state=open&head=${owner}:${encodeURIComponent(BRANCH)}`)[0]; +} + +function remoteBranch(api, repo, main) { + const response = api(`repos/${repo}/branches/${encodeURIComponent(BRANCH)}`); + 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 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) { + 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 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 (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}`], { + 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}`; +} + +export function main(argv, api = githubApi) { + const [command, ...rest] = argv; + const args = {}; + for (let index = 0; index < rest.length; index += 2) args[rest[index].replace(/^--/, "")] = rest[index + 1]; + 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); + 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("")}`); + } 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); + } 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]"); + } +} + +if (process.argv[1] && realpathSync(fileURLToPath(import.meta.url)) === realpathSync(resolve(process.argv[1]))) { + try { + main(process.argv.slice(2)); + } catch (error) { + console.error(`::error::${error.message}`); + process.exitCode = 1; + } +} diff --git a/.github/scripts/update-pins.test.mjs b/.github/scripts/update-pins.test.mjs new file mode 100644 index 0000000..ce56143 --- /dev/null +++ b/.github/scripts/update-pins.test.mjs @@ -0,0 +1,630 @@ +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 { 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"; + +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", + }, + ], +}, 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 }); + +function fakeApi(routes) { + const calls = []; + const api = (endpoint) => { + calls.push(endpoint); + if (!(endpoint in routes)) return { status: 404, body: "{}" }; + return { status: 200, body: JSON.stringify(routes[endpoint]) }; + }; + return Object.assign(api, { calls }); +} + +function upstream({ evalsReleases, actionReleases, actionCompare = "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/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 }); + }); + 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]; + 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.match(plan.body, new RegExp(`compare/${sha("1")}\\.\\.\\.${sha("2")}`)); +}); + +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("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("planUpdate reads every release page before choosing", () => { + 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") }, + }); + 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"); +}); + +test("requiredChecks reads every rules page and keeps app bindings", () => { + const filler = Array.from({ length: 100 }, () => ({ type: "deletion" })); + 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" }], + }); + assert.equal(approvedCopilotReview(staleApproval, "o/r", 7, head), false); +}); + +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", + }], + }); + 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); + } +}); + +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 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("update CLI reports the unchanged plan and writes its step outputs", (t) => { + const { output, summary } = commandWorkspace(t); + 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": [], + }); + + 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", + ]); +}); + +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("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("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("CLI requires a repository and rejects unknown commands", (t) => { + commandWorkspace(t); + const previous = process.env.GITHUB_REPOSITORY; + delete process.env.GITHUB_REPOSITORY; + try { + assert.throws(() => main(["gate"], fakeApi({})), /GITHUB_REPOSITORY must name this repository/); + } finally { + if (previous === undefined) delete process.env.GITHUB_REPOSITORY; + else process.env.GITHUB_REPOSITORY = previous; + } + 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/); +}); + +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("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("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("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)) { + 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`); + } + 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, + }); +}); diff --git a/.github/scripts/validation.test.mjs b/.github/scripts/validation.test.mjs index 6063235..8bb6372 100644 --- a/.github/scripts/validation.test.mjs +++ b/.github/scripts/validation.test.mjs @@ -299,8 +299,9 @@ test("manifest authentication and server errors stop rather than falling through }); test("gh transport retains HTTP statuses and raw JSON without exposing stderr", () => { - const run = (_command, args) => { + const run = (_command, args, options) => { assert.ok(args.includes("--include")); + assert.equal(options.maxBuffer, 16 * 1024 * 1024); return { status: 0, stdout: 'HTTP/2.0 200 OK\r\nContent-Type: application/json\r\n\r\n{"name":"tool"}', stderr: "" }; }; assert.deepEqual(githubApi("repos/owner/repo", run), { status: 200, body: '{"name":"tool"}' }); @@ -311,6 +312,24 @@ test("gh transport retains HTTP statuses and raw JSON without exposing stderr", assert.throws(() => githubApi("repos/owner/repo", () => ({ error: { code: "ENOENT" } })), /Couldn't run gh api \(ENOENT\)/); }); +test("gh transport supports Copilot review POSTs and retains conflict status", () => { + const run = (_command, args) => { + assert.ok(args.includes("-X")); + assert.equal(args[args.indexOf("-X") + 1], "POST"); + assert.ok(args.includes("X-GitHub-Api-Version: 2026-03-10")); + assert.ok(args.includes("Accept: application/vnd.github+json")); + return { status: 0, stdout: 'HTTP/2.0 201 Created\r\nContent-Type: application/json\r\n\r\n{"state":"PENDING"}', stderr: "" }; + }; + assert.deepEqual(githubApi("repos/owner/repo/pulls/7/copilot-code-review", run, "POST"), { + status: 201, + body: '{"state":"PENDING"}', + }); + assert.deepEqual(githubApi("repos/owner/repo/pulls/7/copilot-code-review", () => ({ + status: 1, stdout: "HTTP/2.0 409 Conflict\nContent-Type: application/json\n\n{}", stderr: "", + }), "POST"), { status: 409, body: "{}" }); + assert.throws(() => githubApi("repos/owner/repo", spawnSync, "DELETE"), /Unsupported GitHub API method DELETE/); +}); + test("schema script keeps pinned AJV and draft2020, and cleans its directory on success and failures", (t) => { const directory = fixture(t); mkdirSync(resolve(directory, ".github/scripts"), { recursive: true }); diff --git a/.github/workflows/evals.yml b/.github/workflows/evals.yml index d453d3f..b2596f0 100644 --- a/.github/workflows/evals.yml +++ b/.github/workflows/evals.yml @@ -3,8 +3,7 @@ name: Evals # This full smoke-suite workflow starts by explicit manual dispatch only. # Same-repository PRs that change plugins//skills// with a matching # evals//skills//eval.yaml run .github/workflows/skill-eval-comparison.yml -# (using github/evals-action@3c551330898c1467b8ddf9ef7c7f6e6c6af489d6 from -# github/evals-action#34 with report-id: evals-baseline and +# (using github/evals-action with report-id: evals-baseline and # baseline-report-id: evals-baseline to update one sticky PR comment automatically); # see docs/checks-and-evals.md#automatic-pr-skill-comparison. on: diff --git a/.github/workflows/skill-eval-comparison.yml b/.github/workflows/skill-eval-comparison.yml index 7e47401..8c9c3c6 100644 --- a/.github/workflows/skill-eval-comparison.yml +++ b/.github/workflows/skill-eval-comparison.yml @@ -13,6 +13,9 @@ permissions: jobs: select: if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository + concurrency: + group: skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-select + cancel-in-progress: ${{ github.event_name == 'pull_request' }} runs-on: ubuntu-latest timeout-minutes: 5 outputs: @@ -59,6 +62,9 @@ jobs: run-baseline: needs: select if: needs.select.outputs.eval_paths != '' + concurrency: + group: skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-run-baseline + cancel-in-progress: ${{ github.event_name == 'pull_request' }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -86,7 +92,7 @@ jobs: git checkout "$BASE_SHA" -- "$dir" fi done <<< "$SKILL_DIRS" - - uses: github/evals-action@3c551330898c1467b8ddf9ef7c7f6e6c6af489d6 + - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb continue-on-error: true env: VALLY_TELEMETRY_OPTOUT: '1' @@ -101,6 +107,9 @@ jobs: run: needs: select if: needs.select.outputs.eval_paths != '' + concurrency: + group: skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-run + cancel-in-progress: ${{ github.event_name == 'pull_request' }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -110,7 +119,7 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: github/evals-action@3c551330898c1467b8ddf9ef7c7f6e6c6af489d6 + - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb env: VALLY_TELEMETRY_OPTOUT: '1' with: @@ -123,7 +132,7 @@ jobs: report: needs: [select, run-baseline, run] - if: always() && needs.select.outputs.eval_paths != '' && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + if: always() && needs.select.outputs.eval_paths != '' && needs.run-baseline.result != 'cancelled' && needs.run.result != 'cancelled' && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -131,10 +140,11 @@ jobs: contents: read pull-requests: write concurrency: + # The pinned report action requires this exact, separate group. group: evals-${{ github.workflow_ref }} cancel-in-progress: false steps: - - uses: github/evals-action@3c551330898c1467b8ddf9ef7c7f6e6c6af489d6 + - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb with: command: report report-id: evals diff --git a/.github/workflows/update-pins.yml b/.github/workflows/update-pins.yml new file mode 100644 index 0000000..7fdf7ce --- /dev/null +++ b/.github/workflows/update-pins.yml @@ -0,0 +1,161 @@ +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. +on: + schedule: + - cron: '7,37 * * * *' + workflow_dispatch: + inputs: + dry_run: + description: Report what would change without pushing, opening, or merging a PR. + type: boolean + default: true + workflow_run: + workflows: [Validate] + types: [completed] + branches: [automation/update-pins] +permissions: + contents: read +concurrency: + group: update-pins + cancel-in-progress: false +jobs: + plan: + 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) + 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: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 + with: + node-version: 24 + - id: update + 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 + 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' diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 22bddd4..daf22de 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -4,6 +4,8 @@ on: pull_request: push: branches: [main] + merge_group: + types: [checks_requested] workflow_dispatch: permissions: contents: read diff --git a/README.md b/README.md index 7315ae1..d913581 100644 --- a/README.md +++ b/README.md @@ -211,10 +211,8 @@ 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`, introduced in -[github/evals-action#34](https://github.com/github/evals-action/pull/34) at -commit `3c551330898c1467b8ddf9ef7c7f6e6c6af489d6` and included in `@v0` once -released) so any changed skill under +`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 `evals//skills//eval.yaml` automatically runs Baseline vs. Candidate and updates one sticky PR comparison comment; see diff --git a/docs/checks-and-evals.md b/docs/checks-and-evals.md index 1e4db7a..aac61ca 100644 --- a/docs/checks-and-evals.md +++ b/docs/checks-and-evals.md @@ -62,6 +62,87 @@ The schema check downloads the Agent Plugins schema and runs running it. The pin check makes read-only GitHub API calls through your 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 +[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`, @@ -296,7 +377,10 @@ dispatching a run. automatically on same-repository pull requests (`github.event.pull_request.head.repo.full_name == github.repository`, excluding fork PRs) whenever a skill under `plugins//skills//` with a -matching `evals//skills//eval.yaml` changes: +matching `evals//skills//eval.yaml` changes. A newer eligible +push cancels the superseded selection and evaluation jobs for the same PR. +Canceled runs do not post partial reports; report jobs use their separate +non-canceling lock. Manual dispatches do not cancel in-progress runs. 1. **Discover changed skills (`select`):** diff `plugins//skills//` between the PR base and head, and keep every skill whose @@ -316,13 +400,12 @@ matching `evals//skills//eval.yaml` changes: run evidence** `
` section (`Outcome`, `Passed/Failed`, `Score delta`, `Turns delta`, `Duration delta`, and `Token in/out + %` delta). -> **Action version note:** `baseline-report-id` (`evals-baseline`) is provided -> by [github/evals-action#34](https://github.com/github/evals-action/pull/34) -> (`3c551330898c1467b8ddf9ef7c7f6e6c6af489d6`), and the top-level **Ship / -> No-ship** verdict table layout is added in -> [github/evals-action#35](https://github.com/github/evals-action/pull/35). Pin -> `github/evals-action` to that commit until published to -> `github/evals-action@v0`. +> **Action version note:** `baseline-report-id` (`evals-baseline`) and the +> 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. ```yaml name: Skill eval comparison @@ -337,6 +420,9 @@ permissions: jobs: select: if: github.event.pull_request.head.repo.full_name == github.repository + concurrency: + group: skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-select + cancel-in-progress: ${{ github.event_name == 'pull_request' }} runs-on: ubuntu-latest timeout-minutes: 5 outputs: @@ -373,6 +459,9 @@ jobs: run-baseline: needs: select if: needs.select.outputs.eval_paths != '' + concurrency: + group: skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-run-baseline + cancel-in-progress: ${{ github.event_name == 'pull_request' }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -394,7 +483,7 @@ jobs: git checkout "$BASE_SHA" -- "$dir" fi done <<< "$SKILL_DIRS" - - uses: github/evals-action@3c551330898c1467b8ddf9ef7c7f6e6c6af489d6 # github/evals-action#34 (use @v0 once released) + - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb continue-on-error: true env: VALLY_TELEMETRY_OPTOUT: '1' @@ -409,6 +498,9 @@ jobs: run: needs: select if: needs.select.outputs.eval_paths != '' + concurrency: + group: skill-eval-comparison-${{ github.event.pull_request.number || github.ref }}-run + cancel-in-progress: ${{ github.event_name == 'pull_request' }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: @@ -418,7 +510,7 @@ jobs: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 with: persist-credentials: false - - uses: github/evals-action@3c551330898c1467b8ddf9ef7c7f6e6c6af489d6 # github/evals-action#34 (use @v0 once released) + - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb env: VALLY_TELEMETRY_OPTOUT: '1' with: @@ -431,7 +523,7 @@ jobs: report: needs: [select, run-baseline, run] - if: always() && needs.select.outputs.eval_paths != '' && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + if: always() && needs.select.outputs.eval_paths != '' && needs.run-baseline.result != 'cancelled' && needs.run.result != 'cancelled' && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest timeout-minutes: 5 permissions: @@ -442,7 +534,7 @@ jobs: group: evals-${{ github.workflow_ref }} cancel-in-progress: false steps: - - uses: github/evals-action@3c551330898c1467b8ddf9ef7c7f6e6c6af489d6 # github/evals-action#34 (use @v0 once released) + - uses: github/evals-action@d7b40d34236f09c8078a2b4e0008ed2ac81919cb with: command: report report-id: evals diff --git a/evals/marketplace-maintainer/skills/update-remote-pins/eval.yaml b/evals/marketplace-maintainer/skills/update-remote-pins/eval.yaml index 90386d5..ccdae62 100644 --- a/evals/marketplace-maintainer/skills/update-remote-pins/eval.yaml +++ b/evals/marketplace-maintainer/skills/update-remote-pins/eval.yaml @@ -16,7 +16,7 @@ grading_environment: stimuli: - name: update-remote-pins-uses-reviewed-release prompt: >- - Pin outside-notes at its latest release using the reviewed offline + Use the update-remote-pins skill to pin outside-notes at its latest release using the reviewed offline upstream-snapshot.json instead of GitHub. Its current catalog pin is the previous release. Review and summarize the supplied upstream changes, update the selected entry. Don't access the network, install @@ -59,7 +59,7 @@ stimuli: - type: diff-empty - name: update-remote-pins-preserves-stable-channel-after-latest-404 prompt: >- - Check outside-notes for the latest stable release using only the reviewed + Use the update-remote-pins skill to check outside-notes for the latest stable release using only the reviewed offline prerelease-only.json responses. Don't access the network. The releases/latest endpoint returned 404, but repository access and the complete release listing succeeded. Explain the available channel and diff --git a/plugins/marketplace-maintainer/CHANGELOG.md b/plugins/marketplace-maintainer/CHANGELOG.md index 6f8a732..528e466 100644 --- a/plugins/marketplace-maintainer/CHANGELOG.md +++ b/plugins/marketplace-maintainer/CHANGELOG.md @@ -3,6 +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. ## 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 112601d..65e52b1 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,8 +76,22 @@ pin; don't change the SHA just to make the check pass. ## Keep pins current -Nothing updates remote pins automatically. On a regular cadence, or when -upstream announces a release: +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: 1. Check each pin as described above. 2. Review what changed upstream between the pinned SHA and the new one.