Skip to content

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

TypeScript

ci(review-signal): one review gate carries spec approval, bound to the reviewed spec content (#8886)

Cindy Zhangf6d9ce12c0ce
diff --git a/.github/DESIGNOWNERS b/.github/DESIGNOWNERS
index 5de4ef5871..6e2ef4758c 100644
--- a/.github/DESIGNOWNERS
+++ b/.github/DESIGNOWNERS
@@ -2,10 +2,11 @@
# Design-team members. This list has three responsibilities:
#
# - Current design and theme specs, component/module Design decisions, and
-# normative design assets may receive exact-head approval from any
-# DESIGNOWNER. ENGOWNERS may approve every spec.
-# - A DESIGNOWNER approves with an exact-head review or `/approve-spec <head>`,
-# like every other owner; in a mixed PR every other applicable code or
+# normative design assets may be approved by any DESIGNOWNER; an approval
+# binds the spec content (architecture:knowledge-contracts DEC-14). ENGOWNERS
+# may approve every spec.
+# - A DESIGNOWNER approves with a review or `/approve-spec <sha>`, like every
+# other owner; in a mixed PR every other applicable code or
# spec-owner group remains required. A classifier-proven appearance-only Core
# runtime change may bypass the engineering review gate only when no other
# code reason applies. The gate decides approval only; it never enables
diff --git a/.github/ENGOWNERS b/.github/ENGOWNERS
index 8f1b0724d6..7a859a63f7 100644
--- a/.github/ENGOWNERS
+++ b/.github/ENGOWNERS
@@ -1,8 +1,9 @@
# Engineering owners for the Astryx repository
#
# This checked-in list defines engineering owners for spec-owner reconciliation.
-# Any ENGOWNER may approve every current knowledge-record kind on the exact pull
-# request head. The review-signal workflows read the matching ENGOWNERS repository
+# Any ENGOWNER may approve every current knowledge-record kind; an approval binds
+# the pull request's spec content (architecture:knowledge-contracts DEC-14). The
+# review-signal workflows read the matching ENGOWNERS repository
# variable instead; keep that variable synchronized with this file when membership
# changes.
#
diff --git a/.github/PULL_REQUEST_TEMPLATE/visual-update.md b/.github/PULL_REQUEST_TEMPLATE/visual-update.md
index e4eb1d6daa..8a619c9b38 100644
--- a/.github/PULL_REQUEST_TEMPLATE/visual-update.md
+++ b/.github/PULL_REQUEST_TEMPLATE/visual-update.md
@@ -13,7 +13,7 @@ Choose one and link it:
- [ ] Correction already settled by current family, design, theme, or objective accessibility authority.
- [ ] New shared or cross-component direction settled in `docs/design/`.
-<!-- External contributors are not expected to author or update specifications. Maintainers record missing authority. A human request supplies intent; current authority still requires exact-head owner approval. -->
+<!-- External contributors are not expected to author or update specifications. Maintainers record missing authority. A human request supplies intent; current authority still requires owner approval of its content. -->
## Before and after
diff --git a/.github/REVIEW_GATE.md b/.github/REVIEW_GATE.md
index 1b4d080c68..2d5ce948d8 100644
--- a/.github/REVIEW_GATE.md
+++ b/.github/REVIEW_GATE.md
@@ -33,24 +33,15 @@ neutral yellow "waiting" signal, not a red failure).
## Spec records
Any PR that creates, changes, or archives a `current` architecture, component,
-family, design, or system spec waits on `spec-owner-approval` for its exact
-current head. Any handle in `.github/ENGOWNERS` can approve every record kind.
-Current design and theme records and normative design assets may also be approved
-by any handle in `.github/DESIGNOWNERS`. Mixed PRs still require an ENGOWNER for
-non-design current records. Same-repository owner reviews update the exact-head
-approval automatically. Fork review events cannot write
-with their read-only token, so an approver uses an issue comment containing
-`/approve-spec <full-head-sha>` instead; that command runs from the trusted
-default branch and a new commit invalidates it.
-
-Only that exact form decides the gate. The command must start the comment,
-lowercase and unindented, because the workflow trigger matches the raw comment
-body — an indented or capitalized command never starts the workflow, so the
-parser refuses it too rather than counting a comment nobody's run ever saw. The
-SHA itself may be either casing. A command that names no commit, names
-something other than one full 40-character SHA, or names a superseded commit
-changes nothing — so the gate replies once per head with the exact command to
-copy, rather than leaving the owner believing they approved.
+family, design, or system spec needs a spec owner's approval of its content
+(`architecture:knowledge-contracts` DEC-14), which `review-required` carries
+after code review: `pending`, never red, with `⏳ Waiting for human spec
+approval: …` naming who can approve. ENGOWNERS approve every record kind;
+design and theme records also accept DESIGNOWNERS. Approve with
+`/approve-spec <full-sha>` at the start of a comment (the trigger matches the
+raw body) or a non-author review; `/revoke-spec` withdraws. The gate's details
+give the command to copy and why an approval no longer counts; it posts no
+comments. `spec-owner-approval` mirrors the spec half.
The gate never re-decides a merged or closed head. A run that starts after the
merge publishes nothing, and neither does a run yielding to a newer one.
@@ -169,46 +160,13 @@ write-access author who is not an owner still needs an engineering owner's
approval or the review app's exact-head approval. (Repo admins can still
bypass.)
-`spec-owner-approval` must be a required status context on `main` as well. It is
-published on every PR — `success` when no knowledge records changed — so
-requiring it does not permanently strand unrelated work. **Until it is in the
-required list, a pending owner gate is advisory and does not block the merge
-button.** If the repository ever enables a merge queue, this gate also has to
-report on `merge_group` before the context is required, or queued entries stall
-waiting for a status nothing publishes.
-
-### Making it required (ordered; do not reorder)
-
-An open PR whose head predates the gate has no `spec-owner-approval` status at
-all. Requiring the context first would block those heads on a status no event
-will produce, because the gate only runs on a new event. Backfill first.
-
-1. Land the gate changes. `workflow_dispatch` always runs the default branch's
- copy.
-2. List the heads that would strand:
-
- ```sh
- gh pr list --state open --limit 300 --json number,headRefOid \
- --jq '.[]|"\(.number) \(.headRefOid)"' \
- | while read -r pr sha; do
- state=$(gh api "repos/meta/astryx/commits/$sha/status" \
- --jq '[.statuses[]|select(.context=="spec-owner-approval")|.state]
- | if length==0 then "MISSING" else .[0] end')
- [ "$state" = MISSING ] && echo "$pr"
- done
- ```
-
-3. Backfill each one; a reconcile only publishes the status:
-
- ```sh
- gh workflow run spec-owner-gate.yml -f pr=<number>
- ```
-
-4. Re-run the step 2 query and confirm it prints nothing.
-5. Only then add `spec-owner-approval` to the required status checks on `main`.
-
-A `pending` result from the backfill is the correct outcome for a PR that
-genuinely awaits an owner, not a stranded head.
+### The mirror
+
+`spec-owner-approval` now only mirrors the spec half of `review-required`.
+First re-flag every open PR (`gh workflow run review-signal.yml` with a blank
+`pr`) so each `review-required` carries its spec half; then remove the mirror
+from the required status checks on `main`. To re-publish a head's statuses, run
+`gh workflow run review-signal.yml -f pr=<number>`.
## Why a commit status (not a check run)
diff --git a/.github/scripts/review-clear-workflow.test.mjs b/.github/scripts/review-clear-workflow.test.mjs
index 0c94ac38c7..63a96aa192 100644
--- a/.github/scripts/review-clear-workflow.test.mjs
+++ b/.github/scripts/review-clear-workflow.test.mjs
@@ -59,6 +59,13 @@ const appReview = (state, commitId = head2) => ({
commit_id: commitId,
});
const ungatedSuccess = gateStatus('success', 'No code review required.');
+// The spec-owner job's decision for a PR that changes no spec record.
+const specOk = {
+ context: 'spec-owner-approval',
+ state: 'success',
+ description: 'Mirrors review-required · spec ok',
+ creator: {login: 'github-actions[bot]'},
+};
function harness(
reviews,
@@ -82,7 +89,7 @@ function harness(
labels: labels.map(name => ({name})),
};
const methods = {
- listCommitStatusesForRef: async () => ({data: statuses}),
+ listCommitStatusesForRef: async () => ({data: [...statuses, specOk]}),
listReviews: async () => ({data: reviews}),
};
const github = {
@@ -282,6 +289,38 @@ describe('review-clear exact-head workflow', () => {
});
});
+ it('restores a gate cleared under a spec wait and then spec-approved, on changes requested', async () => {
+ const specWait = gateStatus(
+ 'pending',
+ '⏳ Waiting for human spec approval: an eng owner can reply /approve-spec <sha>',
+ );
+ const h = harness([review('APPROVED'), review('CHANGES_REQUESTED')], {
+ labels: [],
+ // Newest first: /approve-spec, review-clear's clear, the code wait.
+ statuses: [
+ gateStatus(
+ 'success',
+ '✅ Spec approved by @cixzhang · Review complete.',
+ ),
+ specWait,
+ gateStatus(
+ 'pending',
+ 'Waiting on code review: core runtime change (+ spec approval)',
+ ),
+ ],
+ });
+
+ await run(h);
+
+ expect(h.calls).toContainEqual({
+ type: 'status',
+ input: expect.objectContaining({
+ state: 'pending',
+ description: 'Waiting on code review after approval withdrawal.',
+ }),
+ });
+ });
+
it('does not mutate the label when the pending status persistently fails', async () => {
const h = harness([review('APPROVED'), review('CHANGES_REQUESTED')], {
labels: [],
@@ -463,6 +502,30 @@ describe('review-clear review-app approval for write-access authors', () => {
]);
});
+ it('restores an app clear hidden under a spec wait when the app path no longer applies', async () => {
+ const h = harness([appReview('APPROVED')], {
+ labels: [],
+ // REVIEW_APP is unset; newest first: the spec wait over the app's clear.
+ statuses: [
+ gateStatus(
+ 'pending',
+ '⏳ Waiting for human spec approval: an eng owner can reply /approve-spec <sha>',
+ ),
+ gateStatus(
+ 'pending',
+ 'Waiting on code review: core runtime change (+ spec approval)',
+ ),
+ ],
+ });
+
+ await run(h);
+
+ expect(statusesOf(h.calls).at(-1)).toMatchObject({
+ state: 'pending',
+ description: expect.stringContaining('withdrawal'),
+ });
+ });
+
it('ignores app reviews when REVIEW_APP is unset', async () => {
const h = harness([appReview('APPROVED')]);
diff --git a/.github/scripts/review-signal-decision.cjs b/.github/scripts/review-signal-decision.cjs
index 81e6bccac9..a326e45bd9 100644
--- a/.github/scripts/review-signal-decision.cjs
+++ b/.github/scripts/review-signal-decision.cjs
@@ -121,8 +121,164 @@ function resolveReviewApprovals({
};
}
+// One review gate (architecture:knowledge-contracts DEC-14, spec:AST-030
+// FR15): every writer of `review-required` composes code review and the spec
+// half that `spec-owner-approval` mirrors.
+
+const REVIEW_GATE_CONTEXT = 'review-required';
+const SPEC_GATE_CONTEXT = 'spec-owner-approval';
+const TRUSTED_STATUS_CREATOR = 'github-actions[bot]';
+const SPEC_WAITING_PREFIX = '⏳ Waiting for human spec approval: ';
+const SPEC_WAITING_TEXT = {
+ eng: `${SPEC_WAITING_PREFIX}an eng owner can reply /approve-spec <sha>`,
+ design: `${SPEC_WAITING_PREFIX}a design or eng owner can reply /approve-spec <sha>`,
+ // An owner's request for changes on the current content holds the gate.
+ held: login =>
+ `${SPEC_WAITING_PREFIX}@${login} requested changes and can reply /approve-spec <sha>`,
+};
+const SPEC_MIRROR_PREFIX = 'Mirrors review-required · spec ';
+const SPEC_CHECKING_TEXT = '⏳ Checking for spec changes…';
+const CODE_WAITING_PREFIX = 'Waiting on code review';
+const REVIEW_COMPLETE = 'Review complete.';
+
+// GitHub lists a ref's statuses newest first.
+function newestTrusted(statuses, contextName) {
+ return (
+ (statuses ?? []).find(
+ status =>
+ status.context === contextName &&
+ status.creator?.login === TRUSTED_STATUS_CREATOR,
+ ) ?? null
+ );
+}
+
+/**
+ * The spec half, from the newest trusted `spec-owner-approval`. With none yet
+ * (or a failed read) it fails closed; the spec-owner job composes on publish.
+ */
+function readSpecGate(statuses) {
+ const status = newestTrusted(statuses, SPEC_GATE_CONTEXT);
+ if (!status)
+ return {known: false, satisfied: false, text: SPEC_CHECKING_TEXT};
+ return {...readSpecStatus(status), url: status.target_url};
+}
+
+function readSpecStatus(status) {
+ const description = status.description ?? '';
+ if (description.startsWith(SPEC_MIRROR_PREFIX)) {
+ const rest = description.slice(SPEC_MIRROR_PREFIX.length);
+ const holder = rest.match(/^waiting \(changes @([\w-]+)\)/)?.[1];
+ if (holder) {
+ return {
+ known: true,
+ satisfied: false,
+ text: SPEC_WAITING_TEXT.held(holder),
+ };
+ }
+ if (rest.startsWith('waiting (design)')) {
+ return {known: true, satisfied: false, text: SPEC_WAITING_TEXT.design};
+ }
+ if (rest.startsWith('waiting')) {
+ return {known: true, satisfied: false, text: SPEC_WAITING_TEXT.eng};
+ }
+ const approvers = rest.match(/^ok \((.+)\)$/)?.[1];
+ if (approvers && status.state === 'success') {
+ return {
+ known: true,
+ satisfied: true,
+ text: `✅ Spec approved by ${approvers}`,
+ };
+ }
+ }
+ // An earlier gate's status: success counts; anything else is re-read.
+ return status.state === 'success'
+ ? {known: true, satisfied: true, text: null}
+ : {known: true, satisfied: false, text: SPEC_CHECKING_TEXT};
+}
+
+function parseCodeGate(status) {
+ const description = status.description ?? '';
+ if (status.state === 'success') {
+ // Drop a spec approval this gate already carries.
+ const code = description.replace(/^✅ Spec approved by [^·]+ · /, '');
+ return {gated: false, description: code};
+ }
+ if (description.startsWith(CODE_WAITING_PREFIX)) {
+ return {
+ gated: true,
+ description: description.replace(/ \(\+ spec approval\)$/, ''),
+ };
+ }
+ return {gated: false, description: REVIEW_COMPLETE};
+}
+
+/**
+ * The code half of `review-required`, from the newest status carrying one
+ * (spec waits and the `Review complete.` placeholder carry none). A newer spec
+ * wait means satisfied code review; `{latest: false}` skips that, for
+ * review-clear's ownership check.
+ */
+function readCodeGate(statuses, {latest = true} = {}) {
+ const gates = (statuses ?? []).filter(
+ gate =>
+ gate.context === REVIEW_GATE_CONTEXT &&
+ gate.creator?.login === TRUSTED_STATUS_CREATOR,
+ );
+ if (gates.length === 0) return null;
+ const coded = gates.find(gate => {
+ const description = gate.description ?? '';
+ return !(
+ description.startsWith(SPEC_WAITING_PREFIX) ||
+ description === SPEC_CHECKING_TEXT ||
+ parseCodeGate(gate).description === REVIEW_COMPLETE
+ );
+ });
+ const code = coded ? parseCodeGate(coded) : null;
+ if (!latest || coded === gates[0]) {
+ return code ?? {gated: false, description: REVIEW_COMPLETE};
+ }
+ return {
+ gated: false,
+ description: code && !code.gated ? code.description : REVIEW_COMPLETE,
+ };
+}
+
+/** The one review gate: code review leads; success needs both; never red. */
+function composeReviewGate({codeGated, codeDescription, spec}) {
+ if (codeGated) {
+ const withSpec =
+ spec && !spec.satisfied
+ ? `${codeDescription} (+ spec approval)`
+ : codeDescription;
+ return {
+ state: 'pending',
+ description: (withSpec.length <= 140 ? withSpec : codeDescription).slice(
+ 0,
+ 140,
+ ),
+ };
+ }
+ if (spec && !spec.satisfied) {
+ // The spec decision's run is where the command to copy lives.
+ return {state: 'pending', description: spec.text, target_url: spec.url};
+ }
+ const done = codeDescription || REVIEW_COMPLETE;
+ const withSpec = spec?.text ? `${spec.text} · ${done}` : done;
+ return {
+ state: 'success',
+ description: withSpec.length <= 140 ? withSpec : (spec?.text ?? done),
+ };
+}
+
module.exports = {
+ REVIEW_GATE_CONTEXT,
+ SPEC_GATE_CONTEXT,
+ SPEC_MIRROR_PREFIX,
+ SPEC_WAITING_TEXT,
classifyReviewSignalPaths,
+ composeReviewGate,
+ readCodeGate,
+ readSpecGate,
hasWritePermission,
isSafeSpace,
normalizeReviewApp,
diff --git a/.github/scripts/review-signal-workflow.test.mjs b/.github/scripts/review-signal-workflow.test.mjs
index afd9438d1b..0120918d79 100644
--- a/.github/scripts/review-signal-workflow.test.mjs
+++ b/.github/scripts/review-signal-workflow.test.mjs
@@ -35,6 +35,15 @@ async function runSignal({
reviews = [],
reviewApp = '',
permission = 'write',
+ // The spec-owner job's decision for a PR that changes no spec record.
+ specStatuses = [
+ {
+ context: 'spec-owner-approval',
+ state: 'success',
+ description: 'Mirrors review-required · spec ok',
+ creator: {login: 'github-actions[bot]'},
+ },
+ ],
} = {}) {
const pr = {
number: 42,
@@ -89,6 +98,10 @@ async function runSignal({
repos: {
getContent,
createCommitStatus: mutations.createCommitStatus,
+ listCommitStatusesForRef: vi.fn(async () => ({
+ data:
+ typeof specStatuses === 'function' ? specStatuses() : specStatuses,
+ })),
getCollaboratorPermissionLevel: vi.fn(async () => {
if (permission instanceof Error) throw permission;
return {data: {permission}};
diff --git a/.github/scripts/spec-owner-decision.cjs b/.github/scripts/spec-owner-decision.cjs
index 26788d628f..dac446a798 100644
--- a/.github/scripts/spec-owner-decision.cjs
+++ b/.github/scripts/spec-owner-decision.cjs
@@ -12,6 +12,8 @@ const {
parseKind,
parseOwnerFile,
} = require('./knowledge-frontmatter.cjs');
+const crypto = require('node:crypto');
+const {SPEC_MIRROR_PREFIX} = require('./review-signal-decision.cjs');
/* eslint-enable @typescript-eslint/no-require-imports */
const GATE_STATUS_CONTEXT = 'spec-owner-approval';
@@ -32,20 +34,17 @@ function isDispatchableOwnerCommand(body) {
function parseOwnerCommand(body, headSha) {
if (!isDispatchableOwnerCommand(body)) return null;
- // The command prefix must match the trigger exactly, but a commit SHA is
- // case-insensitive everywhere else in git and GitHub. Accept either casing
- // rather than silently ignoring a copy-pasted uppercase head.
- const match = body
- .trim()
- .match(/^\/(approve|revoke)-spec\s+([0-9a-fA-F]{40})$/);
- if (!match || headSha.toLowerCase() !== match[2].toLowerCase()) return null;
- return match[1] === 'approve';
+ // A commit SHA is case-insensitive everywhere else in git and GitHub, so a
+ // copy-pasted uppercase head still names it.
+ const target = parseOwnerCommandTarget(body);
+ if (!target?.sha || target.sha !== headSha.toLowerCase()) return null;
+ return target.approved;
}
/**
* Recognize that a comment was meant as an owner command, whatever it names.
- * Only the exact-head form in `parseOwnerCommand` decides the gate; this looser
- * shape exists so a near-miss command is answered instead of ignored.
+ * Only a well-formed command decides the gate; this looser shape exists so a
+ * near-miss command is explained in the gate's details instead of ignored.
*/
function parseOwnerCommandIntent(body) {
if (!isDispatchableOwnerCommand(body)) return null;
@@ -61,17 +60,16 @@ function parseOwnerCommandIntent(body) {
* null when it does. The reasons are the two silent failures owners hit: a
* command that names no full head SHA, and one that names a superseded commit.
*/
-function describeOwnerCommandProblem(intent, headSha) {
+function describeOwnerCommandProblem(intent) {
if (!intent) return null;
if (!intent.argument) {
- return 'it did not name a commit';
+ return intent.verb === 'approve'
+ ? 'it did not name a commit; post /approve-spec with the full head SHA'
+ : null;
}
if (!/^[0-9a-f]{40}$/i.test(intent.argument)) {
return 'it did not name exactly one full 40-character commit SHA';
}
- if (intent.argument.toLowerCase() !== headSha.toLowerCase()) {
- return `it named ${intent.argument.slice(0, 7)}, which is not the current head`;
- }
return null;
}
@@ -106,6 +104,10 @@ function resolveOwnerDecision({
dismissalEvents = [],
owners,
headSha,
+ // Spec approvals bind content (DEC-14): a review or a command counts when
+ // the commit it names carries the current spec content. A `/revoke-spec`
+ // without a commit withdraws whatever that owner approved.
+ approvesCurrentContent = sha => sha === headSha,
}) {
const allowed = new Set(owners.map(owner => owner.toLowerCase()));
const latestByOwner = new Map();
@@ -127,7 +129,15 @@ function resolveOwnerDecision({
for (const review of reviews) {
const login = review.user?.login?.toLowerCase();
- if (!login || review.commit_id !== headSha) continue;
+ // An approval counts only for the current spec content (DEC-14). A
+ // request for changes on it holds the gate; one on other content, or a
+ // dismissal, withdraws only that owner's approval.
+ if (
+ !login ||
+ (review.state === 'APPROVED' && !approvesCurrentContent(review.commit_id))
+ ) {
+ continue;
+ }
if (
!['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)
) {
@@ -141,7 +151,8 @@ function resolveOwnerDecision({
approved:
review.state === 'APPROVED'
? true
- : review.state === 'CHANGES_REQUESTED'
+ : review.state === 'CHANGES_REQUESTED' &&
+ approvesCurrentContent(review.commit_id)
? false
: null,
at:
@@ -156,10 +167,13 @@ function resolveOwnerDecision({
for (const comment of comments) {
const login = comment.user?.login?.toLowerCase();
if (!login) continue;
- const approved = parseOwnerCommand(comment.body ?? '', headSha);
- if (approved == null) continue;
+ if (!isDispatchableOwnerCommand(comment.body)) continue;
+ const target = parseOwnerCommandTarget(comment.body);
+ if (target == null) continue;
+ if (target.approved && !approvesCurrentContent(target.sha)) continue;
+ // `/revoke-spec` withdraws that owner's approval (DEC-14).
consider(login, {
- approved,
+ approved: target.approved || null,
at: comment.created_at,
source: 'command',
});
@@ -278,18 +292,113 @@ function requiresOwnerApproval(records, options = {}) {
return groups.spec || groups.design || groups.theme;
}
+// --- Spec content an approval binds, and the gate's text (DEC-14). ---
+
+// Recording an approval writes these values, so they never take part in the
+// content an approval binds (DEC-14).
+const BOOKKEEPING_KEYS = new Set(['authority', 'approved_by', 'approved_at']);
+
+function sha256(value) {
+ return crypto.createHash('sha256').update(value).digest('hex');
+}
+
+/**
+ * A Markdown record's text without the front-matter values that approval
+ * bookkeeping rewrites. Everything else, body and other keys, stays.
+ */
+function normalizeRecordText(text) {
+ const normalized = text.replace(/\r\n/g, '\n');
+ if (!normalized.startsWith('---\n')) return normalized;
+ const end = normalized.indexOf('\n---', 4);
+ if (end === -1) return normalized;
+ const frontMatter = normalized
+ .slice(4, end)
+ .split('\n')
+ .filter(line => {
+ const key = line.match(/^([A-Za-z_][\w-]*)\s*:/)?.[1];
+ return key == null || !BOOKKEEPING_KEYS.has(key);
+ })
+ .join('\n');
+ return `---\n${frontMatter}${normalized.slice(end)}`;
+}
+
+/**
+ * One fingerprint over every changed spec path. Each entry is
+ * `{path, content}`, where `content` is the text at the head (`null` when the
+ * path is absent there). Markdown is normalized; other files hash as read.
+ */
+function fingerprintSpecContent(entries) {
+ const files = {};
+ for (const {path, content} of entries) {
+ files[path] =
+ content == null
+ ? 'absent'
+ : sha256(path.endsWith('.md') ? normalizeRecordText(content) : content);
+ }
+ const fingerprint = sha256(
+ Object.keys(files)
+ .sort()
+ .map(filePath => `${filePath}\0${files[filePath]}\n`)
+ .join(''),
+ );
+ return {fingerprint, files};
+}
+
+/**
+ * Read an owner command. `/approve-spec <sha>` approves the spec content at
+ * that commit; the SHA says which content the owner reviewed. `/revoke-spec`
+ * withdraws the owner's approval, with or without a commit.
+ */
+function parseOwnerCommandTarget(body) {
+ if (typeof body !== 'string') return null;
+ const match = body
+ .trim()
+ .match(/^\/(approve|revoke)-spec(?:\s+([0-9a-fA-F]{40}))?$/);
+ if (!match) return null;
+ if (match[1] === 'approve' && !match[2]) return null;
+ return {
+ approved: match[1] === 'approve',
+ sha: match[2] ? match[2].toLowerCase() : null,
+ };
+}
+
+function approvedDescription(owners) {
+ const names = owners.map(name => `@${name}`).join(', ');
+ return `✅ Spec approved by ${names || 'an owner'}`;
+}
+
+/**
+ * The `spec-owner-approval` description. That context only mirrors the spec
+ * half of `review-required` until branch protection stops requiring it; the
+ * review gate reads the state from this text.
+ */
+function mirrorDescription({state, missing, approvers = []}) {
+ if (state === 'success') {
+ return approvers.length
+ ? `${SPEC_MIRROR_PREFIX}ok (${approvers.map(name => `@${name}`).join(', ')})`
+ : `${SPEC_MIRROR_PREFIX}ok`;
+ }
+ if (missing?.heldBy)
+ return `${SPEC_MIRROR_PREFIX}waiting (changes @${missing.heldBy})`;
+ return `${SPEC_MIRROR_PREFIX}waiting (${missing?.spec ? 'eng' : 'design'})`;
+}
+
module.exports = {
GATE_STATUS_CONTEXT,
OWNER_COMMAND_PREFIXES,
+ approvedDescription,
canonicalRunUrl,
describeOwnerCommandProblem,
+ fingerprintSpecContent,
isDispatchableOwnerCommand,
+ mirrorDescription,
newestGateRun,
parseAuthority,
parseCanonicalRunId,
parseKind,
parseOwnerCommand,
parseOwnerCommandIntent,
+ parseOwnerCommandTarget,
parseOwnerFile,
requiredApprovalGroups,
requiresOwnerApproval,
diff --git a/.github/scripts/spec-owner-decision.test.mjs b/.github/scripts/spec-owner-decision.test.mjs
index 7571c51e21..09ba6304b5 100644
--- a/.github/scripts/spec-owner-decision.test.mjs
+++ b/.github/scripts/spec-owner-decision.test.mjs
@@ -17,6 +17,14 @@ const {
requiredApprovalGroups,
resolveOwnerDecision,
} = require('./spec-owner-decision.cjs');
+const {
+ fingerprintSpecContent,
+ parseOwnerCommandTarget,
+} = require('./spec-owner-decision.cjs');
+const {
+ composeReviewGate,
+ readSpecGate,
+} = require('./review-signal-decision.cjs');
const head = 'abcdef1234567890abcdef1234567890abcdef12';
const owner = {login: 'cixzhang'};
@@ -373,7 +381,38 @@ describe('spec owner decision', () => {
],
});
expect(decision.approved).toBe(false);
- expect(decision.source).toBe('command');
+ });
+
+ it('withdraws only the revoking owner, and holds on a current request for changes', () => {
+ const earlier = '1111111111111111111111111111111111111111';
+ const at = '2026-08-30T10:01:00Z';
+ const decide = ({reviews = [], comments = []}) =>
+ resolveOwnerDecision({
+ owners: ['cixzhang', 'imdreamrunner'],
+ headSha: head,
+ reviews: [
+ {
+ user: {login: 'imdreamrunner'},
+ state: 'APPROVED',
+ commit_id: head,
+ submitted_at: at,
+ },
+ ...reviews,
+ ],
+ comments,
+ approvesCurrentContent: sha => sha === head,
+ }).approved;
+ const say = body => ({comments: [{user: owner, body, created_at: at}]});
+ const changes = commit_id => ({
+ reviews: [
+ {user: owner, state: 'CHANGES_REQUESTED', commit_id, submitted_at: at},
+ ],
+ });
+
+ expect(decide(say('/revoke-spec'))).toBe(true);
+ expect(decide(say(`/revoke-spec ${earlier}`))).toBe(true);
+ expect(decide(changes(earlier))).toBe(true);
+ expect(decide(changes(head))).toBe(false);
});
it('ignores commands from other users', () => {
@@ -571,26 +610,24 @@ describe('spec owner decision', () => {
}
});
- it('explains each way a recognized command misses the head', () => {
+ it('explains each way a recognized command decides nothing', () => {
const stale = '1111111111111111111111111111111111111111';
expect(
- describeOwnerCommandProblem(
- parseOwnerCommandIntent('/approve-spec'),
- head,
- ),
+ describeOwnerCommandProblem(parseOwnerCommandIntent('/approve-spec')),
).toContain('did not name a commit');
expect(
describeOwnerCommandProblem(
parseOwnerCommandIntent('/approve-spec abc1234'),
- head,
),
).toContain('full 40-character commit SHA');
- expect(
- describeOwnerCommandProblem(
- parseOwnerCommandIntent(`/approve-spec ${stale}`),
- head,
- ),
- ).toContain('1111111');
+ // A well-formed SHA is decided by comparing its spec content (DEC-14),
+ // and a bare /revoke-spec withdraws.
+ for (const body of [`/approve-spec ${stale}`, '/revoke-spec']) {
+ expect(
+ describeOwnerCommandProblem(parseOwnerCommandIntent(body)),
+ body,
+ ).toBe(null);
+ }
});
it('accepts a commit SHA in either casing', () => {
@@ -604,13 +641,12 @@ describe('spec owner decision', () => {
expect(
describeOwnerCommandProblem(
parseOwnerCommandIntent(`/approve-spec ${upper}`),
- head,
),
).toBe(null);
expect(parseOwnerCommand(`/approve-spec ${head}`, upper)).toBe(true);
});
- it('agrees with the help validator on every recognized command', () => {
+ it('agrees with the validator on every recognized command', () => {
const stale = '1111111111111111111111111111111111111111';
for (const body of [
@@ -618,26 +654,70 @@ describe('spec owner decision', () => {
`/approve-spec ${head.toUpperCase()}`,
`/revoke-spec ${head}`,
'/approve-spec',
+ '/revoke-spec',
'/approve-spec abc1234',
`/approve-spec ${stale}`,
- `/approve-spec ${stale.toUpperCase()}`,
`/approve-spec ${head} please`,
]) {
- const intent = parseOwnerCommandIntent(body);
- const decided = parseOwnerCommand(body, head) !== null;
- const problem = describeOwnerCommandProblem(intent, head);
- // Exactly one of the two is true: the command decides the gate, or
- // the gate can say why it did not.
- expect(decided, body).toBe(problem === null);
+ const parsed = parseOwnerCommandTarget(body) !== null;
+ const problem = describeOwnerCommandProblem(
+ parseOwnerCommandIntent(body),
+ );
+ // Exactly one holds: the command reads as a decision, or the gate
+ // can say why it does not.
+ expect(parsed, body).toBe(problem === null);
}
});
+ });
+});
- it('reports no problem for the exact form the gate accepts', () => {
- const intent = parseOwnerCommandIntent(`/approve-spec ${head}`);
+const record = [
+ '---',
+ 'kind: architecture',
+ 'authority: draft',
+ 'approved_by: null',
+ 'approved_at: null',
+ 'owners: [cixzhang]',
+ '---',
+ '',
+ '# Example',
+ '',
+ 'The contract.',
+ '',
+].join('\n');
+const fingerprint = content =>
+ fingerprintSpecContent([{path: 'docs/a.md', content}]).fingerprint;
+
+describe('spec content fingerprint (DEC-14)', () => {
+ it('ignores only the values approval bookkeeping writes', () => {
+ const flipped = record
+ .replace('authority: draft', 'authority: current')
+ .replace('approved_by: null', 'approved_by: cixzhang')
+ .replace('approved_at: null', 'approved_at: 2026-10-28');
+ expect(fingerprint(flipped)).toBe(fingerprint(record));
+ for (const edited of [
+ record.replace('The contract.', 'Another contract.'),
+ record.replace('owners: [cixzhang]', 'owners: [someone]'),
+ `${record}authority: current\n`,
+ ]) {
+ expect(fingerprint(edited)).not.toBe(fingerprint(record));
+ }
+ });
+});
- expect(describeOwnerCommandProblem(intent, head)).toBe(null);
- expect(parseOwnerCommand(`/approve-spec ${head}`, head)).toBe(true);
- expect(describeOwnerCommandProblem(null, head)).toBe(null);
+describe('one review gate', () => {
+ const noCode = 'No code review required.';
+
+ it('fails closed before a spec decision, and links a wait to its run', () => {
+ const compose = spec =>
+ composeReviewGate({codeGated: false, codeDescription: noCode, spec});
+ expect(compose(readSpecGate([]))).toMatchObject({
+ state: 'pending',
+ description: '⏳ Checking for spec changes…',
});
+ const url = 'https://github.com/meta/astryx/actions/runs/7/attempts/1';
+ expect(
+ compose({known: true, satisfied: false, text: '⏳ wait', url}),
+ ).toEqual({state: 'pending', description: '⏳ wait', target_url: url});
});
});
diff --git a/.github/scripts/spec-owner-reconcile.cjs b/.github/scripts/spec-owner-reconcile.cjs
index e2e5b97acf..4dc3cfd43c 100644
--- a/.github/scripts/spec-owner-reconcile.cjs
+++ b/.github/scripts/spec-owner-reconcile.cjs
@@ -9,15 +9,27 @@ const path = require('node:path');
const {classifyChanges} = require('./change-scope.cjs');
const {
GATE_STATUS_CONTEXT,
+ approvedDescription,
+ fingerprintSpecContent,
+ mirrorDescription,
+ parseOwnerCommandTarget,
canonicalRunUrl,
describeOwnerCommandProblem,
newestGateRun,
- parseOwnerCommand,
parseOwnerCommandIntent,
+ parseAuthority,
+ parseKind,
parseOwnerFile,
requiredApprovalGroups,
resolveOwnerDecision,
} = require('./spec-owner-decision.cjs');
+const {
+ REVIEW_GATE_CONTEXT,
+ SPEC_WAITING_TEXT,
+ composeReviewGate,
+ readCodeGate,
+ readSpecGate,
+} = require('./review-signal-decision.cjs');
/* eslint-enable @typescript-eslint/no-require-imports */
function isCommandComment(eventName, payload) {
@@ -43,21 +55,9 @@ function labelNames(pr) {
return new Set(pr.labels.map(label => label.name));
}
-function ownerCommandHelpMarker(headSha) {
- return `<!-- spec-owner-command-help:${headSha} -->`;
-}
-
-function ownerCommandHelpBody({verb, headSha, problem}) {
- return [
- ownerCommandHelpMarker(headSha),
- `That \`/${verb}-spec\` comment did not change \`${GATE_STATUS_CONTEXT}\`: ${problem}.`,
- '',
- 'The gate only accepts the exact current head, so post this instead:',
- '',
- ` /${verb}-spec ${headSha}`,
- '',
- 'A new commit invalidates the command, so repeat it after any push.',
- ].join('\n');
+function isSpecPath(filePath) {
+ const scope = classifyChanges([{filename: filePath}]);
+ return scope.touchesKnowledgeRecords || scope.touchesDesignAssets;
}
function isSettled(pr) {
@@ -137,7 +137,7 @@ async function reconcileSpecOwnerGate({
description,
targetUrl = runUrl,
}) {
- await github.rest.repos.createCommitStatus({
+ const {data} = await github.rest.repos.createCommitStatus({
owner,
repo,
sha,
@@ -146,6 +146,7 @@ async function reconcileSpecOwnerGate({
description: description.slice(0, 140),
target_url: targetUrl,
});
+ return data;
}
async function newestRun(headSha) {
@@ -202,6 +203,7 @@ async function reconcileSpecOwnerGate({
description: newest.status.description,
targetUrl: newest.status.target_url,
});
+ await publishReviewGate(headSha, readSpecGate([newest.status]));
}
core.info(
`Run ${context.runId} yielded to newer run ${newest.runId.toString()}.`,
@@ -214,13 +216,22 @@ async function reconcileSpecOwnerGate({
return newest === null || newest.runId <= runId;
}
- async function setFinalStatus(headSha, state, description) {
+ // The owners whose approval decided the gate, once the decision is known.
+ let approvedBy = [];
+ /** Publish the mirror, then the review gate composed with code review. */
+ async function setFinalStatus(headSha, state, text, missing = null) {
+ const approvers = state === 'success' ? approvedBy : [];
if (!(await isPublishable(headSha))) return false;
await createStatus({
sha: headSha,
context: GATE_STATUS_CONTEXT,
state,
- description,
+ description: mirrorDescription({state, missing, approvers}),
+ });
+ if (await restoreNewerStatus(headSha)) return false;
+ await publishReviewGate(headSha, {
+ satisfied: state === 'success',
+ text: state === 'success' && approvers.length === 0 ? null : text,
});
// The write cannot be undone, so verify what it landed on. A success that
// raced a merge is reported loudly.
@@ -295,6 +306,195 @@ async function reconcileSpecOwnerGate({
}
}
+ /** A spec path's text at `ref`, or null when the path is absent there. */
+ async function readSpecContent(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)) return null;
+ if (data.content == null) return `blob:${data.sha}`;
+ // Only Markdown is read as text; other assets hash as their bytes.
+ return filePath.endsWith('.md')
+ ? Buffer.from(data.content, 'base64').toString('utf8')
+ : `base64:${data.content.replace(/\s/g, '')}`;
+ } catch (error) {
+ if (error.status === 404) return null;
+ throw error;
+ }
+ }
+
+ /** Details notes: the newest approval of other content; a revocation. */
+ function ownerActNotes({
+ reviews: ownerReviews,
+ comments: allComments,
+ owners: eligible,
+ approvesCurrentContent,
+ }) {
+ const stale = ownerReviews
+ .filter(
+ review =>
+ review.state === 'APPROVED' &&
+ !approvesCurrentContent(review.commit_id),
+ )
+ .map(review => review.submitted_at);
+ // Comments arrive oldest first, so the last act per owner wins.
+ const lastAct = new Map();
+ for (const comment of allComments) {
+ const login = comment.user?.login?.toLowerCase() ?? '';
+ const target =
+ eligible.has(login) && parseOwnerCommandTarget(comment.body);
+ if (!target) continue;
+ if (target.approved && !approvesCurrentContent(target.sha)) {
+ stale.push(comment.created_at);
+ }
+ lastAct.set(login, {owner: login, ...target, at: comment.created_at});
+ }
+ const revokedBy =
+ [...lastAct.values()]
+ .filter(act => !act.approved)
+ .sort((x, y) => Date.parse(y.at) - Date.parse(x.at))[0] ?? null;
+ return {
+ staleApprovalAt: stale.filter(Boolean).sort().at(-1) ?? null,
+ revokedBy,
+ };
+ }
+
+ /** The gate's details: the run summary its statuses link to. */
+ async function writeDetails({
+ statusText,
+ headSha,
+ approvalRequired,
+ approved: isApproved,
+ records: changedRecords,
+ currentContent,
+ notes,
+ commandProblem,
+ }) {
+ if (typeof core.summary?.addRaw !== 'function') return;
+ const groupFor = record => {
+ const current =
+ parseAuthority(record.headContent, record.path) === 'current' ||
+ parseAuthority(record.baseContent, record.previousPath) === 'current';
+ if (!current) return 'none (draft)';
+ const kind = parseKind(
+ record.headContent ?? record.baseContent,
+ record.path,
+ );
+ return kind === 'design' || kind === 'theme'
+ ? 'design or eng owner'
+ : 'eng owner';
+ };
+ const rows = changedRecords.map(record => {
+ const text = record.headContent ?? record.baseContent ?? '';
+ const id = text.match(/^id:\s*(.+)$/m)?.[1]?.trim() ?? record.path;
+ const title = text.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? '';
+ const before =
+ record.baseContent == null
+ ? 'new'
+ : (parseAuthority(record.baseContent, record.previousPath) ?? '?');
+ const after =
+ record.headContent == null
+ ? 'removed'
+ : (parseAuthority(record.headContent, record.path) ?? '?');
+ const change = before === after ? after : `${before} → ${after}`;
+ return `| \`${id}\` | ${title} | ${change} | ${groupFor(record)} |`;
+ });
+ // `<sha>` in the status text is literal, not markup.
+ const lines = [`### ${statusText.replace(/</g, '&lt;')}`, ''];
+ if (!isApproved && notes.revokedBy) {
+ lines.push(
+ `Approval revoked by @${notes.revokedBy.owner} at ${notes.revokedBy.at}.`,
+ '',
+ );
+ } else if (!isApproved && notes.staleApprovalAt) {
+ lines.push(
+ `Spec changed after approval at ${notes.staleApprovalAt}; approve the current head again.`,
+ '',
+ );
+ }
+ if (commandProblem) {
+ lines.push(`Your owner command decided nothing: ${commandProblem}.`, '');
+ }
+ if (approvalRequired && !isApproved) {
+ lines.push(
+ 'Approve the current spec text with a comment on the pull request:',
+ '',
+ '```',
+ `/approve-spec ${headSha}`,
+ '```',
+ '',
+ );
+ }
+ lines.push(
+ '| Record | Title | Authority | Needs approval from |',
+ '| --- | --- | --- | --- |',
+ ...rows,
+ '',
+ '<details><summary>Changed spec paths and content fingerprint</summary>',
+ '',
+ ...Object.keys(currentContent.files).map(filePath => `- \`${filePath}\``),
+ '',
+ `Fingerprint \`${currentContent.fingerprint}\`. An approval of any commit with this fingerprint counts, so commits that leave these paths' text unchanged (other paths, merges from main, rebases, the draft → current flip) keep it.`,
+ '',
+ '</details>',
+ );
+ try {
+ await core.summary.addRaw(lines.join('\n')).write();
+ } catch (error) {
+ core.warning(`Could not write the gate details: ${error.message}`);
+ }
+ }
+
+ /** Compose the review gate; with no code half yet, review-signal does. */
+ async function publishReviewGate(headSha, spec) {
+ // If another job writes between this read and write, compose again, so a
+ // withdrawn code review is never overwritten with success.
+ const written = new Set();
+ const othersNewest = statuses =>
+ statuses.find(
+ status =>
+ status.context === REVIEW_GATE_CONTEXT && !written.has(status.id),
+ ) ?? null;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const live = await listStatuses(headSha);
+ const basis = othersNewest(live);
+ const code = readCodeGate(live.filter(status => !written.has(status.id)));
+ if (!code) return;
+ const gate = composeReviewGate({
+ codeGated: code.gated,
+ codeDescription: code.description,
+ spec,
+ });
+ // The details link names the spec decision run (a newer one on yield).
+ const targetUrl = gate.target_url ?? runUrl;
+ const current = live.find(
+ status => status.context === REVIEW_GATE_CONTEXT,
+ );
+ if (
+ current?.state === gate.state &&
+ current?.description === gate.description &&
+ current?.target_url === targetUrl
+ ) {
+ return;
+ }
+ if (!(await isLiveHeadWritable(headSha))) return;
+ const status = await createStatus({
+ sha: headSha,
+ context: REVIEW_GATE_CONTEXT,
+ state: gate.state,
+ description: gate.description,
+ targetUrl,
+ });
+ if (status?.id != null) written.add(status.id);
+ if (othersNewest(await listStatuses(headSha))?.id === basis?.id) return;
+ }
+ }
+
async function fetchSnapshot() {
const before = await getPullRequest();
const headSha = before.head.sha;
@@ -398,7 +598,6 @@ async function reconcileSpecOwnerGate({
if (await restoreNewerStatus(initialHead)) return;
const commentAuthor = context.payload.comment?.user?.login?.toLowerCase();
-
const snapshot = await fetchSnapshot();
if (snapshot === null || snapshot.pr.head.sha !== initialHead) {
core.info(
@@ -413,29 +612,13 @@ async function reconcileSpecOwnerGate({
const {pr, scope, records, reviews, comments, timeline, statuses} = snapshot;
- // A near-miss owner command used to do nothing at all, so an owner could
- // believe they had approved a head the gate never read. Answer it once per
- // head with the exact command instead of leaving it silent.
- if (context.eventName === 'issue_comment' && commentAuthor) {
- const intent = parseOwnerCommandIntent(context.payload.comment?.body);
- const problem = describeOwnerCommandProblem(intent, initialHead);
- const marker = ownerCommandHelpMarker(initialHead);
- if (problem && !comments.some(entry => entry.body?.includes(marker))) {
- await github.rest.issues.createComment({
- owner,
- repo,
- issue_number: pullNumber,
- body: ownerCommandHelpBody({
- verb: intent.verb,
- headSha: initialHead,
- problem,
- }),
- });
- core.info(
- `Answered an inexact ${intent.verb} command on ${initialHead}.`,
- );
- }
- }
+ // A malformed owner command decides nothing; the details say why.
+ const commandProblem =
+ context.eventName === 'issue_comment' && commentAuthor
+ ? describeOwnerCommandProblem(
+ parseOwnerCommandIntent(context.payload.comment?.body),
+ )
+ : null;
if (!scope.touchesKnowledgeRecords) {
await removeLabel(env.REVIEW_LABEL);
@@ -465,11 +648,97 @@ async function reconcileSpecOwnerGate({
}
const designApprovers = [...new Set([...engineeringOwners, ...designOwners])];
const themeApprovers = [...new Set([...engineeringOwners, ...designOwners])];
+
+ // --- The spec content an approval binds (DEC-14). ---
+ const specPaths = [
+ ...new Set(
+ snapshot.files.flatMap(file =>
+ [file.filename, file.previous_filename].filter(
+ filePath => filePath && isSpecPath(filePath),
+ ),
+ ),
+ ),
+ ].sort();
+ const textCache = new Map();
+ function specText(sha, filePath) {
+ const key = `${sha.toLowerCase()}\0${filePath}`;
+ if (!textCache.has(key)) {
+ textCache.set(
+ key,
+ readSpecContent(pr.head.repo.full_name, sha, filePath),
+ );
+ }
+ return textCache.get(key);
+ }
+ async function fingerprintAt(sha, paths) {
+ const entries = await Promise.all(
+ paths.map(async filePath => ({
+ path: filePath,
+ content: await specText(sha, filePath),
+ })),
+ );
+ return fingerprintSpecContent(entries);
+ }
+ // An approved commit's spec paths join the head's, so dropping an approved
+ // change no longer matches. A failed comparison matches nothing.
+ async function specPathsAt(sha) {
+ const {data} = await github.rest.repos.compareCommitsWithBasehead({
+ owner,
+ repo,
+ basehead: `${pr.base.sha}...${sha}`,
+ });
+ return (data.files ?? []).flatMap(file =>
+ [file.filename, file.previous_filename].filter(
+ filePath => filePath && isSpecPath(filePath),
+ ),
+ );
+ }
+ async function hasCurrentContent(sha) {
+ try {
+ const paths = [
+ ...new Set([...specPaths, ...(await specPathsAt(sha))]),
+ ].sort();
+ const [atHead, atSha] = await Promise.all([
+ fingerprintAt(initialHead, paths),
+ fingerprintAt(sha, paths),
+ ]);
+ return atHead.fingerprint === atSha.fingerprint;
+ } catch (error) {
+ core.warning(`Could not compare ${sha.slice(0, 7)}: ${error.message}`);
+ return false;
+ }
+ }
+ const currentContent = await fingerprintAt(initialHead, specPaths);
+ // Only commits an eligible owner named, by review or command, are read.
+ const authorLogin = pr.user.login.toLowerCase();
+ const ownerReviews = reviews.filter(review => {
+ const login = review.user?.login?.toLowerCase();
+ // GitHub refuses an author's approving review; never count one anyway.
+ return login && login !== authorLogin && allOwners.has(login);
+ });
+ const namedShas = new Set([
+ ...ownerReviews.map(review => review.commit_id?.toLowerCase()),
+ ...comments
+ .filter(comment =>
+ allOwners.has(comment.user?.login?.toLowerCase() ?? ''),
+ )
+ .map(comment => parseOwnerCommandTarget(comment.body)?.sha),
+ ]);
+ const sameContent = new Set([initialHead.toLowerCase()]);
+ for (const sha of [...namedShas].filter(Boolean)) {
+ if (!sameContent.has(sha) && (await hasCurrentContent(sha))) {
+ sameContent.add(sha);
+ }
+ }
+ const approvesCurrentContent = sha =>
+ sha != null && sameContent.has(sha.toLowerCase());
+
const decisionInput = {
- reviews,
+ reviews: ownerReviews,
comments,
dismissalEvents: timeline,
headSha: initialHead,
+ approvesCurrentContent,
};
const specDecision = requiredGroups.spec
? resolveOwnerDecision({...decisionInput, owners: engineeringOwners})
@@ -489,19 +758,37 @@ async function reconcileSpecOwnerGate({
]
.filter(Boolean)
.filter((ownerName, index, owners) => owners.indexOf(ownerName) === index);
- const requiredOwnerDescription = [
- requiredGroups.spec
- ? `an engineering owner (${engineeringOwners.join(',')})`
- : null,
- requiredGroups.design
- ? `a design approver (${designApprovers.join(',')})`
- : null,
- requiredGroups.theme
- ? `a theme approver (${themeApprovers.join(',')})`
- : null,
- ]
- .filter(Boolean)
- .join(' and ');
+ const missingGroups = {
+ spec: !specDecision.approved,
+ design: !designDecision.approved,
+ theme: !themeDecision.approved,
+ heldBy: [specDecision, designDecision, themeDecision].find(
+ decision => decision.approved === false && decision.source === 'review',
+ )?.owner,
+ };
+ const statusText =
+ ownerApprovalRequired && !approved
+ ? missingGroups.heldBy
+ ? SPEC_WAITING_TEXT.held(missingGroups.heldBy)
+ : SPEC_WAITING_TEXT[missingGroups.spec ? 'eng' : 'design']
+ : ownerApprovalRequired
+ ? approvedDescription(approvingOwners)
+ : 'Draft-only knowledge change; owner approval is not required.';
+ await writeDetails({
+ statusText,
+ headSha: initialHead,
+ approvalRequired: ownerApprovalRequired,
+ approved,
+ records,
+ currentContent,
+ notes: ownerActNotes({
+ reviews: ownerReviews,
+ comments,
+ owners: allOwners,
+ approvesCurrentContent,
+ }),
+ commandProblem,
+ });
if (ownerApprovalRequired && !approved) {
if (!(await isCurrentRun(initialHead))) return;
@@ -511,11 +798,7 @@ async function reconcileSpecOwnerGate({
'd4c5f9',
'Current knowledge records await owner approval',
);
- await setFinalStatus(
- initialHead,
- 'pending',
- `Waiting for ${requiredOwnerDescription} on ${initialHead.slice(0, 7)}.`,
- );
+ await setFinalStatus(initialHead, 'pending', statusText, missingGroups);
return;
}
@@ -530,11 +813,8 @@ async function reconcileSpecOwnerGate({
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.';
+ const successDescription = statusText;
+ approvedBy = ownerApprovalRequired ? approvingOwners : [];
if (!(await isCurrentRun(initialHead))) return;
await removeLabel(env.REVIEW_LABEL);
diff --git a/.github/scripts/spec-owner-reconcile.test.mjs b/.github/scripts/spec-owner-reconcile.test.mjs
index b939a3fc7e..9c6c2e2922 100644
--- a/.github/scripts/spec-owner-reconcile.test.mjs
+++ b/.github/scripts/spec-owner-reconcile.test.mjs
@@ -60,6 +60,14 @@ function context({
};
}
+const reviewGate = (description, state = 'pending') => ({
+ sha: head,
+ context: 'review-required',
+ state,
+ description,
+ creator: {login: 'github-actions[bot]'},
+});
+
function trustedStatus({
runId,
statusContext = 'spec-owner-approval',
@@ -99,16 +107,31 @@ function createHarness({
changedFiles,
headContent = 'kind: architecture\nauthority: current\n',
baseContent = '',
+ // Spec text by commit, for heads before the current one.
+ contentAt = {},
+ // Changed files of an earlier commit against the base; the head's files
+ // when absent.
+ filesAt = {},
+ codeGate = {
+ sha: head,
+ context: 'review-required',
+ state: 'success',
+ description: 'No code review required.',
+ creator: {login: 'github-actions[bot]'},
+ created_at: '2026-08-30T09:00:00Z',
+ },
} = {}) {
const files = changedFiles ?? [changedFile];
const state = {
pullGets: 0,
- statuses: [...statuses],
+ // review-signal's code half of the review gate, already published.
+ statuses: [...statuses, ...(codeGate ? [codeGate] : [])],
comments: [...comments],
reviews: [...reviews],
timeline: [...timeline],
calls: [],
reads: [],
+ summary: null,
labels: new Set(labels),
knownLabels: new Set(labels),
pr: {
@@ -200,11 +223,15 @@ function createHarness({
},
},
repos: {
+ compareCommitsWithBasehead: async ({basehead}) => ({
+ data: {files: filesAt[basehead.split('...')[1]] ?? files},
+ }),
listCommitStatusesForRef: methods.listStatuses,
createCommitStatus: async input => {
onCreateStatus?.(input, state);
state.reads.push(`status:${input.context}:${input.state}`);
const status = {
+ id: (state.nextStatusId = (state.nextStatusId ?? 0) + 1),
...input,
creator: {login: 'github-actions[bot]'},
created_at: '2026-08-30T10:00:30Z',
@@ -214,10 +241,16 @@ function createHarness({
state.calls.push(`status:${input.context}:${input.state}`);
return {data: status};
},
- getContent: async ({ref}) => ({
+ getContent: async ({ref, path: filePath}) => ({
data: {
content: Buffer.from(
- ref === state.pr.head.sha ? headContent : baseContent,
+ `${ref}:${filePath}` in contentAt
+ ? contentAt[`${ref}:${filePath}`]
+ : ref in contentAt
+ ? contentAt[ref]
+ : ref === state.pr.head.sha
+ ? headContent
+ : baseContent,
).toString('base64'),
},
}),
@@ -238,6 +271,13 @@ function createHarness({
const core = {
info: message => state.calls.push(`info:${message}`),
warning: message => state.calls.push(`warning:${message}`),
+ summary: {
+ addRaw(markdown) {
+ state.summary = markdown;
+ return this;
+ },
+ write: async () => {},
+ },
};
return {github, core, state};
}
@@ -252,6 +292,21 @@ async function run(harness, runContext) {
});
}
+// Statuses this run published, without the seeded code half of the gate.
+function published(state) {
+ return state.statuses.filter(
+ status =>
+ !(
+ status.context === 'review-required' &&
+ status.created_at === '2026-08-30T09:00:00Z'
+ ),
+ );
+}
+
+function latestReviewGate(state) {
+ return state.statuses.find(status => status.context === 'review-required');
+}
+
function latestGateStatus(state) {
return state.statuses.find(
status => status.context === 'spec-owner-approval',
@@ -271,8 +326,8 @@ function currentComponentSpec(decision, body = 'Body.') {
return `---\nkind: component\nauthority: current\n---\n\n## Design relationships\n\n${body}\n\n### Design decisions\n\n<!-- design-decisions:v1 -->\n\n| ID | Decision | Intent or reason | Applies to | Allowed variation |\n| --- | --- | --- | --- | --- |\n| DD1 | ${decision} | Preserve emphasis. | Default state | Theme tokens may vary. |\n\n### Theming anatomy\n`;
}
-// Exact-head approval by a real spec owner. The auto-merge mechanics below
-// need an approved head.
+// Exact-head approval by a real spec owner. The approval cases below
+// need an approved head; they must not borrow the design self-attestation.
const specOwnerReview = {
user: {login: 'imdreamrunner'},
state: 'APPROVED',
@@ -299,9 +354,9 @@ describe('spec owner workflow reconciliation', () => {
await run(harness, context({runId: 100n}));
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'success',
- description: expect.stringContaining('Approved by @imdreamrunner'),
+ description: expect.stringContaining('Spec approved by @imdreamrunner'),
});
});
@@ -325,9 +380,9 @@ describe('spec owner workflow reconciliation', () => {
}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'success',
- description: expect.stringContaining('Approved by @josephfarina'),
+ description: expect.stringContaining('Spec approved by @josephfarina'),
});
});
@@ -351,9 +406,11 @@ describe('spec owner workflow reconciliation', () => {
}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'pending',
- description: expect.stringContaining('engineering owner'),
+ description: expect.stringContaining(
+ 'an eng owner can reply /approve-spec <sha>',
+ ),
});
expect(harness.state.calls).not.toContain('enable-auto-merge');
});
@@ -382,9 +439,9 @@ describe('spec owner workflow reconciliation', () => {
}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'success',
- description: expect.stringContaining('Approved by @ernestt'),
+ description: expect.stringContaining('Spec approved by @ernestt'),
});
});
@@ -403,7 +460,7 @@ describe('spec owner workflow reconciliation', () => {
expect(latestGateStatus(harness.state)).toMatchObject({
state: 'success',
- description: 'No knowledge records changed.',
+ description: 'Mirrors review-required · spec ok',
});
expect(harness.state.calls).not.toContain('enable-auto-merge');
});
@@ -426,9 +483,11 @@ describe('spec owner workflow reconciliation', () => {
}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'pending',
- description: expect.stringContaining('theme approver'),
+ description: expect.stringContaining(
+ 'a design or eng owner can reply /approve-spec <sha>',
+ ),
});
expect(harness.state.calls).not.toContain('enable-auto-merge');
expect(harness.state.pr.auto_merge).toBe(null);
@@ -455,9 +514,11 @@ describe('spec owner workflow reconciliation', () => {
}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'pending',
- description: expect.stringContaining('theme approver'),
+ description: expect.stringContaining(
+ 'a design or eng owner can reply /approve-spec <sha>',
+ ),
});
expect(harness.state.calls).not.toContain('enable-auto-merge');
expect(
@@ -496,7 +557,7 @@ describe('spec owner workflow reconciliation', () => {
}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'success',
description: expect.stringContaining('@rubyycheung'),
});
@@ -529,7 +590,7 @@ describe('spec owner workflow reconciliation', () => {
}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'success',
description: expect.stringContaining('@czarandy'),
});
@@ -564,7 +625,7 @@ describe('spec owner workflow reconciliation', () => {
);
expect(harness.state.pullGets).toBe(0);
- expect(harness.state.statuses).toEqual([]);
+ expect(published(harness.state)).toEqual([]);
});
it('abandons the old event when the live head changes', async () => {
@@ -602,6 +663,42 @@ describe('spec owner workflow reconciliation', () => {
).toBe(true);
});
+ it('restores the review gate from a newer run it yields to', async () => {
+ const harness = createHarness({
+ headContent: 'kind: architecture\nauthority: current\n',
+ comments: [{user: {login: 'cixzhang'}, body: `/approve-spec ${head}`}],
+ statuses: [
+ trustedStatus({
+ runId: 101n,
+ description: 'Mirrors review-required · spec waiting (eng)',
+ }),
+ ],
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ target_url: canonicalRunUrl(repository, '101', '1'),
+ });
+ });
+
+ it('leads with code review, and relinks the same text to a newer run', async () => {
+ const harness = createHarness({
+ headContent: 'kind: architecture\nauthority: current\n',
+ codeGate: reviewGate('Waiting on code review: core change'),
+ });
+
+ await run(harness, context({runId: 100n}));
+ await run(harness, context({runId: 101n}));
+
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ description: 'Waiting on code review: core change (+ spec approval)',
+ target_url: canonicalRunUrl(repository, '101', '1'),
+ });
+ });
+
it('skips fork owner reviews before any GitHub API work', async () => {
const review = {
user: {login: 'cixzhang'},
@@ -641,16 +738,17 @@ describe('spec owner workflow reconciliation', () => {
it('orders a dismissal after an earlier command by its timeline time', async () => {
const review = {
id: 17,
- user: {login: 'cixzhang'},
+ user: {login: 'imdreamrunner'},
state: 'DISMISSED',
commit_id: head,
submitted_at: '2026-08-30T09:00:00Z',
updated_at: '2026-08-30T10:02:00Z',
};
- // A same-owner command at 10:01; the dismissal is dated by its 10:02
+ // A same-owner command at 10:01 (a non-author owner, as GitHub accepts no
+ // review from the author); the dismissal is dated by its 10:02
// timeline event, so it is the latest act and the gate waits.
const command = {
- user: {login: 'cixzhang'},
+ user: {login: 'imdreamrunner'},
body: `/approve-spec ${head}`,
created_at: '2026-08-30T10:01:00Z',
};
@@ -703,16 +801,16 @@ describe('spec owner workflow reconciliation', () => {
context({runId: 100n, actor: 'ernestt', author: 'ernestt'}),
);
- expect(latestGateStatus(harness.state)).toMatchObject({
+ expect(latestReviewGate(harness.state)).toMatchObject({
state: 'pending',
- description: expect.stringContaining('engineering owner'),
+ description: expect.stringContaining('an eng owner can reply'),
});
expect(harness.state.calls).not.toContain('enable-auto-merge');
});
it('reconciles same-repository owner reviews automatically', async () => {
const review = {
- user: {login: 'cixzhang'},
+ user: {login: 'czarandy'},
state: 'APPROVED',
commit_id: head,
submitted_at: '2026-08-30T10:00:00Z',
@@ -730,7 +828,7 @@ describe('spec owner workflow reconciliation', () => {
);
expect(harness.state.pullGets).toBeGreaterThan(0);
- expect(latestGateStatus(harness.state).state).toBe('success');
+ expect(latestReviewGate(harness.state).state).toBe('success');
});
it('reconciles an exact-head owner command for a fork current-spec PR', async () => {
@@ -755,7 +853,7 @@ describe('spec owner workflow reconciliation', () => {
);
expect(harness.state.pullGets).toBeGreaterThan(0);
- expect(latestGateStatus(harness.state).state).toBe('success');
+ expect(latestReviewGate(harness.state).state).toBe('success');
});
it('rejects valid-shaped non-owner commands before API work', async () => {
@@ -777,7 +875,7 @@ describe('spec owner workflow reconciliation', () => {
);
expect(harness.state.pullGets).toBe(0);
- expect(harness.state.statuses).toEqual([]);
+ expect(published(harness.state)).toEqual([]);
});
it('rejects non-owner reviews before API work', async () => {
@@ -801,7 +899,7 @@ describe('spec owner workflow reconciliation', () => {
);
expect(harness.state.pullGets).toBe(0);
- expect(harness.state.statuses).toEqual([]);
+ expect(published(harness.state)).toEqual([]);
});
it('rejects ordinary comments before any API work', async () => {
@@ -833,7 +931,7 @@ describe('spec owner workflow reconciliation', () => {
await run(harness, context({runId: 100n}));
- expect(harness.state.statuses).toEqual([]);
+ expect(published(harness.state)).toEqual([]);
expect(harness.state.calls).toEqual([
'info:The pull request is already merged or closed; the gate does not rewrite a settled head.',
]);
@@ -845,7 +943,7 @@ describe('spec owner workflow reconciliation', () => {
await run(harness, context({runId: 100n}));
- expect(harness.state.statuses).toEqual([]);
+ expect(published(harness.state)).toEqual([]);
expect(harness.state.calls).not.toContain(
'status:spec-owner-approval:pending',
);
@@ -946,7 +1044,7 @@ describe('spec owner workflow reconciliation', () => {
await run(harness, context({runId: 100n}));
- expect(latestGateStatus(harness.state).state).toBe('success');
+ expect(latestReviewGate(harness.state).state).toBe('success');
expect(harness.state.calls).not.toContain('enable-auto-merge');
expect(harness.state.pr.auto_merge).toBe(null);
});
@@ -993,72 +1091,245 @@ describe('spec owner workflow reconciliation', () => {
).toBe(true);
});
- describe('an owner command that misses the exact head is answered', () => {
- function commandRun(body, harness = createHarness()) {
- const comment = {
- user: {login: 'cixzhang'},
- body,
- created_at: '2026-08-30T10:00:00Z',
- };
+ describe('one approval binds the spec content (DEC-14)', () => {
+ const oldHead = '3333333333333333333333333333333333333333';
+ const draftRecord = [
+ '---',
+ 'kind: architecture',
+ 'id: architecture:owner-ready',
+ 'authority: draft',
+ 'approved_by: null',
+ 'approved_at: null',
+ '---',
+ '',
+ '# Owner ready',
+ '',
+ 'The contract.',
+ '',
+ ].join('\n');
+ const currentRecord = draftRecord
+ .replace('authority: draft', 'authority: current')
+ .replace('approved_by: null', 'approved_by: cixzhang')
+ .replace('approved_at: null', 'approved_at: 2026-10-28');
+ const changedRecord = currentRecord.replace(
+ 'The contract.',
+ 'A different contract.',
+ );
+ const waiting =
+ '⏳ Waiting for human spec approval: an eng owner can reply /approve-spec <sha>';
+
+ function ownerComment(
+ body,
+ createdAt = '2026-08-30T10:05:00Z',
+ login = 'cixzhang',
+ ) {
+ return {user: {login}, body, created_at: createdAt};
+ }
+
+ async function commentRun(harness, comment, runId = 100n) {
harness.state.comments.push(comment);
- return {
+ await run(
harness,
- comment,
- promise: run(
- harness,
- context({
- runId: 100n,
- eventName: 'issue_comment',
- action: 'created',
- comment,
- }),
- ),
- };
+ context({
+ runId,
+ eventName: 'issue_comment',
+ action: 'created',
+ comment,
+ }),
+ );
}
+ it('keeps an ENGOWNER-authored spec PR pending until /approve-spec <head>', async () => {
+ const harness = createHarness({headContent: currentRecord});
+
+ await run(harness, context({runId: 100n}));
+
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ description: waiting,
+ });
+ expect(latestGateStatus(harness.state)).toMatchObject({
+ state: 'pending',
+ description: 'Mirrors review-required · spec waiting (eng)',
+ });
+ expect(harness.state.calls).not.toContain('create-comment');
+ expect(harness.state.summary).toContain(`/approve-spec ${head}`);
+ expect(harness.state.summary).toContain('architecture:owner-ready');
+ expect(harness.state.summary).toContain('Owner ready');
+
+ await commentRun(harness, ownerComment(`/approve-spec ${head}`), 101n);
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'success',
+ description: '✅ Spec approved by @cixzhang · No code review required.',
+ });
+ expect(latestGateStatus(harness.state).description).toBe(
+ 'Mirrors review-required · spec ok (@cixzhang)',
+ );
+ });
+
it.each([
- ['/approve-spec', 'did not name a commit'],
- ['/approve-spec abc1234', 'full 40-character commit SHA'],
- [`/approve-spec ${nextHead}`, 'is not the current head'],
- ])('answers %s instead of ignoring it', async (body, reason) => {
- const {harness, promise} = commandRun(body);
- await promise;
-
- const help = harness.state.comments.at(-1);
- expect(harness.state.calls).toContain('create-comment');
- expect(help.body).toContain(`<!-- spec-owner-command-help:${head} -->`);
- expect(help.body).toContain(reason);
- expect(help.body).toContain(`/approve-spec ${head}`);
- expect(latestGateStatus(harness.state).state).toBe('pending');
- expect(harness.state.calls).not.toContain('enable-auto-merge');
+ ['a commit that changes no spec text', 'currentRecord', 'review'],
+ ['the draft-to-current flip', 'draftRecord', 'command'],
+ ])('keeps an approval across %s', async (_name, earlier, act) => {
+ const harness = createHarness({
+ headContent: currentRecord,
+ contentAt: {
+ [oldHead]: earlier === 'draftRecord' ? draftRecord : currentRecord,
+ },
+ reviews:
+ act === 'review' ? [{...specOwnerReview, commit_id: oldHead}] : [],
+ comments:
+ act === 'command' ? [ownerComment(`/approve-spec ${oldHead}`)] : [],
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(latestReviewGate(harness.state).state).toBe('success');
});
- it('names the revoke verb the owner actually used', async () => {
- const {harness, promise} = commandRun('/revoke-spec');
- await promise;
+ it('resets an approval when spec text changes, and says so', async () => {
+ const harness = createHarness({
+ headContent: changedRecord,
+ contentAt: {[oldHead]: currentRecord},
+ comments: [ownerComment(`/approve-spec ${oldHead}`)],
+ });
+
+ await run(harness, context({runId: 100n}));
- expect(harness.state.comments.at(-1).body).toContain(
- `/revoke-spec ${head}`,
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ description: waiting,
+ });
+ expect(harness.state.summary).toContain(
+ 'Spec changed after approval at 2026-08-30T10:05:00Z',
);
});
- it('answers a given head only once', async () => {
- const {harness, promise} = commandRun('/approve-spec');
- await promise;
- const {promise: second} = commandRun('/approve-spec', harness);
- await second;
+ it('resets an approval when the head drops an approved spec path', async () => {
+ const dropped = 'docs/specs/dropped/spec.md';
+ const harness = createHarness({
+ headContent: currentRecord,
+ contentAt: {
+ [oldHead]: currentRecord,
+ [`${head}:docs/specs/dropped/spec.md`]: 'base text\n',
+ [`${oldHead}:docs/specs/dropped/spec.md`]: 'approved text\n',
+ },
+ // The approved commit also changed a record the head reverted.
+ filesAt: {
+ [oldHead]: [
+ {filename: 'docs/specs/owner-ready/spec.md', status: 'added'},
+ {filename: dropped, status: 'modified'},
+ ],
+ },
+ comments: [ownerComment(`/approve-spec ${oldHead}`)],
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ description: waiting,
+ });
+ });
+
+ it('reads a spec wait as satisfied code review, not an older code wait', async () => {
+ const harness = createHarness({
+ headContent: currentRecord,
+ comments: [ownerComment(`/approve-spec ${head}`)],
+ // review-clear cleared code review under a spec wait.
+ statuses: [reviewGate(waiting)],
+ codeGate: reviewGate(
+ 'Waiting on code review: core change (+ spec approval)',
+ ),
+ });
+
+ await run(harness, context({runId: 100n}));
- expect(
- harness.state.calls.filter(call => call === 'create-comment'),
- ).toHaveLength(1);
+ expect(latestReviewGate(harness.state).state).toBe('success');
});
- it('stays quiet when the command names the exact head', async () => {
- const {harness, promise} = commandRun(`/approve-spec ${head}`);
- await promise;
+ it('names the owner whose request for changes holds the gate', async () => {
+ const harness = createHarness({
+ headContent: currentRecord,
+ comments: [ownerComment(`/approve-spec ${head}`)],
+ reviews: [
+ {
+ user: {login: 'imdreamrunner'},
+ state: 'CHANGES_REQUESTED',
+ commit_id: head,
+ submitted_at: '2026-08-30T10:06:00Z',
+ },
+ ],
+ });
- expect(harness.state.calls).not.toContain('create-comment');
- expect(latestGateStatus(harness.state).state).toBe('success');
+ await run(harness, context({runId: 100n}));
+
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ description:
+ '⏳ Waiting for human spec approval: @imdreamrunner requested changes and can reply /approve-spec <sha>',
+ });
+ });
+
+ it('recomposes when code review is withdrawn while it writes', async () => {
+ let injected = false;
+ const harness = createHarness({
+ headContent: currentRecord,
+ comments: [ownerComment(`/approve-spec ${head}`)],
+ // review-clear withdraws code approval between this job's read and write.
+ onCreateStatus: (input, state) => {
+ if (input.context !== 'review-required' || injected) return;
+ injected = true;
+ state.statuses.unshift({
+ ...reviewGate('Waiting on code review after approval withdrawal.'),
+ id: 999,
+ });
+ },
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ description: 'Waiting on code review after approval withdrawal.',
+ });
+ });
+
+ it('withdraws on /revoke-spec, says who, and approves again after it', async () => {
+ const harness = createHarness({
+ headContent: currentRecord,
+ comments: [ownerComment(`/approve-spec ${head}`)],
+ });
+
+ await commentRun(
+ harness,
+ ownerComment('/revoke-spec', '2026-08-30T10:10:00Z'),
+ );
+ expect(latestReviewGate(harness.state)).toMatchObject({
+ state: 'pending',
+ description: waiting,
+ });
+ expect(harness.state.summary).toContain(
+ 'Approval revoked by @cixzhang at 2026-08-30T10:10:00Z',
+ );
+
+ await commentRun(
+ harness,
+ ownerComment(`/approve-spec ${head}`, '2026-08-30T10:15:00Z'),
+ 101n,
+ );
+ expect(latestReviewGate(harness.state).state).toBe('success');
+ });
+
+ it('never counts an approving review by the author', async () => {
+ const harness = createHarness({
+ headContent: currentRecord,
+ reviews: [{...specOwnerReview, user: {login: 'cixzhang'}}],
+ });
+
+ await run(harness, context({runId: 100n}));
+
+ expect(latestReviewGate(harness.state).state).toBe('pending');
});
});
});
diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjs
index 6163d0a4db..2d61a39dd7 100644
--- a/.github/scripts/spec-owner-workflow.test.mjs
+++ b/.github/scripts/spec-owner-workflow.test.mjs
@@ -252,7 +252,7 @@ describe('spec-only workflow contract', () => {
});
it('runs the tested exact-head reconciler from the trusted default branch', () => {
- const workflow = read('.github/workflows/spec-owner-gate.yml');
+ const workflow = read('.github/workflows/review-signal.yml');
const reconciler = read('.github/scripts/spec-owner-reconcile.cjs');
expect(workflow).toContain(
'ref: ${{ github.event.repository.default_branch }}',
@@ -260,17 +260,19 @@ describe('spec-only workflow contract', () => {
expect(workflow).toContain(
'reconcileSpecOwnerGate({github, context, core})',
);
- expect(workflow).not.toContain('concurrency:');
- const reconcileCondition = workflow
- .slice(
- workflow.indexOf(' if: >-', workflow.indexOf(' reconcile:')),
- workflow.indexOf(' runs-on:', workflow.indexOf(' reconcile:')),
- )
+ const specJob = workflow.slice(workflow.indexOf(' spec-owner:'));
+ // A cancelled reconcile could leave its head without a terminal status,
+ // so the spec-owner job never joins a cancel group (AST-030 FR15).
+ expect(specJob).not.toContain('concurrency:');
+ expect(specJob).not.toContain('cancel-in-progress');
+ expect(workflow).not.toMatch(/^concurrency:/m);
+ const reconcileCondition = specJob
+ .slice(specJob.indexOf(' if: >-'), specJob.indexOf(' name:'))
.replace(/^ if: >-\s*/, '')
.replace(/\s+/g, ' ')
.trim();
expect(reconcileCondition).toBe(
- "(github.event_name != 'pull_request_review' || github.event.pull_request.head.repo.full_name == github.repository) && (github.event_name != 'issue_comment' || (github.event.issue.pull_request != null && (startsWith(github.event.comment.body, '/approve-spec') || startsWith(github.event.comment.body, '/revoke-spec'))))",
+ "(github.event_name != 'pull_request_review' || github.event.pull_request.head.repo.full_name == github.repository) && (github.event_name != 'issue_comment' || (github.event.issue.pull_request != null && (startsWith(github.event.comment.body, '/approve-spec') || startsWith(github.event.comment.body, '/revoke-spec')))) && (github.event_name != 'workflow_dispatch' || github.event.inputs.pr != '')",
);
expect(workflow).toContain('pull_request_review:');
expect(workflow).toContain('issue_comment:');
@@ -315,12 +317,12 @@ describe('spec-only workflow contract', () => {
expect(reconciler).toContain('designDecision.approved');
expect(reconciler).toContain('themeDecision.approved');
expect(reconciler).toContain('context: GATE_STATUS_CONTEXT');
- // The gate decides approval only; merging stays with the merge path.
+ // The gate decides approval only; merging stays with the merge queue.
expect(reconciler).not.toContain('enablePullRequestAutoMerge');
});
it('derives the comment trigger from the parser\u2019s own prefixes', () => {
- const workflow = read('.github/workflows/spec-owner-gate.yml');
+ const workflow = read('.github/workflows/review-signal.yml');
const {OWNER_COMMAND_PREFIXES} = require(
path.join(root, '.github/scripts/spec-owner-decision.cjs'),
);
@@ -376,4 +378,16 @@ describe('spec-only workflow contract', () => {
expect(workflow).toContain("needs.resolve.outputs.spec_only == 'true'");
expect(workflow).not.toContain("context: 'visual-acceptance'");
});
+
+ it('lets only the two review workflows publish the review contexts', () => {
+ const dir = path.join(root, '.github/workflows');
+ const writers = fs
+ .readdirSync(dir)
+ .filter(name =>
+ /context: '(review-required|spec-owner-approval)'|reconcileSpecOwnerGate/.test(
+ fs.readFileSync(path.join(dir, name), 'utf8'),
+ ),
+ );
+ expect(writers.sort()).toEqual(['review-clear.yml', 'review-signal.yml']);
+ });
});
diff --git a/.github/scripts/workflow-paths.test.mjs b/.github/scripts/workflow-paths.test.mjs
index 4da12b13a2..b889e11caf 100644
--- a/.github/scripts/workflow-paths.test.mjs
+++ b/.github/scripts/workflow-paths.test.mjs
@@ -27,7 +27,6 @@ const REQUIRED_CONTEXT_WORKFLOWS = [
'ci.yml',
'lint.yml',
'review-signal.yml',
- 'spec-owner-gate.yml',
];
// `**`, `**/*`, `**/**`: a glob that matches every path is no allowlist.
const MATCH_ALL = /^\*\*(\/\*+)*$/;
diff --git a/.github/workflows/review-clear.yml b/.github/workflows/review-clear.yml
index 80387757e8..8813cd1e81 100644
--- a/.github/workflows/review-clear.yml
+++ b/.github/workflows/review-clear.yml
@@ -172,6 +172,7 @@ jobs:
let codeWithdrawn = false;
let gateOwned = false;
let appClearedStatus = false;
+ let shownSatisfied = false;
try {
const reviews = await github.paginate(github.rest.pulls.listReviews, {
owner, repo, pull_number: prNumber, per_page: 100,
@@ -190,23 +191,20 @@ jobs:
github.rest.repos.listCommitStatusesForRef,
{owner, repo, ref: headSha, per_page: 100},
);
- const latestGateStatus = statuses.find(
- (status) => status.context === 'review-required',
- );
- const trustedStatus =
- latestGateStatus?.creator?.login === 'github-actions[bot]';
- const description = latestGateStatus?.description || '';
- appClearedStatus =
- trustedStatus &&
- latestGateStatus.state === 'success' &&
- description === APP_CLEARED;
+ // The newest status that names the code review, read past spec
+ // waits and spec-approval prefixes.
+ const code = decision.readCodeGate(statuses, {latest: false});
+ const description = code?.description || '';
+ appClearedStatus = code?.gated === false && description === APP_CLEARED;
+ // An owned gate showing code review satisfied (a clear, or a spec
+ // wait or approval over one) stays so only while approvals hold.
+ shownSatisfied = decision.readCodeGate(statuses)?.gated === false;
const statusOwnsGate =
- trustedStatus &&
- ((latestGateStatus.state === 'pending' &&
+ code != null &&
+ ((code.gated &&
(description.startsWith('Waiting on code review:') ||
description === 'Waiting on code review after approval withdrawal.')) ||
- (latestGateStatus.state === 'success' &&
- (description === OWNER_CLEARED || appClearedStatus)));
+ (!code.gated && (description === OWNER_CLEARED || appClearedStatus)));
gateOwned =
full.labels.some((label) => label.name === CODE) || statusOwnsGate;
} catch (e) {
@@ -222,7 +220,7 @@ jobs:
// still approves this head. If it no longer does — the author lost
// write access, the permission could not be read, or REVIEW_APP was
// unset — restore the pending gate (fail closed).
- if (!codeApproved && appClearedStatus) codeWithdrawn = true;
+ if (!codeApproved && (appClearedStatus || shownSatisfied)) codeWithdrawn = true;
if (!codeApproved && !codeWithdrawn) {
core.info(`PR #${prNumber}: no effective review-state change; leaving gate as-is.`);
return;
@@ -240,14 +238,43 @@ jobs:
}
const labels = current.labels.map((l) => l.name);
+ // One review gate (DEC-14): code review leads; success needs both.
+ async function publishReviewGate(codeGated, codeDescription) {
+ // Write, then read the spec half once more: the spec-owner job
+ // writes its half before it reads this one, so one of the two
+ // always sees the other's latest write.
+ let gate = null;
+ for (let pass = 0; pass < 2; pass++) {
+ let statuses = [];
+ try {
+ statuses = await github.paginate(github.rest.repos.listCommitStatusesForRef, {
+ owner, repo, ref: headSha, per_page: 100,
+ });
+ } catch (e) {
+ core.warning(`Could not read the spec decision: ${e.message}`);
+ }
+ const next = decision.composeReviewGate({
+ codeGated,
+ codeDescription,
+ spec: decision.readSpecGate(statuses),
+ });
+ if (gate && next.state === gate.state && next.description === gate.description) break;
+ gate = next;
+ await github.rest.repos.createCommitStatus({
+ owner, repo, sha: headSha,
+ context: 'review-required',
+ state: gate.state,
+ description: gate.description,
+ target_url: gate.target_url,
+ });
+ }
+ return gate;
+ }
+
if (codeWithdrawn) {
// The commit status is the hard gate; publish it before the advisory
// label. If this POST fails, throw without any label-only mutation.
- await github.rest.repos.createCommitStatus({
- owner, repo, sha: headSha, context: 'review-required',
- state: 'pending',
- description: 'Waiting on code review after approval withdrawal.',
- });
+ await publishReviewGate(true, 'Waiting on code review after approval withdrawal.');
core.info(`review-required status → pending on #${prNumber}.`);
if (!labels.includes(CODE)) {
await github.rest.issues.addLabels({
@@ -268,11 +295,7 @@ jobs:
core.warning(`Could not remove ${CODE} (may already be gone): ${e.message}`);
}
}
- await github.rest.repos.createCommitStatus({
- owner, repo, sha: headSha, context: 'review-required',
- state: 'success',
- description: codeApprovedBy === 'review-app' ? APP_CLEARED : OWNER_CLEARED,
- });
+ await publishReviewGate(false, codeApprovedBy === 'review-app' ? APP_CLEARED : OWNER_CLEARED);
core.info(`review-required status → success on #${prNumber}.`);
// Neutralize stale check-run(s) of the same name so the rollup isn't
// dragged to failure by a pre-status action_required leftover.
diff --git a/.github/workflows/review-signal.yml b/.github/workflows/review-signal.yml
index 8f84781aa3..e50a00a709 100644
--- a/.github/workflows/review-signal.yml
+++ b/.github/workflows/review-signal.yml
@@ -56,7 +56,10 @@
# trusted workflow SHA; the visual classifier comes from the PR base ref. It reads
# eng/design owner lists from repository VARIABLES (vars.ENGOWNERS /
# vars.DESIGNOWNERS) — no checkout and no execution of PR-controlled code.
-# Do not add checkout or build steps here.
+# Do not add checkout or build steps to the flag job.
+#
+# ONE REVIEW GATE (spec:AST-030 FR15): "review-required" carries code review and
+# the spec half the spec-owner job decides (DEC-14) from the trusted default branch.
name: Review signal
@@ -66,6 +69,10 @@ on:
types: [opened, synchronize, reopened, ready_for_review, converted_to_draft]
pull_request_review:
types: [submitted, dismissed]
+ # Owner commands for the spec-owner job. The job-level filter skips every
+ # other comment before a runner starts.
+ issue_comment:
+ types: [created]
# Manual re-trigger. The App only auto-runs on the PR events above, so if it
# ever misses one (e.g. the workflow was added after a PR was opened, leaving
# the required "review-required" check stuck as Expected/pending), this is the
@@ -80,16 +87,11 @@ on:
permissions: {}
-concurrency:
- # One group per PR for the event/single-dispatch paths; a run-scoped group for
- # the backfill-all dispatch so it is never cancelled by an unrelated re-run.
- group: review-signal-${{ github.event.pull_request.number || github.event.inputs.pr || github.run_id }}
- cancel-in-progress: true
-
env:
CODE_LABEL: 'needs:code-review'
DESIGN_LABEL: 'needs:design-review'
COMMUNITY_LABEL: 'community'
+ REVIEW_LABEL: needs:spec-owner-review
jobs:
# ---------------------------------------------------------------------------
@@ -101,6 +103,11 @@ jobs:
|| github.event_name == 'workflow_dispatch'
name: Flag review signals
runs-on: ubuntu-slim
+ # Per PR (run-scoped for backfill-all). Only this job cancels: a cancelled
+ # spec-owner reconcile could leave its head without a terminal status.
+ concurrency:
+ group: review-signal-${{ github.event.pull_request.number || github.event.inputs.pr || github.run_id }}
+ cancel-in-progress: true
permissions:
pull-requests: write
contents: read
@@ -193,6 +200,57 @@ jobs:
const authorIsEng = engOwners.includes(author);
const authorIsDesign = designOwners.includes(author);
+ // Match the trusted workflow version: an older PR base can predate
+ // this helper even though the running workflow requires it.
+ const { data: reviewDecisionFile } = await github.rest.repos.getContent({
+ owner, repo, ref: context.sha,
+ path: '.github/scripts/review-signal-decision.cjs',
+ });
+ const reviewDecisionSource = Buffer.from(
+ reviewDecisionFile.content,
+ 'base64',
+ ).toString('utf8');
+ const reviewDecisionModule = { exports: {} };
+ new Function('module', 'exports', 'require', reviewDecisionSource)(
+ reviewDecisionModule,
+ reviewDecisionModule.exports,
+ () => { throw new Error('review-signal-decision.cjs must stay dependency-free'); },
+ );
+ const reviewDecision = reviewDecisionModule.exports;
+
+ // One review gate (DEC-14): code review leads; success needs both.
+ async function publishReviewGate(codeGated, codeDescription) {
+ // Write, then read the spec half once more: the spec-owner job
+ // writes its half before it reads this one, so one of the two
+ // always sees the other's latest write.
+ let gate = null;
+ for (let pass = 0; pass < 2; pass++) {
+ let statuses = [];
+ try {
+ statuses = await github.paginate(github.rest.repos.listCommitStatusesForRef, {
+ owner, repo, ref: pr.head.sha, per_page: 100,
+ });
+ } catch (e) {
+ core.warning(`Could not read the spec decision: ${e.message}`);
+ }
+ const next = reviewDecision.composeReviewGate({
+ codeGated,
+ codeDescription,
+ spec: reviewDecision.readSpecGate(statuses),
+ });
+ if (gate && next.state === gate.state && next.description === gate.description) break;
+ gate = next;
+ await github.rest.repos.createCommitStatus({
+ owner, repo, sha: pr.head.sha,
+ context: 'review-required',
+ state: gate.state,
+ description: gate.description,
+ target_url: gate.target_url,
+ });
+ }
+ return gate;
+ }
+
// Bot PRs: no gate, no community label. Set the check to success so
// a required "review-required" doesn't block them, drop any stray
// gate/community labels, and stop.
@@ -210,31 +268,10 @@ jobs:
}
}
}
- await github.rest.repos.createCommitStatus({
- owner, repo, sha: pr.head.sha,
- context: 'review-required', state: 'success',
- description: 'Automated (bot) PR — exempt from review gates.',
- });
+ await publishReviewGate(false, 'Automated (bot) PR — exempt from code review.');
return;
}
- // Match the trusted workflow version: an older PR base can predate
- // this helper even though the running workflow requires it.
- const { data: reviewDecisionFile } = await github.rest.repos.getContent({
- owner, repo, ref: context.sha,
- path: '.github/scripts/review-signal-decision.cjs',
- });
- const reviewDecisionSource = Buffer.from(
- reviewDecisionFile.content,
- 'base64',
- ).toString('utf8');
- const reviewDecisionModule = { exports: {} };
- new Function('module', 'exports', 'require', reviewDecisionSource)(
- reviewDecisionModule,
- reviewDecisionModule.exports,
- () => { throw new Error('review-signal-decision.cjs must stay dependency-free'); },
- );
- const reviewDecision = reviewDecisionModule.exports;
// --- Changed files. ---
const allFiles = await github.paginate(github.rest.pulls.listFiles, {
@@ -608,15 +645,8 @@ jobs:
: codeHighRisk && codeApproved
? 'Cleared by code-owner approval.'
: 'No code review required.';
- await github.rest.repos.createCommitStatus({
- owner,
- repo,
- sha: pr.head.sha,
- context: 'review-required',
- state: codeGated ? 'pending' : 'success',
- description: gateDescription,
- });
- core.info(`review-required status: ${codeGated ? 'pending' : 'success'}`);
+ const gate = await publishReviewGate(codeGated, gateDescription);
+ core.info(`review-required status: ${gate.state}`);
// Neutralize any stale "review-required" CHECK RUN left over from the
// pre-status gate. Such a leftover (conclusion action_required) drags
// the status rollup to FAILURE even though we now gate via a commit
@@ -652,3 +682,41 @@ jobs:
steps:
- name: Note review state change
run: echo "Review state changed; review-clear will reconcile the code gate."
+
+ # Spec owner gate: reconcile the spec half for one pull request.
+ spec-owner:
+ # Fork reviews (read-only tokens) are skipped; owners use the command. The
+ # reconciler orders concurrent runs itself: no concurrency group.
+ if: >-
+ (github.event_name != 'pull_request_review' ||
+ github.event.pull_request.head.repo.full_name == github.repository) &&
+ (github.event_name != 'issue_comment' ||
+ (github.event.issue.pull_request != null &&
+ (startsWith(github.event.comment.body, '/approve-spec') ||
+ startsWith(github.event.comment.body, '/revoke-spec')))) &&
+ (github.event_name != 'workflow_dispatch' || github.event.inputs.pr != '')
+ name: Spec owner gate
+ runs-on: ubuntu-slim
+ permissions:
+ contents: read
+ pull-requests: write
+ issues: write
+ statuses: write
+ steps:
+ # Every privileged event checks out the trusted default branch. Never
+ # execute the PR merge ref or PR-controlled helpers with write permissions.
+ - uses: actions/checkout@v7
+ with:
+ ref: ${{ github.event.repository.default_branch }}
+
+ - name: Reconcile owner gate
+ uses: actions/github-script@v9
+ with:
+ retries: 3
+ script: |
+ const path = require('node:path');
+ const {reconcileSpecOwnerGate} = require(path.join(
+ process.env.GITHUB_WORKSPACE,
+ '.github/scripts/spec-owner-reconcile.cjs',
+ ));
+ await reconcileSpecOwnerGate({github, context, core});
diff --git a/.github/workflows/spec-owner-gate.yml b/.github/workflows/spec-owner-gate.yml
deleted file mode 100644
index a4449f0297..0000000000
--- a/.github/workflows/spec-owner-gate.yml
+++ /dev/null
@@ -1,70 +0,0 @@
-# Copyright (c) Meta Platforms, Inc. and affiliates.
-
-# Current knowledge records are consequential to future reviewers. Creating,
-# changing, or archiving one waits for owner approval. ENGOWNERS may approve
-# every record kind. Current design and theme records, component/module
-# Design-decision-only changes, and normative design assets also accept
-# DESIGNOWNERS. Mixed DD plus other component/module spec edits require both
-# design and engineering. Other mixed PRs keep every applicable owner-group
-# requirement. Pure spec-record PRs skip heavy CI only when every changed path
-# is recognized; current records need approval on the exact current head. The
-# gate decides approval only; it never enables auto-merge.
-name: Spec owner gate
-
-on:
- pull_request_target:
- branches: [main]
- types: [opened, synchronize, reopened, ready_for_review, converted_to_draft]
- pull_request_review:
- types: [submitted, dismissed]
- issue_comment:
- types: [created]
- workflow_dispatch:
- inputs:
- pr:
- description: Pull request number to reconcile
- required: true
- type: string
-
-permissions: {}
-
-env:
- REVIEW_LABEL: needs:spec-owner-review
-
-jobs:
- reconcile:
- # Fork review events have read-only tokens. Same-repo reviews reconcile
- # automatically; fork approvals use the trusted issue_comment command path.
- # The comment filter admits any owner-command shape, including one missing
- # the head SHA, so the reconciler answers it instead of ignoring it.
- if: >-
- (github.event_name != 'pull_request_review' ||
- github.event.pull_request.head.repo.full_name == github.repository) &&
- (github.event_name != 'issue_comment' ||
- (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
- pull-requests: write
- issues: write
- statuses: write
- steps:
- # Every privileged event checks out the trusted default branch. Never
- # execute the PR merge ref or PR-controlled helpers with write permissions.
- - uses: actions/checkout@v7
- with:
- ref: ${{ github.event.repository.default_branch }}
-
- - name: Reconcile owner gate
- uses: actions/github-script@v9
- with:
- retries: 3
- script: |
- const path = require('node:path');
- const {reconcileSpecOwnerGate} = require(path.join(
- process.env.GITHUB_WORKSPACE,
- '.github/scripts/spec-owner-reconcile.cjs',
- ));
- await reconcileSpecOwnerGate({github, context, core});
diff --git a/docs/README.md b/docs/README.md
index 98e2cf9d28..1054f2fd59 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -54,13 +54,9 @@ Every knowledge record declares `authority: draft | current | archived`.
accept current `.github/DESIGNOWNERS` members. Legacy v1 `owners` metadata is
descriptive and does not grant approval rights.
- Pull requests that create, change, or archive a `current` record wait on the
- `spec-owner-approval` status for their exact current head. Draft-only records
- pass that status after validation without an owner review.
-- Any ENGOWNER can approve another author's current-record PR through GitHub
- review. A DESIGNOWNER may do the same for current design or theme records and
- normative design assets. When an eligible approver is also the PR author, they
- comment `/approve-spec <full-head-sha>`. Any new commit invalidates that
- approval.
+ review gate, `review-required`, until an owner approves their content with
+ `/approve-spec <full-sha>` or a review (`architecture:knowledge-contracts`
+ DEC-14). Draft-only records need no owner approval.
- Only `current` documents guide implementation and review.
- A specification describes durable ideal behavior independently of any one pull
request. Pull requests and issues may appear only as clearly non-authoritative
diff --git a/docs/architecture/knowledge-contracts.md b/docs/architecture/knowledge-contracts.md
index f0af637ecf..87e961f7a8 100644
--- a/docs/architecture/knowledge-contracts.md
+++ b/docs/architecture/knowledge-contracts.md
@@ -260,7 +260,7 @@ Every record is either:
pull request. External contributors follow the normal contribution flow and
MUST NOT be asked to author specifications; maintainers own any missing
authority. A human request supplies intent but becomes committed current
- authority only through exact-head owner approval.
+ authority only through owner approval of the current spec content (DEC-14).
### Review evidence placement
@@ -712,11 +712,13 @@ this flow passes the historical review benchmark and is enforced on pull request
and head bytes. DD-only requires unchanged path, kind, authority, and every byte
outside a valid optional block.
- `.github/scripts/change-scope.cjs` identifies pure spec-record changes.
-- `.github/workflows/spec-owner-gate.yml` binds approval to the exact pull
- request head. Approval for every record kind derives from `.github/ENGOWNERS`;
- current design and theme records, normative design assets, and DD-only current
- component/module changes additionally accept `.github/DESIGNOWNERS`. A mixed
- DD plus other component/module edit requires both groups. Record metadata never
+- `.github/workflows/review-signal.yml` publishes the one review gate,
+ `review-required`, which carries spec-owner approval too (DEC-14). One owner approval covers every knowledge-record change in the pull
+ request and binds the approved spec content, not a commit. Approval for every
+ record kind derives from `.github/ENGOWNERS`; current design and theme records,
+ normative design assets, and DD-only current component/module changes
+ additionally accept `.github/DESIGNOWNERS`. A mixed DD plus other
+ component/module edit requires both groups. Record metadata never
self-authorizes. The gate decides approval only; it never enables auto-merge.
- `.github/workflows/review-signal.yml` lets a DESIGNOWNER author bypass the
engineering gate only when trusted-base code verifies every changed Core line
@@ -770,8 +772,8 @@ maintainers and review agents are responsible for the spec system. They record
the ruling in the same branch when possible, or in a small linked lower spec PR
when the contributor branch cannot be updated. Rejected implementation is
removed or changed; a rejected alternative is recorded only when it protects a
-consequential boundary from being debated again. Final exact-head approval
-attests that the decision and implementation agree.
+consequential boundary from being debated again. Final owner approval of the
+current spec content attests that the decision and implementation agree.
Rejected: requiring the owner to open a second pull request for every ruling,
because it separates the answer from the change and adds unnecessary review
@@ -908,8 +910,8 @@ remains in `docs/design/`.
A team DESIGNOWNER may include the local decision, implementation, and evidence
in one atomic appearance-only pull request. DD-only current-record changes route
to design approval; mixing a DD edit with another component/module contract edit
-requires both design and engineering. A DESIGNOWNER approves with an exact-head
-review or `/approve-spec <head>` like every other owner. The Core code gate is bypassed only when trusted-base
+requires both design and engineering. A DESIGNOWNER approves with
+`/approve-spec <sha>` like every other owner. The Core code gate is bypassed only when trusted-base
classification proves an existing-file declaration-only appearance diff and no
other code reason applies. Any uncertainty, contributor-authored change, behavior,
JSX, API, package, barrel, new component, or unknown runtime path fails closed to
@@ -918,11 +920,11 @@ engineering review.
External contributors explain intent and supply normal evidence; maintainers own
specification work and never require contributors to author it. A request or
conversation is decision input, not committed authority. The edited current
-record becomes reusable only after exact-head owner approval.
+record becomes reusable only after owner approval of its content (DEC-14).
Rejected: sidecar records or one design record per pixel tweak, because they split
routine intent from its owner; treating a design request as authority before
-exact-head approval, because reviewable intent is not yet committed policy.
+owner approval, because reviewable intent is not yet committed policy.
### DEC-11 — A review-app approval clears the code gate for write-access authors
@@ -984,23 +986,95 @@ documentation stand in as that contract.
Rejected: package-local spec formats, because their records skip structure
checks, the owner gate, and path routing.
+### DEC-14 — One owner approval binds a pull request's spec content
+
+**Reference:** `architecture:knowledge-contracts/DEC-14`
+**Decider:** `cixzhang`, `2026-10-28`
+
+A spec owner reviews a pull request's knowledge-record changes together and
+approves or reworks them as a whole. The approval binds the **spec content**:
+one fingerprint over every changed knowledge-record and normative design-asset
+path, each read at a commit. In Markdown records the fingerprint omits the
+front-matter `authority`, `approved_by`, and `approved_at` values, so recording
+an approval and moving a record from `draft` to `current` never change it. The
+workflow computes every fingerprint from the pull request's files; no comment,
+label, or status supplies it.
+
+- **Approving acts.** Each of these, by an eligible owner, approves the content
+ of the commit it names, and counts while that commit's fingerprint equals the
+ current head's:
+ - an `/approve-spec <sha>` comment naming a full commit SHA; the SHA states
+ which content the owner reviewed;
+ - a GitHub approving review, for its commit.
+
+ `/revoke-spec`, with or without a SHA, and a request for changes on other
+ spec content withdraw that owner's approval until they approve again. A
+ request for changes on the current spec content holds the gate until that
+ owner approves again. Reactions are not approvals.
+ Eligibility follows the owner groups above. An ENGOWNER author may approve
+ their own pull request with `/approve-spec`; an approving review by the
+ author never counts.
+
+- **What keeps approval.** Commits that change only other paths, merges from
+ the base branch, rebases, and approval bookkeeping keep the fingerprint, so
+ they keep every approval.
+- **What resets it.** A change to approved spec text, a newly changed spec
+ path, or a head that drops an approved spec change; the earlier approval stops
+ counting until an owner approves a commit that carries the current content.
+- **One review gate.** `review-required` carries both the code review and the
+ spec approval. Code review leads while it is missing; once it is satisfied, a
+ missing spec approval shows on the same status; success needs both. A missing
+ approval is `pending`, never a failure. The status names who can approve:
+
+ | Spec groups still missing | `review-required` text |
+ | ---------------------------------------- | ----------------------------------------------------------------------------------------- |
+ | engineering (alone or with design/theme) | `⏳ Waiting for human spec approval: an eng owner can reply /approve-spec <sha>` |
+ | design or theme only | `⏳ Waiting for human spec approval: a design or eng owner can reply /approve-spec <sha>` |
+
+ A request for changes holding the gate names its owner instead: `…: @owner
+requested changes and can reply /approve-spec <sha>`. An approved spec change
+ reads `✅ Spec approved by @owner` beside the code review result. An ENGOWNER
+ approval satisfies every group.
+
+- **Details.** The gate's details give the head's command to copy, list the
+ changed records (id, title, authority change, and the group each needs), the
+ changed paths and the fingerprint, and say why an earlier act no longer
+ counts: the spec changed after approval, it was revoked, or the command was
+ malformed.
+- **Mirror.** `spec-owner-approval` reports the spec half with a minimal
+ description while branch protection still requires it; it decides nothing
+ `review-required` does not already show.
+- **Event coverage.** Every pull-request event, same-repository review, and
+ owner command re-evaluates the gate, and each evaluation publishes a terminal
+ state for the head it read. A fork review carries a read-only token and is
+ skipped, so owners approve a fork pull request with the command. Comments that
+ are not owner commands start no runner.
+
+Rejected: exact-head binding (recording the approval and every base merge
+forced re-approval of unchanged text); per-record or per-section approval
+(spec review is all or nothing); a command without a SHA (a push just before
+it would be approved unseen); a separate spec status (one gate, one message);
+reaction approvals (no event, so a polling job); a workflow-pushed
+`draft`-to-`current` change (it starts no checks and cannot write a fork).
+
## Verification
-| Invariant | Evidence | Failure signal |
-| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| INV1, INV6 | `scripts/check-knowledge.test.mjs` | An unapproved current record or unmigrated active record passes |
-| INV5, INV7 | `.github/scripts/change-scope.test.mjs` | A template, schema, guidance, architecture, code change, unsafe rename, or truncated list qualifies as spec-only |
-| Approval follows the current head | `.github/scripts/spec-owner-decision.test.mjs` | An approval for another commit clears the gate, a self-declared owner becomes an approver, or the wrong owner group approves a current record |
-| INV3, INV4, INV11 | Blinded historical review benchmark | Reviewer re-asks a settled decision, invents a new one, approves an unsettled public delta, or treats a contradiction as preserves |
-| INV10 | Record-content and review-disposition fixtures | A spec assigns a PR verdict, or a reviewer treats a PR link as authority |
-| INV13 | Blinded spec-authorship fixture plus overlap-search receipt | An author creates parallel authority, searches only landed records or filenames, misses open work on the canonical owner, or treats an open PR as authority |
-| INV14, INV15 | Narrow-decision and mixed-intent review fixtures | A current visual slice is forced to contract its whole module, a separable tagalong blocks a repair, or review reports a gap without a landing-ready remedy |
-| INV16, INV17 | Spec-first review and missing-context fixtures | Generated checklist completeness overrides authority, review invents product direction, restates supplied context, or fails to identify an unrelated tagalong or affected caller state |
-| INV18 | Spec-review mechanism analysis plus owner migration receipt | A new/amended product spec requires a private mechanism without proving it is public, silently invalidates an existing current record, or leaves touched architecture wording in the product contract |
-| INV19 | Spec-review ownership-collision receipt and human decision | Automated review approves a product contract, omits current/open owner overlap, misses a collision or architecture leak, or returns only a human hold without actionable written analysis |
-| INV20, DEC-9 | `scripts/check-knowledge.test.mjs` and `scripts/review-global-baselines.mjs` | A matching review misses a current global claim, loads a draft/nonmatching claim, loses base-commit provenance, or treats the rest of a routed record as authority |
-| INV21, DEC-10 | `.github/scripts/component-design-decisions.test.mjs`, `.github/scripts/review-signal-decision.test.mjs`, `.github/scripts/spec-owner-decision.test.mjs`, and `.github/scripts/lib/classify-visual.test.mjs` | A malformed/local DD escapes validation, stale approval clears a new head, owner routing loses mixed-change gates, or executable/API/unknown runtime code is misclassified as appearance-only |
-| DEC-11 | `.github/scripts/review-signal-decision.test.mjs`, `.github/scripts/review-clear-workflow.test.mjs`, and `.github/scripts/review-signal-workflow.test.mjs` | An app approval clears a read-only or fork author or an earlier head; a later app request for changes or dismissal leaves the gate clear; an app approval overrides an ENGOWNER request for changes; or an unset app or unreadable permission clears the gate |
+| Invariant | Evidence | Failure signal |
+| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| INV1, INV6 | `scripts/check-knowledge.test.mjs` | An unapproved current record or unmigrated active record passes |
+| INV5, INV7 | `.github/scripts/change-scope.test.mjs` | A template, schema, guidance, architecture, code change, unsafe rename, or truncated list qualifies as spec-only |
+| Approval follows the spec content | `.github/scripts/spec-owner-decision.test.mjs` | An approval of other spec content clears the gate, a self-declared owner becomes an approver, or the wrong owner group approves a current record |
+| INV3, INV4, INV11 | Blinded historical review benchmark | Reviewer re-asks a settled decision, invents a new one, approves an unsettled public delta, or treats a contradiction as preserves |
+| INV10 | Record-content and review-disposition fixtures | A spec assigns a PR verdict, or a reviewer treats a PR link as authority |
+| INV13 | Blinded spec-authorship fixture plus overlap-search receipt | An author creates parallel authority, searches only landed records or filenames, misses open work on the canonical owner, or treats an open PR as authority |
+| INV14, INV15 | Narrow-decision and mixed-intent review fixtures | A current visual slice is forced to contract its whole module, a separable tagalong blocks a repair, or review reports a gap without a landing-ready remedy |
+| INV16, INV17 | Spec-first review and missing-context fixtures | Generated checklist completeness overrides authority, review invents product direction, restates supplied context, or fails to identify an unrelated tagalong or affected caller state |
+| INV18 | Spec-review mechanism analysis plus owner migration receipt | A new/amended product spec requires a private mechanism without proving it is public, silently invalidates an existing current record, or leaves touched architecture wording in the product contract |
+| INV19 | Spec-review ownership-collision receipt and human decision | Automated review approves a product contract, omits current/open owner overlap, misses a collision or architecture leak, or returns only a human hold without actionable written analysis |
+| INV20, DEC-9 | `scripts/check-knowledge.test.mjs` and `scripts/review-global-baselines.mjs` | A matching review misses a current global claim, loads a draft/nonmatching claim, loses base-commit provenance, or treats the rest of a routed record as authority |
+| INV21, DEC-10 | `.github/scripts/component-design-decisions.test.mjs`, `.github/scripts/review-signal-decision.test.mjs`, `.github/scripts/spec-owner-decision.test.mjs`, and `.github/scripts/lib/classify-visual.test.mjs` | A malformed/local DD escapes validation, stale approval clears a new head, owner routing loses mixed-change gates, or executable/API/unknown runtime code is misclassified as appearance-only |
+| DEC-14 | `.github/scripts/spec-owner-reconcile.test.mjs`, `.github/scripts/spec-owner-decision.test.mjs`, and `.github/scripts/spec-owner-workflow.test.mjs` | A non-spec commit, base merge, rebase, or status flip resets approval; changed spec text or a new spec path keeps it; a command naming other spec content, a reaction, a non-owner act, or an author review approves; `review-required` succeeds while spec approval is missing or before the spec decision is published; a revoke or request for changes naming other spec content is ignored; a missing approval reports failure; or an evaluation leaves its head without a terminal state |
+| DEC-11 | `.github/scripts/review-signal-decision.test.mjs`, `.github/scripts/review-clear-workflow.test.mjs`, and `.github/scripts/review-signal-workflow.test.mjs` | An app approval clears a read-only or fork author or an earlier head; a later app request for changes or dismissal leaves the gate clear; an app approval overrides an ENGOWNER request for changes; or an unset app or unreadable permission clears the gate |
| Invariant | Evidence | Failure signal |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
diff --git a/docs/contributing/pull-requests.md b/docs/contributing/pull-requests.md
index 0dcd66617c..7055a23344 100644
--- a/docs/contributing/pull-requests.md
+++ b/docs/contributing/pull-requests.md
@@ -90,7 +90,7 @@ code and evidence, and shared or cross-component rules stay in `docs/design/`.
External contributors keep the normal contribution flow and are never asked to
author specifications. If authority is missing, a maintainer records the owner
ruling. A human request supplies intent, but it becomes current committed
-authority only after exact-head owner approval.
+authority only after an owner approves its content.
A new visual representation, subjective direction, or interaction model remains a design decision. Put a shared decision in its own design specification; keep a durable component-local decision in the owning component/module table.
diff --git a/docs/design/README.md b/docs/design/README.md
index 8dc3354b36..0ddc71e261 100644
--- a/docs/design/README.md
+++ b/docs/design/README.md
@@ -47,13 +47,14 @@ Generated audit screenshots remain audit evidence rather than design authority.
Private design sources stay private and are never named or linked here.
New design specs start as `draft`. Initial promotion to `current`, later changes,
-and normative asset updates require exact-head approval from any current member
-of `.github/ENGOWNERS` or `.github/DESIGNOWNERS`. A mixed PR still needs an
+and normative asset updates require approval of their content from any current
+member of `.github/ENGOWNERS` or `.github/DESIGNOWNERS`
+(`architecture:knowledge-contracts` DEC-14). A mixed PR still needs an
ENGOWNER for non-design current records. The design record names its content
owners separately from this repository gate.
-A DESIGNOWNER approves with an exact-head review or `/approve-spec <head>`,
-like every other owner; in a mixed PR every other applicable code or spec-owner
+A DESIGNOWNER approves with a review or `/approve-spec <sha>`, like every other
+owner; in a mixed PR every other applicable code or spec-owner
group remains required. The gate decides approval only; it never enables
auto-merge.
diff --git a/docs/specs/AST-030/spec.md b/docs/specs/AST-030/spec.md
index 6384c9bf8d..48c0ea0867 100644
--- a/docs/specs/AST-030/spec.md
+++ b/docs/specs/AST-030/spec.md
@@ -73,8 +73,9 @@ they are separately named.
- Define compatibility semantics or release-pair delta classes. Those belong to
[`spec:AST-017`](../AST-017/spec.md); this record routes their checks and owns the
exact-main release-check execution boundary.
-- Remove required check names, branch protection, merge-queue coverage, or
- exact-head owner approval.
+- Remove required check names (other than retiring the `spec-owner-approval`
+ mirror, FR15), branch protection, merge-queue coverage, or owner approval of
+ spec content.
- Infer safety from file extensions, directory names, or the absence of a known
risky path.
- Treat tests, specifications, generated files, or changesets as proof that the
@@ -92,7 +93,7 @@ they are separately named.
| Surface | Positive path ownership | Current check owners |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
- | `knowledge` | canonical system, family, design, theme, component, and module records | knowledge validation and exact-head spec-owner approval |
+ | `knowledge` | canonical system, family, design, theme, component, and module records | knowledge validation and spec-owner approval of the current spec content |
| `docsite` | the docsite application | docsite generation and tests |
| `node-tooling` | admitted operational Node tooling whose consumers are covered by Node contract tests | Node Vitest, repository guardrails, and ESLint |
| `runtime:<package>` | public source and package contract for Core, Lab, Charts, Rich Text, Vega, CLI, and Build | the package's unit/type checks plus current broad build and downstream consumer checks; Build's owner includes production CSS-layer browser behavior |
@@ -257,7 +258,8 @@ they are separately named.
relevant on that trigger (`paths:`), and those paths name what the workflow
reads or runs, never everything; a merge-group entry, which cannot filter by
path, keeps running. A workflow that reports a required context (`build`,
- `test`, `docsite-test`, `lint`, `spec-owner-approval`, `review-required`)
+ `test`, `docsite-test`, `lint`, `review-required`, and the
+ `spec-owner-approval` mirror while it is required, FR15)
starts on every pull request and is never path-filtered: the trusted
classifier's positive surfaces (FR1–FR5) choose the work inside it, and a job
whose suite does not apply reports success without running it (FR7). A push
@@ -266,6 +268,19 @@ they are separately named.
`paths-ignore` or another exclusion list, which would run on any path no one
thought to exclude.
+- **FR15 — One review gate carries code review and spec approval.** The
+ review workflow (`review-signal.yml`) and `review-clear.yml` publish
+ `review-required`, which carries both the code review and spec-owner approval
+ (`architecture:knowledge-contracts` DEC-14); no other workflow publishes a
+ review or spec context. `spec-owner-approval` is published only as a mirror of
+ the spec half while branch protection still requires it. The spec-owner job
+ evaluates pull-request, review, and owner-command comment events, runs
+ without cancel-in-progress, and publishes a terminal state for the head it
+ read. It skips fork review events, whose tokens are read-only; fork approvals
+ use the owner command. Only the review-signal job keeps a per-pull-request
+ cancel group. Each writer of `review-required` composes both halves and links
+ a spec wait to the spec decision's details. Comments that are not owner
+ commands start no runner, and no scheduled job reads approvals.
- **FR16 — One author's pull requests share the heavy suites.** On a pull
request, the heavy browser suites (the interaction proofs and the Build
package's browser and fixture-contrast contracts) run only when the pull
@@ -343,6 +358,7 @@ read change (FR14).
| FR12 | Storybook visual-plan, canonical workflow, and repository-owner guard tests | PR scope; full-plan maintenance; report-only publication; deployment/a11y/RTL/vibe artifacts | another workflow captures or compares pixels, a renamed or aliased owner escapes the guard, or legitimate non-visual artifacts are rejected |
| FR13 | classifier, workflow contract, component-analysis and RTL-scope tests | component change; shared module; Changeset beside code; infrastructure path; incomplete list; no build | an infrastructure path is scoped, a file-system guard test is skipped, a reverse dependent leaves visual/RTL or enters PR accessibility, or a full-suite event is narrowed |
| FR14 | `workflow-paths.test.mjs` over every workflow | path allowlist; required-context workflow | a `paths-ignore`, a match-all or exclusion glob, or a path filter on a workflow that reports a required context fails |
+| FR15 | workflow contract and reconciler tests | ENGOWNER spec PR; owner command; other comment; fork review; non-spec PR | `review-required` succeeds while spec approval is missing, another workflow publishes a review context, a fork review starts the spec checks, or a non-command comment starts a runner |
| FR16 | `heavy-caps-action.test.mjs` cap cases and heavy-job contract | fourth-oldest PR; thirteenth heavy run of the day, beside cancelled, light and other-branch runs; agent lane and its five-PR and forty-run backstops; bot; the deciding run; re-run; failed lookup | a heavy suite that runs ahead of the author's three oldest PRs, or past the daily cap, a capped job that passes, or a re-run that is held fails |
| FR17 | `ci-pr-gate.test.mjs` over every `pull_request` workflow and the shared conditions | branch here, fork with and without `ci:run`, another label, draft with the label, ready, push, merge group, dispatch | a job that can start on a pull request without the condition, a label trigger, a required job that skips for a pull request that may not run CI, or a draft or unlabelled fork that runs fails |
@@ -501,6 +517,20 @@ starts.
Rejected: `paths-ignore` lists (they run on whatever is new); path-filtering a
required context (its check would never report).
+### DEC-9 — Spec-owner approval runs in the review workflow
+
+**Reference:** `spec:AST-030/DEC-9`
+**Decider:** `cixzhang`, `2026-10-28`
+
+The spec-owner gate and the review gate read the same pull-request events, so
+they run in one workflow, and a contributor reads one review gate:
+`review-required` names whichever review is still missing, code first.
+`spec-owner-approval` remains a mirror until branch protection stops requiring
+it, so the merge rules change only when an administrator removes it.
+
+Rejected: keeping a separate spec-owner workflow, which split one review state
+across two workflows and two visible gates.
+
## Open questions
None.
diff --git a/docs/themes/README.md b/docs/themes/README.md
index 48c356970f..c65393d1c8 100644
--- a/docs/themes/README.md
+++ b/docs/themes/README.md
@@ -37,6 +37,7 @@ and other knowledge relationships rather than separate relation fields:
Only `current` records are policy. A draft may link another draft while decisions
are being developed, but current records may depend only on current records.
-Current theme records require exact-head approval from the committed union of
+Current theme records require approval of their content (`architecture:knowledge-contracts`
+DEC-14) from the committed union of
`.github/ENGOWNERS` and `.github/DESIGNOWNERS`. Theme records do not declare an
`owners` field, and record metadata never grants approval rights.