An open source design system that's fully customizable and agent ready
TypeScript
docs(architecture): a record's approval lines are append-only (#10688)
Cindy Zhang516630d5b63d
diff --git a/docs/architecture/knowledge-contracts.md b/docs/architecture/knowledge-contracts.mdindex 2547709d30..5d048a4815 100644--- a/docs/architecture/knowledge-contracts.md+++ b/docs/architecture/knowledge-contracts.md@@ -51,7 +51,8 @@ deciding_specs: []"DEC-12","DEC-13","DEC-15",- "INV28"+ "INV28",+ "INV31"]}}@@ -463,6 +464,24 @@ the rest:reserved example domains are not external links for this rule.- **a human owner** is `cixzhang` or a DESIGNOWNER, approving the exact head.+### Approval lines++- **INV31 — A record's approval lines are append-only.** A pull request that+ changes or removes an existing decision's Decider line, or replaces a+ record's `approved_by` with a different account, needs that original+ decider's approval at its exact head; `cixzhang`'s own pull request counts as+ hers. Adding a decision or an approver needs nothing extra (DEC-18). In this+ rule:+ - **the original decider** is the account the existing line names.+ - **approval** is an approving review at the exact head, or a+ `/approve-spec <full head SHA>` comment, from that account. Any decider+ other than `cixzhang` approves the exact head, also on their own pull+ request.+ - **a change** is an edit to or removal of the line, a removed decision+ included. A line that only moves, text added after an unchanged Decider+ line, and a placeholder decider that a real decider replaces are not+ changes.+## Path applicabilityUse this optional block when a record governs paths that its placement, path@@ -1316,6 +1335,18 @@ automation (INV30). Automated approval must not publish links an outsidecontributor added without a person checking them. Team-authored links followthe normal gates.+### DEC-18 — A record's approval lines are append-only++**Reference:** `architecture:knowledge-contracts/DEC-18`+**Decider:** `cixzhang`, `2026-11-08`++An existing decision's Decider line and a record's `approved_by` change only+with the original decider's approval at the exact head (INV31). An approval line+records who decided, so a rewrite without that person names someone who did not+make the decision. Only `cixzhang`'s own pull request counts as approval of her+own lines; every other decider approves the exact head. New decisions and added+approvers follow the normal gates.+### DEC-19 — A Lab-only pull request needs no owner decision**Reference:** `architecture:knowledge-contracts/DEC-19`@@ -1353,6 +1384,7 @@ Rejected: treating a pull request that also changes Core or another package as L| INV28, DEC-16 | `apps/docsite/src/lib/exampleCoverage.mjs` and `apps/docsite/src/__tests__/example-coverage.test.ts` (advisory: the report prints and never gates), plus review of each hook example against INV28's criteria | The report omits a public hook that has no hook doc or no conforming example block, or a missing or non-conforming hook example fails a merge or release || INV29 | Baselined lint over comments in package source (not built): record ids, pull request and issue numbers, date stamps, and long quote blocks fail in new comments, and existing sites are baselined. Review reports narration and file headers past about 12 lines as non-blocking findings. Cleanup lands in per-area pull requests with no behavior change, each with a `pnpm specs:for` comparison of every touched file before and after | A new comment cites a record, pull request, issue, or date, quotes a record, or narrates the code; a header grows past about 12 lines, with no lint failure or review finding; removing a comment drops a record or cited claim from a file's `pnpm specs:for` result because that comment was the file's only link to it; or cleanup removes or rewrites a directive a tool reads, such as a `@pr-a11y` line || INV30, DEC-17 | Human-owner review of each new external URL in a pull request from an author outside the team, enforced by review and merge tooling outside the repository; no repository CI check (the INV30 enforcement gap below) | An outside pull request that adds an external URL under package docs or the docsite is approved or merged without a human owner's exact-head approval, or a team pull request that adds one is held for a human owner |+| INV31, DEC-18 | `scripts/check-knowledge.test.mjs` "approval line history"; `pnpm check:knowledge --base <base>` lists each changed approval line with its original decider; review and merge tooling outside the repository require that decider's exact-head approval (the INV31 enforcement gap below) | A pull request that changes or removes an existing Decider or `approved_by` line is approved or merged without the original decider's exact-head approval, or a pull request that only adds a decision or an approver is held || DEC-15 | `.github/scripts/knowledge-paths.test.mjs`, `.github/scripts/change-scope.test.mjs`, `scripts/check-knowledge.test.mjs`, `scripts/specs-for-file.test.mjs`, and `pnpm check:knowledge` | A component or module record outside `docs/specs/components/<ComponentRoot>/`, a `*.spec.md` left in a component package's source tree or beside a Swift view, a record matched to the wrong package when two share a root, a record whose component root no registered package's source tree has, a platform record whose id or `platform_of` does not match its path, or a platform record change that skips the spec-owner gate |Evidence placement is enforced by contributors and reviewers. The local@@ -1392,3 +1424,8 @@ docs gap under INV28, tracked in the repository's issue queue.Current enforcement gap: no repository CI check detects a new external URL in apull request from an author outside the team (INV30). Review and merge toolingoutside the repository enforces this.++Current enforcement gap: no repository check reads approvals (INV31).+`pnpm check:knowledge --base <base>` reports each changed approval line as a+warning and does not fail. Review and merge tooling outside the repository+requires the original decider's approval.diff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjsindex ade3989a15..cfd75e01bd 100644--- a/scripts/check-knowledge.mjs+++ b/scripts/check-knowledge.mjs@@ -40,6 +40,7 @@ const {isIgnoredComponentKnowledgeSegment,isKnowledgeRecordPath,isPlatformComponentSpecPath,+ isValidatedRecordPath,locateComponentKnowledgePath,} = require('../.github/scripts/knowledge-paths.cjs');@@ -841,6 +842,17 @@ export function readKnowledgeRecordsAtAuthority(`authority commit must equal the review head's origin/main merge base ${expectedBase}.`,);}+ return {+ records: readKnowledgeRecordsAtRevision(root, resolvedCommit),+ authority: resolvedCommit,+ };+}++function readKnowledgeRecordsAtRevision(+ root,+ revision,+ isRecord = isKnowledgeRecordPath,+) {const paths = execFileSync('git',[@@ -849,7 +861,7 @@ export function readKnowledgeRecordsAtAuthority('ls-tree','-r','--name-only',- resolvedCommit,+ revision,'--','docs/architecture','docs/design',@@ -860,19 +872,148 @@ export function readKnowledgeRecordsAtAuthority({encoding: 'utf8'},).split(/\r?\n/)- .filter(isKnowledgeRecordPath);+ .filter(isRecord);const objects = readObjects(root,- paths.map(filePath => `${resolvedCommit}:${filePath}`),+ paths.map(filePath => `${revision}:${filePath}`),);- const records = paths.map(filePath => {- const content = objects.get(`${resolvedCommit}:${filePath}`);+ return paths.map(filePath => {+ const content = objects.get(`${revision}:${filePath}`);if (!content) {- throw new Error(`cannot read ${filePath} at ${resolvedCommit}.`);+ throw new Error(`cannot read ${filePath} at ${revision}.`);}return {path: filePath, content: content.toString('utf8')};});- return {records, authority: resolvedCommit};+}++// A decision starts at a `DEC-n` or `Amendment` heading, or at a+// `- **DEC-n …**` list item. Its Decider line may share a line with its+// Reference, and may name several deciders.+const DECISION_HEADING = /^#{2,4} (DEC-[0-9]+[a-z]?)\b/;+const AMENDMENT_HEADING = /^#{2,4} (Amendment\b.*?)\s*$/;+const DECISION_ITEM = /^\s*[-*] \*\*(DEC-[0-9]+[a-z]?)\b/;+const ANY_HEADING = /^#{1,4} /;+// Any bold label that ends in "decider" or "deciders" (a decision may name+// several, such as a system-boundary and an adoption decider), except a+// proposed one, which approves nothing.+const DECIDER_LINE =+ /\*\*((?:[^*]*?\s)?[Dd]eciders?|Direction owners?):?\*\*:?\s*(.*)$/;+const PROPOSED_DECIDER = /^proposed\b/i;+const PLACEHOLDER_DECIDER = /pending|<[^>]*>/i;++function deciderLines(content) {+ const deciders = new Map();+ let decision = null;+ for (const line of content.split(/\r?\n/)) {+ const heading =+ line.match(DECISION_HEADING) ?? line.match(AMENDMENT_HEADING);+ if (heading || ANY_HEADING.test(line)) decision = heading?.[1] ?? null;+ const item = line.match(DECISION_ITEM);+ if (item) decision = item[1];+ const decider = decision && line.match(DECIDER_LINE);+ if (!decider || PROPOSED_DECIDER.test(decider[1])) continue;+ const label = decider[1].trim();+ const key = /^(deciders?|direction owners?)$/i.test(label)+ ? decision+ : `${decision} (${label})`;+ if (!deciders.has(key)) {+ deciders.set(key, decider[2].replace(/\s+/g, ' ').trim());+ }+ }+ return deciders;+}++function approvers(document) {+ const value = document.frontmatter.get('approved_by');+ if (value == null) return [];+ return Array.isArray(value) ? value.map(String) : [String(value)];+}++function originalDecider(line) {+ return line+ .split(';')[0]+ .split(',')+ .map(field => field.replace(/[`@]/g, '').replace(/\.$/, '').trim())+ .filter(field => field && !/^\d{4}-\d{2}-\d{2}/.test(field))+ .join(', ');+}++// Only the decider and date fields can hold a placeholder. The rest of the+// line is free text, such as a decision's subject.+function hasPlaceholderDecider(line) {+ const [decider = '', date = ''] = line.split(';')[0].split(',');+ return (+ PROPOSED_DECIDER.test(decider.replace(/[`@]/g, '').trim()) ||+ PLACEHOLDER_DECIDER.test(decider) ||+ PLACEHOLDER_DECIDER.test(date.split('(')[0])+ );+}++/**+ * The approval lines a pull request changes or removes, with the account whose+ * approval each change needs (INV31). Records pair by id, so a moved record or+ * a moved line is not a change.+ */+export function findApprovalLineRewrites(baseRecords, currentRecords) {+ const byId = records =>+ new Map(+ records.map(record => {+ const document = parseKnowledgeDocument(record.content, record.path);+ return [+ document.frontmatter.get('id') ?? record.path,+ {record, document},+ ];+ }),+ );+ const current = byId(currentRecords);+ const changes = [];+ for (const [id, base] of byId(baseRecords)) {+ const head = current.get(id);+ const headApprovers = head ? approvers(head.document) : [];+ const path = head?.record.path ?? base.record.path;+ const baseApprovers = approvers(base.document);+ for (const login of baseApprovers) {+ if (headApprovers.includes(login)) continue;+ const from = baseApprovers.join(', ');+ const to = headApprovers.join(', ') || null;+ changes.push({path, claim: 'approved_by', from, to, decider: login});+ }+ const headDeciders = head ? deciderLines(head.record.content) : new Map();+ for (const [decision, from] of deciderLines(base.record.content)) {+ if (hasPlaceholderDecider(from)) continue;+ const to = headDeciders.get(decision) ?? null;+ if (to?.startsWith(from)) continue;+ changes.push({+ path,+ claim: decision,+ from,+ to,+ decider: originalDecider(from),+ });+ }+ }+ return changes;+}++function currentValidatedRecords(root, repositoryFiles) {+ return repositoryFiles+ .filter(isValidatedRecordPath)+ .filter(filePath => fs.existsSync(path.join(root, filePath)))+ .map(filePath => ({+ path: filePath,+ content: fs.readFileSync(path.join(root, filePath), 'utf8'),+ }));+}++/**+ * The approval lines the working tree changes since `baseRevision`, in every+ * validated record: knowledge records and platform component records.+ */+export function approvalLineRewritesSince(root, baseRevision, repositoryFiles) {+ return findApprovalLineRewrites(+ readKnowledgeRecordsAtRevision(root, baseRevision, isValidatedRecordPath),+ currentValidatedRecords(root, repositoryFiles),+ );}function immediateDirectories(directory) {@@ -2477,6 +2618,15 @@ async function main() {currentSchemaFiles(DEFAULT_ROOT),),);+ const repositoryFiles = repositoryFileList(DEFAULT_ROOT);+ const changes = repositoryFiles+ ? approvalLineRewritesSince(DEFAULT_ROOT, baseRevision, repositoryFiles)+ : [];+ for (const change of changes) {+ console.warn(+ `${change.path}: ${change.claim} changes from "${change.from}" to "${change.to ?? 'removed'}"; it needs ${change.decider}'s approval at the exact head (INV31).`,+ );+ }}if (problems.length) {console.error(`Knowledge validation failed (${problems.length}):\n`);diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjsindex ba88ec91cd..2de9f9913a 100644--- a/scripts/check-knowledge.test.mjs+++ b/scripts/check-knowledge.test.mjs@@ -31,6 +31,8 @@ import {validatePathApplicability,validateReviewApplicability,validateSchemaEvolution,+ approvalLineRewritesSince,+ findApprovalLineRewrites,} from './check-knowledge.mjs';const repoRoot = path.resolve(import.meta.dirname, '..');@@ -850,6 +852,276 @@ describe('schema evolution', () => {});});+describe('approval line history', () => {+ function record({approvedBy = 'owner-a', decisions = []} = {}) {+ return {+ path: 'docs/architecture/example.md',+ content: [+ '---',+ 'id: architecture:example',+ 'authority: current',+ `approved_by: ${approvedBy}`,+ '---',+ '',+ '## Deciding specs',+ '',+ ...decisions.flatMap(([id, decider]) => [+ `### ${id} — A decision`,+ '',+ `**Decider:** ${decider}`,+ '',+ 'The decision text.',+ '',+ ]),+ ].join('\n'),+ };+ }+ const base = record({+ decisions: [['DEC-1', '`owner-a`, `2026-11-01`']],+ });++ it('reports a rewritten Decider and approved_by with the original decider', () => {+ const head = record({+ approvedBy: 'owner-b',+ decisions: [['DEC-1', '`owner-b`, `2026-11-01`']],+ });+ expect(findApprovalLineRewrites([base], [head])).toEqual([+ {+ path: 'docs/architecture/example.md',+ claim: 'approved_by',+ from: 'owner-a',+ to: 'owner-b',+ decider: 'owner-a',+ },+ {+ path: 'docs/architecture/example.md',+ claim: 'DEC-1',+ from: '`owner-a`, `2026-11-01`',+ to: '`owner-b`, `2026-11-01`',+ decider: 'owner-a',+ },+ ]);+ });++ it('reports a removed decision', () => {+ expect(findApprovalLineRewrites([base], [record()])).toEqual([+ expect.objectContaining({claim: 'DEC-1', to: null, decider: 'owner-a'}),+ ]);+ });++ it('allows a new decision, an added approver, an amendment, and a filled placeholder', () => {+ const pendingBase = record({+ decisions: [+ ['DEC-1', '`owner-a`, `2026-11-01`'],+ ['DEC-2', '`owner-a`, `<pending>`'],+ ],+ });+ const head = record({+ approvedBy: '[owner-a, owner-b]',+ decisions: [+ ['DEC-2', '`owner-a`, `2026-11-08`'],+ ['DEC-1', '`owner-a`, `2026-11-01`; amended `2026-11-08`'],+ ['DEC-3', '`owner-b`, `2026-11-08`'],+ ],+ });+ expect(findApprovalLineRewrites([pendingBase], [head])).toEqual([]);+ });++ it('reads a placeholder only in the decider and date fields', () => {+ const decided =+ '`owner-a`, `2026-11-01`; pending-search Enter, a quiet send';+ const rewritten = findApprovalLineRewrites(+ [record({decisions: [['DEC-1', decided]]})],+ [+ record({+ decisions: [+ [+ 'DEC-1',+ '`owner-b`, `2026-11-01`; pending-search Enter, a quiet send',+ ],+ ],+ }),+ ],+ );+ expect(rewritten).toEqual([+ expect.objectContaining({+ claim: 'DEC-1',+ from: decided,+ decider: 'owner-a',+ }),+ ]);+ // A placeholder date, with or without a note, is still a placeholder.+ for (const placeholder of [+ '`owner-a`, `<pending>`',+ '`owner-a`, pending (awaiting the owner)',+ 'proposed by `owner-a`, `2026-09-27`; pending owner review',+ ]) {+ expect(+ findApprovalLineRewrites(+ [record({decisions: [['DEC-1', placeholder]]})],+ [record({decisions: [['DEC-1', '`owner-a`, `2026-11-08`']]})],+ ),+ placeholder,+ ).toEqual([]);+ }+ });++ it('reads every decided-line shape the records use', () => {+ const doc = lines => ({+ path: 'docs/specs/AST-900/spec.md',+ content: [+ '---',+ 'id: spec:AST-900',+ 'authority: current',+ 'approved_by: owner-a',+ '---',+ '',+ ...lines,+ ].join('\n'),+ });+ const shapes = [+ // Reference and Decider on one line.+ [+ '### DEC-1 — One line',+ '',+ '**Reference:** `spec:AST-900/DEC-1` · **Decider:** `owner-a`, `2026-08-31`',+ ],+ // Several deciders.+ [+ '### DEC-2 — Two owners',+ '',+ '**Deciders:** `owner-a`, `owner-c`, `2026-09-03`',+ ],+ // A list-item decision with an indented Decider line.+ [+ '- **DEC-3 — A list item.**',+ '',+ ' **Decider:** `owner-a`, 2026-10-24',+ ],+ // An amendment heading.+ [+ '### Amendment — Narrow the name',+ '',+ '**Decider:** `owner-a`, `2026-09-12`',+ ],+ // A direction owner names who decided.+ [+ '### DEC-4 — Owner label',+ '',+ '**Direction owner:** `owner-a`, `2026-10-02`',+ ],+ ];+ const expected = [+ {claim: 'DEC-1', decider: 'owner-a'},+ {claim: 'DEC-2', decider: 'owner-a, owner-c'},+ {claim: 'DEC-3', decider: 'owner-a'},+ {claim: 'Amendment — Narrow the name', decider: 'owner-a'},+ {claim: 'DEC-4', decider: 'owner-a'},+ ];+ shapes.forEach((shape, i) => {+ const rewritten = shape.map(line => line.replace('owner-a', 'owner-b'));+ expect(+ findApprovalLineRewrites([doc(shape)], [doc(rewritten)]),+ shape[0],+ ).toEqual([expect.objectContaining(expected[i])]);+ expect(+ findApprovalLineRewrites([doc(shape)], [doc(['## Notes'])]),+ `${shape[0]} removed`,+ ).toEqual([expect.objectContaining({...expected[i], to: null})]);+ expect(findApprovalLineRewrites([doc(shape)], [doc(shape)])).toEqual([]);+ });+ });++ it('reads each labelled decider of a decision, and no proposed one', () => {+ const doc = lines => ({+ path: 'packages/themes/example/example.spec.md',+ content: [+ '---',+ 'id: theme:example',+ 'authority: current',+ 'approved_by: owner-a',+ '---',+ '',+ '### DEC-1 — Two deciders',+ '',+ ...lines,+ ].join('\n'),+ });+ const base = [+ '**System-boundary decider:** `owner-a`, `2026-08-31`',+ '**Final adoption decider:** `owner-c`, `2026-10-17`',+ '**Proposed decider:** `owner-d`',+ ];+ const adoption = base.map(line => line.replace('owner-c', 'owner-b'));+ expect(findApprovalLineRewrites([doc(base)], [doc(adoption)])).toEqual([+ expect.objectContaining({+ claim: 'DEC-1 (Final adoption decider)',+ decider: 'owner-c',+ }),+ ]);+ const boundary = base.map(line => line.replace('owner-a', 'owner-b'));+ expect(findApprovalLineRewrites([doc(base)], [doc(boundary)])).toEqual([+ expect.objectContaining({+ claim: 'DEC-1 (System-boundary decider)',+ decider: 'owner-a',+ }),+ ]);+ const proposal = base.map(line => line.replace('owner-d', 'owner-e'));+ expect(findApprovalLineRewrites([doc(base)], [doc(proposal)])).toEqual([]);+ });++ it('warns for a platform component record too', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'approval-lines-'));+ try {+ const file = 'docs/specs/components/TextInput/TextInput.swift.spec.md';+ const git = (...args) =>+ execFileSync('git', ['-C', dir, ...args], {+ encoding: 'utf8',+ env: {+ ...process.env,+ GIT_AUTHOR_NAME: 't',+ GIT_AUTHOR_EMAIL: '[email protected]',+ GIT_COMMITTER_NAME: 't',+ GIT_COMMITTER_EMAIL: '[email protected]',+ },+ });+ const write = approvedBy => {+ fs.mkdirSync(path.join(dir, path.dirname(file)), {recursive: true});+ fs.writeFileSync(+ path.join(dir, file),+ [+ '---',+ 'id: component:TextInput/swift',+ 'authority: current',+ `approved_by: ${approvedBy}`,+ '---',+ '',+ '# TextInput (Swift)',+ '',+ ].join('\n'),+ );+ };+ git('init', '-q');+ write('owner-a');+ git('add', '-A');+ git('commit', '-q', '-m', 'base');+ const base = git('rev-parse', 'HEAD').trim();+ write('owner-b');+ expect(approvalLineRewritesSince(dir, base, [file])).toEqual([+ {+ path: file,+ claim: 'approved_by',+ from: 'owner-a',+ to: 'owner-b',+ decider: 'owner-a',+ },+ ]);+ } finally {+ fs.rmSync(dir, {recursive: true, force: true});+ }+ });+});+describe('component-local design decisions', () => {const row ='| DD1 | Keep the label visually quiet. | Preserve primary-action emphasis. | Default label | Theme token substitutions may preserve contrast. |';