Skip to content

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

TypeScript

docs: route global review baselines by claim (#6386)

Cindy Zhang176dfa624002
diff --git a/AGENTS.md b/AGENTS.md
index 5887263203..bfeddfee6a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -20,9 +20,16 @@ nested `AGENTS.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.
-- Component work: read the component's `{Name}.spec.md` when one exists, then
- any `module:*` records it lists for the public module being changed, followed by
- consumer docs, tests, and implementation.
+- 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> --triggers
+<comma-separated-triggers>`, then read
+ the component's `{Name}.spec.md` when one exists and any `module:*` records it
+ lists. Load global records before narrower owners, but resolve the direct
+ component or family owner first when it governs the exact delta. A global
+ route exposes only the listed claim; it never makes the whole record govern
+ the component or change. Preserve each matched record, claim, trigger, and
+ match reason in the review receipt.
- Cross-component work: read the relevant contract under `docs/families/`,
applicable design spec under `docs/design/`, and current architecture under
`docs/architecture/`.
diff --git a/docs/README.md b/docs/README.md
index 542703dade..890a8442a4 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -96,6 +96,17 @@ Published schema versions may extend an earlier schema. The checker composes the
chain and tracks the latest version that defines each record kind. A new kind is
therefore additive; changing an existing kind migrates only that kind.
+An optional `review-applicability:v1` JSON block can route selected claims from a
+record as cross-cutting review baselines. This is an independently versioned
+metadata overlay, like `anatomy-theming:v1`, so adding it does not change a
+record kind's required shape or migrate records that do not opt in. The block
+must declare `scope: "global"` and map each semantic trigger to one or more exact
+claim ids from the same record. Validation rejects malformed, empty, duplicate,
+or stale claim routes. Routing requires the reviewed head, verifies the supplied
+base authority commit is its `origin/main` merge base, includes only
+`authority: current` records, and returns only the matched claims; draft records
+and nonmatching routes are omitted.
+
New record kinds should prefer one typed relationship list over parallel fields.
If `system-spec` receives a future schema revision, replace its legacy
`affects_*` fields with one typed `affects` list containing ids such as
diff --git a/docs/architecture/component-size-cascade.md b/docs/architecture/component-size-cascade.md
index f29c13a521..b5b858cd2e 100644
--- a/docs/architecture/component-size-cascade.md
+++ b/docs/architecture/component-size-cascade.md
@@ -30,6 +30,17 @@ deciding_specs: []
# Component size cascade architecture
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "layout": ["INV1", "INV2", "INV3", "INV4", "INV5", "INV9"]
+ }
+}
+```
+
## Purpose
A person should encounter coherent control sizing inside a component-owned group
diff --git a/docs/architecture/component-style-authoring.md b/docs/architecture/component-style-authoring.md
index 39e10e6872..d3c8497dc5 100644
--- a/docs/architecture/component-style-authoring.md
+++ b/docs/architecture/component-style-authoring.md
@@ -22,6 +22,17 @@ deciding_specs: []
# Component style authoring architecture
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "styling": ["INV1", "INV2", "INV3", "INV4", "INV5"]
+ }
+}
+```
+
## Purpose
Astryx component styling should lower to valid maintained CSS, compose predictably
diff --git a/docs/architecture/component-test-sufficiency.md b/docs/architecture/component-test-sufficiency.md
index 90161a31d8..6ff46334ab 100644
--- a/docs/architecture/component-test-sufficiency.md
+++ b/docs/architecture/component-test-sufficiency.md
@@ -23,6 +23,27 @@ deciding_specs: []
# Component test sufficiency architecture
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "testing": [
+ "INV1",
+ "INV2",
+ "INV3",
+ "INV4",
+ "INV5",
+ "INV6",
+ "INV7",
+ "INV10",
+ "INV11"
+ ]
+ }
+}
+```
+
## Purpose
Astryx component tests should give maintainers confidence that current promised
diff --git a/docs/architecture/component-theming-surface.md b/docs/architecture/component-theming-surface.md
index 6fd0fc27f9..2ae02729fd 100644
--- a/docs/architecture/component-theming-surface.md
+++ b/docs/architecture/component-theming-surface.md
@@ -41,6 +41,29 @@ deciding_specs:
# Component theming surface
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "theming": [
+ "INV3",
+ "INV4",
+ "INV5",
+ "INV6",
+ "INV7",
+ "INV8",
+ "INV9",
+ "INV10",
+ "INV12",
+ "INV14",
+ "INV15"
+ ]
+ }
+}
+```
+
This record defines how component anatomy relates to the public theming API.
## Purpose
diff --git a/docs/architecture/container-padding.md b/docs/architecture/container-padding.md
index 6fb9184357..5157b7491c 100644
--- a/docs/architecture/container-padding.md
+++ b/docs/architecture/container-padding.md
@@ -41,6 +41,17 @@ deciding_specs: [spec:AST-025/DEC-2]
# Container padding architecture
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "layout": ["INV1", "INV3", "INV6", "INV8"]
+ }
+}
+```
+
## Purpose
Padded containers and their descendants need one shared account of the inset at
diff --git a/docs/architecture/icon-resolution-and-component-slots.md b/docs/architecture/icon-resolution-and-component-slots.md
index 556f014fe8..7baa5f3763 100644
--- a/docs/architecture/icon-resolution-and-component-slots.md
+++ b/docs/architecture/icon-resolution-and-component-slots.md
@@ -28,6 +28,17 @@ deciding_specs: []
# Icon resolution and component slots
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "component-slots": ["INV1", "INV2", "INV3", "INV6", "INV7", "INV10"]
+ }
+}
+```
+
This record defines how shared icons and component-owned icon roles fit together.
It is the approved target architecture. Existing extension keys continue to work
until a separate compatibility decision changes them.
diff --git a/docs/architecture/interaction-modality.md b/docs/architecture/interaction-modality.md
index 9a964b757e..711ba66107 100644
--- a/docs/architecture/interaction-modality.md
+++ b/docs/architecture/interaction-modality.md
@@ -30,6 +30,17 @@ deciding_specs: []
# Interaction modality architecture
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "interaction": ["INV1", "INV2", "INV3", "INV4", "INV7", "INV8"]
+ }
+}
+```
+
## Purpose
Astryx components behave predictably when people move between keyboard, pointer,
diff --git a/docs/architecture/knowledge-contracts.md b/docs/architecture/knowledge-contracts.md
index f1e19db068..3ed003e8c4 100644
--- a/docs/architecture/knowledge-contracts.md
+++ b/docs/architecture/knowledge-contracts.md
@@ -28,6 +28,25 @@ deciding_specs: []
# Knowledge contracts and decisions
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "specification": [
+ "INV9",
+ "INV11",
+ "INV14",
+ "INV16",
+ "INV18",
+ "INV20",
+ "DEC-9"
+ ]
+ }
+}
+```
+
## Purpose
A reviewer should be able to answer two questions without rereading old pull
@@ -196,6 +215,49 @@ Every record is either:
clarify. Automation may report contradictions, evidence gaps, and proposed edits;
it MUST NOT approve, adopt, ratify, or make the contract current. A human approval
remains required even when the advisory analysis finds no defect.
+- **INV20 — Global review routing is explicit and claim-scoped.** A cross-cutting
+ baseline 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
+ global claims before narrower records, then resolves the direct component,
+ module, or family owner first when it governs the delta. The marker never makes
+ the 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.
+
+## Global review applicability
+
+Use this optional block only when named claims apply across otherwise unrelated
+component owners. Ordinary component, module, family, design, architecture, theme,
+and system records remain unmarked.
+
+<!-- review-applicability-example:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "public-api": ["FR1", "DEC-2"],
+ "accessibility": ["AR1"]
+ }
+}
+```
+
+In an opted-in record, replace the example marker with
+`review-applicability:v1`. Trigger names use this closed vocabulary:
+`accessibility`, `behavior`, `compatibility`, `component-slots`, `docsite`,
+`interaction`, `layering`, `layout`, `motion`, `navigation`, `platform`,
+`public-api`, `react-runtime`, `responsive`, `scrolling`, `specification`,
+`styling`, `testing`, `theming`, `tokens`, and `visual`. Every trigger has a
+non-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.
+`scripts/review-global-baselines.mjs` requires both the exact reviewed head and
+its full base authority commit, verifies that commit is the head's `origin/main`
+merge base, and emits deterministically sorted match rows. It therefore cannot
+read a proposed head as its own authority. Consumers load those rows before narrow lookup, preserve their
+provenance in a review receipt, and apply only the cited claim after the direct
+owner has been resolved.
## Writing specifications and contracts
@@ -626,20 +688,36 @@ Rejected: automatically approving a specification because its checks are green,
returning only “needs human” without giving the owner the contract and ownership
analysis already available to the reviewer.
+### DEC-9 — Global applicability routes exact claims, not whole records
+
+**Reference:** `architecture:knowledge-contracts/DEC-9`
+**Decider:** `cixzhang`, `2026-09-19`
+
+A cross-cutting rule is discoverable without a component backlink only through a
+validated `review-applicability:v1` block. Each semantic trigger names exact local
+claim ids. Reviewers load matching current claims from the base authority commit
+before narrower records, preserve match provenance, and then resolve the direct
+owner first when it governs the delta.
+
+Rejected: treating a `global` marker as authority for every statement in a file,
+because that would erase claim boundaries and let unrelated or draft material
+silently govern a change.
+
## Verification
-| Invariant | Evidence | Failure signal |
-| --------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| INV1, INV6 | `scripts/check-knowledge.test.mjs` | An unapproved current record or unmigrated active record passes |
-| INV5, INV7 | `.github/scripts/change-scope.test.mjs` | A template, schema, guidance, architecture, code change, unsafe rename, or truncated list qualifies as spec-only |
-| Approval follows the current head | `.github/scripts/spec-owner-decision.test.mjs` | An approval for another commit clears the gate, a self-declared owner becomes an approver, or the wrong owner group approves a current theme record |
-| INV3, INV4, INV11 | Blinded historical review benchmark | Reviewer re-asks a settled decision, invents a new one, approves an unsettled public delta, or treats a contradiction as preserves |
-| INV10 | Record-content and review-disposition fixtures | A spec assigns a PR verdict, or a reviewer treats a PR link as authority |
-| INV13 | Blinded spec-authorship fixture plus overlap-search receipt | An author creates parallel authority, searches only landed records or filenames, misses open work on the canonical owner, or treats an open PR as authority |
-| INV14, INV15 | Narrow-decision and mixed-intent review fixtures | A current visual slice is forced to contract its whole module, a separable tagalong blocks a repair, or review reports a gap without a landing-ready remedy |
-| INV16, INV17 | Spec-first review and missing-context fixtures | Generated checklist completeness overrides authority, review invents product direction, restates supplied context, or fails to identify an unrelated tagalong or affected caller state |
-| INV18 | Spec-review mechanism analysis plus owner migration receipt | A new/amended product spec requires a private mechanism without proving it is public, silently invalidates an existing current record, or leaves touched architecture wording in the product contract |
-| INV19 | Spec-review ownership-collision receipt and human decision | Automated review approves a product contract, omits current/open owner overlap, misses a collision or architecture leak, or returns only a human hold without actionable written analysis |
+| Invariant | Evidence | Failure signal |
+| --------------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| INV1, INV6 | `scripts/check-knowledge.test.mjs` | An unapproved current record or unmigrated active record passes |
+| INV5, INV7 | `.github/scripts/change-scope.test.mjs` | A template, schema, guidance, architecture, code change, unsafe rename, or truncated list qualifies as spec-only |
+| Approval follows the current head | `.github/scripts/spec-owner-decision.test.mjs` | An approval for another commit clears the gate, a self-declared owner becomes an approver, or the wrong owner group approves a current theme record |
+| INV3, INV4, INV11 | Blinded historical review benchmark | Reviewer re-asks a settled decision, invents a new one, approves an unsettled public delta, or treats a contradiction as preserves |
+| INV10 | Record-content and review-disposition fixtures | A spec assigns a PR verdict, or a reviewer treats a PR link as authority |
+| INV13 | Blinded spec-authorship fixture plus overlap-search receipt | An author creates parallel authority, searches only landed records or filenames, misses open work on the canonical owner, or treats an open PR as authority |
+| INV14, INV15 | Narrow-decision and mixed-intent review fixtures | A current visual slice is forced to contract its whole module, a separable tagalong blocks a repair, or review reports a gap without a landing-ready remedy |
+| INV16, INV17 | Spec-first review and missing-context fixtures | Generated checklist completeness overrides authority, review invents product direction, restates supplied context, or fails to identify an unrelated tagalong or affected caller state |
+| INV18 | Spec-review mechanism analysis plus owner migration receipt | A new/amended product spec requires a private mechanism without proving it is public, silently invalidates an existing current record, or leaves touched architecture wording in the product contract |
+| INV19 | Spec-review ownership-collision receipt and human decision | Automated review approves a product contract, omits current/open owner overlap, misses a collision or architecture leak, or returns only a human hold without actionable written analysis |
+| INV20, DEC-9 | `scripts/check-knowledge.test.mjs` and `scripts/review-global-baselines.mjs` | A matching review misses a current global claim, loads a draft/nonmatching claim, loses base-commit provenance, or treats the rest of a routed record as authority |
Current enforcement gap: no checked-in gate yet proves the open-pull-request
search. Until one exists, the pull-request summary records the search terms,
diff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.md
index b13fac61ac..7ebd388728 100644
--- a/docs/architecture/layer-runtime.md
+++ b/docs/architecture/layer-runtime.md
@@ -42,6 +42,17 @@ deciding_specs: []
# Layer runtime
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "layering": ["INV2", "INV5", "INV6", "INV7"]
+ }
+}
+```
+
This record describes the layer runtime shipped on current `main`. Accepted but
unimplemented changes live in `spec:AST-003`; they are not current architecture.
diff --git a/docs/architecture/public-component-api.md b/docs/architecture/public-component-api.md
index c08ed6066b..9e27b7d0ff 100644
--- a/docs/architecture/public-component-api.md
+++ b/docs/architecture/public-component-api.md
@@ -35,6 +35,28 @@ deciding_specs:
# Public component API
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "public-api": [
+ "INV1",
+ "INV2",
+ "INV3",
+ "INV4",
+ "INV5",
+ "INV6",
+ "INV7",
+ "INV8",
+ "INV9",
+ "INV12"
+ ]
+ }
+}
+```
+
This record defines the shared public API contract for stable Astryx components.
## Purpose
diff --git a/docs/architecture/react-component-runtime.md b/docs/architecture/react-component-runtime.md
index 29f9c3440a..0fb4496b1b 100644
--- a/docs/architecture/react-component-runtime.md
+++ b/docs/architecture/react-component-runtime.md
@@ -20,6 +20,17 @@ deciding_specs: []
# React component runtime architecture
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "react-runtime": ["INV1", "INV2", "INV3", "INV4", "INV5", "INV6", "INV8"]
+ }
+}
+```
+
## Purpose
Astryx components should preserve their documented behavior through render,
diff --git a/docs/architecture/theme-application.md b/docs/architecture/theme-application.md
index 58c779b7a9..8e6b841650 100644
--- a/docs/architecture/theme-application.md
+++ b/docs/architecture/theme-application.md
@@ -30,6 +30,17 @@ deciding_specs: [spec:AST-012/DEC-1]
# Theme application
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "theming": ["INV1", "INV2", "INV3", "INV7", "INV8", "INV9"]
+ }
+}
+```
+
This record defines how a compiled theme becomes active for a React tree and the
browser document.
diff --git a/docs/architecture/theme-authoring-contract.md b/docs/architecture/theme-authoring-contract.md
index 58aa56d53a..7e9d0e484e 100644
--- a/docs/architecture/theme-authoring-contract.md
+++ b/docs/architecture/theme-authoring-contract.md
@@ -53,6 +53,17 @@ deciding_specs:
# Theme authoring contract
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "theming": ["INV1", "INV3", "INV8", "INV9", "INV11", "INV12"]
+ }
+}
+```
+
This record defines what a theme author may express and how `defineTheme`
normalizes that input into one self-contained theme representation.
diff --git a/docs/architecture/theme-compilation.md b/docs/architecture/theme-compilation.md
index 7040ffec93..c8dae4a3cf 100644
--- a/docs/architecture/theme-compilation.md
+++ b/docs/architecture/theme-compilation.md
@@ -40,6 +40,17 @@ deciding_specs:
# Theme compilation
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "theming": ["INV2", "INV3", "INV4", "INV6", "INV9", "INV10"]
+ }
+}
+```
+
This record defines how one theme definition becomes usable styles.
## Purpose
diff --git a/docs/architecture/theme-tokens.md b/docs/architecture/theme-tokens.md
index dc792db32a..5bead3a0d3 100644
--- a/docs/architecture/theme-tokens.md
+++ b/docs/architecture/theme-tokens.md
@@ -30,6 +30,17 @@ deciding_specs: [spec:AST-006/DEC-1, spec:AST-006/DEC-5]
# Theme token architecture
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "tokens": ["INV1", "INV3", "INV4", "INV6", "INV8"]
+ }
+}
+```
+
This record defines the semantic token vocabulary that components, themes,
documentation, and non-CSS consumers share.
diff --git a/docs/contributing/pull-requests.md b/docs/contributing/pull-requests.md
index 645f53c4d5..508be8875e 100644
--- a/docs/contributing/pull-requests.md
+++ b/docs/contributing/pull-requests.md
@@ -33,6 +33,12 @@ Product behavior remains owned by the applicable current component, module,
family, design, theme, architecture, or system record. API caller burden follows
`spec:AST-002`.
+Reviews also load any `current` cross-cutting claims whose machine-readable global
+route matches the change's semantic triggers. The direct component, module, or
+family owner still resolves the exact delta first; a global route contributes only
+its listed claim and never grants authority to the rest of that record. Review
+receipts identify the matched record, claim, trigger, and reason.
+
## Keep the intent atomic
Before requesting review, partition every observable delta:
diff --git a/docs/families/navigation-destinations.md b/docs/families/navigation-destinations.md
index b720eabec7..74437fe7f1 100644
--- a/docs/families/navigation-destinations.md
+++ b/docs/families/navigation-destinations.md
@@ -47,6 +47,17 @@ deciding_specs: [spec:AST-005/DEC-1, spec:AST-005/DEC-2]
# Navigation destinations contract
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "navigation": ["FR1", "FR3", "FR4", "FR5"]
+ }
+}
+```
+
## Intent
People should receive the same safe navigation behavior from every Astryx
diff --git a/docs/families/overlay-dismissal.md b/docs/families/overlay-dismissal.md
index a57899abbe..deff79eded 100644
--- a/docs/families/overlay-dismissal.md
+++ b/docs/families/overlay-dismissal.md
@@ -65,6 +65,17 @@ deciding_specs: []
# Overlay dismissal family contract
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "layering": ["FR1", "FR2", "FR3", "FR6"]
+ }
+}
+```
+
## Intent
A person dismissing layered UI should affect only the topmost relevant surface.
diff --git a/docs/specs/AST-002/spec.md b/docs/specs/AST-002/spec.md
index b20f872b50..04baa2de77 100644
--- a/docs/specs/AST-002/spec.md
+++ b/docs/specs/AST-002/spec.md
@@ -18,6 +18,26 @@ affects_consumer_docs: []
# Public API admission and operation shape
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "public-api": [
+ "FR4",
+ "FR15",
+ "DEC-1",
+ "DEC-2",
+ "DEC-3",
+ "DEC-6",
+ "DEC-7",
+ "DEC-8"
+ ]
+ }
+}
+```
+
## Intent
Keep Astryx public APIs intentional. A public API should represent a distinction
diff --git a/docs/specs/AST-003/spec.md b/docs/specs/AST-003/spec.md
index 4ee114225a..764c2bd59d 100644
--- a/docs/specs/AST-003/spec.md
+++ b/docs/specs/AST-003/spec.md
@@ -23,6 +23,17 @@ affects_consumer_docs: []
# Layer coordination and global hosting system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "layering": ["FR10", "DEC-1", "DEC-2", "DEC-3", "DEC-5"]
+ }
+}
+```
+
## Intent
Make every layered interaction close the intended owner or interaction branch,
diff --git a/docs/specs/AST-005/spec.md b/docs/specs/AST-005/spec.md
index 8efb42efbd..d3b23c1080 100644
--- a/docs/specs/AST-005/spec.md
+++ b/docs/specs/AST-005/spec.md
@@ -19,6 +19,17 @@ affects_consumer_docs:
# Safe navigation destinations
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "navigation": ["FR2", "FR3", "FR4", "FR6", "FR7", "FR8", "DEC-1", "DEC-2"]
+ }
+}
+```
+
## Intent
A person activating an Astryx link should get the same destination safety no
diff --git a/docs/specs/AST-006/spec.md b/docs/specs/AST-006/spec.md
index b921647905..a0ac564328 100644
--- a/docs/specs/AST-006/spec.md
+++ b/docs/specs/AST-006/spec.md
@@ -23,6 +23,17 @@ affects_consumer_docs: [theme]
# Theme-local tokens system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "tokens": ["DEC-1", "DEC-2", "DEC-3", "DEC-4", "DEC-5", "DEC-6"]
+ }
+}
+```
+
## Intent
Let a maintained theme reuse one of its own semantic decisions across component
diff --git a/docs/specs/AST-009/spec.md b/docs/specs/AST-009/spec.md
index a2b62ef01f..7fa836301f 100644
--- a/docs/specs/AST-009/spec.md
+++ b/docs/specs/AST-009/spec.md
@@ -18,6 +18,33 @@ affects_consumer_docs: []
# Assistive-technology verification system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "accessibility": [
+ "FR1",
+ "FR2",
+ "FR3",
+ "FR4",
+ "FR5",
+ "FR6",
+ "FR7",
+ "FR9",
+ "FR10",
+ "FR11",
+ "FR12",
+ "FR13",
+ "FR14",
+ "FR15",
+ "FR16"
+ ]
+ }
+}
+```
+
## Intent
People who depend on assistive technology should get the AT-specific focus and announcement outcome Astryx claims, not only plausible test-DOM markup. Astryx uses real AT/browser checks when that outcome depends on how AT exposes or announces focus, AT-specific focus order, announcement behavior, virtual-cursor entry, or a known AT/browser divergence.
diff --git a/docs/specs/AST-012/spec.md b/docs/specs/AST-012/spec.md
index fa585e9769..861eaee4ac 100644
--- a/docs/specs/AST-012/spec.md
+++ b/docs/specs/AST-012/spec.md
@@ -25,6 +25,17 @@ affects_consumer_docs: [theme, AppShell]
# Theme adaptations
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "theming": ["FR4", "FR5", "FR6", "FR7"]
+ }
+}
+```
+
## Intent
Themes should express opt-in token and component adaptations for environmental
diff --git a/docs/specs/AST-013/spec.md b/docs/specs/AST-013/spec.md
index afe2487617..8248f8a45b 100644
--- a/docs/specs/AST-013/spec.md
+++ b/docs/specs/AST-013/spec.md
@@ -19,6 +19,27 @@ affects_consumer_docs: [browser-support, useLayer, Popover, Toast, Dialog]
# Browser and platform support system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "platform": [
+ "FR1",
+ "FR3",
+ "FR5",
+ "FR6",
+ "FR7",
+ "FR8",
+ "FR9",
+ "FR10",
+ "FR12"
+ ]
+ }
+}
+```
+
## Intent
Give stable Astryx web components one owner for browser support, native-feature
diff --git a/docs/specs/AST-017/spec.md b/docs/specs/AST-017/spec.md
index bd9725728b..8f9155da98 100644
--- a/docs/specs/AST-017/spec.md
+++ b/docs/specs/AST-017/spec.md
@@ -19,6 +19,17 @@ affects_consumer_docs: [release-process, templates]
# Published compatibility and breaking-change classification system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "compatibility": ["DEC-1", "FR3", "FR4", "FR5", "FR12"]
+ }
+}
+```
+
## Intent
Give contributors and reviewers one rule for deciding whether a change is
diff --git a/docs/specs/AST-020/spec.md b/docs/specs/AST-020/spec.md
index c4d93176f8..68d0e3030b 100644
--- a/docs/specs/AST-020/spec.md
+++ b/docs/specs/AST-020/spec.md
@@ -18,6 +18,17 @@ affects_consumer_docs: []
# Accessibility spec-test authoring system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "accessibility": ["FR1", "FR2", "FR6"]
+ }
+}
+```
+
## Intent
People using Astryx components should get the keyboard, focus, meaning, and state
diff --git a/docs/specs/AST-025/spec.md b/docs/specs/AST-025/spec.md
index e56c16780f..2d2e9f70c7 100644
--- a/docs/specs/AST-025/spec.md
+++ b/docs/specs/AST-025/spec.md
@@ -20,6 +20,17 @@ affects_consumer_docs:
# Scrollable container behavior system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "scrolling": ["FR1", "FR12", "FR13", "FR14", "FR15", "FR16", "FR18"]
+ }
+}
+```
+
## Intent
People should be able to reach and scroll overflowing content, continue scrolling
diff --git a/docs/specs/AST-027/spec.md b/docs/specs/AST-027/spec.md
index 57fbf89384..6be6868a6e 100644
--- a/docs/specs/AST-027/spec.md
+++ b/docs/specs/AST-027/spec.md
@@ -19,6 +19,17 @@ affects_consumer_docs: []
# Local stacking and browser top-layer routing system spec
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "layering": ["DEC-1", "DEC-2", "DEC-3", "DEC-4", "FR11"]
+ }
+}
+```
+
## Intent
An Astryx component should be able to order its own painted parts without
diff --git a/docs/specs/AST-033/spec.md b/docs/specs/AST-033/spec.md
index cc6643cfb7..71e73d0a07 100644
--- a/docs/specs/AST-033/spec.md
+++ b/docs/specs/AST-033/spec.md
@@ -18,6 +18,17 @@ affects_consumer_docs: [docsite]
# Docsite interaction and product-data contract
+<!-- review-applicability:v1 -->
+
+```json
+{
+ "scope": "global",
+ "triggers": {
+ "docsite": ["DEC-1", "DEC-2", "DEC-3", "DEC-5", "FR3", "FR8", "FR13"]
+ }
+}
+```
+
## Intent
People using the Astryx Docsite should see truthful projections of the owning
diff --git a/scripts/check-knowledge.mjs b/scripts/check-knowledge.mjs
index d0b01c2401..3271b64829 100644
--- a/scripts/check-knowledge.mjs
+++ b/scripts/check-knowledge.mjs
@@ -4,6 +4,7 @@
import fs from 'node:fs';
import path from 'node:path';
import {execFileSync} from 'node:child_process';
+import {createHash} from 'node:crypto';
import {createRequire} from 'node:module';
import {fileURLToPath} from 'node:url';
import {collectThemingTargets} from '../packages/cli/foundation/discovery/theming-targets.mjs';
@@ -117,6 +118,353 @@ export function parseKnowledgeDocument(content, filePath = '<document>') {
return {frontmatter, sections, problems};
}
+const REVIEW_APPLICABILITY_MARKER = 'review-applicability:v1';
+export const GLOBAL_REVIEW_TRIGGERS = new Set([
+ 'accessibility',
+ 'behavior',
+ 'compatibility',
+ 'component-slots',
+ 'docsite',
+ 'interaction',
+ 'layering',
+ 'layout',
+ 'motion',
+ 'navigation',
+ 'platform',
+ 'public-api',
+ 'react-runtime',
+ 'responsive',
+ 'scrolling',
+ 'specification',
+ 'styling',
+ 'testing',
+ 'theming',
+ 'tokens',
+ 'visual',
+]);
+const REVIEW_TRIGGER_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
+const REVIEW_CLAIM_ID_PATTERN = /^[A-Z][A-Z0-9]*-?[0-9]+[a-z]?$/;
+
+function exactKeys(value, expected) {
+ return (
+ value != null &&
+ typeof value === 'object' &&
+ !Array.isArray(value) &&
+ Object.keys(value).sort().join('\0') === [...expected].sort().join('\0')
+ );
+}
+
+export function extractKnowledgeClaims(content) {
+ const claims = new Map();
+ const definitions = [
+ {
+ pattern:
+ /^\s*[-*]\s+\*\*([A-Z][A-Z0-9]*-?[0-9]+[a-z]?)\s+—\s+([\s\S]*?)\*\*/gm,
+ title: match => match[2].replace(/\s+/g, ' ').trim(),
+ },
+ {
+ pattern: /^#{2,6}\s+([A-Z][A-Z0-9]*-?[0-9]+[a-z]?)\s+—\s+(.+?)\s*$/gm,
+ title: match => match[2].trim(),
+ },
+ ];
+ for (const {pattern, title} of definitions) {
+ for (const match of content.matchAll(pattern)) {
+ if (!claims.has(match[1])) {
+ claims.set(match[1], title(match));
+ }
+ }
+ }
+
+ let levelTwoSection = null;
+ for (const line of content.split(/\r?\n/)) {
+ const heading = /^##\s+(.+?)\s*$/.exec(line);
+ if (heading) {
+ levelTwoSection = heading[1];
+ continue;
+ }
+ if (levelTwoSection !== 'Requirements') continue;
+ const row =
+ /^\|\s*([A-Z][A-Z0-9]*-?[0-9]+[a-z]?)\s*\|\s*([^|]+?)\s*\|/.exec(line);
+ if (row && !claims.has(row[1])) {
+ claims.set(row[1], row[2].replace(/\s+/g, ' ').trim());
+ }
+ }
+ return claims;
+}
+
+export function parseReviewApplicabilityBlock(
+ content,
+ filePath = '<knowledge record>',
+) {
+ const marker = /<!--\s*review-applicability:v1\s*-->/g;
+ const markers = [...content.matchAll(marker)];
+ if (markers.length === 0) return {config: null, problems: []};
+ if (markers.length > 1) {
+ return {
+ config: null,
+ problems: [
+ `${filePath}: duplicate ${REVIEW_APPLICABILITY_MARKER} blocks.`,
+ ],
+ };
+ }
+
+ const remainder = content.slice(markers[0].index + markers[0][0].length);
+ const block = /^\s*```json\s*\n([\s\S]*?)\n```/.exec(remainder);
+ if (!block) {
+ return {
+ config: null,
+ problems: [
+ `${filePath}: ${REVIEW_APPLICABILITY_MARKER} must be followed by one JSON code block.`,
+ ],
+ };
+ }
+
+ const propertyNames = [...block[1].matchAll(/"((?:\\.|[^"\\])*)"\s*:/g)].map(
+ match => JSON.parse(`"${match[1]}"`),
+ );
+ const duplicates = propertyNames.filter(
+ (name, index) => propertyNames.indexOf(name) !== index,
+ );
+ if (duplicates.length > 0) {
+ return {
+ config: null,
+ problems: [
+ `${filePath}: ${REVIEW_APPLICABILITY_MARKER} repeats JSON field ${JSON.stringify(duplicates[0])}.`,
+ ],
+ };
+ }
+
+ try {
+ return {config: JSON.parse(block[1]), problems: []};
+ } catch (error) {
+ return {
+ config: null,
+ problems: [
+ `${filePath}: ${REVIEW_APPLICABILITY_MARKER} is not valid JSON (${error.message}).`,
+ ],
+ };
+ }
+}
+
+export function validateReviewApplicability(
+ config,
+ content,
+ filePath = '<knowledge record>',
+) {
+ if (config == null) return [];
+ const problems = [];
+ if (!exactKeys(config, ['scope', 'triggers'])) {
+ return [
+ `${filePath}: ${REVIEW_APPLICABILITY_MARKER} requires exactly scope and triggers.`,
+ ];
+ }
+ if (config.scope !== 'global') {
+ problems.push(
+ `${filePath}: ${REVIEW_APPLICABILITY_MARKER} scope must be "global".`,
+ );
+ }
+ if (
+ config.triggers == null ||
+ typeof config.triggers !== 'object' ||
+ Array.isArray(config.triggers) ||
+ Object.keys(config.triggers).length === 0
+ ) {
+ problems.push(
+ `${filePath}: ${REVIEW_APPLICABILITY_MARKER} requires at least one trigger with explicit claims.`,
+ );
+ return problems;
+ }
+
+ const knownClaims = extractKnowledgeClaims(content);
+ const seenPairs = new Set();
+ for (const [trigger, claims] of Object.entries(config.triggers)) {
+ const where = `${filePath}: ${REVIEW_APPLICABILITY_MARKER} trigger ${JSON.stringify(trigger)}`;
+ if (!REVIEW_TRIGGER_PATTERN.test(trigger)) {
+ problems.push(`${where} must use lower-kebab-case.`);
+ } else if (!GLOBAL_REVIEW_TRIGGERS.has(trigger)) {
+ problems.push(`${where} is not a supported semantic trigger.`);
+ }
+ if (!Array.isArray(claims) || claims.length === 0) {
+ problems.push(`${where} requires a non-empty claim list.`);
+ continue;
+ }
+ for (const claimId of claims) {
+ if (
+ typeof claimId !== 'string' ||
+ !REVIEW_CLAIM_ID_PATTERN.test(claimId)
+ ) {
+ problems.push(
+ `${where} has malformed claim id ${JSON.stringify(claimId)}.`,
+ );
+ continue;
+ }
+ const pair = `${trigger}\0${claimId}`;
+ if (seenPairs.has(pair)) {
+ problems.push(`${where} repeats claim ${JSON.stringify(claimId)}.`);
+ continue;
+ }
+ seenPairs.add(pair);
+ if (!knownClaims.has(claimId)) {
+ problems.push(
+ `${where} references missing claim ${JSON.stringify(claimId)}.`,
+ );
+ }
+ }
+ }
+ return problems;
+}
+
+function isKnowledgeRecordPath(filePath) {
+ if (/^docs\/(?:architecture|design|families)\/[^/]+\.md$/.test(filePath)) {
+ return !filePath.endsWith('/README.md');
+ }
+ if (/^docs\/specs\/[^/]+\/(?:spec|plan)\.md$/.test(filePath)) {
+ return true;
+ }
+ const themeMatch = /^packages\/themes\/([^/]+)\/([^/]+)\.spec\.md$/.exec(
+ filePath,
+ );
+ if (themeMatch) return themeMatch[1] === themeMatch[2];
+ return isComponentSpecRecordPath(filePath);
+}
+
+export function collectGlobalReviewMatches(
+ records,
+ requestedTriggers,
+ authorityCommit,
+) {
+ const requested = [...new Set(requestedTriggers)].sort();
+ for (const trigger of requested) {
+ if (
+ !REVIEW_TRIGGER_PATTERN.test(trigger) ||
+ !GLOBAL_REVIEW_TRIGGERS.has(trigger)
+ ) {
+ throw new Error(`Invalid review trigger ${JSON.stringify(trigger)}.`);
+ }
+ }
+
+ const matches = [];
+ for (const record of records) {
+ const document = parseKnowledgeDocument(record.content, record.path);
+ const parsed = parseReviewApplicabilityBlock(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' ||
+ parsed.config?.scope !== 'global'
+ ) {
+ continue;
+ }
+
+ const recordId = document.frontmatter.get('id');
+ if (typeof recordId !== 'string' || recordId.length === 0) {
+ throw new Error(`${record.path}: a routed record requires an id.`);
+ }
+ const claims = extractKnowledgeClaims(record.content);
+ const recordDigest = createHash('sha256')
+ .update(record.content)
+ .digest('hex');
+ for (const trigger of requested) {
+ for (const claimId of parsed.config.triggers[trigger] ?? []) {
+ matches.push({
+ recordId,
+ path: record.path,
+ trigger,
+ claimId,
+ claim: claims.get(claimId),
+ matchReason: `Requested trigger ${JSON.stringify(trigger)} matched ${REVIEW_APPLICABILITY_MARKER} claim ${JSON.stringify(`${recordId}/${claimId}`)}.`,
+ authorityCommit,
+ recordDigest,
+ });
+ }
+ }
+ }
+ return matches.sort((left, right) =>
+ [left.recordId, left.path, left.trigger, left.claimId]
+ .join('\0')
+ .localeCompare(
+ [right.recordId, right.path, right.trigger, right.claimId].join('\0'),
+ ),
+ );
+}
+
+export function routeGlobalReviewBaselinesAtRevision(
+ root,
+ authorityCommit,
+ reviewHead,
+ requestedTriggers,
+) {
+ const resolvedCommit = execFileSync(
+ 'git',
+ ['-C', root, 'rev-parse', '--verify', `${authorityCommit}^{commit}`],
+ {encoding: 'utf8'},
+ ).trim();
+ if (resolvedCommit !== authorityCommit) {
+ throw new Error(
+ `authority commit must be the full resolved commit ${resolvedCommit}.`,
+ );
+ }
+ const resolvedHead = execFileSync(
+ 'git',
+ ['-C', root, 'rev-parse', '--verify', `${reviewHead}^{commit}`],
+ {encoding: 'utf8'},
+ ).trim();
+ if (resolvedHead !== reviewHead) {
+ throw new Error(
+ `review head must be the full resolved commit ${resolvedHead}.`,
+ );
+ }
+ const expectedBase = execFileSync(
+ 'git',
+ ['-C', root, 'merge-base', 'origin/main', resolvedHead],
+ {encoding: 'utf8'},
+ ).trim();
+ if (resolvedCommit !== expectedBase) {
+ throw new Error(
+ `authority commit must equal the review head's origin/main merge base ${expectedBase}.`,
+ );
+ }
+ const paths = execFileSync(
+ 'git',
+ [
+ '-C',
+ root,
+ 'ls-tree',
+ '-r',
+ '--name-only',
+ resolvedCommit,
+ '--',
+ 'docs/architecture',
+ 'docs/design',
+ 'docs/families',
+ 'docs/specs',
+ 'packages',
+ ],
+ {encoding: 'utf8'},
+ )
+ .split(/\r?\n/)
+ .filter(isKnowledgeRecordPath);
+ const records = paths.map(filePath => ({
+ path: filePath,
+ content: execFileSync(
+ 'git',
+ ['-C', root, 'show', `${resolvedCommit}:${filePath}`],
+ {encoding: 'utf8'},
+ ),
+ }));
+ return collectGlobalReviewMatches(records, requestedTriggers, resolvedCommit);
+}
+
function immediateDirectories(directory) {
if (!fs.existsSync(directory)) return [];
return fs
@@ -1286,6 +1634,18 @@ export async function validateKnowledgeRoot(root = DEFAULT_ROOT) {
const filePath = path.relative(root, absolutePath);
const content = fs.readFileSync(absolutePath, 'utf8');
const document = parseKnowledgeDocument(content, filePath);
+ const reviewApplicability = parseReviewApplicabilityBlock(
+ content,
+ filePath,
+ );
+ problems.push(
+ ...reviewApplicability.problems,
+ ...validateReviewApplicability(
+ reviewApplicability.config,
+ content,
+ filePath,
+ ),
+ );
const recordVersion = document.frontmatter.get('schema_version');
const versionedSchema = schemas.get(recordVersion);
if (!versionedSchema) {
diff --git a/scripts/check-knowledge.test.mjs b/scripts/check-knowledge.test.mjs
index 59d75f2543..6f66f019d3 100644
--- a/scripts/check-knowledge.test.mjs
+++ b/scripts/check-knowledge.test.mjs
@@ -3,15 +3,21 @@
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 {
composeKnowledgeSchemas,
+ collectGlobalReviewMatches,
discoverKnowledgeRecords,
+ extractKnowledgeClaims,
parseAnatomyThemingBlock,
parseKnowledgeDocument,
+ parseReviewApplicabilityBlock,
+ routeGlobalReviewBaselinesAtRevision,
validateAnatomyThemingMap,
validateDelegations,
validateKnowledgeRoot,
+ validateReviewApplicability,
validateSchemaEvolution,
} from './check-knowledge.mjs';
@@ -290,11 +296,295 @@ function writeButtonDoc(directory) {
return content;
}
+function reviewApplicabilityBlock(triggers, scope = 'global') {
+ return `<!-- review-applicability:v1 -->\n\`\`\`json\n${JSON.stringify(
+ {scope, triggers},
+ null,
+ 2,
+ )}\n\`\`\``;
+}
+
+function withReviewApplicability(record, triggers, scope = 'global') {
+ const lines = record.split('\n');
+ const titleIndex = lines.findIndex(line => line.startsWith('# '));
+ lines.splice(
+ titleIndex + 1,
+ 0,
+ '',
+ reviewApplicabilityBlock(triggers, scope),
+ );
+ return lines.join('\n');
+}
+
+function withSystemClaims(record) {
+ return record.replace(
+ '## Requirements\n\nBody.',
+ '## Requirements\n\n- **FR1 — Public API stays stable.** Callers keep the same contract.\n\n- **FR2 — Evidence stays scoped.** Tests prove only this claim.',
+ );
+}
+
+function commitFixture(root, message) {
+ execFileSync('git', ['init', '-q'], {cwd: root});
+ execFileSync('git', ['config', 'user.name', 'Fixture'], {cwd: root});
+ execFileSync('git', ['config', 'user.email', '[email protected]'], {
+ cwd: root,
+ });
+ execFileSync('git', ['add', '.'], {cwd: root});
+ execFileSync('git', ['commit', '-q', '-m', message], {cwd: root});
+ return execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: root,
+ encoding: 'utf8',
+ }).trim();
+}
+
afterEach(() => {
for (const root of roots.splice(0))
fs.rmSync(root, {recursive: true, force: true});
});
+describe('global review applicability', () => {
+ const currentRecord = withSystemClaims(systemSpecRecord());
+
+ it('parses explicit trigger-to-claim routing', () => {
+ const record = withReviewApplicability(currentRecord, {
+ 'public-api': ['FR1'],
+ testing: ['FR2'],
+ });
+ const parsed = parseReviewApplicabilityBlock(record);
+ expect(parsed.problems).toEqual([]);
+ expect(parsed.config).toEqual({
+ scope: 'global',
+ triggers: {'public-api': ['FR1'], testing: ['FR2']},
+ });
+ expect(extractKnowledgeClaims(record)).toEqual(
+ new Map([
+ ['FR1', 'Public API stays stable.'],
+ ['FR2', 'Evidence stays scoped.'],
+ ]),
+ );
+ expect(validateReviewApplicability(parsed.config, record)).toEqual([]);
+ });
+
+ it.each([
+ [
+ 'global routing without claims',
+ {scope: 'global', triggers: {'public-api': []}},
+ /non-empty claim list/,
+ ],
+ [
+ 'a stale claim reference',
+ {scope: 'global', triggers: {'public-api': ['FR99']}},
+ /references missing claim "FR99"/,
+ ],
+ [
+ 'a duplicate trigger and claim pair',
+ {scope: 'global', triggers: {'public-api': ['FR1', 'FR1']}},
+ /repeats claim "FR1"/,
+ ],
+ [
+ 'a malformed trigger',
+ {scope: 'global', triggers: {'Public API': ['FR1']}},
+ /must use lower-kebab-case/,
+ ],
+ [
+ 'an unsupported trigger',
+ {scope: 'global', triggers: {'unknown-area': ['FR1']}},
+ /is not a supported semantic trigger/,
+ ],
+ [
+ 'an unsupported scope',
+ {scope: 'component', triggers: {'public-api': ['FR1']}},
+ /scope must be "global"/,
+ ],
+ ])('rejects %s', (_name, config, expected) => {
+ expect(
+ validateReviewApplicability(config, currentRecord).join('\n'),
+ ).toMatch(expected);
+ });
+
+ it('rejects duplicate JSON object keys before parsing can overwrite them', () => {
+ const record = currentRecord.replace(
+ '# Fixture system spec',
+ '# Fixture system spec\n\n<!-- review-applicability:v1 -->\n```json\n{"scope":"global","triggers":{"public-api":["FR1"],"public-api":["FR2"]}}\n```',
+ );
+ expect(parseReviewApplicabilityBlock(record).problems.join('\n')).toMatch(
+ /repeats JSON field "public-api"/,
+ );
+ });
+
+ 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(
+ 'Public API stays stable.',
+ );
+ });
+
+ it('does not treat a verification-table reference as a claim definition', () => {
+ const record = withReviewApplicability(
+ `${currentRecord.replace(
+ '- **FR1 — Public API stays stable.** Callers keep the same contract.\n\n',
+ '',
+ )}\n| Contract | Verification |\n| --- | --- |\n| FR1 | A test file, not the claim. |\n`,
+ {'public-api': ['FR1']},
+ );
+ const parsed = parseReviewApplicabilityBlock(record);
+ expect(
+ validateReviewApplicability(parsed.config, record).join('\n'),
+ ).toMatch(/references missing claim "FR1"/);
+ });
+
+ it('keeps legacy records with no applicability block valid', async () => {
+ const root = fixtureRoot();
+ writeSystemSpec(root, 'AST-900', currentRecord);
+ expect(await validateKnowledgeRoot(root)).toEqual([]);
+ });
+
+ it('fails knowledge validation for malformed global routing', async () => {
+ const root = fixtureRoot();
+ writeSystemSpec(
+ root,
+ 'AST-900',
+ withReviewApplicability(currentRecord, {'public-api': ['FR99']}),
+ );
+ expect((await validateKnowledgeRoot(root)).join('\n')).toMatch(
+ /references missing claim "FR99"/,
+ );
+ });
+
+ it('routes only matching claims from current records', () => {
+ const record = withReviewApplicability(currentRecord, {
+ 'public-api': ['FR1'],
+ testing: ['FR2'],
+ });
+ const matches = collectGlobalReviewMatches(
+ [{path: 'docs/specs/AST-900/spec.md', content: record}],
+ ['public-api'],
+ 'a'.repeat(40),
+ );
+ expect(matches).toHaveLength(1);
+ expect(matches[0]).toMatchObject({
+ recordId: 'spec:AST-900',
+ path: 'docs/specs/AST-900/spec.md',
+ trigger: 'public-api',
+ claimId: 'FR1',
+ claim: 'Public API stays stable.',
+ authorityCommit: 'a'.repeat(40),
+ });
+ expect(matches[0].matchReason).toContain('public-api');
+ expect(matches[0].matchReason).toContain('spec:AST-900/FR1');
+ expect(matches[0].recordDigest).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ it('omits nonmatching and draft records', () => {
+ const current = withReviewApplicability(currentRecord, {
+ 'public-api': ['FR1'],
+ });
+ const draft = withReviewApplicability(
+ currentRecord.replace('authority: current', 'authority: draft'),
+ {testing: ['FR2']},
+ );
+ expect(
+ collectGlobalReviewMatches(
+ [
+ {path: 'docs/specs/AST-900/spec.md', content: current},
+ {path: 'docs/specs/AST-901/spec.md', content: draft},
+ ],
+ ['testing'],
+ 'b'.repeat(40),
+ ),
+ ).toEqual([]);
+ });
+
+ it('pins routing to the reviewed head base and rejects self-authorization', () => {
+ const root = fixtureRoot();
+ writeSystemSpec(root, 'AST-900', currentRecord);
+ const baseWithoutRouting = commitFixture(
+ root,
+ 'base without global routing',
+ );
+ execFileSync(
+ 'git',
+ ['update-ref', 'refs/remotes/origin/main', baseWithoutRouting],
+ {cwd: root},
+ );
+
+ fs.writeFileSync(
+ path.join(root, 'docs/specs/AST-900/spec.md'),
+ withReviewApplicability(currentRecord, {'public-api': ['FR1']}),
+ );
+ execFileSync('git', ['add', '.'], {cwd: root});
+ execFileSync('git', ['commit', '-q', '-m', 'head adds global routing'], {
+ cwd: root,
+ });
+ const proposedHead = execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: root,
+ encoding: 'utf8',
+ }).trim();
+
+ expect(
+ routeGlobalReviewBaselinesAtRevision(
+ root,
+ baseWithoutRouting,
+ proposedHead,
+ ['public-api'],
+ ),
+ ).toEqual([]);
+ expect(() =>
+ routeGlobalReviewBaselinesAtRevision(root, proposedHead, proposedHead, [
+ 'public-api',
+ ]),
+ ).toThrow(/origin\/main merge base/);
+
+ execFileSync(
+ 'git',
+ ['update-ref', 'refs/remotes/origin/main', proposedHead],
+ {
+ cwd: root,
+ },
+ );
+ fs.writeFileSync(path.join(root, 'README.md'), '# Reviewed change\n');
+ execFileSync('git', ['add', '.'], {cwd: root});
+ execFileSync('git', ['commit', '-q', '-m', 'later review head'], {
+ cwd: root,
+ });
+ const laterHead = execFileSync('git', ['rev-parse', 'HEAD'], {
+ cwd: root,
+ encoding: 'utf8',
+ }).trim();
+ expect(
+ routeGlobalReviewBaselinesAtRevision(root, proposedHead, laterHead, [
+ 'public-api',
+ ]),
+ ).toHaveLength(1);
+ });
+
+ it('sorts multiple matches deterministically', () => {
+ const first = withReviewApplicability(
+ withSystemClaims(systemSpecRecord({id: 'spec:AST-902'})),
+ {testing: ['FR2'], 'public-api': ['FR1']},
+ );
+ const second = withReviewApplicability(
+ withSystemClaims(systemSpecRecord({id: 'spec:AST-901'})),
+ {'public-api': ['FR1']},
+ );
+ const matches = collectGlobalReviewMatches(
+ [
+ {path: 'docs/specs/AST-902/spec.md', content: first},
+ {path: 'docs/specs/AST-901/spec.md', content: second},
+ ],
+ ['testing', 'public-api'],
+ 'c'.repeat(40),
+ );
+ expect(
+ matches.map(row => `${row.recordId}:${row.trigger}:${row.claimId}`),
+ ).toEqual([
+ 'spec:AST-901:public-api:FR1',
+ 'spec:AST-902:public-api:FR1',
+ 'spec:AST-902:testing:FR2',
+ ]);
+ });
+});
+
describe('schema evolution', () => {
it('tracks latest schema versions per kind', () => {
const raw = new Map([
diff --git a/scripts/review-global-baselines.mjs b/scripts/review-global-baselines.mjs
new file mode 100644
index 0000000000..a370eec6e7
--- /dev/null
+++ b/scripts/review-global-baselines.mjs
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/* global console, process */
+import path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {routeGlobalReviewBaselinesAtRevision} from './check-knowledge.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const DEFAULT_ROOT = path.resolve(HERE, '..');
+
+function valueFor(flag) {
+ const index = process.argv.indexOf(flag);
+ if (index === -1) return null;
+ const value = process.argv[index + 1];
+ if (!value || value.startsWith('--')) {
+ throw new Error(`${flag} requires a value.`);
+ }
+ return value;
+}
+
+const root = path.resolve(valueFor('--root') ?? DEFAULT_ROOT);
+const authorityCommit = valueFor('--authority-commit');
+const reviewHead = valueFor('--review-head');
+const triggerValue = valueFor('--triggers');
+
+if (!authorityCommit) {
+ throw new Error(
+ '--authority-commit requires the full base authority commit.',
+ );
+}
+if (!/^[0-9a-f]{40}$/.test(authorityCommit)) {
+ throw new Error(
+ '--authority-commit must be a full 40-character commit hash.',
+ );
+}
+if (!reviewHead) {
+ throw new Error('--review-head requires the full reviewed commit.');
+}
+if (!/^[0-9a-f]{40}$/.test(reviewHead)) {
+ throw new Error('--review-head must be a full 40-character commit hash.');
+}
+if (!triggerValue) {
+ throw new Error('--triggers requires a comma-separated trigger list.');
+}
+
+const requestedTriggers = triggerValue
+ .split(',')
+ .map(value => value.trim())
+ .filter(Boolean);
+if (requestedTriggers.length === 0) {
+ throw new Error('--triggers requires at least one trigger.');
+}
+
+const matches = routeGlobalReviewBaselinesAtRevision(
+ root,
+ authorityCommit,
+ reviewHead,
+ requestedTriggers,
+);
+console.log(
+ JSON.stringify(
+ {
+ schemaVersion: 1,
+ authorityCommit,
+ reviewHead,
+ requestedTriggers: [...new Set(requestedTriggers)].sort(),
+ matches,
+ },
+ null,
+ 2,
+ ),
+);