Skip to content

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

TypeScript

fix(knowledge): gate, check, and route platform records under docs/specs/components (#9279)

Cindy Zhangf2e9b9254472
diff --git a/.github/scripts/change-scope.cjs b/.github/scripts/change-scope.cjs
index d0f105e382..3148fd31cf 100644
--- a/.github/scripts/change-scope.cjs
+++ b/.github/scripts/change-scope.cjs
@@ -7,6 +7,7 @@
const {
isComponentSpecRecordPath,
isLegacyComponentSpecPath,
+ isPlatformComponentSpecPath,
} = require('./knowledge-paths.cjs');
/**
@@ -114,6 +115,9 @@ const KNOWLEDGE_RECORD_PATTERNS = [
function isSpecRecordPath(filePath) {
return (
isComponentSpecRecordPath(filePath) ||
+ // A platform record (`<Root>/<PublicName>.swift.spec.md`) is a component
+ // record for its language, gated like the core record beside it.
+ isPlatformComponentSpecPath(filePath) ||
SPEC_RECORD_PATTERNS.some(pattern => pattern.test(filePath))
);
}
diff --git a/.github/scripts/change-scope.test.mjs b/.github/scripts/change-scope.test.mjs
index 5451a0d724..e503e35dc8 100644
--- a/.github/scripts/change-scope.test.mjs
+++ b/.github/scripts/change-scope.test.mjs
@@ -31,6 +31,40 @@ describe('spec-only change scope', () => {
expect(result.specOnly).toBe(true);
});
+ it('treats a platform record beside the core record as a component record', () => {
+ const result = classifyChanges([
+ {filename: 'docs/specs/components/TextInput/TextInput.swift.spec.md'},
+ ]);
+ expect(result.touchesKnowledgeRecords).toBe(true);
+ expect(result.specOnly).toBe(true);
+ expect(result.surfaces).toEqual([SURFACES.KNOWLEDGE]);
+ });
+
+ it('owner-gates a platform record changed with its Swift view', () => {
+ const result = classifyChanges([
+ {filename: 'docs/specs/components/Button/Button.swift.spec.md'},
+ {filename: 'packages/native/apple/Sources/Astryx/Button/Button.swift'},
+ ]);
+ expect(result.touchesKnowledgeRecords).toBe(true);
+ expect(result.specOnly).toBe(false);
+ });
+
+ it('does not owner-gate a Swift view change that leaves its platform record alone', () => {
+ const result = classifyChanges([
+ {filename: 'packages/native/apple/Sources/Astryx/Button/Button.swift'},
+ ]);
+ expect(result.touchesKnowledgeRecords).toBe(false);
+ });
+
+ it('does not treat an unsupported language or a misplaced platform file as a record', () => {
+ for (const filename of [
+ 'docs/specs/components/Button/Button.kotlin.spec.md',
+ 'docs/specs/components/Button/modules/Button.swift.spec.md',
+ ]) {
+ expect(classifyChanges([{filename}]).specOnly).toBe(false);
+ }
+ });
+
it('owner-gates architecture records without granting the spec-only fast path', () => {
const result = classifyChanges([
{filename: 'docs/architecture/knowledge-contracts.md'},
diff --git a/.github/scripts/knowledge-paths.cjs b/.github/scripts/knowledge-paths.cjs
index 8e834578f5..563795c804 100644
--- a/.github/scripts/knowledge-paths.cjs
+++ b/.github/scripts/knowledge-paths.cjs
@@ -31,6 +31,14 @@ const COMPONENT_SPEC_ROOT = 'docs/specs/components';
*/
const PLATFORM_SPEC_LANGUAGES = Object.freeze(['swift']);
+/**
+ * Where each platform language keeps its component code, as
+ * `<root>/<Module>/<ComponentRoot>/…`.
+ */
+const PLATFORM_SOURCE_ROOTS = Object.freeze({
+ swift: 'packages/native/apple/Sources',
+});
+
const IGNORED_COMPONENT_KNOWLEDGE_SEGMENTS = new Set([
'__fixtures__',
'__generated__',
@@ -150,6 +158,29 @@ function isPlatformComponentSpecPath(filePath) {
return classifyPlatformComponentSpecPath(filePath) !== null;
}
+/**
+ * A platform language's component code file:
+ * `<source root>/<Module>/<ComponentRoot>/…/<file>`. Returns the language,
+ * component root, and file stem; null for any other path, a spec file, or a
+ * file in an ignored directory.
+ */
+function locatePlatformComponentSource(filePath) {
+ const normalized = normalizePath(filePath);
+ if (normalized.endsWith('.md')) return null;
+ for (const [language, sourceRoot] of Object.entries(PLATFORM_SOURCE_ROOTS)) {
+ if (!normalized.startsWith(`${sourceRoot}/`)) continue;
+ const segments = normalized.slice(sourceRoot.length + 1).split('/');
+ if (segments.length < 3) return null;
+ if (segments.some(isIgnoredComponentKnowledgeSegment)) return null;
+ return {
+ language,
+ componentRoot: segments[1],
+ stem: segments.at(-1).split('.')[0],
+ };
+ }
+ return null;
+}
+
/**
* Exact-case directory entries, so a case-insensitive file system agrees with
* CI. Read fresh on every call: callers resolve a few hundred records at most,
@@ -315,6 +346,7 @@ module.exports = {
COMPONENT_PACKAGE_NAMES,
COMPONENT_SPEC_ROOT,
IGNORED_COMPONENT_KNOWLEDGE_SEGMENTS,
+ PLATFORM_SOURCE_ROOTS,
PLATFORM_SPEC_LANGUAGES,
classifyComponentKnowledgePath,
classifyPlatformComponentSpecPath,
@@ -324,5 +356,6 @@ module.exports = {
isLegacyComponentSpecPath,
isPlatformComponentSpecPath,
locateComponentKnowledgePath,
+ locatePlatformComponentSource,
resolveComponentPackage,
};
diff --git a/.github/scripts/knowledge-paths.test.mjs b/.github/scripts/knowledge-paths.test.mjs
index 2b0ab2d33d..19e71545f7 100644
--- a/.github/scripts/knowledge-paths.test.mjs
+++ b/.github/scripts/knowledge-paths.test.mjs
@@ -15,6 +15,7 @@ const {
isLegacyComponentSpecPath,
isPlatformComponentSpecPath,
locateComponentKnowledgePath,
+ locatePlatformComponentSource,
} = require('./knowledge-paths.cjs');
const roots = [];
@@ -109,6 +110,27 @@ describe('component knowledge paths', () => {
}
});
+ it("locates a platform language's component code by its component root", () => {
+ expect(
+ locatePlatformComponentSource(
+ 'packages/native/apple/Sources/Astryx/Avatar/AvatarStatusDot.swift',
+ ),
+ ).toEqual({
+ language: 'swift',
+ componentRoot: 'Avatar',
+ stem: 'AvatarStatusDot',
+ });
+ for (const filePath of [
+ 'packages/native/apple/Sources/Astryx/Astryx.swift',
+ 'packages/native/apple/Sources/Astryx/Avatar/Avatar.spec.md',
+ 'packages/native/apple/Sources/Astryx/Avatar/tests/Avatar.swift',
+ 'packages/native/apple/Tests/AstryxTests/AvatarTests.swift',
+ 'packages/core/src/Avatar/Avatar.tsx',
+ ]) {
+ expect(locatePlatformComponentSource(filePath)).toBeNull();
+ }
+ });
+
it('recognizes a spec left at a pre-move record location', () => {
for (const filePath of [
'packages/core/src/Button/Button.spec.md',
diff --git a/.github/scripts/spec-owner-decision.test.mjs b/.github/scripts/spec-owner-decision.test.mjs
index 282ff66e94..18f3df9466 100644
--- a/.github/scripts/spec-owner-decision.test.mjs
+++ b/.github/scripts/spec-owner-decision.test.mjs
@@ -87,6 +87,33 @@ describe('spec owner decision', () => {
expect(requiresOwnerApproval([], {complete: false})).toBe(true);
});
+ it('requires an engineering owner when a platform record becomes current', () => {
+ const swiftRecord = authority =>
+ [
+ '---',
+ 'schema_version: 3',
+ 'kind: component',
+ 'id: component:swift/TextInput',
+ 'platform_of: component:TextInput',
+ `authority: ${authority}`,
+ '---',
+ '',
+ '## Purpose',
+ '',
+ 'A text field.',
+ '',
+ ].join('\n');
+ expect(
+ requiredApprovalGroups([
+ {
+ path: 'docs/specs/components/TextInput/TextInput.swift.spec.md',
+ baseContent: swiftRecord('draft'),
+ headContent: swiftRecord('current'),
+ },
+ ]),
+ ).toEqual({spec: true, design: false, theme: false});
+ });
+
it('parses DESIGNOWNERS without comment examples', () => {
expect(
parseOwnerFile(`
diff --git a/.github/scripts/spec-owner-reconcile.test.mjs b/.github/scripts/spec-owner-reconcile.test.mjs
index 5f723601f9..9da4f65777 100644
--- a/.github/scripts/spec-owner-reconcile.test.mjs
+++ b/.github/scripts/spec-owner-reconcile.test.mjs
@@ -609,6 +609,70 @@ describe('spec owner workflow reconciliation', () => {
},
);
+ it('keeps a Swift platform record made current pending without exact-head approval', async () => {
+ const harness = createHarness({
+ changedFile: {
+ filename: 'docs/specs/components/TextInput/TextInput.swift.spec.md',
+ status: 'modified',
+ },
+ baseContent:
+ '---\nkind: component\nid: component:swift/TextInput\nauthority: draft\n---\n',
+ headContent:
+ '---\nkind: component\nid: component:swift/TextInput\nauthority: current\n---\n',
+ });
+
+ await run(harness, context({runId: 100n, action: 'synchronize'}));
+
+ expect(latestReviewGate(harness.state)).toMatchObject({state: 'pending'});
+ expect(latestGateStatus(harness.state)).toMatchObject({
+ state: 'pending',
+ description: 'Mirrors review-required · spec waiting (eng)',
+ });
+ expect(
+ harness.state.calls.some(call =>
+ call.includes('No knowledge records changed'),
+ ),
+ ).toBe(false);
+ expect(harness.state.calls).not.toContain('enable-auto-merge');
+ });
+
+ it('leaves the gate clear when a Swift view changes and its platform record does not', async () => {
+ const harness = createHarness({
+ changedFile: {
+ filename:
+ 'packages/native/apple/Sources/Astryx/TextInput/TextInput.swift',
+ status: 'modified',
+ },
+ });
+
+ await run(harness, context({runId: 100n, action: 'synchronize'}));
+
+ expect(latestGateStatus(harness.state)).toMatchObject({state: 'success'});
+ expect(harness.state.calls).not.toContain('enable-auto-merge');
+ });
+
+ it('needs no owner approval for an edit to a draft Swift platform record', async () => {
+ const draft =
+ '---\nkind: component\nid: component:swift/TextInput\nauthority: draft\n---\n';
+ const harness = createHarness({
+ changedFile: {
+ filename: 'docs/specs/components/TextInput/TextInput.swift.spec.md',
+ status: 'modified',
+ },
+ baseContent: draft,
+ headContent: `${draft}\n## Intent\n\nUpdated.\n`,
+ });
+
+ await run(harness, context({runId: 100n, action: 'synchronize'}));
+
+ expect(latestReviewGate(harness.state).state).toBe('success');
+ 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'},
diff --git a/docs/architecture/knowledge-contracts.md b/docs/architecture/knowledge-contracts.md
index 7230f0646c..5071d4f441 100644
--- a/docs/architecture/knowledge-contracts.md
+++ b/docs/architecture/knowledge-contracts.md
@@ -1146,12 +1146,12 @@ needs its own spec location.
| DEC-14 | `.github/scripts/spec-owner-reconcile.test.mjs`, `.github/scripts/spec-owner-decision.test.mjs`, and `.github/scripts/spec-owner-workflow.test.mjs` | A non-spec commit, base merge, rebase, or status flip resets approval; changed spec text or a new spec path keeps it; a command naming other spec content, a reaction, a non-owner act, or an author review approves; `review-required` succeeds while spec approval is missing or before the spec decision is published; a revoke or request for changes naming other spec content is ignored; a missing approval reports failure; or an evaluation leaves its head without a terminal state |
| DEC-11 | `.github/scripts/review-signal-decision.test.mjs`, `.github/scripts/review-clear-workflow.test.mjs`, and `.github/scripts/review-signal-workflow.test.mjs` | An app approval clears a read-only or fork author or an earlier head; a later app request for changes or dismissal leaves the gate clear; an app approval overrides an ENGOWNER request for changes; or an unset app or unreadable permission clears the gate |
-| Invariant | Evidence | Failure signal |
-| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| INV22–INV24 | Contributor/reviewer evidence inventory; public-link and byte verification; retained remote refs; unchanged fixture/baseline/media paths | Disposable captures enter the source tree, cleanup loses a referenced image, a temporary branch is called durable, or storage changes overwrite an owner's proof or retention contract |
-| INV25, INV26, DEC-12 | `scripts/specs-for-file.test.mjs`, `scripts/check-knowledge.test.mjs`, and `pnpm check:knowledge` | A current record is reached by no tracked non-record path, a lookup infers a link from a name, a pattern matches nothing or the whole repository, or a pattern match widens a claim or outranks a narrower owner |
-| INV27, DEC-13 | `scripts/check-knowledge.test.mjs` and `pnpm check:knowledge` | A `*.spec.md` file or a Markdown file under a `specs` directory without valid record frontmatter, outside its kind's location, or following a package-local template passes |
-| DEC-15 | `.github/scripts/knowledge-paths.test.mjs`, `scripts/check-knowledge.test.mjs`, `scripts/specs-for-file.test.mjs`, and `pnpm check:knowledge` | A component or module record outside `docs/specs/components/<ComponentRoot>/`, a `*.spec.md` left in a component package's source tree or beside a Swift view, a record matched to the wrong package when two share a root, or a record whose component root no registered package's source tree has |
+| Invariant | Evidence | Failure signal |
+| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| INV22–INV24 | Contributor/reviewer evidence inventory; public-link and byte verification; retained remote refs; unchanged fixture/baseline/media paths | Disposable captures enter the source tree, cleanup loses a referenced image, a temporary branch is called durable, or storage changes overwrite an owner's proof or retention contract |
+| INV25, INV26, DEC-12 | `scripts/specs-for-file.test.mjs`, `scripts/check-knowledge.test.mjs`, and `pnpm check:knowledge` | A current record is reached by no tracked non-record path, a lookup infers a link from a name, a pattern matches nothing or the whole repository, or a pattern match widens a claim or outranks a narrower owner |
+| INV27, DEC-13 | `scripts/check-knowledge.test.mjs` and `pnpm check:knowledge` | A `*.spec.md` file or a Markdown file under a `specs` directory without valid record frontmatter, outside its kind's location, or following a package-local template passes |
+| DEC-15 | `.github/scripts/knowledge-paths.test.mjs`, `.github/scripts/change-scope.test.mjs`, `scripts/check-knowledge.test.mjs`, `scripts/specs-for-file.test.mjs`, and `pnpm check:knowledge` | A component or module record outside `docs/specs/components/<ComponentRoot>/`, a `*.spec.md` left in a component package's source tree or beside a Swift view, a record matched to the wrong package when two share a root, a record whose component root no registered package's source tree has, a platform record whose id or `platform_of` does not match its path, or a platform record change that skips the spec-owner gate |
Evidence placement is enforced by contributors and reviewers. The local
`docs/pr-assets/` ignore prevents accidental staging; it is not a blocking CI
@@ -1161,8 +1161,15 @@ Current enforcement gap: discovery does not yet read record candidates outside
`docs/` and themes; component records have no `platform_of` field until the
next schema version; and the component id pattern does not yet accept a
language-qualified id such as `component:swift/Button`. Until all three land,
-platform records (`docs/specs/components/<ComponentRoot>/<PublicName>.<language>.spec.md`)
-and package records under `packages/native/specs/` are checked only by review.
+package records under `packages/native/specs/` are checked only by review.
+`pnpm check:knowledge` checks a platform record
+(`docs/specs/components/<ComponentRoot>/<PublicName>.<language>.spec.md`) as it
+checks a core component record (its folder and public name, schema rules,
+applicability blocks, and id), accepting its language-qualified id, and also
+checks that `platform_of` names its core component and that its `verified_by`
+paths exist. Its theme-target block has no core theming contract to check
+against. The spec-owner gate and `pnpm specs:for` treat a platform record like
+the core record beside it.
Current enforcement gap: no checked-in gate yet proves the open-pull-request
search. Until one exists, the pull-request summary records the search terms,
diff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjs
index 83a15b8c66..a553342877 100644
--- a/scripts/check-knowledge.mjs
+++ b/scripts/check-knowledge.mjs
@@ -31,6 +31,8 @@ const {
} = require('../.github/scripts/component-design-decisions.cjs');
const {
COMPONENT_SPEC_ROOT,
+ PLATFORM_SOURCE_ROOTS,
+ classifyPlatformComponentSpecPath,
componentSpecPathForSource,
isComponentSpecRecordPath,
isIgnoredComponentKnowledgeSegment,
@@ -984,6 +986,96 @@ export function discoverKnowledgeRecords(root = DEFAULT_ROOT) {
return records.sort();
}
+/**
+ * Platform implementation records:
+ * `docs/specs/components/<ComponentRoot>/<PublicName>.<language>.spec.md`.
+ */
+export function discoverPlatformComponentRecords(root = DEFAULT_ROOT) {
+ return matchingFilesRecursively(
+ path.join(root, COMPONENT_SPEC_ROOT),
+ (_name, candidate) =>
+ isPlatformComponentSpecPath(
+ path.relative(root, candidate).split(path.sep).join('/'),
+ ),
+ {skipDirectory: isIgnoredComponentKnowledgeSegment},
+ ).sort();
+}
+
+/**
+ * What only a platform record has, checked after the record loop has read every
+ * id: `platform_of` names the core component, the core record beside it
+ * declares that id, and its `verified_by` paths exist. `ids` maps every record
+ * id to its path and authority.
+ */
+export function validatePlatformComponentRecords(root, {ids, repositoryFiles}) {
+ const problems = [];
+ const tracked = repositoryFiles ? new Set(repositoryFiles) : null;
+ for (const absolutePath of discoverPlatformComponentRecords(root)) {
+ const filePath = path
+ .relative(root, absolutePath)
+ .split(path.sep)
+ .join('/');
+ const {componentRoot, publicName} =
+ classifyPlatformComponentSpecPath(filePath);
+ const {frontmatter} = parseKnowledgeDocument(
+ fs.readFileSync(absolutePath, 'utf8'),
+ filePath,
+ );
+ if (frontmatter.get('kind') !== 'component') {
+ problems.push(`${filePath}: a platform record must be kind: component.`);
+ }
+ const coreId = `component:${publicName}`;
+ if (frontmatter.get('platform_of') !== coreId) {
+ problems.push(
+ `${filePath}: platform_of must name the core component, ${coreId}.`,
+ );
+ }
+ const corePath = `${COMPONENT_SPEC_ROOT}/${componentRoot}/${publicName}.spec.md`;
+ // Placed like the core record it implements, whether or not that record
+ // exists yet.
+ const location = componentRecordLocation(root, path.join(root, corePath));
+ if (!location) {
+ problems.push(
+ `${filePath}: platform records must live at ${COMPONENT_SPEC_ROOT}/<ComponentRoot>/, where exactly one registered component package owns <ComponentRoot>.`,
+ );
+ } else {
+ const placement = componentNamePlacement(root, location, publicName);
+ if (placement.missingFlatExport) {
+ problems.push(
+ `${filePath}: platform record for ${publicName} must match a public named export and TSX module in packages/${location.packageName}/src.`,
+ );
+ }
+ if (placement.outsideRoot) {
+ problems.push(
+ `${filePath}: platform record for ${publicName} must match component root ${JSON.stringify(componentRoot)} or an exact public component entry in that root's consumer docs.`,
+ );
+ }
+ }
+ if (fs.existsSync(path.join(root, corePath))) {
+ const core = ids.get(coreId);
+ if (!core || core.filePath.split(path.sep).join('/') !== corePath) {
+ problems.push(
+ `${filePath}: the core record beside it, ${corePath}, must declare id ${coreId}.`,
+ );
+ }
+ }
+ const verifiedBy = frontmatter.get('verified_by');
+ for (const entry of Array.isArray(verifiedBy) ? verifiedBy : []) {
+ const cited = String(entry).replace(/\/+$/, '');
+ const exists = tracked
+ ? tracked.has(cited) ||
+ [...tracked].some(file => file.startsWith(`${cited}/`))
+ : fs.existsSync(path.join(root, cited));
+ if (!exists) {
+ problems.push(
+ `${filePath}: verified_by path ${entry} is not in the repository.`,
+ );
+ }
+ }
+ }
+ return problems;
+}
+
/**
* Spec files outside the component record layout: a `*.spec.md` left in a
* registered component package's source tree, and a `*.spec.md` under
@@ -1014,7 +1106,7 @@ export function discoverMisplacedComponentSpecs(root = DEFAULT_ROOT) {
}
}
- const nativeSources = path.join(root, 'packages/native/apple/Sources');
+ const nativeSources = path.join(root, PLATFORM_SOURCE_ROOTS.swift);
for (const candidate of matchingFilesRecursively(
nativeSources,
name => isSpecFile(name) && !name.startsWith('.'),
@@ -1097,6 +1189,25 @@ export function consumerDocPublicNames(docPath) {
return [...names].sort();
}
+/**
+ * Whether a component record's public name fits where its folder places it: a
+ * flat package exports it, and it is the component root or an exact public
+ * component entry in that root's consumer docs.
+ */
+function componentNamePlacement(root, location, publicName) {
+ return {
+ missingFlatExport:
+ location.layout === 'flat' &&
+ !packageHasPublicComponent(root, location.packageName, publicName),
+ outsideRoot:
+ publicName !== location.componentRoot &&
+ !componentRootDefinesPublicComponent(
+ location.componentSourcePath,
+ publicName,
+ ),
+ };
+}
+
function componentRootDefinesPublicComponent(componentRootPath, publicName) {
for (const docPath of matchingFilesRecursively(
componentRootPath,
@@ -1178,21 +1289,13 @@ export function validateComponentModuleRelationships(
`${record.filePath}: component record id must be ${expectedId} to match its filename.`,
);
}
- if (
- location.layout === 'flat' &&
- !packageHasPublicComponent(root, location.packageName, publicName)
- ) {
+ const placement = componentNamePlacement(root, location, publicName);
+ if (placement.missingFlatExport) {
problems.push(
`${record.filePath}: flat-package component record ${expectedId} must match a public named export and TSX module in packages/${location.packageName}/src.`,
);
}
- if (
- publicName !== location.componentRoot &&
- !componentRootDefinesPublicComponent(
- location.componentSourcePath,
- publicName,
- )
- ) {
+ if (placement.outsideRoot) {
problems.push(
`${record.filePath}: flat component record ${expectedId} must match component root ${JSON.stringify(location.componentRoot)} or an exact public component entry in that root's consumer docs.`,
);
@@ -1767,6 +1870,7 @@ function validateAgainstSchema(
currentTemplateVersion,
designApprovalOwners = [],
engineeringApprovalOwners = [],
+ {idPattern = null} = {},
) {
const problems = [...document.problems];
const {frontmatter, sections} = document;
@@ -1845,12 +1949,13 @@ function validateAgainstSchema(
}
const id = frontmatter.get('id');
+ const expectedIdPattern = idPattern ?? kindSchema.idPattern;
if (
- kindSchema.idPattern &&
- (typeof id !== 'string' || !new RegExp(kindSchema.idPattern).test(id))
+ expectedIdPattern &&
+ (typeof id !== 'string' || !new RegExp(expectedIdPattern).test(id))
) {
problems.push(
- `${filePath}: id must match ${JSON.stringify(kindSchema.idPattern)}.`,
+ `${filePath}: id must match ${JSON.stringify(expectedIdPattern)}.`,
);
}
@@ -2123,10 +2228,19 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
}
}
- for (const absolutePath of discoverKnowledgeRecords(root)) {
+ const platformRecordPaths = new Set(discoverPlatformComponentRecords(root));
+ for (const absolutePath of [
+ ...discoverKnowledgeRecords(root),
+ ...platformRecordPaths,
+ ]) {
const filePath = path.relative(root, absolutePath);
const content = fs.readFileSync(absolutePath, 'utf8');
const document = parseKnowledgeDocument(content, filePath);
+ // A platform record is checked like any record, with its
+ // language-qualified id (`component:<language>/<PublicName>`).
+ const platform = platformRecordPaths.has(absolutePath)
+ ? classifyPlatformComponentSpecPath(filePath.split(path.sep).join('/'))
+ : null;
const pathApplicability = parsePathApplicabilityBlock(content, filePath);
problems.push(
...pathApplicability.problems,
@@ -2166,6 +2280,11 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
templateVersions[document.frontmatter.get('kind')],
designApprovalOwners,
engineeringApprovalOwners,
+ platform
+ ? {
+ idPattern: `^component:${platform.language}/${platform.publicName}$`,
+ }
+ : {},
),
);
const authority = document.frontmatter.get('authority');
@@ -2185,7 +2304,9 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
);
const parsed = parseAnatomyThemingBlock(content, filePath);
problems.push(...parsed.problems);
- if (parsed.mapping != null) {
+ // Theme targets map a core component's anatomy; a platform record's
+ // block is parsed but has no core contract to check against.
+ if (parsed.mapping != null && !platform) {
if (isActiveRecord) {
delegations.push(...collectDelegations(parsed.mapping, filePath));
}
@@ -2223,10 +2344,11 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
});
}
}
- records.push({filePath, absolutePath, document});
+ if (!platform) records.push({filePath, absolutePath, document});
}
problems.push(
+ ...validatePlatformComponentRecords(root, {ids, repositoryFiles}),
...validateComponentModuleRelationships(
root,
records,
diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjs
index fdd204d8c9..ce8e10d6e1 100644
--- a/scripts/check-knowledge.test.mjs
+++ b/scripts/check-knowledge.test.mjs
@@ -154,6 +154,24 @@ function componentRecord(overrides = {}) {
return `---\n${frontmatter}\n---\n\n# Button component contract\n\n${sections}\n`;
}
+function platformRecord(overrides = {}) {
+ return componentRecord({
+ id: 'component:swift/Button',
+ platform_of: 'component:Button',
+ verified_by: '[packages/native/apple/Tests/AstryxTests/ButtonTests.swift]',
+ ...overrides,
+ });
+}
+
+function writeSwiftTest(root) {
+ const swiftTest = path.join(
+ root,
+ 'packages/native/apple/Tests/AstryxTests/ButtonTests.swift',
+ );
+ fs.mkdirSync(path.dirname(swiftTest), {recursive: true});
+ fs.writeFileSync(swiftTest, '');
+}
+
function moduleRecord(overrides = {}) {
const values = {
schema_version: '3',
@@ -1697,8 +1715,11 @@ describe('knowledge validation', () => {
componentRecord(),
);
const folder = path.join(root, 'docs/specs/components/Button');
- // Platform records are not checked yet (no platform_of in the schema).
- fs.writeFileSync(path.join(folder, 'Button.swift.spec.md'), '# Swift\n');
+ writeSwiftTest(root);
+ fs.writeFileSync(
+ path.join(folder, 'Button.swift.spec.md'),
+ platformRecord(),
+ );
fs.writeFileSync(path.join(folder, 'Button.klingon.spec.md'), '# ?\n');
fs.writeFileSync(
path.join(root, 'docs/specs/components/Loose.spec.md'),
@@ -1711,6 +1732,141 @@ describe('knowledge validation', () => {
).toHaveLength(2);
});
+ it('checks a platform record with the shared validator and against its core component', async () => {
+ const root = fixtureRoot();
+ fs.mkdirSync(path.join(root, 'packages/core/src/Button'));
+ fs.writeFileSync(
+ recordPath(path.join(root, 'packages/core/src/Button/Button.spec.md')),
+ componentRecord(),
+ );
+ writeSwiftTest(root);
+ const swift = path.join(
+ root,
+ 'docs/specs/components/Button/Button.swift.spec.md',
+ );
+ const swiftProblems = async overrides => {
+ fs.writeFileSync(swift, platformRecord(overrides));
+ return (await validateKnowledgeRoot(root)).filter(problem =>
+ problem.startsWith('docs/specs/components/Button/Button.swift.spec.md'),
+ );
+ };
+
+ expect(await swiftProblems()).toEqual([]);
+ expect(
+ await swiftProblems({
+ id: 'component:Button',
+ platform_of: 'component:Card',
+ owners: '[]',
+ verified_by: '[packages/native/apple/Tests/Missing.swift]',
+ }),
+ ).toEqual([
+ 'docs/specs/components/Button/Button.swift.spec.md: id must match "^component:swift/Button$".',
+ 'docs/specs/components/Button/Button.swift.spec.md: owners must be a non-empty inline list.',
+ 'docs/specs/components/Button/Button.swift.spec.md: duplicate id component:Button; first declared in docs/specs/components/Button/Button.spec.md.',
+ 'docs/specs/components/Button/Button.swift.spec.md: platform_of must name the core component, component:Button.',
+ 'docs/specs/components/Button/Button.swift.spec.md: verified_by path packages/native/apple/Tests/Missing.swift is not in the repository.',
+ ]);
+ // It is placed like the core record it implements.
+ for (const [misplaced, message] of [
+ [
+ 'docs/specs/components/Buton/Button.swift.spec.md',
+ 'platform records must live at docs/specs/components/<ComponentRoot>/',
+ ],
+ [
+ 'docs/specs/components/Button/Banana.swift.spec.md',
+ 'platform record for Banana must match component root "Button"',
+ ],
+ ]) {
+ const misplacedPath = path.join(root, misplaced);
+ fs.mkdirSync(path.dirname(misplacedPath), {recursive: true});
+ const name = path.basename(misplaced, '.swift.spec.md');
+ fs.writeFileSync(
+ misplacedPath,
+ platformRecord({
+ id: `component:swift/${name}`,
+ platform_of: `component:${name}`,
+ }),
+ );
+ const misplacedProblems = (await validateKnowledgeRoot(root)).filter(
+ problem => problem.startsWith(misplaced),
+ );
+ expect(misplacedProblems.join('\n')).toContain(message);
+ fs.rmSync(misplacedPath);
+ }
+ // Its applicability blocks are validated, since specs:for reads them.
+ fs.writeFileSync(
+ swift,
+ withReviewApplicability(platformRecord(), {'not-a-trigger': ['INV1']}) +
+ '\n<!-- path-applicability:v1 -->\n\n```json\n{"paths": []}\n```\n',
+ );
+ const blockProblems = (await validateKnowledgeRoot(root)).filter(problem =>
+ problem.startsWith('docs/specs/components/Button/Button.swift.spec.md'),
+ );
+ expect(
+ blockProblems.some(problem => problem.includes('review-applicability')),
+ ).toBe(true);
+ expect(blockProblems).toContain(
+ 'docs/specs/components/Button/Button.swift.spec.md: path-applicability:v1 requires a non-empty paths list.',
+ );
+ // The shared validator's current-record rules apply, verified_by included.
+ expect(
+ await swiftProblems({authority: 'current', verified_by: '[]'}),
+ ).toEqual(
+ expect.arrayContaining([
+ 'docs/specs/components/Button/Button.swift.spec.md: current records require non-empty verified_by.',
+ 'docs/specs/components/Button/Button.swift.spec.md: current records require approved_by to name an authorized owner.',
+ 'docs/specs/components/Button/Button.swift.spec.md: current records require approved_at as YYYY-MM-DD.',
+ ]),
+ );
+ expect(
+ await swiftProblems({
+ authority: 'current',
+ approved_by: 'cixzhang',
+ approved_at: '2026-11-01',
+ }),
+ ).toEqual([]);
+ });
+
+ it('places a flat-package platform record by the same rules as its core record', async () => {
+ const root = fixtureRoot();
+ const source = path.join(root, 'packages/charts/src');
+ fs.writeFileSync(
+ path.join(source, 'index.ts'),
+ "export {Chart} from './Chart';\nexport {Ghost} from './Ghost';\n",
+ );
+ fs.writeFileSync(
+ path.join(source, 'Chart.tsx'),
+ 'export function Chart() {}\n',
+ );
+ fs.writeFileSync(
+ path.join(source, 'Ghost.tsx'),
+ 'export function Ghost() {}\n',
+ );
+ writeSwiftTest(root);
+ const swiftRecord = (folder, name) => {
+ const filePath = path.join(
+ root,
+ `docs/specs/components/${folder}/${name}.swift.spec.md`,
+ );
+ fs.mkdirSync(path.dirname(filePath), {recursive: true});
+ fs.writeFileSync(
+ filePath,
+ platformRecord({
+ id: `component:swift/${name}`,
+ platform_of: `component:${name}`,
+ }),
+ );
+ };
+ swiftRecord('Chart', 'Chart');
+ swiftRecord('Chart', 'Ghost');
+
+ const problems = (await validateKnowledgeRoot(root)).join('\n');
+ expect(problems).not.toContain('Chart/Chart.swift.spec.md');
+ expect(problems).toContain(
+ 'docs/specs/components/Chart/Ghost.swift.spec.md: platform record for Ghost must match component root "Chart"',
+ );
+ });
+
it('rejects a nested component record instead of treating it as a module', async () => {
const root = fixtureRoot();
const componentDirectory = path.join(root, 'packages/core/src/Button');
diff --git a/scripts/specs-for-file.mjs b/scripts/specs-for-file.mjs
index bbc2415bab..60159b8d19 100644
--- a/scripts/specs-for-file.mjs
+++ b/scripts/specs-for-file.mjs
@@ -22,6 +22,7 @@ import {
collectConcernMatches,
collectGlobalReviewMatches,
discoverKnowledgeRecords,
+ discoverPlatformComponentRecords,
consumerDocPublicNames,
matchesPathPattern,
parseKnowledgeDocument,
@@ -33,7 +34,9 @@ const require = createRequire(import.meta.url);
const {componentPackage} = require('./component-packages.cjs');
const {
classifyComponentKnowledgePath,
+ classifyPlatformComponentSpecPath,
locateComponentKnowledgePath,
+ locatePlatformComponentSource,
} = require('../.github/scripts/knowledge-paths.cjs');
const HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -51,6 +54,8 @@ const INHERITED_REFERENCE_FIELDS = [
'system_specs',
'references',
'parent_component',
+ // A platform record adds to its core component's contract (INV2).
+ 'platform_of',
];
/**
@@ -133,7 +138,10 @@ function pathEntryCovers(root, entry, filePath) {
/** Load every knowledge record in the working tree once. */
export function loadKnowledgeIndex(root = DEFAULT_ROOT) {
const records = [];
- for (const absolutePath of discoverKnowledgeRecords(root)) {
+ for (const absolutePath of [
+ ...discoverKnowledgeRecords(root),
+ ...discoverPlatformComponentRecords(root),
+ ]) {
const filePath = toPosix(path.relative(root, absolutePath));
const content = fs.readFileSync(absolutePath, 'utf8');
const {frontmatter} = parseKnowledgeDocument(content, filePath);
@@ -148,6 +156,7 @@ export function loadKnowledgeIndex(root = DEFAULT_ROOT) {
frontmatter,
classified: classifyComponentKnowledgePath(filePath),
located: locateComponentKnowledgePath(root, filePath),
+ platform: classifyPlatformComponentSpecPath(filePath),
pathPatterns: asList(
parsePathApplicabilityBlock(content, filePath).config?.paths,
).filter(pattern => typeof pattern === 'string'),
@@ -261,6 +270,25 @@ function placementMatches(index, filePath, location) {
}
continue;
}
+ if (record.platform) {
+ // A platform record governs its language's code for the same component
+ // root: the whole root when it is named after it, otherwise its
+ // same-stem files.
+ const {componentRoot, language, publicName} = record.platform;
+ const source = locatePlatformComponentSource(filePath);
+ if (
+ source?.language === language &&
+ source.componentRoot === componentRoot &&
+ (publicName === componentRoot || source.stem === publicName)
+ ) {
+ matches.push({
+ record,
+ via: 'placement',
+ detail: `${language} record for ${publicName} in ${componentRoot}`,
+ });
+ }
+ continue;
+ }
const {classified, located} = record;
if (!classified) continue;
const recordStem = classified.publicName;
diff --git a/scripts/specs-for-file.test.mjs b/scripts/specs-for-file.test.mjs
index fd9c0b75e9..4f3cc30c54 100644
--- a/scripts/specs-for-file.test.mjs
+++ b/scripts/specs-for-file.test.mjs
@@ -499,6 +499,65 @@ describe('resolveSpecsForFile', () => {
).toEqual(['component:ChatComposerDrawer']);
});
+ it("places a platform record over its language's code and brings in the core record", () => {
+ const root = fixtureRoot();
+ write(root, 'packages/core/src/Avatar/Avatar.tsx');
+ write(root, 'packages/native/apple/Sources/Astryx/Avatar/Avatar.swift');
+ write(
+ root,
+ 'packages/native/apple/Sources/Astryx/Avatar/AvatarStatusDot.swift',
+ );
+ write(root, 'packages/native/apple/Sources/Astryx/Button/Button.swift');
+ writeRecord(root, 'docs/specs/components/Avatar/Avatar.spec.md', {
+ kind: 'component',
+ id: 'component:Avatar',
+ });
+ writeRecord(root, 'docs/specs/components/Avatar/Avatar.swift.spec.md', {
+ kind: 'component',
+ id: 'component:swift/Avatar',
+ platform_of: 'component:Avatar',
+ });
+ writeRecord(
+ root,
+ 'docs/specs/components/Avatar/AvatarStatusDot.swift.spec.md',
+ {
+ kind: 'component',
+ id: 'component:swift/AvatarStatusDot',
+ platform_of: 'component:AvatarStatusDot',
+ },
+ );
+ const index = loadKnowledgeIndex(root);
+ const lookup = file => ids(resolveSpecsForFile(index, file).records);
+
+ expect(
+ lookup('packages/native/apple/Sources/Astryx/Avatar/Avatar.swift'),
+ ).toEqual(['component:Avatar', 'component:swift/Avatar']);
+ expect(
+ lookup(
+ 'packages/native/apple/Sources/Astryx/Avatar/AvatarStatusDot.swift',
+ ),
+ ).toEqual([
+ 'component:Avatar',
+ 'component:swift/Avatar',
+ 'component:swift/AvatarStatusDot',
+ ]);
+ expect(lookup('packages/core/src/Avatar/Avatar.tsx')).toEqual([
+ 'component:Avatar',
+ ]);
+ expect(
+ lookup('packages/native/apple/Sources/Astryx/Button/Button.swift'),
+ ).toEqual([]);
+ expect(
+ lookup('docs/specs/components/Avatar/AvatarStatusDot.swift.spec.md'),
+ ).toEqual(['component:swift/AvatarStatusDot']);
+ expect(
+ findUnreachedRecords(index, [
+ 'packages/core/src/Avatar/Avatar.tsx',
+ 'packages/native/apple/Sources/Astryx/Avatar/AvatarStatusDot.swift',
+ ]).map(record => record.id),
+ ).toEqual([]);
+ });
+
it('names a member without its own consumer doc by its file stem', () => {
const index = loadKnowledgeIndex(popoverFixture());
expect(