From e6fed94f5275eb0b32dcb3b76b8170da9b69ad9b Mon Sep 17 00:00:00 2001 From: Howard Braham Date: Mon, 9 Nov 2026 12:10:08 -0800 Subject: [PATCH 1/4] fix(release/auto-changelog): stop false left-out warnings, warn when the baseline restore drops entries, and stop quietly when a newer run supersedes this one Count the earlier release changelog PR before warning about left-out PRs, warn when restoring from the baseline drops entries the release branch lists, refresh stale generated warnings on a kept PR body, end a run that the release branch moved past without failing when the push that moved it started its own run, and use the gpt-6.1-terra proofreader model. --- .github/scripts/clean-release-changelog.mts | 2 +- .../tests/clean-release-changelog.test.mts | 2 +- .../tests/update-release-changelog.test.mts | 440 ++++++++++++++++ .github/scripts/update-release-changelog.mts | 476 ++++++++++++++++-- CHANGELOG.md | 12 + 5 files changed, 897 insertions(+), 35 deletions(-) diff --git a/.github/scripts/clean-release-changelog.mts b/.github/scripts/clean-release-changelog.mts index 85686b4e..1f3e3f81 100644 --- a/.github/scripts/clean-release-changelog.mts +++ b/.github/scripts/clean-release-changelog.mts @@ -17,7 +17,7 @@ import { getEnvironmentWithoutAiKey } from './shared/environment.mts'; import { writeReport } from './shared/report.mts'; import { retry } from './shared/retry.mts'; -const MODEL = 'gpt-5.6-terra'; +const MODEL = 'gpt-6.1-terra'; const DEFAULT_BASE_URL = 'https://litellm.consensys.info'; const DEFAULT_TIMEOUT_MS = 90_000; const MAX_ATTEMPTS = 2; diff --git a/.github/scripts/tests/clean-release-changelog.test.mts b/.github/scripts/tests/clean-release-changelog.test.mts index 325c2360..9dc7bdd1 100644 --- a/.github/scripts/tests/clean-release-changelog.test.mts +++ b/.github/scripts/tests/clean-release-changelog.test.mts @@ -656,7 +656,7 @@ test('sends the pinned model with the bearer credential to chat completions', as temperature: number; messages: { content: string }[]; }; - assert.equal(body.model, 'gpt-5.6-terra'); + assert.equal(body.model, 'gpt-6.1-terra'); assert.equal(body.temperature, 0); assert.match(body.messages[1]?.content ?? '', //u); assert.doesNotMatch(JSON.stringify(body), /litellm-key/u); diff --git a/.github/scripts/tests/update-release-changelog.test.mts b/.github/scripts/tests/update-release-changelog.test.mts index 1e9ac9cf..80ed7869 100644 --- a/.github/scripts/tests/update-release-changelog.test.mts +++ b/.github/scripts/tests/update-release-changelog.test.mts @@ -7,6 +7,7 @@ import test from 'node:test'; import { assertReleaseSectionHasEntries, excludePrsCherryPickedOntoBaseline, + findEntriesDroppedByRestore, findPrsMissingFromChangelog, findReleaseVersionsContainingPrs, getAutoChangelogCli, @@ -17,13 +18,18 @@ import { getChangelogPrPresentation, getCherryPickAliasesByPr, getCherryPickedPrsByCommit, + getCallingWorkflowPath, + getDroppedEntriesWarning, getHistoricalSkippedPrNumbers, + getOpenBaselineChangelogSection, getPrsCherryPickedOntoBaseline, getUnlistedCherryPicksWarning, isReleaseSectionEmpty, hasOnlyUpdaterCommits, + hasWorkflowRunForSha, isUntouchedUnproofreadChangelogPr, parseUpdateChangelogArguments, + refreshGeneratedWarnings, shouldKeepChangelogPrPresentation, validateGeneratedReleaseSection, writeFailedProofreadingReport, @@ -668,6 +674,291 @@ test('reports PRs that no other section lists under any of their numbers', () => ); }); +test('counts a pending section of the earlier release as listing a PR', () => { + const changelog = ['## [2.0.0]', '', '- Fixed one (#1)', ''].join('\n'); + const pendingSection = [ + '## [1.0.0]', + '', + '- Fixed two (#2)', + '- Fixed three by its cherry-pick (#31)', + ].join('\n'); + + assert.deepEqual( + findPrsMissingFromChangelog({ + changelog, + pendingSections: [pendingSection], + prNumbers: ['2', '3', '4'], + aliasesByPr: new Map([['3', ['31']]]), + version: '2.0.0', + repositoryUrl: 'https://github.com/MetaMask/example', + }), + ['4'], + ); +}); + +const RELEASE_BASELINE = { + kind: 'release', + ref: 'origin/release/1.0.0', + version: '1.0.0', +} as const; + +test('reads the earlier release section from its open changelog PR', () => { + const lookups: string[][] = []; + + assert.equal( + getOpenBaselineChangelogSection({ + baseline: RELEASE_BASELINE, + determineBranch: (version) => `release-changelog/${version}`, + getSha: () => 'abc', + getOpenPrNumber: (...branches) => { + lookups.push(branches); + return '9'; + }, + readSection: (branch, version) => `${branch} ${version}`, + }), + 'release-changelog/1.0.0 1.0.0', + ); + assert.deepEqual(lookups, [['release-changelog/1.0.0', 'release/1.0.0']]); +}); + +test('ignores the earlier release changelog when no PR is open', () => { + const options = { + baseline: RELEASE_BASELINE, + determineBranch: (version: string) => `release-changelog/${version}`, + readSection: () => { + throw new Error('must not read'); + }, + }; + + assert.equal( + getOpenBaselineChangelogSection({ + ...options, + getSha: () => undefined, + getOpenPrNumber: () => '9', + }), + undefined, + ); + assert.equal( + getOpenBaselineChangelogSection({ + ...options, + getSha: () => 'abc', + getOpenPrNumber: () => undefined, + }), + undefined, + ); +}); + +test('only reads an open changelog PR for a release baseline', () => { + for (const kind of ['stable', 'target'] as const) { + assert.equal( + getOpenBaselineChangelogSection({ + baseline: { kind, ref: 'origin/stable', version: '1.0.0' }, + getSha: () => 'abc', + getOpenPrNumber: () => '9', + readSection: () => 'section', + }), + undefined, + ); + } +}); + +test('carries on when the open changelog branch lacks the section', (context) => { + context.mock.method(console, 'warn', () => undefined); + + assert.equal( + getOpenBaselineChangelogSection({ + baseline: RELEASE_BASELINE, + determineBranch: (version) => `release-changelog/${version}`, + getSha: () => 'abc', + getOpenPrNumber: () => '9', + readSection: () => { + throw new Error('Expected exactly one release heading for 1.0.0'); + }, + }), + undefined, + ); +}); + +const RELEASE_BRANCH_CHANGELOG = [ + '## [Unreleased]', + '', + '- Unreleased only (#9)', + '', + '## [2.0.0]', + '', + '### Fixed', + '', + '- Fixed one (#1)', + '- Fixed two (#2)', + ' - A sub-bullet', + '', + '## [1.0.0]', + '', + '- Fixed three (#3)', + '- Fixed four (#4)', + '', +].join('\n'); + +test('finds released entries a stale baseline restore drops', () => { + const restoredChangelog = [ + '## [2.0.0]', + '', + '- Fixed one (#1)', + '', + '## [1.0.0]', + '', + '- Fixed three (#3)', + '- Fixed four (#4)', + '', + ].join('\n'); + + assert.deepEqual( + findEntriesDroppedByRestore({ + restoredChangelog, + releaseChangelog: RELEASE_BRANCH_CHANGELOG, + }), + [{ version: '2.0.0', entryCount: 1, prNumbers: ['2'] }], + ); +}); + +test('counts an entry as dropped when only another version lists it', () => { + const restoredChangelog = [ + '## [2.0.0]', + '', + '- Fixed one (#1)', + '- Fixed two (#2)', + '- Fixed three (#3)', + '', + '## [1.0.0]', + '', + '- Fixed four (#4)', + '', + ].join('\n'); + + assert.deepEqual( + findEntriesDroppedByRestore({ + restoredChangelog, + releaseChangelog: RELEASE_BRANCH_CHANGELOG, + }), + [{ version: '1.0.0', entryCount: 1, prNumbers: ['3'] }], + ); +}); + +test('reports nothing when the restore keeps every released entry', () => { + assert.deepEqual( + findEntriesDroppedByRestore({ + restoredChangelog: `${RELEASE_BRANCH_CHANGELOG}\n## [3.0.0]\n\n- New (#5)\n`, + releaseChangelog: RELEASE_BRANCH_CHANGELOG, + }), + [], + ); +}); + +test('words the warning for entries the restore dropped', () => { + assert.equal( + getDroppedEntriesWarning('8.20.0', { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [ + { + version: '8.18.0', + entryCount: 5, + prNumbers: ['1', '2', '3', '4', '5'], + }, + { version: '8.17.0', entryCount: 1, prNumbers: ['6'] }, + ], + }), + '> Restoring the changelog from the 8.19.0 baseline dropped 6 entries that release/8.20.0 lists under earlier releases: 8.18.0 (5 entries: #1, #2, #3, +2 more); 8.17.0 (1 entry: #6). The 8.19.0 changelog may be stale for 8.20.0; fix it or merge its changelog PR first, then rerun.', + ); + assert.match( + getDroppedEntriesWarning('8.20.0', { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [{ version: '8.18.0', entryCount: 1, prNumbers: ['1'] }], + }), + /dropped 1 entry that release\/8\.20\.0 lists/u, + ); +}); + +test('does not count a reworded entry as dropped', () => { + const releaseChangelog = '## [1.0.0]\n\n- Fixed a crash (#1, #2)\n'; + assert.deepEqual( + findEntriesDroppedByRestore({ + restoredChangelog: '## [1.0.0]\n\n- Fixed the crash on launch (#2)\n', + releaseChangelog, + }), + [], + ); +}); + +test('reads long PR links when comparing dropped entries', () => { + const repositoryUrl = 'https://github.com/MetaMask/metamask-mobile'; + const link = (number: string): string => + `[#${number}](${repositoryUrl}/pull/${number})`; + const releaseChangelog = `## [1.0.0]\n\n- Fixed a crash (${link('1')})\n- Fixed a hang (${link('2')})\n`; + assert.deepEqual( + findEntriesDroppedByRestore({ + restoredChangelog: `## [1.0.0]\n\n- Fixed the crash on launch (${link('1')})\n`, + releaseChangelog, + repositoryUrl, + }), + [{ version: '1.0.0', entryCount: 1, prNumbers: ['2'] }], + ); +}); + +test('compares an entry without a PR number by its text', () => { + const releaseChangelog = '## [1.0.0]\n\n- Manual note\n'; + assert.deepEqual( + findEntriesDroppedByRestore({ + restoredChangelog: '## [1.0.0]\n\n- Other note\n', + releaseChangelog, + }), + [{ version: '1.0.0', entryCount: 1, prNumbers: [] }], + ); + assert.deepEqual( + findEntriesDroppedByRestore({ + restoredChangelog: releaseChangelog, + releaseChangelog, + }), + [], + ); +}); + +test('lists up to three dropped PRs before summarizing the rest', () => { + const warningFor = (prNumbers: string[]): string => + getDroppedEntriesWarning('8.20.0', { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [ + { version: '8.18.0', entryCount: prNumbers.length, prNumbers }, + ], + }); + assert.match(warningFor(['1', '2', '3']), /\(3 entries: #1, #2, #3\)/u); + assert.match( + warningFor(['1', '2', '3', '4']), + /\(4 entries: #1, #2, #3, \+1 more\)/u, + ); +}); + +test('adds the dropped entries warning to the PR body', () => { + const { body } = getChangelogPrPresentation({ + version: '8.20.0', + changelogBranch: 'release-changelog/8.20.0', + proofreadingStatus: 'succeeded', + droppedEntries: { + baselineVersion: '8.19.0', + releaseBranch: 'release/8.20.0', + versions: [{ version: '8.18.0', entryCount: 1, prNumbers: ['1'] }], + }, + }); + + assert.match(body, /^This PR updates the change log for 8\.20\.0\./u); + assert.match( + body, + /\n\n> Restoring the changelog from the 8\.19\.0 baseline/u, + ); +}); + test('words the warning for PRs the earlier changelog lacks', () => { assert.equal( getUnlistedCherryPicksWarning('13.56.0', { @@ -685,6 +976,155 @@ test('words the warning for PRs the earlier changelog lacks', () => { ); }); +test('removes a left-out warning that no longer holds', () => { + const existingBody = `This PR updates the change log for 8.20.0.\r\n\r\n${getUnlistedCherryPicksWarning('8.20.0', { baselineVersion: '8.19.0', prNumbers: ['1'] })}`; + assert.equal( + refreshGeneratedWarnings({ existingBody, version: '8.20.0' }), + 'This PR updates the change log for 8.20.0.', + ); +}); + +test('replaces a stale warning and keeps unrelated quotes', () => { + const kept = '> AI automation failed, not proofread.'; + const existingBody = `Intro.\n\n${kept}\n\n${getUnlistedCherryPicksWarning('8.20.0', { baselineVersion: '8.19.0', prNumbers: ['1', '2'] })}`; + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['2'], + }; + assert.equal( + refreshGeneratedWarnings({ + existingBody, + version: '8.20.0', + unlistedCherryPicks, + }), + `Intro.\n\n${kept}\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`, + ); +}); + +test('leaves a body whose warnings still hold', () => { + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['1'], + }; + const existingBody = `Intro.\n\n${getUnlistedCherryPicksWarning('8.20.0', unlistedCherryPicks)}`; + assert.equal( + refreshGeneratedWarnings({ + existingBody, + version: '8.20.0', + unlistedCherryPicks, + }), + undefined, + ); +}); + +const RUN_PATH = '.github/workflows/update-release-changelog.yml'; + +test('finds the run the moving push triggered', () => { + assert.equal( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => ['.github/workflows/other.yml', RUN_PATH], + }), + true, + ); +}); + +test('does not assume a newer run when none matches or the lookup fails', () => { + assert.equal( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => ['.github/workflows/other.yml'], + }), + false, + ); + assert.equal( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => { + throw new Error('403'); + }, + }), + false, + ); + assert.equal( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: undefined, + listRunPaths: () => [RUN_PATH], + }), + false, + ); +}); + +test('reads the calling workflow path from the workflow ref', () => { + assert.equal( + getCallingWorkflowPath({ + GITHUB_REPOSITORY: 'MetaMask/metamask-mobile', + GITHUB_WORKFLOW_REF: `MetaMask/metamask-mobile/${RUN_PATH}@refs/heads/release/8.20.0`, + }), + RUN_PATH, + ); + assert.equal(getCallingWorkflowPath({}), undefined); +}); + +const staleWarning = getUnlistedCherryPicksWarning('8.20.0', { + baselineVersion: '8.19.0', + prNumbers: ['1'], +}); + +test('keeps text written on the line after a stale warning', () => { + assert.equal( + refreshGeneratedWarnings({ + existingBody: `Intro.\n\n${staleWarning}\nChecked #1, fine.`, + version: '8.20.0', + }), + 'Intro.\n\nChecked #1, fine.', + ); +}); + +test('removes a stale warning separated by extra blank lines', () => { + assert.equal( + refreshGeneratedWarnings({ + existingBody: `Intro.\n\n\n${staleWarning}`, + version: '8.20.0', + }), + 'Intro.', + ); +}); + +test('adds a warning to an empty body without leading blank lines', () => { + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['1'], + }; + assert.equal( + refreshGeneratedWarnings({ + existingBody: '', + version: '8.20.0', + unlistedCherryPicks, + }), + staleWarning, + ); +}); + +test('leaves a CRLF body whose warning sits mid-body', () => { + const unlistedCherryPicks = { + baselineVersion: '8.19.0', + prNumbers: ['1'], + }; + assert.equal( + refreshGeneratedWarnings({ + existingBody: `Intro.\r\n\r\n${staleWarning}\r\n\r\nTrailing note.`, + version: '8.20.0', + unlistedCherryPicks, + }), + undefined, + ); +}); + const EXCLUSION_SECTION = [ '## [2.0.0]', '', diff --git a/.github/scripts/update-release-changelog.mts b/.github/scripts/update-release-changelog.mts index 53a8dc45..8390e3fb 100644 --- a/.github/scripts/update-release-changelog.mts +++ b/.github/scripts/update-release-changelog.mts @@ -55,6 +55,18 @@ type UnlistedCherryPicks = { prNumbers: readonly string[]; }; +type DroppedEntryVersion = { + version: string; + entryCount: number; + prNumbers: readonly string[]; +}; + +type DroppedEntries = { + baselineVersion: string; + releaseBranch: string; + versions: readonly DroppedEntryVersion[]; +}; + const SCRIPT_DIRECTORY = dirname(fileURLToPath(import.meta.url)); const CLEANER_PATH = resolve(SCRIPT_DIRECTORY, 'clean-release-changelog.mts'); const PROMPT_PATH = resolve( @@ -208,6 +220,80 @@ function getRemoteRefSha(ref: string): string | undefined { return getRemoteBranchSha(branch); } +/** A remote ref moved after the run read it. */ +export class RemoteRefMovedError extends Error { + readonly currentSha: string | undefined; + + constructor(message: string, currentSha: string | undefined) { + super(message); + this.name = 'RemoteRefMovedError'; + this.currentSha = currentSha; + } +} + +/** A newer run of this workflow publishes the changelog instead. */ +export class SupersededRunError extends Error { + constructor(message: string) { + super(message); + this.name = 'SupersededRunError'; + } +} + +/** + * Reports whether a run of the calling workflow already exists for a commit. + * The push that moved the release branch triggers it, so it publishes the + * changelog for that tip. A push made with `GITHUB_TOKEN` triggers no run, so + * nothing would publish and the caller must not treat this run as superseded. + * + * @param options0 - The options. + * @param options0.sha - The branch tip the push created. + * @param options0.workflowPath - The calling workflow's file path, such as + * `.github/workflows/update-release-changelog.yml`. + * @param options0.listRunPaths - Lists the workflow file paths of the runs for + * a commit; replaceable in tests. + * @returns `true` only when such a run is found; `false` when the lookup fails. + */ +export function hasWorkflowRunForSha({ + sha, + workflowPath, + listRunPaths = (commitSha) => + capture('gh', [ + 'api', + `repos/${process.env.GITHUB_REPOSITORY ?? ''}/actions/runs?head_sha=${commitSha}&per_page=100`, + '--jq', + '.workflow_runs[].path', + ]).split(/\r?\n/u), +}: { + sha: string; + workflowPath: string | undefined; + listRunPaths?: (sha: string) => string[]; +}): boolean { + if (!workflowPath) { + return false; + } + try { + return listRunPaths(sha).some((path) => path.startsWith(workflowPath)); + } catch { + return false; + } +} + +/** + * Reads the calling workflow's file path from `GITHUB_WORKFLOW_REF`. + * + * @param env - The environment; replaceable in tests. + * @returns The path, or `undefined` outside GitHub Actions. + */ +export function getCallingWorkflowPath( + env: NodeJS.ProcessEnv = process.env, +): string | undefined { + const [workflowFile] = (env.GITHUB_WORKFLOW_REF ?? '').split('@'); + const prefix = `${env.GITHUB_REPOSITORY ?? ''}/`; + return env.GITHUB_REPOSITORY && workflowFile?.startsWith(prefix) + ? workflowFile.slice(prefix.length) + : undefined; +} + /** * Throws when a remote ref moved since it was read, so stale output is never * published. @@ -228,8 +314,9 @@ export function assertRemoteRefUnchanged({ }): void { const currentSha = getRemoteRefSha(ref); if (currentSha !== expectedSha) { - throw new Error( + throw new RemoteRefMovedError( `${description} ${ref} changed during changelog generation; refusing to publish stale output`, + currentSha, ); } } @@ -284,12 +371,12 @@ function getReleaseBranches() { * * @param changelogBranch - The PR head branch. * @param releaseBranch - The PR base branch. - * @returns The PR number and title, or `undefined` when no PR is open. + * @returns The PR number, title and body, or `undefined` when no PR is open. */ function getOpenChangelogPr( changelogBranch: string, releaseBranch: string, -): { number: string; title: string } | undefined { +): { number: string; title: string; body: string } | undefined { const output = capture('gh', [ 'pr', 'list', @@ -300,18 +387,19 @@ function getOpenChangelogPr( '--state', 'open', '--json', - 'number,title', + 'number,title,body', '--jq', '.[0] // empty', ]); if (!output) { return undefined; } - const { number, title } = JSON.parse(output) as { + const { number, title, body } = JSON.parse(output) as { number: number; title: string; + body: string | null; }; - return { number: String(number), title }; + return { number: String(number), title, body: body ?? '' }; } /** @@ -657,6 +745,9 @@ export function getCherryPickAliasesByPr( * * @param options0 - The options. * @param options0.changelog - The full changelog text. + * @param options0.pendingSections - Release sections that are not in the + * changelog yet, such as the earlier release's section in its open changelog + * PR. They count like any other section. * @param options0.prNumbers - The PRs to check. * @param options0.aliasesByPr - The cherry-pick PR numbers by canonical PR. * @param options0.version - The version whose section is ignored. @@ -665,21 +756,24 @@ export function getCherryPickAliasesByPr( */ export function findPrsMissingFromChangelog({ changelog, + pendingSections = [], prNumbers, aliasesByPr, version, repositoryUrl, }: { changelog: string; + pendingSections?: readonly string[]; prNumbers: readonly string[]; aliasesByPr: ReadonlyMap; version: string; repositoryUrl: string; }): string[] { + const searchedText = [changelog, ...pendingSections].join('\n\n'); return prNumbers.filter( (prNumber) => findReleaseVersionsContainingPrs( - changelog, + searchedText, [prNumber, ...(aliasesByPr.get(prNumber) ?? [])], version, repositoryUrl, @@ -687,6 +781,62 @@ export function findPrsMissingFromChangelog({ ); } +/** + * Reads the earlier release's section from its open changelog PR. Until that + * PR merges, the release branch holds an older section, so an entry the PR + * already lists would look missing. + * + * @param options0 - The options. + * @param options0.baseline - The selected baseline. + * @param options0.determineBranch - Names the earlier release's changelog + * branch; replaceable in tests. + * @param options0.getSha - Reads a remote branch tip; replaceable in tests. + * @param options0.getOpenPrNumber - Looks up the open PR number; replaceable in + * tests. + * @param options0.readSection - Reads the release section from the changelog + * branch; replaceable in tests. + * @returns The section, or `undefined` when no such PR is open or readable. + */ +export function getOpenBaselineChangelogSection({ + baseline, + determineBranch = determineChangelogBranch, + getSha = getRemoteBranchSha, + getOpenPrNumber = getOpenChangelogPrNumber, + readSection = (branch, version) => { + execute('git', ['fetch', 'origin', branch]); + return readReleaseSectionAtRef(`origin/${branch}`, version); + }, +}: { + baseline: ChangelogBaseline; + determineBranch?: typeof determineChangelogBranch; + getSha?: typeof getRemoteBranchSha; + getOpenPrNumber?: typeof getOpenChangelogPrNumber; + readSection?: (branch: string, version: string) => string; +}): string | undefined { + // A baseline on stable or on the target has no open changelog PR to read. + if (baseline.kind !== 'release') { + return undefined; + } + + const changelogBranch = determineBranch(baseline.version); + const baselineReleaseBranch = baseline.ref.replace(/^origin\//u, ''); + try { + if ( + !getSha(changelogBranch) || + !getOpenPrNumber(changelogBranch, baselineReleaseBranch) + ) { + return undefined; + } + return readSection(changelogBranch, baseline.version); + } catch (error) { + // The PR is only extra evidence, so a failed lookup must not stop the run. + console.warn( + `Could not read ${baseline.version} from open changelog branch ${changelogBranch}: ${error instanceof Error ? error.message : String(error)}`, + ); + return undefined; + } +} + /** * Removes the entries of PRs already cherry-picked onto the baseline's branch. * An entry is removed only when all its PRs are among them. @@ -734,6 +884,111 @@ export function excludePrsCherryPickedOntoBaseline({ return { section: updatedSection, excludedPrNumbers }; } +/** + * Groups the top-level entries of each released version's section. + * + * @param changelog - The changelog text. + * @returns The trimmed entry lines by version. `Unreleased` is not included. + */ +function getEntriesByVersion(changelog: string): Map { + const entriesByVersion = new Map(); + let entries: string[] | undefined; + for (const line of splitLines(changelog)) { + const headingVersion = parseReleaseHeadingVersion(line); + if (headingVersion) { + entries = entriesByVersion.get(headingVersion) ?? []; + entriesByVersion.set(headingVersion, entries); + } else if (line.startsWith('## [')) { + entries = undefined; + } else if (entries && line.startsWith('- ')) { + entries.push(line.trim()); + } + } + return entriesByVersion; +} + +/** + * Finds the entries of released versions that the release branch lists but the + * changelog restored from the baseline lacks. Restoring replaces the whole + * file, so a stale baseline silently reverts them. An entry counts as kept + * when the restored version lists any of its PRs, so rewording is not a loss; + * an entry without a PR number must match exactly. + * + * @param options0 - The options. + * @param options0.restoredChangelog - The changelog restored from the baseline. + * @param options0.releaseChangelog - The release branch's own changelog, without + * releases newer than the target. + * @param options0.repositoryUrl - The repository's GitHub URL, so its long PR + * links count as references. + * @returns The lost entries by version, in file order. + */ +export function findEntriesDroppedByRestore({ + restoredChangelog, + releaseChangelog, + repositoryUrl, +}: { + restoredChangelog: string; + releaseChangelog: string; + repositoryUrl?: string; +}): DroppedEntryVersion[] { + const normalize = (changelog: string): string => + repositoryUrl + ? normalizeRepositoryPrLinks(changelog, repositoryUrl) + : changelog; + const restoredEntries = getEntriesByVersion(normalize(restoredChangelog)); + return [...getEntriesByVersion(normalize(releaseChangelog))].flatMap( + ([version, entries]) => { + const keptEntries = restoredEntries.get(version) ?? []; + const keptTexts = new Set(keptEntries); + const keptPrNumbers = new Set(keptEntries.flatMap(getPrNumbers)); + const dropped = entries.filter((entry) => { + const prNumbers = getPrNumbers(entry); + return prNumbers.length > 0 + ? !prNumbers.some((prNumber) => keptPrNumbers.has(prNumber)) + : !keptTexts.has(entry); + }); + if (dropped.length === 0) { + return []; + } + return [ + { + version, + entryCount: dropped.length, + prNumbers: [ + ...new Set(dropped.flatMap((entry) => getPrNumbers(entry))), + ], + }, + ]; + }, + ); +} + +/** + * Builds the PR warning for entries the baseline restore removed. + * + * @param version - The version being released. + * @param droppedEntries - The baseline and the entries it lacks. + * @returns The warning as a Markdown quote. + */ +export function getDroppedEntriesWarning( + version: string, + droppedEntries: DroppedEntries, +): string { + const { baselineVersion, releaseBranch, versions } = droppedEntries; + const count = (total: number): string => + `${total} ${total === 1 ? 'entry' : 'entries'}`; + const total = versions.reduce((sum, { entryCount }) => sum + entryCount, 0); + const summary = versions + .map(({ version: droppedVersion, entryCount, prNumbers }) => { + const shown = prNumbers.slice(0, 3).map((prNumber) => `#${prNumber}`); + const more = + prNumbers.length > 3 ? [`+${prNumbers.length - 3} more`] : []; + return `${droppedVersion} (${count(entryCount)}: ${[...shown, ...more].join(', ')})`; + }) + .join('; '); + return `> Restoring the changelog from the ${baselineVersion} baseline dropped ${count(total)} that ${releaseBranch} lists under earlier releases: ${summary}. The ${baselineVersion} changelog may be stale for ${version}; fix it or merge its changelog PR first, then rerun.`; +} + /** * Builds the PR warning for PRs left out because an earlier release's branch * has them, when that release's changelog does not list them. @@ -755,6 +1010,69 @@ export function getUnlistedCherryPicksWarning( return `> ${list} ${was} left out of ${version} because ${cherryPicks} already on the ${baselineVersion} branch, but the ${baselineVersion} changelog does not list ${pronoun}. Add an entry to the right release if one is needed.`; } +const GENERATED_WARNING_PATTERNS = [ + /^> .* left out of .* because .* already on the .* branch, but the .* changelog does not list /u, + /^> Restoring the changelog from the .* baseline dropped /u, +]; + +/** + * Rebuilds the left-out and dropped-entry warnings of an existing PR body from + * this run, so a warning that no longer holds is removed. Only whole lines + * that match a generated warning are touched; other text stays as written. + * + * @param options0 - The options. + * @param options0.existingBody - The open PR's current body. + * @param options0.version - The version being released. + * @param options0.unlistedCherryPicks - This run's left-out PRs, if any. + * @param options0.droppedEntries - This run's dropped entries, if any. + * @returns The new body, or `undefined` when it would not change. + */ +export function refreshGeneratedWarnings({ + existingBody, + version, + unlistedCherryPicks, + droppedEntries, +}: { + existingBody: string; + version: string; + unlistedCherryPicks?: UnlistedCherryPicks; + droppedEntries?: DroppedEntries; +}): string | undefined { + const wanted = [ + ...(unlistedCherryPicks + ? [getUnlistedCherryPicksWarning(version, unlistedCherryPicks)] + : []), + ...(droppedEntries + ? [getDroppedEntriesWarning(version, droppedEntries)] + : []), + ]; + const lines = existingBody.replace(/\r\n/gu, '\n').split('\n'); + const present: string[] = []; + const keptLines: string[] = []; + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index] as string; + if ( + GENERATED_WARNING_PATTERNS.some((pattern) => pattern.test(line.trim())) + ) { + present.push(line.trim()); + // Drop the blank line that separated the warning from what follows. + if (lines[index + 1] === '') { + index += 1; + } + } else { + keptLines.push(line); + } + } + if ( + present.length === wanted.length && + present.every((warning, index) => warning === wanted[index]) + ) { + return undefined; + } + const keptText = keptLines.join('\n').trimEnd(); + return [...(keptText ? [keptText] : []), ...wanted].join('\n\n'); +} + /** * Finds the other released versions whose sections mention any of the PRs. * @@ -1302,6 +1620,8 @@ export function getDeletedPrNumbers({ * cherry-picked PRs. * @param options0.unlistedCherryPicks - PRs left out of this release that the * earlier release's changelog does not list. + * @param options0.droppedEntries - Entries the baseline restore removed from + * earlier releases. * @returns The PR title and body. */ export function getChangelogPrPresentation({ @@ -1311,6 +1631,7 @@ export function getChangelogPrPresentation({ proofreadingStage, presentInVersions = [], unlistedCherryPicks, + droppedEntries, }: { version: string; changelogBranch: string; @@ -1318,6 +1639,7 @@ export function getChangelogPrPresentation({ proofreadingStage?: string; presentInVersions?: readonly string[]; unlistedCherryPicks?: UnlistedCherryPicks; + droppedEntries?: DroppedEntries; }): ChangelogPrPresentation { let title = `release: ${changelogBranch}`; let body = `This PR updates the change log for ${version}.`; @@ -1332,6 +1654,9 @@ export function getChangelogPrPresentation({ if (unlistedCherryPicks) { body = `${body}\n\n${getUnlistedCherryPicksWarning(version, unlistedCherryPicks)}`; } + if (droppedEntries) { + body = `${body}\n\n${getDroppedEntriesWarning(version, droppedEntries)}`; + } return { title, body }; } @@ -1457,6 +1782,9 @@ export function hasSameChangelogAsRemoteBranch( * @param options0.proofreadingStatus - The proofreading outcome of this run. * @param options0.replacesWholeSection - Whether this run proofread the whole * section again. + * @param options0.version - The version being released. + * @param options0.unlistedCherryPicks - This run's left-out PRs, if any. + * @param options0.droppedEntries - This run's dropped entries, if any. */ function createOrUpdateChangelogPr({ changelogBranch, @@ -1464,12 +1792,18 @@ function createOrUpdateChangelogPr({ presentation, proofreadingStatus, replacesWholeSection, + version, + unlistedCherryPicks, + droppedEntries, }: { changelogBranch: string; releaseBranch: string; presentation: ChangelogPrPresentation; proofreadingStatus: ProofreadingStatus; replacesWholeSection: boolean; + version: string; + unlistedCherryPicks?: UnlistedCherryPicks; + droppedEntries?: DroppedEntries; }): void { const existingPr = getOpenChangelogPr(changelogBranch, releaseBranch); if (existingPr) { @@ -1480,6 +1814,22 @@ function createOrUpdateChangelogPr({ replacesWholeSection, }) ) { + // The kept body may carry warnings this run no longer raises. + const refreshedBody = refreshGeneratedWarnings({ + existingBody: existingPr.body, + version, + ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), + ...(droppedEntries ? { droppedEntries } : {}), + }); + if (refreshedBody !== undefined) { + execute('gh', [ + 'pr', + 'edit', + existingPr.number, + '--body', + refreshedBody, + ]); + } return; } execute('gh', [ @@ -1528,6 +1878,8 @@ function createOrUpdateChangelogPr({ * from. * @param options0.unlistedCherryPicks - PRs left out of this release that the * earlier release's changelog does not list. + * @param options0.droppedEntries - Entries the baseline restore removed from + * earlier releases. * @param options0.assertSourcesUnchanged - Throws when a source ref moved during * the run. */ @@ -1541,6 +1893,7 @@ function commitAndPushChangelog({ markUnproofread, generatedThrough, unlistedCherryPicks, + droppedEntries, assertSourcesUnchanged, }: { version: string; @@ -1552,6 +1905,7 @@ function commitAndPushChangelog({ markUnproofread: boolean; generatedThrough: string; unlistedCherryPicks?: UnlistedCherryPicks; + droppedEntries?: DroppedEntries; assertSourcesUnchanged: () => void; }): void { const unexpectedChanges = capture('git', [ @@ -1609,6 +1963,9 @@ function commitAndPushChangelog({ releaseBranch, proofreadingStatus: proofreading.status, replacesWholeSection, + version, + ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), + ...(droppedEntries ? { droppedEntries } : {}), presentation: getChangelogPrPresentation({ version, changelogBranch, @@ -1618,6 +1975,7 @@ function commitAndPushChangelog({ ? { presentInVersions: proofreading.presentInVersions } : {}), ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), + ...(droppedEntries ? { droppedEntries } : {}), }), }); } @@ -1757,6 +2115,30 @@ function main(): void { rebuildChangelogBranch({ changelogBranch, releaseBranch, baseline }); writeChangelog(removeNewerReleases(readChangelog(), version)); + + // The restore replaces the whole file, so a stale baseline reverts entries + // that the release branch's own changelog already has. + let droppedEntries: DroppedEntries | undefined; + if (baseline.kind !== 'target') { + const versions = findEntriesDroppedByRestore({ + restoredChangelog: readChangelog(), + releaseChangelog: removeNewerReleases( + readChangelogAtRef(`origin/${releaseBranch}`), + version, + ), + repositoryUrl, + }); + if (versions.length > 0) { + droppedEntries = { + baselineVersion: baseline.version, + releaseBranch, + versions, + }; + console.warn( + getDroppedEntriesWarning(version, droppedEntries).replace(/^> /u, ''), + ); + } + } if (preservedReviewedSection) { writeChangelog( mergeCurrentReleaseSection({ @@ -1802,8 +2184,12 @@ function main(): void { skippedPrNumbers.push(...excludedPrNumbers); // A PR whose earlier changelog never listed it would vanish from both. + const openBaselineSection = getOpenBaselineChangelogSection({ + baseline, + }); const missingPrNumbers = findPrsMissingFromChangelog({ changelog: readChangelog(), + pendingSections: openBaselineSection ? [openBaselineSection] : [], prNumbers: excludedPrNumbers, aliasesByPr: cherryPickAliasesByPr, version, @@ -1902,11 +2288,27 @@ function main(): void { runChangelogValidation(proofreading, version); const assertSourcesUnchanged = () => { - assertRemoteRefUnchanged({ - ref: `origin/${releaseBranch}`, - expectedSha: targetReleaseSha, - description: 'Target release branch', - }); + try { + assertRemoteRefUnchanged({ + ref: `origin/${releaseBranch}`, + expectedSha: targetReleaseSha, + description: 'Target release branch', + }); + } catch (error) { + if ( + error instanceof RemoteRefMovedError && + error.currentSha && + hasWorkflowRunForSha({ + sha: error.currentSha, + workflowPath: getCallingWorkflowPath(), + }) + ) { + throw new SupersededRunError( + `${releaseBranch} moved to ${error.currentSha} during changelog generation. The run for that push publishes the changelog, so this run stops without publishing.`, + ); + } + throw error; + } assertRemoteRefUnchanged({ ref: baseline.ref, expectedSha: baselineSha, @@ -1921,28 +2323,36 @@ function main(): void { } }; - if (dryRun) { - // Preflight the same source snapshots used for publication, but leave all - // commits, remote branches, and pull requests unchanged. - assertSourcesUnchanged(); - console.log( - `Dry run passed for ${releaseBranch}; no commit, push, or PR update was performed.`, - ); - return; + try { + if (dryRun) { + // Preflight the same source snapshots used for publication, but leave all + // commits, remote branches, and pull requests unchanged. + assertSourcesUnchanged(); + console.log( + `Dry run passed for ${releaseBranch}; no commit, push, or PR update was performed.`, + ); + return; + } + commitAndPushChangelog({ + version, + changelogBranch, + releaseBranch, + expectedRemoteSha: changelogBranchSha, + proofreading, + replacesWholeSection: regenerateWholeSection, + markUnproofread: + proofreading.status === 'failed' && !preservedReviewedSection, + generatedThrough: targetReleaseSha, + ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), + ...(droppedEntries ? { droppedEntries } : {}), + assertSourcesUnchanged, + }); + } catch (error) { + if (!(error instanceof SupersededRunError)) { + throw error; + } + console.log(`::notice::${error.message}`); } - commitAndPushChangelog({ - version, - changelogBranch, - releaseBranch, - expectedRemoteSha: changelogBranchSha, - proofreading, - replacesWholeSection: regenerateWholeSection, - markUnproofread: - proofreading.status === 'failed' && !preservedReviewedSection, - generatedThrough: targetReleaseSha, - ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), - assertSourcesUnchanged, - }); } // Run only when executed directly, not when the tests import this module. diff --git a/CHANGELOG.md b/CHANGELOG.md index d28ce1cc..ed280af1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- Count the earlier release's open changelog PR before `update-release-changelog` warns about left-out PRs ([#309](https://github.com/MetaMask/github-tools/pull/309)) + - A PR that the earlier release branch cherry-picked is no longer reported as missing when the earlier release's open changelog PR already lists it. +- Warn in the changelog PR when restoring from the baseline drops entries that the release branch lists under earlier releases ([#309](https://github.com/MetaMask/github-tools/pull/309)) + - An entry counts as kept when the restored version lists any of its PRs, so rewording is not reported. +- Remove generated "left out" and "dropped entries" warnings from an open changelog PR body once they no longer hold ([#309](https://github.com/MetaMask/github-tools/pull/309)) + - Only whole lines that match a generated warning are removed; text a reviewer added stays. +- Stop `update-release-changelog` quietly, instead of failing, when the release branch moved during generation and the push that moved it started its own run ([#309](https://github.com/MetaMask/github-tools/pull/309)) + - That run publishes the changelog for the new tip. If no such run is found, the run still fails as before. +- Update the changelog proofreader model from `gpt-5.6-terra` to `gpt-6.1-terra` ([#309](https://github.com/MetaMask/github-tools/pull/309)) + ## [1.22.1] ### Fixed From ac2f1186838b94e36e40d35aeafe93b67003cc33 Mon Sep 17 00:00:00 2001 From: Howard Braham Date: Mon, 9 Nov 2026 12:30:16 -0800 Subject: [PATCH 2/4] fix(release/auto-changelog): wait for the superseding run to appear before deciding none exists --- .../tests/update-release-changelog.test.mts | 36 +++++++++++++++++++ .github/scripts/update-release-changelog.mts | 32 ++++++++++++++--- 2 files changed, 63 insertions(+), 5 deletions(-) diff --git a/.github/scripts/tests/update-release-changelog.test.mts b/.github/scripts/tests/update-release-changelog.test.mts index 80ed7869..6ae78cc2 100644 --- a/.github/scripts/tests/update-release-changelog.test.mts +++ b/.github/scripts/tests/update-release-changelog.test.mts @@ -1030,6 +1030,42 @@ test('finds the run the moving push triggered', () => { ); }); +test('waits for the run of the moving push to appear', () => { + const waits: number[] = []; + let lookups = 0; + assert.equal( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => { + lookups += 1; + return lookups < 3 ? [] : [RUN_PATH]; + }, + attempts: 5, + delayMs: 1000, + wait: (milliseconds) => waits.push(milliseconds), + }), + true, + ); + assert.deepEqual(waits, [1000, 1000]); +}); + +test('gives up after the last attempt without a matching run', () => { + const waits: number[] = []; + assert.equal( + hasWorkflowRunForSha({ + sha: 'abc', + workflowPath: RUN_PATH, + listRunPaths: () => [], + attempts: 3, + delayMs: 1000, + wait: (milliseconds) => waits.push(milliseconds), + }), + false, + ); + assert.deepEqual(waits, [1000, 1000]); +}); + test('does not assume a newer run when none matches or the lookup fails', () => { assert.equal( hasWorkflowRunForSha({ diff --git a/.github/scripts/update-release-changelog.mts b/.github/scripts/update-release-changelog.mts index 8390e3fb..fc6a5a35 100644 --- a/.github/scripts/update-release-changelog.mts +++ b/.github/scripts/update-release-changelog.mts @@ -251,7 +251,13 @@ export class SupersededRunError extends Error { * `.github/workflows/update-release-changelog.yml`. * @param options0.listRunPaths - Lists the workflow file paths of the runs for * a commit; replaceable in tests. - * @returns `true` only when such a run is found; `false` when the lookup fails. + * @param options0.attempts - How many lookups to make. A run appears a few + * seconds after its push, so the first lookup can miss it. + * @param options0.delayMs - The wait between lookups. + * @param options0.wait - Blocks for a number of milliseconds; replaceable in + * tests. + * @returns `true` only when such a run is found; `false` when none appears + * or the lookup fails. */ export function hasWorkflowRunForSha({ sha, @@ -263,19 +269,35 @@ export function hasWorkflowRunForSha({ '--jq', '.workflow_runs[].path', ]).split(/\r?\n/u), + attempts = 10, + delayMs = 3000, + wait = (milliseconds) => + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds), }: { sha: string; workflowPath: string | undefined; listRunPaths?: (sha: string) => string[]; + attempts?: number; + delayMs?: number; + wait?: (milliseconds: number) => unknown; }): boolean { if (!workflowPath) { return false; } - try { - return listRunPaths(sha).some((path) => path.startsWith(workflowPath)); - } catch { - return false; + for (let attempt = 1; attempt <= attempts; attempt += 1) { + try { + if (listRunPaths(sha).some((path) => path.startsWith(workflowPath))) { + return true; + } + } catch { + // A failed lookup, such as a token without read access, will not improve. + return false; + } + if (attempt < attempts) { + wait(delayMs); + } } + return false; } /** From a2754067f16622fbd2bf570677428f5acefc42ca Mon Sep 17 00:00:00 2001 From: Howard Braham Date: Mon, 9 Nov 2026 12:37:48 -0800 Subject: [PATCH 3/4] test(release/auto-changelog): stub the wait in the no-matching-run test --- .github/scripts/tests/update-release-changelog.test.mts | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/scripts/tests/update-release-changelog.test.mts b/.github/scripts/tests/update-release-changelog.test.mts index 6ae78cc2..2847a9ac 100644 --- a/.github/scripts/tests/update-release-changelog.test.mts +++ b/.github/scripts/tests/update-release-changelog.test.mts @@ -1072,6 +1072,7 @@ test('does not assume a newer run when none matches or the lookup fails', () => sha: 'abc', workflowPath: RUN_PATH, listRunPaths: () => ['.github/workflows/other.yml'], + wait: () => undefined, }), false, ); From 0fae804cc472153b47cb326c2322bfc1d8d18c90 Mon Sep 17 00:00:00 2001 From: Howard Braham Date: Mon, 9 Nov 2026 14:00:07 -0800 Subject: [PATCH 4/4] fix(release/auto-changelog): refresh PR warnings when already in sync --- .github/scripts/update-release-changelog.mts | 59 ++++++++++++++++---- 1 file changed, 47 insertions(+), 12 deletions(-) diff --git a/.github/scripts/update-release-changelog.mts b/.github/scripts/update-release-changelog.mts index fc6a5a35..9defff80 100644 --- a/.github/scripts/update-release-changelog.mts +++ b/.github/scripts/update-release-changelog.mts @@ -1794,6 +1794,41 @@ export function hasSameChangelogAsRemoteBranch( } } +/** + * Edits an open changelog PR's body so its generated warnings match this run, + * keeping everything else. The body may carry warnings this run no longer + * raises. + * + * @param options0 - The options. + * @param options0.existingPr - The open changelog PR. + * @param options0.existingPr.number - Its number. + * @param options0.existingPr.body - Its body. + * @param options0.version - The version being released. + * @param options0.unlistedCherryPicks - This run's left-out PRs, if any. + * @param options0.droppedEntries - This run's dropped entries, if any. + */ +function refreshPrBodyWarnings({ + existingPr, + version, + unlistedCherryPicks, + droppedEntries, +}: { + existingPr: { number: string; body: string }; + version: string; + unlistedCherryPicks?: UnlistedCherryPicks; + droppedEntries?: DroppedEntries; +}): void { + const refreshedBody = refreshGeneratedWarnings({ + existingBody: existingPr.body, + version, + ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), + ...(droppedEntries ? { droppedEntries } : {}), + }); + if (refreshedBody !== undefined) { + execute('gh', ['pr', 'edit', existingPr.number, '--body', refreshedBody]); + } +} + /** * Edits the open changelog PR, or creates a draft one when none is open. * @@ -1836,22 +1871,12 @@ function createOrUpdateChangelogPr({ replacesWholeSection, }) ) { - // The kept body may carry warnings this run no longer raises. - const refreshedBody = refreshGeneratedWarnings({ - existingBody: existingPr.body, + refreshPrBodyWarnings({ + existingPr, version, ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), ...(droppedEntries ? { droppedEntries } : {}), }); - if (refreshedBody !== undefined) { - execute('gh', [ - 'pr', - 'edit', - existingPr.number, - '--body', - refreshedBody, - ]); - } return; } execute('gh', [ @@ -1966,6 +1991,16 @@ function commitAndPushChangelog({ ]); } else { console.log('Changelog branch and release branch are already in sync.'); + // An open PR may still carry warnings that no longer hold. + const openPr = getOpenChangelogPr(changelogBranch, releaseBranch); + if (openPr) { + refreshPrBodyWarnings({ + existingPr: openPr, + version, + ...(unlistedCherryPicks ? { unlistedCherryPicks } : {}), + ...(droppedEntries ? { droppedEntries } : {}), + }); + } return; }