Skip to content

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

TypeScript

docs(knowledge): add first-class theme specifications (#5792)

Cindy Zhangedc0cfc2c620
diff --git a/.github/scripts/change-scope.cjs b/.github/scripts/change-scope.cjs
index 73f0b96739..53abb1b47b 100644
--- a/.github/scripts/change-scope.cjs
+++ b/.github/scripts/change-scope.cjs
@@ -7,20 +7,28 @@
* 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.
+ * architecture, guidance, 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\/themes\/([^/]+)\/\1\.spec\.md$/,
/^packages\/(?:core|lab)\/src\/[^/]+\/[^/]+\.spec\.md$/,
];
const CHANGESET_PATTERN = /^\.changeset\/(?!README\.md$)[^/]+\.md$/;
+const THEME_DOC_CANDIDATE = /^docs\/themes\/(?!README\.md$)[^/]+\.md$/;
+const THEME_PACKAGE_CANDIDATE =
+ /^packages\/themes\/[^/]+\/(?:.*\/)?[^/]+\.spec\.md$/;
+
const KNOWLEDGE_RECORD_PATTERNS = [
...SPEC_RECORD_PATTERNS,
+ THEME_DOC_CANDIDATE,
+ THEME_PACKAGE_CANDIDATE,
/^docs\/architecture\/(?!README\.md$)[^/]+\.md$/,
/^docs\/design\/assets\//,
];
diff --git a/.github/scripts/change-scope.test.mjs b/.github/scripts/change-scope.test.mjs
index 8a08b7c48d..1aa39d87d1 100644
--- a/.github/scripts/change-scope.test.mjs
+++ b/.github/scripts/change-scope.test.mjs
@@ -7,12 +7,13 @@ 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', () => {
+ it('accepts system, family, design, theme, 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/themes/neutral/neutral.spec.md'},
{filename: 'packages/core/src/Selector/Selector.spec.md'},
{filename: 'packages/lab/src/FutureInput/FutureInput.spec.md'},
]);
@@ -86,13 +87,28 @@ describe('spec-only change scope', () => {
'packages/core/src/Selector/Selector.audit.json',
'docs/architecture/layers.md',
'docs/templates/knowledge/component-spec.md',
+ 'docs/templates/knowledge/theme-spec.md',
'docs/schemas/knowledge/v2.json',
+ 'docs/themes/neutral.md',
+ 'packages/themes/neutral/Theme.spec.md',
+ 'docs/themes/README.md',
+ 'docs/README.md',
'docs/specs/README.md',
'.github/workflows/ci.yml',
])('rejects %s', filename => {
expect(classifyChanges([{filename}]).specOnly).toBe(false);
});
+ it.each([
+ 'docs/themes/neutral.md',
+ 'packages/themes/neutral/Theme.spec.md',
+ 'packages/themes/neutral/subdir/neutral.spec.md',
+ ])('treats misplaced theme candidate %s as unsafe knowledge', filename => {
+ const result = classifyChanges([{filename}]);
+ expect(result.touchesKnowledgeRecords).toBe(true);
+ expect(result.specOnly).toBe(false);
+ });
+
it('fails closed for an empty change set', () => {
expect(classifyChanges([]).specOnly).toBe(false);
});
diff --git a/.github/scripts/spec-owner-decision.cjs b/.github/scripts/spec-owner-decision.cjs
index 83672fea62..8ac4f52aa4 100644
--- a/.github/scripts/spec-owner-decision.cjs
+++ b/.github/scripts/spec-owner-decision.cjs
@@ -208,16 +208,19 @@ function newestGateRun(statuses, repository) {
return newest;
}
-function isDesignVersion(content, filePath) {
- return parseKind(content, filePath) === 'design';
+function approvalGroupFor(content, filePath) {
+ const kind = parseKind(content, filePath);
+ if (kind === 'design') return 'design';
+ if (kind === 'theme') return 'theme';
+ return 'spec';
}
function requiredApprovalGroups(
records,
{complete = true, touchesDesignAssets = false} = {},
) {
- if (!complete) return {spec: true, design: true};
- const groups = {spec: false, design: touchesDesignAssets};
+ if (!complete) return {spec: true, design: true, theme: true};
+ const groups = {spec: false, design: touchesDesignAssets, theme: false};
for (const record of records) {
const versions = [
{content: record.baseContent, path: record.previousPath ?? record.path},
@@ -225,9 +228,7 @@ function requiredApprovalGroups(
];
for (const version of versions) {
if (parseAuthority(version.content, version.path) !== 'current') continue;
- groups[
- isDesignVersion(version.content, version.path) ? 'design' : 'spec'
- ] = true;
+ groups[approvalGroupFor(version.content, version.path)] = true;
}
}
return groups;
@@ -235,7 +236,7 @@ function requiredApprovalGroups(
function requiresOwnerApproval(records, options = {}) {
const groups = requiredApprovalGroups(records, options);
- return groups.spec || groups.design;
+ return groups.spec || groups.design || groups.theme;
}
module.exports = {
diff --git a/.github/scripts/spec-owner-decision.test.mjs b/.github/scripts/spec-owner-decision.test.mjs
index dc5fd21866..c18e2c1b56 100644
--- a/.github/scripts/spec-owner-decision.test.mjs
+++ b/.github/scripts/spec-owner-decision.test.mjs
@@ -87,7 +87,16 @@ describe('spec owner decision', () => {
headContent: 'kind: design\nauthority: current',
},
]),
- ).toEqual({spec: false, design: true});
+ ).toEqual({spec: false, design: true, theme: false});
+ expect(
+ requiredApprovalGroups([
+ {
+ path: 'packages/themes/neutral/neutral.spec.md',
+ baseContent: null,
+ headContent: 'kind: theme\nauthority: current',
+ },
+ ]),
+ ).toEqual({spec: false, design: false, theme: true});
expect(
requiredApprovalGroups([
{
@@ -96,7 +105,7 @@ describe('spec owner decision', () => {
headContent: 'kind: component\nauthority: current',
},
]),
- ).toEqual({spec: true, design: false});
+ ).toEqual({spec: true, design: false, theme: false});
expect(
requiredApprovalGroups(
[
@@ -113,7 +122,7 @@ describe('spec owner decision', () => {
],
{touchesDesignAssets: true},
),
- ).toEqual({spec: true, design: true});
+ ).toEqual({spec: true, design: true, theme: false});
expect(
requiredApprovalGroups([
{
@@ -122,7 +131,7 @@ describe('spec owner decision', () => {
headContent: 'kind: architecture\nauthority: current',
},
]),
- ).toEqual({spec: true, design: false});
+ ).toEqual({spec: true, design: false, theme: false});
expect(
requiredApprovalGroups([
{
@@ -132,18 +141,68 @@ describe('spec owner decision', () => {
headContent: 'kind: design\nauthority: current',
},
]),
- ).toEqual({spec: true, design: true});
+ ).toEqual({spec: true, design: true, theme: false});
});
it('owner-gates design assets even without a text record', () => {
expect(requiredApprovalGroups([], {touchesDesignAssets: true})).toEqual({
spec: false,
design: true,
+ theme: false,
});
expect(requiredApprovalGroups([], {complete: false})).toEqual({
spec: true,
design: true,
+ theme: true,
+ });
+ });
+
+ it('accepts an exact-head repo-owner review for the theme group', () => {
+ const groups = requiredApprovalGroups([
+ {
+ path: 'packages/themes/neutral/neutral.spec.md',
+ baseContent: null,
+ headContent: 'kind: theme\nauthority: current',
+ },
+ ]);
+ const decision = resolveOwnerDecision({
+ owners: ['cixzhang', 'rubyycheung', 'imdreamrunner'],
+ headSha: head,
+ comments: [],
+ reviews: [
+ {
+ user: {login: 'rubyycheung'},
+ state: 'APPROVED',
+ commit_id: head,
+ submitted_at: '2026-08-30T10:00:00Z',
+ },
+ ],
+ });
+
+ expect(groups).toEqual({spec: false, design: false, theme: true});
+ expect(decision).toMatchObject({
+ approved: true,
+ owner: 'rubyycheung',
+ source: 'review',
+ });
+ });
+
+ it('does not make a self-declared record owner an approver', () => {
+ const decision = resolveOwnerDecision({
+ owners: ['cixzhang', 'rubyycheung', 'imdreamrunner'],
+ headSha: head,
+ comments: [],
+ reviews: [
+ {
+ user: {login: 'self-declared-owner'},
+ state: 'APPROVED',
+ commit_id: head,
+ submitted_at: '2026-08-30T10:00:00Z',
+ },
+ ],
});
+
+ expect(decision.approved).toBe(false);
});
it('accepts either configured owner', () => {
diff --git a/.github/scripts/spec-owner-reconcile.cjs b/.github/scripts/spec-owner-reconcile.cjs
index 3ae9fbd8d7..1f8c8ffe3c 100644
--- a/.github/scripts/spec-owner-reconcile.cjs
+++ b/.github/scripts/spec-owner-reconcile.cjs
@@ -70,7 +70,14 @@ async function reconcileSpecOwnerGate({
const designOwners = parseOwnerFile(
fs.readFileSync(path.join(workspace, '.github/DESIGNOWNERS'), 'utf8'),
);
- const allOwners = new Set([...specOwners, ...designOwners]);
+ const engineeringOwners = parseOwnerFile(
+ fs.readFileSync(path.join(workspace, '.github/ENGOWNERS'), 'utf8'),
+ );
+ const allOwners = new Set([
+ ...specOwners,
+ ...engineeringOwners,
+ ...designOwners,
+ ]);
if (!isAuthorizedEvent(context.eventName, context.payload, allOwners)) {
core.info('Ignoring an event from someone outside the eligible owners.');
return;
@@ -411,11 +418,22 @@ async function reconcileSpecOwnerGate({
complete: scope.complete,
touchesDesignAssets: scope.touchesDesignAssets,
});
- const ownerApprovalRequired = requiredGroups.spec || requiredGroups.design;
+ const ownerApprovalRequired =
+ requiredGroups.spec || requiredGroups.design || requiredGroups.theme;
if (requiredGroups.design && designOwners.length === 0) {
throw new Error('No DESIGNOWNERS are configured.');
}
+ if (
+ requiredGroups.theme &&
+ engineeringOwners.length === 0 &&
+ designOwners.length === 0
+ ) {
+ throw new Error('No ENGOWNERS or DESIGNOWNERS are configured.');
+ }
const designApprovers = [...new Set([...specOwners, ...designOwners])];
+ const themeApprovers = [
+ ...new Set([...engineeringOwners, ...designOwners]),
+ ];
const readyAttestations = parseReadyAttestations(statuses, {
repository,
headSha: initialHead,
@@ -433,8 +451,18 @@ async function reconcileSpecOwnerGate({
const designDecision = requiredGroups.design
? resolveOwnerDecision({...decisionInput, owners: designApprovers})
: {approved: true, owner: null};
- const approved = specDecision.approved && designDecision.approved;
- const approvingOwners = [specDecision.owner, designDecision.owner]
+ const themeDecision = requiredGroups.theme
+ ? resolveOwnerDecision({...decisionInput, owners: themeApprovers})
+ : {approved: true, owner: null};
+ const approved =
+ specDecision.approved &&
+ designDecision.approved &&
+ themeDecision.approved;
+ const approvingOwners = [
+ specDecision.owner,
+ designDecision.owner,
+ themeDecision.owner,
+ ]
.filter(Boolean)
.filter((ownerName, index, owners) => owners.indexOf(ownerName) === index);
const requiredOwnerDescription = [
@@ -442,6 +470,9 @@ async function reconcileSpecOwnerGate({
requiredGroups.design
? `a design approver (${designApprovers.join(',')})`
: null,
+ requiredGroups.theme
+ ? `a theme approver (${themeApprovers.join(',')})`
+ : null,
]
.filter(Boolean)
.join(' and ');
diff --git a/.github/scripts/spec-owner-reconcile.test.mjs b/.github/scripts/spec-owner-reconcile.test.mjs
index dc03ff1968..e6b7482d2b 100644
--- a/.github/scripts/spec-owner-reconcile.test.mjs
+++ b/.github/scripts/spec-owner-reconcile.test.mjs
@@ -91,6 +91,12 @@ function createHarness({
autoMerge = null,
onPullGet,
onEnableAutoMerge,
+ changedFile = {
+ filename: 'docs/specs/owner-ready/spec.md',
+ status: 'added',
+ },
+ headContent = 'kind: architecture\nauthority: current\n',
+ baseContent = '',
} = {}) {
const state = {
pullGets: 0,
@@ -129,14 +135,7 @@ function createHarness({
syncLabels();
return {data: state.pr};
},
- listFiles: async () => ({
- data: [
- {
- filename: 'docs/specs/owner-ready/spec.md',
- status: 'added',
- },
- ],
- }),
+ listFiles: async () => ({data: [changedFile]}),
listReviews: async () => ({data: state.reviews}),
listComments: async () => ({data: state.comments}),
listTimeline: async () => ({data: state.timeline}),
@@ -199,9 +198,7 @@ function createHarness({
getContent: async ({ref}) => ({
data: {
content: Buffer.from(
- ref === state.pr.head.sha
- ? 'kind: architecture\nauthority: current\n'
- : '',
+ ref === state.pr.head.sha ? headContent : baseContent,
).toString('base64'),
},
}),
@@ -274,6 +271,167 @@ describe('spec owner workflow reconciliation', () => {
expect(harness.state.calls).not.toContain('enable-auto-merge');
});
+ it('keeps a current theme change pending without exact-head approval', async () => {
+ const harness = createHarness({
+ changedFile: {
+ filename: 'packages/themes/neutral/neutral.spec.md',
+ status: 'added',
+ },
+ headContent: 'kind: theme\nauthority: current\n',
+ });
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ action: 'synchronize',
+ actor: 'rubyycheung',
+ }),
+ );
+
+ expect(latestGateStatus(harness.state)).toMatchObject({
+ state: 'pending',
+ description: expect.stringContaining('theme approver'),
+ });
+ expect(harness.state.calls).not.toContain('enable-auto-merge');
+ expect(harness.state.pr.auto_merge).toBe(null);
+ });
+
+ it.each([
+ 'docs/themes/neutral.md',
+ 'packages/themes/neutral/Theme.spec.md',
+ 'packages/themes/neutral/subdir/neutral.spec.md',
+ ])(
+ 'keeps misplaced current theme candidate %s pending and non-merging',
+ async filename => {
+ const harness = createHarness({
+ changedFile: {filename, status: 'added'},
+ headContent: 'kind: theme\nauthority: current\n',
+ });
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ action: 'synchronize',
+ actor: 'rubyycheung',
+ }),
+ );
+
+ expect(latestGateStatus(harness.state)).toMatchObject({
+ state: 'pending',
+ description: expect.stringContaining('theme approver'),
+ });
+ expect(harness.state.calls).not.toContain('enable-auto-merge');
+ expect(
+ harness.state.calls.some(call =>
+ call.includes('No knowledge records changed'),
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it('accepts an exact-head derived theme-owner review for a current theme record', async () => {
+ const review = {
+ user: {login: 'rubyycheung'},
+ state: 'APPROVED',
+ commit_id: head,
+ submitted_at: '2026-08-30T10:00:00Z',
+ };
+ const harness = createHarness({
+ changedFile: {
+ filename: 'packages/themes/neutral/neutral.spec.md',
+ status: 'added',
+ },
+ headContent:
+ 'kind: theme\nauthority: current\nadditional_owners: [self-declared-owner]\n',
+ reviews: [review],
+ });
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ eventName: 'pull_request_review',
+ action: 'submitted',
+ actor: 'rubyycheung',
+ review,
+ }),
+ );
+
+ expect(latestGateStatus(harness.state)).toMatchObject({
+ state: 'success',
+ description: expect.stringContaining('@rubyycheung'),
+ });
+ expect(harness.state.calls).toContain('enable-auto-merge');
+ });
+
+ it('accepts an exact-head ENGOWNER review for a current theme record', async () => {
+ const review = {
+ user: {login: 'czarandy'},
+ state: 'APPROVED',
+ commit_id: head,
+ submitted_at: '2026-08-30T10:00:00Z',
+ };
+ const harness = createHarness({
+ changedFile: {
+ filename: 'packages/themes/neutral/neutral.spec.md',
+ status: 'added',
+ },
+ headContent: 'kind: theme\nauthority: current\n',
+ reviews: [review],
+ });
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ eventName: 'pull_request_review',
+ action: 'submitted',
+ actor: 'czarandy',
+ review,
+ }),
+ );
+
+ expect(latestGateStatus(harness.state)).toMatchObject({
+ state: 'success',
+ description: expect.stringContaining('@czarandy'),
+ });
+ expect(harness.state.calls).toContain('enable-auto-merge');
+ });
+
+ it('does not authorize a theme record through its self-declared owners', async () => {
+ const review = {
+ user: {login: 'self-declared-owner'},
+ state: 'APPROVED',
+ commit_id: head,
+ submitted_at: '2026-08-30T10:00:00Z',
+ };
+ const harness = createHarness({
+ changedFile: {
+ filename: 'packages/themes/neutral/neutral.spec.md',
+ status: 'added',
+ },
+ headContent:
+ 'kind: theme\nauthority: current\nadditional_owners: [self-declared-owner]\n',
+ reviews: [review],
+ });
+
+ await run(
+ harness,
+ context({
+ runId: 100n,
+ eventName: 'pull_request_review',
+ action: 'submitted',
+ actor: 'self-declared-owner',
+ review,
+ }),
+ );
+
+ expect(harness.state.pullGets).toBe(0);
+ expect(harness.state.statuses).toEqual([]);
+ });
+
it('abandons the old event when the live head changes', async () => {
const harness = createHarness({
onPullGet: (count, state) => {
diff --git a/.github/scripts/spec-owner-workflow.test.mjs b/.github/scripts/spec-owner-workflow.test.mjs
index 48226514f3..238d185964 100644
--- a/.github/scripts/spec-owner-workflow.test.mjs
+++ b/.github/scripts/spec-owner-workflow.test.mjs
@@ -116,9 +116,16 @@ describe('spec-only workflow contract', () => {
expect(reconciler).toContain('scope.touchesDesignAssets');
expect(reconciler).toContain('requiredApprovalGroups(records');
expect(reconciler).toContain("'.github/DESIGNOWNERS'");
+ expect(reconciler).toContain("'.github/ENGOWNERS'");
expect(reconciler).toContain(
- 'specDecision.approved && designDecision.approved',
+ '...new Set([...engineeringOwners, ...designOwners])',
);
+ expect(reconciler).not.toContain(
+ '...new Set([...specOwners, ...engineeringOwners, ...designOwners])',
+ );
+ expect(reconciler).toContain('specDecision.approved');
+ expect(reconciler).toContain('designDecision.approved');
+ expect(reconciler).toContain('themeDecision.approved');
expect(reconciler).toContain('context: GATE_STATUS_CONTEXT');
expect(reconciler).toContain('expectedHeadOid: $oid');
expect(reconciler).toContain('mergeMethod: SQUASH');
diff --git a/.github/workflows/spec-owner-gate.yml b/.github/workflows/spec-owner-gate.yml
index 8685cd733d..0eb0a5b5fe 100644
--- a/.github/workflows/spec-owner-gate.yml
+++ b/.github/workflows/spec-owner-gate.yml
@@ -2,8 +2,9 @@
# 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
+# and normative design assets also accept DESIGNOWNERS; current theme records
+# accept the committed union of ENGOWNERS and DESIGNOWNERS. Mixed PRs keep every applicable owner-group
+# requirement. Pure spec-record PRs
# skip heavy CI only when every changed path is recognized; draft-only records
# can auto-merge after validation, while current records also need approval on
# the exact current head.
diff --git a/docs/README.md b/docs/README.md
index 0d07d0fcef..ec341dbea7 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -9,13 +9,15 @@ it governs. Consumer documentation remains in component `.doc.mjs` files and
- `architecture/`: the shipped system, its boundaries, and invariants.
- `contributing/`: practical contributor workflows that project current owner records without replacing them.
- `design/`: human-owned visual and interaction specifications.
+- `themes/`: guidance and index for package-local theme 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`.
+`<Name>.spec.md` and `<Name>.audit.json`. Theme contracts likewise live beside
+the package as `packages/themes/<theme>/<theme>.spec.md`.
## Authority
@@ -26,7 +28,9 @@ Every knowledge record declares `authority: draft | current | archived`.
- 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`.
+ `.github/DESIGNOWNERS`; current theme records accept the committed union of
+ `.github/ENGOWNERS` and `.github/DESIGNOWNERS`. Legacy v1 `owners` metadata is
+ descriptive and does not grant approval rights.
- Pull requests that create, change, or archive a `current` record wait on the
`spec-owner-approval` status for their exact current head. Draft-only records
pass that status after validation without an owner review.
@@ -50,9 +54,20 @@ aligned. They are intentionally separate:
- 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.
+- Every active record (`draft` or `current`) must use the latest schema that
+ defines its kind. Adding a new kind does not migrate unrelated records;
+ structurally changing an existing kind migrates only active records of that
+ kind. Archived records may retain an older schema that remains checked in.
+
+Published schema versions may extend an earlier schema. The checker composes the
+chain and tracks the latest version that defines each record kind. A new kind is
+therefore additive; changing an existing kind migrates only that kind.
+
+New record kinds should prefer one typed relationship list over parallel fields.
+If `system-spec` receives a future schema revision, replace its legacy
+`affects_*` fields with one typed `affects` list containing ids such as
+`architecture:*`, `family:*`, `theme:*`, and `contributing:*`; this PR does not
+change the v1 system-spec shape.
Run `pnpm check:knowledge` to validate templates and records. Pure spec-record
pull requests do not add Changesets because they do not publish package changes.
diff --git a/docs/architecture/knowledge-contracts.md b/docs/architecture/knowledge-contracts.md
index 9fc97f061c..70dc525171 100644
--- a/docs/architecture/knowledge-contracts.md
+++ b/docs/architecture/knowledge-contracts.md
@@ -35,8 +35,13 @@ Astryx keeps different facts in different places:
- Component contracts describe behavior one component promises.
- Family contracts describe behavior sibling components share.
-- Design specs record human-owned visual and interaction decisions.
-- System specs record decisions that cross components or change architecture.
+- Design specs record human-owned visual and interaction decisions, including the
+ cross-theme accessibility and contrast methodology used to judge token/color
+ pairings.
+- Theme specs record one package theme's intent, inherited base, selected token
+ and palette mappings, required pairings/states, theme-specific exceptions,
+ measured receipts, known gaps, compatibility, and artifacts.
+- System specs record decisions that cross components or themes or change architecture.
- Consumer docs explain props, examples, and usage.
- Audit records hold current evidence and findings.
@@ -44,8 +49,8 @@ The reviewer starts with the changed code and the nearest current component
contract. They follow only the links needed for the question:
```text
-changed code
- → nearest current component contract
+changed code or theme source
+ → nearest current component or theme contract
→ relevant family or design requirement
→ architecture or system decision only when referenced
→ mapped tests and audit evidence
@@ -54,6 +59,16 @@ changed code
A current record may cite a previous human decision. When the new case is within
that decision's stated scope, the reviewer applies it without asking again.
+Theme records sit between shared theming architecture and downstream records.
+Cross-theme API, vocabulary, inheritance, validation, compiler behavior, and
+artifact policy remain in architecture or system specs. Cross-theme human visual
+and accessibility methodology for contrast belongs in a current design record;
+shared measurement/tool implementation belongs to architecture or tooling. One
+theme's selected token/palette mappings, required pairings and states,
+exceptions, measured receipts, known gaps, migration, and artifacts belong in
+its package-local theme record. Components and families continue to own
+observable behavior; consumer docs continue to own supported syntax and examples.
+
Every record is either:
- `draft`: useful for review, but not a rule;
@@ -64,8 +79,13 @@ Every record is either:
- **INV1 — Current means approved.** Only `current` records guide implementation
and review.
-- **INV2 — One fact has one owner.** A component record does not copy family,
- design, consumer, or audit content.
+- **INV2 — One fact has one owner.** A component or theme record does not copy
+ family, design, system, consumer, audit, or tooling content. Cross-theme API and
+ compiler behavior stay in architecture/system records; human contrast
+ methodology stays in design; shared measurement implementation stays in
+ architecture/tooling; theme-specific mappings, states, exceptions, receipts,
+ and gaps stay in the package-local theme record; observable component behavior
+ stays in component/family records; consumer syntax stays in consumer docs.
- **INV3 — Existing decisions are reusable.** A reviewer cites an applicable
decision and proceeds without asking the human again.
- **INV4 — New judgment is explicit.** A reviewer asks a human when no current
@@ -73,12 +93,15 @@ Every record is either:
human-owned.
- **INV5 — Blank forms are not policy.** Templates only create drafts. Search
and review never present template text as an approved Astryx decision.
-- **INV6 — Required structure changes together.** Template wording may change
- without touching existing records. Adding or removing a required field or
- section must update every draft and current record in the same pull request.
+- **INV6 — Required structure changes per kind.** Template wording may change
+ without touching existing records. Adding a new kind does not migrate unrelated
+ kinds. Adding or removing a required field or section from an existing kind
+ creates a later schema definition for that kind and migrates every active record
+ of that kind in the same pull request.
- **INV7 — Only pure spec changes use lightweight CI.** Every changed file must
- be a component, family, design, or system spec. A change to code, architecture,
- templates, schemas, audits, or any unknown path runs normal CI.
+ be a component, family, design, theme, or system spec. A change to code,
+ architecture, guidance, templates, schemas, audits, or any unknown path runs
+ normal CI.
- **INV8 — Private operations stay private.** Public records never name or link
private release or automation systems.
- **INV9 — Current records have no implicit precedence.** A newer, narrower, or
@@ -88,7 +111,8 @@ Every record is either:
1. A draft is context only and cannot conflict with current policy.
2. Identify the canonical owner from the fact's scope: component behavior,
- family behavior, design representation, consumer usage, or audit evidence.
+ family behavior, design representation, one theme's semantics/mappings,
+ cross-theme architecture, consumer usage, or audit evidence.
3. If two current records make different claims, review stops. Do not choose by
recency, path proximity, or specificity; record a `novel-human` gap.
4. Resolve the gap by changing the canonical owner and removing the copied claim.
@@ -101,7 +125,7 @@ Every record is either:
A document does not stay current by convention alone.
-Before any component, family, design, or architecture record becomes `current`,
+Before any component, family, design, theme, or architecture record becomes `current`,
the repository must support this flow:
1. The record names the code surface that can affect it and the checks that
@@ -183,12 +207,16 @@ flow passes the historical review benchmark and is enforced on pull requests.
- `AGENTS.md` points reviewers to the narrowest relevant record.
- `docs/templates/knowledge/` contains authoring forms.
+- `packages/themes/<theme>/<theme>.spec.md` contains that package theme's
+ canonical record; `docs/themes/README.md` is guidance and an index only.
- `docs/schemas/knowledge/` defines required structure.
- `scripts/check-knowledge.mjs` validates templates, records, and approval
metadata.
- `.github/scripts/change-scope.cjs` identifies pure spec-record changes.
- `.github/workflows/spec-owner-gate.yml` binds approval to the exact pull
- request head and enables auto-merge only for pure spec changes.
+ request head. Theme approval derives from the committed union of
+ `.github/ENGOWNERS` and `.github/DESIGNOWNERS`; record metadata never
+ self-authorizes. The workflow enables auto-merge only for pure spec changes.
## Deciding specs
@@ -225,9 +253,9 @@ work.
## Verification
-| Invariant | Evidence | Failure signal |
-| --------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
-| INV1, INV6 | `scripts/check-knowledge.test.mjs` | An unapproved current record or unmigrated active record passes |
-| INV5, INV7 | `.github/scripts/change-scope.test.mjs` | A template, schema, architecture, code change, unsafe rename, or truncated list qualifies as spec-only |
-| Approval follows the current head | `.github/scripts/spec-owner-decision.test.mjs` | An approval for another commit clears the gate |
-| INV3, INV4 | Blinded historical review benchmark | Reviewer re-asks a settled decision or invents a new one |
+| Invariant | Evidence | Failure signal |
+| --------------------------------- | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
+| INV1, INV6 | `scripts/check-knowledge.test.mjs` | An unapproved current record or unmigrated active record passes |
+| INV5, INV7 | `.github/scripts/change-scope.test.mjs` | A template, schema, guidance, architecture, code change, unsafe rename, or truncated list qualifies as spec-only |
+| Approval follows the current head | `.github/scripts/spec-owner-decision.test.mjs` | An approval for another commit clears the gate, a self-declared owner becomes an approver, or the wrong owner group approves a current theme record |
+| INV3, INV4 | Blinded historical review benchmark | Reviewer re-asks a settled decision or invents a new one |
diff --git a/docs/schemas/knowledge/v2.json b/docs/schemas/knowledge/v2.json
new file mode 100644
index 0000000000..e9b86574f9
--- /dev/null
+++ b/docs/schemas/knowledge/v2.json
@@ -0,0 +1,43 @@
+{
+ "schemaVersion": 2,
+ "extends": 1,
+ "kinds": {
+ "theme": {
+ "template": "docs/templates/knowledge/theme-spec.md",
+ "requiredFrontmatter": [
+ "schema_version",
+ "template_version",
+ "kind",
+ "id",
+ "authority",
+ "approved_by",
+ "approved_at",
+ "review_triggers",
+ "verified_by",
+ "package",
+ "source_theme",
+ "references"
+ ],
+ "requiredSections": [
+ "Intent and audience",
+ "Inheritance and base",
+ "Portable token overrides",
+ "Theme-local role definitions",
+ "Tonal palette definitions",
+ "Component and state mappings",
+ "Compatibility and migration",
+ "Accessibility and contrast evidence",
+ "Build and artifact contract",
+ "Verification map",
+ "Decision log",
+ "Open questions",
+ "Content boundary"
+ ],
+ "currentNonEmptyFields": ["review_triggers", "verified_by"],
+ "requiredNonEmptyStringFields": ["package", "source_theme"],
+ "listFields": ["review_triggers", "verified_by", "references"],
+ "referenceFields": ["references"],
+ "idPattern": "^theme:[a-z0-9]+(?:-[a-z0-9]+)*$"
+ }
+ }
+}
diff --git a/docs/templates/knowledge/theme-spec.md b/docs/templates/knowledge/theme-spec.md
new file mode 100644
index 0000000000..7b953a8482
--- /dev/null
+++ b/docs/templates/knowledge/theme-spec.md
@@ -0,0 +1,66 @@
+---
+schema_version: 2
+template_version: 1
+kind: theme
+id: theme:<package-theme-name>
+authority: draft
+approved_by: null
+approved_at: null
+review_triggers: [tokens, component-mappings, contrast, artifacts]
+verified_by: [<test-or-evidence>]
+package: '@astryxdesign/theme-<name>'
+source_theme: packages/themes/<name>/src/<name>Theme.ts
+references: [architecture:<surface>, design:<contrast-methodology>]
+---
+
+# <Theme name> theme specification
+
+## Intent and audience
+
+## Inheritance and base
+
+## Portable token overrides
+
+## Theme-local role definitions
+
+<!-- Record factual theme-owned roles and evidence. Public theme API proposals belong in a separate system spec. -->
+
+## Tonal palette definitions
+
+<!-- Record factual palette inventory and evidence. Palette generation or artifact APIs belong in a separate system spec. -->
+
+## Component and state mappings
+
+## Compatibility and migration
+
+## Accessibility and contrast evidence
+
+<!-- Link the current cross-theme design record that owns human visual and
+accessibility methodology. This theme owns only its application: selected
+foreground/background or graphical-object pairings, required modes and states,
+exceptions, measured receipts, and known gaps. Do not copy shared methodology or
+measurement-tool implementation here. If no current design record exists, keep
+the dependency in Open questions; a current theme record cannot reference a
+draft or nonexistent record. -->
+
+## Build and artifact contract
+
+## Verification map
+
+| Theme contract | Evidence | Representative states | Failure signal |
+| --------------- | -------------------- | --------------------- | ------------------------------ |
+| `<requirement>` | `<test or artifact>` | `<modes and states>` | `<what regression looks like>` |
+
+## Decision log
+
+## Open questions
+
+## Content boundary
+
+This record owns this theme's intent, selected token/palette mappings, required
+pairings and states, theme-specific exceptions, measured receipts, known gaps,
+compatibility, artifacts, and evidence. A current cross-theme design record owns
+human contrast methodology; shared measurement/tool implementation belongs to
+architecture or tooling. Cross-theme APIs belong to separate architecture or
+system specs. Component behavior belongs to component or family records.
+Consumer syntax and examples belong to consumer docs.
diff --git a/docs/templates/knowledge/versions.json b/docs/templates/knowledge/versions.json
index cdfe7feea9..aab9c9536b 100644
--- a/docs/templates/knowledge/versions.json
+++ b/docs/templates/knowledge/versions.json
@@ -4,5 +4,6 @@
"design": 1,
"family": 1,
"implementation-plan": 1,
- "system-spec": 1
+ "system-spec": 1,
+ "theme": 1
}
diff --git a/docs/themes/README.md b/docs/themes/README.md
new file mode 100644
index 0000000000..853fd17dae
--- /dev/null
+++ b/docs/themes/README.md
@@ -0,0 +1,37 @@
+# Theme specifications
+
+Theme specifications are the canonical owner for decisions that belong to one
+published theme package: its audience and visual intent, inherited base, portable
+token choices, theme-local roles, tonal palette families and selected tones,
+component/state mappings, compatibility, artifact shape, and measured evidence.
+
+Theme specifications are colocated with their package at
+`packages/themes/<theme>/<theme>.spec.md`, analogous to component specs. This
+page is guidance and an index, not a canonical record. Start a record from
+`docs/templates/knowledge/theme-spec.md` and use an id of the form
+`theme:<package-theme-name>` (for example, `theme:neutral`).
+
+Current records:
+
+- [Neutral](../../packages/themes/neutral/neutral.spec.md) — draft
+
+A theme record sits between system theming architecture and consumer/component
+records. It uses one typed `references` list for architecture, design, system,
+and other knowledge relationships rather than separate relation fields:
+
+- architecture and system specs own cross-theme APIs, vocabulary boundaries,
+ inheritance rules, validation, compiler behavior, and shared artifact policy;
+- design records own cross-theme visual and accessibility methodology, including
+ how contrast evidence is judged;
+- architecture/tooling owns shared measurement implementation;
+- package-local theme specs own application of that methodology: selected
+ token/palette mappings, required pairings/states, exceptions, measured receipts,
+ and known gaps;
+- component and family records own observable component behavior; and
+- consumer docs own supported syntax, examples, and usage guidance.
+
+Only `current` records are policy. A draft may link another draft while decisions
+are being developed, but current records may depend only on current records.
+Current theme records require exact-head approval from the committed union of
+`.github/ENGOWNERS` and `.github/DESIGNOWNERS`. Theme records do not declare an
+`owners` field, and record metadata never grants approval rights.
diff --git a/packages/themes/neutral/neutral.spec.md b/packages/themes/neutral/neutral.spec.md
new file mode 100644
index 0000000000..8f0c239c80
--- /dev/null
+++ b/packages/themes/neutral/neutral.spec.md
@@ -0,0 +1,129 @@
+---
+schema_version: 2
+template_version: 1
+kind: theme
+id: theme:neutral
+authority: draft
+approved_by: null
+approved_at: null
+review_triggers:
+ [tokens, palette-values, component-mappings, contrast, artifacts]
+verified_by: [scripts/check-badge-contrast.test.mjs]
+package: '@astryxdesign/theme-neutral'
+source_theme: packages/themes/neutral/src/neutralTheme.ts
+references:
+ [
+ architecture:theme-authoring-contract,
+ architecture:theme-tokens,
+ architecture:theme-compilation,
+ architecture:component-theming-surface,
+ ]
+---
+
+# Neutral theme specification
+
+This draft is a theme-record example and a factual inventory. It does not decide
+local-token, palette-generation, compiler, or artifact APIs; separate system
+specifications own those proposals.
+
+## Intent and audience
+
+Neutral serves builders who want a quiet grayscale foundation with restrained
+surfaces and distinguishable semantic and categorical color. It should remain
+product-neutral while status and interaction states stay recognizable in both
+color modes.
+
+## Inheritance and base
+
+Neutral starts from Astryx core defaults and overrides selected typography,
+motion, radius, shadow, semantic color, syntax, icon, and component values. It
+does not currently extend another published package theme.
+
+## Portable token overrides
+
+The exact shipped values remain in `source_theme`. Neutral owns its grayscale
+canvas/surface hierarchy, near-black/near-white content roles, status and
+categorical selections, neutral boundaries, and syntax choices. Cross-theme token
+vocabulary remains owned by `architecture:theme-tokens`.
+
+## Theme-local role definitions
+
+Current source has no accepted first-class theme-local-role API. Candidate
+Neutral-only repeated meanings from unlanded work include filled accent, success,
+warning, and error status colors and content/interaction colors used on tinted
+surfaces. Their names, authoring API, namespace, inheritance, and validation are
+not decided here; a separate draft system spec must be accepted first.
+
+## Tonal palette definitions
+
+Candidate source work contains complete light and separately tuned dark ramps for
+neutral, red, orange, yellow, green, teal, cyan, blue, purple, and pink. This is
+useful theme-owned inventory and evidence, not a requirement to adopt a palette
+generator or publish palette artifacts. Those cross-theme choices require a
+separate draft system spec.
+
+## Component and state mappings
+
+Current source is the implementation baseline. Candidate mappings under review
+share filled status color across Badge, compact status indicators, Stepper, Table
+row status, and ProgressBar, and preserve legibility of Banner content on tinted
+surfaces. This record does not change which component states exist or authorize
+unlanded mappings.
+
+## Compatibility and migration
+
+This knowledge-only record changes no package output. Existing Neutral authoring,
+portable token overrides, runtime behavior, and package exports remain unchanged.
+Any future API adoption is optional and requires its own accepted system spec,
+implementation evidence, compatibility plan, and release note.
+
+## Accessibility and contrast evidence
+
+A current cross-theme design record for contrast methodology does not yet exist,
+so this draft does not select or restate a methodology. The future record is an
+unresolved dependency and therefore is not listed in frontmatter.
+
+Current Neutral-specific receipts include the Badge contrast check and pairings
+documented beside Neutral source. Candidate mappings still need receipts for the
+actual light/dark and interaction states they affect. This record will own those
+pairings, exceptions, measurements, and known gaps after the shared methodology
+is current; it will not copy the methodology or shared measurement-tool
+implementation.
+
+## Build and artifact contract
+
+The package manifest and existing build tests define Neutral's current runtime,
+CSS, declaration, and export outputs. This record does not require new generated
+palette or local-token artifacts.
+
+## Verification map
+
+| Theme contract | Evidence | Representative states | Failure signal |
+| ------------------------- | ------------------------------------------ | ------------------------------------------ | --------------------------------------------------------------- |
+| Current value inventory | Neutral source and theme tests | light/dark token families | Source and record disagree about a theme-owned meaning. |
+| Component mappings | Theme tests and rendered evidence | status and interaction states | A mapped state loses its intended distinction. |
+| Contrast | Badge check plus rendered component matrix | light/dark and interactive states | A required pairing falls below its threshold. |
+| Existing package contract | Theme build, package, and resolution tests | runtime, CSS, declarations, public exports | This record implies an artifact that the package does not ship. |
+
+## Decision log
+
+No theme decision is accepted while this record has `authority: draft`.
+
+## Open questions
+
+- Which candidate Neutral values and component mappings should become current
+ after their cross-theme enabling APIs, if any, are settled separately?
+- What current design record should own the cross-theme contrast methodology
+ before Neutral can rely on it through `references`?
+- Which rendered pairings and interaction states still need theme-specific
+ measured receipts?
+
+## Content boundary
+
+This record owns Neutral's intent, factual value inventory, selected mappings,
+required pairings/states, theme-specific exceptions, measured receipts, known
+gaps, compatibility, and package facts. A future current design record owns the
+cross-theme contrast methodology; shared measurement implementation belongs to
+architecture/tooling. This record does not define cross-theme local-token or
+palette APIs. Component/family records own observable behavior, and consumer
+docs own supported syntax and examples.
diff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjs
index 18a4299ac2..113540a5bc 100644
--- a/scripts/check-knowledge.mjs
+++ b/scripts/check-knowledge.mjs
@@ -64,7 +64,9 @@ export function parseKnowledgeDocument(content, filePath = '<document>') {
block.push(lines[index + 1].trim());
index += 1;
}
- if (block[0] === '[' && block.at(-1) === ']') {
+ if (block.length === 1 && /^\[.*\]$/.test(block[0])) {
+ raw = block[0];
+ } else 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(',')}]`;
@@ -108,6 +110,55 @@ function matchingFiles(directory, predicate) {
.map(entry => path.join(directory, entry.name));
}
+function matchingFilesRecursively(directory, predicate) {
+ if (!fs.existsSync(directory)) return [];
+ const matches = [];
+ const pending = [directory];
+ while (pending.length > 0) {
+ const current = pending.pop();
+ for (const entry of fs.readdirSync(current, {withFileTypes: true})) {
+ const candidate = path.join(current, entry.name);
+ if (entry.isDirectory()) pending.push(candidate);
+ else if (entry.isFile() && predicate(entry.name)) matches.push(candidate);
+ }
+ }
+ return matches;
+}
+
+export function discoverThemeRecordCandidates(root = DEFAULT_ROOT) {
+ const records = [];
+ const problems = [];
+
+ for (const filePath of matchingFiles(
+ path.join(root, 'docs/themes'),
+ name => name.endsWith('.md') && name !== 'README.md',
+ )) {
+ records.push(filePath);
+ problems.push(
+ `${path.relative(root, filePath)}: theme records must be placed at packages/themes/<theme>/<theme>.spec.md; docs/themes contains guidance only.`,
+ );
+ }
+
+ for (const themeDirectory of immediateDirectories(
+ path.join(root, 'packages/themes'),
+ )) {
+ const themeName = path.basename(themeDirectory);
+ const expectedPath = path.join(themeDirectory, `${themeName}.spec.md`);
+ for (const filePath of matchingFilesRecursively(themeDirectory, name =>
+ name.endsWith('.spec.md'),
+ )) {
+ records.push(filePath);
+ if (filePath !== expectedPath) {
+ problems.push(
+ `${path.relative(root, filePath)}: theme record must be placed exactly at packages/themes/${themeName}/${themeName}.spec.md.`,
+ );
+ }
+ }
+ }
+
+ return {records: records.sort(), problems};
+}
+
export function discoverKnowledgeRecords(root = DEFAULT_ROOT) {
const records = [];
@@ -135,6 +186,8 @@ export function discoverKnowledgeRecords(root = DEFAULT_ROOT) {
),
);
+ records.push(...discoverThemeRecordCandidates(root).records);
+
for (const packageName of ['core', 'lab']) {
for (const componentDirectory of immediateDirectories(
path.join(root, `packages/${packageName}/src`),
@@ -496,6 +549,7 @@ function validateAgainstSchema(
isTemplate,
currentTemplateVersion,
designApprovalOwners = [],
+ themeApprovalOwners = [],
) {
const problems = [...document.problems];
const {frontmatter, sections} = document;
@@ -534,6 +588,12 @@ function validateAgainstSchema(
);
}
+ for (const field of kindSchema.listFields ?? []) {
+ if (!Array.isArray(frontmatter.get(field))) {
+ problems.push(`${filePath}: ${field} must be a list.`);
+ }
+ }
+
if (isTemplate) {
if (templateVersion !== currentTemplateVersion) {
problems.push(
@@ -558,9 +618,28 @@ function validateAgainstSchema(
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.`);
+ for (const field of kindSchema.requiredNonEmptyStringFields ?? []) {
+ const value = frontmatter.get(field);
+ if (typeof value !== 'string' || value.trim().length === 0) {
+ problems.push(`${filePath}: ${field} must be a non-empty string.`);
+ }
+ }
+
+ const id = frontmatter.get('id');
+ if (
+ kindSchema.idPattern &&
+ (typeof id !== 'string' || !new RegExp(kindSchema.idPattern).test(id))
+ ) {
+ problems.push(
+ `${filePath}: id must match ${JSON.stringify(kindSchema.idPattern)}.`,
+ );
+ }
+
+ if (kindSchema.requiredFrontmatter.includes('owners')) {
+ 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');
@@ -583,7 +662,9 @@ function validateAgainstSchema(
const authorizedOwners =
kind === 'design'
? [...new Set([...schema.approvalOwners, ...designApprovalOwners])]
- : schema.approvalOwners;
+ : kind === 'theme'
+ ? themeApprovalOwners
+ : schema.approvalOwners;
if (!authorizedOwners.includes(approvedBy)) {
problems.push(
`${filePath}: current records require approved_by to name an authorized owner.`,
@@ -689,9 +770,46 @@ function currentSchemaFiles(root) {
);
}
+export function composeKnowledgeSchemas(rawSchemas) {
+ const composed = new Map();
+ const latestKindVersions = new Map();
+
+ function compose(version, stack = []) {
+ if (composed.has(version)) return composed.get(version);
+ const entry = rawSchemas.get(version);
+ if (!entry) throw new Error(`Schema v${version} does not exist.`);
+ if (stack.includes(version))
+ throw new Error('Knowledge schema extends cycle.');
+ const parentVersion = entry.schema.extends;
+ const parent =
+ parentVersion == null
+ ? null
+ : compose(parentVersion, [...stack, version]);
+ const schema = parent
+ ? {
+ ...parent.schema,
+ ...entry.schema,
+ kinds: {...parent.schema.kinds, ...(entry.schema.kinds ?? {})},
+ }
+ : entry.schema;
+ const result = {...entry, schema};
+ composed.set(version, result);
+ return result;
+ }
+
+ for (const version of [...rawSchemas.keys()].sort((a, b) => a - b)) {
+ const entry = rawSchemas.get(version);
+ compose(version);
+ for (const kind of Object.keys(entry.schema.kinds ?? {})) {
+ latestKindVersions.set(kind, version);
+ }
+ }
+ return {schemas: composed, latestKindVersions};
+}
+
export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
const schemaDirectory = path.join(root, 'docs/schemas/knowledge');
- const schemas = new Map(
+ const rawSchemas = new Map(
matchingFiles(schemaDirectory, name => /^v[0-9]+\.json$/.test(name)).map(
schemaPath => {
const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8'));
@@ -707,11 +825,11 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
},
),
);
- if (schemas.size === 0)
+ if (rawSchemas.size === 0)
return ['docs/schemas/knowledge: no versioned schemas found.'];
+ const {schemas, latestKindVersions} = composeKnowledgeSchemas(rawSchemas);
const latestVersion = Math.max(...schemas.keys());
- const {schema, schemaPath} = schemas.get(latestVersion);
- const relativeSchemaPath = path.relative(root, schemaPath);
+ const {schema} = schemas.get(latestVersion);
const templateVersions = JSON.parse(
fs.readFileSync(
path.join(root, 'docs/templates/knowledge/versions.json'),
@@ -722,12 +840,21 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
const designApprovalOwners = fs.existsSync(designOwnersPath)
? parseOwnerFile(fs.readFileSync(designOwnersPath, 'utf8'))
: [];
- const problems = [];
+ const engineeringOwnersPath = path.join(root, '.github/ENGOWNERS');
+ const engineeringApprovalOwners = fs.existsSync(engineeringOwnersPath)
+ ? parseOwnerFile(fs.readFileSync(engineeringOwnersPath, 'utf8'))
+ : [];
+ const themeApprovalOwners = [
+ ...new Set([...engineeringApprovalOwners, ...designApprovalOwners]),
+ ];
+ const problems = [...discoverThemeRecordCandidates(root).problems];
const ids = new Map();
const records = [];
const delegations = [];
for (const [kind, kindSchema] of Object.entries(schema.kinds)) {
+ const kindVersion = latestKindVersions.get(kind);
+ const kindSchemaEntry = schemas.get(kindVersion);
if (
!Number.isInteger(templateVersions[kind]) ||
templateVersions[kind] < 1
@@ -751,12 +878,13 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
problems.push(
...validateAgainstSchema(
template,
- schema,
- relativeSchemaPath,
+ kindSchemaEntry.schema,
+ path.relative(root, kindSchemaEntry.schemaPath),
kindSchema.template,
true,
templateVersions[kind],
designApprovalOwners,
+ themeApprovalOwners,
),
);
if (template.frontmatter.get('kind') !== kind) {
@@ -785,14 +913,17 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
false,
templateVersions[document.frontmatter.get('kind')],
designApprovalOwners,
+ themeApprovalOwners,
),
);
const authority = document.frontmatter.get('authority');
const isActiveRecord =
versionedSchema.schema.activeAuthorities.includes(authority);
- if (isActiveRecord && recordVersion !== latestVersion) {
+ const kind = document.frontmatter.get('kind');
+ const latestKindVersion = latestKindVersions.get(kind);
+ if (isActiveRecord && recordVersion !== latestKindVersion) {
problems.push(
- `${filePath}: active records must use latest schema_version ${latestVersion}.`,
+ `${filePath}: active ${kind} records must use latest schema_version ${latestKindVersion} for that kind.`,
);
}
if (document.frontmatter.get('kind') === 'component') {
diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjs
index fa72572973..ca30a40249 100644
--- a/scripts/check-knowledge.test.mjs
+++ b/scripts/check-knowledge.test.mjs
@@ -5,6 +5,8 @@ import os from 'node:os';
import path from 'node:path';
import {afterEach, describe, expect, it} from 'vitest';
import {
+ composeKnowledgeSchemas,
+ discoverKnowledgeRecords,
parseAnatomyThemingBlock,
parseKnowledgeDocument,
validateAnatomyThemingMap,
@@ -26,24 +28,35 @@ function fixtureRoot() {
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 version of ['v1.json', 'v2.json']) {
+ fs.copyFileSync(
+ path.join(repoRoot, `docs/schemas/knowledge/${version}`),
+ path.join(root, `docs/schemas/knowledge/${version}`),
+ );
+ }
for (const relative of [
'docs/specs',
'docs/families',
'docs/architecture',
+ 'docs/themes',
'packages/core/src',
'packages/lab/src',
]) {
fs.mkdirSync(path.join(root, relative), {recursive: true});
}
+ for (const relative of [
+ 'packages/themes/neutral',
+ 'packages/themes/duplicate',
+ ]) {
+ 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'),
- );
+ for (const ownerFile of ['DESIGNOWNERS', 'ENGOWNERS']) {
+ fs.copyFileSync(
+ path.join(repoRoot, `.github/${ownerFile}`),
+ path.join(root, `.github/${ownerFile}`),
+ );
+ }
return root;
}
@@ -101,6 +114,102 @@ function componentRecord(overrides = {}) {
return `---\n${frontmatter}\n---\n\n# Button component contract\n\n${sections}\n`;
}
+function themeRecord(overrides = {}) {
+ const values = {
+ schema_version: '2',
+ template_version: '1',
+ kind: 'theme',
+ id: 'theme:neutral',
+ authority: 'draft',
+ approved_by: 'null',
+ approved_at: 'null',
+ review_triggers: '[tokens]',
+ verified_by: '[theme.test.ts]',
+ package: "'@astryxdesign/theme-neutral'",
+ source_theme: 'packages/themes/neutral/src/neutralTheme.ts',
+ references: '[architecture:theme-test]',
+ ...overrides,
+ };
+ const frontmatter = Object.entries(values)
+ .map(([key, value]) => `${key}: ${value}`)
+ .join('\n');
+ const sections = [
+ 'Intent and audience',
+ 'Inheritance and base',
+ 'Portable token overrides',
+ 'Theme-local role definitions',
+ 'Tonal palette definitions',
+ 'Component and state mappings',
+ 'Compatibility and migration',
+ 'Accessibility and contrast evidence',
+ 'Build and artifact contract',
+ 'Verification map',
+ 'Decision log',
+ 'Open questions',
+ 'Content boundary',
+ ]
+ .map(section => `## ${section}\n\nBody.`)
+ .join('\n\n');
+ return `---\n${frontmatter}\n---\n\n# Neutral theme specification\n\n${sections}\n`;
+}
+
+function systemSpecRecord(overrides = {}) {
+ const values = {
+ schema_version: '1',
+ template_version: '1',
+ kind: 'system-spec',
+ id: 'spec:AST-900',
+ authority: 'current',
+ archive_reason: 'null',
+ superseded_by: 'null',
+ approved_by: 'cixzhang',
+ approved_at: '2026-08-31',
+ phase: 'accepted',
+ owners: '[cixzhang]',
+ affects_architecture: '[]',
+ affects_families: '[]',
+ affects_contributing: '[]',
+ affects_consumer_docs: '[]',
+ ...overrides,
+ };
+ const frontmatter = Object.entries(values)
+ .map(([key, value]) => `${key}: ${value}`)
+ .join('\n');
+ const sections = [
+ 'Intent',
+ 'Non-goals',
+ 'Requirements',
+ 'Current-state impact',
+ 'Verification',
+ 'Decision log',
+ 'Open questions',
+ ]
+ .map(section => `## ${section}\n\nBody.`)
+ .join('\n\n');
+ return `---\n${frontmatter}\n---\n\n# Fixture system spec\n\n${sections}\n`;
+}
+
+function writeSystemSpec(root, directoryName, record) {
+ const directory = path.join(root, `docs/specs/${directoryName}`);
+ fs.mkdirSync(directory);
+ fs.writeFileSync(path.join(directory, 'spec.md'), record);
+}
+
+function writeCurrentArchitecture(root) {
+ const template = fs.readFileSync(
+ path.join(root, 'docs/templates/knowledge/architecture.md'),
+ 'utf8',
+ );
+ fs.writeFileSync(
+ path.join(root, 'docs/architecture/theme-test.md'),
+ template
+ .replace('id: architecture:<surface>', 'id: architecture:theme-test')
+ .replace('authority: draft', 'authority: current')
+ .replace('approved_by: null', 'approved_by: cixzhang')
+ .replace('approved_at: null', 'approved_at: 2026-08-31'),
+ );
+}
+
function anatomyThemingBlock(mapping) {
return `### Theming anatomy\n\n<!-- anatomy-theming:v1 -->\n\`\`\`json\n${JSON.stringify(mapping, null, 2)}\n\`\`\``;
}
@@ -143,6 +252,45 @@ afterEach(() => {
});
describe('schema evolution', () => {
+ it('tracks latest schema versions per kind', () => {
+ const raw = new Map([
+ [
+ 1,
+ {
+ schema: {schemaVersion: 1, kinds: {component: {marker: 'v1'}}},
+ schemaPath: 'v1.json',
+ },
+ ],
+ [
+ 2,
+ {
+ schema: {
+ schemaVersion: 2,
+ extends: 1,
+ kinds: {theme: {marker: 'v2'}},
+ },
+ schemaPath: 'v2.json',
+ },
+ ],
+ [
+ 3,
+ {
+ schema: {
+ schemaVersion: 3,
+ extends: 2,
+ kinds: {component: {marker: 'v3'}},
+ },
+ schemaPath: 'v3.json',
+ },
+ ],
+ ]);
+ const {schemas, latestKindVersions} = composeKnowledgeSchemas(raw);
+ expect(schemas.get(2).schema.kinds.component.marker).toBe('v1');
+ expect(schemas.get(2).schema.kinds.theme.marker).toBe('v2');
+ expect(latestKindVersions.get('theme')).toBe(2);
+ expect(latestKindVersions.get('component')).toBe(3);
+ });
+
it('allows appending a higher schema version', () => {
expect(
validateSchemaEvolution(
@@ -605,6 +753,255 @@ describe('knowledge validation', () => {
expect(await validateKnowledgeRoot(root)).toEqual([]);
});
+ it('discovers only the exact canonical package-local theme record without placement errors', async () => {
+ const root = fixtureRoot();
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord(),
+ );
+ fs.writeFileSync(
+ path.join(root, 'docs/themes/README.md'),
+ '# Guidance only\n',
+ );
+
+ const discovered = discoverKnowledgeRecords(root).map(filePath =>
+ path.relative(root, filePath),
+ );
+ expect(discovered).toContain('packages/themes/neutral/neutral.spec.md');
+ expect(discovered).not.toContain('docs/themes/README.md');
+ expect(await validateKnowledgeRoot(root)).toEqual([]);
+ });
+
+ it.each([
+ [
+ 'docs guidance directory',
+ 'docs/themes/neutral.md',
+ /theme records must be placed at packages\/themes\/<theme>\/<theme>\.spec\.md/,
+ ],
+ [
+ 'wrong package filename',
+ 'packages/themes/neutral/Theme.spec.md',
+ /theme record must be placed exactly at packages\/themes\/neutral\/neutral\.spec\.md/,
+ ],
+ [
+ 'nested package path',
+ 'packages/themes/neutral/subdir/neutral.spec.md',
+ /theme record must be placed exactly at packages\/themes\/neutral\/neutral\.spec\.md/,
+ ],
+ ])(
+ 'rejects a theme-shaped record in the %s',
+ async (_name, relative, error) => {
+ const root = fixtureRoot();
+ const absolute = path.join(root, relative);
+ fs.mkdirSync(path.dirname(absolute), {recursive: true});
+ fs.writeFileSync(absolute, themeRecord());
+
+ const discovered = discoverKnowledgeRecords(root).map(filePath =>
+ path.relative(root, filePath),
+ );
+ expect(discovered).toContain(relative);
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(error);
+ },
+ );
+
+ it('accepts derived repo-owner approval on a current theme record', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'rubyycheung',
+ approved_at: '2026-08-31',
+ }),
+ );
+
+ expect(await validateKnowledgeRoot(root)).toEqual([]);
+ });
+
+ it('does not inherit v1 approvalOwners for theme approval', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ for (const ownerFile of ['ENGOWNERS', 'DESIGNOWNERS']) {
+ const filePath = path.join(root, `.github/${ownerFile}`);
+ fs.writeFileSync(
+ filePath,
+ fs.readFileSync(filePath, 'utf8').replace(/@cixzhang\b/g, ''),
+ );
+ }
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'cixzhang',
+ approved_at: '2026-08-31',
+ }),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /approved_by to name an authorized owner/,
+ );
+ });
+
+ it('accepts an ENGOWNER approval on a current theme record', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'czarandy',
+ approved_at: '2026-08-31',
+ }),
+ );
+
+ expect(await validateKnowledgeRoot(root)).toEqual([]);
+ });
+
+ it('rejects a scalar references field on a current theme', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'rubyycheung',
+ approved_at: '2026-08-31',
+ references: 'spec:AST-006',
+ }),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /references must be a list/,
+ );
+ });
+
+ it('does not let a self-declared theme owner approve a current record', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ additional_owners: '[self-declared-owner]',
+ approved_by: 'self-declared-owner',
+ approved_at: '2026-08-31',
+ }),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /approved_by to name an authorized owner/,
+ );
+ });
+
+ it('rejects an unresolved reference from a current theme record', async () => {
+ const root = fixtureRoot();
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'rubyycheung',
+ approved_at: '2026-08-31',
+ references: '[architecture:missing]',
+ }),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /references reference architecture:missing does not resolve/,
+ );
+ });
+
+ it('rejects an unresolved typed reference list from a current theme', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'rubyycheung',
+ approved_at: '2026-08-31',
+ references: '[spec:missing]',
+ }),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /references reference spec:missing does not resolve/,
+ );
+ });
+
+ it('rejects a current theme that relies on a draft deciding spec', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ const specDirectory = path.join(root, 'docs/specs/AST-006');
+ fs.mkdirSync(specDirectory);
+ const systemTemplate = fs.readFileSync(
+ path.join(root, 'docs/templates/knowledge/system-spec.md'),
+ 'utf8',
+ );
+ fs.writeFileSync(
+ path.join(specDirectory, 'spec.md'),
+ systemTemplate.replace('id: spec:AST-000', 'id: spec:AST-006'),
+ );
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'rubyycheung',
+ approved_at: '2026-08-31',
+ references: '[spec:AST-006]',
+ }),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /current records may not rely on non-current spec:AST-006/,
+ );
+ });
+
+ it('accepts a current theme list reference to a current deciding spec', async () => {
+ const root = fixtureRoot();
+ writeCurrentArchitecture(root);
+ writeSystemSpec(root, 'AST-006', systemSpecRecord({id: 'spec:AST-006'}));
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({
+ authority: 'current',
+ approved_by: 'rubyycheung',
+ approved_at: '2026-08-31',
+ references: '[spec:AST-006]',
+ }),
+ );
+
+ expect(await validateKnowledgeRoot(root)).toEqual([]);
+ });
+
+ it('rejects duplicate theme ids', async () => {
+ const root = fixtureRoot();
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord(),
+ );
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/duplicate/duplicate.spec.md'),
+ themeRecord(),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /duplicate id theme:neutral/,
+ );
+ });
+
+ it('rejects a theme id outside the package-theme-name format', async () => {
+ const root = fixtureRoot();
+ fs.writeFileSync(
+ path.join(root, 'packages/themes/neutral/neutral.spec.md'),
+ themeRecord({id: 'theme:Neutral Theme'}),
+ );
+
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /id must match/,
+ );
+ });
+
it('rejects duplicate authority fields', async () => {
const root = fixtureRoot();
const directory = path.join(root, 'packages/core/src/Button');
@@ -702,7 +1099,7 @@ describe('knowledge validation', () => {
componentRecord({schema_version: '0'}),
);
expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
- /active records must use latest schema_version 1/,
+ /active component records must use latest schema_version 1 for that kind/,
);
});