diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0335e28451..11ef68ceb8 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -19,8 +19,11 @@ jobs: timeout-minutes: 10 environment: npm-publish permissions: + actions: read + checks: read contents: write id-token: write + pull-requests: read env: EXPECTED_RELEASE_SHA: >- ${{ github.event_name == 'pull_request' @@ -83,6 +86,13 @@ jobs: PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} run: node scripts/validate-release-channel.mjs + - name: Guard stable release + if: github.event_name == 'pull_request' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ steps.version.outputs.version }} + run: node scripts/stable-release-guard.mjs + - name: Create release tag if: github.event_name == 'pull_request' env: diff --git a/package.json b/package.json index 504e5315c3..8388832bdf 100644 --- a/package.json +++ b/package.json @@ -48,7 +48,7 @@ "player:perf": "bun run --filter @hyperframes/player perf", "format:check": "oxfmt --check .", "knip": "knip", - "test:scripts": "node --import tsx --test scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs && vitest run scripts/catalog/", + "test:scripts": "node --import tsx --test scripts/release-packages.test.ts scripts/publish-packages.test.ts scripts/stable-release-guard.test.mjs scripts/animejs-v4-guidance.test.mjs scripts/check-tracked-artifacts.test.mjs scripts/check-no-main-deletions.test.mjs scripts/check-docs-snippet-motion.test.mjs scripts/registry-target-paths.test.mjs scripts/check-workspace-contracts.test.mjs scripts/check-package-cycles.test.mjs scripts/check-cli-process-ownership.test.mjs scripts/package-subpaths.test.mjs scripts/validate-release-channel.test.mjs scripts/publish-workflow.test.mjs scripts/install-workspace-dependencies.test.mjs scripts/draft-changelog.test.ts scripts/set-version.test.ts scripts/release-prepare.test.ts scripts/cli-options.test.ts scripts/changelog-weekly.test.ts scripts/claude-plugin-compression.test.ts scripts/catalog-payload-assets.test.ts scripts/catalog-preview-temp.test.ts scripts/player-cdn-pin.test.ts scripts/studio-runtime-smoke.test.mjs scripts/verify-packed-manifests.test.mjs scripts/lint-skills.test.mjs packages/gcp-cloud-run/check-dockerfile-workspaces.test.mjs && vitest run scripts/catalog/", "typecheck:scripts": "tsc --noEmit -p scripts/tsconfig.json", "test:skills": "node --test 'skills/**/*.test.mjs'", "generate:previews": "tsx scripts/generate-template-previews.ts", diff --git a/scripts/publish-workflow.test.mjs b/scripts/publish-workflow.test.mjs index 051543daff..28b9b301df 100644 --- a/scripts/publish-workflow.test.mjs +++ b/scripts/publish-workflow.test.mjs @@ -14,6 +14,8 @@ const checkoutGuard = publish.steps.find( (step) => step.name === "Verify immutable release checkout", ); const createReleaseTag = publish.steps.find((step) => step.name === "Create release tag"); +const stableGuard = publish.steps.find((step) => step.name === "Guard stable release"); +const publishPackages = publish.steps.find((step) => step.name === "Publish packages"); const normalizeExpression = (expression) => expression.replace(/\s+/g, " ").trim(); @@ -99,6 +101,25 @@ test("stable release tag recovery is idempotent and immutable", () => { ); }); +test("the stable guard precedes every irreversible release side effect", () => { + assert.ok(stableGuard); + assert.equal(stableGuard.if, "github.event_name == 'pull_request'"); + assert.equal(stableGuard["continue-on-error"], undefined); + assert.match(stableGuard.run, /stable-release-guard\.mjs/); + assert.ok(publish.steps.indexOf(stableGuard) < publish.steps.indexOf(createReleaseTag)); + assert.ok(publish.steps.indexOf(stableGuard) < publish.steps.indexOf(publishPackages)); + assert.equal(publish.permissions.actions, "read"); + assert.equal(publish.permissions.checks, "read"); + assert.equal(publish.permissions["pull-requests"], "read"); +}); + +test("the workflow invokes one shared publisher and owns no package roster", () => { + assert.ok(publishPackages); + assert.equal(publishPackages.run.trim(), "node --import tsx scripts/publish-packages.ts"); + assert.doesNotMatch(workflow, /@hyperframes\//); + assert.doesNotMatch(workflow, /publish_pkg|packages\/cli/); +}); + test("stable release tag creation survives retries and rejects a mismatched commit", () => { const root = mkdtempSync(join(tmpdir(), "hyperframes-release-tag-test-")); const origin = join(root, "origin.git"); diff --git a/scripts/stable-release-guard.mjs b/scripts/stable-release-guard.mjs new file mode 100644 index 0000000000..0bd36c2aa1 --- /dev/null +++ b/scripts/stable-release-guard.mjs @@ -0,0 +1,463 @@ +#!/usr/bin/env node +import { execFileSync } from "node:child_process"; +import { readFileSync } from "node:fs"; + +export const DEFAULT_TIMEOUT_MS = 8 * 60 * 1_000; +export const INITIAL_BACKOFF_MS = 5_000; +export const MAX_BACKOFF_MS = 30_000; + +const PASSING_CONCLUSIONS = new Set(["success", "neutral", "skipped"]); +const TERMINAL_FAILURE_CONCLUSIONS = new Set([ + "action_required", + "cancelled", + "failure", + "stale", + "startup_failure", + "timed_out", + "error", +]); +const DECISIVE_REVIEW_STATES = new Set(["APPROVED", "CHANGES_REQUESTED", "DISMISSED"]); +const REVIEW_STATES = new Set([...DECISIVE_REVIEW_STATES, "COMMENTED"]); +const NON_CHECK_RULES = new Set([ + "creation", + "update", + "deletion", + "required_linear_history", + "required_signatures", + "non_fast_forward", + "commit_message_pattern", + "commit_author_email_pattern", + "committer_email_pattern", + "branch_name_pattern", + "tag_name_pattern", +]); + +function requiredString(value, label) { + if (typeof value !== "string" || value.length === 0) throw new Error(`Missing ${label}.`); + return value; +} + +function requiredNumber(value, label) { + if (!Number.isInteger(value)) throw new Error(`Missing ${label}.`); + return value; +} + +// fallow-ignore-next-line complexity +function pullIdentity(pull, label) { + if (!pull || typeof pull !== "object") throw new Error(`Missing ${label}.`); + return { + number: requiredNumber(pull.number, `${label} number`), + merged: pull.merged === true, + baseRef: requiredString(pull.base?.ref, `${label} base ref`), + headRef: requiredString(pull.head?.ref, `${label} head ref`), + headSha: requiredString(pull.head?.sha, `${label} head SHA`), + mergeSha: requiredString(pull.merge_commit_sha, `${label} merge SHA`), + authorLogin: requiredString(pull.user?.login, `${label} author`), + }; +} + +// All identity comparisons stay together so no caller can omit one. +// fallow-ignore-next-line complexity +export function assertImmutableRelease({ + event, + apiPull, + expectedSha, + githubSha, + checkoutSha, + version, +}) { + if (event?.action !== "closed") + throw new Error("Stable release event must be pull_request closed."); + const fromEvent = pullIdentity(event.pull_request, "event pull request"); + const fromApi = pullIdentity(apiPull, "API pull request"); + if (!fromEvent.merged || !fromApi.merged) throw new Error("Stable release PR must be merged."); + if (fromEvent.baseRef !== "main" || fromApi.baseRef !== "main") + throw new Error("Stable release PR must target main."); + const expectedBranch = `release/v${version}`; + if (fromEvent.headRef !== expectedBranch || fromApi.headRef !== expectedBranch) { + throw new Error(`Stable release branch mismatch: expected ${expectedBranch}.`); + } + const identities = [ + ["PR number", fromEvent.number, fromApi.number], + ["head SHA", fromEvent.headSha, fromApi.headSha], + ["merge SHA", fromEvent.mergeSha, fromApi.mergeSha], + ["author", fromEvent.authorLogin, fromApi.authorLogin], + ["EXPECTED_RELEASE_SHA", fromEvent.mergeSha, expectedSha], + ["GITHUB_SHA", fromEvent.mergeSha, githubSha], + ["checked-out HEAD", fromEvent.mergeSha, checkoutSha], + ]; + for (const [label, expected, actual] of identities) { + if (expected !== actual) + throw new Error(`${label} mismatch: expected ${expected}, got ${actual}.`); + } + return fromEvent; +} + +function reviewOrder(review) { + return [Date.parse(review.submitted_at), review.id]; +} + +// Every decisive review field is validated together so malformed records cannot be partially used. +// fallow-ignore-next-line complexity +function validateReview(review) { + const state = typeof review?.state === "string" ? review.state.toUpperCase() : ""; + if ( + !Number.isInteger(review?.id) || + typeof review?.user?.login !== "string" || + review.user.login.length === 0 || + !REVIEW_STATES.has(state) || + typeof review?.submitted_at !== "string" || + !Number.isFinite(Date.parse(review.submitted_at)) || + typeof review?.commit_id !== "string" || + review.commit_id.length === 0 + ) { + throw new Error( + `Malformed review record: reviewer=${String(review?.user?.login)} state=${String(review?.state)} head=${String(review?.commit_id)}.`, + ); + } + return { ...review, state }; +} + +// The decisive-review reducer mirrors GitHub's per-reviewer state semantics. +// fallow-ignore-next-line complexity +export function collectEffectiveApprovals({ reviews, authorLogin, headSha, requiredCount }) { + if (!Array.isArray(reviews)) throw new Error("Review API response is malformed."); + const latestByReviewer = new Map(); + for (const candidate of reviews) { + const review = validateReview(candidate); + const { state } = review; + const login = review.user.login; + if (!DECISIVE_REVIEW_STATES.has(state)) continue; + const existing = latestByReviewer.get(login.toLowerCase()); + const [time, id] = reviewOrder(review); + const [existingTime, existingId] = existing ? reviewOrder(existing) : [-1, -1]; + if (!existing || time > existingTime || (time === existingTime && id > existingId)) { + latestByReviewer.set(login.toLowerCase(), review); + } + } + const approvals = [...latestByReviewer.values()] + .filter( + (review) => + review.state.toUpperCase() === "APPROVED" && + review.commit_id === headSha && + review.user.login.toLowerCase() !== authorLogin.toLowerCase(), + ) + .map((review) => review.user.login) + .sort(); + const minimum = Math.max(1, Number.isInteger(requiredCount) ? requiredCount : 0); + if (approvals.length < minimum) { + throw new Error( + `Final release head requires ${minimum} valid non-author approval(s); found ${approvals.length}.`, + ); + } + return approvals; +} + +// Unknown effective gates must fail closed rather than disappear during parsing. +// fallow-ignore-next-line complexity +export function extractEffectiveRules(rules) { + if (!Array.isArray(rules)) throw new Error("Repository rules API response is malformed."); + const requiredChecks = []; + let requiredApprovals = 0; + let requireLastPushApproval = false; + let requireExtraApprovalForUnattributedChanges = false; + let requireSignedCommits = false; + for (const rule of rules) { + if (rule?.type === "required_status_checks") { + const checks = rule.parameters?.required_status_checks; + if (!Array.isArray(checks)) throw new Error("Required status checks rule is malformed."); + for (const check of checks) { + if (typeof check?.context !== "string" || !Number.isInteger(check.integration_id)) { + throw new Error("Required status check identity is malformed."); + } + requiredChecks.push({ context: check.context, integrationId: check.integration_id }); + } + continue; + } + if (rule?.type === "pull_request") { + const count = rule.parameters?.required_approving_review_count; + if (!Number.isInteger(count)) throw new Error("Pull request approval rule is malformed."); + requiredApprovals = Math.max(requiredApprovals, count); + requireLastPushApproval ||= rule.parameters.require_last_push_approval === true; + requireExtraApprovalForUnattributedChanges ||= + rule.parameters.require_extra_approval_for_unattributed_changes === true; + continue; + } + if (rule?.type === "required_signatures") { + requireSignedCommits = true; + continue; + } + if (!NON_CHECK_RULES.has(rule?.type)) { + throw new Error(`Unsupported effective repository rule: ${String(rule?.type)}.`); + } + } + if (requiredChecks.length === 0) throw new Error("No required status checks found for main."); + const unique = new Map( + requiredChecks.map((check) => [`${check.context}:${check.integrationId}`, check]), + ); + return { + requiredApprovals, + requiredChecks: [...unique.values()], + requireLastPushApproval, + requireExtraApprovalForUnattributedChanges, + requireSignedCommits, + }; +} + +// The exact update identity and outcome form one indivisible authoritative gate. +// fallow-ignore-next-line complexity +function assertRuleSuitePass(suite, mergeSha) { + if ( + suite?.afterSha !== mergeSha || + suite?.ref !== "refs/heads/main" || + suite?.result !== "pass" + ) { + throw new Error( + `Rule suite for ${mergeSha} must be pass, got after=${String(suite?.afterSha)} ref=${String(suite?.ref)} result=${String(suite?.result)}.`, + ); + } +} + +// fallow-ignore-next-line complexity +function checkOrder(check) { + return [ + Date.parse(check.started_at ?? "") || 0, + Date.parse(check.completed_at ?? "") || 0, + Number(check.id) || 0, + ]; +} + +function isNewer(candidate, existing) { + const left = checkOrder(candidate); + const right = checkOrder(existing); + for (let index = 0; index < left.length; index += 1) { + if (left[index] !== right[index]) return left[index] > right[index]; + } + return false; +} + +function belongsToRun(check, runId) { + return Boolean(runId) && String(check.details_url ?? "").includes(`/actions/runs/${runId}/`); +} + +// Required-context classification remains one exhaustive outcome reducer. +// fallow-ignore-next-line complexity +export function evaluateRequiredChecks({ requiredChecks, checkRuns, currentRunId }) { + if (!Array.isArray(checkRuns)) + return { kind: "api-failure", summary: "Check-runs response is malformed." }; + const details = []; + for (const requirement of requiredChecks) { + const matching = checkRuns.filter( + (check) => + check?.name === requirement.context && check?.app?.id === requirement.integrationId, + ); + const latest = matching.reduce( + (selected, candidate) => (!selected || isNewer(candidate, selected) ? candidate : selected), + null, + ); + if (!latest) { + details.push(`${requirement.context}: missing`); + continue; + } + if (belongsToRun(latest, currentRunId)) { + return { + kind: "self-reference", + summary: `${requirement.context} resolves to current publish run ${currentRunId}.`, + }; + } + if (latest.status !== "completed") { + details.push(`${requirement.context}: ${latest.status}`); + continue; + } + if (PASSING_CONCLUSIONS.has(latest.conclusion)) continue; + if (TERMINAL_FAILURE_CONCLUSIONS.has(latest.conclusion) || latest.conclusion == null) { + return { + kind: "terminal-failure", + summary: `${requirement.context}: ${String(latest.conclusion)}`, + }; + } + return { + kind: "terminal-failure", + summary: `${requirement.context}: unsupported conclusion ${latest.conclusion}`, + }; + } + return details.length > 0 + ? { kind: "pending", summary: details.join(", ") } + : { kind: "passing", summary: "All required checks are terminal green." }; +} + +// fallow-ignore-next-line complexity +export async function runStableReleaseGuard({ + event, + expectedSha, + githubSha, + checkoutSha, + version, + currentRunId, + client, + now, + sleep, + timeoutMs, + initialBackoffMs, + maxBackoffMs, + log, +}) { + const deadline = now() + timeoutMs; + const remainingBudget = (phase) => { + const remaining = deadline - now(); + if (remaining <= 0) throw new Error(`Timed out during stable release guard (${phase}).`); + return remaining; + }; + const apiPull = await client.getPull(event.pull_request.number, remainingBudget("pull request")); + const identity = assertImmutableRelease({ + event, + apiPull, + expectedSha, + githubSha, + checkoutSha, + version, + }); + const ruleSuite = await client.getRuleSuite(identity.mergeSha, remainingBudget("rule suite")); + assertRuleSuitePass(ruleSuite, identity.mergeSha); + const rules = await client.getEffectiveRules("main", remainingBudget("effective rules")); + const reviews = await client.listReviews(identity.number, remainingBudget("reviews")); + const approvals = collectEffectiveApprovals({ + reviews, + authorLogin: identity.authorLogin, + headSha: identity.headSha, + requiredCount: rules.requiredApprovals, + }); + log( + `Stable release identity verified: PR #${identity.number} head=${identity.headSha} merge=${identity.mergeSha}.`, + ); + log(`Valid final-head approvals: ${approvals.join(", ")}.`); + log( + `Effective PR rules: last-push=${rules.requireLastPushApproval === true} unattributed=${rules.requireExtraApprovalForUnattributedChanges === true} signatures=${rules.requireSignedCommits === true}; exact update rule suite passed.`, + ); + + let backoff = initialBackoffMs; + while (true) { + const checkRuns = await client.listCheckRuns( + identity.mergeSha, + remainingBudget("required checks"), + ); + const outcome = evaluateRequiredChecks({ + requiredChecks: rules.requiredChecks, + checkRuns, + currentRunId, + }); + log(`Required checks: ${outcome.summary}`); + if (outcome.kind === "passing") return; + if (outcome.kind !== "pending") + throw new Error(`Stable release checks failed: ${outcome.summary}`); + const remaining = deadline - now(); + if (remaining <= 0) + throw new Error( + `Timed out waiting for required checks on ${identity.mergeSha}: ${outcome.summary}`, + ); + await sleep(Math.min(backoff, remaining)); + backoff = Math.min(maxBackoffMs, backoff * 2); + } +} + +function createGitHubClient({ repository, token }) { + const request = async (path, requestBudgetMs) => { + const response = await fetch(`https://api.github.com${path}`, { + headers: { + Accept: "application/vnd.github+json", + Authorization: `Bearer ${token}`, + "X-GitHub-Api-Version": "2022-11-28", + }, + signal: AbortSignal.timeout(Math.max(1, requestBudgetMs)), + }); + if (!response.ok) throw new Error(`GitHub API ${response.status} for ${path}.`); + return response.json(); + }; + // fallow-ignore-next-line complexity + const paginate = async (path, itemKey, requestBudgetMs) => { + const items = []; + const deadline = Date.now() + requestBudgetMs; + for (let page = 1; ; page += 1) { + const separator = path.includes("?") ? "&" : "?"; + const remaining = deadline - Date.now(); + if (remaining <= 0) throw new Error(`GitHub API pagination timed out for ${path}.`); + const response = await request(`${path}${separator}per_page=100&page=${page}`, remaining); + const pageItems = itemKey ? response?.[itemKey] : response; + if (!Array.isArray(pageItems)) + throw new Error(`GitHub API pagination response is malformed for ${path}.`); + items.push(...pageItems); + if (pageItems.length < 100) return items; + } + }; + return { + getPull: (number, requestBudgetMs) => + request(`/repos/${repository}/pulls/${number}`, requestBudgetMs), + listReviews: (number, requestBudgetMs) => + paginate(`/repos/${repository}/pulls/${number}/reviews`, null, requestBudgetMs), + getRuleSuite: async (sha, requestBudgetMs) => { + const suites = await paginate( + `/repos/${repository}/rulesets/rule-suites?ref=${encodeURIComponent("refs/heads/main")}`, + null, + requestBudgetMs, + ); + const matching = suites.filter((suite) => suite?.after_sha === sha); + if (matching.length !== 1) { + throw new Error( + `Expected one rule suite for main update ${sha}, found ${matching.length}.`, + ); + } + return { + afterSha: matching[0].after_sha, + ref: matching[0].ref, + result: matching[0].result, + }; + }, + getEffectiveRules: async (branch, requestBudgetMs) => + extractEffectiveRules( + await request( + `/repos/${repository}/rules/branches/${encodeURIComponent(branch)}`, + requestBudgetMs, + ), + ), + listCheckRuns: (sha, requestBudgetMs) => + paginate( + `/repos/${repository}/commits/${sha}/check-runs?filter=all`, + "check_runs", + requestBudgetMs, + ), + }; +} + +async function main() { + const eventPath = requiredString(process.env.GITHUB_EVENT_PATH, "GITHUB_EVENT_PATH"); + const repository = requiredString(process.env.GITHUB_REPOSITORY, "GITHUB_REPOSITORY"); + const token = requiredString(process.env.GH_TOKEN, "GH_TOKEN"); + const expectedSha = requiredString(process.env.EXPECTED_RELEASE_SHA, "EXPECTED_RELEASE_SHA"); + const githubSha = requiredString(process.env.GITHUB_SHA, "GITHUB_SHA"); + const version = requiredString(process.env.VERSION, "VERSION"); + const currentRunId = requiredString(process.env.GITHUB_RUN_ID, "GITHUB_RUN_ID"); + const event = JSON.parse(readFileSync(eventPath, "utf8")); + const checkoutSha = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); + await runStableReleaseGuard({ + event, + expectedSha, + githubSha, + checkoutSha, + version, + currentRunId, + client: createGitHubClient({ repository, token }), + now: Date.now, + sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + timeoutMs: DEFAULT_TIMEOUT_MS, + initialBackoffMs: INITIAL_BACKOFF_MS, + maxBackoffMs: MAX_BACKOFF_MS, + log: console.log, + }); +} + +if (import.meta.url === `file://${process.argv[1]}`) { + main().catch((error) => { + console.error(`::error::${error instanceof Error ? error.message : String(error)}`); + process.exitCode = 1; + }); +} diff --git a/scripts/stable-release-guard.test.mjs b/scripts/stable-release-guard.test.mjs new file mode 100644 index 0000000000..317aa5a08a --- /dev/null +++ b/scripts/stable-release-guard.test.mjs @@ -0,0 +1,462 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { + assertImmutableRelease, + collectEffectiveApprovals, + evaluateRequiredChecks, + extractEffectiveRules, + runStableReleaseGuard, +} from "./stable-release-guard.mjs"; + +const headSha = "1".repeat(40); +const mergeSha = "2".repeat(40); + +function releaseEvent(overrides = {}) { + return { + action: "closed", + pull_request: { + number: 42, + merged: true, + base: { ref: "main" }, + head: { ref: "release/v1.2.3", sha: headSha }, + merge_commit_sha: mergeSha, + user: { login: "release-author" }, + }, + ...overrides, + }; +} + +function pull(overrides = {}) { + return { + number: 42, + merged: true, + base: { ref: "main" }, + head: { ref: "release/v1.2.3", sha: headSha }, + merge_commit_sha: mergeSha, + user: { login: "release-author" }, + ...overrides, + }; +} + +function review(overrides = {}) { + return { + id: 1, + user: { login: "reviewer" }, + state: "APPROVED", + commit_id: headSha, + submitted_at: "2026-08-23T18:00:00Z", + ...overrides, + }; +} + +const requiredChecks = [ + { context: "Build", integrationId: 15368 }, + { context: "Test", integrationId: 15368 }, +]; + +function check(name, overrides = {}) { + return { + id: name === "Build" ? 100 : 200, + name, + app: { id: 15368 }, + status: "completed", + conclusion: "success", + started_at: "2026-08-23T18:00:00Z", + completed_at: "2026-08-23T18:01:00Z", + details_url: "https://github.com/heygen-com/hyperframes/actions/runs/99/job/1", + ...overrides, + }; +} + +describe("immutable stable release identity", () => { + it("accepts one exact merged release PR identity", () => { + assert.doesNotThrow(() => + assertImmutableRelease({ + event: releaseEvent(), + apiPull: pull(), + expectedSha: mergeSha, + githubSha: mergeSha, + checkoutSha: mergeSha, + version: "1.2.3", + }), + ); + }); + + it("rejects non-merged, wrong-base, wrong-branch, and any SHA/version mismatch", () => { + const base = { + event: releaseEvent(), + apiPull: pull(), + expectedSha: mergeSha, + githubSha: mergeSha, + checkoutSha: mergeSha, + version: "1.2.3", + }; + for (const mutation of [ + { event: releaseEvent({ action: "opened" }) }, + { apiPull: pull({ merged: false }) }, + { apiPull: pull({ base: { ref: "next" } }) }, + { apiPull: pull({ head: { ref: "feature/not-release", sha: headSha } }) }, + { expectedSha: "3".repeat(40) }, + { githubSha: "3".repeat(40) }, + { checkoutSha: "3".repeat(40) }, + { version: "1.2.4" }, + ]) { + assert.throws( + () => assertImmutableRelease({ ...base, ...mutation }), + /release|mismatch|merged|main/i, + ); + } + }); +}); + +describe("effective final-head approvals", () => { + it("requires the ruleset count of effective non-author final-head approvals", () => { + assert.deepEqual( + collectEffectiveApprovals({ + reviews: [review(), review({ id: 2, user: { login: "second" } })], + authorLogin: "release-author", + headSha, + requiredCount: 2, + }), + ["reviewer", "second"], + ); + }); + + it("fails zero, author-only, old-head, dismissed, and later change-requested reviews", () => { + for (const reviews of [ + [], + [review({ user: { login: "release-author" } })], + [review({ commit_id: "0".repeat(40) })], + [review(), review({ id: 2, state: "DISMISSED", submitted_at: "2026-08-23T18:02:00Z" })], + [ + review(), + review({ id: 2, state: "CHANGES_REQUESTED", submitted_at: "2026-08-23T18:02:00Z" }), + ], + ]) { + assert.throws( + () => + collectEffectiveApprovals({ + reviews, + authorLogin: "release-author", + headSha, + requiredCount: 1, + }), + /approval/i, + ); + } + }); + + it("fails closed on malformed decisive review records", () => { + for (const malformed of [ + review({ id: "not-a-number" }), + review({ submitted_at: "not-a-date" }), + review({ user: {} }), + review({ commit_id: null }), + review({ state: "UNKNOWN" }), + ]) { + assert.throws( + () => + collectEffectiveApprovals({ + reviews: [malformed, review({ id: 99, user: { login: "valid" } })], + authorLogin: "release-author", + headSha, + requiredCount: 1, + }), + /malformed review/i, + ); + } + }); +}); + +// fallow-ignore-next-line unit-size +describe("latest required checks", () => { + it("accepts success, neutral, and skipped while ignoring irrelevant checks", () => { + const outcome = evaluateRequiredChecks({ + requiredChecks, + checkRuns: [ + check("Build"), + check("Test", { conclusion: "neutral" }), + check("Docs", { conclusion: "failure" }), + ], + currentRunId: "777", + }); + assert.equal(outcome.kind, "passing"); + }); + + it("uses only the newest attempt for duplicate contexts", () => { + for (const [newestStatus, newestConclusion, expectedKind] of [ + ["in_progress", null, "pending"], + ["completed", "failure", "terminal-failure"], + ["completed", "success", "passing"], + ]) { + const outcome = evaluateRequiredChecks({ + requiredChecks: [requiredChecks[0]], + checkRuns: [ + check("Build", { id: 1, started_at: "2026-08-23T18:00:00Z" }), + check("Build", { + id: 2, + status: newestStatus, + conclusion: newestConclusion, + started_at: "2026-08-23T18:02:00Z", + completed_at: newestStatus === "completed" ? "2026-08-23T18:03:00Z" : null, + }), + ], + currentRunId: "777", + }); + assert.equal(outcome.kind, expectedKind); + } + assert.equal( + evaluateRequiredChecks({ + requiredChecks: [requiredChecks[0]], + checkRuns: [ + check("Build", { id: 999, started_at: "2026-08-23T17:00:00Z" }), + check("Build", { id: 2, started_at: "2026-08-23T18:00:00Z" }), + ], + currentRunId: "777", + }).kind, + "passing", + ); + }); + + it("fails terminal conclusions and identifies missing, pending, and self-referential checks", () => { + for (const conclusion of [ + "failure", + "cancelled", + "timed_out", + "action_required", + "stale", + "startup_failure", + ]) { + assert.equal( + evaluateRequiredChecks({ + requiredChecks: [requiredChecks[0]], + checkRuns: [check("Build", { conclusion })], + currentRunId: "777", + }).kind, + "terminal-failure", + ); + } + assert.equal( + evaluateRequiredChecks({ requiredChecks, checkRuns: [], currentRunId: "777" }).kind, + "pending", + ); + assert.equal( + evaluateRequiredChecks({ + requiredChecks: [requiredChecks[0]], + checkRuns: [check("Build", { status: "queued", conclusion: null })], + currentRunId: "777", + }).kind, + "pending", + ); + assert.equal( + evaluateRequiredChecks({ + requiredChecks: [requiredChecks[0]], + checkRuns: [ + check("Build", { + details_url: "https://github.com/heygen-com/hyperframes/actions/runs/777/job/1", + }), + ], + currentRunId: "777", + }).kind, + "self-reference", + ); + }); +}); + +describe("effective repository rules", () => { + it("extracts required contexts with integration identity and the approval count", () => { + assert.deepEqual( + extractEffectiveRules([ + { + type: "required_status_checks", + parameters: { + required_status_checks: [ + { context: "Build", integration_id: 15368 }, + { context: "Test", integration_id: 15368 }, + ], + }, + }, + { + type: "pull_request", + parameters: { + required_approving_review_count: 2, + require_last_push_approval: true, + require_extra_approval_for_unattributed_changes: true, + }, + }, + { type: "required_signatures" }, + ]), + { + requiredApprovals: 2, + requiredChecks, + requireLastPushApproval: true, + requireExtraApprovalForUnattributedChanges: true, + requireSignedCommits: true, + }, + ); + }); + + it("fails closed for malformed or unsupported gate rules", () => { + assert.throws(() => extractEffectiveRules([]), /required status checks/i); + assert.throws( + () => extractEffectiveRules([{ type: "required_status_checks", parameters: {} }]), + /malformed/i, + ); + assert.throws(() => extractEffectiveRules([{ type: "required_deployments" }]), /unsupported/i); + }); +}); + +function fakeClient(checkResponses, overrides = {}) { + let index = 0; + return { + getPull: async () => pull(), + getRuleSuite: async () => ({ afterSha: mergeSha, ref: "refs/heads/main", result: "pass" }), + listReviews: async () => [review()], + getEffectiveRules: async () => ({ requiredApprovals: 1, requiredChecks }), + listCheckRuns: async () => checkResponses[Math.min(index++, checkResponses.length - 1)], + ...overrides, + }; +} + +// fallow-ignore-next-line unit-size +describe("stable release polling guard", () => { + it("passes all-green and pending-then-green cases", async () => { + for (const responses of [ + [[check("Build"), check("Test")]], + [ + [check("Build", { status: "queued", conclusion: null }), check("Test")], + [check("Build"), check("Test")], + ], + ]) { + let now = 0; + await assert.doesNotReject(() => + runStableReleaseGuard({ + event: releaseEvent(), + expectedSha: mergeSha, + githubSha: mergeSha, + checkoutSha: mergeSha, + version: "1.2.3", + currentRunId: "777", + client: fakeClient(responses), + now: () => now, + sleep: async (ms) => { + now += ms; + }, + timeoutMs: 100, + initialBackoffMs: 10, + maxBackoffMs: 20, + log: () => undefined, + }), + ); + } + }); + + it("fails closed for timeout, terminal failure, API error, approval failure, and immutable mismatch", async () => { + const pending = [check("Build", { status: "queued", conclusion: null }), check("Test")]; + const base = { + event: releaseEvent(), + expectedSha: mergeSha, + githubSha: mergeSha, + checkoutSha: mergeSha, + version: "1.2.3", + currentRunId: "777", + now: () => nowValue, + sleep: async (ms) => { + nowValue += ms; + }, + timeoutMs: 50, + initialBackoffMs: 10, + maxBackoffMs: 20, + log: () => undefined, + }; + let nowValue = 0; + await assert.rejects( + runStableReleaseGuard({ ...base, client: fakeClient([pending]) }), + /timed out/i, + ); + await assert.rejects( + runStableReleaseGuard({ + ...base, + client: fakeClient([[check("Build", { conclusion: "failure" }), check("Test")]]), + }), + /failed/i, + ); + await assert.rejects( + runStableReleaseGuard({ + ...base, + client: fakeClient([], { + getEffectiveRules: async () => { + throw new Error("API down"); + }, + }), + }), + /API down/, + ); + await assert.rejects( + runStableReleaseGuard({ + ...base, + client: fakeClient([], { listReviews: async () => [] }), + }), + /approval/i, + ); + await assert.rejects( + runStableReleaseGuard({ + ...base, + githubSha: "3".repeat(40), + client: fakeClient([[check("Build"), check("Test")]]), + }), + /mismatch/i, + ); + await assert.rejects( + runStableReleaseGuard({ + ...base, + client: fakeClient([[check("Build"), check("Test")]], { + getRuleSuite: async () => ({ + afterSha: mergeSha, + ref: "refs/heads/main", + result: "bypass", + }), + }), + }), + /rule suite.*bypass/i, + ); + }); + + it("clamps every wait and API request to the hard deadline", async () => { + let nowValue = 0; + const sleeps = []; + const requestBudgets = []; + const client = fakeClient( + [[check("Build", { status: "queued", conclusion: null }), check("Test")]], + { + listCheckRuns: async (_sha, budget) => { + requestBudgets.push(budget); + return [check("Build", { status: "queued", conclusion: null }), check("Test")]; + }, + }, + ); + await assert.rejects( + runStableReleaseGuard({ + event: releaseEvent(), + expectedSha: mergeSha, + githubSha: mergeSha, + checkoutSha: mergeSha, + version: "1.2.3", + currentRunId: "777", + client, + now: () => nowValue, + sleep: async (ms) => { + sleeps.push(ms); + nowValue += ms; + }, + timeoutMs: 25, + initialBackoffMs: 20, + maxBackoffMs: 30, + log: () => undefined, + }), + /timed out/i, + ); + assert.deepEqual(sleeps, [20, 5]); + assert.ok(requestBudgets.every((budget) => budget > 0 && budget <= 25)); + }); +});