An open source design system that's fully customizable and agent ready
TypeScript
chore(review): add pnpm review:pre and a pre-review checklist for contributors (#9585)
Cindy Zhangd3a0f466beec
diff --git a/AGENTS.md b/AGENTS.mdindex 07fd4451c4..89f0960fe2 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -19,7 +19,8 @@ nested `AGENTS.md`.`docs/README.md`.- Pull requests: choose one primary intent and use its template under`.github/PULL_REQUEST_TEMPLATE/`; read `docs/contributing/pull-requests.md`- before opening or reviewing a mixed change.+ before opening or reviewing a mixed change. Before you request review, run+ `pnpm review:pre` and its checklist from a fresh session.- Component work: derive the review's semantic triggers, load matching `current`global baseline claims with `node scripts/review-global-baselines.mjs--authority-commit <base-sha> --review-head <head-sha> --triggersdiff --git a/docs/contributing/README.md b/docs/contributing/README.mdindex 44d00736cc..e021a2c5ea 100644--- a/docs/contributing/README.md+++ b/docs/contributing/README.md@@ -6,6 +6,8 @@ contracts, or component contracts.- [Pull request intents](pull-requests.md): choose one primary intent, use thematching template, and supply the right evidence without absorbing tagalongs.+- [Pre-review](pull-requests.md#review-your-change-before-you-ask-for-review):+ run `pnpm review:pre` and the checklist before you request review.- [API conventions](api-conventions.md): shape, propose, implement, and review apublic component API.- [CLI conventions](cli-conventions.md): propose, implement, and review a changediff --git a/docs/contributing/pull-requests.md b/docs/contributing/pull-requests.mdindex 3fc0b6c018..0ac9d489f9 100644--- a/docs/contributing/pull-requests.md+++ b/docs/contributing/pull-requests.md@@ -103,6 +103,116 @@ public retained copy outside the implementation branch. Keep reusable fixtures,accepted baselines, and media used by public documentation in their owning sourcepaths. Evidence storage does not relax the matching template's evidence bar.+## Review your change before you ask for review++Review reads each pull request against the current records and the checklist+below. Run the same pass first. Each finding you fix before review saves a+review round.++### Run the pre-review report++```bash+pnpm review:pre # the working tree against origin/main+pnpm review:pre --base upstream/main # a fork whose main remote is upstream+pnpm review:pre --head HEAD # committed work only+pnpm review:pre --json # the same report as JSON+```++The report reads only the local repository. It prints:++- each changed file and its class: record, owner-gated record, API report,+ published package code, other package file, Lab, or repository;+- the current records that govern those files, and the claims that the files+ cite or that the added lines route;+- the global baseline claims that the linked components' review triggers route,+ read at the merge base;+- the checklist items that apply to this change, each with its reason.++The report is a lookup. The records decide acceptance, not the report.++### Find the governing records by hand++| Command | What it answers |+| ------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |+| `pnpm specs:for <path>` | The records linked to one path, the specs that decided them, and the routed global claims |+| `pnpm specs:for --diff origin/main` | The same for every changed file, with the claims that the added lines route first |+| `node scripts/review-global-baselines.mjs --authority-commit <base-sha> --review-head <head-sha> --triggers <a,b>` | The current global claims for the review triggers, read at the merge base |+| `pnpm check:knowledge` | Whether records and templates are valid after you edit one |+| `git diff --name-only origin/main... \| node .github/scripts/change-scope.cjs --classify-paths` | Which changed paths are spec records, and which need a spec owner's approval |++### Pre-review checklist++First apply the protocol above: one primary intent, no tagalongs, and+specifications last. Then check each item that the report lists. Item d applies+to every pull request.++- **a. API delta.** A current record decides each added or changed row of a+ package's `api-report.md`. The record is current at the merge base or changes+ in the same pull request. After a public API change, run `pnpm api:report`+ and commit the report. A row that no record decides goes to an owner for a+ decision; review does not ask you to remove it+ ([`architecture:public-component-api`](../architecture/public-component-api.md#boundaries-and-invariants)+ INV24 and INV25).+- **b. Behavior.** Each observable behavior change in a published package+ cites the current record and clause that settle it. If nothing changes+ behavior, write "No behavior change" in the description. A clause settles+ only what its text states. A clause that only names a prop, key, or slot, or+ a general baseline such as a WCAG level, does not settle the wording, default,+ fallback, or result that ships. Catalogs, Changesets, stories, and comments+ are not records. An unsettled behavior goes to an owner. Lab is not a stable+ public promise, so a Lab-only change skips this item+ ([Authority](../../AGENTS.md#authority);+ [`architecture:knowledge-contracts` contract before escalation](../architecture/knowledge-contracts.md#contract-before-escalation)).+- **c. Behavior props.** A prop that chooses how a component responds to input+ is named `<thing>Behavior` and takes a closed union of behavior names. Its+ name holds no input word (press, touch, tap, hover, mouse, click) when its+ values can name the behavior. One behavior is one prop. When the behavior+ differs by device, the prop offers `'adaptive'` or `'adaptive-<target>'`. A+ new behavior prop defaults to the shipped behavior. An `is…` or `has…`+ boolean names only a true on/off+ ([`architecture:public-component-api`](../architecture/public-component-api.md#boundaries-and-invariants)+ INV2 and INV3).+- **d. Public boundary.** No internal or private context in source, tests,+ fixtures, Changesets, commit messages, branch names, or pull request text+ ([Public repository boundary](#public-repository-boundary)).+- **e. New public hook.** Each public hook has a minimal, runnable example: a+ live template block that names the hook in `exampleFor` or `alsoExampleFor`.+ A public hook is a hook that a package's API report lists, so a new Hooks row+ or a new export from a published entry point makes one. Motion and gesture+ hooks count. A public hook without a conforming example is a docs gap that an+ issue tracks+ ([`architecture:knowledge-contracts`](../architecture/knowledge-contracts.md#consumer-docs)+ INV28 and DEC-16).+- **f. Comments.** New or changed comments in `packages/*/src/**`, Lab+ included, explain only a reason, a constraint, an invariant, or a platform+ quirk. They do not narrate the code, restate names, or cite pull requests,+ issues, dates, or records. They follow ASD-STE100 Simplified Technical+ English: at most 20 words in an instruction and 25 in a description, one+ topic per sentence, and active voice. A file header stays within about 12+ lines+ ([`architecture:knowledge-contracts`](../architecture/knowledge-contracts.md#source-comments)+ INV29).+- **g. Records.** A change to an owner-gated path waits on `review-required`+ until a spec owner approves its spec content, with `/approve-spec <sha>` or an+ approving review. Base merges, rebases, and commits to other paths keep that+ approval. A later change to the approved spec text resets it+ ([`architecture:knowledge-contracts`](../architecture/knowledge-contracts.md#dec-14--one-owner-approval-binds-a-pull-requests-spec-content)+ DEC-14). The description also reports `## Writing rubric results`+ ([Writing specification records](spec-writing.md)).++### Use a fresh session for an agent's change++The author of a change reads intent into it. A reviewer reads only the diff.+When an agent wrote the change:++1. Start a new agent session that has no memory of writing the change. Check+ out the pull request branch.+2. Run `pnpm review:pre`.+3. Read every record and claim that the report lists.+4. Apply the protocol above and each listed checklist item to the diff.+5. Fix each finding, or split it out. Run `pnpm review:pre` again.+6. Request review when no finding is left.+## Public repository boundaryDescriptions, screenshots, commits, tests, and specification records are public. Do not include internal links, identifiers, hostnames, tools, or operational context.diff --git a/package.json b/package.jsonindex 4467fe1b50..ed5cef9868 100644--- a/package.json+++ b/package.json@@ -99,6 +99,7 @@"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",+ "review:pre": "node scripts/pre-review.mjs","specs:for": "node scripts/specs-for-file.mjs"},"devDependencies": {diff --git a/scripts/lib/review-diff.mjs b/scripts/lib/review-diff.mjsindex 8df82eb76b..e2e8862e7b 100644--- a/scripts/lib/review-diff.mjs+++ b/scripts/lib/review-diff.mjs@@ -4,7 +4,7 @@* @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.+ * every changed path, and every added line of each 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`).@@ -24,10 +24,14 @@ export function isShippedSource(file) {return SOURCE_FILE.test(file) && !NOT_SHIPPED.test(file);}-/** Parse a unified diff into its changed paths and added lines. */+/**+ * Parse a unified diff into its changed paths and added lines. `addedLines`+ * keeps shipped source only; `addedByFile` keeps every added line of each path.+ */export function readDiff(diffText) {const files = [];const addedLines = [];+ const addedByFile = {};let file = null;let newLine = 0;for (const line of diffText.split('\n')) {@@ -35,6 +39,7 @@ export function readDiff(diffText) {if (header) {file = header[1];files.push(file);+ addedByFile[file] ??= [];continue;}if (line.startsWith('+++ ') || line.startsWith('--- ')) continue;@@ -45,6 +50,7 @@ export function readDiff(diffText) {}if (file == null) continue;if (line.startsWith('+')) {+ addedByFile[file].push(line.slice(1));if (isShippedSource(file)) {addedLines.push({file, line: newLine, text: line.slice(1)});}@@ -53,5 +59,5 @@ export function readDiff(diffText) {newLine += 1;}}- return {files, addedLines};+ return {files, addedLines, addedByFile};}diff --git a/scripts/lib/review-diff.test.mjs b/scripts/lib/review-diff.test.mjsindex b519d72a43..4d3125a989 100644--- a/scripts/lib/review-diff.test.mjs+++ b/scripts/lib/review-diff.test.mjs@@ -25,6 +25,21 @@ const routed = name =>);describe('readDiff', () => {+ it('keeps every added line of each path in addedByFile', () => {+ const diff = [+ 'diff --git a/docs/a.md b/docs/a.md',+ '--- a/docs/a.md',+ '+++ b/docs/a.md',+ '@@ -1,1 +1,2 @@',+ ' context',+ '+added',+ '-removed',+ ].join('\n');+ const {addedLines, addedByFile} = readDiff(diff);+ expect(addedLines).toEqual([]);+ expect(addedByFile).toEqual({'docs/a.md': ['added']});+ });+it('reads added shipped-source lines with their new line numbers', () => {const {files, addedLines} = readDiff(fixture('pr-8381.diff'));expect(files).toEqual([diff --git a/scripts/pre-review.mjs b/scripts/pre-review.mjsnew file mode 100644index 0000000000..54d977bff9--- /dev/null+++ b/scripts/pre-review.mjs@@ -0,0 +1,299 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Pre-review report: what a reviewer checks in a change, before review.+ * @input `--base <ref>` (default `origin/main`), an optional `--head <ref>`+ * (default: the working tree, with uncommitted and untracked files), `--json`.+ * @output The changed files and their class, the governing records and routed+ * claims, and the checklist items that apply to this change.+ * @position `pnpm review:pre`. The checklist it names is in+ * `docs/contributing/pull-requests.md`. SYNC: keep `CHECKS` in step with it.+ */+/* global console, process */+import {execFileSync} from 'node:child_process';+import fs from 'node:fs';+import {createRequire} from 'node:module';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {isShippedSource, readDiff} from './lib/review-diff.mjs';+import {+ diffText,+ loadKnowledgeIndex,+ resolveSpecsForFile,+} from './specs-for-file.mjs';++const require = createRequire(import.meta.url);+const {+ classifyChanges,+ classifyPaths,+ isPackageReleasePath,+ parseNameStatus,+} = require('../.github/scripts/change-scope.cjs');++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+export const CHECKLIST_LINK =+ 'docs/contributing/pull-requests.md#pre-review-checklist';++export const CHECKS = {+ a: 'API delta: a current record decides each added or changed API report row',+ b: 'Behavior: each observable behavior change cites a current record and clause, or the description says "No behavior change"',+ c: 'Behavior props: a prop that selects a behavior follows the naming and one-prop rules',+ d: 'Public boundary: no internal or private context in source, tests, fixtures, commits, or pull request text',+ e: 'New public hook: a runnable example in a template block that names the hook in exampleFor or alsoExampleFor',+ f: 'Comments: new or changed source comments explain only non-obvious work, in Simplified Technical English',+ g: 'Records: a changed record needs a spec owner to approve its spec content',+};++const API_REPORT = /(?:^|\/)api-report\.md$/;+const LAB = /^packages\/lab\//;+const TEMPLATES = /^packages\/cli\/assets\/templates\//;+const NOT_PACKAGE_CODE =+ /\.stories\.[^/]+$|\.doc\.mjs$|\.md$|(?:^|\/)(?:package\.json|package-lock\.json|tsconfig[^/]*\.json)$|\/(?:scripts|test-utils)\//;+const COMMENT = /^\s*(?:\/\/|\/\*|\*)/;+const DIRECTIVE = /Copyright|eslint-|@ts-|prettier-ignore|@pr-a11y/;++const publishedByRoot = new Map();++/** True when the nearest package manifest above `file` is not private. */+function isPublished(file) {+ let dir = path.posix.dirname(file);+ while (dir.startsWith('packages/')) {+ if (!publishedByRoot.has(dir)) {+ const manifest = path.join(ROOT, dir, 'package.json');+ publishedByRoot.set(+ dir,+ fs.existsSync(manifest)+ ? JSON.parse(fs.readFileSync(manifest, 'utf8')).private !== true+ : null,+ );+ }+ const published = publishedByRoot.get(dir);+ if (published != null) return published;+ dir = path.posix.dirname(dir);+ }+ return false;+}++/** Code or data a published package ships: not tests, stories, docs, or config. */+function isPublishedPackageCode(file) {+ return (+ isPackageReleasePath(file) &&+ !API_REPORT.test(file) &&+ !NOT_PACKAGE_CODE.test(file) &&+ isPublished(file)+ );+}++function isPackageSource(file) {+ return (+ file.startsWith('packages/') &&+ /\/src\//.test(file) &&+ isShippedSource(file) &&+ !file.endsWith('.doc.mjs') &&+ !TEMPLATES.test(file)+ );+}++/** The class a reviewer reads a changed path as. */+export function fileClass(file, classes) {+ if (classes.ownerGatedRecord) return 'record, owner-gated';+ if (classes.specRecord) return 'record';+ if (API_REPORT.test(file)) return 'API report';+ if (LAB.test(file)) return 'Lab';+ if (isPublishedPackageCode(file)) return 'published package code';+ if (file.startsWith('packages/')) return 'package file';+ return 'repository';+}++/**+ * The checklist items this change triggers, each with the reason. Item `d`+ * applies to every pull request.+ */+export function applicableChecks(files, diff) {+ const {addedByFile} = readDiff(diff);+ const classes = classifyPaths(files);+ const reasons = new Map([['d', 'every pull request is public']]);+ const note = (id, reason) => reasons.has(id) || reasons.set(id, reason);+ for (const file of files) {+ const lines = addedByFile[file] ?? [];+ const adds = pattern => lines.some(line => pattern.test(line));+ if (API_REPORT.test(file) && lines.length > 0) {+ note('a', `${file} has added or changed rows`);+ if (adds(/^\s*hook use[A-Z]/)) note('e', `${file} adds a hook row`);+ if (adds(/^\s*prop (?:\w+Behavior|(?:is|has)[A-Z]\w*)\??:/)) {+ note('c', `${file} adds a behavior or boolean prop row`);+ }+ }+ if (classes[file].ownerGatedRecord) note('g', `${file} is owner-gated`);+ if (isPublishedPackageCode(file)) {+ note('b', `${file} is published package code`);+ if (adds(/\b\w+Behavior\??\s*:/))+ note('c', `${file} adds a behavior prop`);+ if (/\/index\.tsx?$/.test(file) && adds(/^export\b.*\buse[A-Z]/)) {+ note('e', `${file} exports a hook`);+ }+ }+ if (+ isPackageSource(file) &&+ lines.some(line => COMMENT.test(line) && !DIRECTIVE.test(line))+ ) {+ note('f', `${file} adds comments`);+ }+ }+ return Object.keys(CHECKS)+ .filter(id => reasons.has(id))+ .map(id => ({id, check: CHECKS[id], reason: reasons.get(id)}));+}++function git(args) {+ return execFileSync('git', ['-C', ROOT, ...args], {+ encoding: 'utf8',+ maxBuffer: 256 * 1024 * 1024,+ });+}++function changedFiles(fork, head) {+ const tracked = parseNameStatus(+ git(['diff', '--name-status', '-M', fork, ...(head ? [head] : [])]),+ );+ if (head) return tracked;+ const untracked = git(['ls-files', '--others', '--exclude-standard'])+ .split('\n')+ .filter(Boolean)+ .map(filename => ({filename, status: 'A'}));+ return [...tracked, ...untracked];+}++/** Global baseline claims at the merge base, for the records' own triggers. */+function globalBaselines(fork, headSha, triggers) {+ const args = [+ path.join(ROOT, 'scripts/review-global-baselines.mjs'),+ '--authority-commit',+ fork,+ '--review-head',+ headSha,+ '--triggers',+ triggers.join(','),+ ];+ if (triggers.length === 0) return {command: null, claims: []};+ const command = `node ${path.relative(ROOT, args[0])} ${args.slice(1).join(' ')}`;+ let result;+ try {+ result = JSON.parse(+ execFileSync(process.execPath, args, {encoding: 'utf8', stdio: 'pipe'}),+ );+ } catch (error) {+ const reason =+ /Error: (.*)/.exec(String(error.stderr))?.[1] ?? error.message;+ return {command, claims: [], error: reason};+ }+ const claims = [...result.matches, ...result.concernMatches].map(+ match => `${match.recordId} ${match.claimId}`,+ );+ return {command, claims: [...new Set(claims)].sort()};+}++export function buildReport({base = 'origin/main', head = null} = {}) {+ const fork = git(['merge-base', base, head ?? 'HEAD']).trim();+ const headSha = git(['rev-parse', head ?? 'HEAD']).trim();+ const changes = changedFiles(fork, head);+ const files = [...new Set(changes.map(change => change.filename))].sort();+ if (files.length === 0) return {base, head: head ?? 'working tree', files};+ const diff = diffText(ROOT, head ? `${base}...${head}` : base);+ const classes = classifyPaths(files);+ const index = loadKnowledgeIndex(ROOT);+ const {addedLines} = readDiff(diff);+ const records = new Map();+ const claims = new Set();+ const triggers = new Set();+ for (const file of files) {+ const result = resolveSpecsForFile(index, path.join(ROOT, file), {+ addedLines,+ });+ for (const record of result.records) records.set(record.id, record.path);+ for (const decision of result.decisions) claims.add(decision.id);+ for (const match of result.concernClaims)+ claims.add(`${match.recordId} ${match.claimId}`);+ if (result.triggerSource.startsWith('component')) {+ for (const trigger of result.triggers) triggers.add(trigger);+ }+ }+ return {+ base,+ head: head ?? 'working tree',+ mergeBase: fork,+ scope: classifyChanges(changes).reason,+ files: files.map(file => ({file, class: fileClass(file, classes[file])})),+ records: [...records].map(([id, recordPath]) => ({id, path: recordPath})),+ claims: [...claims].sort(),+ baselines: globalBaselines(fork, headSha, [...triggers].sort()),+ checks: applicableChecks(files, diff),+ checklist: CHECKLIST_LINK,+ };+}++export function formatReport(report) {+ if (report.files.length === 0) {+ return `No changes against ${report.base}...${report.head}.`;+ }+ const lines = [+ `Pre-review: ${report.base}...${report.head} (merge base ${report.mergeBase.slice(0, 12)})`,+ `Scope: ${report.scope}`,+ '',+ `Changed files (${report.files.length}):`,+ ...report.files.map(entry => ` ${entry.file} [${entry.class}]`),+ '',+ 'Governing records (read each one):',+ ...(report.records.length+ ? report.records.map(r => ` ${r.id} ${r.path}`)+ : [' none']),+ '',+ 'Cited and concern-routed claims:',+ ...(report.claims.length+ ? report.claims.map(claim => ` ${claim}`)+ : [' none']),+ '',+ 'Global baseline claims at the merge base:',+ ...(report.baselines.command+ ? [+ ` ${report.baselines.command}`,+ ...(report.baselines.error+ ? [` not run: ${report.baselines.error}`]+ : report.baselines.claims.map(claim => ` ${claim}`)),+ ]+ : [+ ' none: no linked component or module record declares review triggers',+ ]),+ '',+ 'Checklist items that apply:',+ ...report.checks.map(+ item => ` [${item.id}] ${item.check}\n because ${item.reason}`,+ ),+ '',+ `Checklist: ${report.checklist}`,+ ];+ return lines.join('\n');+}++function valueFor(argv, flag) {+ const index = argv.indexOf(flag);+ if (index === -1) return null;+ const value = argv[index + 1];+ if (!value || value.startsWith('--'))+ throw new Error(`${flag} requires a value.`);+ return value;+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ const argv = process.argv.slice(2);+ const report = buildReport({+ base: valueFor(argv, '--base') ?? 'origin/main',+ head: valueFor(argv, '--head'),+ });+ console.log(+ argv.includes('--json')+ ? JSON.stringify(report, null, 2)+ : formatReport(report),+ );+}diff --git a/scripts/pre-review.test.mjs b/scripts/pre-review.test.mjsnew file mode 100644index 0000000000..a44f2e7916--- /dev/null+++ b/scripts/pre-review.test.mjs@@ -0,0 +1,199 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {execFileSync} from 'node:child_process';+import path from 'node:path';+import {describe, expect, it} from 'vitest';+import {+ CHECKS,+ applicableChecks,+ fileClass,+ formatReport,+} from './pre-review.mjs';++const repoRoot = path.resolve(import.meta.dirname, '..');++/** A unified diff that adds `lines` to `file`. */+function diffAdding(file, lines) {+ return [+ `diff --git a/${file} b/${file}`,+ `--- a/${file}`,+ `+++ b/${file}`,+ `@@ -1,0 +1,${lines.length} @@`,+ ...lines.map(line => `+${line}`),+ ].join('\n');+}++function idsFor(entries) {+ const files = entries.map(([file]) => file);+ const diff = entries+ .map(([file, lines]) => diffAdding(file, lines))+ .join('\n');+ return applicableChecks(files, diff).map(item => item.id);+}++describe('applicableChecks', () => {+ it('always applies the public boundary item', () => {+ expect(idsFor([['README.md', ['text']]])).toEqual(['d']);+ });++ it('routes a new hook row to the API delta and hook example items', () => {+ expect(+ idsFor([['packages/core/api-report.md', ['hook useThing: () => void']]]),+ ).toEqual(['a', 'd', 'e']);+ });++ it('routes a behavior or boolean prop row to the behavior prop item', () => {+ expect(+ idsFor([+ [+ 'packages/core/api-report.md',+ [" prop openBehavior?: 'hover' | 'press'"],+ ],+ ]),+ ).toEqual(['a', 'c', 'd']);+ expect(+ idsFor([['packages/core/api-report.md', [' prop isPinned?: boolean']]]),+ ).toEqual(['a', 'c', 'd']);+ });++ it('routes published source to the behavior item and its comments to the comment item', () => {+ expect(+ idsFor([+ [+ 'packages/core/src/Button/Button.tsx',+ [+ '// The focus ring shows only after keyboard input.',+ 'const x = 1;',+ ],+ ],+ ]),+ ).toEqual(['b', 'd', 'f']);+ });++ it('routes a hook export from an entry point to the hook example item', () => {+ expect(+ idsFor([+ [+ 'packages/core/src/index.ts',+ ["export {useThing} from './useThing/useThing';"],+ ],+ ]),+ ).toEqual(['b', 'd', 'e']);+ });++ it('ignores directives and the copyright line', () => {+ expect(+ idsFor([+ [+ 'packages/core/src/Button/Button.tsx',+ [+ '// eslint-disable-next-line no-console',+ '// Copyright (c) Meta Platforms, Inc. and affiliates.',+ ],+ ],+ ]),+ ).toEqual(['b', 'd']);+ });++ it('keeps tests, stories, and docs out of the source items', () => {+ expect(+ idsFor([+ ['packages/core/src/Button/Button.test.tsx', ['// Arrange the menu.']],+ ['packages/core/src/Button/Button.stories.tsx', ['// A story.']],+ ['packages/core/src/Button/Button.doc.mjs', ['// A doc.']],+ ]),+ ).toEqual(['d']);+ });++ it('routes published code outside src and shipped catalogs to the behavior item', () => {+ expect(+ idsFor([['packages/cli/clients/cli/bin/astryx.mjs', ['run();']]]),+ ).toEqual(['b', 'd']);+ expect(+ idsFor([['packages/core/locales/fr-FR.json', ['"key": "value"']]]),+ ).toEqual(['b', 'd']);+ });++ it('keeps private packages out of the behavior item', () => {+ expect(+ idsFor([+ ['packages/charts/src/Chart/Chart.tsx', ['// Clear the ring first.']],+ ]),+ ).toEqual(['d', 'f']);+ });++ it('applies the comment item to Lab source but not the behavior item', () => {+ expect(+ idsFor([+ ['packages/lab/src/Thing/Thing.tsx', ['// Clear the ring first.']],+ ]),+ ).toEqual(['d', 'f']);+ });++ it('routes an owner-gated record to the spec owner item', () => {+ expect(+ idsFor([+ ['docs/architecture/knowledge-contracts.md', ['- **INV99 — A rule.**']],+ ]),+ ).toEqual(['d', 'g']);+ });++ it('gives every item a checklist entry', () => {+ expect(Object.keys(CHECKS)).toEqual(['a', 'b', 'c', 'd', 'e', 'f', 'g']);+ });+});++describe('fileClass', () => {+ it('names the class a reviewer reads each path as', () => {+ const plain = {specRecord: false, ownerGatedRecord: false};+ expect(+ fileClass('docs/x.md', {specRecord: true, ownerGatedRecord: true}),+ ).toBe('record, owner-gated');+ expect(fileClass('packages/core/api-report.md', plain)).toBe('API report');+ expect(fileClass('packages/lab/src/A/A.tsx', plain)).toBe('Lab');+ expect(fileClass('packages/core/src/A/A.tsx', plain)).toBe(+ 'published package code',+ );+ expect(fileClass('packages/charts/src/A/A.tsx', plain)).toBe(+ 'package file',+ );+ expect(fileClass('scripts/x.mjs', plain)).toBe('repository');+ });+});++describe('formatReport', () => {+ it('lists the applicable items and the checklist link', () => {+ const text = formatReport({+ base: 'origin/main',+ head: 'working tree',+ mergeBase: 'a'.repeat(40),+ scope: 'changes include another surface',+ files: [+ {file: 'packages/core/src/A/A.tsx', class: 'published package code'},+ ],+ records: [{id: 'component:A', path: 'docs/specs/components/A/A.spec.md'}],+ claims: [],+ baselines: {command: null, claims: []},+ checks: [+ {id: 'd', check: CHECKS.d, reason: 'every pull request is public'},+ ],+ checklist: 'docs/contributing/pull-requests.md#pre-review-checklist',+ });+ expect(text).toContain('component:A docs/specs/components/A/A.spec.md');+ expect(text).toContain('[d] ');+ expect(text).toContain(+ 'Checklist: docs/contributing/pull-requests.md#pre-review-checklist',+ );+ });+});++describe('pnpm review:pre', () => {+ it('reports no changes for an empty range', () => {+ const output = execFileSync(+ process.execPath,+ ['scripts/pre-review.mjs', '--base', 'HEAD', '--head', 'HEAD'],+ {cwd: repoRoot, encoding: 'utf8'},+ );+ expect(output).toContain('No changes against HEAD...HEAD.');+ });+});diff --git a/scripts/specs-for-file.mjs b/scripts/specs-for-file.mjsindex 60159b8d19..4330ccaf9e 100644--- a/scripts/specs-for-file.mjs+++ b/scripts/specs-for-file.mjs@@ -948,7 +948,7 @@ id; --records shows how each one links.* 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) {+export function diffText(root, range) {const git = args =>execFileSync('git', ['-C', root, ...args], {encoding: 'utf8',