An open source design system that's fully customizable and agent ready
TypeScript
build: bootstrap owner-gated knowledge contracts (#5702)
Cindy Zhang1e5db77c6e6a
diff --git a/.github/DESIGNOWNERS b/.github/DESIGNOWNERSindex 61923f6ead..467deb306e 100644--- a/.github/DESIGNOWNERS+++ b/.github/DESIGNOWNERS@@ -1,14 +1,13 @@# Design owners for the Astryx repository+# Design-team members. This list has two responsibilities:#-# Design-team members. The Copilot reviewer reads this list to frame its review-# for a designer (see .github/copilot-instructions.md, "Review buckets") — it-# names what crosses into engineering territory and needs an engineer's eye.+# - Current design specs and normative design assets may receive exact-head+# approval from any DESIGNOWNER, cixzhang, or imdreamrunner.+# - Review tooling may use the list to frame design-authored changes.#-# This only shapes the TONE of Copilot's comment. It does NOT change merge-# rights or exempt anyone from review: the auto-merge gate is decided by-# high-risk AREA (new package/component/API), not by who authored the PR — see-# .github/workflows/review-signal.yml. No author is exempt from the high-risk-# gate; the low-risk carve-out exempts by area, not by person.+# This does not grant general merge rights or exempt an author from engineering+# review. Mixed PRs still need cixzhang or imdreamrunner for every non-design+# current record.## Uses the same @handle format as CODEOWNERS. Keep this list current.diff --git a/.github/REVIEW_GATE.md b/.github/REVIEW_GATE.mdindex 60af380801..127e824eb4 100644--- a/.github/REVIEW_GATE.md+++ b/.github/REVIEW_GATE.md@@ -20,6 +20,30 @@ neutral yellow "waiting" signal, not a red failure).but does not block the merge.- An entitled owner's **approval clears the gate automatically** (no manual step).+## Spec records++Any PR that creates, changes, or archives a `current` architecture, component,+family, design, or system spec waits on `spec-owner-approval` for its exact+current head. `cixzhang` or `imdreamrunner` can approve every record kind.+Current design records and normative design assets may also be approved by any+handle in `.github/DESIGNOWNERS`. Mixed PRs still require `cixzhang` or+`imdreamrunner` for non-design current records. When an approver is also the+author, the explicit equivalent is a comment containing+`/approve-spec <full-head-sha>`; a new commit invalidates it.++A PR changes only spec records when every changed path is one of:++- `docs/specs/<id>/spec.md` or `plan.md`;+- a family or design spec (excluding indexes, templates, schemas, and assets);+- a colocated Core/Lab `<Name>.spec.md`.++Draft-only spec records can merge after validation without owner approval.+That classification fails closed on an empty or truncated file list and checks+both sides of a rename. Pure spec-record PRs run knowledge validation, skip+runtime/build/visual work with successful required-status acknowledgements, and+enable squash auto-merge after owner approval. Mixed code/spec changes keep full+CI and never gain this auto-merge path.+## Sources of truth| File | Meaning |diff --git a/.github/scripts/change-scope.cjs b/.github/scripts/change-scope.cjsnew file mode 100644index 0000000000..a1476e02d9--- /dev/null+++ b/.github/scripts/change-scope.cjs@@ -0,0 +1,130 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';+/* global module, process, require */++/**+ * Classifies changed paths without reading PR-controlled content.+ *+ * A spec-only PR may change only spec records. Templates, schemas, indexes,+ * architecture, audits, workflows, and code deliberately do not qualify.+ */++const SPEC_RECORD_PATTERNS = [+ /^docs\/specs\/[^/]+\/(?:spec|plan)\.md$/,+ /^docs\/families\/(?!README\.md$)[^/]+\.md$/,+ /^docs\/design\/(?!README\.md$)(?!assets\/)[^/]+\.md$/,+ /^packages\/(?:core|lab)\/src\/[^/]+\/[^/]+\.spec\.md$/,+];++const KNOWLEDGE_RECORD_PATTERNS = [+ ...SPEC_RECORD_PATTERNS,+ /^docs\/architecture\/(?!README\.md$)[^/]+\.md$/,+ /^docs\/design\/assets\//,+];++function isSpecRecordPath(filePath) {+ return SPEC_RECORD_PATTERNS.some(pattern => pattern.test(filePath));+}++function isKnowledgeRecordPath(filePath) {+ return KNOWLEDGE_RECORD_PATTERNS.some(pattern => pattern.test(filePath));+}++function normalizeChange(change) {+ if (typeof change === 'string') {+ return {filename: change, previous_filename: null};+ }+ return {+ filename: change.filename,+ previous_filename: change.previous_filename ?? null,+ };+}++function classifyChanges(changes, {expectedCount} = {}) {+ const normalized = changes+ .map(normalizeChange)+ .filter(change => change.filename);+ if (normalized.length === 0) {+ const complete = expectedCount == null || expectedCount === 0;+ return {+ specOnly: false,+ touchesKnowledgeRecords: !complete,+ touchesDesignAssets: false,+ docsiteOnly: false,+ complete,+ reason: complete ? 'no changed files' : 'changed-file list is incomplete',+ };+ }+ const complete = expectedCount == null || normalized.length === expectedCount;++ const allPaths = normalized.flatMap(change =>+ change.previous_filename+ ? [change.filename, change.previous_filename]+ : [change.filename],+ );+ const touchesKnowledgeRecords =+ !complete || allPaths.some(isKnowledgeRecordPath);+ const touchesDesignAssets = allPaths.some(filePath =>+ filePath.startsWith('docs/design/assets/'),+ );+ const specOnly = complete && allPaths.every(isSpecRecordPath);+ const docsiteOnly = allPaths.every(filePath =>+ filePath.startsWith('apps/docsite/'),+ );+ return {+ specOnly,+ touchesKnowledgeRecords,+ touchesDesignAssets,+ docsiteOnly,+ complete,+ reason: !complete+ ? 'changed-file list is incomplete'+ : specOnly+ ? 'only spec records changed'+ : docsiteOnly+ ? 'only docsite files changed'+ : 'changes include another surface',+ };+}++function parseNameStatus(input) {+ return input+ .split(/\r?\n/)+ .filter(Boolean)+ .map(line => {+ const fields = line.split('\t');+ const status = fields[0];+ if (/^[RC]/.test(status) && fields.length >= 3) {+ return {+ filename: fields[2],+ previous_filename: fields[1],+ };+ }+ return {filename: fields[1] ?? fields[0]};+ });+}++if (require.main === module) {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const fs = require('node:fs');+ const result = classifyChanges(parseNameStatus(fs.readFileSync(0, 'utf8')));+ if (process.argv.includes('--github-output')) {+ const outputPath = process.env.GITHUB_OUTPUT;+ if (!outputPath)+ throw new Error('GITHUB_OUTPUT is required with --github-output.');+ fs.appendFileSync(+ outputPath,+ `spec_only=${result.specOnly}\ndocsite_only=${result.docsiteOnly}\n`,+ );+ } else {+ process.stdout.write(`${JSON.stringify(result)}\n`);+ }+}++module.exports = {+ classifyChanges,+ isKnowledgeRecordPath,+ isSpecRecordPath,+ parseNameStatus,+};diff --git a/.github/scripts/change-scope.test.mjs b/.github/scripts/change-scope.test.mjsnew file mode 100644index 0000000000..b82b675af4--- /dev/null+++ b/.github/scripts/change-scope.test.mjs@@ -0,0 +1,93 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {createRequire} from 'node:module';+import {describe, expect, it} from 'vitest';++const require = createRequire(import.meta.url);+const {classifyChanges, parseNameStatus} = require('./change-scope.cjs');++describe('spec-only change scope', () => {+ it('accepts system, family, component, and plan records', () => {+ const result = classifyChanges([+ {filename: 'docs/specs/AST-001-overlay-policy/spec.md'},+ {filename: 'docs/specs/AST-001-overlay-policy/plan.md'},+ {filename: 'docs/families/input-fields.md'},+ {filename: 'docs/design/selection-inputs.md'},+ {filename: 'packages/core/src/Selector/Selector.spec.md'},+ {filename: 'packages/lab/src/FutureInput/FutureInput.spec.md'},+ ]);+ expect(result.specOnly).toBe(true);+ });++ it('owner-gates architecture records without granting the spec-only fast path', () => {+ const result = classifyChanges([+ {filename: 'docs/architecture/knowledge-contracts.md'},+ ]);+ expect(result.touchesKnowledgeRecords).toBe(true);+ expect(result.specOnly).toBe(false);+ });++ it('owner-gates normative design assets without granting the spec-only fast path', () => {+ const result = classifyChanges([+ {filename: 'docs/design/assets/selector/alignment.png'},+ ]);+ expect(result.touchesDesignAssets).toBe(true);+ expect(result.touchesKnowledgeRecords).toBe(true);+ expect(result.specOnly).toBe(false);+ });++ it.each([+ 'packages/core/src/Selector/Selector.tsx',+ 'packages/core/src/Selector/Selector.audit.json',+ 'docs/architecture/layers.md',+ 'docs/templates/knowledge/component-spec.md',+ 'docs/schemas/knowledge/v2.json',+ 'docs/specs/README.md',+ '.github/workflows/ci.yml',+ ])('rejects %s', filename => {+ expect(classifyChanges([{filename}]).specOnly).toBe(false);+ });++ it('fails closed for an empty change set', () => {+ expect(classifyChanges([]).specOnly).toBe(false);+ });++ it('fails closed when the API file list is incomplete', () => {+ const result = classifyChanges(+ [{filename: 'docs/specs/AST-001-x/spec.md'}],+ {expectedCount: 3001},+ );+ expect(result.complete).toBe(false);+ expect(result.specOnly).toBe(false);+ expect(result.touchesKnowledgeRecords).toBe(true);+ });++ it('fails closed when an expected API file list is empty', () => {+ const result = classifyChanges([], {expectedCount: 1});+ expect(result.complete).toBe(false);+ expect(result.specOnly).toBe(false);+ expect(result.touchesKnowledgeRecords).toBe(true);+ });++ it('checks both sides of a rename', () => {+ expect(+ classifyChanges([+ {+ filename: 'packages/core/src/Selector/Selector.spec.md',+ previous_filename: 'packages/core/src/Selector/Selector.tsx',+ },+ ]).specOnly,+ ).toBe(false);+ });++ it('parses name-status renames without losing the previous path', () => {+ expect(+ parseNameStatus(+ 'A\tdocs/specs/AST-001-x/spec.md\nR100\told.ts\tpackages/core/src/X/X.spec.md\n',+ ),+ ).toEqual([+ {filename: 'docs/specs/AST-001-x/spec.md'},+ {filename: 'packages/core/src/X/X.spec.md', previous_filename: 'old.ts'},+ ]);+ });+});diff --git a/.github/scripts/knowledge-frontmatter.cjs b/.github/scripts/knowledge-frontmatter.cjsnew file mode 100644index 0000000000..45b3fe81bc--- /dev/null+++ b/.github/scripts/knowledge-frontmatter.cjs@@ -0,0 +1,40 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';+/* global module */++function parseSingleField(content, field, filePath = '<knowledge record>') {+ if (content == null) return null;+ const escapedField = field.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ const pattern = new RegExp(+ `^${escapedField}:\\s*['"]?([a-z-]+)['"]?\\s*$`,+ 'gm',+ );+ const matches = [...content.matchAll(pattern)];+ if (matches.length > 1) {+ throw new Error(`${filePath}: duplicate ${field} fields are not allowed.`);+ }+ return matches[0]?.[1] ?? null;+}++function parseAuthority(content, filePath) {+ return parseSingleField(content, 'authority', filePath);+}++function parseKind(content, filePath) {+ return parseSingleField(content, 'kind', filePath);+}++function parseOwnerFile(content) {+ return [+ ...new Set(+ content+ .split(/\r?\n/)+ .map(line => line.replace(/#.*/, ''))+ .flatMap(line => [...line.matchAll(/@([a-z0-9-]+)/gi)])+ .map(match => match[1].toLowerCase()),+ ),+ ];+}++module.exports = {parseAuthority, parseKind, parseOwnerFile, parseSingleField};diff --git a/.github/scripts/spec-owner-decision.cjs b/.github/scripts/spec-owner-decision.cjsnew file mode 100644index 0000000000..ea70e62d02--- /dev/null+++ b/.github/scripts/spec-owner-decision.cjs@@ -0,0 +1,119 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use strict';+/* global module, require */++/* eslint-disable @typescript-eslint/no-require-imports */+const {+ parseAuthority,+ parseKind,+ parseOwnerFile,+} = require('./knowledge-frontmatter.cjs');+/* eslint-enable @typescript-eslint/no-require-imports */++function parseOwnerCommand(body, headSha) {+ const match = body+ .trim()+ .match(/^\/(approve|revoke)-spec\s+([0-9a-f]{40})$/i);+ if (!match || headSha !== match[2].toLowerCase()) return null;+ return match[1].toLowerCase() === 'approve';+}++function resolveOwnerDecision({reviews, comments, owners, headSha}) {+ const allowed = new Set(owners.map(owner => owner.toLowerCase()));+ const latestByOwner = new Map();++ function consider(login, candidate) {+ if (!allowed.has(login)) return;+ const previous = latestByOwner.get(login);+ if (!previous || new Date(candidate.at) > new Date(previous.at)) {+ latestByOwner.set(login, candidate);+ }+ }++ for (const review of reviews) {+ const login = review.user?.login?.toLowerCase();+ if (!login || review.commit_id !== headSha) continue;+ if (+ !['APPROVED', 'CHANGES_REQUESTED', 'DISMISSED'].includes(review.state)+ ) {+ continue;+ }+ consider(login, {+ approved:+ review.state === 'APPROVED'+ ? true+ : review.state === 'CHANGES_REQUESTED'+ ? false+ : null,+ at: review.submitted_at ?? review.updated_at ?? review.created_at,+ source: 'review',+ owner: login,+ });+ }++ for (const comment of comments) {+ const login = comment.user?.login?.toLowerCase();+ if (!login) continue;+ const approved = parseOwnerCommand(comment.body ?? '', headSha);+ if (approved == null) continue;+ consider(login, {+ approved,+ at: comment.created_at,+ source: 'command',+ owner: login,+ });+ }++ const decisions = [...latestByOwner.values()];+ const rejected = decisions.find(decision => decision.approved === false);+ if (rejected) return rejected;+ return (+ decisions.find(decision => decision.approved === true) ?? {+ approved: false,+ at: null,+ source: null,+ owner: null,+ }+ );+}++function isDesignVersion(content, filePath) {+ return parseKind(content, filePath) === 'design';+}++function requiredApprovalGroups(+ records,+ {complete = true, touchesDesignAssets = false} = {},+) {+ if (!complete) return {spec: true, design: true};+ const groups = {spec: false, design: touchesDesignAssets};+ for (const record of records) {+ const versions = [+ {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;+ groups[+ isDesignVersion(version.content, version.path) ? 'design' : 'spec'+ ] = true;+ }+ }+ return groups;+}++function requiresOwnerApproval(records, options = {}) {+ const groups = requiredApprovalGroups(records, options);+ return groups.spec || groups.design;+}++module.exports = {+ parseAuthority,+ parseKind,+ parseOwnerFile,+ requiredApprovalGroups,+ requiresOwnerApproval,+ parseOwnerCommand,+ resolveOwnerDecision,+};diff --git a/.github/scripts/spec-owner-decision.test.mjs b/.github/scripts/spec-owner-decision.test.mjsnew file mode 100644index 0000000000..0ff71391b4--- /dev/null+++ b/.github/scripts/spec-owner-decision.test.mjs@@ -0,0 +1,267 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {createRequire} from 'node:module';+import {describe, expect, it} from 'vitest';++const require = createRequire(import.meta.url);+const {+ parseOwnerCommand,+ parseOwnerFile,+ requiredApprovalGroups,+ resolveOwnerDecision,+} = require('./spec-owner-decision.cjs');++const head = 'abcdef1234567890abcdef1234567890abcdef12';+const owner = {login: 'cixzhang'};++describe('spec owner decision', () => {+ it('binds approval commands to the current head', () => {+ expect(parseOwnerCommand(`/approve-spec ${head}`, head)).toBe(true);+ expect(+ parseOwnerCommand(+ '/approve-spec 1111111111111111111111111111111111111111',+ head,+ ),+ ).toBe(null);+ });++ it('accepts an owner review only for the current head', () => {+ const decision = resolveOwnerDecision({+ owners: ['cixzhang', 'imdreamrunner'],+ headSha: head,+ comments: [],+ reviews: [+ {+ user: owner,+ state: 'APPROVED',+ commit_id: head,+ submitted_at: '2026-08-30T10:00:00Z',+ },+ ],+ });+ expect(decision.approved).toBe(true);+ expect(decision.source).toBe('review');+ });++ it('requires approval only when current authority is involved', () => {+ const {requiresOwnerApproval} = require('./spec-owner-decision.cjs');+ expect(+ requiresOwnerApproval([+ {baseContent: null, headContent: 'authority: draft'},+ ]),+ ).toBe(false);+ expect(+ requiresOwnerApproval([+ {baseContent: 'authority: draft', headContent: 'authority: "current"'},+ ]),+ ).toBe(true);+ expect(+ requiresOwnerApproval([+ {baseContent: 'authority: current', headContent: 'authority: archived'},+ ]),+ ).toBe(true);+ expect(requiresOwnerApproval([], {complete: false})).toBe(true);+ });++ it('parses DESIGNOWNERS without comment examples', () => {+ expect(+ parseOwnerFile(`+# Uses @handle format and does not grant merge rights.+@rubyycheung @ernestt+# @not-an-owner+@kentonquatman @cvkxx+`),+ ).toEqual(['rubyycheung', 'ernestt', 'kentonquatman', 'cvkxx']);+ });++ it('routes current design and non-design records to separate owner groups', () => {+ expect(+ requiredApprovalGroups([+ {+ path: 'docs/design/selection.md',+ baseContent: null,+ headContent: 'kind: design\nauthority: current',+ },+ ]),+ ).toEqual({spec: false, design: true});+ expect(+ requiredApprovalGroups([+ {+ path: 'packages/core/src/Button/Button.spec.md',+ baseContent: 'kind: component\nauthority: current',+ headContent: 'kind: component\nauthority: current',+ },+ ]),+ ).toEqual({spec: true, design: false});+ expect(+ requiredApprovalGroups(+ [+ {+ path: 'docs/design/selection.md',+ baseContent: 'kind: design\nauthority: current',+ headContent: 'kind: design\nauthority: current',+ },+ {+ path: 'docs/architecture/themes.md',+ baseContent: 'kind: architecture\nauthority: current',+ headContent: 'kind: architecture\nauthority: current',+ },+ ],+ {touchesDesignAssets: true},+ ),+ ).toEqual({spec: true, design: true});+ expect(+ requiredApprovalGroups([+ {+ path: 'docs/design/not-a-design-record.md',+ baseContent: null,+ headContent: 'kind: architecture\nauthority: current',+ },+ ]),+ ).toEqual({spec: true, design: false});+ expect(+ requiredApprovalGroups([+ {+ path: 'docs/design/themes.md',+ previousPath: 'docs/architecture/themes.md',+ baseContent: 'kind: architecture\nauthority: current',+ headContent: 'kind: design\nauthority: current',+ },+ ]),+ ).toEqual({spec: true, design: true});+ });++ it('owner-gates design assets even without a text record', () => {+ expect(requiredApprovalGroups([], {touchesDesignAssets: true})).toEqual({+ spec: false,+ design: true,+ });+ expect(requiredApprovalGroups([], {complete: false})).toEqual({+ spec: true,+ design: true,+ });+ });++ it('accepts either configured owner', () => {+ const decision = resolveOwnerDecision({+ owners: ['cixzhang', 'imdreamrunner'],+ headSha: head,+ comments: [],+ reviews: [+ {+ user: {login: 'imdreamrunner'},+ state: 'APPROVED',+ commit_id: head,+ submitted_at: '2026-08-30T10:00:00Z',+ },+ ],+ });+ expect(decision.approved).toBe(true);+ expect(decision.owner).toBe('imdreamrunner');+ });++ it('ignores a dismissed owner review', () => {+ const decision = resolveOwnerDecision({+ owners: ['cixzhang', 'imdreamrunner'],+ headSha: head,+ comments: [],+ reviews: [+ {+ user: owner,+ state: 'DISMISSED',+ commit_id: head,+ submitted_at: '2026-08-30T10:01:00Z',+ },+ {+ user: {login: 'imdreamrunner'},+ state: 'APPROVED',+ commit_id: head,+ submitted_at: '2026-08-30T10:00:00Z',+ },+ ],+ });+ expect(decision.approved).toBe(true);+ expect(decision.owner).toBe('imdreamrunner');+ });++ it('keeps the gate blocked when either owner has a current-head objection', () => {+ const decision = resolveOwnerDecision({+ owners: ['cixzhang', 'imdreamrunner'],+ headSha: head,+ comments: [],+ reviews: [+ {+ user: owner,+ state: 'APPROVED',+ commit_id: head,+ submitted_at: '2026-08-30T10:00:00Z',+ },+ {+ user: {login: 'imdreamrunner'},+ state: 'CHANGES_REQUESTED',+ commit_id: head,+ submitted_at: '2026-08-30T10:01:00Z',+ },+ ],+ });+ expect(decision.approved).toBe(false);+ expect(decision.owner).toBe('imdreamrunner');+ });++ it('rejects an approval attached to an older head', () => {+ const decision = resolveOwnerDecision({+ owners: ['cixzhang', 'imdreamrunner'],+ headSha: head,+ comments: [],+ reviews: [+ {+ user: owner,+ state: 'APPROVED',+ commit_id: '1111111111111111111111111111111111111111',+ submitted_at: '2026-08-30T10:00:00Z',+ },+ ],+ });+ expect(decision.approved).toBe(false);+ });++ it('lets the latest owner action revoke an approval', () => {+ const decision = resolveOwnerDecision({+ owners: ['cixzhang', 'imdreamrunner'],+ headSha: head,+ reviews: [+ {+ user: owner,+ state: 'APPROVED',+ commit_id: head,+ submitted_at: '2026-08-30T10:00:00Z',+ },+ ],+ comments: [+ {+ user: owner,+ body: `/revoke-spec ${head}`,+ created_at: '2026-08-30T10:01:00Z',+ },+ ],+ });+ expect(decision.approved).toBe(false);+ expect(decision.source).toBe('command');+ });++ it('ignores commands from other users', () => {+ const decision = resolveOwnerDecision({+ owners: ['cixzhang', 'imdreamrunner'],+ headSha: head,+ reviews: [],+ comments: [+ {+ user: {login: 'someone-else'},+ body: `/approve-spec ${head}`,+ created_at: '2026-08-30T10:00:00Z',+ },+ ],+ });+ expect(decision.approved).toBe(false);+ });+});diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjsnew file mode 100644index 0000000000..42d34353b8--- /dev/null+++ b/.github/scripts/spec-owner-workflow.test.mjs@@ -0,0 +1,86 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import path from 'node:path';+import {describe, expect, it} from 'vitest';++const root = path.resolve(import.meta.dirname, '../..');+const read = relative => fs.readFileSync(path.join(root, relative), 'utf8');++describe('spec-only workflow contract', () => {+ it('keeps classification in one tested helper', () => {+ for (const workflow of [+ '.github/workflows/ci.yml',+ '.github/workflows/lint.yml',+ '.github/workflows/pr-comment.yml',+ '.github/workflows/spec-owner-gate.yml',+ ]) {+ expect(read(workflow), workflow).toContain(+ '.github/scripts/change-scope.cjs',+ );+ }+ });++ it('keeps required CI names green while skipping heavy work', () => {+ const ci = read('.github/workflows/ci.yml');+ expect(ci).toContain(+ 'git show "origin/${{ github.base_ref }}:.github/scripts/change-scope.cjs"',+ );+ expect(ci).toContain('spec_only: ${{ steps.scope.outputs.spec_only }}');+ expect(ci).toContain('node scripts/check-knowledge.mjs');+ expect(ci).toContain("needs.check-scope.outputs.spec_only != 'true'");+ expect(ci).toContain('build:');+ expect(ci).toContain('docsite-test:');+ expect(ci).toContain('test:');++ const lint = read('.github/workflows/lint.yml');+ expect(lint).toContain("steps.scope.outputs.spec_only == 'true'");+ expect(lint).toContain('node scripts/check-knowledge.mjs');+ });++ it('fails closed when file APIs are truncated or scope classification fails', () => {+ const ci = read('.github/workflows/ci.yml');+ expect(ci).toContain('if: ${{ always() && !cancelled() }}');+ expect(ci).toContain("if: needs.check-scope.result != 'success'");++ const reviewSignal = read('.github/workflows/review-signal.yml');+ expect(reviewSignal).toContain('allFiles.length !== pr.changed_files');++ const prComment = read('.github/workflows/pr-comment.yml');+ expect(prComment).toContain('files.length !== pr.changed_files');+ });++ it('requires approval on the current head before squash auto-merge', () => {+ const workflow = read('.github/workflows/spec-owner-gate.yml');+ expect(workflow).toContain(+ 'ref: ${{ github.event.repository.default_branch }}',+ );+ expect(workflow).toContain('expectedCount: pr.changed_files');+ expect(workflow).toContain('scope.touchesKnowledgeRecords');+ expect(workflow).toContain('scope.touchesDesignAssets');+ expect(workflow).toContain('requiredApprovalGroups(records');+ expect(workflow).toContain("'.github/DESIGNOWNERS'");+ expect(workflow).toContain('designApprovers');+ expect(workflow).toContain(+ 'specDecision.approved && designDecision.approved',+ );+ expect(workflow).toContain(+ 'Draft-only knowledge change; owner approval is not required.',+ );+ expect(workflow).toContain("context: 'spec-owner-approval'");+ expect(workflow).toContain('headSha: pr.head.sha');+ expect(workflow).toContain('expectedHeadOid: $oid');+ expect(workflow).toContain('mergeMethod: SQUASH');+ expect(workflow).toContain('disablePullRequestAutoMerge');+ expect(workflow).toContain('spec-auto-merge');+ });++ it('does not run the privileged visual-report path for spec-only PRs', () => {+ const workflow = read('.github/workflows/pr-comment.yml');+ expect(workflow).toContain("needs.resolve.outputs.spec_only != 'true'");+ expect(workflow).toContain("needs.resolve.outputs.spec_only == 'true'");+ expect(workflow).toContain(+ "context: 'visual-acceptance', state: 'success'",+ );+ });+});diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 110456579e..1ba5e3752a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -19,54 +19,80 @@ concurrency:cancel-in-progress: truejobs:- # Detect docsite-only changes — lets docsite PRs skip heavy jobs+ # Detect lightweight changes. Missing merge-base data fails closed.check-scope:- if: github.event_name == 'pull_request'runs-on: ubuntu-slimpermissions:contents: readoutputs:docsite_only: ${{ steps.scope.outputs.docsite_only }}+ spec_only: ${{ steps.scope.outputs.spec_only }}steps:- uses: actions/checkout@v7with:fetch-depth: 50- name: Fetch base branch+ if: github.event_name == 'pull_request'run: git fetch origin ${{ github.base_ref }} --depth=50- name: Determine change scopeid: scoperun: |+ if [ "${{ github.event_name }}" != "pull_request" ]; then+ printf 'docsite_only=false\nspec_only=false\n' >> "$GITHUB_OUTPUT"+ exit 0+ fiMERGE_BASE=$(git merge-base HEAD origin/${{ github.base_ref }} 2>/dev/null || echo "")if [ -z "$MERGE_BASE" ]; then- echo "docsite_only=false" >> $GITHUB_OUTPUT+ printf 'docsite_only=false\nspec_only=false\n' >> "$GITHUB_OUTPUT"exit 0fi- CHANGED=$(git diff --name-only "$MERGE_BASE"...HEAD)- NON_DOCSITE=$(echo "$CHANGED" | grep -v '^apps/docsite/' | head -1)- if [ -z "$NON_DOCSITE" ]; then- echo "docsite_only=true" >> $GITHUB_OUTPUT+ CLASSIFIER="$RUNNER_TEMP/change-scope.cjs"+ if git show "origin/${{ github.base_ref }}:.github/scripts/change-scope.cjs" > "$CLASSIFIER" 2>/dev/null; then+ git diff --name-status "$MERGE_BASE"...HEAD \+ | node "$CLASSIFIER" --github-outputelse- echo "docsite_only=false" >> $GITHUB_OUTPUT+ # Bootstrap fallback: before the trusted classifier exists on main,+ # no PR can receive the spec-only fast path.+ CHANGED=$(git diff --name-only "$MERGE_BASE"...HEAD)+ NON_DOCSITE=$(printf '%s\n' "$CHANGED" | grep -v '^apps/docsite/' | head -1)+ printf 'docsite_only=%s\nspec_only=false\n' \+ "$( [ -z "$NON_DOCSITE" ] && echo true || echo false )" \+ >> "$GITHUB_OUTPUT"fi# Docsite data extraction tests — always runs, fast (~2s)docsite-test:+ needs: [check-scope]+ if: ${{ always() && !cancelled() }}runs-on: 2-core-ubuntu-armpermissions:contents: readsteps:+ - name: Require successful scope classification+ if: needs.check-scope.result != 'success'+ run: |+ echo "Change scope could not be classified; refusing to skip required work."+ exit 1+- uses: actions/checkout@v7+ - name: Validate spec records+ if: needs.check-scope.outputs.spec_only == 'true'+ run: node scripts/check-knowledge.mjs+- uses: ./.github/actions/setup+ if: needs.check-scope.outputs.spec_only != 'true'# docsite `generate` runs `astryx theme build`, which imports the compiled# @astryxdesign/core/theme entry (dist/theme/index.js). Build core first so that# entry exists — otherwise generate fails with "Cannot find module".- name: Build core package+ if: needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/core build- name: Generate and test docsite data+ if: needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/docsite generate && pnpm -F @astryxdesign/docsite test# Lightweight check — does the PR touch any published components?@@ -79,7 +105,7 @@ jobs:# job learned about packages/lab/src.check-components:needs: [check-scope]- if: github.event_name == 'pull_request' && needs.check-scope.outputs.docsite_only != 'true'+ if: github.event_name == 'pull_request' && needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'runs-on: ubuntu-slimpermissions:contents: read@@ -125,44 +151,60 @@ jobs:# Run tests (parallel with build)test:needs: [check-scope]+ if: ${{ always() && !cancelled() }}runs-on: 2-core-ubuntu-armpermissions:contents: readsteps:- - name: Skip for docsite-only changes- if: needs.check-scope.outputs.docsite_only == 'true'- run: echo "Docsite-only PR — skipping full test suite"+ - name: Require successful scope classification+ if: needs.check-scope.result != 'success'+ run: |+ echo "Change scope could not be classified; refusing to skip required work."+ exit 1++ - name: Skip heavy work for lightweight docs+ if: needs.check-scope.outputs.docsite_only == 'true' || needs.check-scope.outputs.spec_only == 'true'+ run: echo "Lightweight documentation PR — skipping full test suite"- uses: actions/checkout@v7- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'- uses: ./.github/actions/setup- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'++ - name: Check knowledge schema history+ if: >-+ github.event_name == 'pull_request' &&+ needs.check-scope.outputs.docsite_only != 'true' &&+ needs.check-scope.outputs.spec_only != 'true'+ run: |+ git fetch origin "${{ github.event.pull_request.base.sha }}" --depth=1+ node scripts/check-knowledge.mjs --base "${{ github.event.pull_request.base.sha }}"- name: Check copyright headers- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: ./scripts/add-copyright.sh --check- name: Check package.json exports are in sync- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: node scripts/sync-exports.js --check- name: Verify the published CLI ./api type surface- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: node .github/scripts/cli-api-types-verify.mjs- name: Check token docs are in sync- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: node scripts/generate-token-docs.mjs --check# Fails when the lab readiness manifest claims a check the source tree# contradicts — the report is derived, never hand-maintained.- name: Check lab readiness manifest is current- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm lab:readiness:check- run: pnpm test- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'# Build storybook + typecheck + analyze components (parallel with test and# build-sandbox). Uploads the storybook preview and analysis artifacts for@@ -172,6 +214,7 @@ jobs:# `build` join below folds their results into the historical check name.build-storybook:needs: [check-scope]+ if: ${{ always() && !cancelled() }}runs-on: 2-core-ubuntu-armpermissions:contents: read@@ -181,12 +224,18 @@ jobs:sandbox_url: ${{ steps.urls.outputs.sandbox_url }}pr_number: ${{ steps.urls.outputs.pr_number }}steps:- - name: Skip for docsite-only changes- if: needs.check-scope.outputs.docsite_only == 'true'- run: echo "Docsite-only PR — skipping full build"+ - name: Require successful scope classification+ if: needs.check-scope.result != 'success'+ run: |+ echo "Change scope could not be classified; refusing to skip required work."+ exit 1++ - name: Skip heavy work for lightweight docs+ if: needs.check-scope.outputs.docsite_only == 'true' || needs.check-scope.outputs.spec_only == 'true'+ run: echo "Lightweight documentation PR — skipping full build"- name: Checkout- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'uses: actions/checkout@v7with:# Depth 50 (same as check-scope) so analyze-pr.js's three-dot diff@@ -195,58 +244,58 @@ jobs:fetch-depth: 50- name: Fetch base branch for PR analysis- if: needs.check-scope.outputs.docsite_only != 'true' && github.event_name == 'pull_request'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && github.event_name == 'pull_request'run: git fetch origin ${{ github.base_ref }} --depth=50- name: Setup Node and pnpm- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'uses: ./.github/actions/setup- name: Build core package- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm build- name: Verify package exports- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: node scripts/verify-exports.mjs- name: Typecheck component docs- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/core typecheck:docs- name: Typecheck lab docs- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/lab typecheck:docs- name: Typecheck charts docs- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/charts typecheck:docs- name: Typecheck template docs- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/cli typecheck:template-docs# Full-package strict checkJs over the CLI (src, bin, scripts, docs, and# the emitted templates). Requires the `pnpm build` above so the template# .tsx sources can resolve the built @astryxdesign/{core,charts,lab} types.- name: Typecheck CLI (strict)- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/cli typecheck:strict- name: Typecheck storybook- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/storybook typecheck- name: Typecheck core (including tests)- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/core typecheck- name: Build Storybook- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'run: pnpm -F @astryxdesign/storybook build- name: Compute PR preview path- if: needs.check-scope.outputs.docsite_only != 'true' && github.event_name == 'pull_request'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && github.event_name == 'pull_request'id: urlsrun: |PR_NUMBER="${{ github.event.pull_request.number }}"@@ -261,7 +310,7 @@ jobs:echo "sandbox_url=https://${REPO_OWNER}.github.io/${REPO_NAME}/pr/${PR_NUMBER}/sandbox/" >> $GITHUB_OUTPUT- name: Upload Storybook artifact- if: needs.check-scope.outputs.docsite_only != 'true' && github.event_name == 'pull_request'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && github.event_name == 'pull_request'uses: actions/upload-artifact@v7with:name: storybook-${{ steps.urls.outputs.short_hash }}@@ -280,7 +329,7 @@ jobs:# Two paths, so the artifact is rooted at their common ancestor# (packages/) — the download below unpacks it there.- name: Upload built themes and core- if: needs.check-scope.outputs.docsite_only != 'true' && github.event_name == 'pull_request'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && github.event_name == 'pull_request'uses: actions/upload-artifact@v7with:name: dists-${{ steps.urls.outputs.short_hash }}@@ -290,7 +339,7 @@ jobs:retention-days: 1- name: Analyze components- if: needs.check-scope.outputs.docsite_only != 'true' && github.event_name == 'pull_request'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && github.event_name == 'pull_request'run: |node .github/scripts/analyze-pr.js \--base origin/${{ github.base_ref }} \@@ -298,7 +347,7 @@ jobs:--output analysis.json- name: Write PR comment metadata- if: needs.check-scope.outputs.docsite_only != 'true' && github.event_name == 'pull_request'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && github.event_name == 'pull_request'run: |# The pr-comment and deploy-preview workflows run on workflow_run# (privileged token), so they can comment on and deploy previews for@@ -320,7 +369,7 @@ jobs:EOF- name: Upload analysis artifact- if: needs.check-scope.outputs.docsite_only != 'true' && github.event_name == 'pull_request'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true' && github.event_name == 'pull_request'uses: actions/upload-artifact@v7with:name: pr-analysis@@ -335,7 +384,7 @@ jobs:# preview builds entirely.build-sandbox:needs: [check-scope]- if: github.event_name == 'pull_request' && needs.check-scope.outputs.docsite_only != 'true'+ if: github.event_name == 'pull_request' && needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'runs-on: 2-core-ubuntu-armpermissions:contents: read@@ -525,7 +574,7 @@ jobs:# that can break it. Gated like `test` instead: everything but docsite-only.theme-layers:needs: [check-scope]- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'runs-on: 2-core-ubuntu-armpermissions:contents: read@@ -550,7 +599,7 @@ jobs:# which custom properties paint the portaled surfaces.fixture-contrast:needs: [check-scope]- if: needs.check-scope.outputs.docsite_only != 'true'+ if: needs.check-scope.outputs.docsite_only != 'true' && needs.check-scope.outputs.spec_only != 'true'runs-on: 2-core-ubuntu-armpermissions:contents: readdiff --git a/.github/workflows/lint.yml b/.github/workflows/lint.ymlindex 22d7f16654..5b83ec8652 100644--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@ -19,39 +19,49 @@ jobs:steps:- uses: actions/checkout@v7- - name: Check for docsite-only changes+ - name: Classify changed filesif: github.event_name == 'pull_request'id: scoperun: |git fetch origin ${{ github.base_ref }} --depth=50MERGE_BASE=$(git merge-base HEAD origin/${{ github.base_ref }} 2>/dev/null || echo "")if [ -z "$MERGE_BASE" ]; then- echo "docsite_only=false" >> $GITHUB_OUTPUT+ printf 'docsite_only=false\nspec_only=false\n' >> "$GITHUB_OUTPUT"exit 0fi- CHANGED=$(git diff --name-only "$MERGE_BASE"...HEAD)- NON_DOCSITE=$(echo "$CHANGED" | grep -v '^apps/docsite/' | head -1)- if [ -z "$NON_DOCSITE" ]; then- echo "docsite_only=true" >> $GITHUB_OUTPUT+ CLASSIFIER="$RUNNER_TEMP/change-scope.cjs"+ if git show "origin/${{ github.base_ref }}:.github/scripts/change-scope.cjs" > "$CLASSIFIER" 2>/dev/null; then+ git diff --name-status "$MERGE_BASE"...HEAD \+ | node "$CLASSIFIER" --github-outputelse- echo "docsite_only=false" >> $GITHUB_OUTPUT+ # Bootstrap fallback: before the trusted classifier exists on main,+ # no PR can receive the spec-only fast path.+ CHANGED=$(git diff --name-only "$MERGE_BASE"...HEAD)+ NON_DOCSITE=$(printf '%s\n' "$CHANGED" | grep -v '^apps/docsite/' | head -1)+ printf 'docsite_only=%s\nspec_only=false\n' \+ "$( [ -z "$NON_DOCSITE" ] && echo true || echo false )" \+ >> "$GITHUB_OUTPUT"fi- - name: Skip for docsite-only changes- if: steps.scope.outputs.docsite_only == 'true'- run: echo "Docsite-only PR — skipping lint"+ - name: Validate spec records+ if: steps.scope.outputs.spec_only == 'true'+ run: node scripts/check-knowledge.mjs++ - name: Skip full lint for lightweight docs+ if: steps.scope.outputs.docsite_only == 'true' || steps.scope.outputs.spec_only == 'true'+ run: echo "Lightweight documentation PR — skipping full lint"- uses: ./.github/actions/setup- if: steps.scope.outputs.docsite_only != 'true'+ if: steps.scope.outputs.docsite_only != 'true' && steps.scope.outputs.spec_only != 'true'- name: Clear ESLint cache- if: steps.scope.outputs.docsite_only != 'true'+ if: steps.scope.outputs.docsite_only != 'true' && steps.scope.outputs.spec_only != 'true'run: rm -rf .eslintcache node_modules/.cache- name: Check repository guardrails- if: steps.scope.outputs.docsite_only != 'true'+ if: steps.scope.outputs.docsite_only != 'true' && steps.scope.outputs.spec_only != 'true'run: pnpm check:repo- name: Run ESLint- if: steps.scope.outputs.docsite_only != 'true'+ if: steps.scope.outputs.docsite_only != 'true' && steps.scope.outputs.spec_only != 'true'run: pnpm lintdiff --git a/.github/workflows/pr-comment.yml b/.github/workflows/pr-comment.ymlindex f50dd2b2d5..28969cfa00 100644--- a/.github/workflows/pr-comment.yml+++ b/.github/workflows/pr-comment.yml@@ -39,12 +39,19 @@ jobs:if: github.event.workflow_run.event == 'pull_request'runs-on: ubuntu-slimpermissions:+ contents: readpull-requests: readoutputs:valid: ${{ steps.identity.outputs.valid }}pr_number: ${{ steps.identity.outputs.pr_number }}head_sha: ${{ steps.identity.outputs.head_sha }}+ spec_only: ${{ steps.identity.outputs.spec_only }}steps:+ - name: Checkout trusted classifier+ uses: actions/checkout@v7+ with:+ ref: main+- name: Resolve trusted PR identityid: identityuses: actions/github-script@v9@@ -75,15 +82,28 @@ jobs:core.setFailed(`Run head ${run.head_sha} is stale; PR head is ${pr.head.sha}`);return;}+ const path = require('node:path');+ const {classifyChanges} = require(path.join(+ process.env.GITHUB_WORKSPACE,+ '.github/scripts/change-scope.cjs',+ ));+ const files = await github.paginate(github.rest.pulls.listFiles, {+ owner, repo, pull_number: pr.number, per_page: 100,+ });core.setOutput('valid', 'true');core.setOutput('pr_number', String(pr.number));core.setOutput('head_sha', pr.head.sha);+ core.setOutput(+ 'spec_only',+ String(classifyChanges(files, {expectedCount: pr.changed_files}).specOnly),+ );invalidate:needs: resolveif: >-(github.event.action == 'requested' || github.event.action == 'in_progress') &&- needs.resolve.outputs.valid == 'true'+ needs.resolve.outputs.valid == 'true' &&+ needs.resolve.outputs.spec_only != 'true'runs-on: ubuntu-slimpermissions:pull-requests: write@@ -114,12 +134,37 @@ jobs:if (error.status !== 404) throw error;}+ spec-only-visual:+ needs: resolve+ if: >-+ github.event.action == 'completed' &&+ needs.resolve.outputs.valid == 'true' &&+ needs.resolve.outputs.spec_only == 'true'+ runs-on: ubuntu-slim+ permissions:+ statuses: write+ steps:+ - name: Mark spec-only visual scope complete+ uses: actions/github-script@v9+ env:+ HEAD_SHA: ${{ needs.resolve.outputs.head_sha }}+ with:+ retries: 3+ script: |+ const {owner, repo} = context.repo;+ await github.rest.repos.createCommitStatus({+ owner, repo, sha: process.env.HEAD_SHA,+ context: 'visual-acceptance', state: 'success',+ description: 'Spec-only change — no visual scope.',+ });+comment:needs: resolve# Only for completed CI runs whose PR identity was resolved above.if: >-github.event.action == 'completed' &&- needs.resolve.outputs.valid == 'true'+ needs.resolve.outputs.valid == 'true' &&+ needs.resolve.outputs.spec_only != 'true'runs-on: 2-core-ubuntu-armpermissions:pull-requests: write@@ -199,6 +244,12 @@ jobs:const files = await github.paginate(github.rest.pulls.listFiles, {owner, repo, pull_number: pullNumber, per_page: 100,});+ if (files.length !== pr.changed_files) {+ core.setFailed(+ `GitHub returned ${files.length} of ${pr.changed_files} changed files; refusing visual-scope classification.`,+ );+ return;+ }const manifestPaths = new Set();for (const {filename} of files) {const theme = filename.match(/^packages\/themes\/([^/]+)\//);diff --git a/.github/workflows/review-signal.yml b/.github/workflows/review-signal.ymlindex 3dac9628c5..3950a3fa7a 100644--- a/.github/workflows/review-signal.yml+++ b/.github/workflows/review-signal.yml@@ -58,7 +58,7 @@ name: Review signalon:pull_request_target:- branches: ["main"]+ branches: ['main']types: [opened, synchronize, reopened, ready_for_review, converted_to_draft]pull_request_review:types: [submitted]@@ -70,7 +70,7 @@ on:workflow_dispatch:inputs:pr:- description: "PR number to re-flag (blank = all open PRs)"+ description: 'PR number to re-flag (blank = all open PRs)'required: falsetype: string@@ -83,9 +83,9 @@ concurrency:cancel-in-progress: trueenv:- CODE_LABEL: "needs:code-review"- DESIGN_LABEL: "needs:design-review"- COMMUNITY_LABEL: "community"+ CODE_LABEL: 'needs:code-review'+ DESIGN_LABEL: 'needs:design-review'+ COMMUNITY_LABEL: 'community'jobs:# ---------------------------------------------------------------------------@@ -217,6 +217,11 @@ jobs:const allFiles = await github.paginate(github.rest.pulls.listFiles, {owner, repo, pull_number: pr.number, per_page: 100,});+ if (allFiles.length !== pr.changed_files) {+ throw new Error(+ `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)diff --git a/.github/workflows/spec-owner-gate.yml b/.github/workflows/spec-owner-gate.ymlnew file mode 100644index 0000000000..c8a8cc69b1--- /dev/null+++ b/.github/workflows/spec-owner-gate.yml@@ -0,0 +1,317 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.++# Current knowledge records are consequential to future reviewers. Creating,+# changing, or archiving one waits for owner approval. Current design records+# and normative design assets also accept DESIGNOWNERS; mixed PRs keep the+# non-design spec-owner 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 on+# the exact current head.+name: Spec owner gate++on:+ pull_request_target:+ branches: [main]+ types:+ [+ opened,+ synchronize,+ reopened,+ ready_for_review,+ converted_to_draft,+ auto_merge_enabled,+ ]+ pull_request_review:+ types: [submitted, dismissed]+ issue_comment:+ types: [created]+ workflow_dispatch:+ inputs:+ pr:+ description: Pull request number to reconcile+ required: true+ type: string++permissions: {}++concurrency:+ group: spec-owner-${{ github.event.pull_request.number || github.event.issue.number || github.event.inputs.pr }}+ cancel-in-progress: true++env:+ SPEC_OWNERS: cixzhang,imdreamrunner+ REVIEW_LABEL: needs:spec-owner-review+ AUTO_MERGE_LABEL: spec-auto-merge++jobs:+ reconcile:+ if: >-+ github.event_name != 'issue_comment' ||+ github.event.issue.pull_request != null+ runs-on: ubuntu-slim+ permissions:+ contents: read+ pull-requests: write+ issues: write+ statuses: write+ steps:+ # Every privileged event checks out the trusted default branch. Never+ # execute the PR merge ref or PR-controlled helpers with write permissions.+ - uses: actions/checkout@v7+ with:+ ref: ${{ github.event.repository.default_branch }}++ - name: Reconcile owner gate+ uses: actions/github-script@v9+ with:+ retries: 3+ script: |+ const fs = require('node:fs');+ const path = require('node:path');+ const {classifyChanges} = require(path.join(+ process.env.GITHUB_WORKSPACE,+ '.github/scripts/change-scope.cjs',+ ));+ const {+ parseOwnerFile,+ requiredApprovalGroups,+ resolveOwnerDecision,+ } = require(path.join(+ process.env.GITHUB_WORKSPACE,+ '.github/scripts/spec-owner-decision.cjs',+ ));+ const {owner, repo} = context.repo;+ const pull_number = Number(+ context.payload.pull_request?.number ??+ context.payload.issue?.number ??+ context.payload.inputs?.pr,+ );+ if (!pull_number) throw new Error('Could not resolve a pull request number.');++ const {data: pr} = await github.rest.pulls.get({owner, repo, pull_number});+ const files = await github.paginate(github.rest.pulls.listFiles, {+ owner, repo, pull_number, per_page: 100,+ });+ const scope = classifyChanges(files, {expectedCount: pr.changed_files});+ const currentLabels = new Set(pr.labels.map(label => label.name));++ async function setStatus(state, description) {+ await github.rest.repos.createCommitStatus({+ owner, repo, sha: pr.head.sha,+ context: 'spec-owner-approval', state,+ description: description.slice(0, 140),+ });+ }+ async function removeLabel(name) {+ try {+ await github.rest.issues.removeLabel({+ owner, repo, issue_number: pull_number, name,+ });+ } catch (error) {+ if (error.status !== 404) throw error;+ }+ }+ async function ensureLabel(name, color, description) {+ try {+ await github.rest.issues.getLabel({owner, repo, name});+ } catch (error) {+ if (error.status !== 404) throw error;+ await github.rest.issues.createLabel({+ owner, repo, name, color, description,+ });+ }+ if (!currentLabels.has(name)) {+ await github.rest.issues.addLabels({+ owner, repo, issue_number: pull_number, labels: [name],+ });+ }+ }+ async function disableOwnedAutoMerge() {+ if (!currentLabels.has(process.env.AUTO_MERGE_LABEL)) return;+ if (pr.auto_merge) {+ await github.graphql(+ `mutation($id: ID!) {+ disablePullRequestAutoMerge(input: {pullRequestId: $id}) {+ pullRequest { number }+ }+ }`,+ {id: pr.node_id},+ );+ }+ await removeLabel(process.env.AUTO_MERGE_LABEL);+ }++ if (!scope.touchesKnowledgeRecords) {+ await disableOwnedAutoMerge();+ await removeLabel(process.env.REVIEW_LABEL);+ await setStatus('success', 'No knowledge records changed.');+ return;+ }++ if (scope.specOnly) {+ // Spec records cannot affect runtime pixels. This trusted path+ // list is stricter than the visual classifier and is tested.+ await github.rest.repos.createCommitStatus({+ owner, repo, sha: pr.head.sha,+ context: 'visual-acceptance', state: 'success',+ description: 'Spec-only change — no visual scope.',+ });+ }++ async function readText(fullName, ref, filePath) {+ const [repoOwner, repoName] = fullName.split('/');+ try {+ const {data} = await github.rest.repos.getContent({+ owner: repoOwner, repo: repoName, path: filePath, ref,+ });+ if (Array.isArray(data) || !data.content) {+ throw new Error(`Knowledge record ${filePath} could not be read as text.`);+ }+ return Buffer.from(data.content, 'base64').toString('utf8');+ } catch (error) {+ if (error.status === 404) return null;+ throw error;+ }+ }++ const knowledgeChanges = files.filter(file =>+ scope.complete && (+ classifyChanges([{filename: file.filename}]).touchesKnowledgeRecords ||+ (file.previous_filename &&+ classifyChanges([{filename: file.previous_filename}]).touchesKnowledgeRecords)+ ),+ );+ const records = await Promise.all(knowledgeChanges.map(async file => {+ const previousPath = file.previous_filename || file.filename;+ const baseIsTextRecord = previousPath.endsWith('.md');+ const headIsTextRecord = file.filename.endsWith('.md');+ return {+ path: file.filename,+ previousPath,+ baseContent: !baseIsTextRecord || file.status === 'added'+ ? null+ : await readText(+ pr.base.repo.full_name,+ pr.base.sha,+ previousPath,+ ),+ headContent: !headIsTextRecord || file.status === 'removed'+ ? null+ : await readText(pr.head.repo.full_name, pr.head.sha, file.filename),+ };+ }));+ const requiredGroups = requiredApprovalGroups(records, {+ complete: scope.complete,+ touchesDesignAssets: scope.touchesDesignAssets,+ });+ const ownerApprovalRequired = requiredGroups.spec || requiredGroups.design;+ const specOwners = process.env.SPEC_OWNERS.split(',');+ const designOwners = parseOwnerFile(+ fs.readFileSync(+ path.join(process.env.GITHUB_WORKSPACE, '.github/DESIGNOWNERS'),+ 'utf8',+ ),+ );+ if (requiredGroups.design && designOwners.length === 0) {+ throw new Error('No DESIGNOWNERS are configured.');+ }+ const designApprovers = [...new Set([...specOwners, ...designOwners])];++ const [reviews, comments] = await Promise.all([+ github.paginate(github.rest.pulls.listReviews, {+ owner, repo, pull_number, per_page: 100,+ }),+ github.paginate(github.rest.issues.listComments, {+ owner, repo, issue_number: pull_number, per_page: 100,+ }),+ ]);+ const specDecision = requiredGroups.spec+ ? resolveOwnerDecision({+ reviews, comments, owners: specOwners, headSha: pr.head.sha,+ })+ : {approved: true, owner: null};+ const designDecision = requiredGroups.design+ ? resolveOwnerDecision({+ reviews, comments, owners: designApprovers, headSha: pr.head.sha,+ })+ : {approved: true, owner: null};+ const approved = specDecision.approved && designDecision.approved;+ const approvingOwners = [specDecision.owner, designDecision.owner]+ .filter(Boolean)+ .filter((ownerName, index, owners) => owners.indexOf(ownerName) === index);+ const requiredOwnerDescription = [+ requiredGroups.spec ? `a spec owner (${specOwners.join(',')})` : null,+ requiredGroups.design+ ? `a design approver (${designApprovers.join(',')})`+ : null,+ ].filter(Boolean).join(' and ');++ if (ownerApprovalRequired && !approved) {+ // Revoke our own auto-merge before any fallible label/status work.+ await disableOwnedAutoMerge();+ await ensureLabel(+ process.env.REVIEW_LABEL,+ 'd4c5f9',+ 'Current knowledge records await owner approval',+ );+ await setStatus(+ 'pending',+ `Waiting for ${requiredOwnerDescription} on ${pr.head.sha.slice(0, 7)}.`,+ );+ return;+ }++ if (pr.draft) {+ await disableOwnedAutoMerge();+ await removeLabel(process.env.REVIEW_LABEL);+ await setStatus('success', 'Draft PR; owner gate is not blocking.');+ return;+ }++ if (!scope.specOnly) {+ await disableOwnedAutoMerge();+ await removeLabel(process.env.REVIEW_LABEL);+ await setStatus(+ 'success',+ ownerApprovalRequired+ ? `Approved by ${approvingOwners.map(name => `@${name}`).join(' and ')} for ${pr.head.sha.slice(0, 7)}.`+ : 'No current knowledge record changed.',+ );+ return;+ }++ if (!pr.auto_merge) {+ // Record ownership before enabling auto-merge. If enablement+ // fails, the harmless label lets a later run clean up. If a user+ // already enabled auto-merge, do not claim or later disable it.+ await ensureLabel(+ process.env.AUTO_MERGE_LABEL,+ 'bfdadc',+ 'Auto-merge was enabled by the spec owner gate',+ );+ try {+ await github.graphql(+ `mutation($id: ID!, $oid: GitObjectID!) {+ enablePullRequestAutoMerge(input: {+ pullRequestId: $id,+ mergeMethod: SQUASH,+ expectedHeadOid: $oid+ }) {+ pullRequest { number }+ }+ }`,+ {id: pr.node_id, oid: pr.head.sha},+ );+ core.info(`Enabled squash auto-merge for spec-only PR #${pull_number}.`);+ } catch (error) {+ core.warning(`Could not enable auto-merge: ${error.message}`);+ return;+ }+ }+ await removeLabel(process.env.REVIEW_LABEL);+ await setStatus(+ 'success',+ ownerApprovalRequired+ ? `Approved by ${approvingOwners.map(name => `@${name}`).join(' and ')} for ${pr.head.sha.slice(0, 7)}.`+ : 'Draft-only knowledge change; owner approval is not required.',+ );diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000000..9024fdb8d0--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,48 @@+# Astryx repository guidance++Astryx is a public design-system repository. Never commit internal links,+identifiers, service names, private operational instructions, or other+Meta-only context.++## Start here++- Product builders: use `astryx docs`, component `{Name}.doc.mjs` files, and+ `packages/cli/assets/docs/`.+- Contributors: read `CONTRIBUTING.md` and the relevant guidance linked from+ `docs/README.md`.+- Component work: read the component's `{Name}.spec.md` when one exists, then+ its consumer docs, tests, and implementation.+- Cross-component work: read the relevant contract under `docs/families/`,+ applicable design spec under `docs/design/`, and current architecture under+ `docs/architecture/`.+- Consequential shared-system changes: use a record under `docs/specs/`.++## Authority++Knowledge records declare `authority`:++- `draft`: not authoritative; may still need evidence or owner review;+- `current`: explicitly approved and authoritative;+- `archived`: context only, with a reason such as `superseded`, `withdrawn`,+ or `historical` and a replacement link when one exists.++Only `current` records govern implementation and review. Never infer approval+from merged code, silence, an old review, or an existing wiki page.++## Judgment boundary++Resolve checkable behavior from code, tests, and browser evidence. Ask a human+only when a stable public API, theme contract, ownership boundary, compatibility+policy, or genuinely subjective visual direction remains undecided. Ask one+question at a time.++Before reviewing or implementing a proposed outcome, check current `main` and+newer overlapping pull requests. Do not create new policy for work that is+already complete or superseded.++## Validation++Run `pnpm check:knowledge` after editing knowledge records or templates. A+material template-shape change requires a schema-version bump and migration of+active records; changing template guidance alone does not rewrite accepted+history.diff --git a/docs/README.md b/docs/README.mdnew file mode 100644index 0000000000..eabdb0cd05--- /dev/null+++ b/docs/README.md@@ -0,0 +1,62 @@+# Astryx knowledge map++This directory holds maintainer knowledge that must be reviewable with the code+it governs. Consumer documentation remains in component `.doc.mjs` files and+`packages/cli/assets/docs/`.++## Placement++- `architecture/`: the shipped system, its boundaries, and invariants.+- `design/`: human-owned visual and interaction specifications.+- `families/`: contracts shared by sibling components.+- `specs/`: consequential proposed or shipped system changes and their decisions.+- `templates/knowledge/`: authoring templates. Templates never live among records.+- `schemas/knowledge/`: versioned structural requirements for templates and records.++Component-local contracts and audits live beside the component as+`<Name>.spec.md` and `<Name>.audit.json`.++## Authority++Every knowledge record declares `authority: draft | current | archived`.++- `draft` documents are not policy; unresolved evidence and owner decisions are+ recorded as blockers inside the document.+- Initial promotion to `current` requires explicit owner approval recorded in+ the document metadata. `cixzhang` and `imdreamrunner` may approve every record+ kind; current design records and normative design assets also accept current+ `.github/DESIGNOWNERS`.+- Pull requests that create, change, or archive a `current` record wait on the+ `spec-owner-approval` status for their exact current head. Draft-only records+ pass that status after validation without an owner review.+- `cixzhang` or `imdreamrunner` can approve another author's current-record PR+ through GitHub review. When an approver is also the PR author, they comment+ `/approve-spec <full-head-sha>`. Any new commit invalidates that approval.+- Only `current` documents guide implementation and review.+- Current records link only other current records. Draft relationships are listed+ on the candidate record; promotion updates affected backlinks under owner+ review.+- `archived` documents declare `archive_reason` (`superseded`, `withdrawn`, or+ `historical`) and link `superseded_by` when a replacement exists.++## Templates and schemas++Templates create documents; schemas keep existing documents structurally+aligned. They are intentionally separate:++- `template_version` records the authoring form used to create a document.+- `schema_version` records the contract the document must satisfy.+- Editorial template changes may increment only `template_version`.+- Adding or changing required metadata or sections creates a new+ `schema_version`; published schema files are immutable.+- Every active record (`draft` or `current`) must use the latest schema. A+ schema change therefore includes an active-record migration. Archived records+ may retain an older schema that remains checked in.++Run `pnpm check:knowledge` to validate templates and records.++## Visibility++This repository and its wiki are public. Internal operations, credentials,+services, routing, schedules, and private recovery procedures stay in an+access-controlled private home and must not be named or linked here.diff --git a/docs/architecture/README.md b/docs/architecture/README.mdnew file mode 100644index 0000000000..30e21b242f--- /dev/null+++ b/docs/architecture/README.md@@ -0,0 +1,8 @@+# Architecture records++Architecture documents describe the shipped system in present tense. They are+not proposals and must not describe an unshipped future as current.++New records start as `draft`. They become `current` only after explicit owner+approval. Archived records remain for context and state why they no longer+govern. Use `docs/templates/knowledge/architecture.md`.diff --git a/docs/design/README.md b/docs/design/README.mdnew file mode 100644index 0000000000..3c29e69c22--- /dev/null+++ b/docs/design/README.md@@ -0,0 +1,23 @@+# Design specifications++Design specs record human-owned visual and interaction intent: hierarchy,+anatomy, state representation, allowed variation, and representative examples.+They may describe one component or a cross-component pattern.++Design specs do not own implementation mechanics, public prop syntax, current+audit results, or consumer usage guidance. Component and family contracts link+to stable design requirement IDs instead of copying their rationale.++Public-safe normative screenshots, diagrams, and visual state references live+under `docs/design/assets/<design-id>/`. Each referenced asset records alt text,+state, theme/mode, viewport when relevant, and what decision it demonstrates.+Generated audit screenshots remain audit evidence rather than design authority.+Private design sources stay private and are never named or linked here.++New design specs start as `draft`. Initial promotion to `current`, later changes,+and normative asset updates require exact-head approval from `cixzhang`,+`imdreamrunner`, or any current member of `.github/DESIGNOWNERS`. A mixed PR still+needs `cixzhang` or `imdreamrunner` for non-design current records. The design+record names its content owners separately from this repository gate.++Use `docs/templates/knowledge/design-spec.md`.diff --git a/docs/families/README.md b/docs/families/README.mdnew file mode 100644index 0000000000..a11c74fd8b--- /dev/null+++ b/docs/families/README.md@@ -0,0 +1,9 @@+# Component family contracts++Family contracts own behavior shared by sibling components, such as input+sizing, end lanes, overlay dismissal, or status presentation. A component spec+links to its family instead of copying the shared rule.++New records start as `draft`. They become `current` only after explicit owner+approval. Archived records remain for context and state why they no longer+govern. Use `docs/templates/knowledge/family-contract.md`.diff --git a/docs/schemas/knowledge/v1.json b/docs/schemas/knowledge/v1.jsonnew file mode 100644index 0000000000..2c23dfc821--- /dev/null+++ b/docs/schemas/knowledge/v1.json@@ -0,0 +1,205 @@+{+ "schemaVersion": 1,+ "activeAuthorities": ["draft", "current"],+ "authorities": ["draft", "current", "archived"],+ "archiveReasons": ["superseded", "withdrawn", "historical"],+ "kinds": {+ "component": {+ "template": "docs/templates/knowledge/component-spec.md",+ "requiredFrontmatter": [+ "schema_version",+ "template_version",+ "kind",+ "id",+ "authority",+ "archive_reason",+ "superseded_by",+ "approved_by",+ "approved_at",+ "owners",+ "review_triggers",+ "verified_by",+ "families",+ "design_specs",+ "architecture",+ "contributing",+ "system_specs"+ ],+ "requiredSections": [+ "Intent",+ "Compatibility and migration",+ "Ownership boundary",+ "Public concepts",+ "Behavioral and layout contract",+ "Accessibility contract",+ "Design relationships",+ "Family and system relationships",+ "Verification map",+ "Decision log",+ "Open questions",+ "Content boundary"+ ],+ "currentNonEmptyFields": ["owners", "review_triggers", "verified_by"]+ },+ "family": {+ "template": "docs/templates/knowledge/family-contract.md",+ "requiredFrontmatter": [+ "schema_version",+ "template_version",+ "kind",+ "id",+ "authority",+ "archive_reason",+ "superseded_by",+ "approved_by",+ "approved_at",+ "owners",+ "review_triggers",+ "verified_by",+ "members",+ "architecture",+ "contributing",+ "deciding_specs"+ ],+ "requiredSections": [+ "Intent",+ "Membership rule",+ "Shared owner",+ "Canonical concepts",+ "Cross-component invariants",+ "Allowed component variation",+ "Representative matrix",+ "Adoption and exceptions",+ "Verification map",+ "Decision links",+ "Open questions",+ "Content boundary"+ ],+ "currentNonEmptyFields": [+ "owners",+ "members",+ "review_triggers",+ "verified_by"+ ]+ },+ "architecture": {+ "template": "docs/templates/knowledge/architecture.md",+ "requiredFrontmatter": [+ "schema_version",+ "template_version",+ "kind",+ "id",+ "authority",+ "archive_reason",+ "superseded_by",+ "approved_by",+ "approved_at",+ "owners",+ "applies_to",+ "verified_by",+ "deciding_specs"+ ],+ "requiredSections": [+ "Purpose",+ "System model",+ "Boundaries and invariants",+ "Change coupling",+ "Owning code",+ "Deciding specs",+ "Verification"+ ],+ "currentNonEmptyFields": ["owners", "applies_to", "verified_by"]+ },+ "system-spec": {+ "template": "docs/templates/knowledge/system-spec.md",+ "requiredFrontmatter": [+ "schema_version",+ "template_version",+ "kind",+ "id",+ "authority",+ "archive_reason",+ "superseded_by",+ "approved_by",+ "approved_at",+ "phase",+ "owners",+ "affects_architecture",+ "affects_families",+ "affects_contributing",+ "affects_consumer_docs"+ ],+ "requiredSections": [+ "Intent",+ "Non-goals",+ "Requirements",+ "Current-state impact",+ "Verification",+ "Decision log",+ "Open questions"+ ],+ "currentNonEmptyFields": ["owners"]+ },+ "implementation-plan": {+ "template": "docs/templates/knowledge/implementation-plan.md",+ "requiredFrontmatter": [+ "schema_version",+ "template_version",+ "kind",+ "id",+ "authority",+ "archive_reason",+ "superseded_by",+ "approved_by",+ "approved_at",+ "spec",+ "owners"+ ],+ "requiredSections": ["Phases", "Verification", "Status"],+ "currentNonEmptyFields": ["owners"]+ },+ "design": {+ "template": "docs/templates/knowledge/design-spec.md",+ "requiredFrontmatter": [+ "schema_version",+ "template_version",+ "kind",+ "id",+ "authority",+ "archive_reason",+ "superseded_by",+ "approved_by",+ "approved_at",+ "owners",+ "review_triggers",+ "verified_by",+ "architecture",+ "components",+ "families",+ "deciding_specs"+ ],+ "requiredSections": [+ "User intent",+ "Design principles",+ "Anatomy and hierarchy",+ "State representation",+ "Responsive and input behavior",+ "Accessibility intent",+ "Representative examples",+ "Visual references",+ "Component contract links",+ "Decision log",+ "Open questions",+ "Content boundary"+ ],+ "currentNonEmptyFields": [+ "owners",+ "review_triggers",+ "verified_by",+ "architecture"+ ],+ "referenceFields": ["architecture"]+ }+ },+ "approvalOwners": ["cixzhang", "imdreamrunner"]+}diff --git a/docs/specs/README.md b/docs/specs/README.mdnew file mode 100644index 0000000000..e920a93fa9--- /dev/null+++ b/docs/specs/README.md@@ -0,0 +1,19 @@+# System specs++This directory contains records for consequential shared-system changes. Each+spec lives under `docs/specs/<id>-<slug>/spec.md`; an optional sibling `plan.md`+is used only for multi-step implementation.++Templates live separately under `docs/templates/knowledge/`. Existing records+are validated against `docs/schemas/knowledge/`; changing a template does not+silently change accepted history.++A system spec is appropriate when work changes more than one component, a+shared primitive, architecture, public API policy, theming, accessibility+policy, distribution, or lifecycle. Focused fixes that restore an existing+contract do not need a new spec.++Only records with `authority: current` are authoritative. Draft records may+carry unresolved evidence or owner decisions; they do not govern review.+Archived records state why they no longer govern and link a replacement when+one exists. Initial promotion to `current` requires explicit owner approval.diff --git a/docs/templates/knowledge/architecture.md b/docs/templates/knowledge/architecture.mdnew file mode 100644index 0000000000..447fa095eb--- /dev/null+++ b/docs/templates/knowledge/architecture.md@@ -0,0 +1,43 @@+---+schema_version: 1+template_version: 1+kind: architecture+id: architecture:<surface>+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [<owner>]+applies_to: [<path-prefix>]+verified_by: [<test-or-check>]+deciding_specs: [spec:AST-000/DEC-0]+---++# <Surface> architecture++## Purpose++## System model++## Boundaries and invariants++- **INV1 — `<invariant>`.** `<What MUST remain true in the shipped system.>`++## Change coupling++<!-- State how code changes trigger review of this architecture and which checks prove it remains current. -->++## Owning code++- `<path or public module>` — `<responsibility>`++## Deciding specs++- `spec:AST-000/DEC-0` — `<decision>`++## Verification++| Invariant | Evidence | Failure signal |+| --------- | ------------------------------- | ---------------------------------------- |+| INV1 | `<test or observable evidence>` | `<what fails when the invariant breaks>` |diff --git a/docs/templates/knowledge/component-spec.md b/docs/templates/knowledge/component-spec.mdnew file mode 100644index 0000000000..16883c380b--- /dev/null+++ b/docs/templates/knowledge/component-spec.md@@ -0,0 +1,130 @@+---+schema_version: 1+template_version: 1+kind: component+id: component:<Name>+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [<owner>]+review_triggers: [public-api, behavior, layout, theming, accessibility]+verified_by: [<test-or-check>]+families: [family:<family-name>]+design_specs: [design:<surface>]+architecture: [architecture:<surface>]+contributing: [contributing:<surface>]+system_specs: [spec:AST-000/DEC-0]+---++# <Name> component contract++## Intent++<!-- Why this component exists and the system-level job it owns. Consumer usage belongs in <Name>.doc.mjs. -->++## Compatibility and migration++- Released default preserved: `<yes, no, or not yet released>`+- Compatibility class: `<state the compatibility effect>`+- Controlled/uncontrolled behavior: `<unchanged or stated transition>`+- Migration decision: `<component DEC or system spec link>`++Consumer migration instructions belong in consumer docs and release notes.++## Ownership boundary++**Owns**++- `<responsibility>`++**Does not own / non-goals**++- `<responsibility>` — owned by `family:<family>` / `component:<Other>` / product callsite.++## Public concepts++<!-- Concepts, not a prop table. Consumer syntax/defaults remain in <Name>.doc.mjs. -->++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ----------- | ----------------------- | ----------- | ----------------------------------------- | ----------- | ------------------ | -------------------------- | ------------------------------- |+| `<concept>` | `<values>` | `<meaning>` | `<where emitted>` | `<default>` | `component:<Name>` | `<stable or experimental>` | `<reject, ignore, or fallback>` |++## Behavioral and layout contract++Draft requirements identify their basis so observed code is not mistaken for an+intentional decision. A `current` contract contains no unresolved rows.++| ID | Candidate invariant | Basis | Draft review state |+| --- | ------------------------ | ----------------------------------------------------------------------------- | -------------------------------------- |+| FR1 | `<The component MUST …>` | `<existing DEC, documented promise, standard, current behavior, or proposal>` | `<settled, verify, or human decision>` |++### Allowed variation++- **AV1 — `<dimension>`.** `<What may vary without becoming a regression.>`++### Representative states++| State | Required invariant | Allowed variation |+| --------- | ------------------ | ----------------- |+| `<state>` | `<invariant>` | `<variation>` |++### Transformation and precedence order++- **ORD1 — `<pipeline>`.** `<The final invariant and the required order, such as snap → round → clamp.>`++### Performance and resources++- **PR1 — `<constraint>`.** `<Measurement, render, listener, observer, or initialization behavior that MUST remain true.>`++Current measurements belong in the audit record; this subsection owns only+durable constraints and their verification target.++## Accessibility contract++- **AR1 — `<obligation>`.** `<The component MUST …>`++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | ---------------------- | -------------------------------------------- | --------------------------- | ------------------- |+| `<role/state>` | `design:<surface>/DR1` | `<prescribed, human-selected, or unsettled>` | `<prominent or supporting>` | `<FR/AR reference>` |++The component implements design requirements without copying their rationale.+An `unsettled` representation remains a human decision; principles do not let an+agent invent the answer.++## Family and system relationships++Frontmatter lists only `current` family, design, architecture, and system+relationships. Candidate records list proposed members on the candidate itself;+do not edit an existing component contract merely to backlink to a draft.++- `family:<family-name>` owns `<shared concept>`; this component `<adopts or deliberately differs>`.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| -------- | ---------------------------- | --------------------- | ----------------------------------------------- | ------------------------ |+| FR1 | `<test or browser evidence>` | `<states>` | `<removing behavior makes this fail because …>` | `audit:<Name>/<section>` |++## Decision log++### DEC-1 — `<component-local decision>`++**Reference:** `component:<Name>/DEC-1`+**Decider:** `<person>`, `<YYYY-MM-DD>`++`<Reason and user impact.>`++Rejected: `<alternative — why>`.++## Open questions++- **OQ1 — `<question>`** (`checkable | human-design | human-api`)++## Content boundary++This file does not duplicate consumer prop tables/examples, current audit+results, implementation steps, or family/system rules. It links to their owners.diff --git a/docs/templates/knowledge/design-spec.md b/docs/templates/knowledge/design-spec.mdnew file mode 100644index 0000000000..9ca71cc839--- /dev/null+++ b/docs/templates/knowledge/design-spec.md@@ -0,0 +1,84 @@+---+schema_version: 1+template_version: 1+kind: design+id: design:<surface>+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [<design-owner>]+review_triggers: [visual, interaction]+verified_by: [<story-or-check>]+architecture: [architecture:<surface>]+components: [component:<Name>]+families: [family:<family-name>]+deciding_specs: [spec:AST-000/DEC-0]+---++# <Surface> design specification++## User intent++<!-- Who is affected, in which state, and what they should understand or do. -->++## Design principles++- **DR1 — `<principle>`.** `<The experience MUST …>`++## Anatomy and hierarchy++<!-- Name stable visual/interaction roles, not DOM structure. -->++| Role | Purpose | Required relationship |+| -------- | ----------- | --------------------- |+| `<role>` | `<purpose>` | `<relationship>` |++## State representation++| State | Required representation | Allowed variation |+| --------- | -------------------------------- | ----------------------------------- |+| `<state>` | `<what must remain perceivable>` | `<what themes/components may vary>` |++## Responsive and input behavior++- **DR2 — `<contract>`.** `<At this constraint/input mode, the experience MUST …>`++## Accessibility intent++<!-- Human intent that complements, but does not duplicate, the technical accessibility contract. -->++## Representative examples++<!-- Public-safe design artifacts or repo-owned examples. -->++## Visual references++<!-- Public-safe normative images live in docs/design/assets/<design-id>/. -->++| Asset | State | Theme or mode | Viewport | What it demonstrates | Alt text |+| --------------------------------- | --------- | ------------- | --------------- | -------------------- | --------------- |+| `./assets/<design-id>/<file>.png` | `<state>` | `<mode>` | `<size or n/a>` | `<decision>` | `<description>` |++## Component contract links++- `component:<Name>/FR1` implements `design:<surface>/DR1`.++## Decision log++### DEC-1 — `<human design decision>`++**Reference:** `design:<surface>/DEC-1`+**Decider:** `<person>`, `<YYYY-MM-DD>`++`<Reason and user impact.>`++## Open questions++- **OQ1 — `<human design question>`**++## Content boundary++This file does not define prop syntax, implementation structure, current audit+scores, or consumer examples. It links to those owners.diff --git a/docs/templates/knowledge/family-contract.md b/docs/templates/knowledge/family-contract.mdnew file mode 100644index 0000000000..af9dea49c9--- /dev/null+++ b/docs/templates/knowledge/family-contract.md@@ -0,0 +1,86 @@+---+schema_version: 1+template_version: 1+kind: family+id: family:<family-name>+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [<owner>]+review_triggers: [behavior, layout, theming, accessibility]+verified_by: [<test-or-check>]+members: [component:<Name>]+architecture: [architecture:<surface>]+contributing: [contributing:<surface>]+deciding_specs: [spec:AST-000/DEC-0]+---++# <Family name> contract++## Intent++## Membership rule++`members` is the candidate family's source of proposed membership while this+record is `draft`. Existing component records do not backlink until the family is+`current`.++A component belongs when `<observable responsibility>` is its primary purpose+and it must follow `<shared contract>`. List explicit exclusions and collaborating+components that influence members without joining the family.++- **Members:** `<components that satisfy the rule>`+- **Collaborators:** `<layout, grouping, or infrastructure components>`+- **Excluded:** `<nearby components and why they do not satisfy the rule>`++## Shared owner++- `<shared concept>` is owned by `<primitive, hook, or seam>`.++## Canonical concepts++| Concept | Values or states | Default semantics | Stability |+| ----------- | ---------------- | ----------------- | -------------------------- |+| `<concept>` | `<values>` | `<meaning>` | `<stable or experimental>` |++## Cross-component invariants++- **FR1 — `<invariant>`.** `<Every member MUST …>`++## Allowed component variation++- **AV1 — `<dimension>`.** `<Members MAY … because …>`++## Representative matrix++| Member and state | Shared invariant | Deliberate variation |+| ------------------------------ | ---------------- | -------------------- |+| `component:<Name>` / `<state>` | `<invariant>` | `<variation>` |++## Adoption and exceptions++| Component | Adoption | Exception decision |+| ------------------ | ------------- | ------------------ |+| `component:<Name>` | `<mechanism>` | `none` |++## Verification map++| Contract | Verification | Representative members and states | Mutation or failure expectation |+| -------- | ---------------------------- | --------------------------------- | --------------------------------------------- |+| FR1 | `<test or browser evidence>` | `<members/states>` | `<a component-specific fork makes this fail>` |++## Decision links++- `spec:AST-000/DEC-0` — `<shared-system ruling>`++## Open questions++- **OQ1 — `<question>`** (`checkable | human-design | human-api`)++## Content boundary++This file owns only cross-component family behavior. It does not repeat+component-local contracts, consumer docs, current audit results, or system-spec+rationale.diff --git a/docs/templates/knowledge/implementation-plan.md b/docs/templates/knowledge/implementation-plan.mdnew file mode 100644index 0000000000..48d2af13c4--- /dev/null+++ b/docs/templates/knowledge/implementation-plan.md@@ -0,0 +1,32 @@+---+schema_version: 1+template_version: 1+kind: implementation-plan+id: plan:AST-000+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+spec: spec:AST-000+owners: [<owner>]+---++# <Change> implementation plan++## Phases++### Phase 1 — <reviewable outcome>++- [ ] `<step>`++## Verification++| Phase | Contract | Evidence |+| ----- | ------------------ | ------------------------------- |+| 1 | `spec:AST-000/FR1` | `<test or observable evidence>` |++## Status++- Current phase: `<phase>`+- Blockers: `<none or link>`diff --git a/docs/templates/knowledge/system-spec.md b/docs/templates/knowledge/system-spec.mdnew file mode 100644index 0000000000..2c5c0a3345--- /dev/null+++ b/docs/templates/knowledge/system-spec.md@@ -0,0 +1,61 @@+---+schema_version: 1+template_version: 1+kind: system-spec+id: spec:AST-000+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+phase: proposed | accepted | implementing | shipped | withdrawn+owners: [<owner>]+affects_architecture: [architecture:<surface>]+affects_families: [family:<family-name>]+affects_contributing: [contributing:<surface>]+affects_consumer_docs: [<doc-id>]+---++# <Change> system spec++## Intent++## Non-goals++- `<non-goal>`++## Requirements++- **FR1 — `<behavior>`.** `<The system MUST …>`+- **IR1 — `<constraint>`.** `<The implementation MUST …>`++### Platform support++- Supported feature/engine floor: `<matrix or canonical consumer-doc link>`+- Unsupported behavior: `<required fallback, graceful degradation, or prohibition>`+- Browser evidence: `<real browser requirement; do not substitute Playwright WebKit for Safari>`++## Current-state impact++<!-- Name every architecture, family, contributing, and consumer-doc surface changed when this ships. -->++## Verification++| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | -------------------- | --------------------- | ------------------------------------- |+| FR1 | `<test or evidence>` | `<states>` | `<removing behavior makes this fail>` |++## Decision log++### DEC-1 — `<decision>`++**Reference:** `spec:AST-000/DEC-1`+**Decider:** `<person>`, `<YYYY-MM-DD>`++`<Reason and user impact.>`++Rejected: `<alternative — why>`.++## Open questions++- **OQ1 — `<question>`** (`checkable | human-design | human-api`)diff --git a/docs/templates/knowledge/versions.json b/docs/templates/knowledge/versions.jsonnew file mode 100644index 0000000000..455391dff5--- /dev/null+++ b/docs/templates/knowledge/versions.json@@ -0,0 +1,8 @@+{+ "architecture": 1,+ "component": 1,+ "design": 1,+ "family": 1,+ "implementation-plan": 1,+ "system-spec": 1+}diff --git a/package.json b/package.jsonindex 93cb6084d6..9c5436a6eb 100644--- a/package.json+++ b/package.json@@ -11,7 +11,7 @@"test:watch": "vitest","test:coverage": "vitest --coverage","check:package-boundaries": "node scripts/check-package-boundaries.js",- "check:repo": "pnpm check:sync && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures",+ "check:repo": "pnpm check:sync && pnpm check:knowledge && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure && pnpm check:use-client && pnpm check:portable-scripts && pnpm check:i18n-catalog && pnpm check:cldr-weekdays && pnpm check:fixtures","check:fixtures": "node internal/vibe-tests/scripts/fixture-suite.mjs verify","generate:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs","check:cldr-weekdays": "node scripts/generate-cldr-weekdays.mjs --check",@@ -58,7 +58,8 @@"prepare": "husky install","dev:sandbox": "pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/sandbox dev","dev:sandbox:source": "ASTRYX_SOURCE=1 pnpm -F @astryxdesign/sandbox dev",- "npm:prune-canaries": "node scripts/npm/prune-canaries.mjs"+ "npm:prune-canaries": "node scripts/npm/prune-canaries.mjs",+ "check:knowledge": "node scripts/check-knowledge.mjs"},"devDependencies": {"@axe-core/playwright": "^4.12.1",diff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjsnew file mode 100644index 0000000000..96efb66366--- /dev/null+++ b/scripts/check-knowledge.mjs@@ -0,0 +1,520 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/* global console, process */+import fs from 'node:fs';+import path from 'node:path';+import {execFileSync} from 'node:child_process';+import {createRequire} from 'node:module';+import {fileURLToPath} from 'node:url';++const require = createRequire(import.meta.url);+const {+ parseAuthority,+ parseOwnerFile,+} = require('../.github/scripts/knowledge-frontmatter.cjs');++const HERE = path.dirname(fileURLToPath(import.meta.url));+const DEFAULT_ROOT = path.resolve(HERE, '..');++export function parseKnowledgeDocument(content, filePath = '<document>') {+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);+ if (!match) {+ return {+ frontmatter: new Map(),+ sections: [],+ problems: [`${filePath}: missing frontmatter.`],+ };+ }++ function parseScalar(raw) {+ let value = raw.trim();+ if (value === 'null' || value === '~') return null;+ if (/^\[.*\]$/.test(value)) {+ const inner = value.slice(1, -1).trim();+ return inner+ ? inner+ .split(',')+ .map(item => item.trim())+ .filter(Boolean)+ .map(item => item.replace(/^['"]|['"]$/g, ''))+ : [];+ }+ if (/^[0-9]+$/.test(value)) return Number(value);+ return value.replace(/^['"]|['"]$/g, '');+ }++ const frontmatter = new Map();+ const problems = [];+ const lines = match[1].split(/\r?\n/);+ for (let index = 0; index < lines.length; index += 1) {+ const line = lines[index];+ if (+ /^\s/.test(line) ||+ line.trim() === '' ||+ line.trimStart().startsWith('#')+ )+ continue;+ const field = line.match(/^([a-z][a-z0-9_]*):\s*(.*)$/);+ if (!field) continue;+ let raw = field[2].trim();+ if (raw === '') {+ const block = [];+ while (index + 1 < lines.length && /^\s/.test(lines[index + 1])) {+ block.push(lines[index + 1].trim());+ index += 1;+ }+ if (block[0] === '[' && block.at(-1) === ']') {+ raw = `[${block.slice(1, -1).join('')}]`;+ } else if (block.every(item => item.startsWith('- '))) {+ raw = `[${block.map(item => item.slice(2)).join(',')}]`;+ }+ }+ if (frontmatter.has(field[1])) {+ problems.push(`${filePath}: duplicate frontmatter field ${field[1]}.`);+ continue;+ }+ frontmatter.set(field[1], parseScalar(raw));+ }++ try {+ const authority = parseAuthority(content, filePath);+ if (authority !== frontmatter.get('authority')) {+ problems.push(`${filePath}: authority could not be parsed consistently.`);+ }+ } catch (error) {+ problems.push(error.message);+ }++ const sections = [...content.matchAll(/^## (.+?)\s*$/gm)].map(+ section => section[1],+ );+ return {frontmatter, sections, problems};+}++function immediateDirectories(directory) {+ if (!fs.existsSync(directory)) return [];+ return fs+ .readdirSync(directory, {withFileTypes: true})+ .filter(entry => entry.isDirectory())+ .map(entry => path.join(directory, entry.name));+}++function matchingFiles(directory, predicate) {+ if (!fs.existsSync(directory)) return [];+ return fs+ .readdirSync(directory, {withFileTypes: true})+ .filter(entry => entry.isFile() && predicate(entry.name))+ .map(entry => path.join(directory, entry.name));+}++export function discoverKnowledgeRecords(root = DEFAULT_ROOT) {+ const records = [];++ for (const specDirectory of immediateDirectories(+ path.join(root, 'docs/specs'),+ )) {+ for (const name of ['spec.md', 'plan.md']) {+ const candidate = path.join(specDirectory, name);+ if (fs.existsSync(candidate)) records.push(candidate);+ }+ }++ records.push(+ ...matchingFiles(+ path.join(root, 'docs/families'),+ name => name.endsWith('.md') && name !== 'README.md',+ ),+ ...matchingFiles(+ path.join(root, 'docs/architecture'),+ name => name.endsWith('.md') && name !== 'README.md',+ ),+ ...matchingFiles(+ path.join(root, 'docs/design'),+ name => name.endsWith('.md') && name !== 'README.md',+ ),+ );++ for (const packageName of ['core', 'lab']) {+ for (const componentDirectory of immediateDirectories(+ path.join(root, `packages/${packageName}/src`),+ )) {+ records.push(+ ...matchingFiles(componentDirectory, name => name.endsWith('.spec.md')),+ );+ }+ }++ return records.sort();+}++function validateAgainstSchema(+ document,+ schema,+ schemaPath,+ filePath,+ isTemplate,+ currentTemplateVersion,+ designApprovalOwners = [],+) {+ const problems = [...document.problems];+ const {frontmatter, sections} = document;+ const kind = frontmatter.get('kind');+ const kindSchema = schema.kinds[kind];++ if (!kindSchema) {+ problems.push(+ `${filePath}: unknown knowledge kind ${JSON.stringify(kind)}.`,+ );+ return problems;+ }++ for (const field of kindSchema.requiredFrontmatter) {+ if (!frontmatter.has(field))+ problems.push(`${filePath}: missing frontmatter field ${field}.`);+ }+ for (const section of kindSchema.requiredSections) {+ if (!sections.includes(section))+ problems.push(`${filePath}: missing section "${section}".`);+ }++ const templateVersion = frontmatter.get('template_version');+ if (!Number.isInteger(templateVersion) || templateVersion < 1) {+ problems.push(`${filePath}: template_version must be a positive integer.`);+ } else if (templateVersion > currentTemplateVersion) {+ problems.push(+ `${filePath}: template_version ${templateVersion} is newer than ${currentTemplateVersion}.`,+ );+ }++ const schemaVersion = frontmatter.get('schema_version');+ if (schemaVersion !== schema.schemaVersion) {+ problems.push(+ `${filePath}: schema_version ${JSON.stringify(schemaVersion)} does not match ${schema.schemaVersion} from ${schemaPath}.`,+ );+ }++ if (isTemplate) {+ if (templateVersion !== currentTemplateVersion) {+ problems.push(+ `${filePath}: template_version must equal ${currentTemplateVersion}.`,+ );+ }+ const extraFields = [...frontmatter.keys()].filter(+ field => !kindSchema.requiredFrontmatter.includes(field),+ );+ if (extraFields.length) {+ problems.push(+ `${filePath}: template fields are missing from the schema: ${extraFields.join(', ')}.`,+ );+ }+ if (+ JSON.stringify(sections) !== JSON.stringify(kindSchema.requiredSections)+ ) {+ problems.push(+ `${filePath}: template section order must exactly match the schema; bump the schema and migrate active records for a structural change.`,+ );+ }+ return problems;+ }++ const owners = frontmatter.get('owners');+ if (!Array.isArray(owners) || owners.length === 0) {+ problems.push(`${filePath}: owners must be a non-empty inline list.`);+ }++ const authority = frontmatter.get('authority');+ if (!schema.authorities.includes(authority)) {+ problems.push(+ `${filePath}: authority must be ${schema.authorities.join(', ')}.`,+ );+ }+ if (authority === 'current') {+ for (const field of kindSchema.currentNonEmptyFields ?? []) {+ const value = frontmatter.get(field);+ if (!Array.isArray(value) || value.length === 0) {+ problems.push(+ `${filePath}: current records require non-empty ${field}.`,+ );+ }+ }+ const approvedBy = frontmatter.get('approved_by');+ const approvedAt = frontmatter.get('approved_at');+ const authorizedOwners =+ kind === 'design'+ ? [...new Set([...schema.approvalOwners, ...designApprovalOwners])]+ : schema.approvalOwners;+ if (!authorizedOwners.includes(approvedBy)) {+ problems.push(+ `${filePath}: current records require approved_by to name an authorized owner.`,+ );+ }+ if (+ typeof approvedAt !== 'string' ||+ !/^\d{4}-\d{2}-\d{2}$/.test(approvedAt)+ ) {+ problems.push(+ `${filePath}: current records require approved_at as YYYY-MM-DD.`,+ );+ }+ }+ if (authority === 'archived') {+ const reason = frontmatter.get('archive_reason');+ if (!schema.archiveReasons.includes(reason)) {+ problems.push(+ `${filePath}: archived records require archive_reason (${schema.archiveReasons.join(', ')}).`,+ );+ }+ if (reason === 'superseded' && !frontmatter.get('superseded_by')) {+ problems.push(`${filePath}: superseded records require superseded_by.`);+ }+ }++ return problems;+}++export function validateSchemaEvolution(baseSchemas, currentSchemas) {+ const problems = [];+ let highestBaseVersion = -1;+ for (const [filePath, baseContent] of baseSchemas) {+ const match = filePath.match(/v([0-9]+)\.json$/);+ if (match)+ highestBaseVersion = Math.max(highestBaseVersion, Number(match[1]));+ if (!currentSchemas.has(filePath)) {+ problems.push(+ `${filePath}: versioned schemas are append-only and cannot be deleted.`,+ );+ } else if (currentSchemas.get(filePath) !== baseContent) {+ problems.push(+ `${filePath}: versioned schemas are immutable; add a new version and migrate active records.`,+ );+ }+ }+ for (const filePath of currentSchemas.keys()) {+ if (baseSchemas.has(filePath)) continue;+ const version = Number(filePath.match(/v([0-9]+)\.json$/)?.[1]);+ if (!Number.isInteger(version) || version <= highestBaseVersion) {+ problems.push(+ `${filePath}: new schema versions must be greater than ${highestBaseVersion}.`,+ );+ }+ }+ return problems;+}++function schemaFilesAtRevision(root, revision) {+ let output;+ try {+ output = execFileSync(+ 'git',+ [+ '-C',+ root,+ 'ls-tree',+ '-r',+ '--name-only',+ revision,+ '--',+ 'docs/schemas/knowledge',+ ],+ {encoding: 'utf8'},+ );+ } catch (error) {+ throw new Error(`Could not read knowledge schemas at ${revision}.`, {+ cause: error,+ });+ }+ const schemas = new Map();+ for (const filePath of output+ .split(/\r?\n/)+ .filter(path => /^docs\/schemas\/knowledge\/v[0-9]+\.json$/.test(path))) {+ schemas.set(+ filePath,+ execFileSync('git', ['-C', root, 'show', `${revision}:${filePath}`], {+ encoding: 'utf8',+ }),+ );+ }+ return schemas;+}++function currentSchemaFiles(root) {+ return new Map(+ matchingFiles(path.join(root, 'docs/schemas/knowledge'), name =>+ /^v[0-9]+\.json$/.test(name),+ ).map(filePath => [+ path.relative(root, filePath),+ fs.readFileSync(filePath, 'utf8'),+ ]),+ );+}++export function validateKnowledgeRoot(root = DEFAULT_ROOT) {+ const schemaDirectory = path.join(root, 'docs/schemas/knowledge');+ const schemas = new Map(+ matchingFiles(schemaDirectory, name => /^v[0-9]+\.json$/.test(name)).map(+ schemaPath => {+ const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));+ const fileVersion = Number(+ path.basename(schemaPath).match(/^v([0-9]+)\.json$/)[1],+ );+ if (schema.schemaVersion !== fileVersion) {+ throw new Error(+ `${path.relative(root, schemaPath)} declares schemaVersion ${schema.schemaVersion}; expected ${fileVersion}.`,+ );+ }+ return [schema.schemaVersion, {schema, schemaPath}];+ },+ ),+ );+ if (schemas.size === 0)+ return ['docs/schemas/knowledge: no versioned schemas found.'];+ const latestVersion = Math.max(...schemas.keys());+ const {schema, schemaPath} = schemas.get(latestVersion);+ const relativeSchemaPath = path.relative(root, schemaPath);+ const templateVersions = JSON.parse(+ fs.readFileSync(+ path.join(root, 'docs/templates/knowledge/versions.json'),+ 'utf8',+ ),+ );+ const designOwnersPath = path.join(root, '.github/DESIGNOWNERS');+ const designApprovalOwners = fs.existsSync(designOwnersPath)+ ? parseOwnerFile(fs.readFileSync(designOwnersPath, 'utf8'))+ : [];+ const problems = [];+ const ids = new Map();+ const records = [];++ for (const [kind, kindSchema] of Object.entries(schema.kinds)) {+ if (+ !Number.isInteger(templateVersions[kind]) ||+ templateVersions[kind] < 1+ ) {+ problems.push(+ `docs/templates/knowledge/versions.json: missing valid version for ${kind}.`,+ );+ continue;+ }+ const templatePath = path.join(root, kindSchema.template);+ if (!fs.existsSync(templatePath)) {+ problems.push(+ `${kindSchema.template}: template for ${kind} does not exist.`,+ );+ continue;+ }+ const template = parseKnowledgeDocument(+ fs.readFileSync(templatePath, 'utf8'),+ kindSchema.template,+ );+ problems.push(+ ...validateAgainstSchema(+ template,+ schema,+ relativeSchemaPath,+ kindSchema.template,+ true,+ templateVersions[kind],+ designApprovalOwners,+ ),+ );+ if (template.frontmatter.get('kind') !== kind) {+ problems.push(`${kindSchema.template}: template kind must be ${kind}.`);+ }+ }++ for (const absolutePath of discoverKnowledgeRecords(root)) {+ const filePath = path.relative(root, absolutePath);+ const document = parseKnowledgeDocument(+ fs.readFileSync(absolutePath, 'utf8'),+ filePath,+ );+ const recordVersion = document.frontmatter.get('schema_version');+ const versionedSchema = schemas.get(recordVersion);+ if (!versionedSchema) {+ problems.push(+ `${filePath}: schema_version ${JSON.stringify(recordVersion)} has no schema file.`,+ );+ continue;+ }+ problems.push(+ ...validateAgainstSchema(+ document,+ versionedSchema.schema,+ path.relative(root, versionedSchema.schemaPath),+ filePath,+ false,+ templateVersions[document.frontmatter.get('kind')],+ designApprovalOwners,+ ),+ );+ if (+ versionedSchema.schema.activeAuthorities.includes(+ document.frontmatter.get('authority'),+ ) &&+ recordVersion !== latestVersion+ ) {+ problems.push(+ `${filePath}: active records must use latest schema_version ${latestVersion}.`,+ );+ }+ const id = document.frontmatter.get('id');+ if (id) {+ if (ids.has(id))+ problems.push(+ `${filePath}: duplicate id ${id}; first declared in ${ids.get(id).filePath}.`,+ );+ else {+ ids.set(id, {+ filePath,+ authority: document.frontmatter.get('authority'),+ });+ }+ }+ records.push({filePath, document});+ }++ for (const {filePath, document} of records) {+ if (document.frontmatter.get('authority') !== 'current') continue;+ const kindSchema = schema.kinds[document.frontmatter.get('kind')];+ for (const field of kindSchema.referenceFields ?? []) {+ const references = document.frontmatter.get(field);+ if (!Array.isArray(references)) continue;+ for (const reference of references) {+ const targetId = reference.replace(/\/DEC-[0-9]+$/, '');+ const target = ids.get(targetId);+ if (!target) {+ problems.push(+ `${filePath}: ${field} reference ${reference} does not resolve.`,+ );+ } else if (target.authority !== 'current') {+ problems.push(+ `${filePath}: current records may not rely on non-current ${reference} (${target.filePath}).`,+ );+ }+ }+ }+ }++ return problems;+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ const problems = validateKnowledgeRoot();+ const baseIndex = process.argv.indexOf('--base');+ if (baseIndex !== -1) {+ const baseRevision = process.argv[baseIndex + 1];+ if (!baseRevision) throw new Error('--base requires a revision.');+ problems.push(+ ...validateSchemaEvolution(+ schemaFilesAtRevision(DEFAULT_ROOT, baseRevision),+ currentSchemaFiles(DEFAULT_ROOT),+ ),+ );+ }+ if (problems.length) {+ console.error(`Knowledge validation failed (${problems.length}):\n`);+ for (const problem of problems) console.error(`- ${problem}`);+ process.exit(1);+ }+ console.log('Knowledge templates and records are aligned.');+}diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjsnew file mode 100644index 0000000000..55f2d2d53f--- /dev/null+++ b/scripts/check-knowledge.test.mjs@@ -0,0 +1,346 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {afterEach, describe, expect, it} from 'vitest';+import {+ parseKnowledgeDocument,+ validateKnowledgeRoot,+ validateSchemaEvolution,+} from './check-knowledge.mjs';++const repoRoot = path.resolve(import.meta.dirname, '..');+const roots = [];++function fixtureRoot() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-knowledge-'));+ roots.push(root);+ fs.mkdirSync(path.join(root, 'docs/schemas/knowledge'), {recursive: true});+ fs.mkdirSync(path.join(root, 'docs/templates'), {recursive: true});+ fs.cpSync(+ path.join(repoRoot, 'docs/templates/knowledge'),+ path.join(root, 'docs/templates/knowledge'),+ {recursive: true},+ );+ fs.copyFileSync(+ path.join(repoRoot, 'docs/schemas/knowledge/v1.json'),+ path.join(root, 'docs/schemas/knowledge/v1.json'),+ );+ for (const relative of [+ 'docs/specs',+ 'docs/families',+ 'docs/architecture',+ 'packages/core/src',+ 'packages/lab/src',+ ]) {+ fs.mkdirSync(path.join(root, relative), {recursive: true});+ }+ fs.mkdirSync(path.join(root, '.github'), {recursive: true});+ fs.copyFileSync(+ path.join(repoRoot, '.github/DESIGNOWNERS'),+ path.join(root, '.github/DESIGNOWNERS'),+ );+ return root;+}++function addSchemaVersion(root, version) {+ const latest = JSON.parse(+ fs.readFileSync(path.join(root, 'docs/schemas/knowledge/v1.json'), 'utf8'),+ );+ latest.schemaVersion = version;+ fs.writeFileSync(+ path.join(root, `docs/schemas/knowledge/v${version}.json`),+ `${JSON.stringify(latest, null, 2)}\n`,+ );+}++function componentRecord(overrides = {}) {+ const values = {+ schema_version: '1',+ template_version: '1',+ kind: 'component',+ id: 'component:Button',+ authority: 'draft',+ archive_reason: 'null',+ superseded_by: 'null',+ approved_by: 'null',+ approved_at: 'null',+ owners: '[owner]',+ review_triggers: '[behavior]',+ verified_by: '[Button.test.tsx]',+ families: '[family:actions]',+ design_specs: '[design:actions]',+ architecture: '[architecture:components]',+ contributing: '[contributing:api]',+ system_specs: '[]',+ ...overrides,+ };+ const frontmatter = Object.entries(values)+ .map(([key, value]) => `${key}: ${value}`)+ .join('\n');+ const sections = [+ 'Intent',+ 'Compatibility and migration',+ 'Ownership boundary',+ 'Public concepts',+ 'Behavioral and layout contract',+ 'Accessibility contract',+ 'Design relationships',+ 'Family and system relationships',+ 'Verification map',+ 'Decision log',+ 'Open questions',+ 'Content boundary',+ ]+ .map(section => `## ${section}\n\nBody.`)+ .join('\n\n');+ return `---\n${frontmatter}\n---\n\n# Button component contract\n\n${sections}\n`;+}++afterEach(() => {+ for (const root of roots.splice(0))+ fs.rmSync(root, {recursive: true, force: true});+});++describe('schema evolution', () => {+ it('allows appending a higher schema version', () => {+ expect(+ validateSchemaEvolution(+ new Map([['docs/schemas/knowledge/v1.json', 'one']]),+ new Map([+ ['docs/schemas/knowledge/v1.json', 'one'],+ ['docs/schemas/knowledge/v2.json', 'two'],+ ]),+ ),+ ).toEqual([]);+ });++ it('rejects rewriting or deleting a published schema version', () => {+ expect(+ validateSchemaEvolution(+ new Map([+ ['docs/schemas/knowledge/v1.json', 'one'],+ ['docs/schemas/knowledge/v2.json', 'two'],+ ]),+ new Map([['docs/schemas/knowledge/v1.json', 'changed']]),+ ).join('\n'),+ ).toMatch(/immutable.*append-only/s);+ });+});++describe('knowledge validation', () => {+ it('parses only top-level frontmatter and level-two sections', () => {+ const document = parseKnowledgeDocument(+ '---\nschema_version: 1\nowners:\n [\n one,\n two,\n ]\n---\n\n## Intent\n',+ );+ expect(document.frontmatter.get('schema_version')).toBe(1);+ expect(document.frontmatter.get('owners')).toEqual(['one', 'two']);+ expect(document.sections).toEqual(['Intent']);+ });++ it('accepts aligned templates with no records', () => {+ expect(validateKnowledgeRoot(fixtureRoot())).toEqual([]);+ });++ it('rejects a structural template change without a schema update', () => {+ const root = fixtureRoot();+ const template = path.join(+ root,+ 'docs/templates/knowledge/component-spec.md',+ );+ fs.appendFileSync(template, '\n## Undeclared section\n');+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /template section order must exactly match the schema/,+ );+ });++ it('rejects a schema whose filename and declared version disagree', () => {+ const root = fixtureRoot();+ const schemaPath = path.join(root, 'docs/schemas/knowledge/v1.json');+ const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));+ schema.schemaVersion = 2;+ fs.writeFileSync(schemaPath, `${JSON.stringify(schema)}\n`);+ expect(() => validateKnowledgeRoot(root)).toThrow(+ /declares schemaVersion 2/,+ );+ });++ it('accepts a draft component record on the current schema', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(path.join(directory, 'Button.spec.md'), componentRecord());+ expect(validateKnowledgeRoot(root)).toEqual([]);+ });++ it('rejects duplicate authority fields', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord().replace(+ 'authority: draft',+ 'authority: draft\nauthority: "current"',+ ),+ );+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /duplicate authority fields|duplicate frontmatter field authority/,+ );+ });++ it('requires explicit approval for a current record', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord({authority: 'current'}),+ );+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /require approved_by/,+ );+ });++ it('rejects an unauthorized current approval claim', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord({+ authority: 'current',+ approved_by: 'someone-else',+ approved_at: '2026-08-30',+ }),+ );+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(/authorized owner/);+ });++ it('accepts a current record with an authorized dated approval', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord({+ authority: 'current',+ approved_by: 'cixzhang',+ approved_at: '2026-08-30',+ }),+ );+ expect(validateKnowledgeRoot(root)).toEqual([]);+ });++ it('requires a replacement for a superseded archive', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord({authority: 'archived', archive_reason: 'superseded'}),+ );+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /require superseded_by/,+ );+ });++ it('rejects a record claiming a future template version', () => {+ const root = fixtureRoot();+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord({template_version: '2'}),+ );+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /template_version 2 is newer than 1/,+ );+ });++ it('rejects active records on an old schema', () => {+ const root = fixtureRoot();+ addSchemaVersion(root, 0);+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord({schema_version: '0'}),+ );+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /active records must use latest schema_version 1/,+ );+ });++ it('allows archived records to retain an older available schema', () => {+ const root = fixtureRoot();+ addSchemaVersion(root, 0);+ const directory = path.join(root, 'packages/core/src/Button');+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, 'Button.spec.md'),+ componentRecord({+ schema_version: '0',+ authority: 'archived',+ archive_reason: 'historical',+ }),+ );+ expect(validateKnowledgeRoot(root)).toEqual([]);+ });++ it('accepts a DESIGNOWNER approval claim on a current design record', () => {+ const root = fixtureRoot();+ const template = fs.readFileSync(+ path.join(root, 'docs/templates/knowledge/design-spec.md'),+ 'utf8',+ );+ const record = template+ .replace('id: design:<surface>', 'id: design:button')+ .replace('authority: draft', 'authority: current')+ .replace('approved_by: null', 'approved_by: rubyycheung')+ .replace('approved_at: null', 'approved_at: 2026-08-30');+ fs.mkdirSync(path.join(root, 'docs/design'), {recursive: true});+ fs.writeFileSync(path.join(root, 'docs/design/button.md'), record);+ expect(validateKnowledgeRoot(root).join('\n')).not.toMatch(+ /approved_by to name an authorized owner/,+ );+ });++ it('requires current design records to reference current architecture', () => {+ const root = fixtureRoot();+ const template = fs.readFileSync(+ path.join(root, 'docs/templates/knowledge/design-spec.md'),+ 'utf8',+ );+ const record = template+ .replace('id: design:<surface>', 'id: design:button')+ .replace('authority: draft', 'authority: current')+ .replace('approved_by: null', 'approved_by: cixzhang')+ .replace('approved_at: null', 'approved_at: 2026-08-30')+ .replace(+ 'architecture: [architecture:<surface>]',+ 'architecture: [architecture:missing]',+ );+ fs.mkdirSync(path.join(root, 'docs/design'), {recursive: true});+ fs.writeFileSync(path.join(root, 'docs/design/button.md'), record);+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /architecture reference architecture:missing does not resolve/,+ );+ });++ it('rejects duplicate logical ids', () => {+ const root = fixtureRoot();+ for (const name of ['Button', 'Action']) {+ const directory = path.join(root, `packages/core/src/${name}`);+ fs.mkdirSync(directory);+ fs.writeFileSync(+ path.join(directory, `${name}.spec.md`),+ componentRecord(),+ );+ }+ expect(validateKnowledgeRoot(root).join('\n')).toMatch(+ /duplicate id component:Button/,+ );+ });+});