Skip to content

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

TypeScript

fix(release): admit proven test repairs (#10850)

Cindy Zhang18f7f84f07d7
diff --git a/.github/actions/test-scope/action.yml b/.github/actions/test-scope/action.yml
index 34186bc9a1..b320c74629 100644
--- a/.github/actions/test-scope/action.yml
+++ b/.github/actions/test-scope/action.yml
@@ -17,8 +17,9 @@
# classifier, an API error, an empty file list or one GitHub truncates)
# puts everything in scope (spec:AST-030 FR3, FR4). A classifier that rejects the change (a spec-only PR with a
# Changeset) fails the step, as the old scope job failed its dependents.
-# - A release-branch pull request is the generated version bump: spec-only and
-# tooling-only, with `release_bump` true.
+# - A release-branch generated bump keeps its narrow lane. Any other candidate
+# runs every test lane; the trusted release validator then admits only the
+# proven test-repair class and rejects every broader change.
#
# The job must be checked out first: this is a local action.
@@ -86,7 +87,7 @@ outputs:
classifier predates it reports nothing, which runs every test.
value: ${{ steps.scope.outputs.vitest_full_suite }}
release_bump:
- description: The PR targets a release branch (the generated version bump).
+ description: The PR targets a release branch and must pass release validation.
value: ${{ steps.scope.outputs.release_bump }}
decided:
description: >-
@@ -190,6 +191,21 @@ runs:
for (const [key, value] of Object.entries(values)) core.setOutput(key, value);
core.info(Object.entries(values).map(([k, v]) => `${k}=${v}`).join(' '));
};
+ const writeChangedFiles = files => {
+ const changedFilesPath = path.join(
+ process.env.RUNNER_TEMP || os.tmpdir(),
+ 'test-scope-changed-files.txt',
+ );
+ const changed = [
+ ...new Set(
+ files.flatMap(file =>
+ [file.filename, file.previous_filename].filter(Boolean),
+ ),
+ ),
+ ];
+ fs.writeFileSync(changedFilesPath, `${changed.join('\n')}\n`);
+ return changedFilesPath;
+ };
if (context.eventName !== 'pull_request') {
core.info(`${context.eventName}: not a pull request, so everything is in scope.`);
@@ -197,20 +213,6 @@ runs:
return;
}
const pr = context.payload.pull_request;
- if (pr.base.ref.startsWith('release/v')) {
- core.info('Release-branch pull request: the generated version bump.');
- report({
- ...everything,
- ...(audit ? auditNone : {}),
- spec_only: 'true',
- tooling_only: 'true',
- release_bump: 'true',
- touches: 'false',
- applies: 'false',
- });
- return;
- }
-
let files;
let root;
// The base's policy files are copied to a temporary folder that
@@ -233,6 +235,9 @@ runs:
'.github/scripts/change-scope.cjs',
'.github/scripts/knowledge-paths.cjs',
'scripts/component-packages.cjs',
+ ...(pr.base.ref.startsWith('release/v')
+ ? ['scripts/release/release-paths.mjs']
+ : []),
...(audit ? ['.github/scripts/component-audit-scope.cjs'] : []),
// Data, not code: the Lab entry check reads the base's copy.
'packages/cli/assets/discover/official-packages.json',
@@ -258,6 +263,7 @@ runs:
core.warning(`Scope could not be decided (${error.message}); everything is in scope.`);
report({
...everything,
+ release_bump: String(pr.base.ref.startsWith('release/v')),
decided: 'false',
truncated: String(/truncated the file list/.test(error.message)),
});
@@ -270,6 +276,40 @@ runs:
? `R100\t${f.previous_filename}\t${f.filename}`
: `${STATUS[f.status] ?? 'M'}\t${f.filename}`)
.join('\n');
+
+ if (pr.base.ref.startsWith('release/v')) {
+ const releaseKind = execFileSync(
+ 'node',
+ [
+ path.join(root, 'scripts/release/release-paths.mjs'),
+ '--classify',
+ ],
+ {encoding: 'utf8', input: `${nameStatus}\n`},
+ ).trim();
+ if (releaseKind === 'version-bump') {
+ core.info('Release-branch pull request: the generated version bump.');
+ report({
+ ...everything,
+ ...(audit ? auditNone : {}),
+ spec_only: 'true',
+ tooling_only: 'true',
+ release_bump: 'true',
+ touches: 'false',
+ applies: 'false',
+ });
+ } else {
+ core.info(
+ `Release-branch ${releaseKind} candidate: every test lane runs; the release validator decides whether the change is allowed.`,
+ );
+ report({
+ ...everything,
+ ...(audit ? auditAll : {}),
+ release_bump: 'true',
+ changed_files_path: writeChangedFiles(files),
+ });
+ }
+ return;
+ }
const outputFile = path.join(root, 'classification');
fs.writeFileSync(outputFile, '');
// GitHub's patch text for the Lab entry files, handed over as data:
@@ -363,12 +403,7 @@ runs:
componentScope = auditAll;
}
}
- // A file, not an output value: a large pull request's list would
- // not fit an environment variable.
- const changedFilesPath = path.join(process.env.RUNNER_TEMP || os.tmpdir(), 'test-scope-changed-files.txt');
- const changed = [...new Set(files.flatMap(f => [f.filename, f.previous_filename].filter(Boolean)))];
- fs.writeFileSync(changedFilesPath, `${changed.join('\n')}\n`);
- componentScope.changed_files_path = changedFilesPath;
+ componentScope.changed_files_path = writeChangedFiles(files);
}
report({...everything, ...classified, ...componentScope, release_bump: 'false', touches, applies, head_file_present: headFilePresent, lab_specs_path: labSpecsPath});
} finally {
diff --git a/.github/scripts/release-publish-workflow.test.mjs b/.github/scripts/release-publish-workflow.test.mjs
index e3988fba94..31058eab71 100644
--- a/.github/scripts/release-publish-workflow.test.mjs
+++ b/.github/scripts/release-publish-workflow.test.mjs
@@ -842,6 +842,7 @@ describe('stable and canary publication authority', () => {
);
for (const command of [
'git show origin/main:scripts/release/active-release.mjs',
+ 'git show origin/main:scripts/release/release-paths.mjs',
'git show origin/main:scripts/lib/workspace-globs.mjs',
'validate-merge-back',
'--base HEAD^1',
diff --git a/.github/scripts/test-scope-action.test.mjs b/.github/scripts/test-scope-action.test.mjs
index afd4d8565e..7e387277d1 100644
--- a/.github/scripts/test-scope-action.test.mjs
+++ b/.github/scripts/test-scope-action.test.mjs
@@ -40,6 +40,7 @@ const CLASSIFIER_FILES = new Set([
'.github/scripts/knowledge-paths.cjs',
'scripts/component-packages.cjs',
]);
+const RELEASE_PATHS_FILE = 'scripts/release/release-paths.mjs';
const AUDIT_FILE = '.github/scripts/component-audit-scope.cjs';
const OFFICIAL_PACKAGES = 'packages/cli/assets/discover/official-packages.json';
@@ -104,6 +105,7 @@ async function decide({
contentCalls.push({file, ref});
const known =
CLASSIFIER_FILES.has(file) ||
+ file === RELEASE_PATHS_FILE ||
file === AUDIT_FILE ||
file === OFFICIAL_PACKAGES;
const text = ref === BASE_SHA && known ? policyText(file) : null;
@@ -206,9 +208,16 @@ describe('per-job scope step', () => {
expect(skipped.outputs.applies).toBe('false');
});
- it('marks a release-branch pull request as the generated version bump', async () => {
+ it('keeps a generated release-branch pull request on the narrow bump lane', async () => {
const {outputs} = await decide({
context: pullRequestContext('release/v1.2.3'),
+ files: changed(
+ '.changeset/frozen.md',
+ 'packages/core/CHANGELOG.md',
+ 'packages/core/package.json',
+ 'packages/cli/assets/codemods/__tests__/registry.test.mjs',
+ 'packages/cli/assets/codemods/transforms/v1.2.3/__tests__/upgrade.test.mjs',
+ ),
});
expect(outputs).toMatchObject({
release_bump: 'true',
@@ -218,6 +227,55 @@ describe('per-job scope step', () => {
});
});
+ it('runs every lane for a release-branch test-repair candidate', async () => {
+ const {outputs} = await decide({
+ context: pullRequestContext('release/v1.2.3'),
+ files: changed(
+ 'packages/core/src/BottomSheet/__tests__/BottomSheetRelease.a11y.chromium.spec.ts',
+ ),
+ inputs: {'component-audit': 'true'},
+ });
+ expect(outputs).toMatchObject({
+ release_bump: 'true',
+ spec_only: 'false',
+ tooling_only: 'false',
+ full_suite: 'true',
+ vitest_full_suite: 'true',
+ has_components: 'true',
+ force_full_component_audits: 'true',
+ applies: 'true',
+ });
+ expect(fs.readFileSync(outputs.changed_files_path, 'utf8')).toBe(
+ 'packages/core/src/BottomSheet/__tests__/BottomSheetRelease.a11y.chromium.spec.ts\n',
+ );
+ });
+
+ it.each([
+ ['an empty file list', []],
+ ['an API failure', new Error('unavailable')],
+ [
+ 'a truncated file list',
+ Array.from({length: 3000}, (_, index) => ({
+ filename: `packages/core/src/Test${index}.test.ts`,
+ status: 'modified',
+ })),
+ ],
+ ])('runs every lane when release scope has %s', async (_, files) => {
+ const {outputs} = await decide({
+ context: pullRequestContext('release/v1.2.3'),
+ files,
+ inputs: {'component-audit': 'true'},
+ });
+ expect(outputs).toMatchObject({
+ release_bump: 'true',
+ decided: 'false',
+ full_suite: 'true',
+ vitest_full_suite: 'true',
+ force_full_component_audits: 'true',
+ applies: 'true',
+ });
+ });
+
it('classifies the PR file list with the classifier read from the base commit', async () => {
const {outputs, contentCalls} = await decide({
files: changed('packages/core/src/Button/Button.tsx'),
@@ -598,9 +656,14 @@ describe('per-job scope step', () => {
expect(contentCalls).toContainEqual({file: AUDIT_FILE, ref: BASE_SHA});
});
- it('applies no audit to a release-branch pull request', async () => {
+ it('applies no audit to the generated release-branch pull request', async () => {
const {outputs} = await decide({
context: pullRequestContext('release/v1.2.3'),
+ files: changed(
+ '.changeset/frozen.md',
+ 'packages/core/CHANGELOG.md',
+ 'packages/core/package.json',
+ ),
inputs,
});
expect(outputs).toMatchObject({
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 189418cd14..86758b3c3b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -302,6 +302,8 @@ jobs:
mkdir -p "$TRUSTED_POLICY/scripts/release" "$TRUSTED_POLICY/scripts/lib"
git show "origin/$RELEASE_BRANCH:scripts/release/active-release.mjs" \
> "$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ git show "origin/$RELEASE_BRANCH:scripts/release/release-paths.mjs" \
+ > "$TRUSTED_POLICY/scripts/release/release-paths.mjs"
git show "origin/$RELEASE_BRANCH:scripts/lib/workspace-globs.mjs" \
> "$TRUSTED_POLICY/scripts/lib/workspace-globs.mjs"
VALIDATOR="$TRUSTED_POLICY/scripts/release/active-release.mjs"
@@ -372,26 +374,30 @@ jobs:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
- - name: Fetch release refs, base, and trusted release policy
+ - name: Fetch release refs, base, main, and trusted release policy
run: |
git fetch origin '+refs/heads/release/v*:refs/remotes/origin/release/v*'
- git fetch origin "${{ github.base_ref }}" --depth=50
+ git fetch origin "${{ github.base_ref }}" --depth=200
+ git fetch origin 'main:refs/remotes/origin/main'
TRUSTED_POLICY="$RUNNER_TEMP/release-policy"
mkdir -p "$TRUSTED_POLICY/scripts/release" "$TRUSTED_POLICY/scripts/lib"
git show "origin/${{ github.base_ref }}:scripts/release/active-release.mjs" \
> "$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ git show "origin/${{ github.base_ref }}:scripts/release/release-paths.mjs" \
+ > "$TRUSTED_POLICY/scripts/release/release-paths.mjs"
git show "origin/${{ github.base_ref }}:scripts/lib/workspace-globs.mjs" \
> "$TRUSTED_POLICY/scripts/lib/workspace-globs.mjs"
- name: Setup Node and pnpm
uses: ./.github/actions/setup
- - name: Require generated-only release bookkeeping
+ - name: Require generated release bookkeeping or a proven test repair
run: |
node "$RUNNER_TEMP/release-policy/scripts/release/active-release.mjs" validate-diff \
--root "$GITHUB_WORKSPACE" \
--base "origin/${{ github.base_ref }}" \
- --head "${{ github.event.pull_request.head.sha }}"
+ --head "${{ github.event.pull_request.head.sha }}" \
+ --main-ref origin/main
- name: Validate branch, head, plan, versions, and Changeset consumption
run: |
@@ -471,6 +477,8 @@ jobs:
mkdir -p "$TRUSTED_POLICY/scripts/release" "$TRUSTED_POLICY/scripts/lib"
git show origin/main:scripts/release/active-release.mjs \
> "$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ git show origin/main:scripts/release/release-paths.mjs \
+ > "$TRUSTED_POLICY/scripts/release/release-paths.mjs"
git show origin/main:scripts/lib/workspace-globs.mjs \
> "$TRUSTED_POLICY/scripts/lib/workspace-globs.mjs"
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 36ba54d7b8..f59d8e5c3b 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -209,6 +209,8 @@ jobs:
mkdir -p "$TRUSTED_POLICY/scripts/release" "$TRUSTED_POLICY/scripts/lib"
git show origin/main:scripts/release/active-release.mjs \
> "$TRUSTED_POLICY/scripts/release/active-release.mjs"
+ git show origin/main:scripts/release/release-paths.mjs \
+ > "$TRUSTED_POLICY/scripts/release/release-paths.mjs"
git show origin/main:scripts/lib/workspace-globs.mjs \
> "$TRUSTED_POLICY/scripts/lib/workspace-globs.mjs"
VALIDATOR="$TRUSTED_POLICY/scripts/release/active-release.mjs"
diff --git a/docs/release.md b/docs/release.md
index 42685b3dda..241ea0a60b 100644
--- a/docs/release.md
+++ b/docs/release.md
@@ -39,6 +39,28 @@ stable package is built from an immutable release tag and published with provena
the same way. Then merge the generated PR to the release branch, run exact-head
branch CI, and tag and publish that exact branch head. Stable publication from
`main` is refused.
+
+ After that generated PR, the branch admits one additional class only when its
+ exact gate exposes a test or harness defect: one commit whose stable patch id
+ and exact changed-line digest equal a non-merge commit still present in `main`,
+ and whose changed files are only non-docsite tests or `internal/interaction-harness/`. It
+ may not change product code, packages, Changesets, assertions, test controls,
+ timeouts, retries, or snapshots. The rule that admits it must first land on
+ `main` through normal review and CI. If the active branch predates that rule,
+ the release owner appends one normal fast-forward policy sync after
+ `validate-policy-carry` proves that the policy-only file set and resulting
+ contents exactly equal the branch-specific bundle reviewed in the validator
+ commit already merged on `main`. The bundle starts from the active release
+ head. It carries this validator and scope change plus the existing
+ undecided-scope contract fallback that treats every file as changed when
+ GitHub truncates the file list; it carries no other later `main` workflow or
+ product work. The sync is not
+ a pull request, uses no force or admin operation, marks no check, and grants no release state. The repair branch then rebases onto the new release
+ head, and its required checks run under that trusted base. The repair itself needs exact-head CodeBunny approval and every normal product
+ and test lane; after merge, the full exact-head release gate runs again and
+ must pass. No retry, skipped check, admin merge, or manual override replaces
+ these proofs.
+
5. Squash the published branch outputs back into current `main` through
`chore/merge-vX.Y.Z-to-main`. The trusted validator requires the immutable tag,
active branch head, and plan digest; exact generated bytes and frozen deletions;
diff --git a/docs/specs/AST-017/spec.md b/docs/specs/AST-017/spec.md
index 29a6d44ab1..d7c6987657 100644
--- a/docs/specs/AST-017/spec.md
+++ b/docs/specs/AST-017/spec.md
@@ -109,7 +109,9 @@ affects_consumer_docs: [release-process, templates]
"DEC-26",
"DEC-27",
"DEC-28",
- "DEC-30"
+ "DEC-30",
+ "FR61",
+ "DEC-32"
]
}
}
@@ -801,6 +803,30 @@ one removal merged ahead of the decision to allow it.
items, and controls like Button, Switch, and CheckboxInput, keep the strict
budget, at rest and pressed. Anything beyond this needs an owner exception
with before and after counts.
+- **FR61 — A release branch admits only a proven test repair after its generated bump.**
+ When an exact release-branch gate finds a test or harness defect after the generated
+ version pull request has merged, one repair commit may move that branch only when its
+ stable patch id and exact changed-line digest equal one non-merge commit still present
+ in current `main`. Every changed path is a test under `__tests__`, a `*.spec.*` or
+ `*.test.*` file, or the interaction harness; docsite paths and snapshots are excluded. The repair
+ changes no package, product, Changeset, assertion, test control, timeout, retry, or
+ snapshot. The validator that recognizes this class first lands on `main` through
+ ordinary review and green CI, then judges the release pull request from its trusted
+ base. If an active release branch predates that validator, the release owner appends
+ one normal fast-forward policy synchronization commit after `validate-policy-carry`
+ proves that its policy-only file set and resulting file contents exactly equal the
+ branch-specific bundle reviewed in the validator commit already merged on `main`. The
+ bundle is based on the active release head. It carries this validator and scope change
+ plus the existing undecided-scope contract fallback that treats every file as changed
+ when GitHub truncates the file list; it carries no other later `main` workflow or
+ product work. This sync is not a pull request, uses no force or admin operation, marks no check, grants no release state, and changes no
+ package, product, Changeset, or release output. The repair branch rebases onto it, so
+ every required check runs under the new trusted base before the repair can merge. The
+ repair receives CodeBunny approval at its exact
+ head and every normal product and test lane runs and passes. After it merges, the full
+ exact-head release gate runs again and must pass before tagging or publication. A
+ retry, skipped check, admin merge, or manual override cannot substitute for any proof
+ in this rule.
### Platform support
@@ -955,6 +981,7 @@ lands, maintainers apply its requirement in review and release approval.
| FR54 | Changeset classification review against the surface's current record, then the same tier admission every Changeset receives | a CLI correction the CLI record classifies as `[fix]`; a CLI change the CLI record leaves undecided; a CLI change the CLI record classifies as `[breaking]` on a patch plan; a component change | A non-component change is classified by a rule this record restates instead of its surface record, a surface rule turns on risk or adoption, a surface-classified `[breaking]` change ships in a patch or a surface rule makes it patch-eligible, or a component change is classified by a surface record |
| FR59 | Pull request review of fine-pointer before-and-after evidence | a touch change that also fixes a defect fine-pointer users hit; a deliberate cross-device consistency change; a touch-only change; a new fine-pointer look proposed with touch work | A touch change alters fine-pointer behavior or appearance with neither reason, shows no fine-pointer before-and-after evidence, or ships a new fine-pointer look without its own owner decision |
| FR60 | Element counts per story at rest and open, fine and coarse pointer, against architecture INV7 | a surface component at rest; an open layer; a DOM reduction; a recorded exception; an open layer under touch with extra elements | An element beyond INV7's budgets with no recorded owner exception, a hidden twin or second presentation, or a DOM reduction that removes a theme target or documented anatomy, or that is classified as breaking; an open layer more than 5 elements over its fine-pointer count, an added element that is themeable, a new anatomy part, or without a job in its record, or a closed layer, trigger, or repeated component above its fine-pointer count |
+| FR61 | Release-validator, policy-carry, and scope-routing fixtures; one exact test port; exact-head CodeBunny/CI; then the full release gate | one non-merge test commit still present on main; stable patch id equal but changed-line digest different; reverted source; product, package, Changeset, snapshot, assertion, test-control, timeout or retry edits; multiple commits; unauthorized policy-carry path; undecidable file list | A broader change enters the release branch, the carried policy differs from its reviewed main commit, the repair runs a narrow lane, a repeated or waived gate substitutes for proof, or tagging starts before the new exact head passes the full release gate |
| FR3 | Current component contract, latest-stable inspection, and coarse/non-coarse browser evidence | Auxiliary numeric steppers hidden with accessible direct entry and keyboard stepping retained; lost entry path; removed public prop or essential action | A qualifying numeric-stepper adaptation is labeled breaking, or the narrow rule is used to excuse a lost API, essential action, value/validation/callback contract, or accessible entry path |
## Decision log
@@ -1504,6 +1531,24 @@ publication never waits for a canary.
Rejected: a canary for every commit that reaches main.
+### DEC-32 — Post-bump release repairs prove that they are test-only ports
+
+**Reference:** `spec:AST-017/DEC-32`
+**Decider:** the Chief with the release owner, `2026-11-09`
+
+A release gate can expose a defect in its own test after the generated version pull
+request has merged. Recutting from a newer `main` can add unrelated or undecided
+product work, while accepting the red result would waive a release gate. The branch
+therefore admits the narrow FR61 class: one test-only patch still present on `main`,
+proved by patch id, exact changed-line digest, and explicit content limits. A branch
+that predates the rule first receives the branch-specific reviewed policy bundle
+through the validated policy-only carry. The repair is then reviewed and tested normally before
+a new full exact-head release gate.
+
+Rejected: another unchanged retry, accepting a named flake, copying an unreviewed
+patch, allowing product or release-output changes in the repair, or merging around a
+required check.
+
## Open questions
None.
diff --git a/docs/specs/AST-030/spec.md b/docs/specs/AST-030/spec.md
index af9f1f5fef..b743faaad5 100644
--- a/docs/specs/AST-030/spec.md
+++ b/docs/specs/AST-030/spec.md
@@ -24,7 +24,7 @@ affects_consumer_docs: []
{
"scope": "global",
"triggers": {
- "testing": ["FR7", "FR11"]
+ "testing": ["FR7", "FR11", "FR30"]
}
}
```
@@ -609,6 +609,15 @@ they are separately named.
release tooling. Such pull requests stay non-mergeable, and this widens the
scope of no other pull request (DEC-24).
- **FR29 — A stable contribution runs CI without a maintainer.** A stable contribution from a fork runs CI without a maintainer. An automated job starts CI for a fork pull request without `ci:run` (a branch in another repository, so CI doesn't run on its pushes under FR17) when all of these hold: it isn't a draft; its CLA check passes; its head has had no push for 4 hours; the review bot's (`astracat-bot[bot]`) review at that exact head is APPROVED, or COMMENTED with no finding the review marks as blocking (its body or inline comments contain "**Blocking", "Requesting changes" or "Changes requested"); CHANGES_REQUESTED, or no review at the head, never counts; the link guard passes (merge-guard's `external-links` status at the head is success or absent, and the pull request has no `needs-human:external-link` label); GitHub doesn't report it as conflicting with its base; its last push is no more than 30 days old; and it changes no workflow or CI path (`.github/**`, CI scripts). To start the run, the job adds `ci:run` and marks the pull request draft and then ready again, so the ready event starts a run at that exact head (FR17). The same ready event re-requests a human reviewer whose latest review requested changes, as a maintainer's own toggle does. Once the run has started it removes the label, but only when the latest `ci:run` label event is its own, so a later push runs nothing until it is vetted again. The job starts a head at most once, and a new head becomes eligible when it meets the same conditions. It starts a run only when the capacity tool has no release-check or main-break waiter queued in the capacity tool, and room for one more pull-request run under the CI job ceiling, at most one start per sweep, in a contributor class with its own daily runner-minute budget set by the owner, first in, first out by how long each head has been stable; the run is then admitted under FR16 like any pull request run. A daily report shows the minutes used against the budget, flags eligible heads that waited more than 2 days, and lists eligible-but-stale heads (over 30 days since the last push) for triage as needing a rebase. A maintainer can still start CI by hand: `ci:run` with a draft-and-ready toggle, a push, or a reopen runs it outside the stability conditions and the contributor budget, admitted under FR16; the automated job never removes or re-adds a label a maintainer set. (DEC-26)
+- **FR30 — A non-generated release-branch candidate runs broad CI.** The
+ generated version pull request keeps its narrow bookkeeping lane only when
+ every changed path is one of its generated outputs. Any other pull request to
+ a `release/v*` base runs every normal product and test lane and still requires
+ the `release-bump` context. That context applies the trusted base branch's
+ release validator and may admit only the release test-repair class that
+ `spec:AST-017/FR61` defines. An empty, unavailable, or truncated file list
+ also runs broad CI and records undecided scope; uncertainty never grants the
+ generated lane.
### Platform support
@@ -693,6 +702,7 @@ The nightly perf lane is the one scheduled measurement outside them (FR18).
| FR29 | the contributor CI job's rule tests and its dry-run report | A branch in this repository, or a fork pull request that already carries `ci:run`, is never started by the job (CI already runs on its pushes) | the job starts it |
| FR29 | the contributor CI job's rule tests and its dry-run report | A contributor head while a release-check or main-break waiter is queued in the capacity tool, or without room for one more pull-request run under the CI job ceiling, does not start; at most one starts per sweep | it starts, or more than one starts in a sweep |
| FR29 | the contributor CI job's rule tests and its dry-run report | Of two eligible heads, the one stable longer starts first | the one stable for less time starts first |
+| FR30 | `test-scope-action.test.mjs` release-branch cases and the required release-validator contract | generated outputs only; one test-repair path; mixed or product paths; empty, failed, and truncated file lists | a non-generated release candidate gets the narrow lane, uncertainty skips broad CI, or the required release validator disappears |
## Decision log
@@ -1253,6 +1263,20 @@ four times a day).
The owner asked for "some system that will activate ci:run on contribution PRs that are stable", "Or we have some contrib lane that runs off a budget", and "plus ci:run to override?" (FR29). She approved the budget with "Ok 600": The owner set the budget at 600 runner-minutes per UTC day; unused minutes don't carry over.
+### DEC-27 — A release test repair runs every ordinary pull-request lane
+
+**Reference:** `spec:AST-030/DEC-27`
+**Decider:** the Chief with the release owner, `2026-11-09`
+
+The generated release pull request is the only release-branch change that gets
+its narrow bookkeeping lane. A later test-repair candidate runs broad CI while
+the trusted release validator proves the narrower admission rule (FR30 and
+`spec:AST-017/FR61`). This makes a green required check evidence of the amended
+rule, not a skipped or manually overridden check.
+
+Rejected: treating every release-branch pull request as generated, or letting
+the head branch choose its own scope or validator.
+
## Open questions
None.
diff --git a/scripts/release/active-release.mjs b/scripts/release/active-release.mjs
index 7eae88e71b..02d05a4b35 100644
--- a/scripts/release/active-release.mjs
+++ b/scripts/release/active-release.mjs
@@ -11,16 +11,23 @@
* @output fail-closed receipts plus the cut-time release description frozen in the plan digest
* @position single authority used by release CI, stable publishing, and branch cleanup
*
- * CI copies this file and lib/workspace-globs.mjs alone as trusted policy, so
- * it imports nothing else at module load.
+ * CI copies this file, release-paths.mjs, and lib/workspace-globs.mjs as
+ * trusted policy.
*/
import crypto from 'node:crypto';
import fs from 'node:fs';
+import os from 'node:os';
import path from 'node:path';
import {execFileSync} from 'node:child_process';
import {fileURLToPath} from 'node:url';
import {expandWorkspaceDirs} from '../lib/workspace-globs.mjs';
+import {
+ classifyReleaseDiff,
+ diffEntryFiles,
+ isReleaseOutputPath,
+ isReleaseTestRepairPath,
+} from './release-paths.mjs';
const ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -360,8 +367,12 @@ function validateReleaseState({
return errors;
}
+function gitRaw(root, args) {
+ return execFileSync('git', args, {cwd: root, encoding: 'utf8'});
+}
+
function git(root, args) {
- return execFileSync('git', args, {cwd: root, encoding: 'utf8'}).trim();
+ return gitRaw(root, args).trim();
}
/** The highest local stable vX.Y.Z tag, or null when none exists. */
@@ -706,17 +717,522 @@ function listActiveBranches(root) {
return active.sort();
}
-const RELEASE_OUTPUT_PATTERNS = [
- /^packages\/(?:[^/]+|themes\/[^/]+)\/package\.json$/,
- /^packages\/(?:[^/]+|themes\/[^/]+)\/CHANGELOG\.md$/,
- /^packages\/cli\/assets\/codemods\/registry\.mjs$/,
- /^packages\/cli\/assets\/codemods\/__tests__\/registry\.test\.mjs$/,
- /^packages\/cli\/assets\/codemods\/transforms\/(?:next|v\d+\.\d+\.\d+)\//,
- /^pnpm-lock\.yaml$/,
+const RELEASE_TEST_REPAIR_FORBIDDEN_STATEMENT =
+ /(?:unbounded changed statement|\b(?:expect|assert)\s*[.(]|\b(?:expect|assert)[A-Z]\w*\s*\(|\.(?:not\.)?to[A-Z]\w*\s*\(|\b(?:skip|fixme|fail|slow)\s*\(|\b(?:test|it|describe)(?:\.[A-Za-z]+)*\.(?:skip|fixme|fail|slow|skipIf|runIf)\b|\b(?:skip|fixme)\s*:\s*true\b|\breturn\b|timeout|retr(?:y|ies)|\b(?:disableRules|disabledRules|excludeRules)\b|\btoMatch(?:Inline)?Snapshot\b)/i;
+
+function changedStatementsFromDiff(diff) {
+ const statements = [];
+ let oldLines = [];
+ let newLines = [];
+
+ const statementData = text => {
+ const masked = [...text];
+ const stack = [];
+ const pairs = [];
+ let quote = null;
+ let escaped = false;
+ let lineComment = false;
+ let blockComment = false;
+ for (let index = 0; index < text.length; index += 1) {
+ const character = text[index];
+ const next = text[index + 1];
+ if (lineComment) {
+ masked[index] = ' ';
+ if (character === '\n') lineComment = false;
+ continue;
+ }
+ if (blockComment) {
+ masked[index] = ' ';
+ if (character === '*' && next === '/') {
+ masked[index + 1] = ' ';
+ blockComment = false;
+ index += 1;
+ }
+ continue;
+ }
+ if (quote) {
+ masked[index] = ' ';
+ if (escaped) escaped = false;
+ else if (character === '\\') escaped = true;
+ else if (character === quote) quote = null;
+ continue;
+ }
+ if (character === '/' && next === '/') {
+ masked[index] = ' ';
+ masked[index + 1] = ' ';
+ lineComment = true;
+ index += 1;
+ continue;
+ }
+ if (character === '/' && next === '*') {
+ masked[index] = ' ';
+ masked[index + 1] = ' ';
+ blockComment = true;
+ index += 1;
+ continue;
+ }
+ if (character === "'" || character === '"' || character === '`') {
+ masked[index] = ' ';
+ quote = character;
+ continue;
+ }
+ if ('([{'.includes(character)) {
+ stack.push({character, index});
+ continue;
+ }
+ if (')]}'.includes(character)) {
+ const expected = {')': '(', ']': '[', '}': '{'}[character];
+ const opening = stack.at(-1);
+ if (opening?.character === expected) {
+ stack.pop();
+ pairs.push({
+ close: index,
+ open: opening.index,
+ type: opening.character,
+ });
+ }
+ }
+ }
+ return {masked: masked.join(''), pairs};
+ };
+
+ const addChangedStatements = lines => {
+ const text = lines.map(line => line.text).join('\n');
+ const ranges = [];
+ let offset = 0;
+ for (const line of lines) {
+ ranges.push({end: offset + line.text.length, start: offset});
+ offset += line.text.length + 1;
+ }
+ const {masked, pairs} = statementData(text);
+ for (let index = 0; index < lines.length; index += 1) {
+ if (!lines[index].changed) continue;
+ const range = ranges[index];
+ const enclosingCall = pairs
+ .filter(
+ pair =>
+ pair.type === '(' &&
+ pair.open <= range.start &&
+ pair.close >= range.end,
+ )
+ .sort((a, b) => a.close - a.open - (b.close - b.open))[0];
+ const changedCode = masked.slice(range.start, range.end).trim();
+ if (!changedCode) {
+ if (
+ /@(?:vitest-environment|jest-environment|ts-check|ts-nocheck)|(?:eslint|prettier)-(?:disable|enable)/i.test(
+ lines[index].text,
+ )
+ ) {
+ statements.push('<unbounded changed statement>');
+ }
+ continue;
+ }
+ if (!enclosingCall) {
+ if (!changedCode.includes(';')) {
+ statements.push('<unbounded changed statement>');
+ continue;
+ }
+ for (const statement of changedCode.split(';')) {
+ if (statement.trim()) statements.push(`${statement.trim()};`);
+ }
+ continue;
+ }
+ const previousSemicolon = masked.lastIndexOf(';', enclosingCall.open - 1);
+ if (previousSemicolon === -1) {
+ statements.push('<unbounded changed statement>');
+ continue;
+ }
+ const start = previousSemicolon + 1;
+ const semicolon = masked.indexOf(';', enclosingCall.close);
+ if (semicolon === -1) {
+ statements.push('<unbounded changed statement>');
+ continue;
+ }
+ statements.push(text.slice(start, semicolon + 1).trim());
+ }
+ };
+ const flush = () => {
+ addChangedStatements(oldLines);
+ addChangedStatements(newLines);
+ oldLines = [];
+ newLines = [];
+ };
+
+ for (const line of diff.split('\n')) {
+ if (line.startsWith('@@')) {
+ flush();
+ continue;
+ }
+ if (/^(?:diff --git |index |--- |\+\+\+ )/.test(line)) continue;
+ const marker = line[0];
+ const text = line.slice(1);
+ if (marker === ' ') {
+ oldLines.push({changed: false, text});
+ newLines.push({changed: false, text});
+ } else if (marker === '-') {
+ oldLines.push({changed: true, text});
+ } else if (marker === '+') {
+ newLines.push({changed: true, text});
+ }
+ }
+ flush();
+ return [...new Set(statements)];
+}
+
+function validateReleaseTestRepair({
+ entries,
+ changedLines,
+ changedStatements,
+ commitCount,
+ mergeCommitCount,
+ patchId,
+ changeDigest,
+ mainPatches,
+ baseChangesets,
+}) {
+ const errors = [];
+ if (entries.length === 0)
+ errors.push('release test repair has no changed files');
+ if (commitCount !== 1 || mergeCommitCount !== 0)
+ errors.push(
+ 'release test repair must contain exactly one non-merge commit',
+ );
+ if (baseChangesets.size !== 0)
+ errors.push(
+ 'release test repair requires the generated version bump to be merged first',
+ );
+
+ for (const entry of entries) {
+ const status = entry.split('\t', 1)[0];
+ if (status !== 'M')
+ errors.push(`release test repair may only modify an existing test: ${entry}`);
+ const files = diffEntryFiles(entry);
+ if (files === null) {
+ errors.push(`invalid diff entry: ${entry}`);
+ continue;
+ }
+ for (const file of files) {
+ if (!isReleaseTestRepairPath(file))
+ errors.push(`release test repair contains a non-test path: ${file}`);
+ }
+ }
+ for (const statement of changedStatements ?? changedLines ?? []) {
+ if (RELEASE_TEST_REPAIR_FORBIDDEN_STATEMENT.test(statement))
+ errors.push(
+ `release test repair changes an assertion, test control, timeout, retry, or snapshot: ${statement}`,
+ );
+ }
+
+ const source = patchId
+ ? (mainPatches.get(patchId) ?? []).find(
+ candidate =>
+ candidate.changeDigest === changeDigest && candidate.presentAtMain,
+ )
+ : null;
+ if (!patchId || !changeDigest || !source)
+ errors.push(
+ 'release test repair does not exactly match a non-merge commit still present on main',
+ );
+ return {errors, sourceCommit: source?.commit ?? null};
+}
+
+function stablePatchId(root, diff) {
+ if (!diff.trim()) return null;
+ const output = execFileSync('git', ['patch-id', '--stable'], {
+ cwd: root,
+ encoding: 'utf8',
+ input: diff,
+ }).trim();
+ return output.split(/\s+/)[0] || null;
+}
+
+function exactChangeDigest(diff) {
+ const change = diff
+ .split('\n')
+ .filter(
+ line =>
+ /^(?:diff --git |new file mode |deleted file mode |rename (?:from|to) |copy (?:from|to) )/.test(
+ line,
+ ) ||
+ (/^[+-]/.test(line) && !/^(?:\+\+\+|---)/.test(line)),
+ )
+ .join('\n');
+ return change ? sha256(change) : null;
+}
+
+function patchIsPresentAtRef(root, ref, diff) {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-release-index-'));
+ const index = path.join(temp, 'index');
+ const env = {...process.env, GIT_INDEX_FILE: index};
+ try {
+ execFileSync('git', ['read-tree', ref], {
+ cwd: root,
+ env,
+ stdio: 'ignore',
+ });
+ execFileSync(
+ 'git',
+ ['apply', '--cached', '--reverse', '--check', '--whitespace=nowarn'],
+ {
+ cwd: root,
+ env,
+ input: diff.endsWith('\n') ? diff : `${diff}\n`,
+ stdio: ['pipe', 'ignore', 'ignore'],
+ },
+ );
+ return true;
+ } catch {
+ return false;
+ } finally {
+ fs.rmSync(temp, {recursive: true, force: true});
+ }
+}
+
+function validateReleaseTestRepairAtRef(
+ root,
+ {base, head, mainRef, entries, baseChangesets},
+) {
+ const mergeBase = git(root, ['merge-base', base, head]);
+ const commits = git(root, ['rev-list', `${mergeBase}..${head}`])
+ .split('\n')
+ .filter(Boolean);
+ const mergeCommits = git(root, [
+ 'rev-list',
+ '--min-parents=2',
+ `${mergeBase}..${head}`,
+ ])
+ .split('\n')
+ .filter(Boolean);
+ const diff = gitRaw(root, [
+ 'diff',
+ '--binary',
+ `${mergeBase}..${head}`,
+ ]);
+ const changedStatements = changedStatementsFromDiff(
+ git(root, ['diff', '--unified=20', `${mergeBase}..${head}`]),
+ );
+ const patchId = stablePatchId(root, diff);
+ const changeDigest = exactChangeDigest(diff);
+ const files = [
+ ...new Set(entries.flatMap(entry => diffEntryFiles(entry) ?? [])),
+ ];
+ const mainPatches = new Map();
+ if (mainRef) {
+ const candidates = git(root, [
+ 'log',
+ '--format=%H',
+ '--no-merges',
+ mainRef,
+ '--',
+ ...files,
+ ])
+ .split('\n')
+ .filter(Boolean);
+ for (const commit of candidates) {
+ const candidateDiff = gitRaw(root, [
+ 'show',
+ '--format=',
+ '--binary',
+ commit,
+ ]);
+ const candidatePatchId = stablePatchId(root, candidateDiff);
+ if (!candidatePatchId || candidatePatchId !== patchId) continue;
+ const candidateChangeDigest = exactChangeDigest(candidateDiff);
+ const matches = mainPatches.get(candidatePatchId) ?? [];
+ matches.push({
+ commit,
+ changeDigest: candidateChangeDigest,
+ presentAtMain:
+ candidateChangeDigest === changeDigest &&
+ patchIsPresentAtRef(root, mainRef, candidateDiff),
+ });
+ mainPatches.set(candidatePatchId, matches);
+ }
+ }
+ return {
+ ...validateReleaseTestRepair({
+ entries,
+ changedStatements,
+ commitCount: commits.length,
+ mergeCommitCount: mergeCommits.length,
+ patchId,
+ changeDigest,
+ mainPatches,
+ baseChangesets,
+ }),
+ patchId,
+ };
+}
+
+const RELEASE_POLICY_CARRY_PATTERNS = [
+ /^scripts\/release\/active-release(?:\.test)?\.mjs$/,
+ /^scripts\/release\/release-paths\.mjs$/,
+ /^\.github\/actions\/test-scope\/action\.yml$/,
+ /^\.github\/scripts\/test-scope-action\.test\.mjs$/,
+ /^\.github\/workflows\/ci\.yml$/,
+ /^docs\/release\.md$/,
+ /^docs\/specs\/AST-(?:017|030)\/spec\.md$/,
];
-function isReleaseOutputPath(file) {
- return RELEASE_OUTPUT_PATTERNS.some(pattern => pattern.test(file));
+function isAncestor(root, ancestor, descendant) {
+ try {
+ execFileSync('git', ['merge-base', '--is-ancestor', ancestor, descendant], {
+ cwd: root,
+ stdio: 'ignore',
+ });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+function patchBuildsHead(root, base, head, patch) {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-policy-carry-'));
+ const index = path.join(temp, 'index');
+ const env = {...process.env, GIT_INDEX_FILE: index};
+ try {
+ execFileSync('git', ['read-tree', base], {cwd: root, env, stdio: 'ignore'});
+ execFileSync(
+ 'git',
+ ['apply', '--cached', '--unidiff-zero', '--whitespace=nowarn'], {
+ cwd: root,
+ env,
+ input: patch.endsWith('\n') ? patch : `${patch}\n`,
+ stdio: ['pipe', 'ignore', 'ignore'],
+ });
+ const tree = execFileSync('git', ['write-tree'], {
+ cwd: root,
+ env,
+ encoding: 'utf8',
+ }).trim();
+ return tree === git(root, ['rev-parse', `${head}^{tree}`]);
+ } catch {
+ return false;
+ } finally {
+ fs.rmSync(temp, {recursive: true, force: true});
+ }
+}
+
+function validateReleasePolicyCarryAtRef(
+ root,
+ {base, head, source, mainRef, manifestPath, releaseBranch},
+) {
+ const errors = [];
+ const baseCommit = git(root, ['rev-parse', base]);
+ const commits = git(root, ['rev-list', `${baseCommit}..${head}`])
+ .split('\n')
+ .filter(Boolean);
+ const mergeCommits = git(root, [
+ 'rev-list',
+ '--min-parents=2',
+ `${baseCommit}..${head}`,
+ ])
+ .split('\n')
+ .filter(Boolean);
+ if (commits.length !== 1 || mergeCommits.length !== 0)
+ errors.push(
+ 'release policy carry must contain exactly one non-merge commit',
+ );
+ if (git(root, ['rev-parse', `${head}^`]) !== baseCommit)
+ errors.push('release policy carry commit must directly follow the release head');
+ if (!isAncestor(root, source, mainRef))
+ errors.push('release policy carry source is not merged on current main');
+ if (
+ !/^scripts\/release\/policy-carry\/v\d+\.\d+\.\d+\.json$/.test(manifestPath)
+ )
+ errors.push('release policy carry manifest path is invalid');
+
+ const manifest = jsonAtRef(root, source, manifestPath);
+ if (
+ manifest?.schemaVersion !== 1 ||
+ manifest.releaseBranch !== releaseBranch ||
+ manifest.base !== baseCommit ||
+ !/^scripts\/release\/policy-carry\/v\d+\.\d+\.\d+\.diff$/.test(
+ manifest?.patch ?? '',
+ ) ||
+ !/^[0-9a-f]{64}$/.test(manifest?.patchSha256 ?? '') ||
+ !manifest?.targets ||
+ Array.isArray(manifest.targets) ||
+ typeof manifest.targets !== 'object'
+ ) {
+ errors.push(
+ 'release policy carry manifest does not match this branch and base',
+ );
+ }
+
+ const targets =
+ manifest?.targets &&
+ !Array.isArray(manifest.targets) &&
+ typeof manifest.targets === 'object'
+ ? Object.entries(manifest.targets).sort(([a], [b]) => a.localeCompare(b))
+ : [];
+ for (const [file, digest] of targets) {
+ if (
+ !RELEASE_POLICY_CARRY_PATTERNS.some(pattern => pattern.test(file)) ||
+ !/^[0-9a-f]{64}$/.test(digest)
+ ) {
+ errors.push(
+ `release policy carry manifest has an invalid target: ${file}`,
+ );
+ }
+ }
+
+ const candidateEntries = git(root, [
+ 'diff',
+ '--name-status',
+ baseCommit,
+ head,
+ ])
+ .split('\n')
+ .filter(Boolean);
+ const candidateFiles = [
+ ...new Set(
+ candidateEntries.flatMap(entry => {
+ const files = diffEntryFiles(entry);
+ if (files === null) {
+ errors.push(`invalid release policy carry diff entry: ${entry}`);
+ return [];
+ }
+ return files;
+ }),
+ ),
+ ].sort();
+ const targetFiles = targets.map(([file]) => file);
+ for (const file of candidateFiles) {
+ if (!RELEASE_POLICY_CARRY_PATTERNS.some(pattern => pattern.test(file)))
+ errors.push(
+ `release policy carry contains an unauthorized path: ${file}`,
+ );
+ }
+ if (canonicalJson(candidateFiles) !== canonicalJson(targetFiles))
+ errors.push(
+ 'release policy carry file set does not match its reviewed bundle',
+ );
+
+ const candidateDigests = fileDigestsAtRef(root, head, candidateFiles);
+ for (const [file, digest] of targets) {
+ if (candidateDigests.get(file) !== digest)
+ errors.push(
+ `release policy carry file does not match its reviewed bundle: ${file}`,
+ );
+ }
+
+ const patchContent = manifest?.patch
+ ? filesAtRef(root, source, [manifest.patch]).get(manifest.patch)
+ : null;
+ const patch = patchContent?.toString('utf8') ?? '';
+ if (!patch || sha256(patchContent) !== manifest?.patchSha256)
+ errors.push(
+ 'release policy carry patch does not match its manifest digest',
+ );
+ else if (!patchBuildsHead(root, baseCommit, head, patch))
+ errors.push('release policy carry patch does not build the candidate head');
+
+ return {
+ errors,
+ files: candidateEntries.length,
+ bundleDigest: manifest ? sha256(canonicalJson(manifest)) : null,
+ };
}
function validateReleaseDiff(entries, {plan, baseChangesets} = {}) {
@@ -726,14 +1242,9 @@ function validateReleaseDiff(entries, {plan, baseChangesets} = {}) {
: null;
const deletedChangesets = new Set();
for (const entry of entries) {
- const [status, ...files] = entry.split('\t');
- const isMove = status?.startsWith('R') || status?.startsWith('C');
- const expectedPaths = isMove ? 2 : 1;
- if (
- !status ||
- files.length !== expectedPaths ||
- files.some(file => !file)
- ) {
+ const [status] = entry.split('\t');
+ const files = diffEntryFiles(entry);
+ if (files === null) {
errors.push(`invalid diff entry: ${entry}`);
continue;
}
@@ -1263,6 +1774,35 @@ async function main() {
console.log(JSON.stringify(marker));
return;
}
+ if (command === 'validate-policy-carry') {
+ const base = required(values, 'base');
+ const head = required(values, 'head');
+ const source = required(values, 'source');
+ const mainRef = required(values, 'main-ref');
+ const manifestPath = required(values, 'manifest');
+ const releaseBranch = required(values, 'release-branch');
+ const result = validateReleasePolicyCarryAtRef(root, {
+ base,
+ head,
+ source,
+ mainRef,
+ manifestPath,
+ releaseBranch,
+ });
+ if (result.errors.length) throw new Error(result.errors.join('\n'));
+ console.log(
+ JSON.stringify({
+ kind: 'policy-carry',
+ base,
+ head,
+ source,
+ manifest: manifestPath,
+ files: result.files,
+ bundleDigest: result.bundleDigest,
+ }),
+ );
+ return;
+ }
if (command === 'validate-diff') {
const base = required(values, 'base');
const head = required(values, 'head');
@@ -1271,20 +1811,40 @@ async function main() {
git(root, ['show', `${base}:${RELEASE_DIR}/${PLAN_FILE}`]),
);
const raw = git(root, ['diff', '--name-status', `${base}...${head}`]);
- const errors = [
- ...validateIdentity(marker, plan),
- ...validateReleaseDiff(raw ? raw.split('\n') : [], {
- plan,
- baseChangesets: changesetMapAtRef(root, base),
- }),
- ];
+ const entries = raw ? raw.split('\n') : [];
+ const baseChangesets = changesetMapAtRef(root, base);
+ const kind = classifyReleaseDiff(entries);
+ let sourceCommit = null;
+ let patchId = null;
+ let diffErrors;
+ if (kind === 'test-repair') {
+ const repair = validateReleaseTestRepairAtRef(root, {
+ base,
+ head,
+ mainRef: required(values, 'main-ref'),
+ entries,
+ baseChangesets,
+ });
+ sourceCommit = repair.sourceCommit;
+ patchId = repair.patchId;
+ diffErrors = repair.errors;
+ } else if (kind === 'version-bump') {
+ diffErrors = validateReleaseDiff(entries, {plan, baseChangesets});
+ } else {
+ diffErrors = [
+ 'release candidate contains paths outside the generated version bump or test-repair classes',
+ ];
+ }
+ const errors = [...validateIdentity(marker, plan), ...diffErrors];
if (errors.length) throw new Error(errors.join('\n'));
console.log(
JSON.stringify({
base,
head,
+ kind,
planDigest: marker.planDigest,
- files: raw ? raw.split('\n').length : 0,
+ files: entries.length,
+ ...(sourceCommit ? {sourceCommit, patchId} : {}),
}),
);
return;
@@ -1397,11 +1957,13 @@ export {
buildPlan,
canaryEligibility,
canonicalJson,
+ changedStatementsFromDiff,
compareVersions,
computePlanDigest,
declaredVersionAtRef,
filesAtRef,
nextPlannedVersion,
+ isReleaseTestRepairPath,
isStableReleasePackage,
latestStableVersion,
listActiveBranches,
@@ -1409,6 +1971,7 @@ export {
validateIdentity,
validateRefMarker,
validateReleaseDiff,
+ validateReleaseTestRepair,
validateReleaseState,
validateReleaseMergeBack,
validateHistoricalReleaseMergeBack,
diff --git a/scripts/release/active-release.test.mjs b/scripts/release/active-release.test.mjs
index cc60bedcc5..5000977043 100644
--- a/scripts/release/active-release.test.mjs
+++ b/scripts/release/active-release.test.mjs
@@ -8,6 +8,7 @@
* @position focused safety suite for the release-branch CI contract
*/
+import crypto from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -23,11 +24,14 @@ import {
buildMarker,
buildPlan,
canaryEligibility,
+ changedStatementsFromDiff,
declaredVersionAtRef,
+ isReleaseTestRepairPath,
latestStableVersion,
mergeBackEntries,
nextPlannedVersion,
validateReleaseDiff,
+ validateReleaseTestRepair,
validateHistoricalReleaseMergeBack,
validateReleaseMergeBack,
validateReleaseState,
@@ -452,6 +456,549 @@ describe('active release branch authority', () => {
).toEqual([]);
});
+ it('admits one post-bump test repair whose patch already merged on main', () => {
+ const patchId = 'a'.repeat(40);
+ const changeDigest = 'c'.repeat(64);
+ const sourceCommit = 'b'.repeat(40);
+ const valid = {
+ entries: [
+ 'M\tpackages/core/src/BottomSheet/__tests__/BottomSheetRelease.a11y.chromium.spec.ts',
+ ],
+ changedLines: ['await mouseDrag(page, {duration: 50});'],
+ commitCount: 1,
+ mergeCommitCount: 0,
+ patchId,
+ changeDigest,
+ mainPatches: new Map([
+ [patchId, [{commit: sourceCommit, changeDigest, presentAtMain: true}]],
+ ]),
+ baseChangesets: new Map(),
+ };
+ expect(isReleaseTestRepairPath(valid.entries[0].split('\t')[1])).toBe(true);
+ expect(
+ isReleaseTestRepairPath(
+ 'packages/cli/assets/codemods/transforms/v0.7.12/__tests__/remove-old-api.test.mjs',
+ ),
+ ).toBe(false);
+ expect(
+ isReleaseTestRepairPath(
+ 'packages/cli/assets/codemods/__tests__/registry.test.mjs',
+ ),
+ ).toBe(false);
+ expect(validateReleaseTestRepair(valid)).toEqual({
+ errors: [],
+ sourceCommit,
+ });
+ });
+
+ it('fails closed for any broader or unproven release test repair', () => {
+ const patchId = 'a'.repeat(40);
+ const changeDigest = 'c'.repeat(64);
+ const sourceCommit = 'b'.repeat(40);
+ const repair = overrides =>
+ validateReleaseTestRepair({
+ entries: ['M\tinternal/interaction-harness/runner.ts'],
+ changedLines: ['const release = event.timeStamp;'],
+ commitCount: 1,
+ mergeCommitCount: 0,
+ patchId,
+ changeDigest,
+ mainPatches: new Map([
+ [
+ patchId,
+ [{commit: sourceCommit, changeDigest, presentAtMain: true}],
+ ],
+ ]),
+ baseChangesets: new Map(),
+ ...overrides,
+ }).errors;
+
+ expect(
+ repair({
+ entries: [
+ 'R100\tpackages/core/src/BottomSheet/__tests__/BottomSheetScrimClock.a11y.browser.spec.ts\tpackages/core/src/BottomSheet/__tests__/BottomSheetScrimClock.a11y.browser.spec.ts.disabled',
+ ],
+ }),
+ ).toContain(
+ 'release test repair may only modify an existing test: R100\tpackages/core/src/BottomSheet/__tests__/BottomSheetScrimClock.a11y.browser.spec.ts\tpackages/core/src/BottomSheet/__tests__/BottomSheetScrimClock.a11y.browser.spec.ts.disabled',
+ );
+ expect(
+ repair({entries: ['A\tpackages/core/src/Button/Button.test.tsx']}),
+ ).toContain(
+ 'release test repair may only modify an existing test: A\tpackages/core/src/Button/Button.test.tsx',
+ );
+ expect(
+ repair({entries: ['M\tpackages/core/src/Button/Button.tsx']}),
+ ).toContain(
+ 'release test repair contains a non-test path: packages/core/src/Button/Button.tsx',
+ );
+ expect(
+ repair({
+ entries: ['M\tpackages/core/src/Button/__snapshots__/Button.snap'],
+ }),
+ ).toContain(
+ 'release test repair contains a non-test path: packages/core/src/Button/__snapshots__/Button.snap',
+ );
+ expect(
+ repair({
+ entries: ['M\tapps/docsite/e2e/theme-showcase.spec.ts'],
+ }),
+ ).toContain(
+ 'release test repair contains a non-test path: apps/docsite/e2e/theme-showcase.spec.ts',
+ );
+ expect(
+ repair({
+ entries: ['M\tapps/docsite/src/__tests__/routing.test.ts'],
+ }),
+ ).toContain(
+ 'release test repair contains a non-test path: apps/docsite/src/__tests__/routing.test.ts',
+ );
+ for (const line of [
+ 'expect(dialog).toBeHidden();',
+ '.toBeHidden({visible: false});',
+ 'expectNoA11yViolations(page);',
+ 'test.skip(true, "flaky");',
+ 'test.fail();',
+ 'test.slow();',
+ 'skip();',
+ 'ctx.fixme();',
+ 'testInfo.skip();',
+ 'test.info().fail();',
+ 'it.skipIf(process.platform === "darwin")();',
+ 'describe.runIf(false)();',
+ 'const timeoutMs = 2_000;',
+ 'retries: 3,',
+ 'axe.disableRules(["color-contrast"]);',
+ 'return;',
+ 'expect(tree).toMatchSnapshot();',
+ ]) {
+ expect(repair({changedLines: [line]})).toContain(
+ `release test repair changes an assertion, test control, timeout, retry, or snapshot: ${line}`,
+ );
+ }
+ const statementCases = [
+ {
+ diff: `diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -1,6 +1,6 @@
+ before();
+ await expect.poll(() => count).toBeGreaterThan(
+- 0,
++ 1,
+ );
+ after();`,
+ expected:
+ 'await expect.poll(() => count).toBeGreaterThan(\n 1,\n);',
+ },
+ {
+ diff: `diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -1,6 +1,6 @@
+ before();
+ await expect(result).toEqual({
+- value: 1,
++ value: 2,
+ });
+ after();`,
+ expected: 'await expect(result).toEqual({\n value: 2,\n});',
+ },
+ {
+ diff: `diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -1,7 +1,7 @@
+ before();
+ await expect.poll(() => {
+- return ready;
++ return settled;
+ }).toBe(true);
+ after();`,
+ expected:
+ 'await expect.poll(() => {\n return settled;\n}).toBe(true);',
+ },
+ {
+ diff: `diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -84,5 +84,5 @@
+ children: [
+ {type: 'paragraph'},
+ ],
+- ordered: false,
++ ordered: true,
+ });`,
+ expected: '<unbounded changed statement>',
+ },
+ {
+ diff: `diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -493,5 +493,5 @@
+ brand: {
+ light: {
+- accent: neutralPalettes.green.light[25],
++ accent: neutralPalettes.green.light[30],
+ },
+ },`,
+ expected: '<unbounded changed statement>',
+ },
+ ];
+ for (const {diff, expected} of statementCases) {
+ const changedStatements = changedStatementsFromDiff(diff);
+ expect(changedStatements).toContain(expected);
+ expect(repair({changedLines: undefined, changedStatements})).toContain(
+ `release test repair changes an assertion, test control, timeout, retry, or snapshot: ${expected}`,
+ );
+ }
+ const portStatements = changedStatementsFromDiff(`diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -1,7 +1,7 @@
+ /**
+ * @file BottomSheetRelease.a11y.chromium.spec.ts
+- * @input Built BottomSheet stories and real Chromium touch input (CDP), each
+- * event with its own timestamp
++ * @input Built BottomSheet stories and real Chromium touch and mouse input
++ * (CDP), each event with its own timestamp
+ * @output Browser evidence for the touch release.
+ */
+@@ -20,5 +20,8 @@
+ setup();
++const cdp = await page.context().newCDPSession(page);
++// 150 px in 50 ms is 3,000 px/s, so the mouse release projects past the
++// dismiss line even when event delivery is slow.
++await mouseDrag(cdp, sheet, 150, 50);
+ cleanup();`);
+ expect(portStatements).not.toContain('<unbounded changed statement>');
+
+ const multiStatementChange = changedStatementsFromDiff(`diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -1 +1 @@
+-safe(); expect(value).toBe(true);
++safe(); expect(value).toBe(false);`);
+ expect(multiStatementChange).toContain('expect(value).toBe(false);');
+ expect(
+ repair({changedLines: undefined, changedStatements: multiStatementChange}),
+ ).toContain(
+ 'release test repair changes an assertion, test control, timeout, retry, or snapshot: expect(value).toBe(false);',
+ );
+
+ expect(
+ changedStatementsFromDiff(`diff --git a/test.mjs b/test.mjs
+--- a/test.mjs
++++ b/test.mjs
+@@ -1 +1 @@
+-// @vitest-environment node
++// @vitest-environment jsdom`),
+ ).toContain('<unbounded changed statement>');
+
+ expect(repair({commitCount: 2})).toContain(
+ 'release test repair must contain exactly one non-merge commit',
+ );
+ expect(repair({mergeCommitCount: 1})).toContain(
+ 'release test repair must contain exactly one non-merge commit',
+ );
+ expect(repair({mainPatches: new Map()})).toContain(
+ 'release test repair does not exactly match a non-merge commit still present on main',
+ );
+ expect(repair({changeDigest: 'd'.repeat(64)})).toContain(
+ 'release test repair does not exactly match a non-merge commit still present on main',
+ );
+ expect(
+ repair({
+ mainPatches: new Map([
+ [
+ patchId,
+ [
+ {
+ commit: sourceCommit,
+ changeDigest,
+ presentAtMain: false,
+ },
+ ],
+ ],
+ ]),
+ }),
+ ).toContain(
+ 'release test repair does not exactly match a non-merge commit still present on main',
+ );
+ expect(
+ repair({
+ baseChangesets: new Map([['.changeset/frozen.md', 'c'.repeat(64)]]),
+ }),
+ ).toContain(
+ 'release test repair requires the generated version bump to be merged first',
+ );
+ });
+
+ it('proves the real git patch against current main before the CLI admits it', () => {
+ const root = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-release-test-repair-'),
+ );
+ roots.push(root);
+ const testFile =
+ 'packages/core/src/BottomSheet/__tests__/BottomSheetRelease.a11y.chromium.spec.ts';
+ const before =
+ 'const ready = true;\nawait page.mouse.move(0, 150);\n\n';
+ const after = 'const ready = true;\nawait mouseDrag(page);\n\n';
+ const {cut} = createRepository(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'cut',
+ snapshot: true,
+ files: {
+ '.changeset/README.md': '# Changesets\n',
+ 'pnpm-workspace.yaml': "packages:\n - 'packages/*'\n",
+ 'packages/core/package.json': JSON.stringify({
+ name: '@astryxdesign/core',
+ version: '0.6.5',
+ }),
+ [testFile]: before,
+ },
+ },
+ ]);
+ const plan = {
+ schemaVersion: 2,
+ version: '0.6.5',
+ branch: BRANCH,
+ cutSha: cut,
+ changesets: [],
+ };
+ const marker = buildMarker(plan);
+ const {
+ mainRepair,
+ mainRevert,
+ releaseBase,
+ releaseRepair,
+ whitespaceRepair,
+ } = importCommits(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'mainRepair',
+ parent: cut,
+ files: {[testFile]: after},
+ },
+ {
+ ref: `refs/heads/${BRANCH}`,
+ name: 'releaseBase',
+ parent: cut,
+ files: {
+ '.release/active.json': `${JSON.stringify(marker)}\n`,
+ '.release/plan.json': `${JSON.stringify(plan)}\n`,
+ },
+ },
+ {
+ ref: 'refs/heads/repair',
+ name: 'releaseRepair',
+ parent: 'releaseBase',
+ files: {[testFile]: after},
+ },
+ {
+ ref: 'refs/heads/whitespace-repair',
+ name: 'whitespaceRepair',
+ parent: 'releaseBase',
+ files: {
+ [testFile]:
+ 'const ready = true;\nawait mouse Drag(page);\n\n',
+ },
+ },
+ {
+ ref: 'refs/heads/reverted-main',
+ name: 'mainRevert',
+ parent: 'mainRepair',
+ files: {[testFile]: before},
+ },
+ ]);
+ const validator = path.join(import.meta.dirname, 'active-release.mjs');
+ const run = (head, mainRef) =>
+ execFileSync(
+ process.execPath,
+ [
+ validator,
+ 'validate-diff',
+ '--root',
+ root,
+ '--base',
+ releaseBase,
+ '--head',
+ head,
+ '--main-ref',
+ mainRef,
+ ],
+ {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']},
+ );
+
+ expect(JSON.parse(run(releaseRepair, mainRepair))).toMatchObject({
+ kind: 'test-repair',
+ sourceCommit: mainRepair,
+ files: 1,
+ });
+ for (const [head, mainRef] of [
+ [whitespaceRepair, mainRepair],
+ [releaseRepair, mainRevert],
+ ]) {
+ try {
+ run(head, mainRef);
+ throw new Error('expected validation to fail');
+ } catch (error) {
+ expect(error.stderr).toContain(
+ 'does not exactly match a non-merge commit still present on main',
+ );
+ }
+ }
+ });
+
+ it('admits only an exact reviewed policy bundle onto a predating release branch', () => {
+ const root = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-release-policy-carry-'),
+ );
+ roots.push(root);
+ const validatorFile = 'scripts/release/active-release.mjs';
+ const workflowFile = '.github/workflows/ci.yml';
+ const manifestPath = 'scripts/release/policy-carry/v0.6.5.json';
+ const patchPath = 'scripts/release/policy-carry/v0.6.5.diff';
+ const digest = value =>
+ crypto.createHash('sha256').update(value).digest('hex');
+ const {cut} = createRepository(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'cut',
+ snapshot: true,
+ files: {
+ [validatorFile]: 'main generated only\n',
+ [workflowFile]: 'main trusted base\n',
+ 'packages/core/src/Button/Button.tsx': 'export const Button = 1;\n',
+ },
+ },
+ ]);
+ const policyFiles = {
+ [validatorFile]: 'generated or proven test repair\n',
+ [workflowFile]: 'trusted base plus current main\n',
+ };
+ const {releaseBase, policyCarry, wrongContent, productCarry} =
+ importCommits(root, [
+ {
+ ref: `refs/heads/${BRANCH}`,
+ name: 'releaseBase',
+ parent: cut,
+ files: {
+ [validatorFile]: 'release generated only\n',
+ [workflowFile]: 'release trusted base\n',
+ },
+ },
+ {
+ ref: 'refs/heads/policy-carry',
+ name: 'policyCarry',
+ parent: 'releaseBase',
+ files: policyFiles,
+ },
+ {
+ ref: 'refs/heads/wrong-content',
+ name: 'wrongContent',
+ parent: 'releaseBase',
+ files: {
+ ...policyFiles,
+ [workflowFile]: 'almost trusted base plus current main\n',
+ },
+ },
+ {
+ ref: 'refs/heads/product-carry',
+ name: 'productCarry',
+ parent: 'releaseBase',
+ files: {
+ ...policyFiles,
+ 'packages/core/src/Button/Button.tsx': 'export const Button = 2;\n',
+ },
+ },
+ ]);
+ const patch = execFileSync(
+ 'git',
+ ['diff', '--binary', releaseBase, policyCarry],
+ {cwd: root, encoding: 'utf8'},
+ );
+ const targets = Object.fromEntries(
+ Object.keys(policyFiles)
+ .sort()
+ .map(file => [
+ file,
+ digest(
+ execFileSync('git', ['show', `${policyCarry}:${file}`], {
+ cwd: root,
+ }),
+ ),
+ ]),
+ );
+ const manifest = {
+ schemaVersion: 1,
+ releaseBranch: BRANCH,
+ base: releaseBase,
+ patch: patchPath,
+ patchSha256: digest(patch),
+ targets,
+ };
+ const {mainPolicy} = importCommits(root, [
+ {
+ ref: 'refs/heads/main',
+ name: 'mainPolicy',
+ parent: cut,
+ files: {
+ [manifestPath]: `${JSON.stringify(manifest)}\n`,
+ [patchPath]: patch,
+ },
+ },
+ ]);
+ const validator = path.join(import.meta.dirname, 'active-release.mjs');
+ const run = head =>
+ execFileSync(
+ process.execPath,
+ [
+ validator,
+ 'validate-policy-carry',
+ '--root',
+ root,
+ '--base',
+ releaseBase,
+ '--head',
+ head,
+ '--source',
+ mainPolicy,
+ '--main-ref',
+ mainPolicy,
+ '--manifest',
+ manifestPath,
+ '--release-branch',
+ BRANCH,
+ ],
+ {encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']},
+ );
+
+ expect(JSON.parse(run(policyCarry))).toMatchObject({
+ kind: 'policy-carry',
+ source: mainPolicy,
+ manifest: manifestPath,
+ files: 2,
+ });
+ try {
+ run(wrongContent);
+ throw new Error('expected validation to fail');
+ } catch (error) {
+ expect(error.stderr).toContain(
+ `release policy carry file does not match its reviewed bundle: ${workflowFile}`,
+ );
+ }
+ try {
+ run(productCarry);
+ throw new Error('expected validation to fail');
+ } catch (error) {
+ expect(error.stderr).toContain(
+ 'release policy carry contains an unauthorized path: packages/core/src/Button/Button.tsx',
+ );
+ }
+ });
+
it('binds generated-only deletion to the frozen plan paths and hashes', () => {
const digest = value => value.repeat(64).slice(0, 64);
const plan = {
diff --git a/scripts/release/policy-carry/v0.7.12.diff b/scripts/release/policy-carry/v0.7.12.diff
new file mode 100644
index 0000000000..a6c21d795f
--- /dev/null
+++ b/scripts/release/policy-carry/v0.7.12.diff
@@ -0,0 +1,991 @@
+diff --git a/.github/actions/test-scope/action.yml b/.github/actions/test-scope/action.yml
+index eb8aa34cfb0..a869c376ada 100644
+--- a/.github/actions/test-scope/action.yml
++++ b/.github/actions/test-scope/action.yml
+@@ -89,0 +90,5 @@ outputs:
++ truncated:
++ description: >-
++ `true` when the step could not decide because GitHub truncated the pull
++ request's file list (3,000 files); a re-run cannot decide such a scope.
++ value: ${{ steps.scope.outputs.truncated }}
+@@ -150,0 +156 @@ runs:
++ truncated: 'false',
+@@ -171,0 +178,15 @@ runs:
++ const writeChangedFiles = files => {
++ const changedFilesPath = path.join(
++ process.env.RUNNER_TEMP || os.tmpdir(),
++ 'test-scope-changed-files.txt',
++ );
++ const changed = [
++ ...new Set(
++ files.flatMap(file =>
++ [file.filename, file.previous_filename].filter(Boolean),
++ ),
++ ),
++ ];
++ fs.writeFileSync(changedFilesPath, `${changed.join('\n')}\n`);
++ return changedFilesPath;
++ };
+@@ -179,14 +199,0 @@ runs:
+- if (pr.base.ref.startsWith('release/v')) {
+- core.info('Release-branch pull request: the generated version bump.');
+- report({
+- ...everything,
+- ...(audit ? auditNone : {}),
+- spec_only: 'true',
+- tooling_only: 'true',
+- release_bump: 'true',
+- touches: 'false',
+- applies: 'false',
+- });
+- return;
+- }
+-
+@@ -214,0 +222,3 @@ runs:
++ ...(pr.base.ref.startsWith('release/v')
++ ? ['scripts/release/release-paths.mjs']
++ : []),
+@@ -238 +248,6 @@ runs:
+- report({...everything, decided: 'false'});
++ report({
++ ...everything,
++ release_bump: String(pr.base.ref.startsWith('release/v')),
++ decided: 'false',
++ truncated: String(/truncated the file list/.test(error.message)),
++ });
+@@ -247,0 +263,34 @@ runs:
++
++ if (pr.base.ref.startsWith('release/v')) {
++ const releaseKind = execFileSync(
++ 'node',
++ [
++ path.join(root, 'scripts/release/release-paths.mjs'),
++ '--classify',
++ ],
++ {encoding: 'utf8', input: `${nameStatus}\n`},
++ ).trim();
++ if (releaseKind === 'version-bump') {
++ core.info('Release-branch pull request: the generated version bump.');
++ report({
++ ...everything,
++ ...(audit ? auditNone : {}),
++ spec_only: 'true',
++ tooling_only: 'true',
++ release_bump: 'true',
++ touches: 'false',
++ applies: 'false',
++ });
++ } else {
++ core.info(
++ `Release-branch ${releaseKind} candidate: every test lane runs; the release validator decides whether the change is allowed.`,
++ );
++ report({
++ ...everything,
++ ...(audit ? auditAll : {}),
++ release_bump: 'true',
++ changed_files_path: writeChangedFiles(files),
++ });
++ }
++ return;
++ }
+diff --git a/.github/scripts/test-scope-action.test.mjs b/.github/scripts/test-scope-action.test.mjs
+index caa564da490..e65114eaa3e 100644
+--- a/.github/scripts/test-scope-action.test.mjs
++++ b/.github/scripts/test-scope-action.test.mjs
+@@ -42,0 +43 @@ const CLASSIFIER_FILES = new Set([
++const RELEASE_PATHS_FILE = 'scripts/release/release-paths.mjs';
+@@ -106,0 +108 @@ async function decide({
++ file === RELEASE_PATHS_FILE ||
+@@ -183,0 +186 @@ describe('per-job scope step', () => {
++ 'truncated',
+@@ -206 +209 @@ describe('per-job scope step', () => {
+- it('marks a release-branch pull request as the generated version bump', async () => {
++ it('keeps a generated release-branch pull request on the narrow bump lane', async () => {
+@@ -208,0 +212,7 @@ describe('per-job scope step', () => {
++ files: changed(
++ '.changeset/frozen.md',
++ 'packages/core/CHANGELOG.md',
++ 'packages/core/package.json',
++ 'packages/cli/assets/codemods/__tests__/registry.test.mjs',
++ 'packages/cli/assets/codemods/transforms/v1.2.3/__tests__/upgrade.test.mjs',
++ ),
+@@ -217,0 +228,49 @@ describe('per-job scope step', () => {
++ it('runs every lane for a release-branch test-repair candidate', async () => {
++ const {outputs} = await decide({
++ context: pullRequestContext('release/v1.2.3'),
++ files: changed(
++ 'packages/core/src/BottomSheet/__tests__/BottomSheetRelease.a11y.chromium.spec.ts',
++ ),
++ inputs: {'component-audit': 'true'},
++ });
++ expect(outputs).toMatchObject({
++ release_bump: 'true',
++ spec_only: 'false',
++ tooling_only: 'false',
++ full_suite: 'true',
++ vitest_full_suite: 'true',
++ has_components: 'true',
++ force_full_component_audits: 'true',
++ applies: 'true',
++ });
++ expect(fs.readFileSync(outputs.changed_files_path, 'utf8')).toBe(
++ 'packages/core/src/BottomSheet/__tests__/BottomSheetRelease.a11y.chromium.spec.ts\n',
++ );
++ });
++
++ it.each([
++ ['an empty file list', []],
++ ['an API failure', new Error('unavailable')],
++ [
++ 'a truncated file list',
++ Array.from({length: 3000}, (_, index) => ({
++ filename: `packages/core/src/Test${index}.test.ts`,
++ status: 'modified',
++ })),
++ ],
++ ])('runs every lane when release scope has %s', async (_, files) => {
++ const {outputs} = await decide({
++ context: pullRequestContext('release/v1.2.3'),
++ files,
++ inputs: {'component-audit': 'true'},
++ });
++ expect(outputs).toMatchObject({
++ release_bump: 'true',
++ decided: 'false',
++ full_suite: 'true',
++ vitest_full_suite: 'true',
++ force_full_component_audits: 'true',
++ applies: 'true',
++ });
++ });
++
+@@ -382 +441 @@ describe('per-job scope step', () => {
+- ])('puts everything in scope when %s', async (_, options) => {
++ ])('puts everything in scope when %s', async (name, options) => {
+@@ -386,0 +446,4 @@ describe('per-job scope step', () => {
++ // Only a truncated file list is one a re-run cannot decide.
++ expect(outputs.truncated).toBe(
++ name === 'GitHub truncates the file list' ? 'true' : 'false',
++ );
+@@ -543 +606 @@ describe('per-job scope step', () => {
+- it('applies no audit to a release-branch pull request', async () => {
++ it('applies no audit to the generated release-branch pull request', async () => {
+@@ -545,0 +609,5 @@ describe('per-job scope step', () => {
++ files: changed(
++ '.changeset/frozen.md',
++ 'packages/core/CHANGELOG.md',
++ 'packages/core/package.json',
++ ),
+@@ -836,0 +905,39 @@ describe('the temporary policy folder', () => {
++
++describe('the contract job on a pull request GitHub truncates', () => {
++ it('lists every file and runs, never fails, on an undecided scope', async () => {
++ const ci = yaml.parse(
++ fs.readFileSync(
++ path.join(import.meta.dirname, '../workflows/ci.yml'),
++ 'utf8',
++ ),
++ );
++ const job = ci.jobs['pr-component-a11y-contracts'];
++ const scopeStep = job.steps.find(step => step.id === 'scope');
++ const {outputs} = await decide({
++ files: Array.from({length: 3001}, (_, i) => ({
++ filename: `packages/core/src/Button/file${i}.tsx`,
++ status: 'modified',
++ })),
++ inputs: scopeStep.with,
++ });
++ expect(outputs).toMatchObject({applies: 'true', decided: 'false'});
++ expect(outputs.changed_files_path ?? '').toBe('');
++ // The workflow's own conditions, read against these outputs.
++ const holds = condition =>
++ Function(
++ 'outputs',
++ `return (${condition
++ .replace(
++ /steps\.scope\.outputs\.(\w+)/g,
++ (_, key) => `(outputs.${key} ?? '')`,
++ )
++ .replace(/ == /g, ' === ')
++ .replace(/ != /g, ' !== ')});`,
++ )(outputs);
++ const step = name => job.steps.find(candidate => candidate.name === name);
++ expect(holds(step('Require the changed-file list').if)).toBe(false);
++ expect(holds(step('List every file when the scope is undecided').if)).toBe(
++ true,
++ );
++ });
++});
+diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
+index 06d9db55411..f824d6ca219 100644
+--- a/.github/workflows/ci.yml
++++ b/.github/workflows/ci.yml
+@@ -303,0 +304,2 @@ jobs:
++ git show "origin/$RELEASE_BRANCH:scripts/release/release-paths.mjs" \
++ > "$TRUSTED_POLICY/scripts/release/release-paths.mjs"
+@@ -374 +376 @@ jobs:
+- - name: Fetch release refs, base, and trusted release policy
++ - name: Fetch release refs, base, main, and trusted release policy
+@@ -377 +379,2 @@ jobs:
+- git fetch origin "${{ github.base_ref }}" --depth=50
++ git fetch origin "${{ github.base_ref }}" --depth=200
++ git fetch origin 'main:refs/remotes/origin/main'
+@@ -381,0 +385,2 @@ jobs:
++ git show "origin/${{ github.base_ref }}:scripts/release/release-paths.mjs" \
++ > "$TRUSTED_POLICY/scripts/release/release-paths.mjs"
+@@ -388 +393 @@ jobs:
+- - name: Require generated-only release bookkeeping
++ - name: Require generated release bookkeeping or a proven test repair
+@@ -393 +398,2 @@ jobs:
+- --head "${{ github.event.pull_request.head.sha }}"
++ --head "${{ github.event.pull_request.head.sha }}" \
++ --main-ref origin/main
+@@ -472,0 +479,2 @@ jobs:
++ git show origin/main:scripts/release/release-paths.mjs \
++ > "$TRUSTED_POLICY/scripts/release/release-paths.mjs"
+@@ -4291,0 +4300,9 @@ jobs:
++ # When the scope could not be decided, every file counts as changed.
++ - name: List every file when the scope is undecided
++ id: everything
++ if: steps.scope.outputs.applies == 'true' && steps.scope.outputs.changed_files_path == '' && steps.scope.outputs.decided == 'false'
++ run: |
++ git ls-files > "$RUNNER_TEMP/every-file.txt"
++ echo "path=$RUNNER_TEMP/every-file.txt" >> "$GITHUB_OUTPUT"
++ echo "::notice title=Every contract in scope::The scope could not be decided, so every file counts as changed."
++
+@@ -4295 +4312 @@ jobs:
+- if: steps.scope.outputs.applies == 'true' && steps.scope.outputs.changed_files_path == ''
++ if: steps.scope.outputs.applies == 'true' && steps.scope.outputs.changed_files_path == '' && steps.scope.outputs.decided != 'false'
+@@ -4315 +4332 @@ jobs:
+- FILES_PATH: ${{ steps.scope.outputs.changed_files_path }}
++ FILES_PATH: ${{ steps.scope.outputs.changed_files_path || steps.everything.outputs.path }}
+@@ -4326 +4343 @@ jobs:
+- FILES_PATH: ${{ steps.scope.outputs.changed_files_path }}
++ FILES_PATH: ${{ steps.scope.outputs.changed_files_path || steps.everything.outputs.path }}
+@@ -4411 +4428 @@ jobs:
+- FILES_PATH: ${{ steps.scope.outputs.changed_files_path }}
++ FILES_PATH: ${{ steps.scope.outputs.changed_files_path || steps.everything.outputs.path }}
+diff --git a/scripts/release/active-release.mjs b/scripts/release/active-release.mjs
+index 7eae88e71bd..02d05a4b359 100644
+--- a/scripts/release/active-release.mjs
++++ b/scripts/release/active-release.mjs
+@@ -14,2 +14,2 @@
+- * CI copies this file and lib/workspace-globs.mjs alone as trusted policy, so
+- * it imports nothing else at module load.
++ * CI copies this file, release-paths.mjs, and lib/workspace-globs.mjs as
++ * trusted policy.
+@@ -19,0 +20 @@ import fs from 'node:fs';
++import os from 'node:os';
+@@ -23,0 +25,6 @@ import {expandWorkspaceDirs} from '../lib/workspace-globs.mjs';
++import {
++ classifyReleaseDiff,
++ diffEntryFiles,
++ isReleaseOutputPath,
++ isReleaseTestRepairPath,
++} from './release-paths.mjs';
+@@ -362,0 +370,4 @@ function validateReleaseState({
++function gitRaw(root, args) {
++ return execFileSync('git', args, {cwd: root, encoding: 'utf8'});
++}
++
+@@ -364 +375 @@ function git(root, args) {
+- return execFileSync('git', args, {cwd: root, encoding: 'utf8'}).trim();
++ return gitRaw(root, args).trim();
+@@ -709,7 +720,355 @@ function listActiveBranches(root) {
+-const RELEASE_OUTPUT_PATTERNS = [
+- /^packages\/(?:[^/]+|themes\/[^/]+)\/package\.json$/,
+- /^packages\/(?:[^/]+|themes\/[^/]+)\/CHANGELOG\.md$/,
+- /^packages\/cli\/assets\/codemods\/registry\.mjs$/,
+- /^packages\/cli\/assets\/codemods\/__tests__\/registry\.test\.mjs$/,
+- /^packages\/cli\/assets\/codemods\/transforms\/(?:next|v\d+\.\d+\.\d+)\//,
+- /^pnpm-lock\.yaml$/,
++const RELEASE_TEST_REPAIR_FORBIDDEN_STATEMENT =
++ /(?:unbounded changed statement|\b(?:expect|assert)\s*[.(]|\b(?:expect|assert)[A-Z]\w*\s*\(|\.(?:not\.)?to[A-Z]\w*\s*\(|\b(?:skip|fixme|fail|slow)\s*\(|\b(?:test|it|describe)(?:\.[A-Za-z]+)*\.(?:skip|fixme|fail|slow|skipIf|runIf)\b|\b(?:skip|fixme)\s*:\s*true\b|\breturn\b|timeout|retr(?:y|ies)|\b(?:disableRules|disabledRules|excludeRules)\b|\btoMatch(?:Inline)?Snapshot\b)/i;
++
++function changedStatementsFromDiff(diff) {
++ const statements = [];
++ let oldLines = [];
++ let newLines = [];
++
++ const statementData = text => {
++ const masked = [...text];
++ const stack = [];
++ const pairs = [];
++ let quote = null;
++ let escaped = false;
++ let lineComment = false;
++ let blockComment = false;
++ for (let index = 0; index < text.length; index += 1) {
++ const character = text[index];
++ const next = text[index + 1];
++ if (lineComment) {
++ masked[index] = ' ';
++ if (character === '\n') lineComment = false;
++ continue;
++ }
++ if (blockComment) {
++ masked[index] = ' ';
++ if (character === '*' && next === '/') {
++ masked[index + 1] = ' ';
++ blockComment = false;
++ index += 1;
++ }
++ continue;
++ }
++ if (quote) {
++ masked[index] = ' ';
++ if (escaped) escaped = false;
++ else if (character === '\\') escaped = true;
++ else if (character === quote) quote = null;
++ continue;
++ }
++ if (character === '/' && next === '/') {
++ masked[index] = ' ';
++ masked[index + 1] = ' ';
++ lineComment = true;
++ index += 1;
++ continue;
++ }
++ if (character === '/' && next === '*') {
++ masked[index] = ' ';
++ masked[index + 1] = ' ';
++ blockComment = true;
++ index += 1;
++ continue;
++ }
++ if (character === "'" || character === '"' || character === '`') {
++ masked[index] = ' ';
++ quote = character;
++ continue;
++ }
++ if ('([{'.includes(character)) {
++ stack.push({character, index});
++ continue;
++ }
++ if (')]}'.includes(character)) {
++ const expected = {')': '(', ']': '[', '}': '{'}[character];
++ const opening = stack.at(-1);
++ if (opening?.character === expected) {
++ stack.pop();
++ pairs.push({
++ close: index,
++ open: opening.index,
++ type: opening.character,
++ });
++ }
++ }
++ }
++ return {masked: masked.join(''), pairs};
++ };
++
++ const addChangedStatements = lines => {
++ const text = lines.map(line => line.text).join('\n');
++ const ranges = [];
++ let offset = 0;
++ for (const line of lines) {
++ ranges.push({end: offset + line.text.length, start: offset});
++ offset += line.text.length + 1;
++ }
++ const {masked, pairs} = statementData(text);
++ for (let index = 0; index < lines.length; index += 1) {
++ if (!lines[index].changed) continue;
++ const range = ranges[index];
++ const enclosingCall = pairs
++ .filter(
++ pair =>
++ pair.type === '(' &&
++ pair.open <= range.start &&
++ pair.close >= range.end,
++ )
++ .sort((a, b) => a.close - a.open - (b.close - b.open))[0];
++ const changedCode = masked.slice(range.start, range.end).trim();
++ if (!changedCode) {
++ if (
++ /@(?:vitest-environment|jest-environment|ts-check|ts-nocheck)|(?:eslint|prettier)-(?:disable|enable)/i.test(
++ lines[index].text,
++ )
++ ) {
++ statements.push('<unbounded changed statement>');
++ }
++ continue;
++ }
++ if (!enclosingCall) {
++ if (!changedCode.includes(';')) {
++ statements.push('<unbounded changed statement>');
++ continue;
++ }
++ for (const statement of changedCode.split(';')) {
++ if (statement.trim()) statements.push(`${statement.trim()};`);
++ }
++ continue;
++ }
++ const previousSemicolon = masked.lastIndexOf(';', enclosingCall.open - 1);
++ if (previousSemicolon === -1) {
++ statements.push('<unbounded changed statement>');
++ continue;
++ }
++ const start = previousSemicolon + 1;
++ const semicolon = masked.indexOf(';', enclosingCall.close);
++ if (semicolon === -1) {
++ statements.push('<unbounded changed statement>');
++ continue;
++ }
++ statements.push(text.slice(start, semicolon + 1).trim());
++ }
++ };
++ const flush = () => {
++ addChangedStatements(oldLines);
++ addChangedStatements(newLines);
++ oldLines = [];
++ newLines = [];
++ };
++
++ for (const line of diff.split('\n')) {
++ if (line.startsWith('@@')) {
++ flush();
++ continue;
++ }
++ if (/^(?:diff --git |index |--- |\+\+\+ )/.test(line)) continue;
++ const marker = line[0];
++ const text = line.slice(1);
++ if (marker === ' ') {
++ oldLines.push({changed: false, text});
++ newLines.push({changed: false, text});
++ } else if (marker === '-') {
++ oldLines.push({changed: true, text});
++ } else if (marker === '+') {
++ newLines.push({changed: true, text});
++ }
++ }
++ flush();
++ return [...new Set(statements)];
++}
++
++function validateReleaseTestRepair({
++ entries,
++ changedLines,
++ changedStatements,
++ commitCount,
++ mergeCommitCount,
++ patchId,
++ changeDigest,
++ mainPatches,
++ baseChangesets,
++}) {
++ const errors = [];
++ if (entries.length === 0)
++ errors.push('release test repair has no changed files');
++ if (commitCount !== 1 || mergeCommitCount !== 0)
++ errors.push(
++ 'release test repair must contain exactly one non-merge commit',
++ );
++ if (baseChangesets.size !== 0)
++ errors.push(
++ 'release test repair requires the generated version bump to be merged first',
++ );
++
++ for (const entry of entries) {
++ const status = entry.split('\t', 1)[0];
++ if (status !== 'M')
++ errors.push(`release test repair may only modify an existing test: ${entry}`);
++ const files = diffEntryFiles(entry);
++ if (files === null) {
++ errors.push(`invalid diff entry: ${entry}`);
++ continue;
++ }
++ for (const file of files) {
++ if (!isReleaseTestRepairPath(file))
++ errors.push(`release test repair contains a non-test path: ${file}`);
++ }
++ }
++ for (const statement of changedStatements ?? changedLines ?? []) {
++ if (RELEASE_TEST_REPAIR_FORBIDDEN_STATEMENT.test(statement))
++ errors.push(
++ `release test repair changes an assertion, test control, timeout, retry, or snapshot: ${statement}`,
++ );
++ }
++
++ const source = patchId
++ ? (mainPatches.get(patchId) ?? []).find(
++ candidate =>
++ candidate.changeDigest === changeDigest && candidate.presentAtMain,
++ )
++ : null;
++ if (!patchId || !changeDigest || !source)
++ errors.push(
++ 'release test repair does not exactly match a non-merge commit still present on main',
++ );
++ return {errors, sourceCommit: source?.commit ?? null};
++}
++
++function stablePatchId(root, diff) {
++ if (!diff.trim()) return null;
++ const output = execFileSync('git', ['patch-id', '--stable'], {
++ cwd: root,
++ encoding: 'utf8',
++ input: diff,
++ }).trim();
++ return output.split(/\s+/)[0] || null;
++}
++
++function exactChangeDigest(diff) {
++ const change = diff
++ .split('\n')
++ .filter(
++ line =>
++ /^(?:diff --git |new file mode |deleted file mode |rename (?:from|to) |copy (?:from|to) )/.test(
++ line,
++ ) ||
++ (/^[+-]/.test(line) && !/^(?:\+\+\+|---)/.test(line)),
++ )
++ .join('\n');
++ return change ? sha256(change) : null;
++}
++
++function patchIsPresentAtRef(root, ref, diff) {
++ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-release-index-'));
++ const index = path.join(temp, 'index');
++ const env = {...process.env, GIT_INDEX_FILE: index};
++ try {
++ execFileSync('git', ['read-tree', ref], {
++ cwd: root,
++ env,
++ stdio: 'ignore',
++ });
++ execFileSync(
++ 'git',
++ ['apply', '--cached', '--reverse', '--check', '--whitespace=nowarn'],
++ {
++ cwd: root,
++ env,
++ input: diff.endsWith('\n') ? diff : `${diff}\n`,
++ stdio: ['pipe', 'ignore', 'ignore'],
++ },
++ );
++ return true;
++ } catch {
++ return false;
++ } finally {
++ fs.rmSync(temp, {recursive: true, force: true});
++ }
++}
++
++function validateReleaseTestRepairAtRef(
++ root,
++ {base, head, mainRef, entries, baseChangesets},
++) {
++ const mergeBase = git(root, ['merge-base', base, head]);
++ const commits = git(root, ['rev-list', `${mergeBase}..${head}`])
++ .split('\n')
++ .filter(Boolean);
++ const mergeCommits = git(root, [
++ 'rev-list',
++ '--min-parents=2',
++ `${mergeBase}..${head}`,
++ ])
++ .split('\n')
++ .filter(Boolean);
++ const diff = gitRaw(root, [
++ 'diff',
++ '--binary',
++ `${mergeBase}..${head}`,
++ ]);
++ const changedStatements = changedStatementsFromDiff(
++ git(root, ['diff', '--unified=20', `${mergeBase}..${head}`]),
++ );
++ const patchId = stablePatchId(root, diff);
++ const changeDigest = exactChangeDigest(diff);
++ const files = [
++ ...new Set(entries.flatMap(entry => diffEntryFiles(entry) ?? [])),
++ ];
++ const mainPatches = new Map();
++ if (mainRef) {
++ const candidates = git(root, [
++ 'log',
++ '--format=%H',
++ '--no-merges',
++ mainRef,
++ '--',
++ ...files,
++ ])
++ .split('\n')
++ .filter(Boolean);
++ for (const commit of candidates) {
++ const candidateDiff = gitRaw(root, [
++ 'show',
++ '--format=',
++ '--binary',
++ commit,
++ ]);
++ const candidatePatchId = stablePatchId(root, candidateDiff);
++ if (!candidatePatchId || candidatePatchId !== patchId) continue;
++ const candidateChangeDigest = exactChangeDigest(candidateDiff);
++ const matches = mainPatches.get(candidatePatchId) ?? [];
++ matches.push({
++ commit,
++ changeDigest: candidateChangeDigest,
++ presentAtMain:
++ candidateChangeDigest === changeDigest &&
++ patchIsPresentAtRef(root, mainRef, candidateDiff),
++ });
++ mainPatches.set(candidatePatchId, matches);
++ }
++ }
++ return {
++ ...validateReleaseTestRepair({
++ entries,
++ changedStatements,
++ commitCount: commits.length,
++ mergeCommitCount: mergeCommits.length,
++ patchId,
++ changeDigest,
++ mainPatches,
++ baseChangesets,
++ }),
++ patchId,
++ };
++}
++
++const RELEASE_POLICY_CARRY_PATTERNS = [
++ /^scripts\/release\/active-release(?:\.test)?\.mjs$/,
++ /^scripts\/release\/release-paths\.mjs$/,
++ /^\.github\/actions\/test-scope\/action\.yml$/,
++ /^\.github\/scripts\/test-scope-action\.test\.mjs$/,
++ /^\.github\/workflows\/ci\.yml$/,
++ /^docs\/release\.md$/,
++ /^docs\/specs\/AST-(?:017|030)\/spec\.md$/,
+@@ -718,2 +1077,159 @@ const RELEASE_OUTPUT_PATTERNS = [
+-function isReleaseOutputPath(file) {
+- return RELEASE_OUTPUT_PATTERNS.some(pattern => pattern.test(file));
++function isAncestor(root, ancestor, descendant) {
++ try {
++ execFileSync('git', ['merge-base', '--is-ancestor', ancestor, descendant], {
++ cwd: root,
++ stdio: 'ignore',
++ });
++ return true;
++ } catch {
++ return false;
++ }
++}
++
++function patchBuildsHead(root, base, head, patch) {
++ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-policy-carry-'));
++ const index = path.join(temp, 'index');
++ const env = {...process.env, GIT_INDEX_FILE: index};
++ try {
++ execFileSync('git', ['read-tree', base], {cwd: root, env, stdio: 'ignore'});
++ execFileSync(
++ 'git',
++ ['apply', '--cached', '--unidiff-zero', '--whitespace=nowarn'], {
++ cwd: root,
++ env,
++ input: patch.endsWith('\n') ? patch : `${patch}\n`,
++ stdio: ['pipe', 'ignore', 'ignore'],
++ });
++ const tree = execFileSync('git', ['write-tree'], {
++ cwd: root,
++ env,
++ encoding: 'utf8',
++ }).trim();
++ return tree === git(root, ['rev-parse', `${head}^{tree}`]);
++ } catch {
++ return false;
++ } finally {
++ fs.rmSync(temp, {recursive: true, force: true});
++ }
++}
++
++function validateReleasePolicyCarryAtRef(
++ root,
++ {base, head, source, mainRef, manifestPath, releaseBranch},
++) {
++ const errors = [];
++ const baseCommit = git(root, ['rev-parse', base]);
++ const commits = git(root, ['rev-list', `${baseCommit}..${head}`])
++ .split('\n')
++ .filter(Boolean);
++ const mergeCommits = git(root, [
++ 'rev-list',
++ '--min-parents=2',
++ `${baseCommit}..${head}`,
++ ])
++ .split('\n')
++ .filter(Boolean);
++ if (commits.length !== 1 || mergeCommits.length !== 0)
++ errors.push(
++ 'release policy carry must contain exactly one non-merge commit',
++ );
++ if (git(root, ['rev-parse', `${head}^`]) !== baseCommit)
++ errors.push('release policy carry commit must directly follow the release head');
++ if (!isAncestor(root, source, mainRef))
++ errors.push('release policy carry source is not merged on current main');
++ if (
++ !/^scripts\/release\/policy-carry\/v\d+\.\d+\.\d+\.json$/.test(manifestPath)
++ )
++ errors.push('release policy carry manifest path is invalid');
++
++ const manifest = jsonAtRef(root, source, manifestPath);
++ if (
++ manifest?.schemaVersion !== 1 ||
++ manifest.releaseBranch !== releaseBranch ||
++ manifest.base !== baseCommit ||
++ !/^scripts\/release\/policy-carry\/v\d+\.\d+\.\d+\.diff$/.test(
++ manifest?.patch ?? '',
++ ) ||
++ !/^[0-9a-f]{64}$/.test(manifest?.patchSha256 ?? '') ||
++ !manifest?.targets ||
++ Array.isArray(manifest.targets) ||
++ typeof manifest.targets !== 'object'
++ ) {
++ errors.push(
++ 'release policy carry manifest does not match this branch and base',
++ );
++ }
++
++ const targets =
++ manifest?.targets &&
++ !Array.isArray(manifest.targets) &&
++ typeof manifest.targets === 'object'
++ ? Object.entries(manifest.targets).sort(([a], [b]) => a.localeCompare(b))
++ : [];
++ for (const [file, digest] of targets) {
++ if (
++ !RELEASE_POLICY_CARRY_PATTERNS.some(pattern => pattern.test(file)) ||
++ !/^[0-9a-f]{64}$/.test(digest)
++ ) {
++ errors.push(
++ `release policy carry manifest has an invalid target: ${file}`,
++ );
++ }
++ }
++
++ const candidateEntries = git(root, [
++ 'diff',
++ '--name-status',
++ baseCommit,
++ head,
++ ])
++ .split('\n')
++ .filter(Boolean);
++ const candidateFiles = [
++ ...new Set(
++ candidateEntries.flatMap(entry => {
++ const files = diffEntryFiles(entry);
++ if (files === null) {
++ errors.push(`invalid release policy carry diff entry: ${entry}`);
++ return [];
++ }
++ return files;
++ }),
++ ),
++ ].sort();
++ const targetFiles = targets.map(([file]) => file);
++ for (const file of candidateFiles) {
++ if (!RELEASE_POLICY_CARRY_PATTERNS.some(pattern => pattern.test(file)))
++ errors.push(
++ `release policy carry contains an unauthorized path: ${file}`,
++ );
++ }
++ if (canonicalJson(candidateFiles) !== canonicalJson(targetFiles))
++ errors.push(
++ 'release policy carry file set does not match its reviewed bundle',
++ );
++
++ const candidateDigests = fileDigestsAtRef(root, head, candidateFiles);
++ for (const [file, digest] of targets) {
++ if (candidateDigests.get(file) !== digest)
++ errors.push(
++ `release policy carry file does not match its reviewed bundle: ${file}`,
++ );
++ }
++
++ const patchContent = manifest?.patch
++ ? filesAtRef(root, source, [manifest.patch]).get(manifest.patch)
++ : null;
++ const patch = patchContent?.toString('utf8') ?? '';
++ if (!patch || sha256(patchContent) !== manifest?.patchSha256)
++ errors.push(
++ 'release policy carry patch does not match its manifest digest',
++ );
++ else if (!patchBuildsHead(root, baseCommit, head, patch))
++ errors.push('release policy carry patch does not build the candidate head');
++
++ return {
++ errors,
++ files: candidateEntries.length,
++ bundleDigest: manifest ? sha256(canonicalJson(manifest)) : null,
++ };
+@@ -729,8 +1245,3 @@ function validateReleaseDiff(entries, {plan, baseChangesets} = {}) {
+- const [status, ...files] = entry.split('\t');
+- const isMove = status?.startsWith('R') || status?.startsWith('C');
+- const expectedPaths = isMove ? 2 : 1;
+- if (
+- !status ||
+- files.length !== expectedPaths ||
+- files.some(file => !file)
+- ) {
++ const [status] = entry.split('\t');
++ const files = diffEntryFiles(entry);
++ if (files === null) {
+@@ -1265,0 +1777,29 @@ async function main() {
++ if (command === 'validate-policy-carry') {
++ const base = required(values, 'base');
++ const head = required(values, 'head');
++ const source = required(values, 'source');
++ const mainRef = required(values, 'main-ref');
++ const manifestPath = required(values, 'manifest');
++ const releaseBranch = required(values, 'release-branch');
++ const result = validateReleasePolicyCarryAtRef(root, {
++ base,
++ head,
++ source,
++ mainRef,
++ manifestPath,
++ releaseBranch,
++ });
++ if (result.errors.length) throw new Error(result.errors.join('\n'));
++ console.log(
++ JSON.stringify({
++ kind: 'policy-carry',
++ base,
++ head,
++ source,
++ manifest: manifestPath,
++ files: result.files,
++ bundleDigest: result.bundleDigest,
++ }),
++ );
++ return;
++ }
+@@ -1274,7 +1814,25 @@ async function main() {
+- const errors = [
+- ...validateIdentity(marker, plan),
+- ...validateReleaseDiff(raw ? raw.split('\n') : [], {
+- plan,
+- baseChangesets: changesetMapAtRef(root, base),
+- }),
+- ];
++ const entries = raw ? raw.split('\n') : [];
++ const baseChangesets = changesetMapAtRef(root, base);
++ const kind = classifyReleaseDiff(entries);
++ let sourceCommit = null;
++ let patchId = null;
++ let diffErrors;
++ if (kind === 'test-repair') {
++ const repair = validateReleaseTestRepairAtRef(root, {
++ base,
++ head,
++ mainRef: required(values, 'main-ref'),
++ entries,
++ baseChangesets,
++ });
++ sourceCommit = repair.sourceCommit;
++ patchId = repair.patchId;
++ diffErrors = repair.errors;
++ } else if (kind === 'version-bump') {
++ diffErrors = validateReleaseDiff(entries, {plan, baseChangesets});
++ } else {
++ diffErrors = [
++ 'release candidate contains paths outside the generated version bump or test-repair classes',
++ ];
++ }
++ const errors = [...validateIdentity(marker, plan), ...diffErrors];
+@@ -1285,0 +1844 @@ async function main() {
++ kind,
+@@ -1287 +1846,2 @@ async function main() {
+- files: raw ? raw.split('\n').length : 0,
++ files: entries.length,
++ ...(sourceCommit ? {sourceCommit, patchId} : {}),
+@@ -1399,0 +1960 @@ export {
++ changedStatementsFromDiff,
+@@ -1404,0 +1966 @@ export {
++ isReleaseTestRepairPath,
+@@ -1411,0 +1974 @@ export {
++ validateReleaseTestRepair,
+diff --git a/scripts/release/release-paths.mjs b/scripts/release/release-paths.mjs
+new file mode 100644
+index 00000000000..8ede431dd48
+--- /dev/null
++++ b/scripts/release/release-paths.mjs
+@@ -0,0 +1,80 @@
++// Copyright (c) Meta Platforms, Inc. and affiliates.
++
++/**
++ * @file Shared release-branch path classification.
++ *
++ * @input git diff --name-status entries
++ * @output generated bump, test repair, or invalid release-branch classification
++ * @position trusted base policy shared by release validation and CI scope routing
++ */
++
++import fs from 'node:fs';
++
++const RELEASE_OUTPUT_PATTERNS = [
++ /^packages\/(?:[^/]+|themes\/[^/]+)\/package\.json$/,
++ /^packages\/(?:[^/]+|themes\/[^/]+)\/CHANGELOG\.md$/,
++ /^packages\/cli\/assets\/codemods\/registry\.mjs$/,
++ /^packages\/cli\/assets\/codemods\/__tests__\/registry\.test\.mjs$/,
++ /^packages\/cli\/assets\/codemods\/transforms\/(?:next|v\d+\.\d+\.\d+)\//,
++ /^pnpm-lock\.yaml$/,
++];
++
++const RELEASE_TEST_REPAIR_PATTERNS = [
++ /(?:^|\/)__tests__\//,
++ /\.(?:spec|test)\.[cm]?[jt]sx?$/,
++ /^internal\/interaction-harness\//,
++];
++
++function isReleaseOutputPath(file) {
++ return RELEASE_OUTPUT_PATTERNS.some(pattern => pattern.test(file));
++}
++
++function isReleaseTestRepairPath(file) {
++ return (
++ !file.startsWith('apps/docsite/') &&
++ !isReleaseOutputPath(file) &&
++ RELEASE_TEST_REPAIR_PATTERNS.some(pattern => pattern.test(file)) &&
++ !file.includes('/__snapshots__/') &&
++ !file.endsWith('.snap')
++ );
++}
++
++function diffEntryFiles(entry) {
++ const [status, ...files] = entry.split('\t');
++ const isMove = status?.startsWith('R') || status?.startsWith('C');
++ const expectedPaths = isMove ? 2 : 1;
++ return !status || files.length !== expectedPaths || files.some(file => !file)
++ ? null
++ : files;
++}
++
++function classifyReleaseDiff(entries) {
++ if (entries.length === 0) return 'invalid';
++ const files = entries.map(diffEntryFiles);
++ if (files.some(entryFiles => entryFiles === null)) return 'invalid';
++ const paths = files.flat();
++ if (paths.every(isReleaseTestRepairPath)) return 'test-repair';
++ if (
++ paths.every(
++ file => file.startsWith('.changeset/') || isReleaseOutputPath(file),
++ )
++ ) {
++ return 'version-bump';
++ }
++ return 'invalid';
++}
++
++if (process.argv.includes('--classify')) {
++ const entries = fs
++ .readFileSync(0, 'utf8')
++ .split('\n')
++ .filter(Boolean);
++ console.log(classifyReleaseDiff(entries));
++}
++
++export {
++ classifyReleaseDiff,
++ diffEntryFiles,
++ isReleaseOutputPath,
++ isReleaseTestRepairPath,
++};
diff --git a/scripts/release/policy-carry/v0.7.12.json b/scripts/release/policy-carry/v0.7.12.json
new file mode 100644
index 0000000000..8c87878b8e
--- /dev/null
+++ b/scripts/release/policy-carry/v0.7.12.json
@@ -0,0 +1,14 @@
+{
+ "schemaVersion": 1,
+ "releaseBranch": "release/v0.7.12",
+ "base": "b4266ddfb453e8572c4453dcef8d0470fc18545b",
+ "patch": "scripts/release/policy-carry/v0.7.12.diff",
+ "patchSha256": "b6e22ae5318fbf2b3ee4367c98875891cab47ef95a60d88a4850b5ee2d973941",
+ "targets": {
+ ".github/actions/test-scope/action.yml": "987626f51d322f0c51ac78033b075f7607fb65cf4251d56e79750acd5addd3a0",
+ ".github/scripts/test-scope-action.test.mjs": "73aafc08e00b2d76519193f3d87bc26c8d0c42a722e6d81a05fe7f27933d7172",
+ ".github/workflows/ci.yml": "237fee543e4933bc85e8bad889d3b90e3310ebbc5e0e418cb50d70f45d74dba9",
+ "scripts/release/active-release.mjs": "0306bbc3986c918b7563edb6d307e00276cdbf894c29809a406186253c0d8602",
+ "scripts/release/release-paths.mjs": "5ec851b4c242265a7b2f2daf3dbefb6bf2d8137991179bb648a06616e2bc93ae"
+ }
+}
diff --git a/scripts/release/release-paths.mjs b/scripts/release/release-paths.mjs
new file mode 100644
index 0000000000..8ede431dd4
--- /dev/null
+++ b/scripts/release/release-paths.mjs
@@ -0,0 +1,80 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Shared release-branch path classification.
+ *
+ * @input git diff --name-status entries
+ * @output generated bump, test repair, or invalid release-branch classification
+ * @position trusted base policy shared by release validation and CI scope routing
+ */
+
+import fs from 'node:fs';
+
+const RELEASE_OUTPUT_PATTERNS = [
+ /^packages\/(?:[^/]+|themes\/[^/]+)\/package\.json$/,
+ /^packages\/(?:[^/]+|themes\/[^/]+)\/CHANGELOG\.md$/,
+ /^packages\/cli\/assets\/codemods\/registry\.mjs$/,
+ /^packages\/cli\/assets\/codemods\/__tests__\/registry\.test\.mjs$/,
+ /^packages\/cli\/assets\/codemods\/transforms\/(?:next|v\d+\.\d+\.\d+)\//,
+ /^pnpm-lock\.yaml$/,
+];
+
+const RELEASE_TEST_REPAIR_PATTERNS = [
+ /(?:^|\/)__tests__\//,
+ /\.(?:spec|test)\.[cm]?[jt]sx?$/,
+ /^internal\/interaction-harness\//,
+];
+
+function isReleaseOutputPath(file) {
+ return RELEASE_OUTPUT_PATTERNS.some(pattern => pattern.test(file));
+}
+
+function isReleaseTestRepairPath(file) {
+ return (
+ !file.startsWith('apps/docsite/') &&
+ !isReleaseOutputPath(file) &&
+ RELEASE_TEST_REPAIR_PATTERNS.some(pattern => pattern.test(file)) &&
+ !file.includes('/__snapshots__/') &&
+ !file.endsWith('.snap')
+ );
+}
+
+function diffEntryFiles(entry) {
+ const [status, ...files] = entry.split('\t');
+ const isMove = status?.startsWith('R') || status?.startsWith('C');
+ const expectedPaths = isMove ? 2 : 1;
+ return !status || files.length !== expectedPaths || files.some(file => !file)
+ ? null
+ : files;
+}
+
+function classifyReleaseDiff(entries) {
+ if (entries.length === 0) return 'invalid';
+ const files = entries.map(diffEntryFiles);
+ if (files.some(entryFiles => entryFiles === null)) return 'invalid';
+ const paths = files.flat();
+ if (paths.every(isReleaseTestRepairPath)) return 'test-repair';
+ if (
+ paths.every(
+ file => file.startsWith('.changeset/') || isReleaseOutputPath(file),
+ )
+ ) {
+ return 'version-bump';
+ }
+ return 'invalid';
+}
+
+if (process.argv.includes('--classify')) {
+ const entries = fs
+ .readFileSync(0, 'utf8')
+ .split('\n')
+ .filter(Boolean);
+ console.log(classifyReleaseDiff(entries));
+}
+
+export {
+ classifyReleaseDiff,
+ diffEntryFiles,
+ isReleaseOutputPath,
+ isReleaseTestRepairPath,
+};