Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

ci: reconcile spec owner events safely (#5731)

Cindy Zhang1f1809fd1329
diff --git a/.github/scripts/spec-owner-decision.cjs b/.github/scripts/spec-owner-decision.cjs
index ea70e62d02..83672fea62 100644
--- a/.github/scripts/spec-owner-decision.cjs
+++ b/.github/scripts/spec-owner-decision.cjs
@@ -11,6 +11,10 @@ const {
} = require('./knowledge-frontmatter.cjs');
/* eslint-enable @typescript-eslint/no-require-imports */
+const GATE_STATUS_CONTEXT = 'spec-owner-approval';
+const READY_STATUS_PREFIX = 'spec-owner-ready/';
+const TRUSTED_STATUS_CREATOR = 'github-actions[bot]';
+
function parseOwnerCommand(body, headSha) {
const match = body
.trim()
@@ -19,18 +23,66 @@ function parseOwnerCommand(body, headSha) {
return match[1].toLowerCase() === 'approve';
}
-function resolveOwnerDecision({reviews, comments, owners, headSha}) {
+function candidateTime(candidate) {
+ const value = Date.parse(candidate.at);
+ return Number.isNaN(value) ? Number.NEGATIVE_INFINITY : value;
+}
+
+function candidatePriority(candidate) {
+ if (candidate.approved === false || candidate.approved === null) return 2;
+ return candidate.source === 'ready' ? 0 : 1;
+}
+
+function latestDismissalAt(review, dismissalEvents) {
+ const timestamps = [review.updated_at];
+ for (const event of dismissalEvents) {
+ if (
+ event.event === 'review_dismissed' &&
+ event.dismissed_review?.review_id === review.id
+ ) {
+ timestamps.push(event.created_at);
+ }
+ }
+ return timestamps
+ .filter(Boolean)
+ .sort((left, right) => Date.parse(right) - Date.parse(left))[0];
+}
+
+function resolveOwnerDecision({
+ reviews,
+ comments,
+ readyAttestations = [],
+ dismissalEvents = [],
+ owners,
+ headSha,
+}) {
const allowed = new Set(owners.map(owner => owner.toLowerCase()));
const latestByOwner = new Map();
function consider(login, candidate) {
- if (!allowed.has(login)) return;
- const previous = latestByOwner.get(login);
- if (!previous || new Date(candidate.at) > new Date(previous.at)) {
- latestByOwner.set(login, candidate);
+ const normalizedLogin = login.toLowerCase();
+ if (!allowed.has(normalizedLogin) || !candidate.at) return;
+ const normalizedCandidate = {...candidate, owner: normalizedLogin};
+ const previous = latestByOwner.get(normalizedLogin);
+ if (
+ !previous ||
+ candidateTime(normalizedCandidate) > candidateTime(previous) ||
+ (candidateTime(normalizedCandidate) === candidateTime(previous) &&
+ candidatePriority(normalizedCandidate) > candidatePriority(previous))
+ ) {
+ latestByOwner.set(normalizedLogin, normalizedCandidate);
}
}
+ for (const attestation of readyAttestations) {
+ if (attestation.headSha !== headSha) continue;
+ consider(attestation.owner, {
+ approved: true,
+ at: attestation.at,
+ source: 'ready',
+ });
+ }
+
for (const review of reviews) {
const login = review.user?.login?.toLowerCase();
if (!login || review.commit_id !== headSha) continue;
@@ -39,6 +91,10 @@ function resolveOwnerDecision({reviews, comments, owners, headSha}) {
) {
continue;
}
+ const dismissedAt =
+ review.state === 'DISMISSED'
+ ? latestDismissalAt(review, dismissalEvents)
+ : null;
consider(login, {
approved:
review.state === 'APPROVED'
@@ -46,9 +102,12 @@ function resolveOwnerDecision({reviews, comments, owners, headSha}) {
: review.state === 'CHANGES_REQUESTED'
? false
: null,
- at: review.submitted_at ?? review.updated_at ?? review.created_at,
- source: 'review',
- owner: login,
+ at:
+ dismissedAt ??
+ review.submitted_at ??
+ review.updated_at ??
+ review.created_at,
+ source: review.state === 'DISMISSED' ? 'dismissal' : 'review',
});
}
@@ -61,7 +120,6 @@ function resolveOwnerDecision({reviews, comments, owners, headSha}) {
approved,
at: comment.created_at,
source: 'command',
- owner: login,
});
}
@@ -78,6 +136,78 @@ function resolveOwnerDecision({reviews, comments, owners, headSha}) {
);
}
+function canonicalRunUrl(repository, runId, runAttempt) {
+ return `https://github.com/${repository}/actions/runs/${runId}/attempts/${runAttempt}`;
+}
+
+function parseCanonicalRunId(targetUrl, repository) {
+ if (typeof targetUrl !== 'string') return null;
+ const prefix = `https://github.com/${repository}/actions/runs/`;
+ if (!targetUrl.startsWith(prefix)) return null;
+ const match = targetUrl
+ .slice(prefix.length)
+ .match(/^([1-9][0-9]*)\/attempts\/[1-9][0-9]*$/);
+ if (!match) return null;
+ try {
+ return BigInt(match[1]);
+ } catch {
+ return null;
+ }
+}
+
+function isTrustedWorkflowStatus(status, repository) {
+ return (
+ status.creator?.login === TRUSTED_STATUS_CREATOR &&
+ parseCanonicalRunId(status.target_url, repository) !== null
+ );
+}
+
+function parseReadyAttestations(statuses, {repository, headSha}) {
+ const attestations = [];
+ for (const status of statuses) {
+ if (
+ status.state !== 'success' ||
+ !status.context?.startsWith(READY_STATUS_PREFIX) ||
+ !isTrustedWorkflowStatus(status, repository)
+ ) {
+ continue;
+ }
+ const owner = status.context
+ .slice(READY_STATUS_PREFIX.length)
+ .toLowerCase();
+ if (!/^[a-z0-9-]+$/.test(owner)) continue;
+ const match = status.description?.match(
+ /^Owner ready at (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z)\.$/,
+ );
+ if (!match || Number.isNaN(Date.parse(match[1]))) continue;
+ attestations.push({
+ approved: true,
+ at: match[1],
+ headSha,
+ owner,
+ source: 'ready',
+ });
+ }
+ return attestations;
+}
+
+function newestGateRun(statuses, repository) {
+ let newest = null;
+ for (const status of statuses) {
+ if (
+ status.context !== GATE_STATUS_CONTEXT ||
+ !isTrustedWorkflowStatus(status, repository)
+ ) {
+ continue;
+ }
+ const runId = parseCanonicalRunId(status.target_url, repository);
+ if (newest === null || runId > newest.runId) {
+ newest = {runId, status};
+ }
+ }
+ return newest;
+}
+
function isDesignVersion(content, filePath) {
return parseKind(content, filePath) === 'design';
}
@@ -109,11 +239,17 @@ function requiresOwnerApproval(records, options = {}) {
}
module.exports = {
+ GATE_STATUS_CONTEXT,
+ READY_STATUS_PREFIX,
+ canonicalRunUrl,
+ newestGateRun,
parseAuthority,
+ parseCanonicalRunId,
parseKind,
+ parseOwnerCommand,
parseOwnerFile,
+ parseReadyAttestations,
requiredApprovalGroups,
requiresOwnerApproval,
- parseOwnerCommand,
resolveOwnerDecision,
};
diff --git a/.github/scripts/spec-owner-decision.test.mjs b/.github/scripts/spec-owner-decision.test.mjs
index 0ff71391b4..dc5fd21866 100644
--- a/.github/scripts/spec-owner-decision.test.mjs
+++ b/.github/scripts/spec-owner-decision.test.mjs
@@ -5,8 +5,12 @@ import {describe, expect, it} from 'vitest';
const require = createRequire(import.meta.url);
const {
+ canonicalRunUrl,
+ newestGateRun,
+ parseCanonicalRunId,
parseOwnerCommand,
parseOwnerFile,
+ parseReadyAttestations,
requiredApprovalGroups,
resolveOwnerDecision,
} = require('./spec-owner-decision.cjs');
@@ -264,4 +268,167 @@ describe('spec owner decision', () => {
});
expect(decision.approved).toBe(false);
});
+
+ it('accepts only trusted workflow ready attestations', () => {
+ const repository = 'facebook/astryx';
+ const trusted = {
+ context: 'spec-owner-ready/cixzhang',
+ state: 'success',
+ description: 'Owner ready at 2026-08-30T10:00:00.000Z.',
+ target_url: canonicalRunUrl(repository, '9007199254740993', '2'),
+ creator: {login: 'github-actions[bot]'},
+ };
+ const attestations = parseReadyAttestations(
+ [
+ trusted,
+ {...trusted, creator: {login: 'cixzhang'}},
+ {...trusted, target_url: 'https://example.com/forged'},
+ {...trusted, description: 'owner says ready'},
+ ],
+ {repository, headSha: head},
+ );
+
+ expect(attestations).toEqual([
+ {
+ approved: true,
+ at: '2026-08-30T10:00:00.000Z',
+ headSha: head,
+ owner: 'cixzhang',
+ source: 'ready',
+ },
+ ]);
+ expect(
+ resolveOwnerDecision({
+ owners: ['cixzhang'],
+ headSha: head,
+ reviews: [],
+ comments: [],
+ readyAttestations: attestations,
+ }),
+ ).toMatchObject({approved: true, owner: 'cixzhang', source: 'ready'});
+ });
+
+ it('invalidates a ready attestation on a new head', () => {
+ const decision = resolveOwnerDecision({
+ owners: ['cixzhang'],
+ headSha: '1111111111111111111111111111111111111111',
+ reviews: [],
+ comments: [],
+ readyAttestations: [
+ {
+ owner: 'cixzhang',
+ headSha: head,
+ at: '2026-08-30T10:00:00Z',
+ },
+ ],
+ });
+
+ expect(decision.approved).toBe(false);
+ });
+
+ it('lets a newer exact-head revoke override owner-ready', () => {
+ const decision = resolveOwnerDecision({
+ owners: ['cixzhang'],
+ headSha: head,
+ reviews: [],
+ readyAttestations: [
+ {
+ owner: 'cixzhang',
+ headSha: head,
+ at: '2026-08-30T10:00:00Z',
+ },
+ ],
+ comments: [
+ {
+ user: owner,
+ body: `/revoke-spec ${head}`,
+ created_at: '2026-08-30T10:01:00Z',
+ },
+ ],
+ });
+
+ expect(decision).toMatchObject({
+ approved: false,
+ owner: 'cixzhang',
+ source: 'command',
+ });
+ });
+
+ it('orders dismissal by updated_at instead of the original submission', () => {
+ const decision = resolveOwnerDecision({
+ owners: ['cixzhang'],
+ headSha: head,
+ comments: [],
+ readyAttestations: [
+ {
+ owner: 'cixzhang',
+ headSha: head,
+ at: '2026-08-30T10:01:00Z',
+ },
+ ],
+ reviews: [
+ {
+ id: 17,
+ user: owner,
+ state: 'DISMISSED',
+ commit_id: head,
+ submitted_at: '2026-08-30T09:00:00Z',
+ updated_at: '2026-08-30T10:02:00Z',
+ },
+ ],
+ });
+
+ expect(decision.approved).toBe(false);
+ expect(decision.source).toBe(null);
+ });
+
+ it('uses review_dismissed timeline time when it is newer', () => {
+ const decision = resolveOwnerDecision({
+ owners: ['cixzhang'],
+ headSha: head,
+ comments: [],
+ readyAttestations: [
+ {
+ owner: 'cixzhang',
+ headSha: head,
+ at: '2026-08-30T10:01:00Z',
+ },
+ ],
+ reviews: [
+ {
+ id: 17,
+ user: owner,
+ state: 'DISMISSED',
+ commit_id: head,
+ submitted_at: '2026-08-30T09:00:00Z',
+ updated_at: '2026-08-30T09:30:00Z',
+ },
+ ],
+ dismissalEvents: [
+ {
+ event: 'review_dismissed',
+ created_at: '2026-08-30T10:02:00Z',
+ dismissed_review: {review_id: 17},
+ },
+ ],
+ });
+
+ expect(decision.approved).toBe(false);
+ });
+
+ it('compares workflow run ids without losing integer precision', () => {
+ const repository = 'facebook/astryx';
+ const statuses = ['9007199254740992', '9007199254740993'].map(runId => ({
+ context: 'spec-owner-approval',
+ state: 'pending',
+ description: `Run ${runId}`,
+ target_url: canonicalRunUrl(repository, runId, '1'),
+ creator: {login: 'github-actions[bot]'},
+ }));
+
+ expect(parseCanonicalRunId(statuses[1].target_url, repository)).toBe(
+ 9007199254740993n,
+ );
+ expect(newestGateRun(statuses, repository)?.runId).toBe(9007199254740993n);
+ });
});
diff --git a/.github/scripts/spec-owner-reconcile.cjs b/.github/scripts/spec-owner-reconcile.cjs
new file mode 100644
index 0000000000..e71ec3152f
--- /dev/null
+++ b/.github/scripts/spec-owner-reconcile.cjs
@@ -0,0 +1,532 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use strict';
+/* global Buffer, module, process, require */
+
+/* eslint-disable @typescript-eslint/no-require-imports */
+const fs = require('node:fs');
+const path = require('node:path');
+const {classifyChanges} = require('./change-scope.cjs');
+const {
+ GATE_STATUS_CONTEXT,
+ READY_STATUS_PREFIX,
+ canonicalRunUrl,
+ newestGateRun,
+ parseOwnerCommand,
+ parseOwnerFile,
+ parseReadyAttestations,
+ requiredApprovalGroups,
+ resolveOwnerDecision,
+} = require('./spec-owner-decision.cjs');
+/* eslint-enable @typescript-eslint/no-require-imports */
+
+function isCommandComment(eventName, payload) {
+ if (eventName !== 'issue_comment') return true;
+ return /^\/(approve|revoke)-spec [0-9a-f]{40}$/i.test(
+ payload.comment?.body?.trim() ?? '',
+ );
+}
+
+function isAuthorizedEvent(eventName, payload, owners) {
+ if (eventName === 'issue_comment') {
+ const login = payload.comment?.user?.login?.toLowerCase();
+ return Boolean(
+ login && owners.has(login) && isCommandComment(eventName, payload),
+ );
+ }
+ if (eventName === 'pull_request_review') {
+ const login = payload.review?.user?.login?.toLowerCase();
+ return Boolean(login && owners.has(login));
+ }
+ return true;
+}
+
+function labelNames(pr) {
+ return new Set(pr.labels.map(label => label.name));
+}
+
+async function reconcileSpecOwnerGate({
+ github,
+ context,
+ core,
+ workspace = process.env.GITHUB_WORKSPACE,
+ env = process.env,
+}) {
+ const specOwners = env.SPEC_OWNERS.split(',').map(ownerName =>
+ ownerName.toLowerCase(),
+ );
+ const designOwners = parseOwnerFile(
+ fs.readFileSync(path.join(workspace, '.github/DESIGNOWNERS'), 'utf8'),
+ );
+ const allOwners = new Set([...specOwners, ...designOwners]);
+ if (!isAuthorizedEvent(context.eventName, context.payload, allOwners)) {
+ core.info('Ignoring an event from someone outside the eligible owners.');
+ return;
+ }
+
+ const {owner, repo} = context.repo;
+ const repository = `${owner}/${repo}`;
+ const pullNumber = Number(
+ context.payload.pull_request?.number ??
+ context.payload.issue?.number ??
+ context.payload.inputs?.pr,
+ );
+ if (!pullNumber) {
+ throw new Error('Could not resolve a pull request number.');
+ }
+
+ const runId = BigInt(String(context.runId));
+ const runUrl = canonicalRunUrl(
+ repository,
+ String(context.runId),
+ String(context.runAttempt),
+ );
+
+ async function getPullRequest() {
+ const {data} = await github.rest.pulls.get({
+ owner,
+ repo,
+ pull_number: pullNumber,
+ });
+ return data;
+ }
+
+ async function listStatuses(headSha) {
+ return github.paginate(github.rest.repos.listCommitStatusesForRef, {
+ owner,
+ repo,
+ ref: headSha,
+ per_page: 100,
+ });
+ }
+
+ async function createStatus({
+ sha,
+ context: statusContext,
+ state,
+ description,
+ targetUrl = runUrl,
+ }) {
+ await github.rest.repos.createCommitStatus({
+ owner,
+ repo,
+ sha,
+ context: statusContext,
+ state,
+ description: description.slice(0, 140),
+ target_url: targetUrl,
+ });
+ }
+
+ async function newestRun(headSha) {
+ return newestGateRun(await listStatuses(headSha), repository);
+ }
+
+ async function restoreNewerStatus(headSha) {
+ const newest = await newestRun(headSha);
+ if (newest === null || newest.runId <= runId) return false;
+ await createStatus({
+ sha: headSha,
+ context: GATE_STATUS_CONTEXT,
+ state: newest.status.state,
+ description: newest.status.description,
+ targetUrl: newest.status.target_url,
+ });
+ core.info(
+ `Run ${context.runId} yielded to newer run ${newest.runId.toString()}.`,
+ );
+ return true;
+ }
+
+ async function isCurrentRun(headSha) {
+ const newest = await newestRun(headSha);
+ return newest === null || newest.runId <= runId;
+ }
+
+ async function setFinalStatus(headSha, state, description) {
+ if (!(await isCurrentRun(headSha))) return false;
+ await createStatus({
+ sha: headSha,
+ context: GATE_STATUS_CONTEXT,
+ state,
+ description,
+ });
+ return !(await restoreNewerStatus(headSha));
+ }
+
+ async function removeLabel(name) {
+ try {
+ await github.rest.issues.removeLabel({
+ owner,
+ repo,
+ issue_number: pullNumber,
+ name,
+ });
+ } catch (error) {
+ if (error.status !== 404) throw error;
+ }
+ }
+
+ async function ensureLabel(pr, name, color, description) {
+ try {
+ await github.rest.issues.getLabel({owner, repo, name});
+ } catch (error) {
+ if (error.status !== 404) throw error;
+ try {
+ await github.rest.issues.createLabel({
+ owner,
+ repo,
+ name,
+ color,
+ description,
+ });
+ } catch (createError) {
+ if (createError.status !== 422) throw createError;
+ }
+ }
+ if (!labelNames(pr).has(name)) {
+ await github.rest.issues.addLabels({
+ owner,
+ repo,
+ issue_number: pullNumber,
+ labels: [name],
+ });
+ }
+ }
+
+ async function disableAutoMerge(pr, {requireOwnership = true} = {}) {
+ if (requireOwnership && !labelNames(pr).has(env.AUTO_MERGE_LABEL)) {
+ return;
+ }
+ if (pr.auto_merge) {
+ await github.graphql(
+ `mutation($id: ID!) {
+ disablePullRequestAutoMerge(input: {pullRequestId: $id}) {
+ pullRequest { number }
+ }
+ }`,
+ {id: pr.node_id},
+ );
+ }
+ await removeLabel(env.AUTO_MERGE_LABEL);
+ }
+
+ async function readText(fullName, ref, filePath) {
+ const [repoOwner, repoName] = fullName.split('/');
+ try {
+ const {data} = await github.rest.repos.getContent({
+ owner: repoOwner,
+ repo: repoName,
+ path: filePath,
+ ref,
+ });
+ if (Array.isArray(data) || !data.content) {
+ throw new Error(
+ `Knowledge record ${filePath} could not be read as text.`,
+ );
+ }
+ return Buffer.from(data.content, 'base64').toString('utf8');
+ } catch (error) {
+ if (error.status === 404) return null;
+ throw error;
+ }
+ }
+
+ async function fetchSnapshot() {
+ const before = await getPullRequest();
+ const headSha = before.head.sha;
+ const [files, reviews, comments, timeline, statuses] = await Promise.all([
+ github.paginate(github.rest.pulls.listFiles, {
+ owner,
+ repo,
+ pull_number: pullNumber,
+ per_page: 100,
+ }),
+ github.paginate(github.rest.pulls.listReviews, {
+ owner,
+ repo,
+ pull_number: pullNumber,
+ per_page: 100,
+ }),
+ github.paginate(github.rest.issues.listComments, {
+ owner,
+ repo,
+ issue_number: pullNumber,
+ per_page: 100,
+ }),
+ github.paginate(github.rest.issues.listEventsForTimeline, {
+ owner,
+ repo,
+ issue_number: pullNumber,
+ per_page: 100,
+ }),
+ listStatuses(headSha),
+ ]);
+ const after = await getPullRequest();
+ if (after.head.sha !== headSha) return null;
+
+ const scope = classifyChanges(files, {expectedCount: after.changed_files});
+ const knowledgeChanges = files.filter(
+ file =>
+ scope.complete &&
+ (classifyChanges([{filename: file.filename}]).touchesKnowledgeRecords ||
+ (file.previous_filename &&
+ classifyChanges([{filename: file.previous_filename}])
+ .touchesKnowledgeRecords)),
+ );
+ const records = await Promise.all(
+ knowledgeChanges.map(async file => {
+ const previousPath = file.previous_filename || file.filename;
+ const baseIsTextRecord = previousPath.endsWith('.md');
+ const headIsTextRecord = file.filename.endsWith('.md');
+ return {
+ path: file.filename,
+ previousPath,
+ baseContent:
+ !baseIsTextRecord || file.status === 'added'
+ ? null
+ : await readText(
+ after.base.repo.full_name,
+ after.base.sha,
+ previousPath,
+ ),
+ headContent:
+ !headIsTextRecord || file.status === 'removed'
+ ? null
+ : await readText(
+ after.head.repo.full_name,
+ after.head.sha,
+ file.filename,
+ ),
+ };
+ }),
+ );
+ const latest = await getPullRequest();
+ if (latest.head.sha !== headSha) return null;
+ return {
+ pr: latest,
+ files,
+ reviews,
+ comments,
+ timeline,
+ statuses,
+ scope,
+ records,
+ };
+ }
+
+ const initialPr = await getPullRequest();
+ const initialHead = initialPr.head.sha;
+ await createStatus({
+ sha: initialHead,
+ context: GATE_STATUS_CONTEXT,
+ state: 'pending',
+ description: `Reconciling exact head ${initialHead.slice(0, 7)}.`,
+ });
+ if (await restoreNewerStatus(initialHead)) return;
+
+ const actor = context.actor?.toLowerCase();
+ const eventHead = context.payload.pull_request?.head?.sha;
+ const eventTime = context.payload.pull_request?.updated_at;
+ if (
+ context.eventName === 'pull_request_target' &&
+ context.payload.action === 'ready_for_review' &&
+ actor &&
+ actor === initialPr.user.login.toLowerCase() &&
+ allOwners.has(actor) &&
+ eventHead === initialHead &&
+ eventTime &&
+ !Number.isNaN(Date.parse(eventTime))
+ ) {
+ await createStatus({
+ sha: initialHead,
+ context: `${READY_STATUS_PREFIX}${actor}`,
+ state: 'success',
+ description: `Owner ready at ${new Date(eventTime).toISOString()}.`,
+ });
+ }
+
+ const commentAuthor = context.payload.comment?.user?.login?.toLowerCase();
+ const reviewAuthor = context.payload.review?.user?.login?.toLowerCase();
+ const explicitRevoke =
+ context.eventName === 'issue_comment' &&
+ commentAuthor &&
+ allOwners.has(commentAuthor) &&
+ parseOwnerCommand(context.payload.comment.body ?? '', initialHead) ===
+ false;
+ const currentReviewDismissal =
+ context.eventName === 'pull_request_review' &&
+ context.payload.action === 'dismissed' &&
+ reviewAuthor &&
+ allOwners.has(reviewAuthor) &&
+ context.payload.review.commit_id === initialHead;
+ if (explicitRevoke || currentReviewDismissal) {
+ await disableAutoMerge(initialPr);
+ }
+
+ const snapshot = await fetchSnapshot();
+ if (snapshot === null || snapshot.pr.head.sha !== initialHead) {
+ core.info(
+ 'The pull request head changed while this run was reading state.',
+ );
+ return;
+ }
+ if (!(await isCurrentRun(initialHead))) {
+ core.info(`Run ${context.runId} yielded before mutation.`);
+ return;
+ }
+
+ const {pr, scope, records, reviews, comments, timeline, statuses} = snapshot;
+ if (!scope.touchesKnowledgeRecords) {
+ await disableAutoMerge(pr);
+ await removeLabel(env.REVIEW_LABEL);
+ await setFinalStatus(
+ initialHead,
+ 'success',
+ 'No knowledge records changed.',
+ );
+ return;
+ }
+
+ if (scope.specOnly) {
+ await createStatus({
+ sha: initialHead,
+ context: 'visual-acceptance',
+ state: 'success',
+ description: 'Spec-only change — no visual scope.',
+ });
+ }
+
+ const requiredGroups = requiredApprovalGroups(records, {
+ complete: scope.complete,
+ touchesDesignAssets: scope.touchesDesignAssets,
+ });
+ const ownerApprovalRequired = requiredGroups.spec || requiredGroups.design;
+ if (requiredGroups.design && designOwners.length === 0) {
+ throw new Error('No DESIGNOWNERS are configured.');
+ }
+ const designApprovers = [...new Set([...specOwners, ...designOwners])];
+ const readyAttestations = parseReadyAttestations(statuses, {
+ repository,
+ headSha: initialHead,
+ });
+ const decisionInput = {
+ reviews,
+ comments,
+ readyAttestations,
+ dismissalEvents: timeline,
+ headSha: initialHead,
+ };
+ const specDecision = requiredGroups.spec
+ ? resolveOwnerDecision({...decisionInput, owners: specOwners})
+ : {approved: true, owner: null};
+ const designDecision = requiredGroups.design
+ ? resolveOwnerDecision({...decisionInput, owners: designApprovers})
+ : {approved: true, owner: null};
+ const approved = specDecision.approved && designDecision.approved;
+ const approvingOwners = [specDecision.owner, designDecision.owner]
+ .filter(Boolean)
+ .filter((ownerName, index, owners) => owners.indexOf(ownerName) === index);
+ const requiredOwnerDescription = [
+ requiredGroups.spec ? `a spec owner (${specOwners.join(',')})` : null,
+ requiredGroups.design
+ ? `a design approver (${designApprovers.join(',')})`
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' and ');
+
+ if (ownerApprovalRequired && !approved) {
+ await disableAutoMerge(pr);
+ if (!(await isCurrentRun(initialHead))) return;
+ await ensureLabel(
+ pr,
+ env.REVIEW_LABEL,
+ 'd4c5f9',
+ 'Current knowledge records await owner approval',
+ );
+ await setFinalStatus(
+ initialHead,
+ 'pending',
+ `Waiting for ${requiredOwnerDescription} on ${initialHead.slice(0, 7)}.`,
+ );
+ return;
+ }
+
+ if (pr.draft) {
+ await disableAutoMerge(pr);
+ if (!(await isCurrentRun(initialHead))) return;
+ await removeLabel(env.REVIEW_LABEL);
+ await setFinalStatus(
+ initialHead,
+ 'success',
+ 'Draft PR; owner gate is not blocking.',
+ );
+ return;
+ }
+
+ const successDescription = ownerApprovalRequired
+ ? `Approved by ${approvingOwners
+ .map(name => `@${name}`)
+ .join(' and ')} for ${initialHead.slice(0, 7)}.`
+ : 'Draft-only knowledge change; owner approval is not required.';
+
+ if (!scope.specOnly) {
+ await disableAutoMerge(pr);
+ if (!(await isCurrentRun(initialHead))) return;
+ await removeLabel(env.REVIEW_LABEL);
+ await setFinalStatus(initialHead, 'success', successDescription);
+ return;
+ }
+
+ let enabledAutoMergeByThisRun = false;
+ if (!pr.auto_merge) {
+ if (!(await isCurrentRun(initialHead))) return;
+ await ensureLabel(
+ pr,
+ env.AUTO_MERGE_LABEL,
+ 'bfdadc',
+ 'Auto-merge was enabled by the spec owner gate',
+ );
+ if (!(await isCurrentRun(initialHead))) return;
+ try {
+ await github.graphql(
+ `mutation($id: ID!, $oid: GitObjectID!) {
+ enablePullRequestAutoMerge(input: {
+ pullRequestId: $id,
+ mergeMethod: SQUASH,
+ expectedHeadOid: $oid
+ }) {
+ pullRequest { number }
+ }
+ }`,
+ {id: pr.node_id, oid: initialHead},
+ );
+ enabledAutoMergeByThisRun = true;
+ core.info(`Enabled squash auto-merge for spec-only PR #${pullNumber}.`);
+ } catch (error) {
+ core.warning(`Could not enable auto-merge: ${error.message}`);
+ return;
+ }
+ }
+
+ if (enabledAutoMergeByThisRun) {
+ const afterEnable = await newestRun(initialHead);
+ if (
+ afterEnable !== null &&
+ afterEnable.runId > runId &&
+ afterEnable.status.state !== 'success'
+ ) {
+ await disableAutoMerge(await getPullRequest(), {
+ requireOwnership: false,
+ });
+ return;
+ }
+ }
+
+ if (!(await isCurrentRun(initialHead))) return;
+ await removeLabel(env.REVIEW_LABEL);
+ await setFinalStatus(initialHead, 'success', successDescription);
+}
+
+module.exports = {isCommandComment, reconcileSpecOwnerGate};
diff --git a/.github/scripts/spec-owner-reconcile.test.mjs b/.github/scripts/spec-owner-reconcile.test.mjs
new file mode 100644
index 0000000000..06f427e17c
--- /dev/null
+++ b/.github/scripts/spec-owner-reconcile.test.mjs
@@ -0,0 +1,475 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/* global Buffer */
+
+import {createRequire} from 'node:module';
+import path from 'node:path';
+import {describe, expect, it} from 'vitest';
+
+const require = createRequire(import.meta.url);
+const {canonicalRunUrl} = require('./spec-owner-decision.cjs');
+const {
+ isCommandComment,
+ reconcileSpecOwnerGate,
+} = require('./spec-owner-reconcile.cjs');
+
+const head = 'abcdef1234567890abcdef1234567890abcdef12';
+const nextHead = '1111111111111111111111111111111111111111';
+const repository = 'facebook/astryx';
+const workspace = path.resolve(import.meta.dirname, '../..');
+const env = {
+ SPEC_OWNERS: 'cixzhang,imdreamrunner',
+ REVIEW_LABEL: 'needs:spec-owner-review',
+ AUTO_MERGE_LABEL: 'spec-auto-merge',
+};
+
+function context({
+ runId,
+ eventName = 'pull_request_target',
+ action = 'ready_for_review',
+ actor = 'cixzhang',
+ author = 'cixzhang',
+ headSha = head,
+ comment,
+ review,
+}) {
+ return {
+ actor,
+ eventName,
+ runId,
+ runAttempt: 1,
+ repo: {owner: 'facebook', repo: 'astryx'},
+ payload: {
+ action,
+ issue: eventName === 'issue_comment' ? {number: 17} : undefined,
+ comment,
+ review,
+ pull_request:
+ eventName === 'issue_comment'
+ ? undefined
+ : {
+ number: 17,
+ updated_at: '2026-08-30T10:00:00Z',
+ user: {login: author},
+ head: {sha: headSha},
+ },
+ },
+ };
+}
+
+function trustedStatus({
+ runId,
+ statusContext = 'spec-owner-approval',
+ state = 'pending',
+ description = 'Reconciling.',
+ sha = head,
+}) {
+ return {
+ sha,
+ context: statusContext,
+ state,
+ description,
+ target_url: canonicalRunUrl(repository, String(runId), '1'),
+ creator: {login: 'github-actions[bot]'},
+ created_at: '2026-08-30T10:00:00Z',
+ updated_at: '2026-08-30T10:00:00Z',
+ };
+}
+
+function createHarness({
+ author = 'cixzhang',
+ statuses = [],
+ comments = [],
+ reviews = [],
+ timeline = [],
+ labels = [],
+ autoMerge = null,
+ onPullGet,
+ onEnableAutoMerge,
+} = {}) {
+ const state = {
+ pullGets: 0,
+ statuses: [...statuses],
+ comments: [...comments],
+ reviews: [...reviews],
+ timeline: [...timeline],
+ calls: [],
+ labels: new Set(labels),
+ knownLabels: new Set(labels),
+ pr: {
+ number: 17,
+ node_id: 'PR_node',
+ user: {login: author},
+ head: {sha: head, repo: {full_name: repository}},
+ base: {
+ sha: '2222222222222222222222222222222222222222',
+ repo: {full_name: repository},
+ },
+ changed_files: 1,
+ labels: [],
+ auto_merge: autoMerge,
+ draft: false,
+ },
+ };
+
+ function syncLabels() {
+ state.pr.labels = [...state.labels].map(name => ({name}));
+ }
+ syncLabels();
+
+ const methods = {
+ getPull: async () => {
+ state.pullGets += 1;
+ onPullGet?.(state.pullGets, state);
+ syncLabels();
+ return {data: state.pr};
+ },
+ listFiles: async () => ({
+ data: [
+ {
+ filename: 'docs/specs/owner-ready/spec.md',
+ status: 'added',
+ },
+ ],
+ }),
+ listReviews: async () => ({data: state.reviews}),
+ listComments: async () => ({data: state.comments}),
+ listTimeline: async () => ({data: state.timeline}),
+ listStatuses: async ({ref}) => ({
+ data: state.statuses.filter(status => status.sha === ref),
+ }),
+ };
+
+ const github = {
+ paginate: async (method, options) => (await method(options)).data,
+ rest: {
+ pulls: {
+ get: methods.getPull,
+ listFiles: methods.listFiles,
+ listReviews: methods.listReviews,
+ },
+ issues: {
+ listComments: methods.listComments,
+ listEventsForTimeline: methods.listTimeline,
+ getLabel: async ({name}) => {
+ if (!state.knownLabels.has(name)) {
+ const error = new Error('Not found');
+ error.status = 404;
+ throw error;
+ }
+ return {data: {name}};
+ },
+ createLabel: async ({name}) => {
+ state.knownLabels.add(name);
+ state.calls.push(`create-label:${name}`);
+ },
+ addLabels: async ({labels: added}) => {
+ for (const name of added) state.labels.add(name);
+ syncLabels();
+ state.calls.push(`add-label:${added.join(',')}`);
+ },
+ removeLabel: async ({name}) => {
+ if (!state.labels.delete(name)) {
+ const error = new Error('Not found');
+ error.status = 404;
+ throw error;
+ }
+ syncLabels();
+ state.calls.push(`remove-label:${name}`);
+ },
+ },
+ repos: {
+ listCommitStatusesForRef: methods.listStatuses,
+ createCommitStatus: async input => {
+ const status = {
+ ...input,
+ creator: {login: 'github-actions[bot]'},
+ created_at: '2026-08-30T10:00:30Z',
+ updated_at: '2026-08-30T10:00:30Z',
+ };
+ state.statuses.unshift(status);
+ state.calls.push(`status:${input.context}:${input.state}`);
+ return {data: status};
+ },
+ getContent: async ({ref}) => ({
+ data: {
+ content: Buffer.from(
+ ref === state.pr.head.sha
+ ? 'kind: architecture\nauthority: current\n'
+ : '',
+ ).toString('base64'),
+ },
+ }),
+ },
+ },
+ graphql: async query => {
+ if (query.includes('enablePullRequestAutoMerge')) {
+ onEnableAutoMerge?.(state);
+ state.pr.auto_merge = {merge_method: 'squash'};
+ state.calls.push('enable-auto-merge');
+ } else if (query.includes('disablePullRequestAutoMerge')) {
+ state.pr.auto_merge = null;
+ state.calls.push('disable-auto-merge');
+ }
+ return {};
+ },
+ };
+ const core = {
+ info: message => state.calls.push(`info:${message}`),
+ warning: message => state.calls.push(`warning:${message}`),
+ };
+ return {github, core, state};
+}
+
+async function run(harness, runContext) {
+ await reconcileSpecOwnerGate({
+ github: harness.github,
+ context: runContext,
+ core: harness.core,
+ workspace,
+ env,
+ });
+}
+
+function latestGateStatus(state) {
+ return state.statuses.find(
+ status => status.context === 'spec-owner-approval',
+ );
+}
+
+describe('spec owner workflow reconciliation', () => {
+ it('treats an eligible owner-author ready event as exact-head approval', async () => {
+ const harness = createHarness();
+
+ await run(harness, context({runId: 100n}));
+
+ expect(
+ harness.state.statuses.some(
+ status => status.context === 'spec-owner-ready/cixzhang',
+ ),
+ ).toBe(true);
+ expect(latestGateStatus(harness.state).state).toBe('success');
+ expect(harness.state.calls).toContain('enable-auto-merge');
+ });
+
+ it('does not attest ready_for_review by a non-owner author', async () => {
+ const harness = createHarness({author: 'contributor'});
+
+ await run(
+ harness,
+ context({runId: 100n, actor: 'contributor', author: 'contributor'}),
+ );
+
+ expect(
+ harness.state.statuses.some(status =>
+ status.context.startsWith('spec-owner-ready/'),
+ ),
+ ).toBe(false);
+ expect(latestGateStatus(harness.state).state).toBe('pending');
+ expect(harness.state.calls).not.toContain('enable-auto-merge');
+ });
+
+ it('abandons the old event when the live head changes', async () => {
+ const harness = createHarness({
+ onPullGet: (count, state) => {
+ if (count === 2) state.pr.head.sha = nextHead;
+ },
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(harness.state.calls).not.toContain('enable-auto-merge');
+ expect(
+ harness.state.statuses.filter(
+ status =>
+ status.context === 'spec-owner-approval' && status.sha === head,
+ ),
+ ).toHaveLength(1);
+ });
+
+ it('disables gate-owned auto-merge before reconciling a later revoke', async () => {
+ const harness = createHarness();
+ await run(harness, context({runId: 100n}));
+ harness.state.comments.push({
+ user: {login: 'cixzhang'},
+ body: `/revoke-spec ${head}`,
+ created_at: '2026-08-30T10:01:00Z',
+ });
+
+ const beforeRevokeRun = harness.state.calls.length;
+ await run(
+ harness,
+ context({
+ runId: 101n,
+ eventName: 'issue_comment',
+ comment: harness.state.comments[0],
+ }),
+ );
+
+ const secondPending = harness.state.calls.findIndex(
+ (call, index) =>
+ index >= beforeRevokeRun &&
+ call === 'status:spec-owner-approval:pending',
+ );
+ const disabled = harness.state.calls.lastIndexOf('disable-auto-merge');
+ expect(disabled).toBeGreaterThan(secondPending);
+ expect(harness.state.pr.auto_merge).toBe(null);
+ expect(latestGateStatus(harness.state).state).toBe('pending');
+ });
+
+ it('undoes its own enable when a revoke supersedes it after the ownership label is removed', async () => {
+ const harness = createHarness({
+ onEnableAutoMerge: state => {
+ state.statuses.unshift(trustedStatus({runId: 101n}));
+ state.labels.delete('spec-auto-merge');
+ state.pr.labels = [];
+ state.calls.push('interleaved-revoke');
+ },
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(harness.state.calls).toEqual(
+ expect.arrayContaining([
+ 'interleaved-revoke',
+ 'enable-auto-merge',
+ 'disable-auto-merge',
+ ]),
+ );
+ expect(harness.state.calls.indexOf('interleaved-revoke')).toBeLessThan(
+ harness.state.calls.indexOf('enable-auto-merge'),
+ );
+ expect(harness.state.calls.indexOf('enable-auto-merge')).toBeLessThan(
+ harness.state.calls.indexOf('disable-auto-merge'),
+ );
+ expect(harness.state.labels.has('spec-auto-merge')).toBe(false);
+ expect(harness.state.pr.auto_merge).toBe(null);
+ });
+
+ it('uses dismissal ordering and immediately disables owned auto-merge', async () => {
+ const ready = trustedStatus({
+ runId: 90n,
+ statusContext: 'spec-owner-ready/cixzhang',
+ state: 'success',
+ description: 'Owner ready at 2026-08-30T10:01:00.000Z.',
+ });
+ const review = {
+ id: 17,
+ user: {login: 'cixzhang'},
+ state: 'DISMISSED',
+ commit_id: head,
+ submitted_at: '2026-08-30T09:00:00Z',
+ updated_at: '2026-08-30T10:02:00Z',
+ };
+ const harness = createHarness({
+ statuses: [ready],
+ reviews: [review],
+ timeline: [
+ {
+ event: 'review_dismissed',
+ created_at: '2026-08-30T10:02:00Z',
+ dismissed_review: {review_id: 17},
+ },
+ ],
+ labels: ['spec-auto-merge'],
+ autoMerge: {merge_method: 'squash'},
+ });
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ eventName: 'pull_request_review',
+ action: 'dismissed',
+ review,
+ }),
+ );
+
+ expect(harness.state.pr.auto_merge).toBe(null);
+ expect(latestGateStatus(harness.state).state).toBe('pending');
+ });
+
+ it('yields to a newer run id instead of applying stale approval', async () => {
+ const harness = createHarness({
+ statuses: [trustedStatus({runId: 101n, state: 'success'})],
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(harness.state.calls).not.toContain('enable-auto-merge');
+ expect(latestGateStatus(harness.state)).toMatchObject({
+ state: 'success',
+ target_url: canonicalRunUrl(repository, '101', '1'),
+ });
+ expect(
+ harness.state.calls.some(call => call.includes('yielded to newer run')),
+ ).toBe(true);
+ });
+
+ it('rejects valid-shaped non-owner commands before API work', async () => {
+ const harness = createHarness();
+ const comment = {
+ user: {login: 'contributor'},
+ body: `/approve-spec ${head}`,
+ created_at: '2026-08-30T10:00:00Z',
+ };
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ eventName: 'issue_comment',
+ actor: 'contributor',
+ comment,
+ }),
+ );
+
+ expect(harness.state.pullGets).toBe(0);
+ expect(harness.state.statuses).toEqual([]);
+ });
+
+ it('rejects non-owner reviews before API work', async () => {
+ const harness = createHarness();
+ const review = {
+ user: {login: 'contributor'},
+ state: 'APPROVED',
+ commit_id: head,
+ submitted_at: '2026-08-30T10:00:00Z',
+ };
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ eventName: 'pull_request_review',
+ action: 'submitted',
+ actor: 'contributor',
+ review,
+ }),
+ );
+
+ expect(harness.state.pullGets).toBe(0);
+ expect(harness.state.statuses).toEqual([]);
+ });
+
+ it('rejects ordinary comments before any API work', async () => {
+ const harness = createHarness();
+ const ordinaryComment = {
+ user: {login: 'contributor'},
+ body: 'Looks good to me',
+ };
+
+ expect(isCommandComment('issue_comment', {comment: ordinaryComment})).toBe(
+ false,
+ );
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ eventName: 'issue_comment',
+ comment: ordinaryComment,
+ }),
+ );
+ expect(harness.state.pullGets).toBe(0);
+ });
+});
diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjs
index 42d34353b8..b486cd08ec 100644
--- a/.github/scripts/spec-owner-workflow.test.mjs
+++ b/.github/scripts/spec-owner-workflow.test.mjs
@@ -13,12 +13,14 @@ describe('spec-only workflow contract', () => {
'.github/workflows/ci.yml',
'.github/workflows/lint.yml',
'.github/workflows/pr-comment.yml',
- '.github/workflows/spec-owner-gate.yml',
]) {
expect(read(workflow), workflow).toContain(
'.github/scripts/change-scope.cjs',
);
}
+ expect(read('.github/scripts/spec-owner-reconcile.cjs')).toContain(
+ "require('./change-scope.cjs')",
+ );
});
it('keeps required CI names green while skipping heavy work', () => {
@@ -50,29 +52,34 @@ describe('spec-only workflow contract', () => {
expect(prComment).toContain('files.length !== pr.changed_files');
});
- it('requires approval on the current head before squash auto-merge', () => {
+ it('runs the tested exact-head reconciler from the trusted default branch', () => {
const workflow = read('.github/workflows/spec-owner-gate.yml');
+ const reconciler = read('.github/scripts/spec-owner-reconcile.cjs');
expect(workflow).toContain(
'ref: ${{ github.event.repository.default_branch }}',
);
- expect(workflow).toContain('expectedCount: pr.changed_files');
- expect(workflow).toContain('scope.touchesKnowledgeRecords');
- expect(workflow).toContain('scope.touchesDesignAssets');
- expect(workflow).toContain('requiredApprovalGroups(records');
- expect(workflow).toContain("'.github/DESIGNOWNERS'");
- expect(workflow).toContain('designApprovers');
expect(workflow).toContain(
- 'specDecision.approved && designDecision.approved',
+ 'reconcileSpecOwnerGate({github, context, core})',
+ );
+ expect(workflow).not.toContain('concurrency:');
+ expect(workflow).toContain(
+ "startsWith(github.event.comment.body, '/approve-spec ')",
);
expect(workflow).toContain(
- 'Draft-only knowledge change; owner approval is not required.',
+ "startsWith(github.event.comment.body, '/revoke-spec ')",
+ );
+ expect(reconciler).toContain('expectedCount: after.changed_files');
+ expect(reconciler).toContain('scope.touchesKnowledgeRecords');
+ expect(reconciler).toContain('scope.touchesDesignAssets');
+ expect(reconciler).toContain('requiredApprovalGroups(records');
+ expect(reconciler).toContain("'.github/DESIGNOWNERS'");
+ expect(reconciler).toContain(
+ 'specDecision.approved && designDecision.approved',
);
- expect(workflow).toContain("context: 'spec-owner-approval'");
- expect(workflow).toContain('headSha: pr.head.sha');
- expect(workflow).toContain('expectedHeadOid: $oid');
- expect(workflow).toContain('mergeMethod: SQUASH');
- expect(workflow).toContain('disablePullRequestAutoMerge');
- expect(workflow).toContain('spec-auto-merge');
+ expect(reconciler).toContain('context: GATE_STATUS_CONTEXT');
+ expect(reconciler).toContain('expectedHeadOid: $oid');
+ expect(reconciler).toContain('mergeMethod: SQUASH');
+ expect(reconciler).toContain('disablePullRequestAutoMerge');
});
it('does not run the privileged visual-report path for spec-only PRs', () => {
diff --git a/.github/workflows/spec-owner-gate.yml b/.github/workflows/spec-owner-gate.yml
index c8a8cc69b1..b591eb2aa9 100644
--- a/.github/workflows/spec-owner-gate.yml
+++ b/.github/workflows/spec-owner-gate.yml
@@ -34,10 +34,6 @@ on:
permissions: {}
-concurrency:
- group: spec-owner-${{ github.event.pull_request.number || github.event.issue.number || github.event.inputs.pr }}
- cancel-in-progress: true
-
env:
SPEC_OWNERS: cixzhang,imdreamrunner
REVIEW_LABEL: needs:spec-owner-review
@@ -45,9 +41,12 @@ env:
jobs:
reconcile:
+ # Keep ordinary PR discussion outside the privileged pull_request_target path.
if: >-
github.event_name != 'issue_comment' ||
- github.event.issue.pull_request != null
+ (github.event.issue.pull_request != null &&
+ (startsWith(github.event.comment.body, '/approve-spec ') ||
+ startsWith(github.event.comment.body, '/revoke-spec ')))
runs-on: ubuntu-slim
permissions:
contents: read
@@ -66,252 +65,9 @@ jobs:
with:
retries: 3
script: |
- const fs = require('node:fs');
const path = require('node:path');
- const {classifyChanges} = require(path.join(
- process.env.GITHUB_WORKSPACE,
- '.github/scripts/change-scope.cjs',
- ));
- const {
- parseOwnerFile,
- requiredApprovalGroups,
- resolveOwnerDecision,
- } = require(path.join(
+ const {reconcileSpecOwnerGate} = require(path.join(
process.env.GITHUB_WORKSPACE,
- '.github/scripts/spec-owner-decision.cjs',
+ '.github/scripts/spec-owner-reconcile.cjs',
));
- const {owner, repo} = context.repo;
- const pull_number = Number(
- context.payload.pull_request?.number ??
- context.payload.issue?.number ??
- context.payload.inputs?.pr,
- );
- if (!pull_number) throw new Error('Could not resolve a pull request number.');
-
- const {data: pr} = await github.rest.pulls.get({owner, repo, pull_number});
- const files = await github.paginate(github.rest.pulls.listFiles, {
- owner, repo, pull_number, per_page: 100,
- });
- const scope = classifyChanges(files, {expectedCount: pr.changed_files});
- const currentLabels = new Set(pr.labels.map(label => label.name));
-
- async function setStatus(state, description) {
- await github.rest.repos.createCommitStatus({
- owner, repo, sha: pr.head.sha,
- context: 'spec-owner-approval', state,
- description: description.slice(0, 140),
- });
- }
- async function removeLabel(name) {
- try {
- await github.rest.issues.removeLabel({
- owner, repo, issue_number: pull_number, name,
- });
- } catch (error) {
- if (error.status !== 404) throw error;
- }
- }
- async function ensureLabel(name, color, description) {
- try {
- await github.rest.issues.getLabel({owner, repo, name});
- } catch (error) {
- if (error.status !== 404) throw error;
- await github.rest.issues.createLabel({
- owner, repo, name, color, description,
- });
- }
- if (!currentLabels.has(name)) {
- await github.rest.issues.addLabels({
- owner, repo, issue_number: pull_number, labels: [name],
- });
- }
- }
- async function disableOwnedAutoMerge() {
- if (!currentLabels.has(process.env.AUTO_MERGE_LABEL)) return;
- if (pr.auto_merge) {
- await github.graphql(
- `mutation($id: ID!) {
- disablePullRequestAutoMerge(input: {pullRequestId: $id}) {
- pullRequest { number }
- }
- }`,
- {id: pr.node_id},
- );
- }
- await removeLabel(process.env.AUTO_MERGE_LABEL);
- }
-
- if (!scope.touchesKnowledgeRecords) {
- await disableOwnedAutoMerge();
- await removeLabel(process.env.REVIEW_LABEL);
- await setStatus('success', 'No knowledge records changed.');
- return;
- }
-
- if (scope.specOnly) {
- // Spec records cannot affect runtime pixels. This trusted path
- // list is stricter than the visual classifier and is tested.
- await github.rest.repos.createCommitStatus({
- owner, repo, sha: pr.head.sha,
- context: 'visual-acceptance', state: 'success',
- description: 'Spec-only change — no visual scope.',
- });
- }
-
- async function readText(fullName, ref, filePath) {
- const [repoOwner, repoName] = fullName.split('/');
- try {
- const {data} = await github.rest.repos.getContent({
- owner: repoOwner, repo: repoName, path: filePath, ref,
- });
- if (Array.isArray(data) || !data.content) {
- throw new Error(`Knowledge record ${filePath} could not be read as text.`);
- }
- return Buffer.from(data.content, 'base64').toString('utf8');
- } catch (error) {
- if (error.status === 404) return null;
- throw error;
- }
- }
-
- const knowledgeChanges = files.filter(file =>
- scope.complete && (
- classifyChanges([{filename: file.filename}]).touchesKnowledgeRecords ||
- (file.previous_filename &&
- classifyChanges([{filename: file.previous_filename}]).touchesKnowledgeRecords)
- ),
- );
- const records = await Promise.all(knowledgeChanges.map(async file => {
- const previousPath = file.previous_filename || file.filename;
- const baseIsTextRecord = previousPath.endsWith('.md');
- const headIsTextRecord = file.filename.endsWith('.md');
- return {
- path: file.filename,
- previousPath,
- baseContent: !baseIsTextRecord || file.status === 'added'
- ? null
- : await readText(
- pr.base.repo.full_name,
- pr.base.sha,
- previousPath,
- ),
- headContent: !headIsTextRecord || file.status === 'removed'
- ? null
- : await readText(pr.head.repo.full_name, pr.head.sha, file.filename),
- };
- }));
- const requiredGroups = requiredApprovalGroups(records, {
- complete: scope.complete,
- touchesDesignAssets: scope.touchesDesignAssets,
- });
- const ownerApprovalRequired = requiredGroups.spec || requiredGroups.design;
- const specOwners = process.env.SPEC_OWNERS.split(',');
- const designOwners = parseOwnerFile(
- fs.readFileSync(
- path.join(process.env.GITHUB_WORKSPACE, '.github/DESIGNOWNERS'),
- 'utf8',
- ),
- );
- if (requiredGroups.design && designOwners.length === 0) {
- throw new Error('No DESIGNOWNERS are configured.');
- }
- const designApprovers = [...new Set([...specOwners, ...designOwners])];
-
- const [reviews, comments] = await Promise.all([
- github.paginate(github.rest.pulls.listReviews, {
- owner, repo, pull_number, per_page: 100,
- }),
- github.paginate(github.rest.issues.listComments, {
- owner, repo, issue_number: pull_number, per_page: 100,
- }),
- ]);
- const specDecision = requiredGroups.spec
- ? resolveOwnerDecision({
- reviews, comments, owners: specOwners, headSha: pr.head.sha,
- })
- : {approved: true, owner: null};
- const designDecision = requiredGroups.design
- ? resolveOwnerDecision({
- reviews, comments, owners: designApprovers, headSha: pr.head.sha,
- })
- : {approved: true, owner: null};
- const approved = specDecision.approved && designDecision.approved;
- const approvingOwners = [specDecision.owner, designDecision.owner]
- .filter(Boolean)
- .filter((ownerName, index, owners) => owners.indexOf(ownerName) === index);
- const requiredOwnerDescription = [
- requiredGroups.spec ? `a spec owner (${specOwners.join(',')})` : null,
- requiredGroups.design
- ? `a design approver (${designApprovers.join(',')})`
- : null,
- ].filter(Boolean).join(' and ');
-
- if (ownerApprovalRequired && !approved) {
- // Revoke our own auto-merge before any fallible label/status work.
- await disableOwnedAutoMerge();
- await ensureLabel(
- process.env.REVIEW_LABEL,
- 'd4c5f9',
- 'Current knowledge records await owner approval',
- );
- await setStatus(
- 'pending',
- `Waiting for ${requiredOwnerDescription} on ${pr.head.sha.slice(0, 7)}.`,
- );
- return;
- }
-
- if (pr.draft) {
- await disableOwnedAutoMerge();
- await removeLabel(process.env.REVIEW_LABEL);
- await setStatus('success', 'Draft PR; owner gate is not blocking.');
- return;
- }
-
- if (!scope.specOnly) {
- await disableOwnedAutoMerge();
- await removeLabel(process.env.REVIEW_LABEL);
- await setStatus(
- 'success',
- ownerApprovalRequired
- ? `Approved by ${approvingOwners.map(name => `@${name}`).join(' and ')} for ${pr.head.sha.slice(0, 7)}.`
- : 'No current knowledge record changed.',
- );
- return;
- }
-
- if (!pr.auto_merge) {
- // Record ownership before enabling auto-merge. If enablement
- // fails, the harmless label lets a later run clean up. If a user
- // already enabled auto-merge, do not claim or later disable it.
- await ensureLabel(
- process.env.AUTO_MERGE_LABEL,
- 'bfdadc',
- 'Auto-merge was enabled by the spec owner gate',
- );
- try {
- await github.graphql(
- `mutation($id: ID!, $oid: GitObjectID!) {
- enablePullRequestAutoMerge(input: {
- pullRequestId: $id,
- mergeMethod: SQUASH,
- expectedHeadOid: $oid
- }) {
- pullRequest { number }
- }
- }`,
- {id: pr.node_id, oid: pr.head.sha},
- );
- core.info(`Enabled squash auto-merge for spec-only PR #${pull_number}.`);
- } catch (error) {
- core.warning(`Could not enable auto-merge: ${error.message}`);
- return;
- }
- }
- await removeLabel(process.env.REVIEW_LABEL);
- await setStatus(
- 'success',
- ownerApprovalRequired
- ? `Approved by ${approvingOwners.map(name => `@${name}`).join(' and ')} for ${pr.head.sha.slice(0, 7)}.`
- : 'Draft-only knowledge change; owner approval is not required.',
- );
+ await reconcileSpecOwnerGate({github, context, core});