An open source design system that's fully customizable and agent ready
TypeScript
tooling(knowledge): records route the claims of shared concerns a change touches (#9145)
Cindy Zhangdae84a757181
diff --git a/AGENTS.md b/AGENTS.mdindex f944dfa24e..480344c028 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -30,6 +30,9 @@ 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.+- Before editing a path, run `pnpm specs:for <path>`. After editing, before+ you commit or push, run `pnpm specs:for --diff origin/main` and follow every+ concern-routed claim.- 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 triggersroute. It reads the working tree, so on a pull-request branch it shows thatdiff --git a/docs/README.md b/docs/README.mdindex 1054f2fd59..4ca15a71f0 100644--- a/docs/README.md+++ b/docs/README.md@@ -131,7 +131,11 @@ inherit. Only visible records are followed, so a draft never adds a link unlessdecision (`spec:AST-NNN/FR3`) lists that claim, not the whole record. The specs thatdecided a linked record are listed separately, as are the global claims thematched component and module triggers route (the same selection as-`review-global-baselines.mjs`). A path with no linked record is reported as+`review-global-baselines.mjs`). With `--diff origin/main` (or+`--diff <base>..<head>`) it reads the change, lists its files when none are+named, and puts first the claims whose owning record's `concerns` the added+lines match. The default view lists the claims and the linked record ids; `--records`+shows how each record links. A path with no linked record is reported assuch. Records are read from the working tree, so on a pull-request branch theresult includes that branch's proposed records and is not review authority.`pnpm specs:for --unrouted` lists tracked files with no governing record;diff --git a/docs/architecture/interaction-modality.md b/docs/architecture/interaction-modality.mdindex a351692a92..724ca80876 100644--- a/docs/architecture/interaction-modality.md+++ b/docs/architecture/interaction-modality.md@@ -38,6 +38,30 @@ deciding_specs: [spec:AST-100/DEC-1, spec:AST-094/DEC-17]"scope": "global","triggers": {"interaction": ["INV1", "INV2", "INV3", "INV4", "INV7", "INV8", "INV11"]+ },+ "concerns": {+ "modality-tracking": {+ "names": [+ "useInteractionModalityTracking",+ "useInteractionModalityTrackingFor",+ "trackInteractionModalityIn",+ "getInteractionModality"+ ],+ "patterns": ["addEventListener\\(\\s*['\"](?:pointerdown|keydown)['\"]"],+ "claims": ["INV1", "INV2", "INV3"]+ },+ "focus-return": {+ "names": [+ "focusForLastInput",+ "isFocusDetached",+ "useFocusReturnVisibility"+ ],+ "claims": ["INV1"]+ },+ "press-tracking": {+ "names": ["createActionGroupTracker", "useMenuPress"],+ "claims": ["INV13"]+ }}}```diff --git a/docs/architecture/knowledge-contracts.md b/docs/architecture/knowledge-contracts.mdindex a4e7768ed2..769a41aa27 100644--- a/docs/architecture/knowledge-contracts.md+++ b/docs/architecture/knowledge-contracts.md@@ -14,6 +14,7 @@ verified_by:[scripts/check-knowledge.test.mjs,scripts/specs-for-file.test.mjs,+ scripts/lib/review-diff.test.mjs,.github/scripts/change-scope.test.mjs,.github/scripts/component-design-decisions.test.mjs,.github/scripts/lib/classify-visual.test.mjs,@@ -100,7 +101,8 @@ changed code or theme sourceA lookup can also start from any repository path. `pnpm specs:for <path>`lists every current record linked to that path, the system specs that decided-those records, and the global claims the path's component triggers route. It+those records, and the global claims the path's component triggers route; with+`--diff`, the claims the change's concerns route come first (INV20). Itfollows only links that records and files declare:- placement: the record itself, the component, module, or theme record whose@@ -246,12 +248,17 @@ Every record is either:- **INV20 — Global review routing is explicit and claim-scoped.** A cross-cuttingbaseline participates without a component backlink only when its`review-applicability:v1` block declares `scope: "global"` and maps a semantic- trigger to exact claim ids in that same record. Review loads matching current+ trigger or a concern to exact claim ids in that same record. Review loads matching currentglobal claims before narrower records, then resolves the direct component,module, or family owner first when it governs the delta. The marker never makesthe whole record, adjacent claims, drafts, or proposed-head authority govern.Every routed match records the base authority commit, record digest, record id,- path, trigger, claim id, claim title, and deterministic match reason.+ path, trigger or concern, claim id, claim title, and deterministic match+ reason. A record that owns a shared concern MAY list it in the block's+ `concerns` map: the shared utility's names, the code patterns that re-implement it, and+ the claims it routes. A change whose added shipped-source lines match a+ concern routes those claims whatever the component record's+ `review_triggers` list, and each match names the line that matched.- **INV21 — Component-local visual intent stays local and durable.** The optional`### Design decisions` table under `## Design relationships` belongs only tocomponent- or module-local appearance intent that a future redesign must@@ -375,11 +382,31 @@ In an opted-in record, replace the example marker with`public-api`, `react-runtime`, `responsive`, `scrolling`, `specification`,`styling`, `testing`, `theming`, `tokens`, and `visual`. Every trigger has anon-empty list of unique claim ids, and each id resolves to an explicit numbered-claim in that record. The checked-in validator rejects unsupported triggers,-malformed blocks, missing or duplicate claims, and empty routing.+claim in that record. A block may add, or carry instead of `triggers`, a+`concerns` map (INV20). Each lower-kebab concern lists `claims` and at least one+of `names` (identifiers of the shared utility) and `patterns` (regular+expressions for code that re-implements it):++```json+{+ "scope": "global",+ "concerns": {+ "slot-presence": {+ "names": ["isRenderable"],+ "patterns": ["typeof [\\w.]+ !== 'boolean'"],+ "claims": ["INV16"]+ }+ }+}+```++A concern lives in the record that owns its claims, so a claim is routed from+one source. The checked-in validator rejects unsupported triggers, malformed+blocks, missing or duplicate claims, invalid patterns, and empty routing.`scripts/review-global-baselines.mjs` requires both the exact reviewed head andits full base authority commit, verifies that commit is the head's `origin/main`-merge base, and emits deterministically sorted match rows. It therefore cannot+merge base, emits deterministically sorted match rows, and lists in+`concernMatches` the claims whose concerns the head's added lines match. It therefore cannotread a proposed head as its own authority. Consumers load those rows before narrow lookup, preserve theirprovenance in a review receipt, and apply only the cited claim after the directowner has been resolved.diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.mdindex 62b5ba172f..daa06c4bff 100644--- a/docs/architecture/react-component-runtime.md+++ b/docs/architecture/react-component-runtime.md@@ -47,6 +47,30 @@ deciding_specs:"INV15","INV16"]+ },+ "concerns": {+ "effects-listeners-observers": {+ "patterns": [+ "\\buse(?:Layout|Insertion)?Effect\\b",+ "\\b(?:add|remove)EventListener\\b",+ "\\b(?:Mutation|Resize|Intersection)Observer\\b"+ ],+ "claims": ["INV2", "INV3", "INV5", "INV6"]+ },+ "slot-presence": {+ "names": ["isRenderable"],+ "patterns": ["!= null && typeof [\\w.?]+ !==? ['\"]boolean['\"]"],+ "claims": ["INV16"]+ },+ "modality-tracking": {+ "names": [+ "useInteractionModalityTracking",+ "useInteractionModalityTrackingFor",+ "trackInteractionModalityIn"+ ],+ "patterns": ["addEventListener\\(\\s*['\"](?:pointerdown|keydown)['\"]"],+ "claims": ["INV16"]+ }}}```diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.mdindex af0a409312..6711a65a28 100644--- a/docs/families/overlay-dismissal.md+++ b/docs/families/overlay-dismissal.md@@ -78,6 +78,16 @@ deciding_specs: []"scope": "global","triggers": {"layering": ["FR1", "FR2", "FR3", "FR6"]+ },+ "concerns": {+ "focus-return": {+ "names": [+ "focusForLastInput",+ "isFocusDetached",+ "useFocusReturnVisibility"+ ],+ "claims": ["FR9"]+ }}}```diff --git a/docs/specs/AST-086-status-announcements/spec.md b/docs/specs/AST-086-status-announcements/spec.mdindex b1d1ce4d9c..7bdf6ec09e 100644--- a/docs/specs/AST-086-status-announcements/spec.md+++ b/docs/specs/AST-086-status-announcements/spec.md@@ -27,6 +27,25 @@ affects_consumer_docs:# Status announcement delivery system spec+<!-- review-applicability:v1 -->++```json+{+ "scope": "global",+ "concerns": {+ "announcements": {+ "names": [+ "useAnnounce",+ "useAnnounceRenderedText",+ "useBusyAnnouncement"+ ],+ "patterns": ["aria-live", "role=[\"'{](?:status|alert|log)\\b"],+ "claims": ["FR1", "FR2", "FR3", "FR12"]+ }+ }+}+```+## IntentA screen-reader user hears each status change once, when it happens, at thediff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjsindex 659348f57e..39f7544582 100644--- a/scripts/check-knowledge.mjs+++ b/scripts/check-knowledge.mjs@@ -232,12 +232,7 @@ function parseOverlayBlock(content, markerName, filePath) {};}- const propertyNames = [...block[1].matchAll(/"((?:\\.|[^"\\])*)"\s*:/g)].map(- match => JSON.parse(`"${match[1]}"`),- );- const duplicates = propertyNames.filter(- (name, index) => propertyNames.indexOf(name) !== index,- );+ const duplicates = duplicateJsonKeys(block[1]);if (duplicates.length > 0) {return {config: null,@@ -259,6 +254,41 @@ function parseOverlayBlock(content, markerName, filePath) {}}+/**+ * Keys repeated within one JSON object. `JSON.parse` keeps the last value+ * silently, so a repeated key would hide an entry; the same key in two+ * different objects (two concerns that both list `names`) is not a repeat.+ */+function duplicateJsonKeys(text) {+ const duplicates = [];+ const objects = [];+ for (let index = 0; index < text.length; index += 1) {+ const character = text[index];+ if (character === '{') objects.push(new Set());+ else if (character === '}') objects.pop();+ else if (character === '"') {+ let end = index + 1;+ while (end < text.length && text[end] !== '"') {+ end += text[end] === '\\' ? 2 : 1;+ }+ const raw = text.slice(index, end + 1);+ index = end;+ if (!/^\s*:/.test(text.slice(end + 1))) continue;+ const keys = objects.at(-1);+ let key;+ try {+ key = JSON.parse(raw);+ } catch {+ continue;+ }+ if (keys == null) continue;+ if (keys.has(key)) duplicates.push(key);+ keys.add(key);+ }+ }+ return duplicates;+}+export function parseReviewApplicabilityBlock(content,filePath = '<knowledge record>',@@ -273,9 +303,17 @@ export function validateReviewApplicability() {if (config == null) return [];const problems = [];- if (!exactKeys(config, ['scope', 'triggers'])) {+ const keys =+ config != null && typeof config === 'object' && !Array.isArray(config)+ ? Object.keys(config)+ : [];+ if (+ !keys.includes('scope') ||+ keys.some(key => !['scope', 'triggers', 'concerns'].includes(key)) ||+ !(keys.includes('triggers') || keys.includes('concerns'))+ ) {return [- `${filePath}: ${REVIEW_APPLICABILITY_MARKER} requires exactly scope and triggers.`,+ `${filePath}: ${REVIEW_APPLICABILITY_MARKER} requires scope with triggers, concerns, or both, and nothing else.`,];}if (config.scope !== 'global') {@@ -283,6 +321,16 @@ export function validateReviewApplicability(`${filePath}: ${REVIEW_APPLICABILITY_MARKER} scope must be "global".`,);}+ if (keys.includes('concerns')) {+ problems.push(+ ...validateReviewConcerns(+ config.concerns,+ extractKnowledgeClaims(content),+ filePath,+ ),+ );+ }+ if (!keys.includes('triggers')) return problems;if (config.triggers == null ||typeof config.triggers !== 'object' ||@@ -488,6 +536,175 @@ function isKnowledgeRecordPath(filePath) {return isComponentSpecRecordPath(filePath);}+const REVIEW_CONCERN_NAME_PATTERN = REVIEW_TRIGGER_PATTERN;+const IDENTIFIER_PATTERN = /^[A-Za-z_$][\w$]*$/;++/**+ * A record's `concerns` map names the shared utilities it owns and the code+ * that re-implements them. Each entry lists identifiers (`names`), regular+ * expressions (`patterns`), or both, and the claims they route.+ */+function validateReviewConcerns(concerns, knownClaims, filePath) {+ const where = `${filePath}: ${REVIEW_APPLICABILITY_MARKER} concerns`;+ if (+ concerns == null ||+ typeof concerns !== 'object' ||+ Array.isArray(concerns) ||+ Object.keys(concerns).length === 0+ ) {+ return [`${where} must map at least one concern name to its entry.`];+ }+ const problems = [];+ for (const [name, entry] of Object.entries(concerns)) {+ const at = `${where} ${JSON.stringify(name)}`;+ if (!REVIEW_CONCERN_NAME_PATTERN.test(name)) {+ problems.push(`${at} must use lower-kebab-case.`);+ }+ const entryKeys =+ entry != null && typeof entry === 'object' && !Array.isArray(entry)+ ? Object.keys(entry)+ : null;+ if (+ entryKeys == null ||+ !entryKeys.includes('claims') ||+ entryKeys.some(key => !['names', 'patterns', 'claims'].includes(key))+ ) {+ problems.push(+ `${at} requires claims with names, patterns, or both, and nothing else.`,+ );+ continue;+ }+ const names = entry.names ?? [];+ const patterns = entry.patterns ?? [];+ if (!Array.isArray(names) || !Array.isArray(patterns)) {+ problems.push(`${at} names and patterns must be lists.`);+ continue;+ }+ if (names.length + patterns.length === 0) {+ problems.push(`${at} requires at least one name or pattern.`);+ }+ for (const value of names) {+ if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {+ problems.push(+ `${at} has a name that is not an identifier: ${JSON.stringify(value)}.`,+ );+ }+ }+ for (const value of patterns) {+ try {+ if (typeof value !== 'string' || value.length === 0) throw new Error();+ new RegExp(value);+ } catch {+ problems.push(`${at} has an invalid pattern ${JSON.stringify(value)}.`);+ }+ }+ if (!Array.isArray(entry.claims) || entry.claims.length === 0) {+ problems.push(`${at} requires a non-empty claim list.`);+ continue;+ }+ const seen = new Set();+ for (const claimId of entry.claims) {+ if (+ typeof claimId !== 'string' ||+ !REVIEW_CLAIM_ID_PATTERN.test(claimId)+ ) {+ problems.push(+ `${at} has malformed claim id ${JSON.stringify(claimId)}.`,+ );+ } else if (seen.has(claimId)) {+ problems.push(`${at} repeats claim ${JSON.stringify(claimId)}.`);+ } else if (!knownClaims.has(claimId)) {+ problems.push(+ `${at} references missing claim ${JSON.stringify(claimId)}.`,+ );+ }+ seen.add(claimId);+ }+ }+ return problems;+}++function concernMatchers(entry) {+ return [+ ...(entry.names ?? []).map(name => ({+ label: name,+ expression: new RegExp(+ `(?<![\\w$])${name.replace(/\$/g, '\\$')}(?![\\w$])`,+ ),+ })),+ ...(entry.patterns ?? []).map(pattern => ({+ label: pattern,+ expression: new RegExp(pattern),+ })),+ ];+}++/**+ * Route each claim whose owning record's concern matches an added line.+ * `addedLines` are `{file, line, text}` rows of shipped source a diff adds.+ * Every row names the record, concern, claim, and the first added lines that+ * matched it, so a reviewer sees why the claim applies.+ */+export function collectConcernMatches(records, addedLines, authorityCommit) {+ const matches = [];+ if (addedLines.length === 0) return matches;+ for (const record of records) {+ const parsed = parseReviewApplicabilityBlock(record.content, record.path);+ if (parsed.config?.concerns == null) continue;+ const document = parseKnowledgeDocument(record.content, record.path);+ const problems = [+ ...document.problems,+ ...parsed.problems,+ ...validateReviewApplicability(+ parsed.config,+ record.content,+ record.path,+ ),+ ];+ if (problems.length > 0) throw new Error(problems.join('\n'));+ if (document.frontmatter.get('authority') !== 'current') continue;+ const recordId = document.frontmatter.get('id');+ const claims = extractKnowledgeClaims(record.content);+ const recordDigest = createHash('sha256')+ .update(record.content)+ .digest('hex');+ for (const [concern, entry] of Object.entries(parsed.config.concerns)) {+ const matchers = concernMatchers(entry);+ const evidence = [];+ for (const added of addedLines) {+ for (const matcher of matchers) {+ const found = matcher.expression.exec(added.text);+ if (found) {+ evidence.push({...added, matched: found[0], by: matcher.label});+ break;+ }+ }+ }+ if (evidence.length === 0) continue;+ const first = evidence[0];+ for (const claimId of entry.claims) {+ matches.push({+ recordId,+ path: record.path,+ concern,+ claimId,+ claim: claims.get(claimId),+ utilities: entry.names ?? [],+ matchReason: `Added line ${first.file}:${first.line} matched ${JSON.stringify(first.matched)} in concern ${JSON.stringify(concern)}${entry.names?.length ? ` (shared: ${entry.names.join(', ')})` : ''}, which routes claim ${JSON.stringify(`${recordId}/${claimId}`)}.`,+ evidence: evidence.slice(0, 5),+ authorityCommit,+ recordDigest,+ });+ }+ }+ }+ return matches.sort((left, right) =>+ [left.recordId, left.concern, left.claimId]+ .join('\0')+ .localeCompare([right.recordId, right.concern, right.claimId].join('\0')),+ );+}+export function collectGlobalReviewMatches(records,requestedTriggers,@@ -535,7 +752,7 @@ export function collectGlobalReviewMatches(.update(record.content).digest('hex');for (const trigger of requested) {- for (const claimId of parsed.config.triggers[trigger] ?? []) {+ for (const claimId of parsed.config.triggers?.[trigger] ?? []) {matches.push({recordId,path: record.path,@@ -563,6 +780,24 @@ export function routeGlobalReviewBaselinesAtRevision(authorityCommit,reviewHead,requestedTriggers,+) {+ const {records, authority} = readKnowledgeRecordsAtAuthority(+ root,+ authorityCommit,+ reviewHead,+ );+ return collectGlobalReviewMatches(records, requestedTriggers, authority);+}++/**+ * The knowledge records at a review's base authority commit, after checking+ * that commit is the full, resolved `origin/main` merge base of the reviewed+ * head, so a proposed head can never serve as its own authority.+ */+export function readKnowledgeRecordsAtAuthority(+ root,+ authorityCommit,+ reviewHead,) {const resolvedCommit = execFileSync('git',@@ -625,7 +860,7 @@ export function routeGlobalReviewBaselinesAtRevision({encoding: 'utf8'},),}));- return collectGlobalReviewMatches(records, requestedTriggers, resolvedCommit);+ return {records, authority: resolvedCommit};}function immediateDirectories(directory) {diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjsindex c04cc1d047..447c246665 100644--- a/scripts/check-knowledge.test.mjs+++ b/scripts/check-knowledge.test.mjs@@ -7,6 +7,7 @@ import {execFileSync} from 'node:child_process';import {afterEach, describe, expect, it} from 'vitest';import {composeKnowledgeSchemas,+ collectConcernMatches,collectGlobalReviewMatches,discoverKnowledgeRecords,extractKnowledgeClaims,@@ -417,6 +418,149 @@ describe('global review applicability', () => {);});+ it('keeps the same key in two different objects', () => {+ const record = currentRecord.replace(+ '# Fixture system spec',+ '# Fixture system spec\n\n<!-- review-applicability:v1 -->\n```json\n{"scope":"global","concerns":{"a":{"names":["x"],"claims":["FR1"]},"b":{"names":["y"],"claims":["FR2"]}}}\n```',+ );+ const parsed = parseReviewApplicabilityBlock(record);+ expect(parsed.problems).toEqual([]);+ expect(validateReviewApplicability(parsed.config, record)).toEqual([]);+ });++ it('accepts a concerns map with or without triggers', () => {+ const concerns = {+ 'slot-presence': {+ names: ['isRenderable'],+ patterns: ["typeof [\\w.]+ !== 'boolean'"],+ claims: ['FR1'],+ },+ };+ expect(+ validateReviewApplicability({scope: 'global', concerns}, currentRecord),+ ).toEqual([]);+ expect(+ validateReviewApplicability(+ {scope: 'global', triggers: {'public-api': ['FR2']}, concerns},+ currentRecord,+ ),+ ).toEqual([]);+ });++ it.each([+ [+ 'neither triggers nor concerns',+ {scope: 'global'},+ /triggers, concerns, or both/,+ ],+ [+ 'an unknown block key',+ {+ scope: 'global',+ concerns: {a: {names: ['x'], claims: ['FR1']}},+ extra: 1,+ },+ /and nothing else/,+ ],+ [+ 'an empty concerns map',+ {scope: 'global', concerns: {}},+ /at least one concern/,+ ],+ [+ 'a concern without names or patterns',+ {scope: 'global', concerns: {a: {claims: ['FR1']}}},+ /at least one name or pattern/,+ ],+ [+ 'a concern name that is not an identifier',+ {+ scope: 'global',+ concerns: {a: {names: ['is renderable'], claims: ['FR1']}},+ },+ /not an identifier/,+ ],+ [+ 'an invalid pattern',+ {scope: 'global', concerns: {a: {patterns: ['('], claims: ['FR1']}}},+ /invalid pattern/,+ ],+ [+ 'a concern claim the record lacks',+ {scope: 'global', concerns: {a: {names: ['x'], claims: ['FR99']}}},+ /references missing claim "FR99"/,+ ],+ [+ 'an unknown concern key',+ {+ scope: 'global',+ concerns: {a: {names: ['x'], claims: ['FR1'], owner: 'y'}},+ },+ /claims with names, patterns, or both/,+ ],+ ])('rejects concerns with %s', (_name, config, expected) => {+ expect(+ validateReviewApplicability(config, currentRecord).join('\n'),+ ).toMatch(expected);+ });++ it('routes each claim whose concern matches an added line, with the evidence', () => {+ const record = {+ path: 'docs/specs/AST-900/spec.md',+ content: currentRecord.replace(+ '# Fixture system spec',+ `# Fixture system spec\n\n<!-- review-applicability:v1 -->\n\n\`\`\`json\n${JSON.stringify(+ {+ scope: 'global',+ concerns: {+ 'slot-presence': {+ names: ['isRenderable'],+ patterns: ["typeof [\\w.]+ !== 'boolean'"],+ claims: ['FR1'],+ },+ 'unrelated-concern': {names: ['useScrollLock'], claims: ['FR2']},+ },+ },+ )}\n\`\`\`\n`,+ ),+ };+ const added = [+ {+ file: 'packages/core/src/Badge/Badge.tsx',+ line: 3,+ text: 'const x = 1;',+ },+ {+ file: 'packages/core/src/Badge/Badge.tsx',+ line: 4,+ text: " const hasLabel = label !== '' && label != null && typeof label !== 'boolean';",+ },+ {+ file: 'packages/core/src/Badge/Badge.tsx',+ line: 5,+ text: 'isRenderableish(x);',+ },+ ];+ const matches = collectConcernMatches([record], added, null);+ expect(matches).toEqual([+ expect.objectContaining({+ recordId: 'spec:AST-900',+ concern: 'slot-presence',+ claimId: 'FR1',+ claim: 'Public API stays stable.',+ utilities: ['isRenderable'],+ evidence: [+ expect.objectContaining({+ line: 4,+ matched: "typeof label !== 'boolean'",+ }),+ ],+ }),+ ]);+ expect(matches[0].matchReason).toContain('(shared: isRenderable)');+ expect(collectConcernMatches([record], [], null)).toEqual([]);+ });+it('keeps the canonical claim title when a verification table repeats its id', () => {const record = `${currentRecord}\n| Contract | Verification |\n| --- | --- |\n| FR1 | A test file, not the claim. |\n`;expect(extractKnowledgeClaims(record).get('FR1')).toBe(diff --git a/scripts/lib/__fixtures__/review-diff/css-only.diff b/scripts/lib/__fixtures__/review-diff/css-only.diffnew file mode 100644index 0000000000..23b073eb29--- /dev/null+++ b/scripts/lib/__fixtures__/review-diff/css-only.diff@@ -0,0 +1,21 @@+diff --git a/packages/core/src/Card/Card.css b/packages/core/src/Card/Card.css+index 1111111..2222222 100644+--- a/packages/core/src/Card/Card.css++++ b/packages/core/src/Card/Card.css+@@ -1,4 +1,4 @@+ .card {+- padding: 8px;++ padding: 12px;+ border-radius: 4px;+ }+diff --git a/packages/core/src/Card/Card.tsx b/packages/core/src/Card/Card.tsx+index 3333333..4444444 100644+--- a/packages/core/src/Card/Card.tsx++++ b/packages/core/src/Card/Card.tsx+@@ -10,7 +10,7 @@ const styles = stylex.create({+ root: {+- padding: spacingVars['2'],++ padding: spacingVars['3'],+ borderRadius: radiusVars.md,+ },+ });diff --git a/scripts/lib/__fixtures__/review-diff/pr-8236-badge.diff b/scripts/lib/__fixtures__/review-diff/pr-8236-badge.diffnew file mode 100644index 0000000000..8da85350a3--- /dev/null+++ b/scripts/lib/__fixtures__/review-diff/pr-8236-badge.diff@@ -0,0 +1,12 @@+diff --git a/packages/core/src/Badge/Badge.tsx b/packages/core/src/Badge/Badge.tsx+index c6e109aa7bc39..0b57ce8f55499 100644+--- a/packages/core/src/Badge/Badge.tsx++++ b/packages/core/src/Badge/Badge.tsx+@@ -239,5 +249,7 @@ export function Badge({+ ? label+ : undefined;++ // Whether the label renders anything, which is when the badge grows with it.++ const hasLabel = label !== '' && label != null && typeof label !== 'boolean';++ return (+ <spandiff --git a/scripts/lib/__fixtures__/review-diff/pr-8381-dialog-test.diff b/scripts/lib/__fixtures__/review-diff/pr-8381-dialog-test.diffnew file mode 100644index 0000000000..82efc7d44f--- /dev/null+++ b/scripts/lib/__fixtures__/review-diff/pr-8381-dialog-test.diff@@ -0,0 +1,21 @@+diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx+index b676be021577d..1a9bb5c430bcd 100644+--- a/packages/core/src/Dialog/Dialog.test.tsx++++ b/packages/core/src/Dialog/Dialog.test.tsx+@@ -558,0 +743,16 @@ describe('Dialog', () => {++ blur.mockRestore();++ });++++ it('tracks its document while any Dialog there is mounted, and releases it after the last', () => {++ const removeEventListener = vi.spyOn(++ secondDocument,++ 'removeEventListener',++ );++ const removedModalityListeners = () =>++ removeEventListener.mock.calls++ .map(([type]) => type)++ .filter(type => type === 'pointerdown' || type === 'keydown')++ .sort();++ const {rerender} = render(<SecondDocumentDialogs count={2} />);++ fireEvent.pointerDown(secondDocument.body);++ expect(getInteractionModality(secondDocument)).toBe('pointer');diff --git a/scripts/lib/__fixtures__/review-diff/pr-8381.diff b/scripts/lib/__fixtures__/review-diff/pr-8381.diffnew file mode 100644index 0000000000..8da8e5d7ce--- /dev/null+++ b/scripts/lib/__fixtures__/review-diff/pr-8381.diff@@ -0,0 +1,28 @@+diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx+index 2f1e5806bddb0..475465ec16837 100644+--- a/packages/core/src/Dialog/Dialog.tsx++++ b/packages/core/src/Dialog/Dialog.tsx+@@ -537,0 +545,7 @@ export function Dialog({++ // Picture-in-Picture window) never reaches the page's listeners, so the++ // dialog's own document keeps its own last input for the focus return while++ // this Dialog is mounted, from before it opens until it unmounts.++ useEffect(() => {++ const ownerDocument = dialogRef.current?.ownerDocument;++ if (ownerDocument == null || ownerDocument === document) {++ return undefined;+diff --git a/packages/core/src/utils/interactionModality.ts b/packages/core/src/utils/interactionModality.ts+index e17c6b09d9aaf..abfd8829aa9a3 100644+--- a/packages/core/src/utils/interactionModality.ts++++ b/packages/core/src/utils/interactionModality.ts+@@ -112,0 +133,11 @@ export function useInteractionModalityTracking(): void {++ store.consumers = (store.consumers ?? 0) + 1;++ if (store.consumers === 1) {++ store.isListening = true;++ targetDocument.addEventListener('pointerdown', store.onPointerDown, {++ capture: true,++ passive: true,++ });++ targetDocument.addEventListener('keydown', store.onKeyDown, {++ capture: true,++ passive: true,++ });diff --git a/scripts/lib/__fixtures__/review-diff/pr-8513-month-scroller.diff b/scripts/lib/__fixtures__/review-diff/pr-8513-month-scroller.diffnew file mode 100644index 0000000000..9eef35f1c0--- /dev/null+++ b/scripts/lib/__fixtures__/review-diff/pr-8513-month-scroller.diff@@ -0,0 +1,26 @@+diff --git a/packages/core/src/DateInput/MonthScroller.tsx b/packages/core/src/DateInput/MonthScroller.tsx+index 63c8da60124d7..dbf2b8e129481 100644+--- a/packages/core/src/DateInput/MonthScroller.tsx++++ b/packages/core/src/DateInput/MonthScroller.tsx+@@ -329,0 +368,7 @@ export function MonthScroller({++ // Synchronizes the scroller's snapping with the browser's frame loop: it++ // comes back on in the frame after the pause's commit, and a restore still++ // pending at the next pause or at unmount is dropped.++ useLayoutEffect(() => {++ const scroller = scrollerRef.current;++ if (snapPauses === 0 || scroller == null) {++ return undefined;+@@ -604,7 +684,13 @@ export function MonthScroller({+ };+ scroller.addEventListener('scroll', onScroll, {passive: true});++ for (const type of USER_INPUT_EVENTS) {++ scroller.addEventListener(type, endSteer, {passive: true});++ }+ scroller.addEventListener('touchstart', onTouchStart, {passive: true});+ return () => {+ scroller.removeEventListener('scroll', onScroll);++ for (const type of USER_INPUT_EVENTS) {++ scroller.removeEventListener(type, endSteer);++ }+ scroller.removeEventListener('touchstart', onTouchStart);+ if (frameRef.current != null) {diff --git a/scripts/lib/review-diff.mjs b/scripts/lib/review-diff.mjsnew file mode 100644index 0000000000..8df82eb76b--- /dev/null+++ b/scripts/lib/review-diff.mjs@@ -0,0 +1,57 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Read the shipped source lines a change adds.+ * @input A unified diff (`git diff` output).+ * @output Each added line of shipped source with its file and new line number,+ * and every changed path.+ * @position Shared by `pnpm specs:for --diff` and+ * `scripts/review-global-baselines.mjs`, which match these lines against the+ * `concerns` the owning records declare (`architecture:knowledge-contracts/INV20`).+ */++/** Source files whose added lines can change what a product runs. */+const SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/;++/**+ * Tests, stories and fixtures (`*.fixtures.ts`, `fixtures/`) exercise shipped+ * code but are not shipped, so a listener a test adds re-implements nothing.+ */+const NOT_SHIPPED =+ /(?:^|\/)(?:__tests__|__fixtures__|__mocks__|fixtures)\/|\.(?:test|spec|stories|fixtures?)\.[cm]?[jt]sx?$/;++export function isShippedSource(file) {+ return SOURCE_FILE.test(file) && !NOT_SHIPPED.test(file);+}++/** Parse a unified diff into its changed paths and added lines. */+export function readDiff(diffText) {+ const files = [];+ const addedLines = [];+ let file = null;+ let newLine = 0;+ for (const line of diffText.split('\n')) {+ const header = /^diff --git a\/\S+ b\/(\S+)/.exec(line);+ if (header) {+ file = header[1];+ files.push(file);+ continue;+ }+ if (line.startsWith('+++ ') || line.startsWith('--- ')) continue;+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);+ if (hunk) {+ newLine = Number(hunk[1]);+ continue;+ }+ if (file == null) continue;+ if (line.startsWith('+')) {+ if (isShippedSource(file)) {+ addedLines.push({file, line: newLine, text: line.slice(1)});+ }+ newLine += 1;+ } else if (line.startsWith(' ')) {+ newLine += 1;+ }+ }+ return {files, addedLines};+}diff --git a/scripts/lib/review-diff.test.mjs b/scripts/lib/review-diff.test.mjsnew file mode 100644index 0000000000..b519d72a43--- /dev/null+++ b/scripts/lib/review-diff.test.mjs@@ -0,0 +1,261 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import {execFileSync} from 'node:child_process';+import {afterEach, describe, expect, it} from 'vitest';+import {readDiff} from './review-diff.mjs';+import {collectConcernMatches} from '../check-knowledge.mjs';+import {loadKnowledgeIndex} from '../specs-for-file.mjs';++const HERE = import.meta.dirname;+const ROOT = path.resolve(HERE, '../..');+const fixture = name =>+ fs.readFileSync(path.join(HERE, '__fixtures__/review-diff', name), 'utf8');++/** The repository's own records, as `pnpm specs:for` reads them. */+const records = loadKnowledgeIndex(ROOT).records.map(record => ({+ path: record.path,+ content: record.content,+}));+const routed = name =>+ collectConcernMatches(records, readDiff(fixture(name)).addedLines, null).map(+ match => `${match.recordId}/${match.claimId}`,+ );++describe('readDiff', () => {+ it('reads added shipped-source lines with their new line numbers', () => {+ const {files, addedLines} = readDiff(fixture('pr-8381.diff'));+ expect(files).toEqual([+ 'packages/core/src/Dialog/Dialog.tsx',+ 'packages/core/src/utils/interactionModality.ts',+ ]);+ expect(addedLines).toContainEqual({+ file: 'packages/core/src/Dialog/Dialog.tsx',+ line: 548,+ text: ' useEffect(() => {',+ });+ });++ it('reads no lines from fixture files or directories', () => {+ for (const file of [+ 'internal/a11y-spec/src/patterns/accordion.fixtures.ts',+ 'packages/core/src/A/fixtures/data.ts',+ ]) {+ const diff = [+ `diff --git a/${file} b/${file}`,+ `--- a/${file}`,+ `+++ b/${file}`,+ '@@ -1,0 +1,1 @@',+ "+el.addEventListener('keydown', onKey);",+ ].join('\n');+ expect(readDiff(diff).addedLines).toEqual([]);+ }+ });++ it('reads no lines from tests, stories or fixtures', () => {+ const {files, addedLines} = readDiff(fixture('pr-8381-dialog-test.diff'));+ expect(files).toEqual(['packages/core/src/Dialog/Dialog.test.tsx']);+ expect(addedLines).toEqual([]);+ });+});++describe('concern routing on real diffs', () => {+ it("routes #8381's Dialog effect and modality listeners to their owners", () => {+ expect(routed('pr-8381.diff')).toEqual(+ expect.arrayContaining([+ 'architecture:interaction-modality/INV1',+ 'architecture:interaction-modality/INV2',+ 'architecture:interaction-modality/INV3',+ 'architecture:react-component-runtime/INV2',+ 'architecture:react-component-runtime/INV3',+ 'architecture:react-component-runtime/INV5',+ 'architecture:react-component-runtime/INV6',+ 'architecture:react-component-runtime/INV16',+ ]),+ );+ });++ it('routes a call to the document-scoped modality hook', () => {+ const file = 'packages/core/src/Layer/useTouchTrigger.ts';+ const diff = [+ `diff --git a/${file} b/${file}`,+ `--- a/${file}`,+ `+++ b/${file}`,+ '@@ -1,0 +1,1 @@',+ '+ useInteractionModalityTrackingFor(ownerDocument);',+ ].join('\n');+ const claims = collectConcernMatches(+ records,+ readDiff(diff).addedLines,+ null,+ ).map(match => `${match.recordId}/${match.claimId}`);+ expect(claims).toEqual(+ expect.arrayContaining([+ 'architecture:interaction-modality/INV1',+ 'architecture:react-component-runtime/INV16',+ ]),+ );+ });++ it("routes #8236's hand-written slot check to INV16, naming isRenderable", () => {+ const matches = collectConcernMatches(+ records,+ readDiff(fixture('pr-8236-badge.diff')).addedLines,+ null,+ );+ expect(matches).toContainEqual(+ expect.objectContaining({+ recordId: 'architecture:react-component-runtime',+ concern: 'slot-presence',+ claimId: 'INV16',+ utilities: ['isRenderable'],+ }),+ );+ expect(+ matches.find(match => match.concern === 'slot-presence').matchReason,+ ).toContain('(shared: isRenderable)');+ });++ it("routes #8513's MonthScroller listeners to the runtime claims", () => {+ expect(routed('pr-8513-month-scroller.diff')).toEqual(+ expect.arrayContaining([+ 'architecture:react-component-runtime/INV3',+ 'architecture:react-component-runtime/INV5',+ ]),+ );+ });++ it('routes nothing for a CSS-only change', () => {+ expect(routed('css-only.diff')).toEqual([]);+ });++ it('routes nothing for listeners a test adds', () => {+ expect(routed('pr-8381-dialog-test.diff')).toEqual([]);+ });+});++describe('review-global-baselines.mjs', () => {+ const roots = [];+ afterEach(() => {+ for (const root of roots.splice(0)) {+ fs.rmSync(root, {recursive: true, force: true});+ }+ });++ function git(root, ...args) {+ return execFileSync('git', ['-C', root, ...args], {+ encoding: 'utf8',+ env: {+ ...process.env,+ GIT_AUTHOR_NAME: 'Test',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 'Test',+ GIT_COMMITTER_EMAIL: '[email protected]',+ },+ }).trim();+ }++ function write(root, relative, content) {+ const file = path.join(root, relative);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, content);+ }++ /** A base whose runtime record owns an effects concern; a head changing `source`. */+ function repository(source) {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'review-baselines-'));+ roots.push(root);+ git(root, 'init', '-q', '-b', 'main');+ write(+ root,+ 'docs/architecture/react-component-runtime.md',+ [+ '---',+ 'authority: current',+ 'kind: architecture',+ 'id: architecture:react-component-runtime',+ '---',+ '',+ '# React component runtime',+ '',+ '<!-- review-applicability:v1 -->',+ '',+ '```json',+ JSON.stringify({+ scope: 'global',+ triggers: {styling: ['INV2']},+ concerns: {+ effects: {patterns: ['\\buseEffect\\b'], claims: ['INV1']},+ },+ }),+ '```',+ '',+ '## Requirements',+ '',+ '- **INV1 — Effects clean up.** Detail.',+ '- **INV2 — Styles stay static.** Detail.',+ '',+ ].join('\n'),+ );+ write(root, 'packages/core/src/A/A.tsx', 'export function A() {}\n');+ git(root, 'add', '-A');+ git(root, 'commit', '-q', '-m', 'base');+ const base = git(root, 'rev-parse', 'HEAD');+ git(root, 'update-ref', 'refs/remotes/origin/main', base);+ write(root, 'packages/core/src/A/A.tsx', source);+ git(root, 'commit', '-q', '-am', 'head');+ return {root, base, head: git(root, 'rev-parse', 'HEAD')};+ }++ function route({root, base, head}) {+ return JSON.parse(+ execFileSync(+ 'node',+ [+ path.join(ROOT, 'scripts/review-global-baselines.mjs'),+ '--root',+ root,+ '--authority-commit',+ base,+ '--review-head',+ head,+ '--triggers',+ 'styling',+ ],+ {encoding: 'utf8'},+ ),+ );+ }++ it("routes a concern the head's added lines match, beside the requested triggers", () => {+ const result = route(+ repository(+ 'export function A() {\n useEffect(() => () => {}, []);\n}\n',+ ),+ );+ expect(result.matches.map(match => match.claimId)).toEqual(['INV2']);+ expect(result.concernMatches).toEqual([+ expect.objectContaining({+ recordId: 'architecture:react-component-runtime',+ concern: 'effects',+ claimId: 'INV1',+ evidence: [+ expect.objectContaining({+ file: 'packages/core/src/A/A.tsx',+ line: 2,+ matched: 'useEffect',+ }),+ ],+ }),+ ]);+ });++ it('routes no concern when no added line matches', () => {+ const result = route(+ repository('export function A() {\n return null;\n}\n'),+ );+ expect(result.concernMatches).toEqual([]);+ });+});diff --git a/scripts/review-global-baselines.mjs b/scripts/review-global-baselines.mjsindex a370eec6e7..a122f97ed3 100644--- a/scripts/review-global-baselines.mjs+++ b/scripts/review-global-baselines.mjs@@ -2,8 +2,14 @@/* global console, process */import path from 'node:path';+import {execFileSync} from 'node:child_process';import {fileURLToPath} from 'node:url';-import {routeGlobalReviewBaselinesAtRevision} from './check-knowledge.mjs';+import {+ collectConcernMatches,+ collectGlobalReviewMatches,+ readKnowledgeRecordsAtAuthority,+} from './check-knowledge.mjs';+import {readDiff} from './lib/review-diff.mjs';const HERE = path.dirname(fileURLToPath(import.meta.url));const DEFAULT_ROOT = path.resolve(HERE, '..');@@ -51,12 +57,37 @@ if (requestedTriggers.length === 0) {throw new Error('--triggers requires at least one trigger.');}-const matches = routeGlobalReviewBaselinesAtRevision(+const {records, authority} = readKnowledgeRecordsAtAuthority(root,authorityCommit,reviewHead,+);+const matches = collectGlobalReviewMatches(+ records,requestedTriggers,+ authority,+);+// The reviewed change's own added lines route the claims of every concern+// they re-implement (architecture:knowledge-contracts/INV20), whatever the+// caller's triggers or the component record's review_triggers.+const {addedLines} = readDiff(+ execFileSync(+ 'git',+ [+ '-C',+ root,+ 'diff',+ '--no-color',+ '--no-ext-diff',+ '--src-prefix=a/',+ '--dst-prefix=b/',+ authority,+ reviewHead,+ ],+ {encoding: 'utf8', maxBuffer: 256 * 1024 * 1024},+ ),);+const concernMatches = collectConcernMatches(records, addedLines, authority);console.log(JSON.stringify({@@ -65,6 +96,7 @@ console.log(reviewHead,requestedTriggers: [...new Set(requestedTriggers)].sort(),matches,+ concernMatches,},null,2,diff --git a/scripts/specs-for-file.mjs b/scripts/specs-for-file.mjsindex 34c4536e64..ae3d720a7e 100644--- a/scripts/specs-for-file.mjs+++ b/scripts/specs-for-file.mjs@@ -19,6 +19,7 @@ import {createRequire} from 'node:module';import {fileURLToPath} from 'node:url';import {GLOBAL_REVIEW_TRIGGERS,+ collectConcernMatches,collectGlobalReviewMatches,discoverKnowledgeRecords,consumerDocPublicNames,@@ -26,6 +27,7 @@ import {parseKnowledgeDocument,parsePathApplicabilityBlock,} from './check-knowledge.mjs';+import {readDiff} from './lib/review-diff.mjs';const require = createRequire(import.meta.url);const {componentPackage} = require('./component-packages.cjs');@@ -585,7 +587,9 @@ function closeOverReferences(index, direct, visible) {* `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).+ * supported trigger when none matched). `concernClaims` lists the claims whose+ * owning record's `concerns` match one of `options.addedLines` (the file's+ * added lines from a diff), each with the lines that matched.*/export function resolveSpecsForFile(index, file, options = {}) {const includeDraft = options.includeDraft ?? false;@@ -665,6 +669,36 @@ export function resolveSpecsForFile(index, file, options = {}) {claim,}));+ const addedLines = (options.addedLines ?? []).filter(+ line => line.file === filePath,+ );+ const concernClaims = collectConcernMatches(+ index.records.map(record => ({+ path: record.path,+ content: record.content,+ })),+ addedLines,+ null,+ ).map(+ ({+ recordId,+ path: recordPath,+ concern,+ claimId,+ claim,+ utilities,+ evidence,+ }) => ({+ recordId,+ path: recordPath,+ concern,+ claimId,+ claim,+ utilities,+ evidence,+ }),+ );+return {file: filePath,exists: fs.existsSync(path.join(index.root, filePath)),@@ -681,6 +715,7 @@ export function resolveSpecsForFile(index, file, options = {}) {decisions,triggers: [...new Set(triggers)].sort(),triggerSource,+ concernClaims,globalClaims,};}@@ -726,9 +761,39 @@ function trackedFiles(root) {.filter(Boolean);}-function formatResult(result) {+/**+ * The claims a diff's concerns route, grouped per record and concern, with+ * the line that matched. Both views print them first.+ */+function formatConcernLines(result) {+ if (result.concernClaims.length === 0) return [];+ const lines = [];+ lines.push(' Follow first (the change touches a shared concern):');+ const byConcern = new Map();+ for (const item of result.concernClaims) {+ const key = `${item.recordId}\0${item.concern}`;+ const entry = byConcern.get(key) ?? {...item, claimIds: []};+ entry.claimIds.push(item.claimId);+ byConcern.set(key, entry);+ }+ for (const entry of byConcern.values()) {+ const where = entry.evidence[0];+ const shared =+ entry.utilities.length > 0+ ? `; shared: ${entry.utilities.join(', ')}`+ : '';+ lines.push(+ ` ${entry.recordId} ${entry.claimIds.join(', ')} ← ${entry.concern} (line ${where.line}: ${where.matched}${shared})`,+ );+ }+ return lines;+}++export function formatResult(result, {records: listRecords = false} = {}) {+ if (!listRecords) return formatShortResult(result);const lines = [`${result.file}${result.exists ? '' : ' (not in the working tree)'}`,+ ...formatConcernLines(result),];if (result.records.length === 0) {lines.push(@@ -784,18 +849,132 @@ function formatResult(result) {return lines.join('\n');}+/**+ * The default view: the claims to follow, first those the diff's concerns+ * route (with the line that matched), then the trigger-routed global claims+ * one line per record, then the linked records, cited claims and deciding+ * specs by id. `--records` adds how each one links.+ */+function formatShortResult(result) {+ const lines = [+ `${result.file}${result.exists ? '' : ' (not in the working tree)'}`,+ ];+ lines.push(...formatConcernLines(result));+ const byRecord = new Map();+ for (const claim of result.globalClaims) {+ const list = byRecord.get(claim.recordId) ?? [];+ list.push(claim.claimId);+ byRecord.set(claim.recordId, list);+ }+ lines.push(+ ` Global claims for ${result.triggers.join(', ') || '(no triggers)'} (${result.triggerSource}):`,+ );+ if (byRecord.size === 0) lines.push(' none');+ for (const [recordId, claims] of byRecord) {+ lines.push(` ${recordId} ${[...new Set(claims)].join(', ')}`);+ }+ if (result.records.length === 0 && result.decisions.length === 0) {+ lines.push(' No record links to this path.');+ }+ if (result.records.length > 0) {+ lines.push(+ ` Records: ${result.records.map(record => record.id).join(', ')}`,+ );+ }+ if (result.decisions.length > 0) {+ lines.push(+ ` Cited claims: ${result.decisions.map(decision => decision.id).join(', ')}`,+ );+ }+ if (result.decidingSpecs.length > 0) {+ lines.push(+ ` Deciding specs: ${result.decidingSpecs.map(record => record.id).join(', ')}`,+ );+ }+ lines.push(' --records shows how each one links.');+ 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]+const USAGE = `Usage: pnpm specs:for [<file...>] [--diff <base>[..|...<head>]] [--records] [--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.+Lists every knowledge record that governs each file, the specs that decided+those records, and the trigger-routed global claims. --diff reads the change against <base> (its merge base with HEAD, to+the working tree), between <base>..<head>, or from their merge base with+<base>...<head>, lists its changed files when none+are named, and puts first the claims whose owning record's concerns its added+lines match. The linked records, cited claims and deciding specs are listed by+id; --records shows how each one links.+--unreached lists current records no other tracked file reaches.--unrouted lists tracked files no current record governs.`;+/**+ * The diff `--diff` names: `<base>..<head>` between two commits, or `<base>`+ * from its merge base with HEAD to the working tree (uncommitted edits+ * included), the change an author is about to make.+ */+function diffText(root, range) {+ const git = args =>+ execFileSync('git', ['-C', root, ...args], {+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ });+ if (range.includes('...')) {+ // git's three-dot form: the head's change since it branched from base.+ const [base, head] = range.split('...');+ const fork = git(['merge-base', base, head]).trim();+ return git([+ 'diff',+ '--no-color',+ '--no-ext-diff',+ '--src-prefix=a/',+ '--dst-prefix=b/',+ fork,+ head,+ ]);+ }+ if (range.includes('..')) {+ const [base, head] = range.split('..');+ return git([+ 'diff',+ '--no-color',+ '--no-ext-diff',+ '--src-prefix=a/',+ '--dst-prefix=b/',+ base,+ head,+ ]);+ }+ const base = git(['merge-base', 'HEAD', range]).trim();+ const tracked = git([+ 'diff',+ '--no-color',+ '--no-ext-diff',+ '--src-prefix=a/',+ '--dst-prefix=b/',+ base,+ ]);+ // A new file not yet added to git is part of the change too.+ const untracked = git(['ls-files', '--others', '--exclude-standard', '-z'])+ .split('\0')+ .filter(Boolean)+ .map(file => {+ const lines = fs.readFileSync(path.join(root, file), 'utf8').split('\n');+ return [+ `diff --git a/${file} b/${file}`,+ '--- /dev/null',+ `+++ b/${file}`,+ `@@ -0,0 +1,${lines.length} @@`,+ ...lines.map(line => `+${line}`),+ ].join('\n');+ });+ return [tracked, ...untracked].join('\n');+}+function main(argv) {const files = [];let json = false;@@ -803,6 +982,8 @@ function main(argv) {let unreached = false;let unrouted = false;let triggers;+ let diffRange;+ let listRecords = false;for (let i = 0; i < argv.length; i += 1) {const arg = argv[i];if (arg === '--json') json = true;@@ -819,6 +1000,15 @@ function main(argv) {.map(item => item.trim()).filter(Boolean);i += 1;+ } else if (arg === '--diff') {+ const value = argv[i + 1];+ if (!value || value.startsWith('--')) {+ throw new Error('--diff requires <base> or <base>..<head>.');+ }+ diffRange = value;+ i += 1;+ } else if (arg === '--records') {+ listRecords = true;} else if (arg === '--help' || arg === '-h') {console.log(USAGE);return 0;@@ -860,21 +1050,38 @@ function main(argv) {}return 0;}- if (files.length === 0) {+ const diff =+ diffRange == null ? null : readDiff(diffText(DEFAULT_ROOT, diffRange));+ const cwd = process.env.INIT_CWD ?? process.cwd();+ // Named files resolve against where the command ran; the diff's own files+ // are repository-relative.+ const targets = files.map(file => path.resolve(cwd, file));+ if (targets.length === 0 && diff != null) {+ if (diff.files.length === 0) {+ console.log(`No changes against ${diffRange}.`);+ return 0;+ }+ targets.push(...diff.files.map(file => path.join(DEFAULT_ROOT, file)));+ }+ if (targets.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), {+ const results = targets.map(target =>+ resolveSpecsForFile(index, target, {includeDraft,triggers,+ addedLines: diff?.addedLines,}),);if (json) console.log(JSON.stringify(results, null, 2));else {console.log(WORKING_TREE_NOTE);- console.log(results.map(formatResult).join('\n\n'));+ console.log(+ results+ .map(result => formatResult(result, {records: listRecords}))+ .join('\n\n'),+ );}return 0;}diff --git a/scripts/specs-for-file.test.mjs b/scripts/specs-for-file.test.mjsindex ff321716e5..13c3549819 100644--- a/scripts/specs-for-file.test.mjs+++ b/scripts/specs-for-file.test.mjs@@ -14,6 +14,7 @@ import {findUnroutedFiles,loadKnowledgeIndex,resolveSpecsForFile,+ formatResult,} from './specs-for-file.mjs';const repoRoot = path.resolve(import.meta.dirname, '..');@@ -700,6 +701,99 @@ describe('resolveSpecsForFile', () => {});});+describe('concern routing', () => {+ function concernFixture() {+ const root = popoverFixture();+ writeRecord(+ root,+ 'docs/architecture/react-component-runtime.md',+ {kind: 'architecture', id: 'architecture:react-component-runtime'},+ [+ '',+ '<!-- review-applicability:v1 -->',+ '',+ '```json',+ JSON.stringify({+ scope: 'global',+ concerns: {+ 'slot-presence': {+ names: ['isRenderable'],+ patterns: ["typeof [\\w.]+ !== 'boolean'"],+ claims: ['INV16'],+ },+ },+ }),+ '```',+ '',+ '## Requirements',+ '',+ '- **INV16 — A shared concern is extended in its owner.** Detail.',+ '',+ ].join('\n'),+ );+ return loadKnowledgeIndex(root);+ }+ const file = 'packages/core/src/Popover/Popover.tsx';+ const addedLines = [+ {+ file,+ line: 7,+ text: " if (label != null && typeof label !== 'boolean') {",+ },+ {+ file: 'packages/core/src/Other/Other.tsx',+ line: 1,+ text: 'isRenderable(x)',+ },+ ];++ it("lists the claims a concern routes from the file's own added lines", () => {+ const result = resolveSpecsForFile(concernFixture(), file, {addedLines});+ expect(result.concernClaims).toEqual([+ {+ recordId: 'architecture:react-component-runtime',+ path: 'docs/architecture/react-component-runtime.md',+ concern: 'slot-presence',+ claimId: 'INV16',+ claim: 'A shared concern is extended in its owner.',+ utilities: ['isRenderable'],+ evidence: [+ {+ file,+ line: 7,+ text: " if (label != null && typeof label !== 'boolean') {",+ matched: "typeof label !== 'boolean'",+ by: "typeof [\\w.]+ !== 'boolean'",+ },+ ],+ },+ ]);+ expect(resolveSpecsForFile(concernFixture(), file).concernClaims).toEqual(+ [],+ );+ });++ it('prints the concern claims first and lists the linked records by id', () => {+ const result = resolveSpecsForFile(concernFixture(), file, {addedLines});+ const short = formatResult(result).split('\n');+ expect(short[1]).toBe(+ ' Follow first (the change touches a shared concern):',+ );+ expect(short[2]).toBe(+ " architecture:react-component-runtime INV16 ← slot-presence (line 7: typeof label !== 'boolean'; shared: isRenderable)",+ );+ // Every linked record is still listed, by id (INV26).+ expect(+ short.some(line => /^ {2}Records: .*component:Popover/.test(line)),+ ).toBe(true);+ expect(short.join('\n')).not.toContain('via ');+ const long = formatResult(result, {records: true}).split('\n');+ expect(long.join('\n')).toContain('via ');+ // --records prints the same concern claims first.+ expect(long.slice(1, 3)).toEqual(short.slice(1, 3));+ });+});+describe('coverage audits', () => {it('lists current records only their own file reaches', () => {const root = popoverFixture();