Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): stage the newest ancestor native-config prebuild (#3725)

Andrew Mikofalvy79000dad5451
diff --git a/.github/scripts/build-smoke-alert-payload.mjs b/.github/scripts/build-smoke-alert-payload.mjs
index 2023c5702..b76767bdf 100644
--- a/.github/scripts/build-smoke-alert-payload.mjs
+++ b/.github/scripts/build-smoke-alert-payload.mjs
@@ -107,7 +107,16 @@ export function describeBlock({ verdict, blockedBy = '' } = {}) {
return { subject: `DMG smoke ${short}`, detail, smokePassed: false };
}
-/** Re-firing the two dispatch events is the whole recovery; nothing needs repair by hand. */
+/**
+ * The command that re-fires the cascade once the cause is fixed.
+ *
+ * It is NOT a repair. The re-run reads the same immutable tag and the same repo
+ * state, so a DETERMINISTIC block fails again, identically: v0.58.10 and
+ * v0.58.11 were both refused by the native-config staging guard, and the page
+ * told the responder to re-fire a command that could never have succeeded.
+ * Transient blocks do clear on a re-fire, so the command stays — what changed is
+ * the promise around it, which now points at the cause first.
+ */
export function recoveryCommand(tag, repo = DEFAULT_REPO) {
return [
`gh api -X POST repos/${repo}/dispatches -f event_type=desktop-release`,
@@ -137,7 +146,7 @@ function bodyLines({ tag, verdict, reason, runUrl, repo, blockedBy }) {
: `*Why:* ${other} failed (${reason}).`
: `*Why:* ${reason}`,
'*State:* the GitHub Release is still a DRAFT and npm `latest` has NOT moved.',
- `*Recovery (re-fire the cascade; no manual repair needed):*\n\`${recoveryCommand(tag, repo)}\``,
+ `*Recovery (fix the cause above first — re-firing alone repairs nothing):*\n\`${recoveryCommand(tag, repo)}\``,
`*Run:* ${runUrl}`,
];
}
diff --git a/.github/scripts/build-smoke-alert-payload.test.mjs b/.github/scripts/build-smoke-alert-payload.test.mjs
index fdcb27dea..03be070f9 100644
--- a/.github/scripts/build-smoke-alert-payload.test.mjs
+++ b/.github/scripts/build-smoke-alert-payload.test.mjs
@@ -66,6 +66,18 @@ describe('alert content', () => {
expect(recoveryCommand('v9.9.9')).toContain('client_payload[release_tag]=v9.9.9');
expect(recoveryCommand('v9.9.9', 'acme/fork')).toContain('repos/acme/fork/dispatches');
});
+
+ test('recovery points at the cause instead of promising a repair-free retry', () => {
+ // v0.58.10 and v0.58.11 were both refused by a deterministic preparation
+ // guard, and the page told the responder to re-fire a command that reads the
+ // same immutable tag and the same repo state — so it could only ever fail
+ // again. The command stays (transient blocks do clear on a re-fire); the
+ // promise around it must not say the re-fire is the whole recovery.
+ const body = buildSlackPayload(base).blocks[1].text.text;
+ expect(body).toContain('*Recovery');
+ expect(body).toContain('fix the cause');
+ expect(body).not.toContain('no manual repair needed');
+ });
});
describe('a passing smoke is never rendered as a smoke failure', () => {
diff --git a/.github/scripts/point-release-plan.mjs b/.github/scripts/point-release-plan.mjs
index 2b459da37..7127a5487 100644
--- a/.github/scripts/point-release-plan.mjs
+++ b/.github/scripts/point-release-plan.mjs
@@ -27,6 +27,13 @@ import {
realGit,
runGit,
} from '../../scripts/compute-stable-version.mjs';
+import {
+ describeNoSelection,
+ listPrebuildRuns,
+ makeIsAncestor,
+ makeTreeAt,
+ selectPrebuildRun,
+} from './select-native-config-prebuild.mjs';
import { parseChangeset } from './write-back.mjs';
function refuse(code, message) {
@@ -590,12 +597,14 @@ export function guardPatchOnly({ bump }) {
/**
* Would the npm publish survive its native-config provenance check?
*
- * The publish workflow stages prebuilt native binaries from the newest
- * successful prebuild run on `main` and, on the stable path only, HARD-FAILS
- * when that run's head commit is not an ancestor of the commit being released.
- * The synthetic commit is built on the last stable, so it does not contain any
- * main commit that landed after it, and a native-config change on `main` since
- * the last stable puts the newest prebuild out of reach.
+ * The publish workflow stages prebuilt native binaries from the newest prebuild
+ * run on `main` that is BOTH contained in the commit being released and built
+ * from that commit's `packages/native-config` source, and on the stable path
+ * only it HARD-FAILS when there is no such run. The synthetic commit is built on
+ * the last stable, so a native-config change that landed on `main` since then
+ * puts the newest prebuild out of reach — but an older prebuild built from the
+ * source the synthetic commit actually carries is still a valid bundle, and the
+ * publish will find it.
*
* The reason to check it here is ordering, not novelty: that failure happens
* after the tag and the GitHub Release already exist, leaving a version users
@@ -603,29 +612,27 @@ export function guardPatchOnly({ bump }) {
* supposed to be repairing. Checking the same condition before anything is
* created turns it into a clean refusal.
*
- * An absent head sha refuses for the same reason. No successful prebuild run
- * means the publish has nothing to stage and hard-fails one branch earlier in
- * the same step.
+ * `selection` comes from the same selector the publish path runs, so the
+ * prediction and the publish cannot drift apart: an empty `headSha` is exactly
+ * the state that would refuse the cut, and its `reason` is the selector's own
+ * account of why nothing qualified.
*/
-export function guardNativeConfigProvenance({ prebuildHeadSha, syntheticSha, isAncestor }) {
- const head = String(prebuildHeadSha ?? '').trim();
+export function guardNativeConfigProvenance({ selection }) {
+ const head = String(selection?.headSha ?? '').trim();
if (head === '') {
+ const reason =
+ String(selection?.reason ?? '').trim() ||
+ 'No qualifying native-config-prebuild run found on main';
return refuse(
'native-config-drift',
- 'No successful native-config-prebuild run found on main. The stable publish stages its native ' +
- 'binaries from that run and refuses without them, so this release would fail after tagging.',
- );
- }
- if (!isAncestor(head, syntheticSha)) {
- return refuse(
- 'native-config-drift',
- `The newest native-config-prebuild commit (${head}) is not contained in the synthetic commit, so ` +
- 'packages/native-config changed on main after the last stable. The stable publish would refuse ' +
- 'to stage those binaries and fail after the tag exists. Promote through the normal stable path ' +
+ `${reason}. The stable publish stages its native binaries from that run and refuses without ` +
+ 'them, so this release would fail after tagging. Promote through the normal stable path ' +
'instead, so the release contains the native-config change its binaries were built from.',
);
}
- return pass(`native-config prebuild ${head} is contained in the synthetic commit.`);
+ return pass(
+ `native-config prebuild ${head} carries the synthetic commit's packages/native-config source.`,
+ );
}
/**
@@ -695,7 +702,7 @@ function checkGuard(trail, verdict) {
* continueApply / headSha (local only)
* io.fs.readWorktreeFile / writeWorktreeFile (local only)
* io.git.tag / pushTag (REMOTE)
- * io.gh.newestNativeConfigPrebuildHeadSha (read-only)
+ * io.gh.selectNativeConfigPrebuild (read-only)
* io.gh.createRelease / dispatch (REMOTE)
*
* The four REMOTE members are the ones a dry run must never reach. Building the
@@ -785,9 +792,7 @@ export function runPointRelease(opts, io) {
checkGuard(
guards,
guardNativeConfigProvenance({
- prebuildHeadSha: io.gh.newestNativeConfigPrebuildHeadSha(),
- syntheticSha,
- isAncestor: io.git.isAncestor,
+ selection: io.gh.selectNativeConfigPrebuild(syntheticSha),
}),
);
@@ -1168,39 +1173,24 @@ function realIo() {
pushTag: (tag) => void runGit(['push', 'origin', tag]),
},
gh: {
- newestNativeConfigPrebuildHeadSha: () => {
- // Same filters the publish path uses to pick the run it stages
- // binaries from. `--event push` is load-bearing: the prebuild workflow
- // also runs on pull_request, including external PRs against the public
- // mirror, so without it the newest green run can be unmerged source.
- const res = spawnSync(
- 'gh',
- [
- 'run',
- 'list',
- '--workflow=native-config-prebuild.yml',
- '--branch',
- 'main',
- '--event',
- 'push',
- '--status',
- 'success',
- '--limit',
- '1',
- '--json',
- 'headSha',
- '--jq',
- '.[0].headSha // empty',
- ],
- { encoding: 'utf8' },
- );
- // An unreadable answer is not an empty answer. Returning '' on an auth
- // or rate-limit failure would refuse the release naming native-config
- // drift, sending the operator to investigate a repo state that is fine.
- if (res.status !== 0) {
- throw new Error(`gh run list for native-config-prebuild failed: ${String(res.stderr || '').trim()}`);
- }
- return String(res.stdout || '').trim();
+ // The publish path's own selector, run against the synthetic commit.
+ // Sharing it is the point: this preflight exists only to predict what the
+ // publish will decide, so re-deriving the rule here is how the two drift
+ // apart and the refusal starts describing a repo state that is fine.
+ selectNativeConfigPrebuild: (syntheticSha) => {
+ // listPrebuildRuns throws on a non-zero `gh`: an unreadable answer is
+ // not an empty answer, and returning '' on an auth or rate-limit
+ // failure would refuse the release naming native-config drift.
+ const candidates = listPrebuildRuns();
+ const selection = selectPrebuildRun({
+ candidates,
+ isAncestor: makeIsAncestor(),
+ treeAt: makeTreeAt(),
+ releaseRef: syntheticSha,
+ });
+ return selection
+ ? { headSha: selection.headSha, reason: '' }
+ : { headSha: '', reason: describeNoSelection(candidates) };
},
createRelease: ({ tag, targetSha, title, draft, notes }) => {
const args = ['release', 'create', tag, '--target', targetSha, '--title', title, '--notes', notes];
diff --git a/.github/scripts/point-release-plan.test.mjs b/.github/scripts/point-release-plan.test.mjs
index b051ded3b..85bfb821e 100644
--- a/.github/scripts/point-release-plan.test.mjs
+++ b/.github/scripts/point-release-plan.test.mjs
@@ -171,48 +171,35 @@ describe('guardPatchOnly', () => {
});
describe('guardNativeConfigProvenance', () => {
- test('passes when the prebuild head is contained in the synthetic commit', () => {
+ test('passes when the selector found a qualifying prebuild run', () => {
const r = guardNativeConfigProvenance({
- prebuildHeadSha: 'prebuild',
- syntheticSha: 'synthetic',
- isAncestor: membership('prebuild'),
+ selection: { headSha: 'prebuild', reason: '' },
});
expect(r).toMatchObject({ ok: true, code: null });
+ expect(r.message).toContain('prebuild');
});
- test('refuses when the prebuild head is not contained in the synthetic commit', () => {
+ test('refuses with the selector\'s own account of why nothing qualified', () => {
+ // The reason is passed through rather than restated so the preflight and the
+ // publish describe the same repo state in the same words.
const r = guardNativeConfigProvenance({
- prebuildHeadSha: 'prebuild',
- syntheticSha: 'synthetic',
- isAncestor: membership(),
+ selection: { headSha: '', reason: 'newest green run 42 @ abc123 does not' },
});
expect(r.ok).toBe(false);
expect(r.code).toBe('native-config-drift');
- expect(r.message).toContain('native-config');
+ expect(r.message).toContain('newest green run 42 @ abc123 does not');
+ expect(r.message).toContain('after tagging');
});
- test('refuses when no successful prebuild run exists to stage from', () => {
- // An absent head sha must be diagnosed as "no run to stage from", not run
- // through the ancestry check, where the real git boundary would raise an
- // infra error on an empty rev rather than answer cleanly.
- const r = guardNativeConfigProvenance({
- prebuildHeadSha: '',
- syntheticSha: 'synthetic',
- isAncestor: membership('prebuild'),
- });
+ test('still refuses readably when the selector supplied no reason', () => {
+ const r = guardNativeConfigProvenance({ selection: { headSha: '' } });
expect(r.ok).toBe(false);
expect(r.code).toBe('native-config-drift');
- expect(r.message).toMatch(/No successful native-config-prebuild run/i);
+ expect(r.message).toMatch(/native-config-prebuild run/i);
});
- test('propagates an ancestry infra error instead of reading it as drift', () => {
- expect(() =>
- guardNativeConfigProvenance({
- prebuildHeadSha: 'THROW',
- syntheticSha: 'synthetic',
- isAncestor: membership(),
- }),
- ).toThrow(/infra error/);
+ test('treats a missing selection as "nothing qualified", not as a pass', () => {
+ expect(guardNativeConfigProvenance({}).ok).toBe(false);
});
});
@@ -519,7 +506,7 @@ describe('guard codes', () => {
guardTagFree({ tag: 'v0.32.1', tagExists: membership('v0.32.1') }),
guardDeltaMatchesFix({ mode: 'revert', addedIds: ['x'], fixChangesetIds: [] }),
guardPatchOnly({ bump: 'major' }),
- guardNativeConfigProvenance({ prebuildHeadSha: 'p', syntheticSha: 's', isAncestor: membership() }),
+ guardNativeConfigProvenance({ selection: { headSha: '', reason: 'nothing qualified' } }),
guardMainResetDeltaIds({ deltaIds: [] }),
];
expect(refusals.every((r) => r.ok === false)).toBe(true);
@@ -542,7 +529,7 @@ function makeIo(overrides = {}) {
changesets = { 'stable-sha': ['keep-a'], 'synthetic-sha': ['keep-a'] },
bumpTypes = {},
changesetContents = {},
- prebuildHeadSha = 'prebuild-sha',
+ nativeConfigSelection = { headSha: 'prebuild-sha', reason: '' },
ancestries = [['prebuild-sha', 'synthetic-sha']],
cherryPick,
revert,
@@ -628,7 +615,8 @@ function makeIo(overrides = {}) {
pushTag: () => calls.pushTag++,
},
gh: {
- newestNativeConfigPrebuildHeadSha: () => prebuildHeadSha,
+ selectNativeConfigPrebuild: () =>
+ typeof nativeConfigSelection === 'function' ? nativeConfigSelection() : nativeConfigSelection,
createRelease: (r) => {
calls.createRelease++;
releases.push(r);
@@ -942,7 +930,11 @@ describe('runPointRelease refusals', () => {
},
{ mode: 'cherry-pick', fixRefs: ['fix1'] },
],
- ['native-config-drift', { ancestries: [] }, { mode: 'revert', fixRefs: ['bad1'] }],
+ [
+ 'native-config-drift',
+ { nativeConfigSelection: { headSha: '', reason: 'newest green run 42 @ abc123 does not' } },
+ { mode: 'revert', fixRefs: ['bad1'] },
+ ],
];
test.each(cases)('refuses with %s and mutates nothing, even in a real run', (code, ioOpts, runOpts) => {
@@ -965,6 +957,26 @@ describe('runPointRelease refusals', () => {
expect(io.applied).toEqual([]);
});
+ test('an unreadable prebuild listing surfaces as an infra error, not as drift', () => {
+ // Refusing with native-config-drift on an auth or rate-limit failure would
+ // send the operator to investigate a repo state that is fine, so the
+ // selector's throw has to reach the caller intact.
+ const io = makeIo({
+ nativeConfigSelection: () => {
+ throw new Error('gh run list for native-config-prebuild failed: rate limited');
+ },
+ });
+ let thrown;
+ try {
+ runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: false }, io);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown?.message).toMatch(/rate limited/);
+ expect(thrown?.code).toBeUndefined();
+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });
+ });
+
test.each([
['cherry-pick', 'cherryPick'],
['revert', 'revert'],
diff --git a/.github/scripts/select-native-config-prebuild.mjs b/.github/scripts/select-native-config-prebuild.mjs
new file mode 100644
index 000000000..eb50579cd
--- /dev/null
+++ b/.github/scripts/select-native-config-prebuild.mjs
@@ -0,0 +1,196 @@
+// Picks the native-config prebuild run whose `.node` bundle a release may stage.
+//
+// The cross-platform binaries come from the standalone native-config-prebuild
+// workflow, which runs only when `packages/native-config/**` (or its own
+// workflow file) changes on `main`. Both publish paths — release.yml's npm cut
+// and desktop-release.yml's `prepare` — stage that bundle, and both must answer
+// the same question: which green prebuild run was built from the native-config
+// source that is actually in the commit being released?
+//
+// Extracted here (rather than inline bash, duplicated in two workflows) so the
+// answer is unit-tested, mirroring the select-beta-to-promote.mjs precedent.
+// Both workflows execute on the public mirror after a push to main, so they are
+// structurally unexercisable pre-merge — a test on the pure core is the only
+// verification this logic can get before it runs against a real release.
+// point-release-plan.mjs imports the same core for its `native-config-drift`
+// preflight, so the prediction and the publish cannot disagree.
+//
+// WHY NEWEST-ANCESTOR, NOT NEWEST. The previous implementation took the single
+// newest green run (`gh run list --limit 1`) and hard-failed a stable cut when
+// that run's commit was not an ancestor of the release commit. That inverts on
+// every stable tag cut BEFORE the most recent native-config change: the newest
+// prebuild is then a DESCENDANT of the release commit, so the ancestor test
+// fails and the release is refused even though an older prebuild built from
+// byte-identical native-config source is sitting right there. It wedged
+// v0.58.10 and v0.58.11 (2026-08-20), whose tags predate the Linux-terminal
+// change (#3648) that produced the newest prebuild; the correct bundle was the
+// 2026-07-24 run, an ancestor of both. Walking newest -> oldest and taking the
+// first ANCESTOR yields the newest prebuild at-or-before the release commit,
+// which — because the prebuild runs on every native-config change — is exactly
+// the run whose source the release ships.
+//
+// WHY THE TREE COMPARISON. Ancestry alone is necessary but not sufficient: if a
+// prebuild run FAILED for some native-config change, the newest *green* ancestor
+// is older than that change and its binaries no longer match the release's Rust
+// source. Comparing the `packages/native-config` tree object makes the guard's
+// own claim — "built from source that is actually in this release" — something
+// the code verifies rather than assumes. Trees only move forward, so when the
+// newest ancestor's tree already differs no older one can match; the walk then
+// finds nothing and the caller degrades (beta) or refuses (stable), which is the
+// honest answer when no matching bundle exists.
+
+import { spawnSync } from 'node:child_process';
+import { pathToFileURL } from 'node:url';
+
+/** Workflow whose artifacts carry the per-platform `.node` binaries. */
+const PREBUILD_WORKFLOW = 'native-config-prebuild.yml';
+
+// The operator-facing name, kept without the `.yml` so the refusal reads the way
+// it always has — these strings end up in a Slack page and a job annotation.
+const PREBUILD_NAME = 'native-config-prebuild';
+
+/** Tree compared between a candidate run's commit and the release commit. */
+const NATIVE_CONFIG_PATH = 'packages/native-config';
+
+// The prebuild is path-filtered, so green runs on main are rare (four in the
+// repo's history as of 2026-08). Thirty covers years of native-config churn at
+// the cost of one `gh run list` page.
+export const DEFAULT_CANDIDATE_LIMIT = 30;
+
+/**
+ * Pure core: the newest candidate that both descends into the release commit
+ * and carries the release's native-config source.
+ *
+ * `candidates` must be newest-first, the order `gh run list` returns.
+ * `isAncestor` and `treeAt` are the injected git boundary; `treeAt` returns
+ * null when the path or the commit is not resolvable, which is a skip rather
+ * than an error — a prebuild commit can legitimately be absent or unrelated
+ * (a descendant of the release, or a rewritten main line).
+ *
+ * Returns `{ runId, headSha }`, or null when nothing qualifies.
+ */
+export function selectPrebuildRun({ candidates = [], isAncestor, treeAt, releaseRef = 'HEAD' }) {
+ const releaseTree = treeAt(releaseRef);
+ if (releaseTree === null) return null;
+
+ for (const candidate of candidates) {
+ const runId = String(candidate?.databaseId ?? '').trim();
+ const headSha = String(candidate?.headSha ?? '').trim();
+ if (runId === '' || headSha === '') continue;
+ if (!isAncestor(headSha, releaseRef)) continue;
+ if (treeAt(headSha) !== releaseTree) continue;
+ return { runId, headSha };
+ }
+ return null;
+}
+
+/**
+ * Why nothing qualified, phrased for the operator reading the page.
+ *
+ * The newest candidate is named because it is the run they will find by hand,
+ * and "the newest one is not it" is the part that otherwise looks like a bug.
+ */
+export function describeNoSelection(candidates = []) {
+ const newest = candidates.find((c) => String(c?.headSha ?? '').trim() !== '');
+ if (!newest) {
+ return `no successful ${PREBUILD_NAME} run on main found`;
+ }
+ return (
+ `no successful ${PREBUILD_NAME} run on main carries this release's ${NATIVE_CONFIG_PATH} ` +
+ `source (newest green run ${newest.databaseId} @ ${newest.headSha} does not); ` +
+ `re-run the prebuild on a commit contained in this release`
+ );
+}
+
+/**
+ * Green prebuild runs on `main`, newest first.
+ *
+ * `--event push` and `--branch main` are load-bearing, not cosmetic: the
+ * prebuild also runs on `pull_request`, including external PRs against the
+ * public mirror, so without them a candidate could be unmerged source — a
+ * supply-chain gap for native code executed on every CLI invocation.
+ *
+ * An unreadable answer is not an empty answer, so a non-zero `gh` throws
+ * rather than silently reading as "no runs exist".
+ */
+export function listPrebuildRuns({ limit = DEFAULT_CANDIDATE_LIMIT, run = spawnSync } = {}) {
+ const res = run(
+ 'gh',
+ [
+ 'run',
+ 'list',
+ `--workflow=${PREBUILD_WORKFLOW}`,
+ '--branch',
+ 'main',
+ '--event',
+ 'push',
+ '--status',
+ 'success',
+ '--limit',
+ String(limit),
+ '--json',
+ 'databaseId,headSha',
+ ],
+ { encoding: 'utf8' },
+ );
+ if (res.status !== 0) {
+ throw new Error(
+ `gh run list for ${PREBUILD_WORKFLOW} failed: ${String(res.stderr || '').trim()}`,
+ );
+ }
+ const parsed = JSON.parse(String(res.stdout || '[]').trim() || '[]');
+ return Array.isArray(parsed) ? parsed : [];
+}
+
+/** git boundary: containment, tolerating an unresolvable commit as "no". */
+export function makeIsAncestor(run = spawnSync) {
+ return (sha, ref) =>
+ run('git', ['merge-base', '--is-ancestor', sha, ref], { encoding: 'utf8' }).status === 0;
+}
+
+/** git boundary: the `packages/native-config` tree object at a ref, or null. */
+export function makeTreeAt(run = spawnSync) {
+ return (ref) => {
+ const res = run('git', ['rev-parse', '--verify', `${ref}:${NATIVE_CONFIG_PATH}`], {
+ encoding: 'utf8',
+ });
+ if (res.status !== 0) return null;
+ const tree = String(res.stdout || '').trim();
+ return tree === '' ? null : tree;
+ };
+}
+
+/**
+ * CLI: prints `<runId>\t<headSha>` on success.
+ *
+ * A non-zero exit means "stage nothing" and carries the reason on stderr. Both
+ * callers route that into their own degrade-or-fail branch, which keeps the
+ * beta-degrades / stable-refuses split where it already lives rather than
+ * splitting the release policy across two files.
+ */
+export function main(argv = process.argv.slice(2), io = {}) {
+ const { list = listPrebuildRuns, isAncestor = makeIsAncestor(), treeAt = makeTreeAt() } = io;
+ const refFlag = argv.indexOf('--release-ref');
+ const releaseRef = refFlag === -1 ? 'HEAD' : (argv[refFlag + 1] ?? 'HEAD');
+
+ const candidates = list();
+ const selection = selectPrebuildRun({ candidates, isAncestor, treeAt, releaseRef });
+ if (!selection) {
+ return { ok: false, reason: describeNoSelection(candidates) };
+ }
+ return { ok: true, line: `${selection.runId}\t${selection.headSha}` };
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ try {
+ const result = main();
+ if (!result.ok) {
+ process.stderr.write(`${result.reason}\n`);
+ process.exit(1);
+ }
+ process.stdout.write(`${result.line}\n`);
+ } catch (err) {
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
+ process.exit(1);
+ }
+}
diff --git a/.github/scripts/select-native-config-prebuild.test.mjs b/.github/scripts/select-native-config-prebuild.test.mjs
new file mode 100644
index 000000000..8af8da926
--- /dev/null
+++ b/.github/scripts/select-native-config-prebuild.test.mjs
@@ -0,0 +1,269 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+import {
+ DEFAULT_CANDIDATE_LIMIT,
+ describeNoSelection,
+ listPrebuildRuns,
+ main,
+ makeIsAncestor,
+ makeTreeAt,
+ selectPrebuildRun,
+} from './select-native-config-prebuild.mjs';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+const workflow = (name) => readFileSync(join(REPO_ROOT, '.github', 'workflows', name), 'utf8');
+
+/**
+ * Exact bounds of a staging step: its `- name:` up to the next sibling step, so
+ * an assertion cannot run past it into a neighbouring step's shell.
+ */
+const stagingStep = (yaml) => {
+ const rest = yaml.slice(yaml.indexOf('- name: Stage native-config prebuilt binaries'));
+ const end = rest.indexOf('\n - name: ');
+ return end === -1 ? rest : rest.slice(0, end);
+};
+
+/**
+ * A commit graph as a chain, oldest first, each with the native-config tree it
+ * carries. Ancestry is index order; anything absent from the chain is an
+ * unresolvable object, which the real git boundary reports as "not an ancestor"
+ * and "no tree".
+ */
+const chainFixture = (chain) => {
+ const index = new Map(chain.map((c, i) => [c.sha, { ...c, position: i }]));
+ return {
+ isAncestor: (sha, ref) => {
+ const a = index.get(sha);
+ const b = index.get(ref);
+ return Boolean(a && b && a.position <= b.position);
+ },
+ treeAt: (ref) => index.get(ref)?.tree ?? null,
+ };
+};
+
+// The graph that wedged v0.58.10: the release tag sits behind the newest green
+// prebuild, and an older prebuild carries byte-identical native-config source.
+const RELEASE_REGRESSION = chainFixture([
+ { sha: '98556f27', tree: 'eb09e361' }, // 2026-07-24 prebuild — ancestor of the tag
+ { sha: 'b2b06a46', tree: 'eb09e361' }, // v0.58.10's commit
+ { sha: '7d5af880', tree: 'e1a1c0e4' }, // #3648 — newest prebuild, DESCENDANT of the tag
+]);
+
+const CANDIDATES_NEWEST_FIRST = [
+ { databaseId: 32317026296, headSha: '7d5af880' },
+ { databaseId: 30076077253, headSha: '98556f27' },
+];
+
+describe('selectPrebuildRun', () => {
+ test('takes the newest ANCESTOR run, not the newest run', () => {
+ expect(
+ selectPrebuildRun({
+ candidates: CANDIDATES_NEWEST_FIRST,
+ ...RELEASE_REGRESSION,
+ releaseRef: 'b2b06a46',
+ }),
+ ).toEqual({ runId: '30076077253', headSha: '98556f27' });
+ });
+
+ test('prefers the newest qualifying run when several are ancestors', () => {
+ const graph = chainFixture([
+ { sha: 'old', tree: 'T1' },
+ { sha: 'newer', tree: 'T1' },
+ { sha: 'release', tree: 'T1' },
+ ]);
+ expect(
+ selectPrebuildRun({
+ candidates: [
+ { databaseId: 2, headSha: 'newer' },
+ { databaseId: 1, headSha: 'old' },
+ ],
+ ...graph,
+ releaseRef: 'release',
+ }),
+ ).toEqual({ runId: '2', headSha: 'newer' });
+ });
+
+ test('skips an ancestor whose native-config source differs from the release', () => {
+ // The shape a FAILED intermediate prebuild leaves: the newest green ancestor
+ // predates a native-config change the release already carries, so its
+ // binaries no longer match the Rust source being shipped.
+ const graph = chainFixture([
+ { sha: 'stale', tree: 'T1' },
+ { sha: 'release', tree: 'T2' },
+ ]);
+ expect(
+ selectPrebuildRun({
+ candidates: [{ databaseId: 1, headSha: 'stale' }],
+ ...graph,
+ releaseRef: 'release',
+ }),
+ ).toBeNull();
+ });
+
+ test('returns null when only descendants exist', () => {
+ expect(
+ selectPrebuildRun({
+ candidates: [{ databaseId: 32317026296, headSha: '7d5af880' }],
+ ...RELEASE_REGRESSION,
+ releaseRef: 'b2b06a46',
+ }),
+ ).toBeNull();
+ });
+
+ test('returns null when the release ref has no native-config tree', () => {
+ expect(
+ selectPrebuildRun({
+ candidates: CANDIDATES_NEWEST_FIRST,
+ ...RELEASE_REGRESSION,
+ releaseRef: 'unknown-commit',
+ }),
+ ).toBeNull();
+ });
+
+ test('skips candidates missing an id or a head sha', () => {
+ expect(
+ selectPrebuildRun({
+ candidates: [
+ { databaseId: '', headSha: '98556f27' },
+ { databaseId: 7, headSha: '' },
+ { databaseId: 30076077253, headSha: '98556f27' },
+ ],
+ ...RELEASE_REGRESSION,
+ releaseRef: 'b2b06a46',
+ }),
+ ).toEqual({ runId: '30076077253', headSha: '98556f27' });
+ });
+
+ test('tolerates an empty candidate list', () => {
+ expect(
+ selectPrebuildRun({ candidates: [], ...RELEASE_REGRESSION, releaseRef: 'b2b06a46' }),
+ ).toBeNull();
+ });
+});
+
+describe('describeNoSelection', () => {
+ test('names the newest green run so "why not that one" is answered', () => {
+ const reason = describeNoSelection(CANDIDATES_NEWEST_FIRST);
+ expect(reason).toContain('32317026296');
+ expect(reason).toContain('7d5af880');
+ expect(reason).toContain('packages/native-config');
+ });
+
+ test('says no run exists when there are none', () => {
+ expect(describeNoSelection([])).toBe('no successful native-config-prebuild run on main found');
+ });
+});
+
+describe('git boundary', () => {
+ test('isAncestor reads a non-zero exit as "not an ancestor"', () => {
+ const isAncestor = makeIsAncestor((_cmd, args) => ({
+ status: args.includes('good') ? 0 : 1,
+ stdout: '',
+ stderr: '',
+ }));
+ expect(isAncestor('good', 'HEAD')).toBe(true);
+ expect(isAncestor('missing', 'HEAD')).toBe(false);
+ });
+
+ test('treeAt returns null for an unresolvable path', () => {
+ const treeAt = makeTreeAt(() => ({ status: 128, stdout: '', stderr: 'bad revision' }));
+ expect(treeAt('HEAD')).toBeNull();
+ });
+
+ test('treeAt trims the tree object it reports', () => {
+ const treeAt = makeTreeAt(() => ({ status: 0, stdout: 'eb09e361\n', stderr: '' }));
+ expect(treeAt('HEAD')).toBe('eb09e361');
+ });
+});
+
+describe('listPrebuildRuns', () => {
+ test('keeps the supply-chain filters that scope candidates to merged main', () => {
+ let seen = [];
+ listPrebuildRuns({
+ run: (_cmd, args) => {
+ seen = args;
+ return { status: 0, stdout: '[]', stderr: '' };
+ },
+ });
+ expect(seen).toContain('--workflow=native-config-prebuild.yml');
+ expect(seen).toContain('main');
+ expect(seen).toContain('push');
+ expect(seen).toContain('success');
+ expect(seen).toContain(String(DEFAULT_CANDIDATE_LIMIT));
+ expect(seen).toContain('databaseId,headSha');
+ });
+
+ test('walks back far enough to clear a native-config change', () => {
+ expect(DEFAULT_CANDIDATE_LIMIT).toBeGreaterThan(1);
+ });
+
+ test('throws on an unreadable answer rather than reading it as "no runs"', () => {
+ expect(() =>
+ listPrebuildRuns({ run: () => ({ status: 1, stdout: '', stderr: 'rate limited' }) }),
+ ).toThrow(/rate limited/);
+ });
+});
+
+describe('main', () => {
+ test('prints the selected run and commit, tab separated', () => {
+ expect(
+ main(['--release-ref', 'b2b06a46'], {
+ list: () => CANDIDATES_NEWEST_FIRST,
+ ...RELEASE_REGRESSION,
+ }),
+ ).toEqual({ ok: true, line: '30076077253\t98556f27' });
+ });
+
+ test('reports a reason instead of a selection when nothing qualifies', () => {
+ const result = main(['--release-ref', 'b2b06a46'], {
+ list: () => [{ databaseId: 32317026296, headSha: '7d5af880' }],
+ ...RELEASE_REGRESSION,
+ });
+ expect(result.ok).toBe(false);
+ expect(result.reason).toContain('32317026296');
+ });
+
+ test('defaults to HEAD when no ref is given', () => {
+ const graph = chainFixture([
+ { sha: 'prebuild', tree: 'T1' },
+ { sha: 'HEAD', tree: 'T1' },
+ ]);
+ expect(main([], { list: () => [{ databaseId: 9, headSha: 'prebuild' }], ...graph })).toEqual({
+ ok: true,
+ line: '9\tprebuild',
+ });
+ });
+});
+
+describe('workflow wiring', () => {
+ // Both publish paths staged binaries with the same `--limit 1` bash, and both
+ // wedged the same way. Ratcheted here so a future edit cannot reintroduce
+ // newest-run selection in either one, or quietly drop one of them.
+ for (const name of ['desktop-release.yml', 'release.yml']) {
+ test(`${name} stages through the shared selector`, () => {
+ const step = stagingStep(workflow(name));
+ expect(step).toContain('select-native-config-prebuild.mjs');
+ expect(step).not.toContain('--limit');
+ expect(step).not.toContain('merge-base');
+ });
+
+ test(`${name} runs the selector from the workflow's own commit`, () => {
+ // The checkout is the RELEASE ref, so a tag cut before the selector landed
+ // carries no copy of it. Resolving the script from $GITHUB_SHA is what
+ // makes a re-fire on such a tag run current release machinery — without
+ // it the fix only reaches tags cut after it merged, and the releases it
+ // exists to unblock stay blocked.
+ const step = stagingStep(workflow(name));
+ expect(step).toContain('$GITHUB_SHA:.github/scripts/select-native-config-prebuild.mjs');
+ expect(step).toContain('cp .github/scripts/select-native-config-prebuild.mjs');
+ });
+
+ test(`${name} still splits beta degradation from stable refusal`, () => {
+ const step = stagingStep(workflow(name));
+ expect(step).toContain('degrade_or_fail');
+ expect(step).toContain('IS_STABLE');
+ });
+ }
+});
diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml
index b0e328868..db2fca733 100644
--- a/.github/workflows/desktop-release.yml
+++ b/.github/workflows/desktop-release.yml
@@ -352,27 +352,40 @@ jobs:
exit 0
}
- # Scope to runs on `main` triggered by `push` only. The prebuild also
- # runs on `pull_request` (including from the public mirror's external
- # PRs), so without this filter the latest-green run could be an
- # unmerged branch whose Rust source is not what shipped to main — a
- # supply-chain gap for native code executed on every CLI invocation.
- run_id=$(gh run list --workflow=native-config-prebuild.yml --branch main --event push \
- --status success --limit 1 --json databaseId --jq '.[0].databaseId // empty' 2>/dev/null || true)
- if [ -z "$run_id" ]; then
- degrade_or_fail "no successful native-config-prebuild run on main found" "0/8"
+ # Which prebuild run may be staged is release policy shared with the
+ # other publish path and predicted by point-release-plan.mjs, so the
+ # selection lives in one tested script instead of three copies of this
+ # shell. It walks the green prebuild runs on `main` newest -> oldest
+ # and returns the first whose commit is contained in this release AND
+ # whose packages/native-config source matches it — the newest ANCESTOR,
+ # not the newest run. Taking the newest run refused every stable tag
+ # cut before the most recent native-config change, because that run is
+ # then a descendant of the release commit rather than an ancestor.
+ #
+ # The workflow file comes from the DEFAULT branch, but the checkout is
+ # the RELEASE ref — so for any tag cut before this selector landed, the
+ # script is simply absent from the workspace. Materialize it from the
+ # same commit the workflow itself came from, falling back to the
+ # checked-out copy. Pairing the two is what lets a re-fire on a stale
+ # tag run CURRENT release machinery rather than whatever was frozen in
+ # that tag, which is the only way re-firing a blocked release can ever
+ # clear it. fetch-depth:0 in checkout has $GITHUB_SHA.
+ selector="${RUNNER_TEMP:-/tmp}/select-native-config-prebuild.mjs"
+ if ! git show "$GITHUB_SHA:.github/scripts/select-native-config-prebuild.mjs" > "$selector" 2>/dev/null; then
+ cp .github/scripts/select-native-config-prebuild.mjs "$selector" 2>/dev/null || true
fi
-
- # Provenance: the prebuild run's head commit must be an ancestor of
- # the release commit, so the binaries staged were built from source
- # that is actually in this release. fetch-depth:0 in checkout has
- # full history.
- head_sha=$(gh run view "$run_id" --json headSha -q .headSha 2>/dev/null || true)
- if [ -z "$head_sha" ]; then
- degrade_or_fail "could not resolve head commit of native-config-prebuild run $run_id" "0/8"
+ if [ ! -s "$selector" ]; then
+ degrade_or_fail "native-config prebuild selector is missing at $GITHUB_SHA and in the release checkout" "0/8"
+ fi
+ nc_err="${RUNNER_TEMP:-/tmp}/native-config-select.err"
+ if ! selection=$(node "$selector" 2>"$nc_err"); then
+ reason=$(tr '\n' ' ' < "$nc_err" | sed 's/ *$//')
+ degrade_or_fail "${reason:-could not select a native-config prebuild run}" "0/8"
fi
- if ! git merge-base --is-ancestor "$head_sha" HEAD 2>/dev/null; then
- degrade_or_fail "native-config-prebuild run $run_id (commit $head_sha) is not an ancestor of the release commit" "0/8"
+ run_id="${selection%%$'\t'*}"
+ head_sha="${selection##*$'\t'}"
+ if [ -z "$run_id" ] || [ -z "$head_sha" ]; then
+ degrade_or_fail "native-config prebuild selector returned an unusable answer" "0/8"
fi
if ! gh run download "$run_id" --name native-config-bindings-all --dir /tmp/nc-bindings; then
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index aa6aef835..9f268b305 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -194,7 +194,7 @@ jobs:
# The cross-platform native-config `.node` binaries are produced by the
# standalone native-config-prebuild workflow (kept separate so the beta
- # cadence stays pure-JS-fast). Stage the latest successful run's bundle
+ # cadence stays pure-JS-fast). Stage the newest qualifying run's bundle
# into packages/native-config/ so the cli `build:native` step copies all
# eight platforms into dist/native/ before publish. The bundle must come
# from a prebuild run whose head commit is an ancestor of the release
@@ -234,26 +234,40 @@ jobs:
exit 0
}
- # Scope to runs on `main` triggered by `push` only. The prebuild also
- # runs on `pull_request` (including from the public mirror's external
- # PRs), so without this filter the latest-green run could be an
- # unmerged branch whose Rust source is not what shipped to main — a
- # supply-chain gap for native code executed on every CLI invocation.
- run_id=$(gh run list --workflow=native-config-prebuild.yml --branch main --event push \
- --status success --limit 1 --json databaseId --jq '.[0].databaseId // empty' 2>/dev/null || true)
- if [ -z "$run_id" ]; then
- degrade_or_fail "no successful native-config-prebuild run on main found" "0/8"
+ # Which prebuild run may be staged is release policy shared with the
+ # other publish path and predicted by point-release-plan.mjs, so the
+ # selection lives in one tested script instead of three copies of this
+ # shell. It walks the green prebuild runs on `main` newest -> oldest
+ # and returns the first whose commit is contained in this release AND
+ # whose packages/native-config source matches it — the newest ANCESTOR,
+ # not the newest run. Taking the newest run refused every stable tag
+ # cut before the most recent native-config change, because that run is
+ # then a descendant of the release commit rather than an ancestor.
+ #
+ # The workflow file comes from the DEFAULT branch, but the checkout is
+ # the RELEASE ref — so for any tag cut before this selector landed, the
+ # script is simply absent from the workspace. Materialize it from the
+ # same commit the workflow itself came from, falling back to the
+ # checked-out copy. Pairing the two is what lets a re-fire on a stale
+ # tag run CURRENT release machinery rather than whatever was frozen in
+ # that tag, which is the only way re-firing a blocked release can ever
+ # clear it. fetch-depth:0 in checkout has $GITHUB_SHA.
+ selector="${RUNNER_TEMP:-/tmp}/select-native-config-prebuild.mjs"
+ if ! git show "$GITHUB_SHA:.github/scripts/select-native-config-prebuild.mjs" > "$selector" 2>/dev/null; then
+ cp .github/scripts/select-native-config-prebuild.mjs "$selector" 2>/dev/null || true
fi
-
- # Provenance: the prebuild run's head commit must be an ancestor of the
- # release commit, so the binaries staged were built from source that is
- # actually in this release. fetch-depth:0 in checkout has full history.
- head_sha=$(gh run view "$run_id" --json headSha -q .headSha 2>/dev/null || true)
- if [ -z "$head_sha" ]; then
- degrade_or_fail "could not resolve head commit of native-config-prebuild run $run_id" "0/8"
+ if [ ! -s "$selector" ]; then
+ degrade_or_fail "native-config prebuild selector is missing at $GITHUB_SHA and in the release checkout" "0/8"
+ fi
+ nc_err="${RUNNER_TEMP:-/tmp}/native-config-select.err"
+ if ! selection=$(node "$selector" 2>"$nc_err"); then
+ reason=$(tr '\n' ' ' < "$nc_err" | sed 's/ *$//')
+ degrade_or_fail "${reason:-could not select a native-config prebuild run}" "0/8"
fi
- if ! git merge-base --is-ancestor "$head_sha" HEAD 2>/dev/null; then
- degrade_or_fail "native-config-prebuild run $run_id (commit $head_sha) is not an ancestor of the release commit" "0/8"
+ run_id="${selection%%$'\t'*}"
+ head_sha="${selection##*$'\t'}"
+ if [ -z "$run_id" ] || [ -z "$head_sha" ]; then
+ degrade_or_fail "native-config prebuild selector returned an unusable answer" "0/8"
fi
if ! gh run download "$run_id" --name native-config-bindings-all --dir /tmp/nc-bindings; then