An open source design system that's fully customizable and agent ready
TypeScript
chore(scripts): add specs:for to list the records that govern any path (#7790)
Cindy Zhang0012d921181d
diff --git a/AGENTS.md b/AGENTS.mdindex a41562a4b0..47e986aaca 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -30,6 +30,11 @@ nested `AGENTS.md`.route exposes only the listed claim; it never makes the whole record governthe component or change. Preserve each matched record, claim, trigger, andmatch reason in the review receipt.+- Any path: `pnpm specs:for <path>` lists the current records linked to it,+ the specs that decided them, and the global claims its component's triggers+ route. It reads the working tree, so on a pull-request branch it shows that+ branch's proposed records; it is a lookup, not review authority. It adds to+ the component-review steps above; it does not replace them.- Component-local visual intent: reuse or amend the optional `Design decisions`table in the current component/module spec only when durable local intent mustsurvive future redesigns. Keep exact tuning in code/evidence and shared rulesdiff --git a/docs/README.md b/docs/README.mdindex 42f8faeff7..a4ef917d58 100644--- a/docs/README.md+++ b/docs/README.md@@ -117,6 +117,21 @@ If `system-spec` receives a future schema revision, replace its legacy`architecture:*`, `family:*`, `theme:*`, and `contributing:*`; this PR does notchange the v1 system-spec shape.+Run `pnpm specs:for <path>` to list the current records linked to any repository+path: the record's own placement, `applies_to` and `verified_by` entries, family+and design membership, `affects_consumer_docs` ids, system-spec numbers the file+cites in its text (not inside a record path), and the references those records+inherit. Only visible records are followed, so a draft never adds a link unless+`--include-draft` is passed. A reference scoped to one claim or+decision (`spec:AST-NNN/FR3`) lists that claim, not the whole record. The specs that+decided a linked record are listed separately, as are the global claims the+matched component and module triggers route (the same selection as+`review-global-baselines.mjs`). A path with no linked record is reported as+such. Records are read from the working tree, so on a pull-request branch the+result includes that branch's proposed records and is not review authority.+`pnpm specs:for --unrouted` lists tracked files with no governing record;+`--unreached` lists current records that no other path reaches.+Run `pnpm check:knowledge` to validate templates and records. Pure spec-recordpull requests do not add Changesets because they do not publish package changes.diff --git a/package.json b/package.jsonindex bc33b9c75e..725f45077c 100644--- a/package.json+++ b/package.json@@ -74,7 +74,8 @@"dev:sandbox": "pnpm -F @astryxdesign/core build && pnpm -F @astryxdesign/sandbox dev","dev:sandbox:source": "pnpm generate:i18n-runtime && ASTRYX_SOURCE=1 pnpm -F @astryxdesign/sandbox dev","npm:prune-canaries": "node scripts/npm/prune-canaries.mjs",- "check:knowledge": "node scripts/check-knowledge.mjs"+ "check:knowledge": "node scripts/check-knowledge.mjs",+ "specs:for": "node scripts/specs-for-file.mjs"},"devDependencies": {"@axe-core/playwright": "^4.12.1",diff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjsindex 0a270bcb7f..0289467da8 100644--- a/scripts/check-knowledge.mjs+++ b/scripts/check-knowledge.mjs@@ -640,6 +640,30 @@ function isFullConsumerDocEntry(entry) {);}+/**+ * Public names one consumer doc defines: its own `name` and its full+ * `components` entries, as `componentRootDefinesPublicComponent` reads them.+ * Anatomy parts and other nested `name` fields are not names.+ */+export function consumerDocPublicNames(docPath) {+ let mod;+ try {+ mod = require(docPath);+ } catch {+ return [];+ }+ const doc = mod.docs ?? mod.default;+ if (!doc) return [];+ const names = new Set();+ if (typeof doc.name === 'string') names.add(doc.name.replace(/^XDS/, ''));+ for (const entry of doc.components ?? []) {+ if (typeof entry?.name === 'string' && isFullConsumerDocEntry(entry)) {+ names.add(entry.name.replace(/^XDS/, ''));+ }+ }+ return [...names].sort();+}+function componentRootDefinesPublicComponent(componentRootPath, publicName) {for (const docPath of matchingFilesRecursively(componentRootPath,diff --git a/scripts/specs-for-file.mjs b/scripts/specs-for-file.mjsnew file mode 100644index 0000000000..2ddb645692--- /dev/null+++ b/scripts/specs-for-file.mjs@@ -0,0 +1,873 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Resolve the knowledge records that govern a repository file.+ * @input Repository-relative file paths and the working tree's knowledge records.+ * @output Every record linked to each path, with the declared link that put it+ * there, plus the trigger-routed global claims reviewers load today.+ * @position Read-only lookup over the links records already declare. A name+ * matches only an id a record declares exactly; coverage is never inferred+ * from extensions or directory names, and a path no record reaches is+ * reported as such.+ */++/* global console, process */+import fs from 'node:fs';+import path from 'node:path';+import {execFileSync} from 'node:child_process';+import {createRequire} from 'node:module';+import {fileURLToPath} from 'node:url';+import {+ GLOBAL_REVIEW_TRIGGERS,+ collectGlobalReviewMatches,+ discoverKnowledgeRecords,+ consumerDocPublicNames,+ parseKnowledgeDocument,+} from './check-knowledge.mjs';++const require = createRequire(import.meta.url);+const {componentPackage} = require('./component-packages.cjs');+const {+ classifyComponentKnowledgePath,+} = require('../.github/scripts/knowledge-paths.cjs');++const HERE = path.dirname(fileURLToPath(import.meta.url));+const DEFAULT_ROOT = path.resolve(HERE, '..');++/**+ * Reference fields that point from a record to the broader authority it+ * relies on. Following them never narrows scope: a record that governs a path+ * passes that path to the records it inherits from.+ */+const INHERITED_REFERENCE_FIELDS = [+ 'architecture',+ 'families',+ 'design_specs',+ 'system_specs',+ 'references',+ 'parent_component',+];++/**+ * Links from a governing record to the system specs that decided it. Those+ * specs are listed separately: they carry the decisions behind a governing+ * record, but nothing in them declares that the whole spec governs the path.+ */+const DECIDING_REFERENCE_FIELDS = ['deciding_specs'];+const DECIDED_REFERENCE_FIELDS = ['affects_architecture', 'affects_families'];++/** Fields naming the components a family or design record governs. */+const MEMBER_FIELDS = ['members', 'components'];++function toPosix(filePath) {+ return String(filePath).split(path.sep).join('/').replace(/^\.\//, '');+}++function asList(value) {+ if (Array.isArray(value)) return value;+ if (typeof value === 'string' && value.length > 0) return [value];+ return [];+}++// A reference may name one claim of its target: `spec:AST-NNN/FR3`,+// `architecture:x/INV6`, `spec:AST-NNN/DEC-2`.+const CLAIM_SUFFIX = /\/([A-Z][A-Z0-9]*-?[0-9]+[a-z]?)$/;++function referenceTarget(reference) {+ return reference.replace(CLAIM_SUFFIX, '');+}++function referenceDecision(reference) {+ return CLAIM_SUFFIX.exec(reference)?.[1] ?? null;+}++// Path fields mix repository paths with prose and commands; only the prose+// and commands contain whitespace. Route groups such as `(fullscreen)` are+// ordinary path segments.+function looksLikePath(entry) {+ return (+ typeof entry === 'string' &&+ /^\S+$/.test(entry) &&+ (entry.includes('/') || /\.[A-Za-z0-9]+$/.test(entry))+ );+}++/**+ * True when a declared path entry covers `filePath`. A trailing slash or a+ * directory entry covers its subtree; any other entry is exact.+ */+const pathEntryCache = new Map();+const directoryCache = new Map();++function pathEntryCovers(root, entry, filePath) {+ let parsed = pathEntryCache.get(entry);+ if (!parsed) {+ const normalized = toPosix(entry).replace(/\/+$/, '');+ parsed = {+ normalized,+ prefix: `${normalized}/`,+ valid: normalized !== '' && looksLikePath(entry),+ subtree: entry.endsWith('/'),+ };+ pathEntryCache.set(entry, parsed);+ }+ if (!parsed.valid) return false;+ if (filePath === parsed.normalized) return true;+ if (!filePath.startsWith(parsed.prefix)) return false;+ if (parsed.subtree) return true;+ const absolute = path.join(root, parsed.normalized);+ let isDirectory = directoryCache.get(absolute);+ if (isDirectory === undefined) {+ isDirectory =+ fs.existsSync(absolute) && fs.statSync(absolute).isDirectory();+ directoryCache.set(absolute, isDirectory);+ }+ return isDirectory;+}++/** Load every knowledge record in the working tree once. */+export function loadKnowledgeIndex(root = DEFAULT_ROOT) {+ const records = [];+ for (const absolutePath of discoverKnowledgeRecords(root)) {+ const filePath = toPosix(path.relative(root, absolutePath));+ const content = fs.readFileSync(absolutePath, 'utf8');+ const {frontmatter} = parseKnowledgeDocument(content, filePath);+ const id = frontmatter.get('id');+ if (typeof id !== 'string') continue;+ records.push({+ id,+ path: filePath,+ content,+ kind: frontmatter.get('kind'),+ authority: frontmatter.get('authority'),+ frontmatter,+ classified: classifyComponentKnowledgePath(filePath),+ });+ }+ const byId = new Map(records.map(record => [record.id, record]));+ return {root, records, byId};+}++const componentNameCache = new Map();++function docNames(docPath) {+ let names = componentNameCache.get(docPath);+ if (!names) {+ names = fs.existsSync(docPath) ? consumerDocPublicNames(docPath) : [];+ componentNameCache.set(docPath, names);+ }+ return names;+}++function directoryHasDoc(directory) {+ const key = `dir:${directory}`;+ let has = componentNameCache.get(key);+ if (has === undefined) {+ has =+ fs.existsSync(directory) &&+ fs.statSync(directory).isDirectory() &&+ fs.readdirSync(directory).some(name => name.endsWith('.doc.mjs'));+ componentNameCache.set(key, has);+ }+ return has;+}++/**+ * The component a path belongs to under the shared component-package path+ * contract, and the public names that path speaks for: its file stem, plus its+ * own same-stem consumer doc when it has one, otherwise the root's+ * `<Root>.doc.mjs`. A root with no consumer docs (a plain helper directory) is+ * also named by itself; a flat package's top-level module by its stem.+ */+function componentLocation(root, filePath) {+ const match = /^packages\/([^/]+)\/src\/(.+)$/.exec(filePath);+ if (!match) return null;+ const packageConfig = componentPackage(match[1]);+ if (!packageConfig) return null;+ const segments = match[2].split('/');+ const stem = segments.at(-1).split('.')[0];+ let componentRoot;+ if (packageConfig.layout === 'flat') {+ componentRoot = segments.length > 1 ? segments[0] : stem;+ } else {+ if (segments.length < 2) return null;+ componentRoot = segments[0];+ }+ let names;+ if (packageConfig.layout === 'flat' && segments.length === 1) {+ names = [stem];+ } else {+ const rootDirectory = path.join(root, packageConfig.src, componentRoot);+ const own = docNames(+ path.join(root, path.dirname(filePath), `${stem}.doc.mjs`),+ );+ const primary = docNames(+ path.join(rootDirectory, `${componentRoot}.doc.mjs`),+ );+ if (own.length > 0) names = own;+ else if (primary.length > 0) names = primary;+ else if (!directoryHasDoc(rootDirectory)) names = [componentRoot];+ else names = [];+ // A member a family or system spec names may have no consumer doc of its+ // own; its file stem is still its name.+ names = [...names, stem];+ }+ return {+ packageName: match[1],+ layout: packageConfig.layout,+ componentRoot,+ names: new Set(names),+ };+}++function fileStem(filePath) {+ return path.posix.basename(filePath).split('.')[0];+}++/**+ * Records whose own canonical location places `filePath` inside their scope:+ * the record itself; a theme record over its package; the component record+ * named after its root over the whole root; any other component or module+ * record over its same-stem files anywhere under its component root; a module+ * record also beside a same-stem `verified_by` file, or over a directory it is+ * the only module record in.+ */+function placementMatches(index, filePath, location) {+ const matches = [];+ const stem = fileStem(filePath);+ const fileDirectory = path.posix.dirname(filePath);+ for (const record of index.records) {+ if (record.path === filePath) {+ matches.push({record, via: 'self', detail: 'the file is this record'});+ continue;+ }+ const theme = /^packages\/themes\/([^/]+)\/\1\.spec\.md$/.exec(record.path);+ if (theme) {+ if (filePath.startsWith(`packages/themes/${theme[1]}/`)) {+ matches.push({+ record,+ via: 'placement',+ detail: `theme record for packages/themes/${theme[1]}/`,+ });+ }+ continue;+ }+ const {classified} = record;+ if (!classified) continue;+ const recordDirectory = path.posix.dirname(record.path);+ const recordStem = classified.publicName;++ if (classified.kind === 'module' && stem === recordStem) {+ const besideEvidence = asList(record.frontmatter.get('verified_by')).some(+ entry =>+ looksLikePath(entry) &&+ fileStem(entry) === recordStem &&+ path.posix.dirname(entry) === fileDirectory,+ );+ if (besideEvidence) {+ matches.push({+ record,+ via: 'placement',+ detail: `module record beside its verified_by evidence for ${recordStem}`,+ });+ continue;+ }+ }++ if (+ !location ||+ classified.packageName !== location.packageName ||+ classified.componentRoot !== location.componentRoot+ ) {+ continue;+ }++ if (classified.kind === 'component') {+ if (+ classified.layout === 'flat' ||+ recordStem === location.componentRoot+ ) {+ matches.push({+ record,+ via: 'placement',+ detail: `component record for ${location.componentRoot}`,+ });+ } else if (stem === recordStem) {+ matches.push({+ record,+ via: 'placement',+ detail: `component record for ${recordStem} in ${location.componentRoot}`,+ });+ }+ continue;+ }++ if (stem === recordStem) {+ matches.push({+ record,+ via: 'placement',+ detail: `module record for ${recordStem} in ${location.componentRoot}`,+ });+ continue;+ }+ const siblingsInDirectory = index.records.some(+ other =>+ other !== record &&+ path.posix.dirname(other.path) === recordDirectory &&+ other.classified?.kind === 'module',+ );+ if (+ !siblingsInDirectory &&+ (fileDirectory === recordDirectory ||+ fileDirectory.startsWith(`${recordDirectory}/`))+ ) {+ matches.push({+ record,+ via: 'placement',+ detail: `only module record in ${recordDirectory}/`,+ });+ }+ }+ return matches;+}++/** Records that declare a path entry covering `filePath`. */+function declaredPathMatches(index, filePath) {+ const matches = [];+ for (const record of index.records) {+ for (const field of ['applies_to', 'verified_by']) {+ for (const entry of asList(record.frontmatter.get(field))) {+ if (pathEntryCovers(index.root, entry, filePath)) {+ matches.push({record, via: field, detail: entry});+ break;+ }+ }+ }+ }+ return matches;+}++const MENTION_SIZE_LIMIT = 1024 * 1024;++/**+ * System specs the file itself cites by number in prose or a code comment,+ * optionally scoped to one decision ("AST-" + three digits, then "/DEC-" and a+ * number). A number inside a path under docs/specs is not a citation: record+ * paths appear in fixtures and examples far more often than as links.+ */+function mentionedMatches(index, filePath) {+ const absolute = path.join(index.root, filePath);+ let bytes;+ try {+ const stat = fs.statSync(absolute);+ if (!stat.isFile() || stat.size > MENTION_SIZE_LIMIT) return [];+ bytes = fs.readFileSync(absolute);+ } catch {+ return [];+ }+ if (bytes.indexOf('AST-') === -1 || bytes.indexOf(0) !== -1) return [];+ const content = bytes.toString('utf8');+ const cited = new Map();+ for (const match of content.matchAll(+ /(?<![/\\\w-])AST-([0-9]{3})(?:[/ ]([A-Z][A-Z0-9]*-?[0-9]+[a-z]?))?\b/g,+ )) {+ const id = `spec:AST-${match[1]}`;+ const claims = cited.get(id) ?? new Set();+ claims.add(match[2] ?? null);+ cited.set(id, claims);+ }+ const matches = [];+ for (const record of index.records) {+ if (record.path === filePath || !cited.has(record.id)) continue;+ for (const decision of cited.get(record.id)) {+ matches.push({+ record,+ via: 'mentioned',+ detail:+ record.id.replace(/^spec:/, '') + (decision ? `/${decision}` : ''),+ decision,+ });+ }+ }+ return matches;+}++const topicCache = new Map();++/**+ * True when an `affects_consumer_docs` id names a CLI doc topic+ * (`packages/cli/assets/docs/[tree/]<id>.doc*.mjs`) rather than a component.+ * A topic id stays on the topic-file route: `color` is the colour guide, not+ * every file whose stem is `color`.+ */+function isConsumerDocTopic(root, docId) {+ let topics = topicCache.get(root);+ if (!topics) {+ topics = new Set();+ for (const directory of [+ 'packages/cli/assets/docs',+ 'packages/cli/assets/docs/tree',+ ]) {+ const absolute = path.join(root, directory);+ if (!fs.existsSync(absolute)) continue;+ for (const name of fs.readdirSync(absolute)) {+ const match = /^([^/]+?)\.doc(?:\.[a-z]+)*\.mjs$/.exec(name);+ if (match) topics.add(match[1]);+ }+ }+ topicCache.set(root, topics);+ }+ return topics.has(docId.split('/').at(-1));+}++/** Consumer-doc topic files a system spec's `affects_consumer_docs` id names. */+function consumerDocTopicCovers(docId, filePath) {+ const topic = docId.split('/').at(-1);+ const match =+ /^packages\/cli\/assets\/docs\/(?:tree\/)?([^/]+?)\.doc(?:\.[a-z]+)*\.mjs$/.exec(+ filePath,+ );+ return match != null && match[1] === topic;+}++/** Records that name the file's component or consumer-doc topic. */+function namedMatches(index, filePath, location) {+ const matches = [];+ for (const record of index.records) {+ for (const field of MEMBER_FIELDS) {+ for (const member of asList(record.frontmatter.get(field))) {+ const name = member.replace(/^component:/, '');+ if (location?.names.has(name)) {+ matches.push({record, via: field, detail: member});+ }+ }+ }+ for (const docId of asList(+ record.frontmatter.get('affects_consumer_docs'),+ )) {+ if (+ location?.names.has(docId) &&+ !isConsumerDocTopic(index.root, docId)+ ) {+ matches.push({record, via: 'affects_consumer_docs', detail: docId});+ } else if (consumerDocTopicCovers(docId, filePath)) {+ matches.push({record, via: 'affects_consumer_docs', detail: docId});+ } else if (+ docId.includes('/') &&+ pathEntryCovers(index.root, docId, filePath)+ ) {+ matches.push({record, via: 'affects_consumer_docs', detail: docId});+ }+ }+ }+ return matches;+}++function addRoute(reached, record, route) {+ const existing = reached.get(record.id);+ if (existing) {+ if (+ !existing.routes.some(+ known => known.via === route.via && known.detail === route.detail,+ )+ ) {+ existing.routes.push(route);+ }+ return false;+ }+ reached.set(record.id, {record, routes: [route]});+ return true;+}++function addDecision(decisions, record, decision, route) {+ const key = `${record.id}/${decision}`;+ const existing = decisions.get(key);+ if (existing) {+ if (+ !existing.routes.some(+ known => known.via === route.via && known.detail === route.detail,+ )+ ) {+ existing.routes.push(route);+ }+ return;+ }+ decisions.set(key, {record, decision, routes: [route]});+}++/**+ * Close the visible directly matched set over inherited references, then+ * collect the system specs that decided a governing record. A reference scoped+ * to one claim or decision (`spec:AST-NNN/FR3`) lists that claim, never the whole+ * record. Only visible records are followed, so a draft never steers the+ * result unless drafts were asked for.+ */+function closeOverReferences(index, direct, visible) {+ const governing = new Map();+ const decisions = new Map();+ const queue = [];+ for (const match of direct) {+ const route = {via: match.via, detail: match.detail};+ if (match.decision) {+ addDecision(decisions, match.record, match.decision, route);+ } else if (addRoute(governing, match.record, route)) {+ queue.push(match.record);+ }+ }+ while (queue.length > 0) {+ const record = queue.shift();+ for (const field of INHERITED_REFERENCE_FIELDS) {+ for (const reference of asList(record.frontmatter.get(field))) {+ const target = index.byId.get(referenceTarget(reference));+ if (!target || !visible(target)) continue;+ const route = {via: `inherited:${field}`, detail: record.id};+ const decision = referenceDecision(reference);+ if (decision) {+ addDecision(decisions, target, decision, route);+ } else if (addRoute(governing, target, route)) {+ queue.push(target);+ }+ }+ }+ }++ const deciding = new Map();+ for (const {record} of governing.values()) {+ for (const field of DECIDING_REFERENCE_FIELDS) {+ for (const reference of asList(record.frontmatter.get(field))) {+ const target = index.byId.get(referenceTarget(reference));+ if (!target || !visible(target) || governing.has(target.id)) continue;+ const route = {via: field, detail: record.id};+ const decision = referenceDecision(reference);+ if (decision) addDecision(decisions, target, decision, route);+ else addRoute(deciding, target, route);+ }+ }+ }+ for (const decider of index.records) {+ if (!visible(decider) || governing.has(decider.id)) continue;+ for (const field of DECIDED_REFERENCE_FIELDS) {+ for (const reference of asList(decider.frontmatter.get(field))) {+ const target = referenceTarget(reference);+ if (governing.has(target)) {+ addRoute(deciding, decider, {via: field, detail: target});+ }+ }+ }+ }+ return {+ governing: [...governing.values()],+ deciding: [...deciding.values()],+ decisions: [...decisions.values()],+ };+}++/**+ * Resolve the records governing one repository-relative path.+ *+ * `records` lists every record linked to the path, with each route that+ * reached it. `decidingSpecs` lists the system specs that decided one of those+ * records without being linked to the path themselves. `decisions` lists the+ * single claims or decisions (`spec:AST-NNN/FR3`) a linked record or the file cites.+ * Records come from the working tree: on a pull-request branch that includes+ * the branch's proposed records, so the result is not review authority.+ * `globalClaims` lists the trigger-routed global baseline claims, exactly as+ * `scripts/review-global-baselines.mjs` selects them, for `triggers` (default:+ * the review triggers of the matched component and module records, or every+ * supported trigger when none matched).+ */+export function resolveSpecsForFile(index, file, options = {}) {+ const includeDraft = options.includeDraft ?? false;+ const filePath = toPosix(+ path.isAbsolute(file) ? path.relative(index.root, file) : file,+ );+ if (filePath.startsWith('../')) {+ throw new Error(`${file} is outside the repository.`);+ }+ const location = componentLocation(index.root, filePath);+ const visible = record =>+ record.authority === 'current' ||+ (includeDraft && record.authority === 'draft');+ const direct = [+ ...placementMatches(index, filePath, location),+ ...declaredPathMatches(index, filePath),+ ...namedMatches(index, filePath, location),+ ...mentionedMatches(index, filePath),+ ].filter(match => visible(match.record));+ const project = entries =>+ entries+ .map(({record, routes}) => ({+ id: record.id,+ path: record.path,+ kind: record.kind,+ authority: record.authority,+ routes,+ }))+ .sort((left, right) => left.path.localeCompare(right.path));+ const closed = closeOverReferences(index, direct, visible);+ const records = project(closed.governing);+ const decidingSpecs = project(closed.deciding);+ const decisions = closed.decisions+ .map(({record, decision, routes}) => ({+ id: `${record.id}/${decision}`,+ recordId: record.id,+ decision,+ path: record.path,+ authority: record.authority,+ routes,+ }))+ .sort((left, right) => left.id.localeCompare(right.id));++ let triggers = options.triggers;+ let triggerSource = 'requested';+ if (!triggers) {+ const local = new Set();+ for (const {record} of direct) {+ if (record.kind !== 'component' && record.kind !== 'module') continue;+ for (const trigger of asList(record.frontmatter.get('review_triggers'))) {+ if (GLOBAL_REVIEW_TRIGGERS.has(trigger)) local.add(trigger);+ }+ }+ if (local.size > 0) {+ triggers = [...local];+ triggerSource = 'component and module review_triggers';+ } else {+ triggers = [...GLOBAL_REVIEW_TRIGGERS];+ triggerSource = 'every supported trigger (no local record declares any)';+ }+ }+ const globalClaims =+ triggers.length === 0+ ? []+ : collectGlobalReviewMatches(+ index.records.map(record => ({+ path: record.path,+ content: record.content,+ })),+ triggers,+ null,+ ).map(({recordId, path: recordPath, trigger, claimId, claim}) => ({+ recordId,+ path: recordPath,+ trigger,+ claimId,+ claim,+ }));++ return {+ file: filePath,+ exists: fs.existsSync(path.join(index.root, filePath)),+ component: location+ ? {+ package: location.packageName,+ root: location.componentRoot,+ names: [...location.names].sort(),+ }+ : null,+ source: 'working-tree',+ records,+ decidingSpecs,+ decisions,+ triggers: [...new Set(triggers)].sort(),+ triggerSource,+ globalClaims,+ };+}++/**+ * Current records that no tracked non-record file reaches+ * through a placement, path, name, citation, inherited, or deciding link. Every+ * such record is invisible to a path-first lookup.+ */+export function findUnreachedRecords(index, files) {+ const reached = new Set();+ const recordPaths = new Set(index.records.map(record => record.path));+ for (const file of files) {+ if (recordPaths.has(toPosix(file))) continue;+ const result = resolveSpecsForFile(index, file, {triggers: []});+ for (const record of [...result.records, ...result.decidingSpecs]) {+ if (record.routes.some(route => route.via !== 'self')) {+ reached.add(record.id);+ }+ }+ for (const decision of result.decisions) reached.add(decision.recordId);+ }+ return index.records+ .filter(record => record.authority === 'current' && !reached.has(record.id))+ .map(record => ({id: record.id, path: record.path, kind: record.kind}))+ .sort((left, right) => left.path.localeCompare(right.path));+}++/** Tracked files that no current record or cited claim governs. */+export function findUnroutedFiles(index, files) {+ return files.filter(file => {+ const result = resolveSpecsForFile(index, file, {triggers: []});+ return result.records.length === 0 && result.decisions.length === 0;+ });+}++function trackedFiles(root) {+ return execFileSync('git', ['-C', root, 'ls-files', '-z'], {+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ })+ .split('\0')+ .filter(Boolean);+}++function formatResult(result) {+ const lines = [+ `${result.file}${result.exists ? '' : ' (not in the working tree)'}`,+ ];+ if (result.records.length === 0) {+ lines.push(+ result.decisions.length > 0+ ? ' No whole record links to this path; it cites the claims below.'+ : ' No record links to this path.',+ );+ }+ for (const record of result.records) {+ const routes = record.routes+ .map(route => `${route.via} ${route.detail}`)+ .join('; ');+ const status =+ record.authority === 'current' ? '' : ` [${record.authority}]`;+ lines.push(` ${record.path} ${record.id}${status}`);+ lines.push(` via ${routes}`);+ }+ if (result.decisions.length > 0) {+ lines.push(+ ' Single claims or decisions cited by the file or a record above:',+ );+ for (const decision of result.decisions) {+ const routes = decision.routes+ .map(route => `${route.via} ${route.detail}`)+ .join('; ');+ lines.push(` ${decision.path} ${decision.id}`);+ lines.push(` via ${routes}`);+ }+ }+ if (result.decidingSpecs.length > 0) {+ lines.push(' Specs that decided a record above:');+ for (const record of result.decidingSpecs) {+ const routes = record.routes+ .map(route => `${route.via} ${route.detail}`)+ .join('; ');+ lines.push(` ${record.path} ${record.id}`);+ lines.push(` via ${routes}`);+ }+ }+ const byRecord = new Map();+ for (const claim of result.globalClaims) {+ const list = byRecord.get(claim.path) ?? [];+ list.push(`${claim.claimId} (${claim.trigger})`);+ byRecord.set(claim.path, list);+ }+ lines.push(+ ` Global claims for triggers ${result.triggers.join(', ') || '(none)'} — ${result.triggerSource}:`,+ );+ if (byRecord.size === 0) lines.push(' none');+ for (const [recordPath, claims] of byRecord) {+ lines.push(` ${recordPath} ${[...new Set(claims)].join(', ')}`);+ }+ return lines.join('\n');+}++const WORKING_TREE_NOTE =+ "Records are read from the working tree. On a pull-request branch they include that branch's proposed records, so this is a lookup, not review authority.\n";++const USAGE = `Usage: pnpm specs:for <file...> [--json] [--include-draft] [--triggers a,b]+ pnpm specs:for --unreached [--json]+ pnpm specs:for --unrouted [--json]++Lists every knowledge record that governs each file, with the link that put it+there, the specs that decided those records, and the trigger-routed global+claims. --unreached lists current records no other tracked file reaches.+--unrouted lists tracked files no current record governs.`;++function main(argv) {+ const files = [];+ let json = false;+ let includeDraft = false;+ let unreached = false;+ let unrouted = false;+ let triggers;+ for (let i = 0; i < argv.length; i += 1) {+ const arg = argv[i];+ if (arg === '--json') json = true;+ else if (arg === '--include-draft') includeDraft = true;+ else if (arg === '--unreached') unreached = true;+ else if (arg === '--unrouted') unrouted = true;+ else if (arg === '--triggers') {+ const value = argv[i + 1];+ if (!value || value.startsWith('--')) {+ throw new Error('--triggers requires a comma-separated list.');+ }+ triggers = value+ .split(',')+ .map(item => item.trim())+ .filter(Boolean);+ i += 1;+ } else if (arg === '--help' || arg === '-h') {+ console.log(USAGE);+ return 0;+ } else if (arg.startsWith('--')) {+ throw new Error(`Unknown option ${arg}.\n\n${USAGE}`);+ } else files.push(arg);+ }++ const index = loadKnowledgeIndex(DEFAULT_ROOT);+ if (unreached) {+ const result = findUnreachedRecords(index, trackedFiles(DEFAULT_ROOT));+ if (json) console.log(JSON.stringify(result, null, 2));+ else {+ console.log(+ `${result.length} current records are not reached by any tracked file:`,+ );+ for (const record of result)+ console.log(` ${record.path} ${record.id}`);+ }+ return 0;+ }+ if (unrouted) {+ const result = findUnroutedFiles(index, trackedFiles(DEFAULT_ROOT));+ if (json) console.log(JSON.stringify(result, null, 2));+ else {+ const byDirectory = new Map();+ for (const file of result) {+ const key = file.split('/').slice(0, 3).join('/');+ byDirectory.set(key, (byDirectory.get(key) ?? 0) + 1);+ }+ console.log(+ `${result.length} tracked files have no governing current record:`,+ );+ for (const [directory, count] of [...byDirectory].sort(+ (left, right) => right[1] - left[1],+ )) {+ console.log(` ${String(count).padStart(5)} ${directory}`);+ }+ }+ return 0;+ }+ if (files.length === 0) {+ console.error(USAGE);+ return 2;+ }+ const cwd = process.env.INIT_CWD ?? process.cwd();+ const results = files.map(file =>+ resolveSpecsForFile(index, path.resolve(cwd, file), {+ includeDraft,+ triggers,+ }),+ );+ if (json) console.log(JSON.stringify(results, null, 2));+ else {+ console.log(WORKING_TREE_NOTE);+ console.log(results.map(formatResult).join('\n\n'));+ }+ return 0;+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ process.exitCode = main(process.argv.slice(2));+}diff --git a/scripts/specs-for-file.test.mjs b/scripts/specs-for-file.test.mjsnew file mode 100644index 0000000000..68d7dcb021--- /dev/null+++ b/scripts/specs-for-file.test.mjs@@ -0,0 +1,793 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import {execFileSync} from 'node:child_process';+import os from 'node:os';+import path from 'node:path';+import {afterEach, describe, expect, it} from 'vitest';+import {+ GLOBAL_REVIEW_TRIGGERS,+ collectGlobalReviewMatches,+} from './check-knowledge.mjs';+import {+ findUnreachedRecords,+ findUnroutedFiles,+ loadKnowledgeIndex,+ resolveSpecsForFile,+} from './specs-for-file.mjs';++const repoRoot = path.resolve(import.meta.dirname, '..');+const roots = [];++afterEach(() => {+ for (const root of roots.splice(0)) {+ fs.rmSync(root, {recursive: true, force: true});+ }+});++function fixtureRoot() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-specs-for-'));+ roots.push(root);+ return root;+}++function write(root, relative, content = '') {+ const absolute = path.join(root, relative);+ fs.mkdirSync(path.dirname(absolute), {recursive: true});+ fs.writeFileSync(absolute, content);+}++function frontmatterValue(value) {+ return Array.isArray(value) ? `[${value.join(', ')}]` : String(value);+}++function writeRecord(root, relative, fields, body = '') {+ const lines = Object.entries({authority: 'current', ...fields}).map(+ ([key, value]) => `${key}: ${frontmatterValue(value)}`,+ );+ write(root, relative, `---\n${lines.join('\n')}\n---\n\n# Record\n${body}`);+}++function globalBlock(triggers) {+ return [+ '',+ '<!-- review-applicability:v1 -->',+ '',+ '```json',+ JSON.stringify({scope: 'global', triggers}),+ '```',+ '',+ '## Requirements',+ '',+ ...Object.values(triggers)+ .flat()+ .map(id => `- **${id} — Claim ${id}.** Detail.`),+ '',+ ].join('\n');+}++/**+ * A small repository: Popover (component + family + architecture + deciding+ * spec), a Dialog module directory, a tooling architecture, and a docs topic.+ */+function popoverFixture() {+ const root = fixtureRoot();+ write(root, 'packages/core/src/Popover/Popover.tsx');+ write(root, 'packages/core/src/Popover/Popover.test.tsx');+ write(+ root,+ 'packages/core/src/Popover/Popover.doc.mjs',+ "export const docs = {name: 'Popover', usage: {anatomy: [{name: 'Table'}]}, components: [{name: 'PopoverTrigger', description: 'Opens it.'}, {name: 'Item'}]};\n",+ );+ writeRecord(root, 'packages/core/src/Popover/Popover.spec.md', {+ kind: 'component',+ id: 'component:Popover',+ review_triggers: ['behavior', 'layering'],+ verified_by: ['packages/core/src/Popover/Popover.test.tsx'],+ families: ['family:overlay-dismissal'],+ architecture: ['architecture:layer-runtime'],+ modules: [],+ });+ writeRecord(root, 'docs/families/overlay-dismissal.md', {+ kind: 'family',+ id: 'family:overlay-dismissal',+ members: ['component:Popover', 'component:Tooltip'],+ architecture: [],+ deciding_specs: ['spec:AST-003'],+ });+ writeRecord(root, 'docs/architecture/layer-runtime.md', {+ kind: 'architecture',+ id: 'architecture:layer-runtime',+ applies_to: ['packages/core/src/Layer/'],+ verified_by: ['scripts/layer-check.mjs'],+ deciding_specs: [],+ });+ writeRecord(root, 'docs/specs/AST-003/spec.md', {+ kind: 'system-spec',+ id: 'spec:AST-003',+ affects_architecture: ['architecture:layer-runtime'],+ affects_families: [],+ affects_consumer_docs: [],+ });+ writeRecord(root, 'docs/specs/AST-013/spec.md', {+ kind: 'system-spec',+ id: 'spec:AST-013',+ affects_architecture: [],+ affects_families: [],+ affects_consumer_docs: ['Tooltip', 'browser-support'],+ });+ writeRecord(+ root,+ 'docs/specs/AST-020/spec.md',+ {+ kind: 'system-spec',+ id: 'spec:AST-020',+ affects_architecture: [],+ affects_families: [],+ affects_consumer_docs: [],+ },+ globalBlock({behavior: ['FR1'], testing: ['FR2']}),+ );+ writeRecord(root, 'docs/specs/AST-090/spec.md', {+ kind: 'system-spec',+ id: 'spec:AST-090',+ authority: 'draft',+ affects_architecture: [],+ affects_families: ['family:overlay-dismissal'],+ affects_consumer_docs: [],+ });++ write(root, 'packages/core/src/Dialog/Dialog.tsx');+ write(root, 'packages/core/src/Dialog/modules/DialogHeader.tsx');+ write(root, 'packages/core/src/Dialog/modules/DialogHeader.test.tsx');+ write(root, 'packages/core/src/Dialog/modules/DialogFooter.tsx');+ writeRecord(root, 'packages/core/src/Dialog/modules/DialogHeader.spec.md', {+ kind: 'module',+ id: 'module:Dialog/DialogHeader',+ parent_component: 'component:Dialog',+ references: [],+ });+ writeRecord(root, 'packages/core/src/Dialog/modules/DialogBody.spec.md', {+ kind: 'module',+ id: 'module:Dialog/DialogBody',+ parent_component: 'component:Dialog',+ references: [],+ });+ write(root, 'packages/core/src/Table/plugins/activation/useActivation.ts');+ write(root, 'packages/core/src/Table/plugins/activation/helpers/key.ts');+ writeRecord(+ root,+ 'packages/core/src/Table/plugins/activation/useTableActivation.spec.md',+ {+ kind: 'module',+ id: 'module:Table/useTableActivation',+ parent_component: 'component:Table',+ references: [],+ },+ );++ write(root, 'packages/core/src/Layer/Layer.tsx');+ write(root, 'packages/core/src/LayerProvider/LayerProvider.tsx');+ write(root, 'scripts/layer-check.mjs');+ write(root, 'packages/cli/assets/docs/browser-support.doc.mjs');+ write(root, 'packages/cli/assets/docs/tree/browser-support.doc.mjs');+ write(root, 'apps/docsite/src/content/blog/posts/release.md');+ writeRecord(root, 'docs/families/data-display.md', {+ kind: 'family',+ id: 'family:data-display',+ members: ['component:Table', 'component:Item', 'component:ChatHeadingItem'],+ architecture: [],+ deciding_specs: [],+ });+ write(root, 'packages/core/src/Drawer/Drawer.tsx');+ writeRecord(root, 'packages/core/src/Drawer/Drawer.spec.md', {+ kind: 'component',+ id: 'component:Drawer',+ authority: 'draft',+ review_triggers: ['motion'],+ verified_by: [],+ families: [],+ architecture: ['architecture:container-padding'],+ system_specs: ['spec:AST-017/DEC-1'],+ modules: [],+ });+ writeRecord(root, 'docs/architecture/container-padding.md', {+ kind: 'architecture',+ id: 'architecture:container-padding',+ applies_to: ['packages/core/src/Layout/'],+ verified_by: [],+ deciding_specs: [],+ });+ write(+ root,+ 'packages/core/src/Chat/Chat.doc.mjs',+ "export const docs = {name: 'Chat'};\n",+ );+ write(root, 'packages/core/src/Chat/ChatMessageList.tsx');+ write(root, 'packages/core/src/Chat/ChatComposerDrawer.tsx');+ write(root, 'packages/core/src/Chat/ChatComposerDrawer.test.tsx');+ write(+ root,+ 'packages/core/src/Chat/__tests__/ChatComposerDrawer.a11y.states.ts',+ );+ write(root, 'packages/core/src/Chat/ChatHeadingItem.tsx');+ writeRecord(root, 'packages/core/src/Chat/ChatComposerDrawer.spec.md', {+ kind: 'component',+ id: 'component:ChatComposerDrawer',+ review_triggers: ['motion'],+ verified_by: [],+ families: [],+ architecture: [],+ modules: [],+ });+ write(root, 'packages/core/src/Markdown/Markdown.tsx');+ write(root, 'packages/core/src/Markdown/plugins/headingLinks.ts');+ write(root, 'packages/core/src/Markdown/plugins/softBreaks.ts');+ writeRecord(root, 'packages/core/src/Markdown/modules/headingLinks.spec.md', {+ kind: 'module',+ id: 'module:Markdown/headingLinks',+ parent_component: 'component:Markdown',+ references: [],+ });+ writeRecord(root, 'packages/core/src/Markdown/modules/softBreaks.spec.md', {+ kind: 'module',+ id: 'module:Markdown/softBreaks',+ parent_component: 'component:Markdown',+ references: [],+ });+ write(root, 'packages/core/src/hooks/useMenuPress.ts');+ write(root, 'packages/core/src/hooks/useMenuPress.test.tsx');+ write(root, 'packages/core/src/hooks/useEntryAnimation.ts');+ write(+ root,+ 'packages/core/src/hooks/useMenuPress.doc.mjs',+ "export const docs = {name: 'useMenuPress'};\n",+ );+ write(+ root,+ 'packages/core/src/hooks/useEntryAnimation.doc.mjs',+ "export const docs = {name: 'useEntryAnimation'};\n",+ );+ writeRecord(+ root,+ 'packages/core/src/DropdownMenu/modules/useMenuPress.spec.md',+ {+ kind: 'module',+ id: 'module:DropdownMenu/useMenuPress',+ parent_component: 'component:DropdownMenu',+ verified_by: ['packages/core/src/hooks/useMenuPress.test.tsx'],+ references: [],+ },+ );+ writeRecord(root, 'docs/specs/AST-014/spec.md', {+ kind: 'system-spec',+ id: 'spec:AST-014',+ affects_architecture: [],+ affects_families: [],+ affects_consumer_docs: ['useEntryAnimation'],+ });+ write(root, 'apps/sandbox/src/app/(fullscreen)/pages/perf/benchmark.test.ts');+ writeRecord(root, 'packages/core/src/Markdown/Markdown.spec.md', {+ kind: 'component',+ id: 'component:Markdown',+ review_triggers: ['behavior'],+ verified_by: [+ 'apps/sandbox/src/app/(fullscreen)/pages/perf/benchmark.test.ts',+ 'browser check of the rendered page',+ ],+ families: [],+ architecture: [],+ system_specs: ['spec:AST-017/FR3'],+ modules: [],+ });+ write(root, 'packages/cli/assets/docs/color.doc.mjs');+ write(root, 'packages/core/src/utils/color.ts');+ writeRecord(root, 'docs/specs/AST-008/spec.md', {+ kind: 'system-spec',+ id: 'spec:AST-008',+ affects_architecture: [],+ affects_families: [],+ affects_consumer_docs: ['color'],+ });+ write(root, 'packages/core/src/TabList/TabList.tsx');+ writeRecord(root, 'packages/core/src/TabList/TabList.spec.md', {+ kind: 'component',+ id: 'component:TabList',+ review_triggers: ['behavior'],+ verified_by: [],+ families: [],+ architecture: [],+ system_specs: ['spec:AST-017/DEC-1'],+ modules: [],+ });+ writeRecord(root, 'docs/specs/AST-017/spec.md', {+ kind: 'system-spec',+ id: 'spec:AST-017',+ affects_architecture: [],+ affects_families: [],+ affects_consumer_docs: [],+ });+ write(+ root,+ 'scripts/fixture-heavy.test.mjs',+ "const record = 'docs/specs/AST-013/spec.md';\nconst link = '../AST-013/spec.md';\n",+ );+ write(+ root,+ 'packages/core/src/utils/plainDate.ts',+ '// Resolves wall time per AST-013 and docs/architecture/layer-runtime.md.\n// Day boundaries follow AST-017/DEC-1 and AST-020/FR15 (see AST-020 FR9). Not AST-0130 or XAST-020.\n',+ );+ return root;+}++function ids(entries) {+ return entries.map(entry => entry.id).sort();+}++describe('resolveSpecsForFile', () => {+ it('routes a component file to its record, family, inherited architecture, and deciding specs', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'packages/core/src/Popover/Popover.tsx',+ );+ expect(ids(result.records)).toEqual([+ 'architecture:layer-runtime',+ 'component:Popover',+ 'family:overlay-dismissal',+ ]);+ const family = result.records.find(+ record => record.id === 'family:overlay-dismissal',+ );+ expect(family.routes).toEqual([+ {via: 'members', detail: 'component:Popover'},+ {via: 'inherited:families', detail: 'component:Popover'},+ ]);+ expect(ids(result.decidingSpecs)).toEqual(['spec:AST-003']);+ expect(result.component).toEqual({+ package: 'core',+ root: 'Popover',+ names: ['Popover', 'PopoverTrigger'],+ });+ expect(result.source).toBe('working-tree');+ });++ it('keeps draft records out unless asked', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const file = 'packages/core/src/Popover/Popover.tsx';+ expect(ids(resolveSpecsForFile(index, file).decidingSpecs)).not.toContain(+ 'spec:AST-090',+ );+ expect(+ ids(resolveSpecsForFile(index, file, {includeDraft: true}).decidingSpecs),+ ).toContain('spec:AST-090');+ });++ it('routes a module by its same-stem sources and a dedicated module directory by subtree', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const header = resolveSpecsForFile(+ index,+ 'packages/core/src/Dialog/modules/DialogHeader.test.tsx',+ );+ expect(ids(header.records)).toEqual(['module:Dialog/DialogHeader']);+ const footer = resolveSpecsForFile(+ index,+ 'packages/core/src/Dialog/modules/DialogFooter.tsx',+ );+ expect(footer.records).toEqual([]);+ const plugin = resolveSpecsForFile(+ index,+ 'packages/core/src/Table/plugins/activation/helpers/key.ts',+ );+ expect(ids(plugin.records)).toEqual([+ 'family:data-display',+ 'module:Table/useTableActivation',+ ]);+ });++ it('matches applies_to by path segment, never by string prefix', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ expect(+ ids(+ resolveSpecsForFile(index, 'packages/core/src/Layer/Layer.tsx').records,+ ),+ ).toContain('architecture:layer-runtime');+ expect(+ resolveSpecsForFile(+ index,+ 'packages/core/src/LayerProvider/LayerProvider.tsx',+ ).records,+ ).toEqual([]);+ });++ it('routes verified_by evidence to the record it verifies', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(index, 'scripts/layer-check.mjs');+ expect(result.records[0]).toMatchObject({+ id: 'architecture:layer-runtime',+ routes: [{via: 'verified_by', detail: 'scripts/layer-check.mjs'}],+ });+ });++ it('routes consumer-doc ids to their topic files', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ for (const file of [+ 'packages/cli/assets/docs/browser-support.doc.mjs',+ 'packages/cli/assets/docs/tree/browser-support.doc.mjs',+ ]) {+ expect(ids(resolveSpecsForFile(index, file).records)).toEqual([+ 'spec:AST-013',+ ]);+ }+ });++ it('takes component names from docs and full component entries, never anatomy parts or partial entries', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'packages/core/src/Popover/Popover.tsx',+ );+ expect(ids(result.records)).not.toContain('family:data-display');+ });++ it('never lets a draft record steer the result unless drafts are asked for', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const file = 'packages/core/src/Drawer/Drawer.tsx';+ const current = resolveSpecsForFile(index, file);+ expect(current.records).toEqual([]);+ expect(current.decisions).toEqual([]);+ expect(current.triggers).not.toEqual(['motion']);+ const withDrafts = resolveSpecsForFile(index, file, {includeDraft: true});+ expect(ids(withDrafts.records)).toEqual([+ 'architecture:container-padding',+ 'component:Drawer',+ ]);+ expect(withDrafts.triggers).toEqual(['motion']);+ });++ it('lists a decision-scoped citation as that decision, not the whole record', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'packages/core/src/TabList/TabList.tsx',+ );+ expect(ids(result.records)).toEqual(['component:TabList']);+ expect(result.decisions).toEqual([+ expect.objectContaining({+ id: 'spec:AST-017/DEC-1',+ recordId: 'spec:AST-017',+ decision: 'DEC-1',+ routes: [{via: 'inherited:system_specs', detail: 'component:TabList'}],+ }),+ ]);+ });++ it('places a member component record only over its same-stem files', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const unrelated = resolveSpecsForFile(+ index,+ 'packages/core/src/Chat/ChatMessageList.tsx',+ );+ expect(ids(unrelated.records)).toEqual([]);+ expect(unrelated.triggers).not.toEqual(['motion']);+ const own = resolveSpecsForFile(+ index,+ 'packages/core/src/Chat/ChatComposerDrawer.test.tsx',+ );+ expect(ids(own.records)).toEqual(['component:ChatComposerDrawer']);+ expect(own.triggers).toEqual(['motion']);+ expect(+ ids(+ resolveSpecsForFile(+ index,+ 'packages/core/src/Chat/__tests__/ChatComposerDrawer.a11y.states.ts',+ ).records,+ ),+ ).toEqual(['component:ChatComposerDrawer']);+ });++ it('names a member without its own consumer doc by its file stem', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ expect(+ ids(+ resolveSpecsForFile(index, 'packages/core/src/Chat/ChatHeadingItem.tsx')+ .records,+ ),+ ).toEqual(['family:data-display']);+ });++ it('places a module record over its same-stem sources anywhere in its component root', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ expect(+ ids(+ resolveSpecsForFile(+ index,+ 'packages/core/src/Markdown/plugins/headingLinks.ts',+ ).records,+ ),+ ).toEqual(['component:Markdown', 'module:Markdown/headingLinks']);+ expect(+ ids(+ resolveSpecsForFile(index, 'packages/core/src/Markdown/Markdown.tsx')+ .records,+ ),+ ).toEqual(['component:Markdown']);+ });++ it('places a module record beside the same-stem verified_by evidence outside its root', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const source = resolveSpecsForFile(+ index,+ 'packages/core/src/hooks/useMenuPress.ts',+ );+ expect(ids(source.records)).toEqual(['module:DropdownMenu/useMenuPress']);+ expect(source.records[0].routes[0].via).toBe('placement');+ expect(+ ids(+ resolveSpecsForFile(+ index,+ 'packages/core/src/hooks/useEntryAnimation.ts',+ ).records,+ ),+ ).toEqual(['spec:AST-014']);+ });++ it('names a file in a shared directory by its own same-stem doc', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'packages/core/src/hooks/useMenuPress.ts',+ );+ expect(result.component.names).toEqual(['useMenuPress']);+ expect(+ resolveSpecsForFile(index, 'packages/core/src/Chat/ChatMessageList.tsx')+ .component.names,+ ).toEqual(['Chat', 'ChatMessageList']);+ expect(ids(result.records)).not.toContain('spec:AST-014');+ });++ it('matches declared paths with route-group segments, and skips prose entries', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'apps/sandbox/src/app/(fullscreen)/pages/perf/benchmark.test.ts',+ );+ expect(result.records[0]).toMatchObject({+ id: 'component:Markdown',+ routes: [+ {+ via: 'verified_by',+ detail:+ 'apps/sandbox/src/app/(fullscreen)/pages/perf/benchmark.test.ts',+ },+ ],+ });+ });++ it('lists a claim-scoped reference as that claim, not the whole record', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'packages/core/src/Markdown/Markdown.tsx',+ );+ expect(ids(result.records)).toEqual(['component:Markdown']);+ expect(result.decisions).toEqual([+ expect.objectContaining({+ id: 'spec:AST-017/FR3',+ decision: 'FR3',+ routes: [{via: 'inherited:system_specs', detail: 'component:Markdown'}],+ }),+ ]);+ });++ it('keeps a consumer-doc topic id on its topic file, not on files sharing its stem', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ expect(+ resolveSpecsForFile(index, 'packages/core/src/utils/color.ts').records,+ ).toEqual([]);+ expect(+ ids(+ resolveSpecsForFile(index, 'packages/cli/assets/docs/color.doc.mjs')+ .records,+ ),+ ).toEqual(['spec:AST-008']);+ });++ it('ignores spec numbers inside record paths', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(index, 'scripts/fixture-heavy.test.mjs');+ expect(result.records).toEqual([]);+ expect(result.decisions).toEqual([]);+ });++ it('routes a file to the system specs it cites by number', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'packages/core/src/utils/plainDate.ts',+ );+ expect(+ result.records.map(record => [+ record.id,+ record.routes[0].via,+ record.routes[0].detail,+ ]),+ ).toEqual([['spec:AST-013', 'mentioned', 'AST-013']]);+ expect(result.decisions.map(decision => decision.id)).toEqual([+ 'spec:AST-017/DEC-1',+ 'spec:AST-020/FR15',+ 'spec:AST-020/FR9',+ ]);+ expect(ids(result.records)).not.toContain('spec:AST-020');+ });++ it('reports a path no record reaches instead of guessing', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ const result = resolveSpecsForFile(+ index,+ 'apps/docsite/src/content/blog/posts/release.md',+ );+ expect(result.records).toEqual([]);+ expect(result.decidingSpecs).toEqual([]);+ });++ it('selects global claims exactly as the review baseline router does', () => {+ const root = popoverFixture();+ const index = loadKnowledgeIndex(root);+ const records = index.records.map(record => ({+ path: record.path,+ content: record.content,+ }));+ const project = matches =>+ matches.map(({recordId, path: recordPath, trigger, claimId, claim}) => ({+ recordId,+ path: recordPath,+ trigger,+ claimId,+ claim,+ }));++ const local = resolveSpecsForFile(+ index,+ 'packages/core/src/Popover/Popover.tsx',+ );+ expect(local.triggers).toEqual(['behavior', 'layering']);+ expect(local.globalClaims).toEqual(+ project(collectGlobalReviewMatches(records, local.triggers, null)),+ );+ expect(local.globalClaims.map(claim => claim.claimId)).toEqual(['FR1']);++ const requested = resolveSpecsForFile(index, 'scripts/layer-check.mjs', {+ triggers: ['testing'],+ });+ expect(requested.globalClaims.map(claim => claim.claimId)).toEqual(['FR2']);++ const none = resolveSpecsForFile(+ index,+ 'apps/docsite/src/content/blog/posts/release.md',+ );+ expect(none.triggers).toEqual([...GLOBAL_REVIEW_TRIGGERS].sort());+ });+});++describe('coverage audits', () => {+ it('lists current records only their own file reaches', () => {+ const root = popoverFixture();+ const index = loadKnowledgeIndex(root);+ const files = [+ 'packages/core/src/Popover/Popover.tsx',+ 'docs/specs/AST-020/spec.md',+ 'docs/specs/AST-013/spec.md',+ ];+ expect(ids(findUnreachedRecords(index, files))).toEqual([+ 'architecture:container-padding',+ 'component:ChatComposerDrawer',+ 'component:Markdown',+ 'component:TabList',+ 'family:data-display',+ 'module:Dialog/DialogBody',+ 'module:Dialog/DialogHeader',+ 'module:DropdownMenu/useMenuPress',+ 'module:Markdown/headingLinks',+ 'module:Markdown/softBreaks',+ 'module:Table/useTableActivation',+ 'spec:AST-008',+ 'spec:AST-013',+ 'spec:AST-014',+ 'spec:AST-017',+ 'spec:AST-020',+ ]);+ expect(+ ids(+ findUnreachedRecords(index, [+ ...files,+ 'packages/core/src/TabList/TabList.tsx',+ ]),+ ),+ ).not.toContain('spec:AST-017');+ });++ it('lists tracked files without a governing record', () => {+ const index = loadKnowledgeIndex(popoverFixture());+ expect(+ findUnroutedFiles(index, [+ 'packages/core/src/Popover/Popover.tsx',+ 'apps/docsite/src/content/blog/posts/release.md',+ ]),+ ).toEqual(['apps/docsite/src/content/blog/posts/release.md']);+ });+});++describe('repository records', () => {+ const index = loadKnowledgeIndex(repoRoot);++ it('routes every current component and module record from each same-stem source', () => {+ const tracked = execFileSync('git', ['-C', repoRoot, 'ls-files'], {+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ })+ .split('\n')+ .filter(Boolean);+ // A record with no same-stem source is not placed from any file. That is+ // allowed here: reachability of every current record is a separate check.+ const missing = [];+ for (const record of index.records) {+ if (record.authority !== 'current' || !record.classified) continue;+ const {packageName, componentRoot, publicName, layout} =+ record.classified;+ const root =+ layout === 'flat'+ ? `packages/${packageName}/src/`+ : `packages/${packageName}/src/${componentRoot}/`;+ const evidenceDirectories = new Set(+ (record.frontmatter.get('verified_by') ?? [])+ .filter(+ entry => path.posix.basename(entry).split('.')[0] === publicName,+ )+ .map(entry => `${path.posix.dirname(entry)}/`),+ );+ const candidates = tracked.filter(+ file =>+ !file.endsWith('.spec.md') &&+ path.posix.basename(file).split('.')[0] === publicName &&+ (file.startsWith(root) ||+ (record.kind === 'module' &&+ evidenceDirectories.has(`${path.posix.dirname(file)}/`))),+ );+ for (const file of candidates) {+ if (+ !ids(+ resolveSpecsForFile(index, file, {triggers: []}).records,+ ).includes(record.id)+ ) {+ missing.push(`${record.id} from ${file}`);+ }+ }+ }+ expect(missing).toEqual([]);+ });++ it('routes every current architecture record from each applies_to path', () => {+ const missing = [];+ for (const record of index.records) {+ if (record.authority !== 'current' || record.kind !== 'architecture') {+ continue;+ }+ for (const entry of record.frontmatter.get('applies_to') ?? []) {+ const target = path.join(repoRoot, entry);+ if (!fs.existsSync(target)) continue;+ const file = fs.statSync(target).isDirectory()+ ? path.posix.join(entry.replace(/\/+$/, ''), '__probe__.ts')+ : entry;+ if (+ !ids(+ resolveSpecsForFile(index, file, {triggers: []}).records,+ ).includes(record.id)+ ) {+ missing.push(`${record.id} from ${file}`);+ }+ }+ }+ expect(missing).toEqual([]);+ });+});