An open source design system that's fully customizable and agent ready
TypeScript
Add component-local design decisions (#6502)
Cindy Zhang9e4c5458d210
diff --git a/.github/DESIGNOWNERS b/.github/DESIGNOWNERSindex 6eae010ad8..b32fea8b6d 100644--- a/.github/DESIGNOWNERS+++ b/.github/DESIGNOWNERS@@ -1,11 +1,14 @@# Design owners for the Astryx repository# Design-team members. This list has three responsibilities:#-# - Current design and theme specs and normative design assets may receive-# exact-head approval from any DESIGNOWNER. ENGOWNERS may approve every spec.+# - 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 author may attest an exact PR head by marking the PR ready for# review. That evidence satisfies the design-approval group even in a mixed PR;-# every other applicable code or spec-owner group remains required. The+# every other applicable code or spec-owner group remains required. A+# classifier-proven appearance-only Core runtime change may also bypass the+# engineering review gate only when no other code reason applies. The# existing gate may enable squash auto-merge only when every changed path is a# recognized spec record and every required group and branch check passes.# - Review tooling may use the list to frame design-authored changes.diff --git a/.github/PULL_REQUEST_TEMPLATE/visual-update.md b/.github/PULL_REQUEST_TEMPLATE/visual-update.mdindex 50c9be21ed..e4eb1d6daa 100644--- a/.github/PULL_REQUEST_TEMPLATE/visual-update.md+++ b/.github/PULL_REQUEST_TEMPLATE/visual-update.md@@ -8,8 +8,12 @@Choose one and link it:-- [ ] Correction already settled by current component, family, design, theme, or objective accessibility authority.-- [ ] New visual direction settled by an owner-approved current specification.+- [ ] Existing component/module `DD` row reused or amended.+- [ ] Durable component-local intent added to the optional `Design decisions` table by a team design owner.+- [ ] 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. -->## Before and afterdiff --git a/.github/scripts/component-design-decisions.cjs b/.github/scripts/component-design-decisions.cjsnew file mode 100644index 0000000000..66c650b2f8--- /dev/null+++ b/.github/scripts/component-design-decisions.cjs@@ -0,0 +1,325 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';+/* global module */++// This helper is loaded by privileged workflow code from the trusted base.+// Keep it dependency-free CommonJS and deterministic over the supplied bytes.++const DESIGN_DECISIONS_MARKER = '<!-- design-decisions:v1 -->';+const DESIGN_DECISIONS_COLUMNS = [+ 'ID',+ 'Decision',+ 'Intent or reason',+ 'Applies to',+ 'Allowed variation',+];+const DESIGN_DECISION_ID = /^DD[1-9][0-9]*$/;++function splitMarkdownRow(line) {+ const trimmed = line.trim();+ if (!trimmed.startsWith('|') || !trimmed.endsWith('|')) return null;++ const cells = [];+ let cell = '';+ let escaped = false;+ for (const character of trimmed.slice(1, -1)) {+ if (escaped) {+ cell += character;+ escaped = false;+ } else if (character === '\\') {+ cell += character;+ escaped = true;+ } else if (character === '|') {+ cells.push(cell.trim());+ cell = '';+ } else {+ cell += character;+ }+ }+ cells.push(cell.trim());+ return cells;+}++function parseFrontmatterIdentity(content, filePath) {+ const problems = [];+ const values = new Map();+ for (const fieldName of ['authority', 'kind']) {+ const pattern = new RegExp(+ `^${fieldName}:\\s*['"]?([a-z-]+)['"]?\\s*$`,+ 'gm',+ );+ const matches = [...content.matchAll(pattern)];+ if (matches.length === 0) {+ problems.push(`${filePath}: missing frontmatter field ${fieldName}.`);+ continue;+ }+ if (matches.length > 1) {+ problems.push(`${filePath}: duplicate frontmatter field ${fieldName}.`);+ continue;+ }+ values.set(fieldName, matches[0][1]);+ }++ return {+ authority: values.get('authority') ?? null,+ kind: values.get('kind') ?? null,+ problems,+ };+}++function parseDesignDecisionsBlock(content, filePath = '<knowledge record>') {+ const problems = [];+ const headingMatches = [+ ...content.matchAll(/^### Design decisions[ \t]*\r?$/gm),+ ];+ const markerMatches = [...content.matchAll(/<!-- design-decisions:v1 -->/g)];++ if (headingMatches.length === 0) {+ if (markerMatches.length > 0) {+ problems.push(+ `${filePath}: ${DESIGN_DECISIONS_MARKER} must be inside a unique "Design decisions" subsection.`,+ );+ }+ return {+ present: false,+ valid: problems.length === 0,+ rows: [],+ problems,+ range: null,+ raw: null,+ outside: content,+ };+ }++ if (headingMatches.length > 1) {+ problems.push(`${filePath}: duplicate "Design decisions" subsections.`);+ }+ if (markerMatches.length !== 1) {+ problems.push(+ `${filePath}: "Design decisions" requires exactly one ${DESIGN_DECISIONS_MARKER} marker.`,+ );+ }++ const heading = headingMatches[0];+ const precedingSections = [+ ...content.slice(0, heading.index).matchAll(/^##(?!#)\s+(.+?)\s*$/gm),+ ];+ if (precedingSections.at(-1)?.[1] !== 'Design relationships') {+ problems.push(+ `${filePath}: "Design decisions" must be a level-three subsection of "Design relationships".`,+ );+ }++ const afterHeading = heading.index + heading[0].length;+ const followingHeading = /^#{1,3}(?!#)\s+.+?\s*$/gm;+ followingHeading.lastIndex = afterHeading;+ const next = followingHeading.exec(content);+ const end = next?.index ?? content.length;+ const range = {start: heading.index, end};+ const raw = content.slice(range.start, range.end);+ const outside = content.slice(0, range.start) + content.slice(range.end);+ const rows = [];++ const subsectionLines = content.slice(afterHeading, end).split(/\r?\n/);+ let lineIndex = 0;+ while (+ lineIndex < subsectionLines.length &&+ subsectionLines[lineIndex].trim() === ''+ ) {+ lineIndex += 1;+ }++ if (subsectionLines[lineIndex]?.trim() !== DESIGN_DECISIONS_MARKER) {+ problems.push(+ `${filePath}: "Design decisions" must contain only its marker, exact table, contiguous rows, and whitespace.`,+ );+ } else {+ lineIndex += 1;+ while (+ lineIndex < subsectionLines.length &&+ subsectionLines[lineIndex].trim() === ''+ ) {+ lineIndex += 1;+ }++ const header = splitMarkdownRow(subsectionLines[lineIndex] ?? '');+ lineIndex += 1;+ const separator = splitMarkdownRow(subsectionLines[lineIndex] ?? '');+ lineIndex += 1;+ if (+ header === null ||+ header.length !== DESIGN_DECISIONS_COLUMNS.length ||+ !header.every((cell, index) => cell === DESIGN_DECISIONS_COLUMNS[index])+ ) {+ problems.push(+ `${filePath}: ${DESIGN_DECISIONS_MARKER} table columns must be exactly ${DESIGN_DECISIONS_COLUMNS.join(', ')}.`,+ );+ }+ if (+ separator === null ||+ separator.length !== DESIGN_DECISIONS_COLUMNS.length ||+ !separator.every(cell => /^:?-{3,}:?$/.test(cell))+ ) {+ problems.push(+ `${filePath}: ${DESIGN_DECISIONS_MARKER} must include a valid Markdown separator row.`,+ );+ }++ const seenIds = new Set();+ while (lineIndex < subsectionLines.length) {+ const line = subsectionLines[lineIndex];+ if (line.trim() === '') break;+ const cells = splitMarkdownRow(line);+ if (cells === null) break;+ if (cells.length !== DESIGN_DECISIONS_COLUMNS.length) {+ problems.push(+ `${filePath}: every design-decision row must have exactly ${DESIGN_DECISIONS_COLUMNS.length} cells.`,+ );+ } else if (cells.some(cell => cell.length === 0)) {+ problems.push(+ `${filePath}: every authored design-decision row must have non-empty cells.`,+ );+ } else {+ const id = cells[0];+ if (!DESIGN_DECISION_ID.test(id)) {+ problems.push(+ `${filePath}: design-decision id ${JSON.stringify(id)} must match DD1, DD2, and so on.`,+ );+ } else if (seenIds.has(id)) {+ problems.push(`${filePath}: duplicate design-decision id ${id}.`);+ }+ seenIds.add(id);+ rows.push({+ id,+ decision: cells[1],+ intentOrReason: cells[2],+ appliesTo: cells[3],+ allowedVariation: cells[4],+ });+ }+ lineIndex += 1;+ }++ while (+ lineIndex < subsectionLines.length &&+ subsectionLines[lineIndex].trim() === ''+ ) {+ lineIndex += 1;+ }+ if (lineIndex !== subsectionLines.length) {+ problems.push(+ `${filePath}: "Design decisions" must contain only its marker, exact table, contiguous rows, and whitespace.`,+ );+ }+ }++ return {+ present: true,+ valid: problems.length === 0,+ rows,+ problems,+ range,+ raw,+ outside,+ };+}++function validateDesignDecisionsBlock(+ parsed,+ {allowHeaderOnly = false, filePath = '<knowledge record>'} = {},+) {+ const problems = [...parsed.problems];+ if (parsed.present && parsed.rows.length === 0 && !allowHeaderOnly) {+ problems.push(+ `${filePath}: an authored "Design decisions" subsection requires at least one decision row.`,+ );+ }+ return problems;+}++function classifyDesignDecisionChange({+ basePath,+ headPath,+ baseContent,+ headContent,+}) {+ const samePath =+ typeof basePath === 'string' &&+ typeof headPath === 'string' &&+ basePath === headPath;+ const baseBlock =+ typeof baseContent === 'string'+ ? parseDesignDecisionsBlock(baseContent, basePath || '<base>')+ : {+ present: false,+ valid: true,+ raw: null,+ outside: baseContent,+ problems: [],+ };+ const headBlock =+ typeof headContent === 'string'+ ? parseDesignDecisionsBlock(headContent, headPath || '<head>')+ : {+ present: false,+ valid: true,+ raw: null,+ outside: headContent,+ problems: [],+ };+ const baseIdentity =+ typeof baseContent === 'string'+ ? parseFrontmatterIdentity(baseContent, basePath || '<base>')+ : {authority: null, kind: null, problems: []};+ const headIdentity =+ typeof headContent === 'string'+ ? parseFrontmatterIdentity(headContent, headPath || '<head>')+ : {authority: null, kind: null, problems: []};+ const problems = [+ ...validateDesignDecisionsBlock(baseBlock, {+ filePath: basePath || '<base>',+ }),+ ...validateDesignDecisionsBlock(headBlock, {+ filePath: headPath || '<head>',+ }),+ ...baseIdentity.problems,+ ...headIdentity.problems,+ ];+ const blockChanged = baseBlock.raw !== headBlock.raw;++ if (!samePath) {+ return {+ classification: 'mixed',+ blockChanged,+ problems: [...problems, 'Knowledge-record renames fail closed.'],+ };+ }+ if (problems.length > 0) {+ return {classification: 'mixed', blockChanged, problems};+ }+ if (!blockChanged) {+ return {classification: 'no-dd-change', blockChanged: false, problems: []};+ }++ const sameComponentKind =+ baseIdentity.kind === headIdentity.kind &&+ (baseIdentity.kind === 'component' || baseIdentity.kind === 'module');+ const currentOnBothSides =+ baseIdentity.authority === 'current' &&+ headIdentity.authority === 'current';+ const outsideUnchanged = baseBlock.outside === headBlock.outside;+ if (sameComponentKind && currentOnBothSides && outsideUnchanged) {+ return {classification: 'dd-only', blockChanged: true, problems: []};+ }++ return {classification: 'mixed', blockChanged: true, problems: []};+}++module.exports = {+ DESIGN_DECISIONS_COLUMNS,+ DESIGN_DECISIONS_MARKER,+ classifyDesignDecisionChange,+ parseDesignDecisionsBlock,+ validateDesignDecisionsBlock,+};diff --git a/.github/scripts/component-design-decisions.test.mjs b/.github/scripts/component-design-decisions.test.mjsnew file mode 100644index 0000000000..2b5d6ba1d4--- /dev/null+++ b/.github/scripts/component-design-decisions.test.mjs@@ -0,0 +1,372 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {readFileSync} from 'node:fs';+import {createRequire} from 'node:module';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';++const require = createRequire(import.meta.url);+const {+ DESIGN_DECISIONS_COLUMNS,+ classifyDesignDecisionChange,+ parseDesignDecisionsBlock,+ validateDesignDecisionsBlock,+} = require('./component-design-decisions.cjs');++function record({+ kind = 'component',+ authority = 'current',+ before = 'Body.',+ decisions = null,+ after = 'More body.',+} = {}) {+ const block =+ decisions === null+ ? ''+ : `\n\n### Design decisions\n\n<!-- design-decisions:v1 -->\n\n| ${DESIGN_DECISIONS_COLUMNS.join(' | ')} |\n| --- | --- | --- | --- | --- |${decisions+ .map(row => `\n| ${row.join(' | ')} |`)+ .join('')}`;+ return `---\nkind: ${kind}\nauthority: ${authority}\n---\n\n# Record\n\n## Design relationships\n\n${before}${block}\n\n### Theming anatomy\n\n${after}\n`;+}++const row = [+ 'DD1',+ 'Keep the label visually quiet.',+ 'The primary action remains easiest to scan.',+ 'Default label',+ 'Theme token substitutions may preserve contrast.',+];++describe('parseDesignDecisionsBlock', () => {+ it('accepts an absent optional block', () => {+ const parsed = parseDesignDecisionsBlock(record());+ expect(parsed).toMatchObject({present: false, valid: true, rows: []});+ expect(validateDesignDecisionsBlock(parsed)).toEqual([]);+ });++ it('parses the exact columns and stable IDs', () => {+ const parsed = parseDesignDecisionsBlock(record({decisions: [row]}));+ expect(parsed.valid).toBe(true);+ expect(parsed.rows).toEqual([+ {+ id: 'DD1',+ decision: row[1],+ intentOrReason: row[2],+ appliesTo: row[3],+ allowedVariation: row[4],+ },+ ]);+ expect(validateDesignDecisionsBlock(parsed)).toEqual([]);+ });++ it('allows a header-only template but not an authored record', () => {+ const parsed = parseDesignDecisionsBlock(record({decisions: []}));+ expect(+ validateDesignDecisionsBlock(parsed, {allowHeaderOnly: true}),+ ).toEqual([]);+ expect(validateDesignDecisionsBlock(parsed).join('\n')).toMatch(+ /requires at least one decision row/,+ );+ });++ it.each([+ {+ name: 'wrong parent',+ mutate: value =>+ value.replace(+ '## Design relationships',+ '## Behavior\n\nBody.\n\n## Other',+ ),+ expected: /subsection of "Design relationships"/,+ },+ {+ name: 'duplicate subsection',+ mutate: value => `${value}\n### Design decisions\n`,+ expected: /duplicate "Design decisions"/,+ },+ {+ name: 'missing marker',+ mutate: value => value.replace('<!-- design-decisions:v1 -->', ''),+ expected: /requires exactly one/,+ },+ {+ name: 'wrong columns',+ mutate: value => value.replace('Intent or reason', 'Rationale'),+ expected: /columns must be exactly/,+ },+ {+ name: 'empty cell',+ mutate: value => value.replace(row[2], ''),+ expected: /non-empty cells/,+ },+ {+ name: 'invalid id',+ mutate: value => value.replace('| DD1 |', '| DEC-1 |'),+ expected: /must match DD1/,+ },+ {+ name: 'duplicate id',+ mutate: value =>+ value.replace(+ `| ${row.join(' | ')} |`,+ `| ${row.join(' | ')} |\n| ${row.join(' | ')} |`,+ ),+ expected: /duplicate design-decision id DD1/,+ },+ {+ name: 'trailing prose',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ '\nTrailing prose.\n\n### Theming anatomy',+ ),+ expected: /must contain only its marker/,+ },+ {+ name: 'a deeper heading',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ '\n#### Hidden section\n\n### Theming anatomy',+ ),+ expected: /must contain only its marker/,+ },+ {+ name: 'a second table',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ '\n| Other | Table |\n| --- | --- |\n\n### Theming anatomy',+ ),+ expected: /every design-decision row/,+ },+ {+ name: 'a row after a blank',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ `\n\n| ${row.join(' | ')} |\n\n### Theming anatomy`,+ ),+ expected: /must contain only its marker/,+ },+ {+ name: 'a code fence trick',+ mutate: value =>+ value.replace(+ '<!-- design-decisions:v1 -->',+ '```md\n<!-- design-decisions:v1 -->\n```',+ ),+ expected: /must contain only its marker/,+ },+ {+ name: 'a comment trick',+ mutate: value =>+ value.replace(+ '<!-- design-decisions:v1 -->',+ '<!-- hidden -->\n<!-- design-decisions:v1 -->',+ ),+ expected: /must contain only its marker/,+ },+ ])('rejects $name', ({mutate, expected}) => {+ const parsed = parseDesignDecisionsBlock(+ mutate(record({decisions: [row]})),+ );+ expect(validateDesignDecisionsBlock(parsed).join('\n')).toMatch(expected);+ });+});++describe('classifyDesignDecisionChange', () => {+ const path = 'packages/core/src/Button/Button.spec.md';++ it('stays dependency-free for trusted workflow loading', () => {+ const source = readFileSync(+ fileURLToPath(+ new URL('./component-design-decisions.cjs', import.meta.url),+ ),+ 'utf8',+ );+ const mod = {exports: {}};+ new Function('module', 'exports', 'require', source)(+ mod,+ mod.exports,+ () => {+ throw new Error(+ 'component-design-decisions.cjs must stay dependency-free',+ );+ },+ );+ expect(typeof mod.exports.classifyDesignDecisionChange).toBe('function');+ });++ it('classifies unrelated edits as no DD change', () => {+ expect(+ classifyDesignDecisionChange({+ basePath: path,+ headPath: path,+ baseContent: record(),+ headContent: record({before: 'Changed body.'}),+ }).classification,+ ).toBe('no-dd-change');+ });++ it('classifies a valid current component block edit as DD-only', () => {+ expect(+ classifyDesignDecisionChange({+ basePath: path,+ headPath: path,+ baseContent: record({decisions: [row]}),+ headContent: record({+ decisions: [+ [...row.slice(0, 1), 'Use a quiet label.', ...row.slice(2)],+ ],+ }),+ }).classification,+ ).toBe('dd-only');+ });++ it('classifies a valid current module block edit as DD-only', () => {+ const modulePath =+ 'packages/core/src/Table/plugins/rowStatus/useTableRowStatus.spec.md';+ expect(+ classifyDesignDecisionChange({+ basePath: modulePath,+ headPath: modulePath,+ baseContent: record({kind: 'module', decisions: [row]}),+ headContent: record({+ kind: 'module',+ decisions: [['DD1', 'Use a quiet module label.', ...row.slice(2)]],+ }),+ }).classification,+ ).toBe('dd-only');+ });++ it('classifies adding the optional block as DD-only when every outside byte matches', () => {+ expect(+ classifyDesignDecisionChange({+ basePath: path,+ headPath: path,+ baseContent: record(),+ headContent: record({decisions: [row]}),+ }).classification,+ ).toBe('dd-only');+ });++ it.each([+ {+ name: 'outside bytes also change',+ input: {+ baseContent: record({decisions: [row]}),+ headContent: record({+ before: 'Changed body.',+ decisions: [+ ['DD1', 'Keep the label visually subtle.', ...row.slice(2)],+ ],+ }),+ },+ },+ {+ name: 'authority changes',+ input: {+ baseContent: record({authority: 'draft'}),+ headContent: record({authority: 'current', decisions: [row]}),+ },+ },+ {+ name: 'kind changes',+ input: {+ baseContent: record(),+ headContent: record({kind: 'module', decisions: [row]}),+ },+ },+ {+ name: 'block is malformed',+ input: {+ baseContent: record(),+ headContent: record({decisions: [row]}).replace('| DD1 |', '| bad |'),+ },+ },+ {+ name: 'an authored block has no rows',+ input: {+ baseContent: record(),+ headContent: record({decisions: []}),+ },+ },+ ])('fails closed when $name', ({input}) => {+ expect(+ classifyDesignDecisionChange({basePath: path, headPath: path, ...input})+ .classification,+ ).toBe('mixed');+ });++ it.each([+ {+ name: 'trailing prose',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ '\nTrailing prose.\n\n### Theming anatomy',+ ),+ },+ {+ name: 'a deeper heading',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ '\n#### Hidden section\n\n### Theming anatomy',+ ),+ },+ {+ name: 'a second table',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ '\n| Other | Table |\n| --- | --- |\n\n### Theming anatomy',+ ),+ },+ {+ name: 'a row after a blank',+ mutate: value =>+ value.replace(+ '\n\n### Theming anatomy',+ `\n\n| ${row.join(' | ')} |\n\n### Theming anatomy`,+ ),+ },+ {+ name: 'a code fence trick',+ mutate: value =>+ value.replace(+ '<!-- design-decisions:v1 -->',+ '```md\n<!-- design-decisions:v1 -->\n```',+ ),+ },+ {+ name: 'a comment trick',+ mutate: value =>+ value.replace(+ '<!-- design-decisions:v1 -->',+ '<!-- hidden -->\n<!-- design-decisions:v1 -->',+ ),+ },+ ])('classifies $name as mixed', ({mutate}) => {+ const result = classifyDesignDecisionChange({+ basePath: path,+ headPath: path,+ baseContent: record(),+ headContent: mutate(record({decisions: [row]})),+ });+ expect(result.classification).toBe('mixed');+ expect(result.problems.length).toBeGreaterThan(0);+ });++ it('fails closed on a rename even when the bytes are unchanged', () => {+ expect(+ classifyDesignDecisionChange({+ basePath: path,+ headPath: 'packages/core/src/Action/Action.spec.md',+ baseContent: record(),+ headContent: record(),+ }).classification,+ ).toBe('mixed');+ });+});diff --git a/.github/scripts/lib/classify-visual.js b/.github/scripts/lib/classify-visual.jsindex d25769c1b8..b28dfd76cc 100644--- a/.github/scripts/lib/classify-visual.js+++ b/.github/scripts/lib/classify-visual.js@@ -1,6 +1,5 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-/*** @description Static diff classifier that scores how likely a PR changes rendered* appearance (issue #3667). Pure, dependency-free function over unified diff@@ -10,7 +9,8 @@* `stylex.create` edit in a component .tsx). Also runnable locally via* classify-visual-pr.js for calibration.* @input Unified diff text (git diff <base>...<head>)- * @output classifyVisualDiff: { score, bucket, signals, styleSurfacePaths, evidence }+ * @output classifyVisualDiff: { score, bucket, signals, styleSurfacePaths, evidence,+ * appearanceOnly, appearanceReasons }** SYNC: review-signal.yml loads this file with new Function(module, exports,* require) — keep it dependency-free CJS with a plain module.exports object.@@ -43,77 +43,275 @@// style edit. Kebab-case properties in .css files are normalized before lookup.const CSS_PROPERTIES = new Set([// Layout & box model- 'display', 'position', 'top', 'right', 'bottom', 'left', 'inset',- 'insetBlock', 'insetBlockStart', 'insetBlockEnd',- 'insetInline', 'insetInlineStart', 'insetInlineEnd',- 'width', 'height', 'minWidth', 'minHeight', 'maxWidth', 'maxHeight',- 'blockSize', 'inlineSize', 'minBlockSize', 'minInlineSize',- 'maxBlockSize', 'maxInlineSize',- 'margin', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft',- 'marginBlock', 'marginBlockStart', 'marginBlockEnd',- 'marginInline', 'marginInlineStart', 'marginInlineEnd',- 'padding', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',- 'paddingBlock', 'paddingBlockStart', 'paddingBlockEnd',- 'paddingInline', 'paddingInlineStart', 'paddingInlineEnd',- 'boxSizing', 'aspectRatio', 'zIndex', 'overflow', 'overflowX', 'overflowY',- 'overflowWrap', 'overscrollBehavior', 'visibility', 'contain', 'containerType',- 'containerName', 'float', 'clear', 'objectFit', 'objectPosition',+ 'display',+ 'position',+ 'top',+ 'right',+ 'bottom',+ 'left',+ 'inset',+ 'insetBlock',+ 'insetBlockStart',+ 'insetBlockEnd',+ 'insetInline',+ 'insetInlineStart',+ 'insetInlineEnd',+ 'width',+ 'height',+ 'minWidth',+ 'minHeight',+ 'maxWidth',+ 'maxHeight',+ 'blockSize',+ 'inlineSize',+ 'minBlockSize',+ 'minInlineSize',+ 'maxBlockSize',+ 'maxInlineSize',+ 'margin',+ 'marginTop',+ 'marginRight',+ 'marginBottom',+ 'marginLeft',+ 'marginBlock',+ 'marginBlockStart',+ 'marginBlockEnd',+ 'marginInline',+ 'marginInlineStart',+ 'marginInlineEnd',+ 'padding',+ 'paddingTop',+ 'paddingRight',+ 'paddingBottom',+ 'paddingLeft',+ 'paddingBlock',+ 'paddingBlockStart',+ 'paddingBlockEnd',+ 'paddingInline',+ 'paddingInlineStart',+ 'paddingInlineEnd',+ 'boxSizing',+ 'aspectRatio',+ 'zIndex',+ 'overflow',+ 'overflowX',+ 'overflowY',+ 'overflowWrap',+ 'overscrollBehavior',+ 'visibility',+ 'contain',+ 'containerType',+ 'containerName',+ 'float',+ 'clear',+ 'objectFit',+ 'objectPosition',// Flex & grid- 'flex', 'flexDirection', 'flexWrap', 'flexFlow', 'flexGrow', 'flexShrink',- 'flexBasis', 'justifyContent', 'justifyItems', 'justifySelf',- 'alignContent', 'alignItems', 'alignSelf', 'placeContent', 'placeItems',- 'placeSelf', 'gap', 'rowGap', 'columnGap', 'order',- 'grid', 'gridArea', 'gridAutoColumns', 'gridAutoFlow', 'gridAutoRows',- 'gridColumn', 'gridColumnStart', 'gridColumnEnd',- 'gridRow', 'gridRowStart', 'gridRowEnd',- 'gridTemplate', 'gridTemplateAreas', 'gridTemplateColumns', 'gridTemplateRows',+ 'flex',+ 'flexDirection',+ 'flexWrap',+ 'flexFlow',+ 'flexGrow',+ 'flexShrink',+ 'flexBasis',+ 'justifyContent',+ 'justifyItems',+ 'justifySelf',+ 'alignContent',+ 'alignItems',+ 'alignSelf',+ 'placeContent',+ 'placeItems',+ 'placeSelf',+ 'gap',+ 'rowGap',+ 'columnGap',+ 'order',+ 'grid',+ 'gridArea',+ 'gridAutoColumns',+ 'gridAutoFlow',+ 'gridAutoRows',+ 'gridColumn',+ 'gridColumnStart',+ 'gridColumnEnd',+ 'gridRow',+ 'gridRowStart',+ 'gridRowEnd',+ 'gridTemplate',+ 'gridTemplateAreas',+ 'gridTemplateColumns',+ 'gridTemplateRows',// Color & background- 'color', 'background', 'backgroundColor', 'backgroundImage',- 'backgroundPosition', 'backgroundRepeat', 'backgroundSize', 'backgroundClip',- 'backgroundAttachment', 'backgroundBlendMode', 'accentColor', 'caretColor',- 'colorScheme', 'mixBlendMode', 'backdropFilter', 'filter',+ 'color',+ 'background',+ 'backgroundColor',+ 'backgroundImage',+ 'backgroundPosition',+ 'backgroundRepeat',+ 'backgroundSize',+ 'backgroundClip',+ 'backgroundAttachment',+ 'backgroundBlendMode',+ 'accentColor',+ 'caretColor',+ 'colorScheme',+ 'mixBlendMode',+ 'backdropFilter',+ 'filter',// Border & outline- 'border', 'borderTop', 'borderRight', 'borderBottom', 'borderLeft',- 'borderWidth', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth',- 'borderLeftWidth', 'borderStyle', 'borderColor', 'borderTopColor',- 'borderRightColor', 'borderBottomColor', 'borderLeftColor',- 'borderBlock', 'borderBlockStart', 'borderBlockEnd',- 'borderInline', 'borderInlineStart', 'borderInlineEnd',- 'borderInlineStartWidth', 'borderInlineEndWidth',- 'borderRadius', 'borderTopLeftRadius', 'borderTopRightRadius',- 'borderBottomLeftRadius', 'borderBottomRightRadius',- 'borderStartStartRadius', 'borderStartEndRadius',- 'borderEndStartRadius', 'borderEndEndRadius',- 'borderCollapse', 'borderSpacing', 'outline', 'outlineWidth', 'outlineStyle',- 'outlineColor', 'outlineOffset', 'boxShadow',+ 'border',+ 'borderTop',+ 'borderRight',+ 'borderBottom',+ 'borderLeft',+ 'borderWidth',+ 'borderTopWidth',+ 'borderRightWidth',+ 'borderBottomWidth',+ 'borderLeftWidth',+ 'borderStyle',+ 'borderColor',+ 'borderTopColor',+ 'borderRightColor',+ 'borderBottomColor',+ 'borderLeftColor',+ 'borderBlock',+ 'borderBlockStart',+ 'borderBlockEnd',+ 'borderInline',+ 'borderInlineStart',+ 'borderInlineEnd',+ 'borderInlineStartWidth',+ 'borderInlineEndWidth',+ 'borderRadius',+ 'borderTopLeftRadius',+ 'borderTopRightRadius',+ 'borderBottomLeftRadius',+ 'borderBottomRightRadius',+ 'borderStartStartRadius',+ 'borderStartEndRadius',+ 'borderEndStartRadius',+ 'borderEndEndRadius',+ 'borderCollapse',+ 'borderSpacing',+ 'outline',+ 'outlineWidth',+ 'outlineStyle',+ 'outlineColor',+ 'outlineOffset',+ 'boxShadow',// Typography- 'font', 'fontFamily', 'fontSize', 'fontStyle', 'fontWeight', 'fontVariant',- 'fontVariantNumeric', 'fontFeatureSettings', 'fontStretch',- 'lineHeight', 'letterSpacing', 'textAlign', 'textDecoration',- 'textDecorationLine', 'textDecorationColor', 'textDecorationStyle',- 'textDecorationThickness', 'textUnderlineOffset', 'textTransform',- 'textOverflow', 'textWrap', 'textShadow', 'textIndent', 'verticalAlign',- 'whiteSpace', 'wordBreak', 'wordSpacing', 'hyphens', 'lineClamp',- 'webkitLineClamp', 'webkitBoxOrient', 'tabSize', 'userSelect',+ 'font',+ 'fontFamily',+ 'fontSize',+ 'fontStyle',+ 'fontWeight',+ 'fontVariant',+ 'fontVariantNumeric',+ 'fontFeatureSettings',+ 'fontStretch',+ 'lineHeight',+ 'letterSpacing',+ 'textAlign',+ 'textDecoration',+ 'textDecorationLine',+ 'textDecorationColor',+ 'textDecorationStyle',+ 'textDecorationThickness',+ 'textUnderlineOffset',+ 'textTransform',+ 'textOverflow',+ 'textWrap',+ 'textShadow',+ 'textIndent',+ 'verticalAlign',+ 'whiteSpace',+ 'wordBreak',+ 'wordSpacing',+ 'hyphens',+ 'lineClamp',+ 'webkitLineClamp',+ 'webkitBoxOrient',+ 'tabSize',+ 'userSelect',// Transform, transition & animation- 'transform', 'transformOrigin', 'transformStyle', 'translate', 'rotate',- 'scale', 'perspective', 'perspectiveOrigin', 'transition',- 'transitionProperty', 'transitionDuration', 'transitionTimingFunction',- 'transitionDelay', 'transitionBehavior', 'animation', 'animationName',- 'animationDuration', 'animationTimingFunction', 'animationDelay',- 'animationIterationCount', 'animationDirection', 'animationFillMode',- 'animationPlayState', 'willChange',+ 'transform',+ 'transformOrigin',+ 'transformStyle',+ 'translate',+ 'rotate',+ 'scale',+ 'perspective',+ 'perspectiveOrigin',+ 'transition',+ 'transitionProperty',+ 'transitionDuration',+ 'transitionTimingFunction',+ 'transitionDelay',+ 'transitionBehavior',+ 'animation',+ 'animationName',+ 'animationDuration',+ 'animationTimingFunction',+ 'animationDelay',+ 'animationIterationCount',+ 'animationDirection',+ 'animationFillMode',+ 'animationPlayState',+ 'willChange',// Misc visual- 'opacity', 'cursor', 'pointerEvents', 'resize', 'appearance', 'content',- 'listStyle', 'listStyleType', 'listStylePosition', 'clipPath', 'mask',- 'scrollbarWidth', 'scrollbarGutter', 'scrollBehavior', 'scrollMargin',- 'scrollPadding', 'scrollSnapType', 'scrollSnapAlign', 'touchAction',- 'strokeWidth', 'stroke', 'fill', 'viewTransitionName',+ 'opacity',+ 'cursor',+ 'pointerEvents',+ 'resize',+ 'appearance',+ 'content',+ 'listStyle',+ 'listStyleType',+ 'listStylePosition',+ 'clipPath',+ 'mask',+ 'scrollbarWidth',+ 'scrollbarGutter',+ 'scrollBehavior',+ 'scrollMargin',+ 'scrollPadding',+ 'scrollSnapType',+ 'scrollSnapAlign',+ 'touchAction',+ 'strokeWidth',+ 'stroke',+ 'fill',+ 'viewTransitionName',+]);++const INTERACTION_AFFECTING_STYLE_PROPERTIES = new Set([+ // Element operability and hit testing.+ 'display',+ 'visibility',+ 'pointerEvents',+ 'touchAction',+ 'userSelect',+ 'resize',+ 'cursor',+ // Scrolling, clipping, snapping, and scrollbar affordance.+ 'overflow',+ 'overflowX',+ 'overflowY',+ 'overscrollBehavior',+ 'scrollBehavior',+ 'scrollMargin',+ 'scrollPadding',+ 'scrollSnapType',+ 'scrollSnapAlign',+ 'scrollbarWidth',]);// Values that mark a `prop: value` line as a TypeScript type member rather than// a style declaration (e.g. `width: number;` in a Props interface).-const TYPE_ANNOTATION_VALUE = /^(?:string|number|boolean|void|never|unknown|any)(?:\[\])?[;,]?\s*(?:\/\/.*)?$/;+const TYPE_ANNOTATION_VALUE =+ /^(?:string|number|boolean|void|never|unknown|any)(?:\[\])?[;,]?\s*(?:\/\/.*)?$/;// `<something>Vars.<key>` or `<something>Vars['--key']` — matches every token// group exported from packages/core/src/theme (colorVars, spacingVars,@@ -124,7 +322,12 @@ const TOKEN_REFERENCE = /\b[a-zA-Z][a-zA-Z0-9]*Vars\s*(?:\.[a-zA-Z$_]|\[)/;// `</>`) render nothing and are excluded.const JSX_TAG = /^<\/?[a-zA-Z][\w.]*(?:[\s/>]|$)/;-const WEIGHTS = {cssProperties: 3, tokenReferences: 2, styleSurfaceFiles: 3, jsxStructuralChanges: 1};+const WEIGHTS = {+ cssProperties: 3,+ tokenReferences: 2,+ styleSurfaceFiles: 3,+ jsxStructuralChanges: 1,+};const JSX_CAP = 10;const MAX_EVIDENCE_PER_SIGNAL = 5;@@ -164,6 +367,188 @@ function isStyleSurfaceFile(file) {);}+function isCoreRuntimeFile(file) {+ return (+ /^packages\/core\/src\/.+\.tsx?$/.test(file) &&+ !/\.test\.tsx?$/.test(file) &&+ !/\.stories\.tsx?$/.test(file)+ );+}++function isPublicApiPath(file) {+ return (+ /^packages\/[^/]+\/package\.json$/.test(file) ||+ /^packages\/[^/]+\/src\/(?:.+\/)?index\.tsx?$/.test(file)+ );+}++function isHarmlessStylePunctuation(content) {+ return /^[{}()[\],;]+$/.test(content);+}++const SAFE_STYLE_TOKEN_ROOTS = new Set([+ 'borderVars',+ 'colorVars',+ 'durationVars',+ 'easeVars',+ 'focusVars',+ 'fontWeightVars',+ 'radiusVars',+ 'shadowVars',+ 'sizeVars',+ 'spacingVars',+ 'textSizeVars',+ 'typeScaleVars',+ 'typographyVars',+]);++function isSafeStyleValue(value) {+ const trimmed = value.replace(/,\s*$/, '').trim();+ if (/^(?:true|false|null|undefined)$/.test(trimmed)) return true;+ if (/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[a-zA-Z%]+)?$/.test(trimmed)) {+ return true;+ }+ if (/^'(?:\\.|[^'\\])*'$/.test(trimmed)) return true;+ if (/^"(?:\\.|[^"\\])*"$/.test(trimmed)) return true;+ if (/^[A-Z][A-Z0-9_]*$/.test(trimmed)) return true;+ const token = trimmed.match(+ /^([A-Za-z_$][\w$]*Vars)(?:(?:\.[A-Za-z_$][\w$]*)|(?:\[['"][^'"\r\n]+['"]\]))+$/,+ );+ return token !== null && SAFE_STYLE_TOKEN_ROOTS.has(token[1]);+}++function isSafeStyleDeclarationLine(content, file) {+ if (!isCssPropertyLine(content, file)) return false;+ const match = content.match(/^[a-zA-Z][a-zA-Z0-9]*\s*:\s*(.+)$/);+ return match !== null && isSafeStyleValue(match[1]);+}++function scanStylexStructureLine(line, state, startIndex = 0) {+ let code = '';+ let unsafeSlash = false;+ for (let index = startIndex; index < line.length; index += 1) {+ const character = line[index];+ const next = line[index + 1];+ if (state.blockComment) {+ if (character === '*' && next === '/') {+ state.blockComment = false;+ code += ' ';+ index += 1;+ } else {+ code += ' ';+ }+ continue;+ }+ if (state.quote) {+ code += ' ';+ if (state.escaped) {+ state.escaped = false;+ } else if (character === '\\') {+ state.escaped = true;+ } else if (character === state.quote) {+ state.quote = null;+ }+ continue;+ }+ if (character === '/' && next === '/') {+ code += ' '.repeat(line.length - index);+ break;+ }+ if (character === '/' && next === '*') {+ state.blockComment = true;+ code += ' ';+ index += 1;+ continue;+ }+ if (character === '/' && next !== '/' && next !== '*') {+ unsafeSlash = true;+ }+ if (character === "'" || character === '"' || character === '`') {+ state.quote = character;+ state.escaped = false;+ code += ' ';+ continue;+ }+ code += character;+ }+ return {code, unsafeSlash};+}++function hasCanonicalStylexImport(source) {+ const state = {blockComment: false, escaped: false, quote: null};+ for (const line of source.split(/\r?\n/)) {+ const startsInCode = !state.blockComment && state.quote === null;+ const isCanonicalImport =+ startsInCode &&+ /^\s*import\s+\*\s+as\s+stylex\s+from\s+['"]@stylexjs\/stylex['"]\s*;?\s*$/.test(+ line,+ );+ scanStylexStructureLine(line, state);+ if (isCanonicalImport) return true;+ }+ return false;+}++function stylexCreateLineNumbers(source) {+ if (typeof source !== 'string' || !hasCanonicalStylexImport(source)) {+ return new Set();+ }+ const lines = source.split(/\r?\n/);+ const lexicalState = {blockComment: false, escaped: false, quote: null};+ const codeLines = lines.map(line => {+ const startsInCode =+ !lexicalState.blockComment && lexicalState.quote === null;+ const scanned = scanStylexStructureLine(line, lexicalState);+ return startsInCode ? scanned.code : '';+ });+ const covered = new Set();+ const opener =+ /^\s*(?:(?:export\s+)?const\s+[A-Za-z_$][\w$]*\s*=\s*)?stylex\.create\s*\(\s*\{\s*$/;++ for (let start = 0; start < lines.length; start += 1) {+ if (!opener.test(codeLines[start])) continue;+ const state = {blockComment: false, escaped: false, quote: null};+ let depth = 0;+ let unsafe = false;+ let end = null;+ for (let lineIndex = start; lineIndex < lines.length; lineIndex += 1) {+ const scanned = scanStylexStructureLine(lines[lineIndex], state);+ unsafe ||= scanned.unsafeSlash;+ for (let index = 0; index < scanned.code.length; index += 1) {+ const character = scanned.code[index];+ if (character === '{') depth += 1;+ if (character !== '}') continue;+ depth -= 1;+ if (depth !== 0) continue;+ const remainder = scanned.code.slice(index + 1);+ if (!/^\s*\)\s*;?\s*$/.test(remainder)) unsafe = true;+ end = lineIndex;+ break;+ }+ if (end !== null || unsafe) break;+ }+ if (end === null || unsafe || state.blockComment || state.quote) continue;+ for (let lineIndex = start; lineIndex <= end; lineIndex += 1) {+ covered.add(lineIndex + 1);+ }+ start = end;+ }+ return covered;+}++function sourceProofFor(sources, file, side) {+ const source = sources?.[file]?.[side];+ if (typeof source !== 'string') return null;+ return {+ lines: source.split(/\r?\n/),+ stylexLines: stylexCreateLineNumbers(source),+ };+}++function isVisualEvidenceFile(file) {+ return /\.(?:png|jpe?g|gif|webp|svg)$/.test(file);+}+// kebab-case → camelCase for properties in plain .css filesfunction toCamelCase(prop) {return prop.replace(/-([a-z])/g, (_, c) => c.toUpperCase());@@ -218,19 +603,27 @@ function advanceBlockComment(content, inside) {* Classify a unified diff as visual / likely-visual / maybe-visual / non-visual.** @param {string} diffText - output of `git diff <base>...<head>`- * @param {{ignorePath?: (file: string) => boolean}} [opts] - `ignorePath`+ * @param {{ignorePath?: (file: string) => boolean, sources?: Record<string, {base: string, head: string}>}} [opts] - `ignorePath`* excludes additional paths beyond the built-in rules (e.g. review-signal- * passes its safe-space predicate so lab/sandbox/storybook never count)+ * passes its safe-space predicate so lab/sandbox/storybook never count).+ * `sources` provides trusted base/head bytes used for appearance-only proof.* @returns {{* score: number,* bucket: 'visual'|'likely-visual'|'maybe-visual'|'non-visual',* signals: {cssProperties: number, tokenReferences: number, styleSurfaceFiles: number, jsxStructuralChanges: number},* styleSurfacePaths: string[],* evidence: {cssProperties: Array<{file: string, line: string}>, tokenReferences: Array<{file: string, line: string}>, jsxStructuralChanges: Array<{file: string, line: string}>},+ * appearanceOnly: boolean,+ * appearanceReasons: string[],* }}*/function classifyVisualDiff(diffText, opts = {}) {- const ignorePath = typeof opts.ignorePath === 'function' ? opts.ignorePath : null;+ const ignorePath =+ typeof opts.ignorePath === 'function' ? opts.ignorePath : null;+ const sources =+ opts.sources != null && typeof opts.sources === 'object'+ ? opts.sources+ : {};const signals = {cssProperties: 0,tokenReferences: 0,@@ -244,8 +637,26 @@ function classifyVisualDiff(diffText, opts = {}) {};const styleSurfacePaths = [];const touchedStyleSurfaces = new Set();+ const appearanceReasons = new Set();+ const appearancePunctuation = {added: new Map(), removed: new Map()};+ let sawCoreRuntime = false;+ let sawAppearanceDeclaration = false;++ const rejectAppearance = reason => appearanceReasons.add(reason);+ const countPunctuation = (side, file, content) => {+ const key = `${file}\0${content}`;+ appearancePunctuation[side].set(+ key,+ (appearancePunctuation[side].get(key) ?? 0) + 1,+ );+ };let currentFile = null;+ let currentOldPath = null;+ let oldLineNumber = null;+ let newLineNumber = null;+ let sawHunk = false;+ const sourceProofCache = new Map();// Block-comment state per diff side: a `-` line opening a comment must not// silence subsequent `+` lines. Context lines advance both sides. State// resets at file and hunk boundaries — a hunk can start mid-comment we never@@ -259,42 +670,144 @@ function classifyVisualDiff(diffText, opts = {}) {}};- for (const line of (diffText || '').split('\n')) {+ const diffLines = (diffText || '').split('\n');+ for (let lineIndex = 0; lineIndex < diffLines.length; lineIndex += 1) {+ const line = diffLines[lineIndex];// File boundary — `diff --git a/<old> b/<new>`; the b-side names the file// for adds/renames, and still identifies deleted style files.- const fileMatch = line.match(/^diff --git a\/.* b\/(.*)$/);+ const fileMatch = line.match(/^diff --git a\/(.+) b\/(.+)$/);if (fileMatch) {- currentFile = fileMatch[1];+ const oldPath = fileMatch[1];+ const newPath = fileMatch[2];+ currentOldPath = oldPath;+ currentFile = newPath;+ oldLineNumber = null;+ newLineNumber = null;+ sawHunk = false;inComment.added = false;inComment.removed = false;+ if (oldPath !== newPath) rejectAppearance('renamed path');+ if (isPublicApiPath(oldPath) || isPublicApiPath(newPath)) {+ rejectAppearance('public API or package path');+ }+ for (const candidate of [oldPath, newPath]) {+ if (ignorePath && ignorePath(candidate)) continue;+ if (+ !isCoreRuntimeFile(candidate) &&+ !isIgnoredFile(candidate) &&+ !isVisualEvidenceFile(candidate)+ ) {+ rejectAppearance('unknown runtime path');+ }+ }+ continue;+ }+ if (currentFile === null) continue;+ if (/^(?:new|deleted) file mode\s/.test(line)) {+ if (isCoreRuntimeFile(currentFile)) {+ rejectAppearance('new or deleted Core runtime file');+ }+ continue;+ }+ if (/^rename (?:from|to)\s/.test(line)) {+ rejectAppearance('renamed path');continue;}- if (currentFile === null || !isProductFile(currentFile)) continue;+ if (!isProductFile(currentFile)) continue;if (ignorePath && ignorePath(currentFile)) continue;if (isIgnoredFile(currentFile) || !isScannableFile(currentFile)) continue;- if (line.startsWith('@@')) {+ const hunk = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);+ if (hunk) {+ sawHunk = true;inComment.added = false;inComment.removed = false;+ oldLineNumber = Number(hunk[1]);+ newLineNumber = Number(hunk[2]);+ continue;+ }+ if (+ !sawHunk &&+ (line === `--- a/${currentOldPath}` ||+ line === `+++ b/${currentFile}` ||+ line === '--- /dev/null' ||+ line === '+++ /dev/null')+ ) {continue;}- if (/^\+\+\+|^---/.test(line)) continue;- // Context lines advance the comment state on both sides.+ // Context lines advance the comment state and both source positions.if (!/^[+-]/.test(line)) {- const context = line.slice(1).trim();- [, inComment.added] = advanceBlockComment(context, inComment.added);- [, inComment.removed] = advanceBlockComment(context, inComment.removed);+ if (line.startsWith(' ')) {+ const context = line.slice(1).trim();+ [, inComment.added] = advanceBlockComment(context, inComment.added);+ [, inComment.removed] = advanceBlockComment(context, inComment.removed);+ if (oldLineNumber !== null) oldLineNumber += 1;+ if (newLineNumber !== null) newLineNumber += 1;+ }continue;}const side = line[0] === '+' ? 'added' : 'removed';- const content = line.slice(1).trim();- const [wasInsideComment, nowInsideComment] = advanceBlockComment(content, inComment[side]);+ const sourceSide = side === 'added' ? 'head' : 'base';+ const sourcePath = side === 'added' ? currentFile : currentOldPath;+ const lineNumber = side === 'added' ? newLineNumber : oldLineNumber;+ const rawContent = line.slice(1);+ const content = rawContent.trim();+ if (side === 'added' && newLineNumber !== null) newLineNumber += 1;+ if (side === 'removed' && oldLineNumber !== null) oldLineNumber += 1;+ const [wasInsideComment, nowInsideComment] = advanceBlockComment(+ content,+ inComment[side],+ );inComment[side] = nowInsideComment;++ if (isCoreRuntimeFile(currentFile)) {+ sawCoreRuntime = true;+ const cacheKey = `${sourcePath}\0${sourceSide}`;+ if (!sourceProofCache.has(cacheKey)) {+ sourceProofCache.set(+ cacheKey,+ sourceProofFor(sources, sourcePath, sourceSide),+ );+ }+ const proof = sourceProofCache.get(cacheKey);+ const sourceMatches =+ proof !== null &&+ Number.isInteger(lineNumber) &&+ proof.lines[lineNumber - 1] === rawContent;+ const insideStylex = sourceMatches && proof.stylexLines.has(lineNumber);+ if (!insideStylex) {+ rejectAppearance(+ 'changed line lacks source-backed stylex.create proof',+ );+ } else if (content === '') {+ // Whitespace-only changes inside a proven style object are harmless.+ } else if (wasInsideComment || isCommentLine(content)) {+ rejectAppearance('changed Core runtime comment');+ } else if (JSX_TAG.test(content)) {+ rejectAppearance('JSX structure');+ } else if (+ INTERACTION_AFFECTING_STYLE_PROPERTIES.has(+ content.match(/^([a-zA-Z][a-zA-Z0-9]*)\s*:/)?.[1],+ )+ ) {+ rejectAppearance('interaction-affecting style property');+ } else if (isSafeStyleDeclarationLine(content, currentFile)) {+ sawAppearanceDeclaration = true;+ } else if (isHarmlessStylePunctuation(content)) {+ countPunctuation(side, currentFile, content);+ } else {+ rejectAppearance('non-style Core runtime line');+ }+ }+if (content === '' || wasInsideComment || isCommentLine(content)) continue;- if (isStyleSurfaceFile(currentFile) && !touchedStyleSurfaces.has(currentFile)) {+ if (+ isStyleSurfaceFile(currentFile) &&+ !touchedStyleSurfaces.has(currentFile)+ ) {touchedStyleSurfaces.add(currentFile);styleSurfacePaths.push(currentFile);signals.styleSurfaceFiles++;@@ -324,7 +837,8 @@ function classifyVisualDiff(diffText, opts = {}) {signals.cssProperties * WEIGHTS.cssProperties +signals.tokenReferences * WEIGHTS.tokenReferences +signals.styleSurfaceFiles * WEIGHTS.styleSurfaceFiles +- Math.min(signals.jsxStructuralChanges, JSX_CAP) * WEIGHTS.jsxStructuralChanges;+ Math.min(signals.jsxStructuralChanges, JSX_CAP) *+ WEIGHTS.jsxStructuralChanges;let bucket;if (score >= 12) bucket = 'visual';@@ -332,7 +846,29 @@ function classifyVisualDiff(diffText, opts = {}) {else if (score >= 2) bucket = 'maybe-visual';else bucket = 'non-visual';- return {score, bucket, signals, styleSurfacePaths, evidence};+ for (const side of ['added', 'removed']) {+ for (const [key, count] of appearancePunctuation[side]) {+ const other = side === 'added' ? 'removed' : 'added';+ if (appearancePunctuation[other].get(key) !== count) {+ rejectAppearance('unbalanced style punctuation');+ }+ }+ }+ if (!sawCoreRuntime) rejectAppearance('no Core runtime change');+ if (!sawAppearanceDeclaration) {+ rejectAppearance('no recognized visual declaration');+ }+ const appearanceOnly = appearanceReasons.size === 0;++ return {+ score,+ bucket,+ signals,+ styleSurfacePaths,+ evidence,+ appearanceOnly,+ appearanceReasons: [...appearanceReasons],+ };}module.exports = {classifyVisualDiff, WEIGHTS, JSX_CAP};diff --git a/.github/scripts/lib/classify-visual.test.mjs b/.github/scripts/lib/classify-visual.test.mjsindex c3a652051a..556b1bb9dd 100644--- a/.github/scripts/lib/classify-visual.test.mjs+++ b/.github/scripts/lib/classify-visual.test.mjs@@ -25,6 +25,38 @@ function makeDiff(file, added = [], removed = []) {].join('\n');}+function sourceBackedStyleChange(file, added, removed) {+ const prefix = [+ "import * as stylex from '@stylexjs/stylex';",+ 'const styles = stylex.create({',+ ' root: {',+ ];+ const suffix = [' },', '});'];+ const baseLines = [+ ...prefix,+ ...removed.map(line => ` ${line}`),+ ...suffix,+ ];+ const headLines = [...prefix, ...added.map(line => ` ${line}`), ...suffix];+ const diff = [+ `diff --git a/${file} b/${file}`,+ 'index 1111111..2222222 100644',+ `--- a/${file}`,+ `+++ b/${file}`,+ `@@ -1,${baseLines.length} +1,${headLines.length} @@`,+ ...prefix.map(line => ` ${line}`),+ ...removed.map(line => `- ${line}`),+ ...added.map(line => `+ ${line}`),+ ...suffix.map(line => ` ${line}`),+ ].join('\n');+ return {+ diff,+ sources: {+ [file]: {base: baseLines.join('\n'), head: headLines.join('\n')},+ },+ };+}+describe('classifyVisualDiff', () => {it('returns non-visual for an empty diff', () => {const result = classifyVisualDiff('');@@ -45,9 +77,11 @@ describe('classifyVisualDiff', () => {});it('counts removed lines as well as added lines', () => {- const diff = makeDiff('packages/core/src/Card/Card.tsx', [], [- 'boxShadow: shadowVars.raised,',- ]);+ const diff = makeDiff(+ 'packages/core/src/Card/Card.tsx',+ [],+ ['boxShadow: shadowVars.raised,'],+ );const result = classifyVisualDiff(diff);expect(result.signals.cssProperties).toBe(1);expect(result.signals.tokenReferences).toBe(1);@@ -76,19 +110,24 @@ describe('classifyVisualDiff', () => {it('flags style-surface files by path', () => {const diff = [- makeDiff('packages/core/src/Field/inputStyles.stylex.ts', ['const x = 1;']),+ makeDiff('packages/core/src/Field/inputStyles.stylex.ts', [+ 'const x = 1;',+ ]),makeDiff('apps/docsite/src/app/globals.css', ['--brand-accent: #f00;']),makeDiff('packages/themes/matcha/src/theme.ts', ['const y = 2;']),].join('\n');const result = classifyVisualDiff(diff);expect(result.signals.styleSurfaceFiles).toBe(3);- expect(result.styleSurfacePaths).toContain('packages/core/src/Field/inputStyles.stylex.ts');+ expect(result.styleSurfacePaths).toContain(+ 'packages/core/src/Field/inputStyles.stylex.ts',+ );});it('does not flag marker stylex files as style surfaces', () => {- const diff = makeDiff('packages/core/src/CheckboxInput/checkbox.markers.stylex.ts', [- 'export const hoverMarker = stylex.defineMarker();',- ]);+ const diff = makeDiff(+ 'packages/core/src/CheckboxInput/checkbox.markers.stylex.ts',+ ['export const hoverMarker = stylex.defineMarker();'],+ );const result = classifyVisualDiff(diff);expect(result.signals.styleSurfaceFiles).toBe(0);});@@ -124,7 +163,9 @@ describe('classifyVisualDiff', () => {makeDiff('packages/core/src/Button/Button.test.tsx', [styleLine]),makeDiff('apps/storybook/stories/Button.stories.tsx', [styleLine]),makeDiff('packages/core/src/Button/Button.doc.mjs', [styleLine]),- makeDiff('packages/core/src/__tests__/TestIcon.tsx', ['<svg viewBox="0 0 24 24">']),+ makeDiff('packages/core/src/__tests__/TestIcon.tsx', [+ '<svg viewBox="0 0 24 24">',+ ]),// ESLint-plugin fixture of intentional style violationsmakeDiff('packages/core/src/Badge/Badge.test-violations.tsx', ["fontSize: '14px',",@@ -199,12 +240,12 @@ describe('classifyVisualDiff', () => {it('counts JSX structural changes only in packages/**/*.tsx', () => {const jsxLines = ['<VisuallyHidden>', '</VisuallyHidden>'];const inPackages = classifyVisualDiff(- makeDiff('packages/core/src/Banner/Banner.tsx', jsxLines)+ makeDiff('packages/core/src/Banner/Banner.tsx', jsxLines),);expect(inPackages.signals.jsxStructuralChanges).toBe(2);const inApps = classifyVisualDiff(- makeDiff('apps/docsite/src/app/page.tsx', jsxLines)+ makeDiff('apps/docsite/src/app/page.tsx', jsxLines),);expect(inApps.signals.jsxStructuralChanges).toBe(0);});@@ -216,8 +257,13 @@ describe('classifyVisualDiff', () => {});it('caps the JSX contribution to the score', () => {- const lines = Array.from({length: JSX_CAP + 5}, (_, i) => `<div data-i={${i}}>`);- const result = classifyVisualDiff(makeDiff('packages/core/src/Table/Table.tsx', lines));+ const lines = Array.from(+ {length: JSX_CAP + 5},+ (_, i) => `<div data-i={${i}}>`,+ );+ const result = classifyVisualDiff(+ makeDiff('packages/core/src/Table/Table.tsx', lines),+ );expect(result.signals.jsxStructuralChanges).toBe(JSX_CAP + 5);expect(result.score).toBe(JSX_CAP);});@@ -230,13 +276,15 @@ describe('classifyVisualDiff', () => {'color: colorVars.accent,','borderRadius: radiusVars.lg,','gap: spacingVars.xs,',- ])+ ]),);expect(visual.bucket).toBe('visual');// A lone token-reference swap: 2 → maybeconst maybe = classifyVisualDiff(- makeDiff('packages/core/src/Button/Button.tsx', ['const tone = colorVars.accent;'])+ makeDiff('packages/core/src/Button/Button.tsx', [+ 'const tone = colorVars.accent;',+ ]),);expect(maybe.score).toBe(2);expect(maybe.bucket).toBe('maybe-visual');@@ -245,14 +293,14 @@ describe('classifyVisualDiff', () => {const logic = classifyVisualDiff(makeDiff('packages/core/src/Table/useSort.ts', ['const sorted = useMemo(() => rows.sort(compare), [rows, compare]);',- ])+ ]),);expect(logic.bucket).toBe('non-visual');});it('collects capped evidence samples with file attribution', () => {const result = classifyVisualDiff(- makeDiff('packages/core/src/Button/Button.tsx', ['opacity: 0.5,'])+ makeDiff('packages/core/src/Button/Button.tsx', ['opacity: 0.5,']),);expect(result.evidence.cssProperties).toEqual([{file: 'packages/core/src/Button/Button.tsx', line: 'opacity: 0.5,'},@@ -260,10 +308,12 @@ describe('classifyVisualDiff', () => {});it('honors opts.ignorePath for caller-defined exclusions (review-signal safe spaces)', () => {- const isSafeSpace = (p) =>+ const isSafeSpace = p =>/^packages\/lab\//.test(p) || /^apps\/(sandbox|storybook)\//.test(p);const diff = [- makeDiff('packages/lab/src/Rating/Rating.tsx', ['padding: spacingVars.md,']),+ makeDiff('packages/lab/src/Rating/Rating.tsx', [+ 'padding: spacingVars.md,',+ ]),makeDiff('apps/sandbox/src/page.tsx', ['opacity: 0.5,']),makeDiff('packages/core/src/Button/Button.tsx', ['gap: spacingVars.sm,']),].join('\n');@@ -272,6 +322,407 @@ describe('classifyVisualDiff', () => {expect(result.signals.cssProperties).toBe(1);expect(result.signals.tokenReferences).toBe(1);});++ describe('appearanceOnly', () => {+ it('accepts source-proven declaration-only edits in an existing Core runtime file', () => {+ const change = sourceBackedStyleChange(+ 'packages/core/src/Button/Button.tsx',+ ['paddingBlock: spacingVars.md,', 'opacity: 0.9,'],+ ['paddingBlock: spacingVars.sm,', 'opacity: 1,'],+ );+ const result = classifyVisualDiff(change.diff, {sources: change.sources});+ expect(result.appearanceOnly).toBe(true);+ expect(result.appearanceReasons).toEqual([]);+ });++ it('allows component-local authority and visual evidence beside the pixels', () => {+ const change = sourceBackedStyleChange(+ 'packages/core/src/Button/Button.tsx',+ ['color: colorVars.accent,'],+ ['color: colorVars.primary,'],+ );+ const result = classifyVisualDiff(+ [+ change.diff,+ makeDiff('packages/core/src/Button/Button.spec.md', [+ '| DD1 | Keep the label quiet. | Preserve emphasis. | Label | Theme tokens may vary. |',+ ]),+ makeDiff('evidence/button-after.png', ['binary evidence']),+ ].join('\n'),+ {sources: change.sources},+ );+ expect(result.appearanceOnly).toBe(true);+ });++ it('fails closed without both trusted source versions', () => {+ const change = sourceBackedStyleChange(+ 'packages/core/src/Button/Button.tsx',+ ['opacity: 0.9,'],+ ['opacity: 1,'],+ );+ expect(classifyVisualDiff(change.diff).appearanceOnly).toBe(false);+ expect(+ classifyVisualDiff(change.diff, {+ sources: {+ 'packages/core/src/Button/Button.tsx': {+ base: change.sources['packages/core/src/Button/Button.tsx'].base,+ },+ },+ }).appearanceOnly,+ ).toBe(false);+ });++ it('does not accept a commented or locally shadowed stylex.create shape', () => {+ const file = 'packages/core/src/Button/Button.tsx';+ const commentedSource = [+ "import * as stylex from '@stylexjs/stylex';",+ '/*',+ 'const styles = stylex.create({',+ ' root: {',+ ' width: sizeVars.control,',+ ' },',+ '});',+ '*/',+ ].join('\n');+ const commentedDiff = [+ `diff --git a/${file} b/${file}`,+ `--- a/${file}`,+ `+++ b/${file}`,+ '@@ -5 +5 @@',+ '- width: sizeVars.control,',+ '+ width: sizeVars.compact,',+ ].join('\n');+ const commentedHead = commentedSource.replace(+ 'width: sizeVars.control',+ 'width: sizeVars.compact',+ );+ expect(+ classifyVisualDiff(commentedDiff, {+ sources: {[file]: {base: commentedSource, head: commentedHead}},+ }).appearanceOnly,+ ).toBe(false);++ const localChange = sourceBackedStyleChange(+ file,+ ['width: sizeVars.compact,'],+ ['width: sizeVars.control,'],+ );+ for (const side of ['base', 'head']) {+ localChange.sources[file][side] = localChange.sources[file][+ side+ ].replace(+ "import * as stylex from '@stylexjs/stylex';",+ 'const stylex = localStyleRuntime;',+ );+ }+ expect(+ classifyVisualDiff(localChange.diff, {sources: localChange.sources})+ .appearanceOnly,+ ).toBe(false);+ });++ it.each([+ ['display', "'none'"],+ ['visibility', "'hidden'"],+ ['pointerEvents', "'none'"],+ ['touchAction', "'none'"],+ ['userSelect', "'none'"],+ ['resize', "'none'"],+ ['cursor', "'pointer'"],+ ['overflow', "'hidden'"],+ ['overflowX', "'auto'"],+ ['overflowY', "'scroll'"],+ ['overscrollBehavior', "'contain'"],+ ['scrollBehavior', "'smooth'"],+ ['scrollMargin', "'8px'"],+ ['scrollPadding', "'8px'"],+ ['scrollSnapType', "'x mandatory'"],+ ['scrollSnapAlign', "'center'"],+ ['scrollbarWidth', "'none'"],+ ])(+ 'rejects added and removed interaction-affecting %s declarations',+ (property, value) => {+ for (const side of ['added', 'removed']) {+ const unsafe = `${property}: ${value},`;+ const change = sourceBackedStyleChange(+ 'packages/core/src/Button/Button.tsx',+ side === 'added' ? [unsafe] : ['opacity: 0.9,'],+ side === 'removed' ? [unsafe] : ['opacity: 1,'],+ );+ const result = classifyVisualDiff(change.diff, {+ sources: change.sources,+ });+ expect(result.appearanceOnly, `${property} ${side}`).toBe(false);+ expect(result.appearanceReasons).toContain(+ 'interaction-affecting style property',+ );+ }+ },+ );++ it.each([+ 'width: runBehaviorAndReturnWidth(value),',+ 'width: (value = nextWidth),',+ 'width: counter++,',+ 'width: --counter,',+ 'width: behaviorVars.width,',+ ])('rejects executable declaration value %s', addedLine => {+ const change = sourceBackedStyleChange(+ 'packages/core/src/Button/Button.tsx',+ [addedLine],+ ['width: sizeVars.control,'],+ );+ const result = classifyVisualDiff(change.diff, {sources: change.sources});+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons).toContain('non-style Core runtime line');+ });++ it('rejects a CSS-shaped key in an unrelated object in the same hunk', () => {+ const file = 'packages/core/src/Button/Button.tsx';+ const base = [+ "import * as stylex from '@stylexjs/stylex';",+ 'const styles = stylex.create({',+ ' root: {',+ ' color: colorVars.primary,',+ ' },',+ '});',+ 'const dimensions = {',+ ' width: sizeVars.control,',+ '};',+ ];+ const head = [...base];+ head[3] = ' color: colorVars.accent,';+ head[7] = ' width: sizeVars.compact,';+ const diff = [+ `diff --git a/${file} b/${file}`,+ `--- a/${file}`,+ `+++ b/${file}`,+ '@@ -1,9 +1,9 @@',+ " import * as stylex from '@stylexjs/stylex';",+ ' const styles = stylex.create({',+ ' root: {',+ '- color: colorVars.primary,',+ '+ color: colorVars.accent,',+ ' },',+ ' });',+ ' const dimensions = {',+ '- width: sizeVars.control,',+ '+ width: sizeVars.compact,',+ ' };',+ ].join('\n');+ const result = classifyVisualDiff(diff, {+ sources: {[file]: {base: base.join('\n'), head: head.join('\n')}},+ });+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons).toContain(+ 'changed line lacks source-backed stylex.create proof',+ );+ });++ it('does not mistake spaced update expressions for file headers after a hunk starts', () => {+ const file = 'packages/core/src/Button/Button.tsx';+ const base = [+ "import * as stylex from '@stylexjs/stylex';",+ 'const styles = stylex.create({',+ ' root: {',+ ' opacity: 1,',+ ' },',+ '});',+ '-- counter;',+ ];+ const head = [...base];+ head[3] = ' opacity: 0.9,';+ head[6] = '++ counter;';+ const diff = [+ `diff --git a/${file} b/${file}`,+ `--- a/${file}`,+ `+++ b/${file}`,+ '@@ -1,7 +1,7 @@',+ " import * as stylex from '@stylexjs/stylex';",+ ' const styles = stylex.create({',+ ' root: {',+ '- opacity: 1,',+ '+ opacity: 0.9,',+ ' },',+ ' });',+ '--- counter;',+ '+++ counter;',+ ].join('\n');+ const result = classifyVisualDiff(diff, {+ sources: {[file]: {base: base.join('\n'), head: head.join('\n')}},+ });+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons).toContain(+ 'changed line lacks source-backed stylex.create proof',+ );+ });++ it('rejects an imported runtime dependency beside a visual declaration', () => {+ const file = 'packages/core/src/Button/Button.tsx';+ const base = [+ "import * as stylex from '@stylexjs/stylex';",+ 'const styles = stylex.create({',+ ' root: {',+ ' opacity: 1,',+ ' },',+ '});',+ ];+ const head = [+ base[0],+ 'import {runBehavior} from "./behavior";',+ ...base.slice(1),+ ];+ head[4] = ' opacity: 0.9,';+ const diff = [+ `diff --git a/${file} b/${file}`,+ `--- a/${file}`,+ `+++ b/${file}`,+ '@@ -1,2 +1,3 @@',+ ` ${base[0]}`,+ '+import {runBehavior} from "./behavior";',+ ` ${base[1]}`,+ '@@ -3,4 +4,4 @@',+ ` ${base[2]}`,+ `-${base[3]}`,+ `+${head[4]}`,+ ` ${base[4]}`,+ ` ${base[5]}`,+ ].join('\n');+ const result = classifyVisualDiff(diff, {+ sources: {[file]: {base: base.join('\n'), head: head.join('\n')}},+ });+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons).toContain(+ 'changed line lacks source-backed stylex.create proof',+ );+ });++ it.each([+ {+ name: 'JSX structure',+ added: ['<span>Label</span>'],+ removed: ['opacity: 1,'],+ reason: 'JSX structure',+ },+ {+ name: 'an imported symbol',+ added: ['import {runBehavior} from "./behavior";'],+ removed: ['opacity: 1,'],+ reason: 'non-style Core runtime line',+ },+ {+ name: 'runtime logic',+ added: ['const pressed = state === "pressed";'],+ removed: ['opacity: 1,'],+ reason: 'non-style Core runtime line',+ },+ ])(+ 'rejects $name even inside a stylex.create range',+ ({added, removed, reason}) => {+ const change = sourceBackedStyleChange(+ 'packages/core/src/Button/Button.tsx',+ added,+ removed,+ );+ const result = classifyVisualDiff(change.diff, {+ sources: change.sources,+ });+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons.length).toBeGreaterThan(0);+ if (reason !== 'JSX structure') {+ expect(result.appearanceReasons).toContain(reason);+ }+ },+ );++ it.each([+ {+ name: 'Core to lab',+ oldPath: 'packages/core/src/Button/Button.tsx',+ newPath: 'packages/lab/src/Button/Button.tsx',+ },+ {+ name: 'unsafe to sandbox',+ oldPath: 'packages/build/src/Button.ts',+ newPath: 'apps/sandbox/src/Button.ts',+ },+ ])('fails closed for a $name rename', ({oldPath, newPath}) => {+ const diff = [+ `diff --git a/${oldPath} b/${newPath}`,+ 'similarity index 99%',+ `rename from ${oldPath}`,+ `rename to ${newPath}`,+ `--- a/${oldPath}`,+ `+++ b/${newPath}`,+ '@@ -1 +1 @@',+ '-export const value = 1;',+ '+export const value = 2;',+ ].join('\n');+ const result = classifyVisualDiff(diff, {+ ignorePath: file =>+ /^packages\/lab\//.test(file) ||+ /^apps\/(sandbox|storybook)\//.test(file),+ });+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons).toContain('renamed path');+ });++ it.each([+ {+ name: 'a new runtime file',+ diff: `${makeDiff('packages/core/src/NewThing/NewThing.tsx', [+ 'color: colorVars.accent,',+ ])}\nnew file mode 100644`,+ reason: 'new or deleted Core runtime file',+ },+ {+ name: 'a renamed runtime file',+ diff: makeDiff('packages/core/src/Button/Button.tsx', [+ 'color: colorVars.accent,',+ ]).replace(+ 'a/packages/core/src/Button/Button.tsx b/packages/core/src/Button/Button.tsx',+ 'a/packages/core/src/Button/Button.tsx b/packages/core/src/Action/Action.tsx',+ ),+ reason: 'renamed path',+ },+ {+ name: 'a public barrel',+ diff: makeDiff('packages/core/src/Button/index.ts', [+ 'color: colorVars.accent,',+ ]),+ reason: 'public API or package path',+ },+ {+ name: 'an unknown Core source path',+ diff: makeDiff('packages/core/src/Button/styles.json', ['color: red']),+ reason: 'unknown runtime path',+ },+ ])('rejects $name', ({diff, reason}) => {+ const result = classifyVisualDiff(diff);+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons).toContain(reason);+ });++ it('rejects mixed runtime or tooling paths', () => {+ const change = sourceBackedStyleChange(+ 'packages/core/src/Button/Button.tsx',+ ['color: colorVars.accent,'],+ ['color: colorVars.primary,'],+ );+ for (const otherDiff of [+ makeDiff('packages/build/src/compile.ts', [+ 'return compileWithNewBehavior(input);',+ ]),+ makeDiff('scripts/release.mjs', ['publishRelease();']),+ ]) {+ const result = classifyVisualDiff(`${change.diff}\n${otherDiff}`, {+ sources: change.sources,+ });+ expect(result.appearanceOnly).toBe(false);+ expect(result.appearanceReasons).toContain('unknown runtime path');+ }+ });+ });});describe('review-signal loading contract', () => {@@ -282,14 +733,14 @@ describe('review-signal loading contract', () => {it('instantiates via new Function without a real require', () => {const src = readFileSync(fileURLToPath(new URL('./classify-visual.js', import.meta.url)),- 'utf8'+ 'utf8',);const mod = {exports: {}};new Function('module', 'exports', 'require', src)(mod, mod.exports, () => {throw new Error('classify-visual.js must stay dependency-free');});const result = mod.exports.classifyVisualDiff(- makeDiff('packages/core/src/Button/Button.tsx', ['opacity: 0.5,'])+ makeDiff('packages/core/src/Button/Button.tsx', ['opacity: 0.5,']),);expect(result.signals.cssProperties).toBe(1);});diff --git a/.github/scripts/review-clear-workflow.test.mjs b/.github/scripts/review-clear-workflow.test.mjsnew file mode 100644index 0000000000..cc3419d588--- /dev/null+++ b/.github/scripts/review-clear-workflow.test.mjs@@ -0,0 +1,298 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';+import YAML from 'yaml';++const root = path.resolve(import.meta.dirname, '../..');+const workflowSource = fs.readFileSync(+ path.join(root, '.github/workflows/review-clear.yml'),+ 'utf8',+);+const helperSource = fs.readFileSync(+ path.join(root, '.github/scripts/review-signal-decision.cjs'),+ 'utf8',+);+const script = YAML.parse(workflowSource).jobs.clear.steps.find(+ step => step.name === 'Reconcile the exact-head code gate',+).with.script;+const execute = new Function(+ 'github',+ 'context',+ 'core',+ 'process',+ 'Buffer',+ `return (async () => {\n${script}\n})();`,+);++const head1 = '1111111111111111111111111111111111111111';+const head2 = '2222222222222222222222222222222222222222';+const head3 = '3333333333333333333333333333333333333333';+const review = (state, commitId = head2) => ({+ user: {login: 'engineer'},+ state,+ commit_id: commitId,+});+const gateStatus = (state, description) => ({+ context: 'review-required',+ creator: {login: 'github-actions[bot]'},+ description,+ state,+});+const pendingGate = gateStatus(+ 'pending',+ 'Waiting on code review: core runtime change',+);+const clearedGate = gateStatus('success', 'Cleared by code-owner approval.');+const ungatedSuccess = gateStatus('success', 'No code review required.');++function harness(+ reviews,+ {+ labels = ['needs:code-review'],+ moveAfterFirstRead = false,+ statusFailure = false,+ statuses = [pendingGate],+ } = {},+) {+ const calls = [];+ let pullReads = 0;+ const full = {+ number: 17,+ head: {sha: head2},+ base: {sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'},+ labels: labels.map(name => ({name})),+ };+ const methods = {+ listCommitStatusesForRef: async () => ({data: statuses}),+ listReviews: async () => ({data: reviews}),+ };+ const github = {+ paginate: async (method, options) => (await method(options)).data,+ rest: {+ pulls: {+ get: async () => {+ pullReads += 1;+ return {+ data:+ moveAfterFirstRead && pullReads > 1+ ? {...full, head: {sha: head3}}+ : full,+ };+ },+ list: async () => ({data: []}),+ listReviews: methods.listReviews,+ },+ repos: {+ getContent: async ({ref, path: filePath}) => {+ calls.push(`read:${ref}:${filePath}`);+ return {+ data: {+ type: 'file',+ content: Buffer.from(helperSource).toString('base64'),+ },+ };+ },+ listCommitStatusesForRef: methods.listCommitStatusesForRef,+ createCommitStatus: async input => {+ calls.push({type: 'status-attempt', input});+ if (statusFailure) throw new Error('persistent status failure');+ calls.push({type: 'status', input});+ },+ },+ issues: {+ addLabels: async input => calls.push({type: 'add-label', input}),+ removeLabel: async input => calls.push({type: 'remove-label', input}),+ },+ checks: {+ listForRef: async () => ({data: {check_runs: []}}),+ update: async input => calls.push({type: 'check-update', input}),+ },+ },+ };+ const context = {+ repo: {owner: 'facebook', repo: 'astryx'},+ payload: {+ workflow_run: {+ pull_requests: [{number: 17}],+ },+ },+ };+ const core = {+ info: message => calls.push(`info:${message}`),+ warning: message => calls.push(`warning:${message}`),+ };+ const processValue = {env: {ENG_OWNERS: '@engineer'}};+ return {calls, context, core, github, processValue};+}++async function run(h) {+ await execute(h.github, h.context, h.core, h.processValue, Buffer);+}++function mutations(calls) {+ return calls.filter(call =>+ ['add-label', 'remove-label', 'status'].includes(call?.type),+ );+}++describe('review-clear exact-head workflow', () => {+ it('does not let an H1 approval mutate the H2 gate', async () => {+ const h = harness([review('APPROVED', head1)]);++ await run(h);++ expect(mutations(h.calls)).toEqual([]);+ expect(h.calls).toContain(+ 'read:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:.github/scripts/review-signal-decision.cjs',+ );+ });++ it('does not create a gate for a head that review-signal marked ungated', async () => {+ const h = harness([review('APPROVED')], {+ labels: [],+ statuses: [ungatedSuccess],+ });++ await run(h);++ expect(mutations(h.calls)).toEqual([]);+ });++ it('does not trust an unowned green review-required status', async () => {+ const h = harness([review('CHANGES_REQUESTED')], {+ labels: [],+ statuses: [+ {+ ...clearedGate,+ creator: {login: 'untrusted-user'},+ },+ ],+ });++ await run(h);++ expect(mutations(h.calls)).toEqual([]);+ });++ it('clears an owned gate for an entitled approval on the exact head', async () => {+ const h = harness([review('APPROVED')]);++ await run(h);++ expect(h.calls).toContainEqual(+ expect.objectContaining({type: 'remove-label'}),+ );+ expect(h.calls).toContainEqual({+ type: 'status',+ input: expect.objectContaining({+ sha: head2,+ context: 'review-required',+ state: 'success',+ description: 'Cleared by code-owner approval.',+ }),+ });+ });++ it('restores a previously green owned gate after exact-head changes requested', async () => {+ const h = harness([review('APPROVED'), review('CHANGES_REQUESTED')], {+ labels: [],+ statuses: [clearedGate],+ });++ await run(h);++ const pendingIndex = h.calls.findIndex(+ call => call?.type === 'status' && call.input.state === 'pending',+ );+ const labelIndex = h.calls.findIndex(call => call?.type === 'add-label');+ expect(pendingIndex).toBeGreaterThan(-1);+ expect(labelIndex).toBeGreaterThan(pendingIndex);+ expect(h.calls).toContainEqual(+ expect.objectContaining({type: 'add-label'}),+ );+ expect(h.calls).toContainEqual({+ type: 'status',+ input: expect.objectContaining({+ sha: head2,+ context: 'review-required',+ 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: [],+ statusFailure: true,+ statuses: [clearedGate],+ });++ await expect(run(h)).rejects.toThrow('persistent status failure');++ expect(h.calls).toContainEqual(+ expect.objectContaining({+ type: 'status-attempt',+ input: expect.objectContaining({state: 'pending'}),+ }),+ );+ expect(h.calls.some(call => call?.type === 'status')).toBe(false);+ expect(h.calls.some(call => call?.type === 'add-label')).toBe(false);+ });++ it('restores a previously green owned gate after exact-head dismissal', async () => {+ const h = harness([review('APPROVED'), review('DISMISSED')], {+ labels: [],+ statuses: [clearedGate],+ });++ await run(h);++ expect(h.calls).toContainEqual(+ expect.objectContaining({type: 'add-label'}),+ );+ expect(h.calls).toContainEqual(+ expect.objectContaining({+ type: 'status',+ input: expect.objectContaining({state: 'pending'}),+ }),+ );+ });++ it.each([+ {+ name: 'approval',+ reviews: [review('APPROVED')],+ options: {moveAfterFirstRead: true},+ },+ {+ name: 'withdrawal',+ reviews: [review('APPROVED'), review('CHANGES_REQUESTED')],+ options: {+ labels: [],+ moveAfterFirstRead: true,+ statuses: [clearedGate],+ },+ },+ {+ name: 'dismissal',+ reviews: [review('APPROVED'), review('DISMISSED')],+ options: {+ labels: [],+ moveAfterFirstRead: true,+ statuses: [clearedGate],+ },+ },+ ])(+ 'does not mutate after a moved-head $name race',+ async ({reviews, options}) => {+ const h = harness(reviews, options);++ await run(h);++ expect(mutations(h.calls)).toEqual([]);+ },+ );+});diff --git a/.github/scripts/review-signal-decision.cjs b/.github/scripts/review-signal-decision.cjsnew file mode 100644index 0000000000..678df652a6--- /dev/null+++ b/.github/scripts/review-signal-decision.cjs@@ -0,0 +1,83 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';+/* global module */++// Trusted-base helper for review-signal.yml. Keep dependency-free CommonJS.++function isSafeSpace(filePath) {+ return (+ /^packages\/lab\//.test(filePath) ||+ /^apps\/(sandbox|storybook)\//.test(filePath)+ );+}++function classifyReviewSignalPaths(changedFiles) {+ let hasSafeBoundaryRename = false;+ const files = changedFiles.filter(file => {+ if (+ typeof file.previous_filename === 'string' &&+ isSafeSpace(file.filename) !== isSafeSpace(file.previous_filename)+ ) {+ hasSafeBoundaryRename = true;+ }+ const sides = [file.filename, file.previous_filename].filter(+ value => typeof value === 'string' && value.length > 0,+ );+ return sides.length === 0 || !sides.every(isSafeSpace);+ });+ const paths = [+ ...new Set(+ files.flatMap(file =>+ [file.filename, file.previous_filename].filter(+ value => typeof value === 'string' && value.length > 0,+ ),+ ),+ ),+ ];+ return {files, hasSafeBoundaryRename, paths};+}++function resolveReviewApprovals({reviews, headSha, engOwners, designOwners}) {+ const latestByUser = new Map();+ for (const review of reviews) {+ const login = review.user?.login?.toLowerCase();+ if (+ !login ||+ review.commit_id !== headSha ||+ review.state === 'COMMENTED' ||+ !['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)+ ) {+ continue;+ }+ latestByUser.set(login, review.state);+ }++ let codeApproved = false;+ let designApproved = false;+ let codeWithdrawn = false;+ for (const [login, state] of latestByUser) {+ if (state === 'APPROVED') {+ if (engOwners.includes(login)) codeApproved = true;+ if (designOwners.includes(login)) designApproved = true;+ continue;+ }+ if (+ (state === 'CHANGES_REQUESTED' || state === 'DISMISSED') &&+ engOwners.includes(login)+ ) {+ codeWithdrawn = true;+ }+ }+ return {+ codeApproved,+ codeWithdrawn: !codeApproved && codeWithdrawn,+ designApproved,+ };+}++module.exports = {+ classifyReviewSignalPaths,+ isSafeSpace,+ resolveReviewApprovals,+};diff --git a/.github/scripts/review-signal-decision.test.mjs b/.github/scripts/review-signal-decision.test.mjsnew file mode 100644index 0000000000..f6552acbfb--- /dev/null+++ b/.github/scripts/review-signal-decision.test.mjs@@ -0,0 +1,170 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {readFileSync} from 'node:fs';+import {createRequire} from 'node:module';+import {fileURLToPath} from 'node:url';+import {describe, expect, it} from 'vitest';++const require = createRequire(import.meta.url);+const {+ classifyReviewSignalPaths,+ resolveReviewApprovals,+} = require('./review-signal-decision.cjs');++const head1 = '1111111111111111111111111111111111111111';+const head2 = '2222222222222222222222222222222222222222';+const approval = (login, commitId, state = 'APPROVED') => ({+ user: {login},+ commit_id: commitId,+ state,+});++describe('review-signal exact-head approvals', () => {+ it('does not let an H1 engineering approval clear H2', () => {+ expect(+ resolveReviewApprovals({+ reviews: [approval('engineer', head1)],+ headSha: head2,+ engOwners: ['engineer'],+ designOwners: ['designer'],+ }),+ ).toEqual({+ codeApproved: false,+ codeWithdrawn: false,+ designApproved: false,+ });+ });++ it('does not let an H1 design approval clear H2', () => {+ expect(+ resolveReviewApprovals({+ reviews: [approval('designer', head1)],+ headSha: head2,+ engOwners: ['engineer'],+ designOwners: ['designer'],+ }),+ ).toEqual({+ codeApproved: false,+ codeWithdrawn: false,+ designApproved: false,+ });+ });++ it('accepts only exact-head approvals and honors later exact-head revocation', () => {+ expect(+ resolveReviewApprovals({+ reviews: [+ approval('engineer', head1),+ approval('engineer', head2),+ approval('designer', head2),+ ],+ headSha: head2,+ engOwners: ['engineer'],+ designOwners: ['designer'],+ }),+ ).toEqual({+ codeApproved: true,+ codeWithdrawn: false,+ designApproved: true,+ });++ expect(+ resolveReviewApprovals({+ reviews: [+ approval('engineer', head2),+ approval('engineer', head2, 'CHANGES_REQUESTED'),+ approval('designer', head2),+ approval('designer', head2, 'DISMISSED'),+ ],+ headSha: head2,+ engOwners: ['engineer'],+ designOwners: ['designer'],+ }),+ ).toEqual({+ codeApproved: false,+ codeWithdrawn: true,+ designApproved: false,+ });+ });++ it('keeps an effective exact-head approval when another owner withdraws', () => {+ expect(+ resolveReviewApprovals({+ reviews: [+ approval('engineer-a', head2),+ approval('engineer-b', head2),+ approval('engineer-b', head2, 'CHANGES_REQUESTED'),+ ],+ headSha: head2,+ engOwners: ['engineer-a', 'engineer-b'],+ designOwners: [],+ }),+ ).toEqual({+ codeApproved: true,+ codeWithdrawn: false,+ designApproved: false,+ });+ });++ it.each([+ {+ name: 'Core to lab',+ file: {+ filename: 'packages/lab/src/Button/Button.tsx',+ previous_filename: 'packages/core/src/Button/Button.tsx',+ status: 'renamed',+ },+ expectedPaths: [+ 'packages/lab/src/Button/Button.tsx',+ 'packages/core/src/Button/Button.tsx',+ ],+ },+ {+ name: 'unsafe to sandbox',+ file: {+ filename: 'apps/sandbox/src/Button.tsx',+ previous_filename: 'packages/build/src/Button.tsx',+ status: 'renamed',+ },+ expectedPaths: [+ 'apps/sandbox/src/Button.tsx',+ 'packages/build/src/Button.tsx',+ ],+ },+ ])('retains both sides of a $name rename', ({file, expectedPaths}) => {+ expect(classifyReviewSignalPaths([file])).toEqual({+ files: [file],+ hasSafeBoundaryRename: true,+ paths: expectedPaths,+ });+ });++ it('excludes a rename only when both sides are safe', () => {+ const file = {+ filename: 'apps/storybook/stories/Button.stories.tsx',+ previous_filename: 'apps/sandbox/src/Button.tsx',+ status: 'renamed',+ };+ expect(classifyReviewSignalPaths([file])).toEqual({+ files: [],+ hasSafeBoundaryRename: false,+ paths: [],+ });+ });++ it('stays dependency-free for trusted-base loading', () => {+ const source = readFileSync(+ fileURLToPath(new URL('./review-signal-decision.cjs', import.meta.url)),+ 'utf8',+ );+ const mod = {exports: {}};+ new Function('module', 'exports', 'require', source)(+ mod,+ mod.exports,+ () => {+ throw new Error('review-signal-decision.cjs must stay dependency-free');+ },+ );+ expect(typeof mod.exports.resolveReviewApprovals).toBe('function');+ });+});diff --git a/.github/scripts/review-signal-workflow.test.mjs b/.github/scripts/review-signal-workflow.test.mjsnew file mode 100644index 0000000000..ff27d64bce--- /dev/null+++ b/.github/scripts/review-signal-workflow.test.mjs@@ -0,0 +1,112 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';+import YAML from 'yaml';++const root = path.resolve(import.meta.dirname, '../..');+const workflow = fs.readFileSync(+ path.join(root, '.github/workflows/review-signal.yml'),+ 'utf8',+);++describe('review-signal appearance-only contract', () => {+ it('keeps the embedded privileged script syntactically valid', () => {+ const parsed = YAML.parse(workflow);+ const script = parsed.jobs.flag.steps.find(+ step => step.name === 'Detect signals and route',+ ).with.script;+ expect(+ () =>+ new Function(+ 'github',+ 'context',+ 'core',+ 'process',+ 'Buffer',+ `return (async () => {\n${script}\n})();`,+ ),+ ).not.toThrow();+ });++ it('loads the dependency-free classifier and trusted base/head source bytes', () => {+ expect(workflow).not.toContain('ref: pr.base.ref');+ expect(workflow).toContain('ref: pr.base.sha');+ expect(workflow).toContain(+ "path: '.github/scripts/lib/classify-visual.js'",+ );+ expect(workflow).toContain('pr.base.repo.full_name');+ expect(workflow).toContain('pr.base.sha');+ expect(workflow).toContain('pr.head.repo.full_name');+ expect(workflow).toContain('pr.head.sha');+ expect(workflow).toContain(+ 'sources[file.filename] = {base: baseSource, head: headSource}',+ );+ expect(workflow).toContain('if (coreChange || designReasons.length === 0)');+ expect(workflow).toContain(+ "throw new Error('classify-visual.js must stay dependency-free')",+ );+ });++ it('resolves engineering and design approvals only for the current head', () => {+ expect(workflow).toContain(+ "path: '.github/scripts/review-signal-decision.cjs'",+ );+ expect(workflow).toContain('headSha: pr.head.sha');+ expect(workflow).toContain('codeHighRisk && codeApproved');+ expect(workflow).toContain("'Cleared by code-owner approval.'");+ expect(workflow).toContain(+ "throw new Error('review-signal-decision.cjs must stay dependency-free')",+ );+ });++ it('routes safe-space changes using both current and previous paths', () => {+ expect(workflow).toContain(+ 'reviewDecision.classifyReviewSignalPaths(allFiles)',+ );+ expect(workflow).toContain('hasSafeBoundaryRename');+ expect(workflow).toContain(+ "codeReasons.push('safe-space boundary rename')",+ );+ expect(workflow).toContain(+ 'const isSafeSpace = reviewDecision.isSafeSpace',+ );+ expect(workflow).not.toContain('!isLab(f.filename)');+ });++ it('anchors approval, changes-requested, and dismissal review events', () => {+ expect(workflow).toContain('types: [submitted, dismissed]');+ expect(workflow).toContain(+ 'contains(fromJSON(\'["approved","changes_requested","dismissed"]\'), github.event.review.state)',+ );+ });++ it('limits self-service to a DESIGNOWNER with only the proven Core visual reason', () => {+ expect(workflow).toContain(+ 'const appearanceOnly = visualClassification?.appearanceOnly === true',+ );+ expect(workflow).toContain(+ "codeReasons.length === 1 && codeReasons[0] === 'core visual change'",+ );+ expect(workflow).toContain(+ 'authorIsDesign && appearanceOnly && onlyCoreVisualChange',+ );+ expect(workflow).toContain('!designOwnerAppearanceSelfServe');+ });++ it('keeps contributors and classifier failures on the engineering gate', () => {+ const communityReason = workflow.indexOf(+ "codeReasons.push('community contribution')",+ );+ const narrowReasonCheck = workflow.indexOf(+ "codeReasons.length === 1 && codeReasons[0] === 'core visual change'",+ );+ expect(communityReason).toBeGreaterThan(-1);+ expect(narrowReasonCheck).toBeGreaterThan(communityReason);+ expect(workflow).toContain('let visualClassification = null');+ expect(workflow).toContain(+ 'Content-based visual classification failed closed',+ );+ });+});diff --git a/.github/scripts/spec-owner-decision.cjs b/.github/scripts/spec-owner-decision.cjsindex 40399003aa..5a1e1787af 100644--- a/.github/scripts/spec-owner-decision.cjs+++ b/.github/scripts/spec-owner-decision.cjs@@ -4,6 +4,9 @@/* global module, require *//* eslint-disable @typescript-eslint/no-require-imports */+const {+ classifyDesignDecisionChange,+} = require('./component-design-decisions.cjs');const {parseAuthority,parseKind,@@ -281,8 +284,34 @@ function requiredApprovalGroups({content: record.baseContent, path: record.previousPath ?? record.path},{content: record.headContent, path: record.path},];- for (const version of versions) {- if (parseAuthority(version.content, version.path) !== 'current') continue;+ const currentVersions = versions.filter(+ version => parseAuthority(version.content, version.path) === 'current',+ );+ if (currentVersions.length === 0) continue;++ const touchesComponentOrModule = versions.some(version => {+ const kind = parseKind(version.content, version.path);+ return kind === 'component' || kind === 'module';+ });+ if (touchesComponentOrModule) {+ const change = classifyDesignDecisionChange({+ basePath: record.previousPath ?? record.path,+ headPath: record.path,+ baseContent: record.baseContent,+ headContent: record.headContent,+ });+ if (change.classification === 'dd-only') {+ groups.design = true;+ } else if (change.classification === 'mixed') {+ groups.spec = true;+ groups.design = true;+ } else {+ groups.spec = true;+ }+ continue;+ }++ for (const version of currentVersions) {groups[approvalGroupFor(version.content, version.path)] = true;}}diff --git a/.github/scripts/spec-owner-decision.test.mjs b/.github/scripts/spec-owner-decision.test.mjsindex 36607e5d6b..a2b5d8ccb1 100644--- a/.github/scripts/spec-owner-decision.test.mjs+++ b/.github/scripts/spec-owner-decision.test.mjs@@ -21,6 +21,15 @@ const {const head = 'abcdef1234567890abcdef1234567890abcdef12';const owner = {login: 'cixzhang'};+const componentPath = 'packages/core/src/Button/Button.spec.md';++function componentRecord({body = 'Body.', decision = null} = {}) {+ const block =+ decision === null+ ? ''+ : `\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. |`;+ return `---\nkind: component\nauthority: current\n---\n\n## Design relationships\n\n${body}${block}\n\n### Theming anatomy\n`;+}describe('spec owner decision', () => {it('binds approval commands to the current head', () => {@@ -148,6 +157,58 @@ describe('spec owner decision', () => {).toEqual({spec: true, design: true, theme: false});});+ it('routes DD-only component changes to design owners', () => {+ expect(+ requiredApprovalGroups([+ {+ path: componentPath,+ baseContent: componentRecord({decision: 'Use a quiet label.'}),+ headContent: componentRecord({decision: 'Keep the label quiet.'}),+ },+ ]),+ ).toEqual({spec: false, design: true, theme: false});+ });++ it('routes mixed DD and component contract changes to both groups', () => {+ expect(+ requiredApprovalGroups([+ {+ path: componentPath,+ baseContent: componentRecord({decision: 'Use a quiet label.'}),+ headContent: componentRecord({+ body: 'Changed contract.',+ decision: 'Keep the label quiet.',+ }),+ },+ ]),+ ).toEqual({spec: true, design: true, theme: false});+ });++ it('keeps component edits without a DD change in engineering', () => {+ expect(+ requiredApprovalGroups([+ {+ path: componentPath,+ baseContent: componentRecord(),+ headContent: componentRecord({body: 'Changed contract.'}),+ },+ ]),+ ).toEqual({spec: true, design: false, theme: false});+ });++ it('fails closed for a renamed component record', () => {+ expect(+ requiredApprovalGroups([+ {+ path: 'packages/core/src/Action/Action.spec.md',+ previousPath: componentPath,+ baseContent: componentRecord(),+ headContent: componentRecord(),+ },+ ]),+ ).toEqual({spec: true, design: true, theme: false});+ });+it('owner-gates design assets even without a text record', () => {expect(requiredApprovalGroups([], {touchesDesignAssets: true})).toEqual({spec: false,diff --git a/.github/scripts/spec-owner-reconcile.test.mjs b/.github/scripts/spec-owner-reconcile.test.mjsindex 8a16fafb78..bde57b0bd5 100644--- a/.github/scripts/spec-owner-reconcile.test.mjs+++ b/.github/scripts/spec-owner-reconcile.test.mjs@@ -264,6 +264,13 @@ const designRecord = {status: 'added',};const currentDesign = 'kind: design\nauthority: current\n';+const componentRecord = {+ filename: 'packages/core/src/Button/Button.spec.md',+ status: 'modified',+};+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; they must not borrow the design self-attestation.@@ -445,6 +452,50 @@ describe('spec owner workflow reconciliation', () => {expect(harness.state.calls).toContain('enable-auto-merge');});+ it('lets a DESIGNOWNER author self-attest an exact DD-only component spec head', async () => {+ const harness = createHarness({+ author: 'ernestt',+ changedFile: componentRecord,+ baseContent: currentComponentSpec('Use a quiet label.'),+ headContent: currentComponentSpec('Keep the label quiet.'),+ });++ await run(+ harness,+ context({runId: 100n, actor: 'ernestt', author: 'ernestt'}),+ );++ expect(hasReadyAttestation(harness.state)).toBe(true);+ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'success',+ description: expect.stringContaining('Approved by @ernestt'),+ });+ });++ it('keeps mixed DD and component-contract edits waiting for engineering', async () => {+ const harness = createHarness({+ author: 'ernestt',+ changedFile: componentRecord,+ baseContent: currentComponentSpec('Use a quiet label.'),+ headContent: currentComponentSpec(+ 'Keep the label quiet.',+ 'Changed behavioral contract.',+ ),+ });++ await run(+ harness,+ context({runId: 100n, actor: 'ernestt', author: 'ernestt'}),+ );++ expect(hasReadyAttestation(harness.state)).toBe(true);+ expect(latestGateStatus(harness.state)).toMatchObject({+ state: 'pending',+ description: expect.stringContaining('engineering owner'),+ });+ expect(harness.state.calls).not.toContain('enable-auto-merge');+ });+it('requires the ready actor to be the PR author', async () => {const harness = createDesignHarness();diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjsindex 0241b723ed..455a5cc096 100644--- a/.github/scripts/spec-owner-workflow.test.mjs+++ b/.github/scripts/spec-owner-workflow.test.mjs@@ -269,6 +269,9 @@ describe('spec-only workflow contract', () => {expect(reconciler).toContain('scope.touchesKnowledgeRecords');expect(reconciler).toContain('scope.touchesDesignAssets');expect(reconciler).toContain('requiredApprovalGroups(records');+ expect(read('.github/scripts/spec-owner-decision.cjs')).toContain(+ "require('./component-design-decisions.cjs')",+ );expect(reconciler).toContain("'.github/DESIGNOWNERS'");expect(reconciler).toContain("'.github/ENGOWNERS'");expect(workflow).not.toContain('SPEC_OWNERS:');diff --git a/.github/workflows/review-clear.yml b/.github/workflows/review-clear.ymlindex 661fcfdaa2..5e502b53da 100644--- a/.github/workflows/review-clear.yml+++ b/.github/workflows/review-clear.yml@@ -1,33 +1,33 @@# Copyright (c) Meta Platforms, Inc. and affiliates.-# Auto-clear the review gate after an approval — including on FORK PRs.+# Reconcile the code-review gate after an engineering review — including on+# fork PRs.#-# The gate is set by review-signal's "flag" job (label needs:code-review +-# a pending "review-required" commit status). Clearing can't run on the raw-# pull_request_review event for fork PRs (read-only token → 403). So this runs-# on workflow_run after "Review signal" completes for a review submission, from-# the base repo with a write-capable token that works for forks.+# review-signal owns whether a head needs code review. It records that ownership+# with needs:code-review and the review-required status. This workflow may clear+# an owned gate after exact-head approval or restore it after that effective+# approver requests changes or their review is dismissed. It never creates a+# gate for a head that review-signal did not mark as code-gated.#-# It clears DIRECTLY (no re-dispatch hop, which was unreliable): resolve the PR,-# check whether an entitled CODEOWNER has approved, and if so drop the-# needs:code-review label, set the review-required status to success, and-# neutralize any stale action_required "review-required" CHECK RUN left over-# from the pre-status gate (that stale check-run otherwise drags the status-# rollup to FAILURE even when the status is success).-#-# Clearing only ever REMOVES the code gate — an approval can satisfy a gate, not-# create one — so this needs no risk detection. It never checks out or runs+# The mutation cannot run on the raw pull_request_review event for fork PRs+# (read-only token → 403). It therefore runs on workflow_run after Review signal+# anchors approved, changes_requested, and dismissed review events from the base+# repository with a write-capable token. It never checks out or runs# PR-controlled code.name: Review clearon:workflow_run:- workflows: ["Review signal"]+ workflows: ['Review signal']types: [completed]permissions: {}+concurrency:+ group: review-clear-${{ github.event.workflow_run.head_repository.full_name || github.repository }}-${{ github.event.workflow_run.head_branch || github.run_id }}+ cancel-in-progress: true+jobs:clear:if: github.event.workflow_run.event == 'pull_request_review'@@ -38,7 +38,7 @@ jobs:checks: writecontents: readsteps:- - name: Clear the code gate if an entitled owner approved+ - name: Reconcile the exact-head code gateuses: actions/github-script@v9env:ENG_OWNERS: ${{ vars.ENGOWNERS }}@@ -91,7 +91,6 @@ jobs:// Full PR (labels + head sha).const { data: full } = await github.rest.pulls.get({ owner, repo, pull_number: prNumber });const headSha = full.head.sha;- const labels = full.labels.map((l) => l.name);// Entitled code approvers come from the ENGOWNERS repo variable// (passed in as env above). Any eng owner's approval clears the code@@ -110,26 +109,95 @@ jobs:return;}- // Did an entitled owner approve (latest review state per user)?+ // Resolve the effective exact-head review state with the same+ // dependency-free helper review-signal uses. Also read this head's+ // latest review-required status: only the existing label or a latest+ // status emitted by this gate proves that review-signal owned it.let codeApproved = false;+ let codeWithdrawn = false;+ let gateOwned = false;try {const reviews = await github.paginate(github.rest.pulls.listReviews, {owner, repo, pull_number: prNumber, per_page: 100,});- const latest = new Map();- for (const r of reviews) {- if (!r.user || r.state === 'COMMENTED') continue;- latest.set(r.user.login.toLowerCase(), r.state);- }- for (const [login, state] of latest) {- if (state === 'APPROVED' && codeApprovers.has(login)) codeApproved = true;- }+ const { data: decisionFile } = await github.rest.repos.getContent({+ owner, repo, ref: full.base.sha,+ path: '.github/scripts/review-signal-decision.cjs',+ });+ const decisionSrc = Buffer.from(decisionFile.content, 'base64').toString('utf8');+ const decisionModule = { exports: {} };+ new Function('module', 'exports', 'require', decisionSrc)(+ decisionModule, decisionModule.exports,+ () => { throw new Error('review-signal-decision.cjs must stay dependency-free'); },+ );+ ({codeApproved, codeWithdrawn} =+ decisionModule.exports.resolveReviewApprovals({+ reviews,+ headSha,+ engOwners: [...codeApprovers],+ designOwners: [],+ }));++ const statuses = await github.paginate(+ 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 || '';+ const statusOwnsGate =+ trustedStatus &&+ ((latestGateStatus.state === 'pending' &&+ (description.startsWith('Waiting on code review:') ||+ description === 'Waiting on code review after approval withdrawal.')) ||+ (latestGateStatus.state === 'success' &&+ description === 'Cleared by code-owner approval.'));+ gateOwned =+ full.labels.some((label) => label.name === CODE) || statusOwnsGate;} catch (e) {- core.warning(`Could not read reviews: ${e.message}`);+ core.warning(`Could not resolve exact-head gate state: ${e.message}`);+ return;}- if (!codeApproved) {- core.info(`PR #${prNumber}: no entitled code owner (CODEOWNER/ENGOWNER) approval; leaving gate as-is.`);+ if (!gateOwned) {+ core.info(`PR #${prNumber}: current head was not marked as code-gated; leaving it as-is.`);+ return;+ }+ if (!codeApproved && !codeWithdrawn) {+ core.info(`PR #${prNumber}: no effective ENGOWNER review-state change; leaving gate as-is.`);+ return;+ }++ // Re-read immediately before either mutation. A head that moved after+ // review resolution must be reconciled by review-signal for the new+ // head, never by carrying this decision forward.+ const { data: current } = await github.rest.pulls.get({+ owner, repo, pull_number: prNumber,+ });+ if (current.head.sha !== headSha) {+ core.info(`PR #${prNumber}: head moved while resolving approval; leaving gate as-is.`);+ return;+ }+ const labels = current.labels.map((l) => l.name);++ 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.',+ });+ core.info(`review-required status → pending on #${prNumber}.`);+ if (!labels.includes(CODE)) {+ await github.rest.issues.addLabels({+ owner, repo, issue_number: prNumber, labels: [CODE],+ });+ core.info(`Restored ${CODE} on #${prNumber}.`);+ }return;}diff --git a/.github/workflows/review-signal.yml b/.github/workflows/review-signal.ymlindex af5d4d4b56..42bf6704b7 100644--- a/.github/workflows/review-signal.yml+++ b/.github/workflows/review-signal.yml@@ -8,11 +8,13 @@# needs:code-review — HIGH-RISK code areas: a new package, a new# component/module (in core — NOT lab, which is the# canary staging area), any runtime change under-# core/src (incl. styling — core has high blast radius),-# or public API surface, NOT confined to low-risk areas-# (themes, templates, sandbox, storybook, docsite).-# Requests review from CODEOWNERS. Skipped when the-# author is an ENGOWNER (eng self-serves code).+# core/src, or public API surface, NOT confined to+# low-risk areas (themes, templates, sandbox, storybook,+# docsite). Requests review from CODEOWNERS. ENGOWNERS+# self-serve code. A DESIGNOWNER author also self-serves+# an existing-file Core diff only when the trusted-base+# classifier proves every runtime line appearance-only+# and no other code reason applies.## needs:design-review — DESIGN-AFFECTING changes anywhere: StyleX styling,# theme/token files, or a template's .tsx. Keyed on@@ -42,15 +44,16 @@## Design review is ADVISORY: a design-affecting change is labeled# needs:design-review and design owners are requested, but it does NOT block-# the merge. All contributor (non-owner) PRs require code review; owners-# self-serve code.+# the merge. All contributor (non-owner) PRs require code review; engineering+# owners self-serve code, and design owners self-serve only classifier-proven+# appearance-only Core runtime changes.## Uses pull_request_target so it can label / request reviewers / disable-# auto-merge on fork PRs. It reads the PR file LIST, the PR DIFF TEXT, and the-# eng/design owner lists from repo VARIABLES (vars.ENGOWNERS / vars.DESIGNOWNERS)-# via the API — no owner-file content API, no checkout. It never checks out or-# runs PR-controlled code (the diff is scanned as data; the classifier it feeds-# is loaded from the BASE ref, not the PR). Do not add checkout or build steps here.+# auto-merge on fork PRs. It reads the PR file list, diff text, and changed Core+# base/head source bytes as inert API data. The classifiers and approval helper+# come from the trusted 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.name: Review signal@@ -59,7 +62,7 @@ on:branches: ['main']types: [opened, synchronize, reopened, ready_for_review, converted_to_draft]pull_request_review:- types: [submitted]+ types: [submitted, dismissed]# 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@@ -211,6 +214,22 @@ jobs:return;}+ const { data: reviewDecisionFile } = await github.rest.repos.getContent({+ owner, repo, ref: pr.base.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, {owner, repo, pull_number: pr.number, per_page: 100,@@ -220,19 +239,19 @@ jobs:`GitHub returned ${allFiles.length} of ${pr.changed_files} changed files; refusing to classify an incomplete PR.`,);}- // lab is the canary-only staging area — new components are EXPECTED- // to develop and harden there before promotion. Skip the entire- // packages/lab/** folder for ALL signal detection (code and design)- // by filtering it out once, up front. lab is a SAFE SPACE (below).- const isLab = (p) => /^packages\/lab\//.test(p);- const files = allFiles.filter((f) => !isLab(f.filename));- const paths = files.map((f) => f.filename);+ // A change is excluded as a safe-space change only when both its+ // current and previous path are safe. This keeps unsafe→safe and+ // Core→safe renames visible and fail-closed.+ const {files, hasSafeBoundaryRename, paths} =+ reviewDecision.classifyReviewSignalPaths(allFiles);+ const isSafeSpace = reviewDecision.isSafeSpace;// Two DIFFERENT categories — do not conflate them://// SAFE SPACES — experimentation / staging. Exempt from BOTH gates.// No review of any kind is expected here.- // lab (filtered above), sandbox, storybook.+ // lab, sandbox, storybook. A rename is safe only when both the+ // previous and current paths are safe.//// DESIGN SPACES — where design work lives. Exempt from the CODE// gate (low-risk for code), but they TRIGGER the DESIGN gate.@@ -240,8 +259,6 @@ jobs://// Both are low-risk for the CODE gate, so the code gate ignores// their union; only the design gate cares about the distinction.- const isSafeSpace = (p) =>- isLab(p) || /^apps\/(sandbox|storybook)\//.test(p);const isDesignSpace = (p) =>/^packages\/themes\//.test(p) ||/^packages\/cli\/templates\//.test(p) ||@@ -272,6 +289,9 @@ jobs:// ============ HIGH-RISK CODE ============const codeReasons = [];+ if (hasSafeBoundaryRename) {+ codeReasons.push('safe-space boundary rename');+ }const newPackage = files.some((f) => f.status === 'added' &&/^packages\/[^/]+\/package\.json$/.test(f.filename),@@ -288,20 +308,6 @@ jobs:codeReasons.push('public API surface change');}const coreChange = paths.some(isCoreRuntime);- if (coreChange && !codeReasons.includes('new component/module')) {- codeReasons.push('core change');- }-- // ALL contributor (non-owner) PRs require code review, not just the- // high-risk ones. External contributors can't self-merge anyway;- // this mainly holds internal contributors who have write access but- // are not on the eng/design team. Owners still self-serve code- // (gated only by the high-risk reasons above → suppressed for eng).- const authorIsOwner = authorIsEng || authorIsDesign;- if (!authorIsOwner) codeReasons.push('community contribution');-- // Eng owners self-serve code — no code tag for them.- const codeHighRisk = codeReasons.length > 0 && !authorIsEng;// ============ DESIGN-AFFECTING ============// DESIGN SPACES trigger this gate; SAFE SPACES never do (both@@ -323,18 +329,16 @@ jobs:if (paths.some((p) => /^packages\/cli\/templates\/.+\.tsx$/.test(p))) designReasons.push('template change');if (paths.some(isDocsiteVisual)) designReasons.push('docsite visual change');- // Content-based visual signal (#3667). The path signals above- // cannot see the most common visual change in this codebase: an- // inline `stylex.create` edit inside a component .tsx (no- // .stylex.ts touched). Score the diff CONTENT with the shared- // classifier. Safety: both the classifier source and the diff come- // from the API — the source from the BASE ref (trusted), the diff- // as inert text. Best-effort: any failure (huge diff 406, missing- // file on old base) logs a warning and falls back to path signals.- if (designReasons.length === 0) {+ // Content-based visual signal (#3667). The classifier also proves+ // the narrower appearance-only exception for DESIGNOWNER authors.+ // It and the diff both come from the API: trusted BASE-ref source,+ // inert PR diff text. Any fetch or parse failure keeps the exception+ // false, so Core runtime changes continue to require engineering.+ let visualClassification = null;+ if (coreChange || designReasons.length === 0) {try {const { data: libFile } = await github.rest.repos.getContent({- owner, repo, ref: pr.base.ref,+ owner, repo, ref: pr.base.sha,path: '.github/scripts/lib/classify-visual.js',});const libSrc = Buffer.from(libFile.content, 'base64').toString('utf8');@@ -348,18 +352,84 @@ jobs:{ owner, repo, pull_number: pr.number,headers: { accept: 'application/vnd.github.diff' } },);- const vc = mod.exports.classifyVisualDiff(String(diff), {+ const sources = {};+ const coreRuntimeFiles = files.filter((file) =>+ isCoreRuntime(file.filename) ||+ (file.previous_filename && isCoreRuntime(file.previous_filename)),+ );+ async function readSource(fullName, ref, filePath) {+ const [sourceOwner, sourceRepo] = fullName.split('/');+ const { data } = await github.rest.repos.getContent({+ owner: sourceOwner,+ repo: sourceRepo,+ ref,+ path: filePath,+ });+ if (Array.isArray(data) || data.type !== 'file' || !data.content) {+ throw new Error(`Could not read source bytes for ${filePath}.`);+ }+ return Buffer.from(data.content, 'base64').toString('utf8');+ }+ for (const file of coreRuntimeFiles) {+ const previousPath = file.previous_filename || file.filename;+ if (file.status !== 'modified' || previousPath !== file.filename) {+ continue;+ }+ const [baseSource, headSource] = await Promise.all([+ readSource(+ pr.base.repo.full_name,+ pr.base.sha,+ previousPath,+ ),+ readSource(+ pr.head.repo.full_name,+ pr.head.sha,+ file.filename,+ ),+ ]);+ sources[file.filename] = {base: baseSource, head: headSource};+ }+ visualClassification = mod.exports.classifyVisualDiff(String(diff), {ignorePath: isSafeSpace,+ sources,});- core.info(`visual content score: ${vc.score} (${vc.bucket})`);- if (vc.bucket === 'visual' || vc.bucket === 'likely-visual') {- designReasons.push(`visual diff content (score ${vc.score})`);+ core.info(`visual content score: ${visualClassification.score} (${visualClassification.bucket}); appearanceOnly=${visualClassification.appearanceOnly}`);+ if (+ designReasons.length === 0 &&+ (visualClassification.bucket === 'visual' ||+ visualClassification.bucket === 'likely-visual')+ ) {+ designReasons.push(+ `visual diff content (score ${visualClassification.score})`,+ );}} catch (e) {- core.warning(`Content-based visual signal skipped: ${e.message}`);+ core.warning(`Content-based visual classification failed closed: ${e.message}`);}}+ const appearanceOnly = visualClassification?.appearanceOnly === true;+ if (coreChange && !codeReasons.includes('new component/module')) {+ codeReasons.push(appearanceOnly ? 'core visual change' : 'core change');+ }++ // ALL contributor (non-owner) PRs require code review. The narrow+ // appearance-only exception below is available only to a DESIGNOWNER;+ // external contributors stay in the normal contribution flow.+ const authorIsOwner = authorIsEng || authorIsDesign;+ if (!authorIsOwner) codeReasons.push('community contribution');++ const onlyCoreVisualChange =+ codeReasons.length === 1 && codeReasons[0] === 'core visual change';+ const designOwnerAppearanceSelfServe =+ authorIsDesign && appearanceOnly && onlyCoreVisualChange;+ // Eng owners self-serve all code. Design owners self-serve only the+ // classifier-proven appearance-only Core case above.+ const codeHighRisk =+ codeReasons.length > 0 &&+ !authorIsEng &&+ !designOwnerAppearanceSelfServe;+// Design owners self-serve design — no design tag for them.const designAffecting = designReasons.length > 0 && !authorIsDesign;@@ -376,33 +446,25 @@ jobs:// as satisfied when an entitled owner has approved:// code gate → an ENGOWNER approval// design gate → a DESIGNOWNER approval- // We use each reviewer's LATEST review state so a later- // CHANGES_REQUESTED/DISMISSED correctly un-satisfies it.+ // Only reviews whose commit_id equals this current PR head count.+ // Within that head, each reviewer's latest APPROVED /+ // CHANGES_REQUESTED / DISMISSED state wins. An H1 approval can never+ // clear H2 for either engineering or design.let codeApproved = false;let designApproved = false;try {const reviews = await github.paginate(github.rest.pulls.listReviews, {owner, repo, pull_number: pr.number, per_page: 100,});- const latestByUser = new Map();- for (const r of reviews) {- if (!r.user) continue;- // Ignore comment-only reviews; keep the latest APPROVED /- // CHANGES_REQUESTED / DISMISSED per reviewer.- if (r.state === 'COMMENTED') continue;- latestByUser.set(r.user.login.toLowerCase(), r.state);- }- for (const [login, state] of latestByUser) {- if (state !== 'APPROVED') continue;- // Code gate: any ENGOWNER approval satisfies it (eng owns the- // code; the CODEOWNERS subset is a subset of ENGOWNERS, so- // ENGOWNERS covers it). Design gate: only a DESIGNOWNER — an- // eng approval does NOT clear a design gate.- if (engOwners.includes(login)) codeApproved = true;- if (designOwners.includes(login)) designApproved = true;- }+ ({codeApproved, designApproved} =+ reviewDecision.resolveReviewApprovals({+ reviews,+ headSha: pr.head.sha,+ engOwners,+ designOwners,+ }));} catch (e) {- core.warning(`Could not read reviews: ${e.message}`);+ core.warning(`Could not resolve exact-head reviews: ${e.message}`);}// Effective gate = detected gate minus what an entitled owner@@ -511,15 +573,18 @@ jobs:// whose POST failed is blocked on a status that will never arrive.// Throwing marks the run red and lets the per-PR catch continue a// backfill; re-run the workflow to retry.+ const gateDescription = codeGated+ ? `Waiting on code review: ${gateReasons.join(', ')}`.slice(0, 140)+ : 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: codeGated- ? `Waiting on code review: ${gateReasons.join(', ')}`.slice(0, 140)- : 'No code review required.',+ description: gateDescription,});core.info(`review-required status: ${codeGated ? 'pending' : 'success'}`);// Neutralize any stale "review-required" CHECK RUN left over from the@@ -545,17 +610,15 @@ jobs:}} // end flagOne- # Anchor job for the review-clear chain. On a review submission the flag job- # is skipped (it only runs on pull_request_target / workflow_dispatch), so- # without a job that actually runs, the workflow run could end up "skipped"- # rather than "completed" and not reliably fire the review-clear workflow_run.- # This tiny job always runs on pull_request_review so the workflow completes,- # letting review-clear.yml resolve the PR and re-dispatch the fork-safe clear.+ # Anchor the clear/restore chain for every review state that can change the+ # effective exact-head engineering approval.review-anchor:- if: github.event_name == 'pull_request_review' && github.event.review.state == 'approved'+ if: >-+ github.event_name == 'pull_request_review' &&+ contains(fromJSON('["approved","changes_requested","dismissed"]'), github.event.review.state)name: Anchor review-clear chainruns-on: ubuntu-slimpermissions: {}steps:- - name: Note approval- run: echo "Approval received; review-clear will re-dispatch the flag job."+ - name: Note review state change+ run: echo "Review state changed; review-clear will reconcile the code gate."diff --git a/.github/workflows/spec-owner-gate.yml b/.github/workflows/spec-owner-gate.ymlindex 822ef313b0..a213da47c6 100644--- a/.github/workflows/spec-owner-gate.yml+++ b/.github/workflows/spec-owner-gate.yml@@ -2,8 +2,10 @@# 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 and normative design-# assets also accept DESIGNOWNERS. Mixed PRs keep every applicable owner-group+# 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; draft-only records# can auto-merge after validation, while current records also need approval ondiff --git a/AGENTS.md b/AGENTS.mdindex 75b364b3e6..dffd25af35 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -30,6 +30,13 @@ nested `AGENTS.md`.route exposes only the listed claim; it never makes the whole record governthe component or change. Preserve each matched record, claim, trigger, andmatch reason in the review receipt.+- Component-local visual intent: reuse or amend the optional `Design decisions`+ table in the current component/module spec only when durable local intent must+ survive future redesigns. Keep exact tuning in code/evidence and shared rules+ in `docs/design/`. DESIGNOWNER authors may include that local intent with the+ pixels and evidence in one atomic appearance-only PR. External contributors+ follow the normal contribution flow and are never asked to author specs;+ maintainers own missing authority.- Cross-component work: read the relevant contract under `docs/families/`,applicable design spec under `docs/design/`, and current architecture under`docs/architecture/`.diff --git a/docs/architecture/knowledge-contracts.md b/docs/architecture/knowledge-contracts.mdindex 54ba5ddb2c..d7fc705af5 100644--- a/docs/architecture/knowledge-contracts.md+++ b/docs/architecture/knowledge-contracts.md@@ -21,6 +21,11 @@ verified_by:[scripts/check-knowledge.test.mjs,.github/scripts/change-scope.test.mjs,+ .github/scripts/component-design-decisions.test.mjs,+ .github/scripts/lib/classify-visual.test.mjs,+ .github/scripts/review-clear-workflow.test.mjs,+ .github/scripts/review-signal-decision.test.mjs,+ .github/scripts/review-signal-workflow.test.mjs,.github/scripts/spec-owner-decision.test.mjs,]deciding_specs: []@@ -41,7 +46,9 @@ deciding_specs: []"INV16","INV18","INV20",- "DEC-9"+ "INV21",+ "DEC-9",+ "DEC-10"]}}@@ -63,6 +70,9 @@ Astryx keeps different facts in different places:- Module contracts describe an independently contractible public hook, plugin,utility, or subsystem owned by one component. Private implementation helpers donot require records.+- An optional `Design decisions` table inside a component or module contract+ records durable visual intent local to that owner. It does not hold exact pixel+ tuning or rules shared across components.- Family contracts describe behavior sibling components share.- Design specs record human-owned visual and interaction decisions, including thecross-theme accessibility and contrast methodology used to judge token/color@@ -224,6 +234,17 @@ Every record is either:the whole record, adjacent claims, drafts, or proposed-head authority govern.Every routed match records the base authority commit, record digest, record id,path, trigger, claim id, claim title, and deterministic match reason.+- **INV21 — Component-local visual intent stays local and durable.** The optional+ `### Design decisions` table under `## Design relationships` belongs only to+ component- or module-local appearance intent that a future redesign must+ reconsider. Authors cite, reuse, or amend stable `DD1`, `DD2`, … rows before+ adding one. Exact pixel tuning normally remains in code and visual evidence;+ shared or cross-component rules remain in `docs/design/`. Team design owners+ may commit a row with the pixels and evidence in one atomic appearance-only+ 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.## Global review applicability@@ -321,6 +342,15 @@ Then write the authoritative body:- Use readable tables for branches or state matrices when they improve scanning.Never remove contract content merely to shorten a record.+For routine local appearance intent, a component or module record may include the+optional versioned `Design decisions` table under `Design relationships`. Each row+uses a stable, unique `DD` id and states the decision, its intent or reason, where+it applies, and allowed variation. Add a row only when the intent is durable enough+that a future redesign must reconsider it. Reuse or amend an existing row first.+Do not copy exact pixel tuning out of code/evidence or shared rules out of+`docs/design/`. A header-only table is valid in a template; an authored block has+at least one complete row.+Plain language must preserve normative force, predicates, cardinality, defaults,compatibility, authority, owners, IDs, evidence state, and decision status. Do notdelete, weaken, merge, or hide distinct normative content. Replace a local fact@@ -459,8 +489,9 @@ contraction. It does not merely report that authority is missing.### Recording a new human decision1. A contributor explains the intended behavior and primary intent in normal- pull-request language and responds to review. They do not need to know the- repository's spec system.+ pull-request language and responds to review. External contributors keep the+ normal contribution flow: they are never asked to author or update a+ specification.2. A reviewer or agent applies the contraction path above. Only a surviving,intentional `novel-human` question proceeds; the contributor does not inventthe answer or specify unrelated adjacent behavior.@@ -546,14 +577,38 @@ this flow passes the historical review benchmark and is enforced on pull request- `packages/themes/<theme>/<theme>.spec.md` contains that package theme'scanonical record; `docs/themes/README.md` is guidance and an index only.- `docs/schemas/knowledge/` defines required structure.-- `scripts/check-knowledge.mjs` validates templates, records, and approval- metadata.+- `scripts/check-knowledge.mjs` validates templates, records, approval metadata,+ and optional component/module design-decision tables.+- `.github/scripts/component-design-decisions.cjs` classifies current+ component/module changes as no DD change, DD-only, or mixed from trusted base+ 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 pullrequest head. Approval for every record kind derives from `.github/ENGOWNERS`;- current design and theme records and normative design assets additionally accept- `.github/DESIGNOWNERS`. Record metadata never self-authorizes. The workflow- enables auto-merge only for pure spec changes.+ 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 workflow enables auto-merge only for pure spec changes.+- `.github/workflows/review-signal.yml` lets a DESIGNOWNER author bypass the+ engineering gate only when trusted-base code verifies every changed Core line+ against the fetched base/head source bytes as a conservative declaration inside+ a real `stylex.create` call, and no other code reason applies. The classifier+ also rejects direct interaction, operability, and scroll-control+ declarations—including hit testing, touch behavior, selection, resize,+ cursor, visibility, overflow, snapping, and scrollbar affordance—on either+ diff side. Contributors and mixed or behavioral changes remain gated.+ Safe-space classification considers both current and previous paths: only+ changes whose every path is safe are excluded, and any rename crossing that+ boundary is an engineering reason.+ Engineering and design reviews count only when their `commit_id` equals the+ current pull-request head. The direct reconciler clears only a current-head+ gate already owned by `review-signal`; an effective ENGOWNER+ `CHANGES_REQUESTED` or `DISMISSED` state first restores the hard status gate to+ pending, then restores its advisory label. A failed status write performs no+ preceding label mutation.+ Approval, withdrawal, and dismissal all recheck the head immediately before+ mutation, and an ungated head never acquires a gate from review state alone.## Deciding specs@@ -704,21 +759,53 @@ Rejected: treating a `global` marker as authority for every statement in a file,because that would erase claim boundaries and let unrelated or draft materialsilently govern a change.+### DEC-10 — Routine visual intent lives with its component or module++**Reference:** `architecture:knowledge-contracts/DEC-10`+**Decider:** `cixzhang`, `2026-09-23`++A small structured `Design decisions` table in the owning component or module+spec records only durable local visual intent. One row may cover a coherent local+direction; tiny visual tuning does not create one decision record per tweak.+Existing rows are cited, reused, or amended before new rows are added. Exact+pixels remain in code and evidence, while shared and cross-component direction+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's exact-head ready transition+may satisfy the design group. 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+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.++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.+## 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 |+| 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 |Current enforcement gap: no checked-in gate yet proves the open-pull-requestsearch. Until one exists, the pull-request summary records the search terms,diff --git a/docs/contributing/pull-requests.md b/docs/contributing/pull-requests.mdindex 79d9d37917..49f06ceba4 100644--- a/docs/contributing/pull-requests.md+++ b/docs/contributing/pull-requests.md@@ -78,7 +78,19 @@ A current record governs only its explicit claims inside its ownership boundary.A visual change does not automatically need a new specification. It may proceed as a correction when current component, family, design, theme, or objective accessibility authority already settles the exact outcome. Show that authority and verify the affected state with real-browser pixels, plus representative unchanged states.-A new visual representation, subjective direction, or interaction model remains a design decision. Put that decision in its own specification or owner-reviewed visual update instead of attaching it to a bug fix.+For routine component-local or module-local intent, cite and reuse an existing+`DD` row when one applies. A team DESIGNOWNER may amend or add the optional+`Design decisions` table in the component/module spec in the same atomic+appearance-only pull request as the pixels and evidence. Add a row only for+stable intent a future redesign must reconsider; exact pixel tuning stays in+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.++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.## Public repository boundarydiff --git a/docs/templates/knowledge/component-spec.md b/docs/templates/knowledge/component-spec.mdindex 08632127cf..f85dc2b8ee 100644--- a/docs/templates/knowledge/component-spec.md+++ b/docs/templates/knowledge/component-spec.md@@ -1,6 +1,6 @@---schema_version: 3-template_version: 5+template_version: 6kind: componentid: component:<Name>authority: draft@@ -119,6 +119,20 @@ The component implements design requirements without copying their rationale.An `unsettled` representation remains a human decision; principles do not let anagent invent the answer.+Use the optional table below only for durable component-local visual intent that+a future redesign must reconsider. Reuse or amend an existing row before adding+one. Exact pixel tuning normally stays in code and visual evidence. Put shared or+cross-component rules in `docs/design/` and link them from the relationship table+above. Use `DD1`, `DD2`, and so on; IDs remain stable and unique within this+record.++### Design decisions++<!-- design-decisions:v1 -->++| ID | Decision | Intent or reason | Applies to | Allowed variation |+| --- | -------- | ---------------- | ---------- | ----------------- |+### Theming anatomy<!--diff --git a/docs/templates/knowledge/module-spec.md b/docs/templates/knowledge/module-spec.mdindex d837a00942..37ad86f0be 100644--- a/docs/templates/knowledge/module-spec.md+++ b/docs/templates/knowledge/module-spec.md@@ -1,6 +1,6 @@---schema_version: 3-template_version: 2+template_version: 3kind: moduleid: module:<ParentComponent>/<PublicName>authority: draft@@ -88,6 +88,20 @@ Consumer migration instructions belong in consumer docs and release notes.| ---------------- | ---------------------- | -------------------------------------------- | ------------------- || `<role/state>` | `design:<surface>/DR1` | `<prescribed, human-selected, or unsettled>` | `<FR/AR reference>` |+Use the optional table below only for durable module-local visual intent that a+future redesign must reconsider. Reuse or amend an existing row before adding+one. Exact pixel tuning normally stays in code and visual evidence. Put shared or+cross-component rules in `docs/design/` and link them from the relationship table+above. Use `DD1`, `DD2`, and so on; IDs remain stable and unique within this+record.++### Design decisions++<!-- design-decisions:v1 -->++| ID | Decision | Intent or reason | Applies to | Allowed variation |+| --- | -------- | ---------------- | ---------- | ----------------- |+### Theming anatomy<!--diff --git a/docs/templates/knowledge/versions.json b/docs/templates/knowledge/versions.jsonindex 546df9fb20..e1fba65ceb 100644--- a/docs/templates/knowledge/versions.json+++ b/docs/templates/knowledge/versions.json@@ -1,10 +1,10 @@{"architecture": 2,- "component": 5,+ "component": 6,"design": 1,"family": 1,"implementation-plan": 1,- "module": 2,+ "module": 3,"system-spec": 1,"theme": 1}diff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjsindex 79ee1dc459..8d21f3cd72 100644--- a/scripts/check-knowledge.mjs+++ b/scripts/check-knowledge.mjs@@ -18,6 +18,10 @@ const {parseAuthority,parseOwnerFile,} = require('../.github/scripts/knowledge-frontmatter.cjs');+const {+ parseDesignDecisionsBlock,+ validateDesignDecisionsBlock,+} = require('../.github/scripts/component-design-decisions.cjs');const {classifyComponentKnowledgePath,isComponentSpecRecordPath,@@ -35,6 +39,8 @@ const READER_FIRST_TEMPLATE_KINDS = new Set([]);const CONTRACT_AT_A_GLANCE_SECTION = 'Contract at a glance';+export {parseDesignDecisionsBlock, validateDesignDecisionsBlock};+function expectedTemplateSections(kind, requiredSections) {return READER_FIRST_TEMPLATE_KINDS.has(kind)? [CONTRACT_AT_A_GLANCE_SECTION, ...requiredSections]@@ -1612,8 +1618,9 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {);continue;}+ const templateContent = fs.readFileSync(templatePath, 'utf8');const template = parseKnowledgeDocument(- fs.readFileSync(templatePath, 'utf8'),+ templateContent,kindSchema.template,);problems.push(@@ -1631,6 +1638,18 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {if (template.frontmatter.get('kind') !== kind) {problems.push(`${kindSchema.template}: template kind must be ${kind}.`);}+ if (kind === 'component' || kind === 'module') {+ const designDecisions = parseDesignDecisionsBlock(+ templateContent,+ kindSchema.template,+ );+ problems.push(+ ...validateDesignDecisionsBlock(designDecisions, {+ allowHeaderOnly: true,+ filePath: kindSchema.template,+ }),+ );+ }}for (const absolutePath of discoverKnowledgeRecords(root)) {@@ -1680,6 +1699,10 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {);}if (kind === 'component' || kind === 'module') {+ const designDecisions = parseDesignDecisionsBlock(content, filePath);+ problems.push(+ ...validateDesignDecisionsBlock(designDecisions, {filePath}),+ );const parsed = parseAnatomyThemingBlock(content, filePath);problems.push(...parsed.problems);if (parsed.mapping != null) {diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjsindex 5a46076cc1..3f35ddcfe4 100644--- a/scripts/check-knowledge.test.mjs+++ b/scripts/check-knowledge.test.mjs@@ -11,10 +11,12 @@ import {discoverKnowledgeRecords,extractKnowledgeClaims,parseAnatomyThemingBlock,+ parseDesignDecisionsBlock,parseKnowledgeDocument,parseReviewApplicabilityBlock,routeGlobalReviewBaselinesAtRevision,validateAnatomyThemingMap,+ validateDesignDecisionsBlock,validateDelegations,validateKnowledgeRoot,validateReviewApplicability,@@ -664,6 +666,74 @@ describe('schema evolution', () => {});});+describe('component-local design decisions', () => {+ const row =+ '| DD1 | Keep the label visually quiet. | Preserve primary-action emphasis. | Default label | Theme token substitutions may preserve contrast. |';+ const block = `${[+ '### Design decisions',+ '',+ '<!-- design-decisions:v1 -->',+ '',+ '| ID | Decision | Intent or reason | Applies to | Allowed variation |',+ '| --- | --- | --- | --- | --- |',+ row,+ ].join('\n')}\n`;++ it('parses a valid optional table under Design relationships', () => {+ const parsed = parseDesignDecisionsBlock(+ `## Design relationships\n\nBody.\n\n${block}\n### Theming anatomy\n`,+ );+ expect(parsed.rows).toHaveLength(1);+ expect(parsed.rows[0].id).toBe('DD1');+ expect(validateDesignDecisionsBlock(parsed)).toEqual([]);+ });++ it('keeps absence valid and permits header-only template guidance', () => {+ expect(+ validateDesignDecisionsBlock(+ parseDesignDecisionsBlock('## Design relationships\n\nBody.\n'),+ ),+ ).toEqual([]);+ const headerOnly = parseDesignDecisionsBlock(+ `## Design relationships\n\n${block.replace(`\n${row}`, '')}`,+ );+ expect(+ validateDesignDecisionsBlock(headerOnly, {allowHeaderOnly: true}),+ ).toEqual([]);+ });++ it('keeps the optional header-only table in component and module templates', () => {+ for (const template of ['component-spec.md', 'module-spec.md']) {+ const parsed = parseDesignDecisionsBlock(+ fs.readFileSync(+ path.join(repoRoot, 'docs/templates/knowledge', template),+ 'utf8',+ ),+ template,+ );+ expect(parsed.present, template).toBe(true);+ expect(parsed.rows, template).toEqual([]);+ expect(+ validateDesignDecisionsBlock(parsed, {allowHeaderOnly: true}),+ template,+ ).toEqual([]);+ }+ });++ it('rejects malformed, empty, and duplicate authored rows', () => {+ const malformed = block+ .replace('Intent or reason', 'Rationale')+ .replace(row, `${row}\n${row.replace('DD1', 'bad')}`);+ const parsed = parseDesignDecisionsBlock(+ `## Design relationships\n\n${malformed}`,+ 'Button.spec.md',+ );+ expect(validateDesignDecisionsBlock(parsed).join('\n')).toMatch(+ /columns must be exactly.*must match DD1/s,+ );+ });+});+describe('component theming anatomy metadata', () => {const contract = {anatomy: ['Root', 'Label', 'Icon', 'Content'],@@ -1985,10 +2055,10 @@ describe('knowledge validation', () => {fs.mkdirSync(directory);fs.writeFileSync(path.join(directory, 'Button.spec.md'),- componentRecord({template_version: '6'}),+ componentRecord({template_version: '7'}),);expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(- /template_version 6 is newer than 5/,+ /template_version 7 is newer than 6/,);});