From 7067a15386569fe9d34183c1218e182ed236c478 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 3 Nov 2026 08:28:54 +0000 Subject: [PATCH 1/3] Add release-slack-summaries action for Zaps 596 and 597 Port the daily release blocker and release-validation Slack summaries into a composite action. Jira stays read-only, GitHub tokens are supplied by the caller, and dry-run stays on unless a caller turns it off. Co-authored-by: Victor Pinto --- .eslintrc.js | 9 + .../release-slack-summaries/action.yml | 136 +++++ .../release-slack-summaries/adapter.test.mjs | 127 +++++ .../fixtures/build-comment.html | 3 + .../fixtures/jira-issues.json | 78 +++ .../fixtures/release-pr-body.md | 11 + .../fixtures/topology.json | 42 ++ .../release-slack-summaries/gates.test.mjs | 187 +++++++ .../release-slack-summaries/jira.test.mjs | 129 +++++ .../release-slack-summaries/lib/adapter.mjs | 81 +++ .../lib/contributing-teams.mjs | 91 ++++ .../release-slack-summaries/lib/craft-596.mjs | 145 ++++++ .../release-slack-summaries/lib/craft-597.mjs | 373 ++++++++++++++ .../release-slack-summaries/lib/gates.mjs | 60 +++ .../release-slack-summaries/lib/jira.mjs | 174 +++++++ .../lib/release-pr.mjs | 102 ++++ .../release-slack-summaries/lib/releases.mjs | 64 +++ .../release-slack-summaries/lib/teams.mjs | 110 ++++ .../release-slack-summaries/messages.test.mjs | 385 ++++++++++++++ .../release-slack-summaries/releases.test.mjs | 129 +++++ .../actions/release-slack-summaries/run.mjs | 468 ++++++++++++++++++ CHANGELOG.md | 6 + package.json | 2 +- 23 files changed, 2911 insertions(+), 1 deletion(-) create mode 100644 .github/actions/release-slack-summaries/action.yml create mode 100644 .github/actions/release-slack-summaries/adapter.test.mjs create mode 100644 .github/actions/release-slack-summaries/fixtures/build-comment.html create mode 100644 .github/actions/release-slack-summaries/fixtures/jira-issues.json create mode 100644 .github/actions/release-slack-summaries/fixtures/release-pr-body.md create mode 100644 .github/actions/release-slack-summaries/fixtures/topology.json create mode 100644 .github/actions/release-slack-summaries/gates.test.mjs create mode 100644 .github/actions/release-slack-summaries/jira.test.mjs create mode 100644 .github/actions/release-slack-summaries/lib/adapter.mjs create mode 100644 .github/actions/release-slack-summaries/lib/contributing-teams.mjs create mode 100644 .github/actions/release-slack-summaries/lib/craft-596.mjs create mode 100644 .github/actions/release-slack-summaries/lib/craft-597.mjs create mode 100644 .github/actions/release-slack-summaries/lib/gates.mjs create mode 100644 .github/actions/release-slack-summaries/lib/jira.mjs create mode 100644 .github/actions/release-slack-summaries/lib/release-pr.mjs create mode 100644 .github/actions/release-slack-summaries/lib/releases.mjs create mode 100644 .github/actions/release-slack-summaries/lib/teams.mjs create mode 100644 .github/actions/release-slack-summaries/messages.test.mjs create mode 100644 .github/actions/release-slack-summaries/releases.test.mjs create mode 100644 .github/actions/release-slack-summaries/run.mjs diff --git a/.eslintrc.js b/.eslintrc.js index d8fef75a..68b24a64 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -45,6 +45,15 @@ module.exports = { }, }, + { + files: ['.github/actions/release-slack-summaries/**/*.mjs'], + // The composite action passes inputs through the environment, same as + // the scripts under .github/scripts. + rules: { + 'n/no-process-env': 'off', + }, + }, + { files: ['.github/scripts/**/*.test.mts'], rules: { diff --git a/.github/actions/release-slack-summaries/action.yml b/.github/actions/release-slack-summaries/action.yml new file mode 100644 index 00000000..de21f650 --- /dev/null +++ b/.github/actions/release-slack-summaries/action.yml @@ -0,0 +1,136 @@ +name: Release Slack summaries +description: >- + Posts the daily release blocker summary (Zap 596) or release validation + summary (Zap 597) to Slack. Jira is read-only. The caller passes short-lived + GitHub tokens from `.github/actions/get-token`; this action does not mint + tokens. Dry-run defaults to true and writes the message to the job summary. + The release PR checklist is rewritten only when allow-pr-write is true and + dry-run is false. + +inputs: + mode: + description: 'blocker-summary (Zap 596) or release-validation (Zap 597).' + required: true + platform: + description: 'extension or mobile.' + required: true + github-token: + description: >- + Short-lived token for the client repository (pull_requests: write, or + read for blocker-summary). Obtained by the caller via get-token. + required: true + planning-token: + description: >- + Short-lived contents: read token for MetaMask/MetaMask-planning + (topology.json). Obtained by the caller via get-token. + required: true + slack-bot-token: + description: Existing SLACK_BOT_TOKEN secret. Used only when dry-run is false. + required: true + jira-base-url: + description: Jira site origin. Read-only search. + required: false + default: https://consensyssoftware.atlassian.net + jira-email: + description: >- + Atlassian account email for the read-only Jira token (POC secret + JIRA_EMAIL in the release-notifications environment). + required: true + jira-api-token: + description: >- + Read-only Jira API token (POC secret JIRA_API_TOKEN). Never written back + to Jira. + required: true + jira-release-blocker-jql: + description: >- + Base JQL for release blockers. The saved filter is not created yet: leave + this empty and the step logs OPEN and skips the blocker section. Per + release the action appends AND cf[14565] = "V". + required: false + default: '' + jira-regression-jql: + description: >- + Optional base JQL for Found-in regressions. Empty uses the v10 proposal + default (issuetype = Bug, project in the §4 list) and the action appends + AND cf[16946] = "V". OPEN until the field id and project list are confirmed. + required: false + default: '' + topology-jira-project-field: + description: >- + topology.json field holding Jira project keys. PROPOSED name jiraProject + (array or string). OPEN until the schema change lands. Missing keys do + not guess a team. + required: false + default: jiraProject + test-channel: + description: >- + When set, post only to this channel. Real release channels are not used. + required: false + default: '' + dry-run: + description: >- + Default true. Build the Slack message and any PR-body diff into the job + summary. Post nothing and write nothing. + required: false + default: 'true' + allow-pr-write: + description: >- + Default false. Zap 597 rewrites the release PR checklist only when this + is true and dry-run is false. Blocker summary never writes. + required: false + default: 'false' + github-tools-repository: + description: Repository that contains this action. Defaults to the action repository. + required: false + default: ${{ github.action_repository }} + github-tools-ref: + description: Git ref of github-tools to check out. Defaults to the current action ref. + required: false + default: ${{ github.action_ref }} + +runs: + using: composite + steps: + - name: Checkout GitHub tools repository + uses: actions/checkout@v6 + with: + repository: ${{ inputs.github-tools-repository }} + ref: ${{ inputs.github-tools-ref }} + path: ./github-tools + + - name: Set up Node.js + uses: actions/setup-node@v6 + with: + node-version-file: ./github-tools/.nvmrc + cache-dependency-path: ./github-tools/yarn.lock + cache: yarn + + - name: Enable Corepack + shell: bash + run: corepack enable + working-directory: ./github-tools + + - name: Install dependencies + working-directory: ./github-tools + shell: bash + run: yarn --immutable + + - name: Post release Slack summaries + working-directory: ./github-tools + shell: bash + env: + MODE: ${{ inputs.mode }} + PLATFORM: ${{ inputs.platform }} + GITHUB_TOKEN: ${{ inputs.github-token }} + PLANNING_TOKEN: ${{ inputs.planning-token }} + SLACK_BOT_TOKEN: ${{ inputs.slack-bot-token }} + JIRA_BASE_URL: ${{ inputs.jira-base-url }} + JIRA_EMAIL: ${{ inputs.jira-email }} + JIRA_API_TOKEN: ${{ inputs.jira-api-token }} + JIRA_RELEASE_BLOCKER_JQL: ${{ inputs.jira-release-blocker-jql }} + JIRA_REGRESSION_JQL: ${{ inputs.jira-regression-jql }} + TOPOLOGY_JIRA_PROJECT_FIELD: ${{ inputs.topology-jira-project-field }} + TEST_CHANNEL: ${{ inputs.test-channel }} + DRY_RUN: ${{ inputs.dry-run }} + ALLOW_PR_WRITE: ${{ inputs.allow-pr-write }} + run: node .github/actions/release-slack-summaries/run.mjs diff --git a/.github/actions/release-slack-summaries/adapter.test.mjs b/.github/actions/release-slack-summaries/adapter.test.mjs new file mode 100644 index 00000000..fbaef27c --- /dev/null +++ b/.github/actions/release-slack-summaries/adapter.test.mjs @@ -0,0 +1,127 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { describe, it } from 'node:test'; + +import { jiraIssueToRcBug, mergeJiraIssues } from './lib/adapter.mjs'; +import { indexTeams } from './lib/teams.mjs'; + +const BROWSE = 'https://consensyssoftware.atlassian.net'; + +/** + * Reads one fixture shipped with this action. + * + * @param {string} name - Fixture file name. + * @returns {string} File contents. + */ +function fixture(name) { + return readFileSync(new URL(`./fixtures/${name}`, import.meta.url), 'utf8'); +} + +describe('jiraIssueToRcBug', () => { + it('maps an open unassigned issue and omits the team label when none is known', () => { + const bug = jiraIssueToRcBug( + { + key: 'PRED-4', + fields: { + summary: 'Unmapped project blocker', + assignee: null, + project: { key: 'PRED' }, + status: { statusCategory: { key: 'new' } }, + }, + }, + { teamLabel: undefined, inBlockersSet: true, browseBaseUrl: BROWSE }, + ); + + assert.deepEqual(bug, { + key: 'PRED-4', + projectKey: 'PRED', + name: 'Unmapped project blocker', + url: 'https://consensyssoftware.atlassian.net/browse/PRED-4', + closed: 'false', + assigneesLength: 0, + labels: ['release-blocker'], + }); + }); + + it('marks Done issues closed and keeps a single team label', () => { + const bug = jiraIssueToRcBug( + { + key: 'CEUX-3', + fields: { + summary: 'Closed regression', + assignee: { displayName: 'Cy' }, + project: { key: 'CEUX' }, + status: { statusCategory: { key: 'done' } }, + }, + }, + { + teamLabel: 'team-extension-platform', + inBlockersSet: false, + browseBaseUrl: `${BROWSE}/`, + }, + ); + + assert.equal(bug.closed, 'true'); + assert.equal(bug.assigneesLength, 1); + assert.deepEqual(bug.labels, ['team-extension-platform']); + assert.equal( + bug.url, + 'https://consensyssoftware.atlassian.net/browse/CEUX-3', + ); + }); +}); + +describe('mergeJiraIssues', () => { + it('dedupes by key and adds release-blocker only for the blocker set', () => { + const issues = JSON.parse(fixture('jira-issues.json')); + const { projectToLabel } = indexTeams( + JSON.parse(fixture('topology.json')), + 'jiraProject', + ); + const bugs = mergeJiraIssues(issues.regressions, issues.blockers, { + teamLabelFor: (projectKey) => projectToLabel[projectKey], + browseBaseUrl: BROWSE, + }); + + assert.deepEqual( + bugs.map((bug) => bug.key), + ['ASSETS-1', 'ASSETS-2', 'DSYS-9', 'PRED-4', 'CEUX-3'], + ); + const login = bugs.find((bug) => bug.key === 'ASSETS-1'); + assert.deepEqual(login.labels, [ + 'team-extension-platform', + 'release-blocker', + ]); + assert.equal(login.closed, 'false'); + assert.equal(login.assigneesLength, 0); + const icon = bugs.find((bug) => bug.key === 'ASSETS-2'); + assert.deepEqual(icon.labels, ['team-extension-platform']); + assert.equal(bugs.find((bug) => bug.key === 'PRED-4').projectKey, 'PRED'); + assert.equal(bugs.find((bug) => bug.key === 'CEUX-3').closed, 'true'); + }); + + it('keeps a blocker that the regression search did not return', () => { + const bugs = mergeJiraIssues( + [], + [ + { + key: 'SWAPS-1', + fields: { + summary: 'Swap halt', + assignee: { displayName: 'Dee' }, + project: { key: 'SWAPS' }, + status: { statusCategory: { key: 'indeterminate' } }, + }, + }, + ], + { + teamLabelFor: () => undefined, + browseBaseUrl: BROWSE, + }, + ); + + assert.equal(bugs.length, 1); + assert.deepEqual(bugs[0].labels, ['release-blocker']); + assert.equal(bugs[0].projectKey, 'SWAPS'); + }); +}); diff --git a/.github/actions/release-slack-summaries/fixtures/build-comment.html b/.github/actions/release-slack-summaries/fixtures/build-comment.html new file mode 100644 index 00000000..0e42baf7 --- /dev/null +++ b/.github/actions/release-slack-summaries/fixtures/build-comment.html @@ -0,0 +1,3 @@ +

Builds ready for testing.

+

chrome

+

firefox

diff --git a/.github/actions/release-slack-summaries/fixtures/jira-issues.json b/.github/actions/release-slack-summaries/fixtures/jira-issues.json new file mode 100644 index 00000000..e14b92e3 --- /dev/null +++ b/.github/actions/release-slack-summaries/fixtures/jira-issues.json @@ -0,0 +1,78 @@ +{ + "regressions": [ + { + "key": "ASSETS-1", + "fields": { + "summary": "Login crash", + "assignee": null, + "project": { "key": "ASSETS" }, + "status": { "statusCategory": { "key": "indeterminate" } } + } + }, + { + "key": "ASSETS-2", + "fields": { + "summary": "Icon glitch", + "assignee": { "displayName": "Ada" }, + "project": { "key": "ASSETS" }, + "status": { "statusCategory": { "key": "indeterminate" } } + } + }, + { + "key": "DSYS-9", + "fields": { + "summary": "Token icon blocks sign-off", + "assignee": { "displayName": "Bea" }, + "project": { "key": "DSYS" }, + "status": { "statusCategory": { "key": "indeterminate" } } + } + }, + { + "key": "PRED-4", + "fields": { + "summary": "Unmapped project blocker", + "assignee": null, + "project": { "key": "PRED" }, + "status": { "statusCategory": { "key": "new" } } + } + }, + { + "key": "CEUX-3", + "fields": { + "summary": "Closed regression", + "assignee": { "displayName": "Cy" }, + "project": { "key": "CEUX" }, + "status": { "statusCategory": { "key": "done" } } + } + } + ], + "blockers": [ + { + "key": "ASSETS-1", + "fields": { + "summary": "Login crash", + "assignee": null, + "project": { "key": "ASSETS" }, + "status": { "statusCategory": { "key": "indeterminate" } } + } + }, + { + "key": "DSYS-9", + "fields": { + "summary": "Token icon blocks sign-off", + "assignee": { "displayName": "Bea" }, + "project": { "key": "DSYS" }, + "status": { "statusCategory": { "key": "indeterminate" } } + } + }, + { + "key": "PRED-4", + "fields": { + "summary": "Unmapped project blocker", + "assignee": null, + "project": { "key": "PRED" }, + "status": { "statusCategory": { "key": "new" } } + } + } + ] +} diff --git a/.github/actions/release-slack-summaries/fixtures/release-pr-body.md b/.github/actions/release-slack-summaries/fixtures/release-pr-body.md new file mode 100644 index 00000000..5a4ce382 --- /dev/null +++ b/.github/actions/release-slack-summaries/fixtures/release-pr-body.md @@ -0,0 +1,11 @@ +## Summary + +Testing plan: https://docs.google.com/spreadsheets/d/SHEETID/edit?gid=99#gid=99 + +# Team sign-off checklist + +- [x] Mobile Platform +- [ ] Extension Platform +- [x] QA Team + +Follow the checklist before release. diff --git a/.github/actions/release-slack-summaries/fixtures/topology.json b/.github/actions/release-slack-summaries/fixtures/topology.json new file mode 100644 index 00000000..8c5486cc --- /dev/null +++ b/.github/actions/release-slack-summaries/fixtures/topology.json @@ -0,0 +1,42 @@ +{ + "team-extension-platform": { + "name": "Extension Platform team", + "slackHandle": { + "releaseContact": "@release-contact-extension-platform" + }, + "githubLabel": { + "name": "team-extension-platform" + }, + "jiraProject": ["ASSETS"] + }, + "team-mobile-platform": { + "name": "Mobile Platform team", + "slackHandle": { + "releaseContact": "@release-contact-mobile-platform" + }, + "githubLabel": { + "name": "team-mobile-platform" + }, + "jiraProject": "MOBILE" + }, + "team-design-system": { + "name": "Design System team", + "slackHandle": { + "releaseContact": "@release-contact-design-system" + }, + "githubLabel": { + "name": "team-design-system" + }, + "jiraProject": ["DSYS"] + }, + "team-qa": { + "name": "QA Team", + "slackHandle": { + "releaseContact": "@release-contact-qa" + }, + "githubLabel": { + "name": "team-qa" + }, + "jiraProject": ["QA"] + } +} diff --git a/.github/actions/release-slack-summaries/gates.test.mjs b/.github/actions/release-slack-summaries/gates.test.mjs new file mode 100644 index 00000000..07b431ad --- /dev/null +++ b/.github/actions/release-slack-summaries/gates.test.mjs @@ -0,0 +1,187 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { describe, it } from 'node:test'; +import { parse } from 'yaml'; + +import { + isDryRun, + isPrWriteAllowed, + postChannel, + shouldWriteReleasePr, +} from './lib/gates.mjs'; +import { indexTeams } from './lib/teams.mjs'; +import { readConfig } from './run.mjs'; + +/** + * Builds a config object using the safe defaults. + * + * @param {object} [overrides] - Env overrides. + * @returns {object} Parsed config. + */ +function config(overrides = {}) { + return readConfig({ + MODE: 'blocker-summary', + PLATFORM: 'extension', + GITHUB_TOKEN: 'github', + PLANNING_TOKEN: 'planning', + SLACK_BOT_TOKEN: 'slack', + JIRA_EMAIL: 'victor@example.com', + JIRA_API_TOKEN: 'jira', + ...overrides, + }); +} + +describe('safe defaults', () => { + it('dry-run is on and PR writes are off unless the caller opts in', () => { + assert.equal(isDryRun(undefined), true); + assert.equal(isDryRun(''), true); + assert.equal(isDryRun('true'), true); + assert.equal(isDryRun('false'), false); + assert.equal(isDryRun('FALSE'), false); + assert.equal(isPrWriteAllowed(undefined), false); + assert.equal(isPrWriteAllowed('false'), false); + assert.equal(isPrWriteAllowed('yes'), false); + assert.equal(isPrWriteAllowed('true'), true); + + const defaults = config(); + assert.equal(defaults.dryRun, true); + assert.equal(defaults.allowPrWrite, false); + assert.equal(defaults.jiraReleaseBlockerJql, ''); + assert.equal(defaults.topologyJiraProjectField, 'jiraProject'); + assert.equal( + defaults.jiraBaseUrl, + 'https://consensyssoftware.atlassian.net', + ); + assert.equal( + shouldWriteReleasePr({ + mode: 'release-validation', + dryRun: defaults.dryRun, + allowPrWrite: defaults.allowPrWrite, + }), + false, + ); + assert.equal( + shouldWriteReleasePr({ + mode: 'release-validation', + dryRun: false, + allowPrWrite: false, + }), + false, + ); + assert.equal( + shouldWriteReleasePr({ + mode: 'blocker-summary', + dryRun: false, + allowPrWrite: true, + }), + false, + ); + assert.equal( + shouldWriteReleasePr({ + mode: 'release-validation', + dryRun: false, + allowPrWrite: true, + }), + true, + ); + }); + + it('posts only to the test channel when one is set', () => { + assert.equal( + postChannel('release-extension-13-53-0', ''), + 'release-extension-13-53-0', + ); + assert.equal( + postChannel('release-extension-13-53-0', '#release-summary-test'), + '#release-summary-test', + ); + }); +}); + +describe('topology jira projects', () => { + it('reads an array or a string and does not invent keys that are absent', () => { + const topology = JSON.parse( + readFileSync( + new URL('./fixtures/topology.json', import.meta.url), + 'utf8', + ), + ); + const indexed = indexTeams(topology, 'jiraProject'); + assert.equal(indexed.projectToLabel.ASSETS, 'team-extension-platform'); + assert.equal(indexed.projectToLabel.MOBILE, 'team-mobile-platform'); + assert.equal(indexed.projectToLabel.DSYS, 'team-design-system'); + assert.equal(indexed.projectToLabel.PRED, undefined); + assert.deepEqual(indexed.teams['team-qa'].jiraProjects, ['QA']); + assert.equal(indexed.warnings.length, 0); + + const unnamed = indexTeams(topology, ''); + assert.deepEqual(unnamed.projectToLabel, {}); + }); + + it('keeps the first team when two teams claim one project', () => { + const indexed = indexTeams( + { + a: { + name: 'A team', + githubLabel: { name: 'team-a' }, + slackHandle: { releaseContact: '@a' }, + jiraProject: ['ASSETS'], + }, + b: { + name: 'B team', + githubLabel: { name: 'team-b' }, + slackHandle: { releaseContact: '@b' }, + jiraProject: ['ASSETS'], + }, + }, + 'jiraProject', + ); + assert.equal(indexed.projectToLabel.ASSETS, 'team-a'); + assert.equal(indexed.warnings.length, 1); + }); +}); + +describe('action.yml', () => { + it('exposes the shared interface and the safe defaults', () => { + const action = parse( + readFileSync(new URL('./action.yml', import.meta.url), 'utf8'), + ); + assert.equal(action.runs.using, 'composite'); + const { inputs } = action; + for (const name of [ + 'mode', + 'platform', + 'github-token', + 'planning-token', + 'slack-bot-token', + 'jira-base-url', + 'jira-email', + 'jira-api-token', + 'jira-release-blocker-jql', + 'test-channel', + 'dry-run', + 'allow-pr-write', + ]) { + assert.ok(inputs[name], `missing input ${name}`); + } + assert.equal(inputs['dry-run'].default, 'true'); + assert.equal(inputs['allow-pr-write'].default, 'false'); + assert.equal( + inputs['jira-base-url'].default, + 'https://consensyssoftware.atlassian.net', + ); + assert.equal(inputs['jira-release-blocker-jql'].default, ''); + assert.equal(inputs['test-channel'].default, ''); + const runStep = action.runs.steps.find((step) => + String(step.run || '').includes('release-slack-summaries/run.mjs'), + ); + assert.ok(runStep); + const inputExpr = (name) => ['$', '{', '{ inputs.', name, ' }}'].join(''); + assert.equal(runStep.env.DRY_RUN, inputExpr('dry-run')); + assert.equal(runStep.env.ALLOW_PR_WRITE, inputExpr('allow-pr-write')); + assert.equal( + runStep.env.JIRA_RELEASE_BLOCKER_JQL, + inputExpr('jira-release-blocker-jql'), + ); + }); +}); diff --git a/.github/actions/release-slack-summaries/jira.test.mjs b/.github/actions/release-slack-summaries/jira.test.mjs new file mode 100644 index 00000000..3cff44eb --- /dev/null +++ b/.github/actions/release-slack-summaries/jira.test.mjs @@ -0,0 +1,129 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { + DEFAULT_REGRESSION_JQL_BASE, + buildBlockerJql, + buildRegressionJql, + projectScopedJql, + searchJiraIssues, + usesDefaultRegressionJql, +} from './lib/jira.mjs'; + +describe('JQL builders', () => { + it('skips blockers when the filter JQL is empty and appends the release number when it is set', () => { + assert.equal(buildBlockerJql('13.53.0', ''), null); + assert.equal(buildBlockerJql('13.53.0', ' '), null); + assert.equal( + buildBlockerJql('13.53.0', 'filter = 12345'), + 'filter = 12345 AND cf[14565] = "13.53.0"', + ); + }); + + it('uses the proposal regression JQL until a caller overrides it', () => { + assert.equal(usesDefaultRegressionJql(''), true); + const jql = buildRegressionJql('13.53.1', ''); + assert.equal( + jql, + `${DEFAULT_REGRESSION_JQL_BASE} AND cf[16946] = "13.53.1"`, + ); + assert.match(jql, /project in \(MUL, ASSETS,/u); + assert.equal( + buildRegressionJql('8.19.0', 'project = ASSETS'), + 'project = ASSETS AND cf[16946] = "8.19.0"', + ); + }); + + it('refuses to interpolate a release number that is not X.Y.Z', () => { + assert.throws(() => buildBlockerJql('latest', 'filter = 1'), /unexpected/u); + assert.throws(() => buildRegressionJql('13.53', ''), /unexpected/u); + }); + + it('scopes a team link by one project or by project in (...)', () => { + assert.equal(projectScopedJql('filter = 1', []), 'filter = 1'); + assert.equal( + projectScopedJql('filter = 1', ['ASSETS']), + 'filter = 1 AND project = ASSETS', + ); + assert.equal( + projectScopedJql('filter = 1', ['ASSETS', 'CEUX']), + 'filter = 1 AND project in (ASSETS, CEUX)', + ); + }); +}); + +describe('searchJiraIssues', () => { + it('follows nextPageToken and stops on the last page', async () => { + const seen = []; + const fetchImpl = async (url, options) => { + const body = JSON.parse(options.body); + seen.push({ url, body, authorization: options.headers.Authorization }); + if (!body.nextPageToken) { + return { + ok: true, + json: async () => ({ + issues: [{ key: 'ASSETS-1' }], + nextPageToken: 'page-2', + isLast: false, + }), + }; + } + return { + ok: true, + json: async () => ({ + issues: [{ key: 'ASSETS-2' }], + isLast: true, + }), + }; + }; + + const issues = await searchJiraIssues({ + baseUrl: 'https://consensyssoftware.atlassian.net/', + email: 'victor@example.com', + apiToken: 'secret-token', + jql: 'issuetype = Bug', + fetchImpl, + }); + + assert.deepEqual( + issues.map((issue) => issue.key), + ['ASSETS-1', 'ASSETS-2'], + ); + assert.equal(seen.length, 2); + assert.equal( + seen[0].url, + 'https://consensyssoftware.atlassian.net/rest/api/3/search/jql', + ); + assert.equal(seen[0].body.method, undefined); + assert.equal(seen[0].body.jql, 'issuetype = Bug'); + assert.deepEqual(seen[0].body.fields, [ + 'summary', + 'assignee', + 'project', + 'status', + ]); + assert.equal(seen[1].body.nextPageToken, 'page-2'); + assert.match(seen[0].authorization, /^Basic /u); + assert.doesNotMatch(seen[0].authorization, /secret-token/u); + }); + + it('throws the status without the token when Jira rejects the search', async () => { + const fetchImpl = async () => ({ + ok: false, + status: 401, + text: async () => 'auth failed secret-token', + }); + + await assert.rejects( + () => + searchJiraIssues({ + baseUrl: 'https://consensyssoftware.atlassian.net', + email: 'victor@example.com', + apiToken: 'secret-token', + jql: 'issuetype = Bug', + fetchImpl, + }), + /Jira search failed \(401\): auth failed/u, + ); + }); +}); diff --git a/.github/actions/release-slack-summaries/lib/adapter.mjs b/.github/actions/release-slack-summaries/lib/adapter.mjs new file mode 100644 index 00000000..b1356adf --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/adapter.mjs @@ -0,0 +1,81 @@ +/** + * Turns Jira issues into the bug shape Zap 596/597 crafting already expects. + * MCRM-155 §5.4. This is the only new mapping; message text stays in the craft + * modules. + */ + +const RELEASE_BLOCKER_LABEL = 'release-blocker'; + +/** + * Maps one Jira issue into the Zap bug shape. + * + * @param {object} issue - Jira issue from `/rest/api/3/search/jql`. + * @param {object} options - Mapping options. + * @param {string | undefined} options.teamLabel - Topology label for `project.key`, if any. + * @param {boolean} options.inBlockersSet - Whether this key was returned by the blocker search. + * @param {string} options.browseBaseUrl - Jira site origin. + * @returns {object} Zap bug. `closed` is the string `"true"` or `"false"`. + */ +export function jiraIssueToRcBug( + issue, + { teamLabel, inBlockersSet, browseBaseUrl }, +) { + const fields = issue.fields ?? {}; + const projectKey = fields.project?.key; + const statusCategoryKey = fields.status?.statusCategory?.key; + const base = browseBaseUrl.replace(/\/$/u, ''); + const labels = [ + teamLabel, + inBlockersSet ? RELEASE_BLOCKER_LABEL : undefined, + ].filter(Boolean); + + return { + key: issue.key, + // Kept off `labels` so an unmapped project key cannot collide with a + // topology label. Zap 597 reads it only for the registry fallback line. + projectKey: projectKey || '', + name: fields.summary, + url: `${base}/browse/${issue.key}`, + closed: String(statusCategoryKey === 'done'), + assigneesLength: fields.assignee ? 1 : 0, + labels, + }; +} + +/** + * Union of the regression search and the blocker search, one bug per issue key. + * A key present in both sets is a blocker. + * + * @param {object[]} regressions - Found-in search results. + * @param {object[]} blockers - Blocker search results. Empty when the filter is OPEN. + * @param {object} options - Mapping options. + * @param {Function} options.teamLabelFor - Registry lookup from project key to label. + * @param {string} options.browseBaseUrl - Jira site origin. + * @returns {object[]} Zap bugs. + */ +export function mergeJiraIssues( + regressions, + blockers, + { teamLabelFor, browseBaseUrl }, +) { + const byKey = new Map(); + for (const issue of regressions) { + byKey.set(issue.key, { issue, inBlockersSet: false }); + } + for (const issue of blockers) { + const existing = byKey.get(issue.key); + if (existing) { + existing.inBlockersSet = true; + } else { + byKey.set(issue.key, { issue, inBlockersSet: true }); + } + } + + return [...byKey.values()].map(({ issue, inBlockersSet }) => + jiraIssueToRcBug(issue, { + teamLabel: teamLabelFor(issue.fields?.project?.key), + inBlockersSet, + browseBaseUrl, + }), + ); +} diff --git a/.github/actions/release-slack-summaries/lib/contributing-teams.mjs b/.github/actions/release-slack-summaries/lib/contributing-teams.mjs new file mode 100644 index 00000000..e07e7fe0 --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/contributing-teams.mjs @@ -0,0 +1,91 @@ +/** + * Zap 597 no longer reads the Release Progress Tracker sheet. + * Contributing teams are the sign-off checklist lines (MCRM-155 597-4), + * mapped to topology labels with the same name/label match the crafting + * script uses. A line with no match is passed through unchanged so the + * script's "not in team registry" sentence still appears. + */ + +const TEAM_CHECKLIST_SECTION = + /(?:# Team sign-off checklist|## ✅ Team Sign-Off Checklist)[\s\S]*?\n([\s\S]+?)\n\s*\n/u; + +/** + * First Google Sheets URL in the pull request body. + * OPEN (597-4): assumed to be the Testing Plan link. Wording in the Slack + * message is unchanged. + * + * @param {string} releasePrBody - Pull request body. + * @returns {string} URL, or empty when none is present. + */ +export function extractTestingPlanLink(releasePrBody) { + const match = (releasePrBody || '').match( + /https:\/\/docs\.google\.com\/spreadsheets\/[^\s)>]+/u, + ); + if (!match) { + return ''; + } + return match[0].replace(/[.,]$/u, ''); +} + +/** + * Escapes a team name for a literal regular expression. + * + * @param {string} value - Topology name or label interpolated into a RegExp. + * @returns {string} Escaped literal. + */ +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&'); +} + +/** + * Inverse of the Zap's sign-off match: display name (`name` with the first + * `" team"` removed) or the github label, case-insensitive. The longest + * match wins so a shorter name cannot claim a longer checklist line. + * + * @param {string} line - One checklist line. + * @param {object} teams - Topology map keyed by github label. + * @returns {string | null} Label, or null when nothing matches. + */ +function matchTeamLabel(line, teams) { + let best = null; + let bestLength = -1; + for (const [label, team] of Object.entries(teams)) { + const display = team?.name?.replace(' team', '') || label; + const byName = new RegExp(`- \\[([ xX])\\] ${escapeRegExp(display)}`, 'iu'); + const byLabel = new RegExp(`- \\[([ xX])\\] ${escapeRegExp(label)}`, 'iu'); + if (byName.test(line) || byLabel.test(line)) { + const length = Math.max(display.length, label.length); + if (length > bestLength) { + best = label; + bestLength = length; + } + } + } + return best; +} + +/** + * Reads checklist lines and maps them to topology labels. + * + * @param {string} releasePrBody - Pull request body. + * @param {object} teams - Topology map keyed by github label. + * @returns {string[]} Labels in checklist order. Unknown lines are the raw text. + */ +export function contributingTeamLabels(releasePrBody, teams) { + const match = (releasePrBody || '').match(TEAM_CHECKLIST_SECTION); + const section = match ? match[1].trim() : ''; + const lines = section + .split('\n') + .filter((line) => line.trim().startsWith('- [')); + const labels = []; + for (const line of lines) { + const name = line.replace(/^- \[[xX ]\]\s*/u, '').trim(); + if (name) { + const label = matchTeamLabel(line, teams) ?? name; + if (!labels.includes(label)) { + labels.push(label); + } + } + } + return labels; +} diff --git a/.github/actions/release-slack-summaries/lib/craft-596.mjs b/.github/actions/release-slack-summaries/lib/craft-596.mjs new file mode 100644 index 00000000..354b55a2 --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/craft-596.mjs @@ -0,0 +1,145 @@ +/** + * Zap 596 Slack message (release blocker summary). + * + * Port of `zaps/main/release-blocker-notification-automation/scripts/slack-message-crafting.js` + * at metamask-zaps@dc70d6792cbaf9d99f39982868baf7f090dea0af. + * Message text is unchanged. `inputData` is the function argument. + * The platform branch keys off the code repository (MCRM-155 C3). + * `release_epic_url` was read by the Zap and never used, so it is not an argument. + */ + +/** + * Builds the Zap 596 Slack message. + * + * @param {object} input - Zap inputData, as arguments. + * @param {object} input.teams - `githubLabel.name` → `{ name, contact }`. + * @param {string} input.releaseVersion - `X.Y.Z` from the release ref. Not guessed. + * @param {string} input.githubRepo - `metamask-extension` or `metamask-mobile`. + * @param {object[]} input.rcBugs - Adapter output. `closed` is `"true"` / `"false"`. + * @returns {object} Slack fields the Zap wrote to `output`. + */ +export function craftBlockerSummary({ + teams, + releaseVersion, + githubRepo, + rcBugs: rawRcBugs, +}) { + const teamLabels = Object.keys(teams); + + const rcBugs = rawRcBugs + .map((bug) => { + return { + ...bug, + closed: bug?.closed?.toLowerCase() === 'true', + assigneesLength: Number(bug.assigneesLength), + }; + }) + .filter((bug) => !bug?.name?.includes('Bug Report')); + + const blockers = rcBugs.filter((bug) => { + return bug.labels.includes('release-blocker'); + }); + const openBlockers = blockers.filter((blocker) => !blocker.closed); + + const nonBlockers = rcBugs.filter((bug) => { + return !bug.labels.includes('release-blocker'); + }); + const openNonBlockers = nonBlockers.filter((blocker) => !blocker.closed); + + let platform; + let platformIcon; + let releaseOwner; + if (githubRepo?.toLowerCase() === 'metamask-extension') { + platform = 'Extension'; + platformIcon = ':electric_plug:'; + releaseOwner = '@release-owner-extension'; + } else if (githubRepo?.toLowerCase() === 'metamask-mobile') { + platform = 'Mobile'; + platformIcon = ':iphone:'; + releaseOwner = '@release-owner-mobile'; + } else { + throw new Error(`Shall never happen: unknown platform (${githubRepo})`); + } + + const findTeamLabels = (bug) => { + return bug.labels.filter((label) => teamLabels.includes(label)); + }; + + const craftTeamResponsible = (bug) => { + let teamName = ''; + let teamContact = ''; + const bugTeamLabels = findTeamLabels(bug); + bugTeamLabels.forEach((label) => { + if (teamName) { + teamName += ', '; + } + if (teamContact) { + teamContact += ' '; + } + teamName += teams[label]?.name; + teamContact += teams[label]?.contact; + }); + + if (bugTeamLabels?.length > 1) { + teamName += '(:warning: more than 1 team assigned to this bug)'; + } + + return { + name: teamName || ' Issue needs a team label :hi_wave:', + contact: teamContact || ' Issue needs a team label :hi_wave:', + }; + }; + + const craftBugsList = (bugs) => { + let bugsList = ''; + + if (bugs.length > 0) { + bugs.forEach((bug) => { + const teamResponsible = craftTeamResponsible(bug); + const assigneeWarning = + bug.assigneesLength < 1 ? ' Issue needs an assignee :hi_wave:' : ''; + + bugsList += `• <${bug?.url}|${bug?.name}>,${teamResponsible?.contact}${assigneeWarning}\n`; + }); + bugsList += `\n`; + } + return bugsList; + }; + + const slackMessageTitle = `${platform} release bug summary for v${releaseVersion}\n\n`; + + let slackMessage = `*Date:* ${new Date().toLocaleDateString('en-US', { + month: 'long', + day: 'numeric', + year: 'numeric', + })}\n\n`; + + if (openBlockers.length > 0) { + slackMessage += `:stop: *Release Blockers* :stop:\n\n*Important:* All release blockers must be resolved before release sign-off.\n\n`; + slackMessage += craftBugsList(openBlockers); + } + + if (openNonBlockers.length > 0) { + slackMessage += `:warning: *Release regressions* :warning:\n\n*Note:* All teams should do their best to resolve release regressions before release sign-off.\n\n`; + slackMessage += craftBugsList(openNonBlockers); + } + + if (rcBugs.length === 0) { + slackMessage += `:white_check_mark: *No remaining bugs* :white_check_mark:\n\n`; + } + + slackMessage += `${releaseOwner}`; + + const slackThread = `*${platform} v${releaseVersion}* :thread:`; + const slackChannelName = `release-${platform.toLocaleLowerCase()}-${releaseVersion.replaceAll('.', '-')}`; + + return { + platform, + slackChannelName, + slackThreadWithoutBold: slackThread.replace(/\*/gu, ''), + slackThread, + slackMessage, + slackMessageIcon: platformIcon, + slackMessageTitle, + }; +} diff --git a/.github/actions/release-slack-summaries/lib/craft-597.mjs b/.github/actions/release-slack-summaries/lib/craft-597.mjs new file mode 100644 index 00000000..a33b9ffc --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/craft-597.mjs @@ -0,0 +1,373 @@ +/** + * Zap 597 Slack message (release validation) and the release PR checklist rewrite. + * + * Port of `zaps/main/release-sign-off-notification-automation/scripts/slack-message-crafting.js` + * at metamask-zaps@dc70d6792cbaf9d99f39982868baf7f090dea0af. + * Message text is unchanged except the values MCRM-155 names: + * Release Cut is the argument (the runner passes the PR `created_at`); + * `testingPlanLink` is the PR-body Sheets URL; blocker links are Jira JQL + * (597-8); cc handles are the Slack user ids from the v3 posts (597-10). + * The sheet id / gid inputs are gone with the sheet read. + * + * `updatedReleasePrBody` is set only when the checklist text changes. That is + * the code path. The Zapier path-B condition ("Does not exist") reads oddly + * and stays OPEN; the runner writes only when this function returns a body. + */ + +import { jiraIssuesUrl, projectScopedJql } from './jira.mjs'; + +/** + * Escapes a team name for a literal regular expression. + * + * @param {string} value - Team name or label placed in a RegExp. + * @returns {string} Literal pattern. + */ +function escapeRegExp(value) { + return value.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&'); +} + +/** + * Builds the Zap 597 Slack message and the checklist rewrite. + * + * @param {object} input - Zap inputs that still apply, plus the Jira URL pieces. + * @param {object} input.teams - Topology map. `jiraProjects` is read for per-team JQL. + * @param {string} input.platform - `Extension` or `Mobile`. + * @param {string} input.releaseVersion - `X.Y.Z`. + * @param {string[]} input.contributingTeamLabels - Checklist labels, in order. + * @param {string} input.releasePrUrl - Release pull request URL. + * @param {string} input.releasePrBody - Release pull request body. + * @param {string} input.releaseDownloadUrl1 - Chrome (Extension) build URL. + * @param {string} input.releaseDownloadUrl2 - Firefox (Extension) build URL. + * @param {string} input.releaseEpicCreatedAt - Pull request `created_at`. + * @param {object[]} input.rcBugs - Adapter output. + * @param {string | null} input.blockerJql - Per-release blocker JQL, or null when OPEN. + * @param {string} input.jiraBaseUrl - Jira site origin. + * @param {string} input.testingPlanLink - Sheets URL from the PR body. + * @returns {object} Slack fields plus `updatedReleasePrBody` when the checklist changed. + */ +export function craftReleaseValidation({ + teams, + platform, + releaseVersion, + contributingTeamLabels, + releasePrUrl, + releasePrBody, + releaseDownloadUrl1, + releaseDownloadUrl2, + releaseEpicCreatedAt, + rcBugs: rawRcBugs, + blockerJql, + jiraBaseUrl, + testingPlanLink, +}) { + const teamLabels = Object.keys(teams); + + const teamLabelsToIgnore = [ + 'team-external-contributor', + 'team-dev-ops', + 'team-qa', + 'team-bot', + 'unknown', + ]; + const contributingTeams = [ + ...new Set( + (contributingTeamLabels ?? []) + .map((label) => String(label).trim()) + .filter(Boolean), + ), + ].filter((label) => !teamLabelsToIgnore.includes(label)); + const nonContributingTeamsWithBlockersAssigned = []; + // Blocker projects with no topology team. Shown with the registry sentence + // (597-9). They are not "non-contributing teams", so they do not get that + // extra sheet bullet. They are still appended to the checklist as + // `- [ ] {KEY}` because the rewrite has no team name to use (OPEN until + // `jiraProject` is filled in). + const unmappedBlockerLabels = []; + + const rcBugs = rawRcBugs + .map((bug) => { + return { + ...bug, + closed: bug?.closed?.toLowerCase() === 'true', + }; + }) + .filter((bug) => !bug?.name?.includes('Bug Report')); + + const blockers = rcBugs.filter((bug) => { + return bug.labels.includes('release-blocker'); + }); + const openBlockersCount = blockers?.filter( + (blocker) => !blocker.closed, + )?.length; + + const formatDate = ( + dateString, + options = { month: 'short', day: '2-digit' }, + ) => { + const date = new Date(dateString); + return date.toLocaleDateString('en-US', options); + }; + + const addDays = (dateString, days) => { + const date = new Date(dateString); + date.setDate(date.getDate() + days); + return date.toISOString(); + }; + + const releaseBlockerUrl = blockerJql + ? jiraIssuesUrl(jiraBaseUrl, blockerJql) + : ''; + + let platformIcon; + let cherryPickTrackerUrl; + let buildType1; + let buildType2; + let timeBetweenTwoReleases; + if (platform === 'Extension') { + platformIcon = ':electric_plug:'; + cherryPickTrackerUrl = `https://app.runway.team/dashboard/org/org_4tzZCk2L/app/metamask-extension-react-native-ota/releases/${releaseVersion}/step/featureReadiness/summary?sort=codeLastUpdated`; + buildType1 = 'chrome'; + buildType2 = 'firefox'; + timeBetweenTwoReleases = 7; + } else if (platform === 'Mobile') { + platformIcon = ':iphone:'; + cherryPickTrackerUrl = `https://app.runway.team/dashboard/org/org_4tzZCk2L/app/metamask-blockchain-wall-ios3/releases/${releaseVersion}/step/featureReadiness/summary?sort=codeLastUpdated`; + buildType1 = 'ios'; + buildType2 = 'android'; + timeBetweenTwoReleases = 7; + } else { + throw new Error(`Shall never happen: unknown platform (${platform})`); + } + + const releaseCutDate = releaseEpicCreatedAt + ? formatDate(releaseEpicCreatedAt) + : 'Unknown Date'; + const releaseSubmissionDeadlineDate = releaseEpicCreatedAt + ? formatDate(addDays(releaseEpicCreatedAt, timeBetweenTwoReleases)) + : 'Unknown Date'; + + const teamBlockers = {}; + blockers.forEach((bug) => { + const knownLabels = bug.labels.filter( + (label) => label !== 'release-blocker' && teamLabels.includes(label), + ); + knownLabels.forEach((label) => { + if (!teamBlockers[label]) { + teamBlockers[label] = []; + } + teamBlockers[label].push(bug); + + if ( + !contributingTeams.includes(label) && + !nonContributingTeamsWithBlockersAssigned.includes(label) + ) { + nonContributingTeamsWithBlockersAssigned.push(label); + } + }); + + if (knownLabels.length === 0 && bug.projectKey) { + const label = bug.projectKey; + if (!teamBlockers[label]) { + teamBlockers[label] = []; + } + teamBlockers[label].push(bug); + if ( + !contributingTeams.includes(label) && + !unmappedBlockerLabels.includes(label) + ) { + unmappedBlockerLabels.push(label); + } + } + }); + + const signOffLabels = [ + ...contributingTeams, + ...nonContributingTeamsWithBlockersAssigned, + ...unmappedBlockerLabels, + ]; + + const teamSignOffs = {}; + const teamChecklistSectionMatch = (releasePrBody || '').match( + /(?:# Team sign-off checklist|## ✅ Team Sign-Off Checklist)[\s\S]*?\n([\s\S]+?)\n\s*\n/u, + ); + const teamChecklistSection = teamChecklistSectionMatch + ? teamChecklistSectionMatch[1].trim() + : ''; + + const missingTeamsInChecklistSection = []; + signOffLabels.forEach((teamLabel) => { + const teamDisplayName = + teams[teamLabel]?.name?.replace(' team', '') || teamLabel; + // Names are escaped so a parenthesis in a checklist label cannot throw. + // The Zap interpolated them raw; current topology names have no metacharacters. + const teamLabelRegex1 = new RegExp( + `- \\[([ xX])\\] ${escapeRegExp(teamDisplayName)}`, + 'iu', + ); + const teamLabelRegex2 = new RegExp( + `- \\[([ xX])\\] ${escapeRegExp(teamLabel)}`, + 'iu', + ); + const match1 = teamChecklistSection.match(teamLabelRegex1); + const match2 = teamChecklistSection.match(teamLabelRegex2); + + if ( + (match1 && match1[1].toLowerCase() === 'x') || + (match2 && match2[1].toLowerCase() === 'x') + ) { + teamSignOffs[teamLabel] = true; + } else if (match1 || match2) { + teamSignOffs[teamLabel] = false; + } else { + teamSignOffs[teamLabel] = false; + missingTeamsInChecklistSection.push(`- [ ] ${teamDisplayName}`); + } + }); + + let updatedReleasePrBody; + if (teamChecklistSectionMatch) { + const existingChecklistItems = teamChecklistSection + .split('\n') + .filter((line) => line.trim().startsWith('- [')); + const allChecklistItems = [ + ...existingChecklistItems, + ...missingTeamsInChecklistSection, + ]; + const sortedChecklistItems = allChecklistItems.sort((itemA, itemB) => { + const teamNameA = itemA + .replace(/^- \[[xX ]\]\s*/u, '') + .trim() + .toLowerCase(); + const teamNameB = itemB + .replace(/^- \[[xX ]\]\s*/u, '') + .trim() + .toLowerCase(); + return teamNameA.localeCompare(teamNameB); + }); + const updatedTeamChecklistSection = sortedChecklistItems.join('\n'); + + if (updatedTeamChecklistSection !== teamChecklistSection) { + updatedReleasePrBody = releasePrBody.replace( + /(?:# Team sign-off checklist|## ✅ Team Sign-Off Checklist)[\s\S]*?\n([\s\S]+?)\n\s*\n/u, + `# Team sign-off checklist\n${updatedTeamChecklistSection}\n\n`, + ); + } + } + + const slackMessageTitle = `${platform} ${releaseVersion} Release Validation`; + + let slackMessage = ` + +*Current Release Summary* + +Dates: +• Release Cut: *${releaseCutDate}* +• Deadline Date for Release Submission: *${releaseSubmissionDeadlineDate}*`; + + if (releaseDownloadUrl1 && releaseDownloadUrl2) { + slackMessage += ` + +Latest builds available for testing: +• <${releaseDownloadUrl1}|${buildType1}> +• <${releaseDownloadUrl2}|${buildType2}>`; + } + + slackMessage += ` + +Useful links: +• <${releasePrUrl}|Release PR on GitHub> +• <${testingPlanLink}|Testing Plan & Progress Tracker on Google Sheets> +• +• <${cherryPickTrackerUrl}|Cherry-Pick Tracker on Runway>`; + + // Blocker bullet is the Zap's last useful-link line. It is omitted when the + // saved filter JQL is empty (interface: skip the blocker section, log OPEN). + if (releaseBlockerUrl) { + slackMessage += ` +• <${releaseBlockerUrl}|${openBlockersCount} ${openBlockersCount === 1 ? 'Release Blocker' : 'Release Blockers'}>`; + } + + slackMessage += ` + +Teams sign off:\n\n`; + + let stopSlackMessage = ''; + let redSlackMessage = ''; + let greenSlackMessage = ''; + for (const team of signOffLabels) { + let teamSlackMessage = ''; + const teamName = teams[team]?.name?.replace(' team', ''); + const teamSignOffContact = teams[team]?.contact || ''; + let notifyTeam = false; + const openBlockers = teamBlockers?.[team]?.filter( + (blocker) => !blocker.closed, + ); + + if (openBlockers?.length > 0) { + teamSlackMessage += `:stop:`; + notifyTeam = true; + } else if (teamSignOffs[team]) { + teamSlackMessage += ':large_green_circle:'; + } else { + teamSlackMessage += ':red_circle:'; + notifyTeam = true; + } + + const teamProjects = teams[team]?.jiraProjects ?? []; + const blockerUrl = blockerJql + ? jiraIssuesUrl(jiraBaseUrl, projectScopedJql(blockerJql, teamProjects)) + : ''; + + if (teamName) { + teamSlackMessage += ` ${teamName}`; + + if (notifyTeam) { + teamSlackMessage += ` ${teamSignOffContact}`; + } + + if (openBlockers?.length > 0 && blockerUrl) { + teamSlackMessage += ` :arrow_right: <${blockerUrl}|*${openBlockers.length} release blocker${openBlockers.length > 1 ? 's' : ''}*>`; + } + } else { + teamSlackMessage += ` ${team} :arrow_right: `; + } + + if (nonContributingTeamsWithBlockersAssigned.includes(team)) { + teamSlackMessage += `\n • team is not listed amongst contributing teams in the <${testingPlanLink}|release sheet>, but has <${blockerUrl}|blockers> assigned, which is why sign off is requested`; + } + + teamSlackMessage += `\n`; + + if (openBlockers?.length > 0) { + stopSlackMessage += teamSlackMessage; + } else if (teamSignOffs[team]) { + greenSlackMessage += teamSlackMessage; + } else { + redSlackMessage += teamSlackMessage; + } + } + + slackMessage += stopSlackMessage; + slackMessage += redSlackMessage; + slackMessage += greenSlackMessage; + slackMessage += `\n`; + + slackMessage += `*Important Reminder:* + +Please be aware of the importance of starting your testing immediately to ensure there is sufficient time to address any unexpected defects. This proactive approach will help prevent release delays and minimize impact on other teams’ deliveries. + +cc <@U032GHTQDKK> <@U0513NJ3TAB> <@U0204J1ANFR> <@UBGR2LNBS>\n`; + + const slackThread = `*${platform} v${releaseVersion}* :thread:`; + const slackChannelName = `release-${platform.toLocaleLowerCase()}-${releaseVersion.replaceAll('.', '-')}`; + + return { + slackChannelName, + slackThreadWithoutBold: slackThread.replace(/\*/gu, ''), + slackThread, + slackMessage, + slackMessageIcon: platformIcon, + slackMessageTitle, + updatedReleasePrBody, + }; +} diff --git a/.github/actions/release-slack-summaries/lib/gates.mjs b/.github/actions/release-slack-summaries/lib/gates.mjs new file mode 100644 index 00000000..98034bdd --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/gates.mjs @@ -0,0 +1,60 @@ +/** + * Safe defaults for the shared action. + * Dry-run posts nothing and writes nothing. A pull request body is written + * only for release validation, when dry-run is off and allow-pr-write is on. + * `test-channel` changes the Slack target only (see the action description). + */ + +/** + * Parses the dry-run input. Unset stays on. + * + * @param {string | boolean | undefined} value - Action input. Unset or empty stays dry-run. + * @returns {boolean} True unless the value is the string `false`. + */ +export function isDryRun(value) { + if (value === undefined || value === null || String(value).trim() === '') { + return true; + } + return String(value).trim().toLowerCase() !== 'false'; +} + +/** + * Parses allow-pr-write. Only the string true allows a write. + * + * @param {string | boolean | undefined} value - Action input. Only the string `true` allows a write. + * @returns {boolean} Whether the caller asked to rewrite the release PR body. + */ +export function isPrWriteAllowed(value) { + return ( + String(value ?? '') + .trim() + .toLowerCase() === 'true' + ); +} + +/** + * Decides whether this run may update a release pull request body. + * + * @param {object} args - Parsed flags. + * @param {string} args.mode - `blocker-summary` or `release-validation`. + * @param {boolean} args.dryRun - Parsed dry-run flag. + * @param {boolean} args.allowPrWrite - Parsed allow-pr-write flag. + * @returns {boolean} Whether this run may PATCH a pull request body. + */ +export function shouldWriteReleasePr({ mode, dryRun, allowPrWrite }) { + return ( + mode === 'release-validation' && dryRun === false && allowPrWrite === true + ); +} + +/** + * Chooses the Slack channel, honoring test-channel. + * + * @param {string} slackChannelName - Channel the Zap formula produced. + * @param {string} testChannel - Override. When set, this is the only target. + * @returns {string} Channel passed to `chat.postMessage`. + */ +export function postChannel(slackChannelName, testChannel) { + const override = (testChannel || '').trim(); + return override || slackChannelName; +} diff --git a/.github/actions/release-slack-summaries/lib/jira.mjs b/.github/actions/release-slack-summaries/lib/jira.mjs new file mode 100644 index 00000000..97fced46 --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/jira.mjs @@ -0,0 +1,174 @@ +/** + * Read-only Jira search and the JQL this action is allowed to build. + * + * Blocker JQL is caller-supplied (`jira-release-blocker-jql`). The saved + * filter does not exist yet, so an empty base is an OPEN skip, not a guess. + * Per release the action appends `AND cf[14565] = "V"` (MCRM-155 interface). + * Regression JQL defaults to the v10 proposal (Found in `cf[16946]`, §4 + * project list) until callers override `jira-regression-jql`. + */ + +/** Found-in field id from MCRM-155 v10 §5.3 C7. OPEN to confirm. */ +export const FOUND_IN_CUSTOM_FIELD = '16946'; + +/** Release Number field id. The shared interface appends this clause. */ +export const RELEASE_NUMBER_CUSTOM_FIELD = '14565'; + +/** + * Proposal §4 project list. OPEN: the saved filter that owns this list is not + * created yet. Callers can replace it with `jira-regression-jql`. + */ +export const DEFAULT_REGRESSION_JQL_BASE = + 'issuetype = Bug AND project in (MUL, ASSETS, CONF, CEUX, WPC, GE, WPN, TAT, CARD, DSYS, MCWP, TMCU, TRAM, PRED, TSA, SUB, KYC, SWAPS, MWPE, STX, MUSD, MBTB)'; + +const MAX_PAGES = 50; + +const RELEASE_VERSION = /^\d+\.\d+\.\d+$/u; + +/** + * Refuses release numbers that did not come from a `release/X.Y.Z` ref. + * + * @param {string} version - Candidate release number. + */ +function assertReleaseVersion(version) { + if (!RELEASE_VERSION.test(version)) { + throw new Error( + `Refusing to build JQL for an unexpected release version: ${version}`, + ); + } +} + +/** + * Appends the release number to the caller blocker JQL. + * + * @param {string} version - Release number from the pull request head ref. + * @param {string} baseJql - Caller base. Empty means the blocker filter is OPEN. + * @returns {string | null} Full blocker JQL, or null when the base is empty. + */ +export function buildBlockerJql(version, baseJql) { + assertReleaseVersion(version); + if (!baseJql || !baseJql.trim()) { + return null; + } + return `${baseJql.trim()} AND cf[${RELEASE_NUMBER_CUSTOM_FIELD}] = "${version}"`; +} + +/** + * Builds the Found-in JQL for one release. + * + * @param {string} version - Release number from the pull request head ref. + * @param {string} baseJql - Caller base. Empty uses {@link DEFAULT_REGRESSION_JQL_BASE}. + * @returns {string} Full regression JQL. + */ +export function buildRegressionJql(version, baseJql) { + assertReleaseVersion(version); + const base = + baseJql && baseJql.trim() ? baseJql.trim() : DEFAULT_REGRESSION_JQL_BASE; + return `${base} AND cf[${FOUND_IN_CUSTOM_FIELD}] = "${version}"`; +} + +/** + * True when the regression search is using the proposal default. + * + * @param {string} baseJql - Caller-supplied regression base. + * @returns {boolean} Whether the default project list is in use. + */ +export function usesDefaultRegressionJql(baseJql) { + return !baseJql || !baseJql.trim(); +} + +/** + * Adds a project clause to a per-release JQL string. + * + * @param {string} jql - JQL that already scopes the release. + * @param {string[] | undefined} projectKeys - Topology keys for one team. + * @returns {string} JQL plus `project = KEY` or `project in (...)`. + */ +export function projectScopedJql(jql, projectKeys) { + const keys = (projectKeys ?? []).filter(Boolean); + if (keys.length === 0) { + return jql; + } + if (keys.length === 1) { + return `${jql} AND project = ${keys[0]}`; + } + return `${jql} AND project in (${keys.join(', ')})`; +} + +/** + * Encodes JQL into a Jira issue-navigator URL. + * + * @param {string} baseUrl - Jira site origin, no trailing slash required. + * @param {string} jql - JQL to encode into the issues navigator. + * @returns {string} `https://…/issues/?jql=` URL. + */ +export function jiraIssuesUrl(baseUrl, jql) { + const base = baseUrl.replace(/\/$/u, ''); + return `${base}/issues/?jql=${encodeURIComponent(jql)}`; +} + +/** + * POST `/rest/api/3/search/jql`, following `nextPageToken`. Read-only. + * + * @param {object} args - Search arguments. + * @param {string} args.baseUrl - Jira site origin. + * @param {string} args.email - Atlassian account email. + * @param {string} args.apiToken - Atlassian API token. Never logged. + * @param {string} args.jql - JQL to run. + * @param {Function} [args.fetchImpl] - Injectable fetch. + * @returns {Promise} Issue objects. + */ +export async function searchJiraIssues({ + baseUrl, + email, + apiToken, + jql, + fetchImpl = fetch, +}) { + const issues = []; + let nextPageToken; + let page = 0; + const authorization = `Basic ${Buffer.from(`${email}:${apiToken}`).toString('base64')}`; + const endpoint = `${baseUrl.replace(/\/$/u, '')}/rest/api/3/search/jql`; + + do { + page += 1; + const body = { + jql, + maxResults: 100, + // customfield_NNNNN is intentionally absent: the Release Blocker field + // id is not assigned yet. Filtering stays in the caller-supplied JQL. + fields: ['summary', 'assignee', 'project', 'status'], + }; + if (nextPageToken) { + body.nextPageToken = nextPageToken; + } + + const response = await fetchImpl(endpoint, { + method: 'POST', + headers: { + Authorization: authorization, + Accept: 'application/json', + 'Content-Type': 'application/json', + }, + body: JSON.stringify(body), + }); + + if (!response.ok) { + const text = await response.text(); + throw new Error( + `Jira search failed (${response.status}): ${text.slice(0, 500)}`, + ); + } + + const data = await response.json(); + issues.push(...(data.issues ?? [])); + nextPageToken = data.isLast ? undefined : data.nextPageToken; + } while (nextPageToken && page < MAX_PAGES); + + if (nextPageToken) { + throw new Error(`Jira search did not finish after ${MAX_PAGES} pages.`); + } + + return issues; +} diff --git a/.github/actions/release-slack-summaries/lib/release-pr.mjs b/.github/actions/release-slack-summaries/lib/release-pr.mjs new file mode 100644 index 00000000..a509fbe3 --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/release-pr.mjs @@ -0,0 +1,102 @@ +/** + * Port of Zap 597 `fetch-release-pr.js`. + * metamask-zaps@dc70d6792cbaf9d99f39982868baf7f090dea0af. + * + * The GraphQL search is gone: the release pull request comes from the open + * `release/X.Y.Z` → `stable` list. The title check and `extractDownloadUrls` + * regexes are unchanged. The original `bug.platform` reference was a + * ReferenceError (`bug` is not in scope); the message now interpolates + * `platform`. + */ + +/** + * Extracts Chrome and Firefox build URLs from a comment. + * + * @param {string} comment - Comment body. + * @param {string} platform - `Extension` or `Mobile`. + * @returns {{ downloadUrl1: string | undefined, downloadUrl2: string | undefined }} Build URLs. + */ +export function extractDownloadUrls(comment, platform) { + let downloadUrl1; + let downloadUrl2; + if (platform === 'Extension') { + const chromeUrlMatch = comment.match( + / 0 + ? pulls.find((pull) => + pull.title.toLowerCase().includes(`release: ${releaseVersion}`), + ) + : undefined) || pulls[0]; + + if (!releasePr) { + throw new Error( + `No release PR found for release/${releaseVersion} in ${githubCodeRepo}`, + ); + } + if (releasePr.title.toLowerCase() !== `release: ${releaseVersion}`) { + throw new Error( + `Warning: The first PR found for release/${releaseVersion} in ${githubCodeRepo} (${releasePr.url}) does not have the expected title ("Release: ${releaseVersion}"). Its title is actually: "${releasePr.title}".`, + ); + } + + return releasePr; +} + +/** + * Last `metamaskbot` comment that contains "Builds ready", within the + * comments the caller already limited to the latest 50. + * + * @param {object[]} comments - `{ body, url, author: { login } }`. + * @param {string} platform - `Extension` or `Mobile`. + * @returns {{ latestBuildCommentUrl: string | undefined, latestBuildCommentDownloadUrls: object }} Build comment fields. + */ +export function latestBuildFromComments(comments, platform) { + const metamaskBotBuildComments = + comments?.filter( + (comment) => + comment.author?.login === 'metamaskbot' && + comment.body.includes('Builds ready'), + ) || []; + const latestBuildComment = + metamaskBotBuildComments.length > 0 + ? metamaskBotBuildComments[metamaskBotBuildComments.length - 1] + : undefined; + const latestBuildCommentDownloadUrls = latestBuildComment + ? extractDownloadUrls(latestBuildComment.body, platform) + : {}; + + return { + latestBuildCommentUrl: latestBuildComment?.url, + latestBuildCommentDownloadUrls, + }; +} diff --git a/.github/actions/release-slack-summaries/lib/releases.mjs b/.github/actions/release-slack-summaries/lib/releases.mjs new file mode 100644 index 00000000..6cbf5b42 --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/releases.mjs @@ -0,0 +1,64 @@ +/** + * Active releases: open pull requests whose head ref is `release/X.Y.Z` and + * whose base is `stable`. + * + * Version sort is `compareVersions` from + * `helpers/list-release-versions/scripts/release-versions-extraction.js`. + * The five-release cap is `.slice(-5)` after that ascending sort (MCRM-155 + * §5.2): the Zapier loop's "maximum 5" lived outside the script, which has + * the sort but not the slice. Keeping the newest five matches the proposal. + * Release validation also keeps `version.endsWith(".0")` (Zap 597 + * `bug-report-filtering.js`). + */ + +const RELEASE_HEAD = /^release\/(\d+\.\d+\.\d+)$/u; + +/** + * Compares dotted numeric versions, oldest first. + * + * @param {{ version: string }} left - Versioned record. + * @param {{ version: string }} right - Versioned record. + * @returns {number} Sort comparator, oldest first. + */ +export function compareVersions(left, right) { + const aParts = left.version.split('.').map(Number); + const bParts = right.version.split('.').map(Number); + + for (let index = 0; index < aParts.length; index += 1) { + if (aParts[index] !== bParts[index]) { + return aParts[index] - bParts[index]; + } + } + + return 0; +} + +/** + * Selects the newest open release pull requests for this mode. + * + * @param {object[]} pulls - GitHub pull request objects. + * @param {object} options - Selection options. + * @param {'blocker-summary' | 'release-validation'} options.mode - Which Zap to cap for. + * @param {number} [options.limit] - Cap after the version sort. Default 5. + * @returns {object[]} Selected pull requests, oldest first, each with `version`. + */ +export function selectReleases(pulls, { mode, limit = 5 } = {}) { + const matched = pulls + .filter((pull) => (pull.state ? pull.state === 'open' : true)) + .filter((pull) => (pull.base?.ref ? pull.base.ref === 'stable' : true)) + .map((pull) => { + const match = pull.head?.ref?.match(RELEASE_HEAD); + if (!match) { + return null; + } + return { ...pull, version: match[1] }; + }) + .filter((pull) => pull !== null); + + matched.sort(compareVersions); + const versionFiltered = + mode === 'release-validation' + ? matched.filter((pull) => pull.version.endsWith('.0')) + : matched; + return versionFiltered.slice(-limit); +} diff --git a/.github/actions/release-slack-summaries/lib/teams.mjs b/.github/actions/release-slack-summaries/lib/teams.mjs new file mode 100644 index 00000000..c5361470 --- /dev/null +++ b/.github/actions/release-slack-summaries/lib/teams.mjs @@ -0,0 +1,110 @@ +/** + * Port of Zap `teams-fetching.js` (`fetchMetaMaskTeams`). + * metamask-zaps@dc70d6792cbaf9d99f39982868baf7f090dea0af. + * + * Same contents URL, same base64 decode, same `githubLabel.name` → + * `{ name, contact }` map. Also reads the per-team Jira project field. + * The field name is PROPOSED (`jiraProject`, an array) and is an input. + */ + +const TEAMS_URL = + 'https://api.github.com/repos/MetaMask/MetaMask-planning/contents/topology.json?ref=main'; + +/** + * Reads Jira project keys from one topology team. + * + * @param {object} team - One topology.json team record. + * @param {string} fieldName - Property that holds Jira project keys. Empty skips the read. + * @returns {string[]} Project keys. A string or an array are both accepted (format is OPEN). + */ +export function readJiraProjects(team, fieldName) { + if (!fieldName) { + return []; + } + const raw = team?.[fieldName]; + if (raw === undefined || raw === null || raw === '') { + return []; + } + if (Array.isArray(raw)) { + return raw.map((item) => String(item).trim()).filter(Boolean); + } + if (typeof raw === 'string') { + return [raw.trim()].filter(Boolean); + } + return []; +} + +/** + * Indexes topology.json by GitHub label and Jira project key. + * + * @param {object} topology - Parsed topology.json. + * @param {string} jiraProjectField - Field name to read. OPEN / PROPOSED: `jiraProject`. + * @returns {{ teams: object, projectToLabel: object, warnings: string[] }} Registry indexes. + */ +export function indexTeams(topology, jiraProjectField) { + const teams = {}; + const projectToLabel = {}; + const warnings = []; + + for (const [key, value] of Object.entries(topology)) { + if (!value?.githubLabel?.name) { + throw new Error( + `Shall never happen: undefined team github label for: ${key}`, + ); + } + const label = value.githubLabel.name; + const jiraProjects = readJiraProjects(value, jiraProjectField); + teams[label] = { + name: value?.name, + contact: value?.slackHandle?.releaseContact, + jiraProjects, + }; + for (const projectKey of jiraProjects) { + const existing = projectToLabel[projectKey]; + if (existing && existing !== label) { + warnings.push( + `Jira project ${projectKey} is listed for both ${existing} and ${label}. Using ${existing}.`, + ); + } else { + projectToLabel[projectKey] = label; + } + } + } + + return { teams, projectToLabel, warnings }; +} + +/** + * Loads topology.json from MetaMask-planning. + * + * @param {string} token - Contents:read token for MetaMask/MetaMask-planning, from the caller. + * @param {string} jiraProjectField - Topology field holding Jira keys. + * @param {Function} [fetchImpl] - Injectable fetch. + * @returns {Promise<{ teams: object, projectToLabel: object, warnings: string[] }>} Registry indexes. + */ +export async function fetchMetaMaskTeams( + token, + jiraProjectField, + fetchImpl = fetch, +) { + const headers = { + Authorization: `Bearer ${token}`, + Accept: 'application/vnd.github+json', + 'Content-Type': 'application/json', + 'User-Agent': 'metamask-github-tools-release-slack-summaries', + }; + const response = await fetchImpl(TEAMS_URL, { method: 'GET', headers }); + + if (!response.ok) { + throw new Error( + `Failed to fetch MetaMask teams. HTTP Status: ${response.status}`, + ); + } + + const fileData = await response.json(); + const contentString = Buffer.from(fileData.content, 'base64').toString( + 'utf-8', + ); + const jsonContent = JSON.parse(contentString); + return indexTeams(jsonContent, jiraProjectField); +} diff --git a/.github/actions/release-slack-summaries/messages.test.mjs b/.github/actions/release-slack-summaries/messages.test.mjs new file mode 100644 index 00000000..120c0a10 --- /dev/null +++ b/.github/actions/release-slack-summaries/messages.test.mjs @@ -0,0 +1,385 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { describe, it } from 'node:test'; + +import { mergeJiraIssues } from './lib/adapter.mjs'; +import { + contributingTeamLabels, + extractTestingPlanLink, +} from './lib/contributing-teams.mjs'; +import { craftBlockerSummary } from './lib/craft-596.mjs'; +import { craftReleaseValidation } from './lib/craft-597.mjs'; +import { extractDownloadUrls } from './lib/release-pr.mjs'; +import { indexTeams } from './lib/teams.mjs'; + +process.env.TZ = 'UTC'; + +/** + * Reads one fixture shipped with this action. + * + * @param {string} name - Fixture file name. + * @returns {string} File contents. + */ +function fixture(name) { + return readFileSync(new URL(`./fixtures/${name}`, import.meta.url), 'utf8'); +} + +/** + * Formats today the way Zap 596 formats the date line. + * + * @returns {string} The Zap's en-US long date, so the assertion tracks the same call. + */ +function zapDateLine() { + return new Date().toLocaleDateString('en-US', { + month: 'long', + day: 'numeric', + year: 'numeric', + }); +} + +const teams596 = { + 'team-extension-platform': { + name: 'Extension Platform team', + contact: '@release-contact-extension-platform', + }, +}; + +describe('craftBlockerSummary', () => { + it('builds the Zap 596 message verbatim', () => { + const result = craftBlockerSummary({ + teams: teams596, + releaseVersion: '13.53.0', + githubRepo: 'metamask-extension', + rcBugs: [ + { + name: 'Login crash', + url: 'https://consensyssoftware.atlassian.net/browse/ASSETS-1', + closed: 'false', + assigneesLength: 0, + labels: ['team-extension-platform', 'release-blocker'], + }, + { + name: 'Icon glitch', + url: 'https://consensyssoftware.atlassian.net/browse/ASSETS-2', + closed: 'false', + assigneesLength: 1, + labels: ['team-extension-platform'], + }, + { + name: 'Closed crash', + url: 'https://consensyssoftware.atlassian.net/browse/ASSETS-3', + closed: 'true', + assigneesLength: 1, + labels: ['release-blocker'], + }, + { + name: 'v13.53.0 Bug Report', + url: 'https://example.invalid/bug', + closed: 'false', + assigneesLength: 0, + labels: ['release-blocker'], + }, + ], + }); + + assert.equal( + result.slackMessage, + `*Date:* ${zapDateLine()} + +:stop: *Release Blockers* :stop: + +*Important:* All release blockers must be resolved before release sign-off. + +• ,@release-contact-extension-platform Issue needs an assignee :hi_wave: + +:warning: *Release regressions* :warning: + +*Note:* All teams should do their best to resolve release regressions before release sign-off. + +• ,@release-contact-extension-platform + +@release-owner-extension`, + ); + assert.equal( + result.slackMessageTitle, + 'Extension release bug summary for v13.53.0\n\n', + ); + assert.equal(result.slackChannelName, 'release-extension-13-53-0'); + assert.equal(result.slackMessageIcon, ':electric_plug:'); + assert.equal(result.platform, 'Extension'); + assert.match(zapDateLine(), /^[A-Z][a-z]+ \d{1,2}, \d{4}$/u); + }); + + it('uses the team-label sentence when the project is not in the registry', () => { + const result = craftBlockerSummary({ + teams: teams596, + releaseVersion: '13.53.0', + githubRepo: 'metamask-mobile', + rcBugs: [ + { + name: 'Unmapped project blocker', + url: 'https://consensyssoftware.atlassian.net/browse/PRED-4', + closed: 'false', + assigneesLength: '0', + labels: ['release-blocker', 'PRED'], + }, + ], + }); + + assert.match( + result.slackMessage, + /• , Issue needs a team label :hi_wave: Issue needs an assignee :hi_wave:/u, + ); + assert.match(result.slackMessage, /@release-owner-mobile$/u); + assert.equal(result.slackMessageIcon, ':iphone:'); + assert.equal(result.slackChannelName, 'release-mobile-13-53-0'); + }); + + it('says there are no remaining bugs only when the RC set is empty', () => { + const empty = craftBlockerSummary({ + teams: teams596, + releaseVersion: '1.0.0', + githubRepo: 'metamask-extension', + rcBugs: [], + }); + assert.equal( + empty.slackMessage, + `*Date:* ${zapDateLine()} + +:white_check_mark: *No remaining bugs* :white_check_mark: + +@release-owner-extension`, + ); + + const allClosed = craftBlockerSummary({ + teams: teams596, + releaseVersion: '1.0.0', + githubRepo: 'metamask-extension', + rcBugs: [ + { + name: 'Closed crash', + url: 'https://consensyssoftware.atlassian.net/browse/ASSETS-3', + closed: 'true', + assigneesLength: 1, + labels: ['team-extension-platform', 'release-blocker'], + }, + ], + }); + assert.equal( + allClosed.slackMessage, + `*Date:* ${zapDateLine()} + +@release-owner-extension`, + ); + assert.doesNotMatch(allClosed.slackMessage, /Release Blockers/u); + assert.doesNotMatch(allClosed.slackMessage, /No remaining bugs/u); + }); + + it('rejects an unknown repository instead of guessing a platform', () => { + assert.throws( + () => + craftBlockerSummary({ + teams: teams596, + releaseVersion: '1.0.0', + githubRepo: 'metamask-planning', + rcBugs: [], + }), + /unknown platform \(metamask-planning\)/u, + ); + }); +}); + +describe('craftReleaseValidation', () => { + const topology = JSON.parse(fixture('topology.json')); + const { teams } = indexTeams(topology, 'jiraProject'); + const issues = JSON.parse(fixture('jira-issues.json')); + const body = fixture('release-pr-body.md'); + const comment = fixture('build-comment.html'); + const blockerJql = 'filter = 12345 AND cf[14565] = "13.53.0"'; + const bugs = mergeJiraIssues(issues.regressions, issues.blockers, { + teamLabelFor: (projectKey) => { + const team = Object.entries(teams).find(([, value]) => + value.jiraProjects.includes(projectKey), + ); + return team ? team[0] : undefined; + }, + browseBaseUrl: 'https://consensyssoftware.atlassian.net', + }); + + /** + * Crafts a release-validation message from the shared fixtures. + * + * @param {object} [overrides] - Craft input overrides. + * @returns {object} Craft result. + */ + function craft(overrides = {}) { + const downloads = extractDownloadUrls(comment, 'Extension'); + return craftReleaseValidation({ + teams, + platform: 'Extension', + releaseVersion: '13.53.0', + contributingTeamLabels: contributingTeamLabels(body, teams), + releasePrUrl: 'https://github.com/MetaMask/metamask-extension/pull/10', + releasePrBody: body, + releaseDownloadUrl1: downloads.downloadUrl1, + releaseDownloadUrl2: downloads.downloadUrl2, + releaseEpicCreatedAt: '2026-10-23T12:00:00.000Z', + rcBugs: bugs, + blockerJql, + jiraBaseUrl: 'https://consensyssoftware.atlassian.net', + testingPlanLink: extractTestingPlanLink(body), + ...overrides, + }); + } + + it('builds the Zap 597 message from the fixtures', () => { + const result = craft(); + const extensionBlockerUrl = + 'https://consensyssoftware.atlassian.net/issues/?jql=filter%20%3D%2012345%20AND%20cf%5B14565%5D%20%3D%20%2213.53.0%22%20AND%20project%20%3D%20ASSETS'; + const designBlockerUrl = + 'https://consensyssoftware.atlassian.net/issues/?jql=filter%20%3D%2012345%20AND%20cf%5B14565%5D%20%3D%20%2213.53.0%22%20AND%20project%20%3D%20DSYS'; + + assert.equal( + result.slackMessage, + ` + +*Current Release Summary* + +Dates: +• Release Cut: *Oct 23* +• Deadline Date for Release Submission: *Oct 30* + +Latest builds available for testing: +• +• + +Useful links: +• +• +• +• +• + +Teams sign off: + +:stop: Extension Platform @release-contact-extension-platform :arrow_right: <${extensionBlockerUrl}|*1 release blocker*> +:stop: Design System @release-contact-design-system :arrow_right: <${designBlockerUrl}|*1 release blocker*> + • team is not listed amongst contributing teams in the , but has <${designBlockerUrl}|blockers> assigned, which is why sign off is requested +:stop: PRED :arrow_right: +:large_green_circle: Mobile Platform + +*Important Reminder:* + +Please be aware of the importance of starting your testing immediately to ensure there is sufficient time to address any unexpected defects. This proactive approach will help prevent release delays and minimize impact on other teams’ deliveries. + +cc <@U032GHTQDKK> <@U0513NJ3TAB> <@U0204J1ANFR> <@UBGR2LNBS> +`, + ); + assert.equal( + result.slackMessageTitle, + 'Extension 13.53.0 Release Validation', + ); + assert.equal(result.slackChannelName, 'release-extension-13-53-0'); + assert.equal(result.slackMessageIcon, ':electric_plug:'); + assert.doesNotMatch(result.slackMessage, /QA Team/u); + assert.doesNotMatch(result.slackMessage, /@dylan\.butler/u); + }); + + it('sorts the checklist and appends blocker teams that have no line', () => { + const result = craft(); + assert.equal( + result.updatedReleasePrBody, + `## Summary + +Testing plan: https://docs.google.com/spreadsheets/d/SHEETID/edit?gid=99#gid=99 + +# Team sign-off checklist +- [ ] Design System +- [ ] Extension Platform +- [x] Mobile Platform +- [ ] PRED +- [x] QA Team + +Follow the checklist before release. +`, + ); + + const second = craft({ releasePrBody: result.updatedReleasePrBody }); + assert.equal(second.updatedReleasePrBody, undefined); + }); + + it('rewrites a changed mobile checklist and leaves an unchanged one alone', () => { + const mobileBody = `## ✅ Team Sign-Off Checklist +- [ ] Mobile Platform +- [x] Extension Platform + +Notes. +`; + const result = craftReleaseValidation({ + teams, + platform: 'Mobile', + releaseVersion: '13.53.0', + contributingTeamLabels: [ + 'team-extension-platform', + 'team-mobile-platform', + ], + releasePrUrl: 'https://github.com/MetaMask/metamask-mobile/pull/4', + releasePrBody: mobileBody, + releaseDownloadUrl1: '', + releaseDownloadUrl2: '', + releaseEpicCreatedAt: '', + rcBugs: [], + blockerJql: null, + jiraBaseUrl: 'https://consensyssoftware.atlassian.net', + testingPlanLink: '', + }); + + assert.equal( + result.updatedReleasePrBody, + `# Team sign-off checklist +- [x] Extension Platform +- [ ] Mobile Platform + +Notes. +`, + ); + assert.match( + result.slackMessage, + /:red_circle: Mobile Platform @release-contact-mobile-platform\n/u, + ); + assert.match( + result.slackMessage, + /:large_green_circle: Extension Platform\n/u, + ); + assert.match(result.slackMessage, /Release Cut: \*Unknown Date\*/u); + assert.doesNotMatch(result.slackMessage, /Latest builds/u); + assert.doesNotMatch(result.slackMessage, /Release Blocker/u); + assert.equal(result.slackMessageIcon, ':iphone:'); + assert.equal(result.slackChannelName, 'release-mobile-13-53-0'); + + const unchanged = craftReleaseValidation({ + teams, + platform: 'Mobile', + releaseVersion: '13.53.0', + contributingTeamLabels: ['team-extension-platform'], + releasePrUrl: 'https://github.com/MetaMask/metamask-mobile/pull/4', + releasePrBody: `## ✅ Team Sign-Off Checklist +- [ ] Extension Platform + +Notes. +`, + releaseDownloadUrl1: '', + releaseDownloadUrl2: '', + releaseEpicCreatedAt: '', + rcBugs: [], + blockerJql: null, + jiraBaseUrl: 'https://consensyssoftware.atlassian.net', + testingPlanLink: '', + }); + assert.equal(unchanged.updatedReleasePrBody, undefined); + assert.match( + unchanged.slackMessage, + /:red_circle: Extension Platform @release-contact-extension-platform\n/u, + ); + }); +}); diff --git a/.github/actions/release-slack-summaries/releases.test.mjs b/.github/actions/release-slack-summaries/releases.test.mjs new file mode 100644 index 00000000..9434b905 --- /dev/null +++ b/.github/actions/release-slack-summaries/releases.test.mjs @@ -0,0 +1,129 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; + +import { latestBuildFromComments, selectReleasePr } from './lib/release-pr.mjs'; +import { selectReleases } from './lib/releases.mjs'; + +/** + * Builds a pull request fixture for one version. + * + * @param {string} version - X.Y.Z. + * @param {object} [overrides] - Pull fields. + * @returns {object} A stable pull request. + */ +function pull(version, overrides = {}) { + return { + number: Number(version.replaceAll('.', '')), + state: 'open', + title: `Release: ${version}`, + head: { ref: `release/${version}` }, + base: { ref: 'stable' }, + ...overrides, + }; +} + +describe('selectReleases', () => { + const pulls = [ + pull('13.9.0'), + pull('13.10.0'), + pull('13.53.1'), + pull('13.52.0'), + pull('13.51.0'), + pull('13.50.0'), + pull('13.49.0'), + pull('13.53.0'), + pull('13.48.0', { state: 'closed' }), + pull('13.47.0', { base: { ref: 'main' } }), + { + state: 'open', + title: 'Release: 13.46.0', + head: { ref: 'release/v13.46.0' }, + base: { ref: 'stable' }, + }, + ]; + + it('keeps the five newest release refs, including hotfixes, for the blocker summary', () => { + const selected = selectReleases(pulls, { mode: 'blocker-summary' }); + assert.deepEqual( + selected.map((item) => item.version), + ['13.50.0', '13.51.0', '13.52.0', '13.53.0', '13.53.1'], + ); + }); + + it('keeps only x.y.0 releases for release validation', () => { + const selected = selectReleases(pulls, { mode: 'release-validation' }); + assert.deepEqual( + selected.map((item) => item.version), + ['13.49.0', '13.50.0', '13.51.0', '13.52.0', '13.53.0'], + ); + }); +}); + +describe('selectReleasePr', () => { + it('throws when the title is not exactly Release: V, and does not post', () => { + assert.throws( + () => + selectReleasePr( + [ + { + title: 'release: 13.53.0 (draft)', + url: 'https://github.com/MetaMask/metamask-extension/pull/10', + }, + ], + '13.53.0', + 'metamask-extension', + ), + /does not have the expected title/u, + ); + }); + + it('accepts Release: V regardless of case', () => { + const selected = selectReleasePr( + [{ title: 'Release: 13.53.0', url: 'https://example.invalid/10' }], + '13.53.0', + 'metamask-extension', + ); + assert.equal(selected.title, 'Release: 13.53.0'); + }); +}); + +describe('latestBuildFromComments', () => { + it('uses the last metamaskbot Builds ready comment', () => { + const older = + ''; + const newerChrome = + ''; + const newerFirefox = + ''; + const result = latestBuildFromComments( + [ + { + author: { login: 'metamaskbot' }, + body: `Builds ready ${older}`, + url: 'https://example.invalid/1', + }, + { + author: { login: 'someone' }, + body: `Builds ready ${newerChrome}${newerFirefox}`, + url: 'https://example.invalid/2', + }, + { + author: { login: 'metamaskbot' }, + body: `Builds ready ${newerChrome}${newerFirefox}`, + url: 'https://example.invalid/3', + }, + ], + 'Extension', + ); + + assert.equal(result.latestBuildCommentUrl, 'https://example.invalid/3'); + assert.equal( + result.latestBuildCommentDownloadUrls.downloadUrl1, + 'https://github.com/MetaMask/metamask-extension/releases/download/build-dist-browserify/builds/metamask-chrome-13.53.0.zip', + ); + assert.equal( + result.latestBuildCommentDownloadUrls.downloadUrl2, + 'https://github.com/MetaMask/metamask-extension/releases/download/build-dist-mv2-browserify/builds/metamask-firefox-13.53.0.zip', + ); + }); +}); diff --git a/.github/actions/release-slack-summaries/run.mjs b/.github/actions/release-slack-summaries/run.mjs new file mode 100644 index 00000000..ea82a914 --- /dev/null +++ b/.github/actions/release-slack-summaries/run.mjs @@ -0,0 +1,468 @@ +/** + * Daily release Slack summaries (MCRM-155). + * + * Zap 596 → `blocker-summary`. Zap 597 → `release-validation`. + * Jira is read-only. GitHub tokens are passed in by the caller (get-token); + * this action does not mint them and does not read a personal access token. + * Defaults: dry-run, and no pull request write unless `allow-pr-write` is set. + */ + +import { Octokit } from '@octokit/rest'; +import { WebClient } from '@slack/web-api'; +import { appendFileSync, realpathSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; + +import { mergeJiraIssues } from './lib/adapter.mjs'; +import { + contributingTeamLabels, + extractTestingPlanLink, +} from './lib/contributing-teams.mjs'; +import { craftBlockerSummary } from './lib/craft-596.mjs'; +import { craftReleaseValidation } from './lib/craft-597.mjs'; +import { + isDryRun, + isPrWriteAllowed, + postChannel, + shouldWriteReleasePr, +} from './lib/gates.mjs'; +import { + buildBlockerJql, + buildRegressionJql, + searchJiraIssues, + usesDefaultRegressionJql, +} from './lib/jira.mjs'; +import { latestBuildFromComments, selectReleasePr } from './lib/release-pr.mjs'; +import { selectReleases } from './lib/releases.mjs'; +import { fetchMetaMaskTeams } from './lib/teams.mjs'; + +const GITHUB_OWNER = 'MetaMask'; + +const REPOS = { + extension: { repo: 'metamask-extension', platformLabel: 'Extension' }, + mobile: { repo: 'metamask-mobile', platformLabel: 'Mobile' }, +}; + +const SKIPPED_CHANNEL_ERRORS = new Set([ + 'channel_not_found', + 'not_in_channel', + 'is_archived', +]); + +/** + * Reads action inputs from the environment. + * + * @param {NodeJS.ProcessEnv} env - Action environment. + * @returns {object} Parsed inputs. Dry-run defaults to true. + */ +export function readConfig(env = process.env) { + const mode = required('mode', env.MODE); + if (mode !== 'blocker-summary' && mode !== 'release-validation') { + throw new Error( + `Unknown mode "${mode}". Expected blocker-summary or release-validation.`, + ); + } + const platform = required('platform', env.PLATFORM); + if (platform !== 'extension' && platform !== 'mobile') { + throw new Error( + `Unknown platform "${platform}". Expected extension or mobile.`, + ); + } + + const topologyField = (env.TOPOLOGY_JIRA_PROJECT_FIELD ?? '').trim(); + + return { + mode, + platform, + githubToken: required('github-token', env.GITHUB_TOKEN), + planningToken: required('planning-token', env.PLANNING_TOKEN), + slackBotToken: required('slack-bot-token', env.SLACK_BOT_TOKEN), + jiraBaseUrl: ( + env.JIRA_BASE_URL || 'https://consensyssoftware.atlassian.net' + ).replace(/\/$/u, ''), + jiraEmail: required('jira-email', env.JIRA_EMAIL), + jiraApiToken: required('jira-api-token', env.JIRA_API_TOKEN), + jiraReleaseBlockerJql: (env.JIRA_RELEASE_BLOCKER_JQL || '').trim(), + jiraRegressionJql: (env.JIRA_REGRESSION_JQL || '').trim(), + topologyJiraProjectField: topologyField || 'jiraProject', + testChannel: (env.TEST_CHANNEL || '').trim(), + dryRun: isDryRun(env.DRY_RUN), + allowPrWrite: isPrWriteAllowed(env.ALLOW_PR_WRITE), + }; +} + +/** + * Returns a required input or throws. + * + * @param {string} name - Input name, for the error. + * @param {string | undefined} value - Raw value. + * @returns {string} Trimmed value. + */ +function required(name, value) { + if (!value || !String(value).trim()) { + throw new Error(`Missing required input: ${name}`); + } + return String(value).trim(); +} + +/** + * Appends markdown to the job summary and the log. + * + * @param {string} markdown - Markdown appended to the step summary and the log. + */ +function writeSummary(markdown) { + const path = process.env.GITHUB_STEP_SUMMARY; + if (path) { + appendFileSync(path, `${markdown}\n`); + } + console.log(markdown); +} + +/** + * Posts one Slack message, or skips a missing channel. + * + * @param {string} token - Caller-supplied Slack bot token. + * @param {object} message - Fields for chat.postMessage. + * @param {string} message.channel - Channel name or id. + * @param {string} message.text - Message body. + * @param {string} message.username - Bot name. Trailing newlines from Zap 596 are trimmed. + * @param {string} message.iconEmoji - `:electric_plug:` or `:iphone:`. + * @returns {Promise<{ skipped: boolean, reason?: string }>} Skip when the channel is missing. + */ +async function postSlack(token, { channel, text, username, iconEmoji }) { + const client = new WebClient(token); + try { + await client.chat.postMessage({ + channel, + text, + username: username.trimEnd(), + icon_emoji: iconEmoji, + link_names: true, + unfurl_links: false, + unfurl_media: false, + }); + } catch (error) { + const code = error?.data?.error; + if (SKIPPED_CHANNEL_ERRORS.has(code)) { + return { skipped: true, reason: code }; + } + throw error; + } + return { skipped: false }; +} + +/** + * Runs one summary for every selected release. + * + * @param {object} config - Parsed inputs. + * @param {object} deps - Injectable clients, for tests. Production builds them. + * @returns {Promise} + */ +export async function run(config, deps = {}) { + const { repo, platformLabel } = REPOS[config.platform]; + const octokit = + deps.octokit ?? + new Octokit({ + auth: config.githubToken, + userAgent: 'metamask-github-tools-release-slack-summaries', + }); + const searchIssues = deps.searchJiraIssues ?? searchJiraIssues; + const loadTeams = + deps.fetchMetaMaskTeams ?? + ((token, field) => fetchMetaMaskTeams(token, field)); + const post = deps.postSlack ?? postSlack; + + const registry = await loadTeams( + config.planningToken, + config.topologyJiraProjectField, + ); + const pulls = await octokit.paginate(octokit.rest.pulls.list, { + owner: GITHUB_OWNER, + repo, + state: 'open', + base: 'stable', + per_page: 100, + }); + const releases = selectReleases(pulls, { mode: config.mode }); + const teamsWithProjects = Object.values(registry.teams).filter( + (team) => team.jiraProjects.length > 0, + ).length; + + const openLines = []; + if (!config.jiraReleaseBlockerJql) { + openLines.push( + 'OPEN: jira-release-blocker-jql is empty. The MetaMask Release Blockers filter is not created yet. Skipping the blocker section. Blocker issues are not queried.', + ); + } + if (usesDefaultRegressionJql(config.jiraRegressionJql)) { + openLines.push( + 'OPEN: jira-regression-jql is empty. Using the v10 proposal default (Found in cf[16946] = "V" and the §4 project list). Confirm the field id and the project list.', + ); + } + openLines.push( + 'OPEN: the Release Blocker custom field id is unknown (cf[NNNNN]). A regression flagged Yes for a different Release Number is not excluded until that id exists.', + ); + openLines.push( + `OPEN: topology Jira project field "${config.topologyJiraProjectField}" is the PROPOSED name. Teams with a key: ${teamsWithProjects} of ${Object.keys(registry.teams).length}.`, + ); + openLines.push(...registry.warnings.map((warning) => `OPEN: ${warning}`)); + + writeSummary( + [ + '# Release Slack summaries', + '', + `- Mode: \`${config.mode}\``, + `- Platform: \`${config.platform}\` (\`${GITHUB_OWNER}/${repo}\`)`, + `- Dry run: \`${config.dryRun}\` (default true; nothing is posted or written)`, + `- Allow PR write: \`${config.allowPrWrite}\``, + `- Test channel: \`${config.testChannel || '(none)'}\``, + `- Releases: ${releases.map((release) => release.version).join(', ') || '(none)'}`, + '', + ...openLines.map((line) => `- ${line}`), + '', + ].join('\n'), + ); + + const failures = []; + for (const release of releases) { + try { + // eslint-disable-next-line no-await-in-loop + await processRelease({ + config, + octokit, + searchIssues, + post, + repo, + platformLabel, + release, + registry, + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + failures.push(`${release.version}: ${message}`); + writeSummary( + `## ${release.version}\n\nFailed before posting: ${message}\n`, + ); + } + } + + if (failures.length > 0) { + throw new Error( + `Release Slack summaries failed for: ${failures.join(' | ')}`, + ); + } +} + +/** + * Builds the message for one release and posts or records it. + * + * @param {object} args - One release. + * @param {object} args.config - Parsed action inputs. + * @param {object} args.octokit - GitHub client for the client repository. + * @param {Function} args.searchIssues - Read-only Jira search. + * @param {Function} args.post - Slack poster. + * @param {string} args.repo - Client repository name. + * @param {string} args.platformLabel - `Extension` or `Mobile`. + * @param {object} args.release - Selected pull request, including `version`. + * @param {object} args.registry - Topology indexes. + * @returns {Promise} Resolves when the release is summarized. + */ +async function processRelease({ + config, + octokit, + searchIssues, + post, + repo, + platformLabel, + release, + registry, +}) { + const { version } = release; + const blockerJql = buildBlockerJql(version, config.jiraReleaseBlockerJql); + const regressionJql = buildRegressionJql(version, config.jiraRegressionJql); + const jiraAuth = { + baseUrl: config.jiraBaseUrl, + email: config.jiraEmail, + apiToken: config.jiraApiToken, + }; + const regressions = await searchIssues({ ...jiraAuth, jql: regressionJql }); + const blockerIssues = blockerJql + ? await searchIssues({ ...jiraAuth, jql: blockerJql }) + : []; + const rcBugs = mergeJiraIssues(regressions, blockerIssues, { + teamLabelFor: (projectKey) => + projectKey ? registry.projectToLabel[projectKey] : undefined, + browseBaseUrl: config.jiraBaseUrl, + }); + + let crafted; + let pullNumber = release.number; + if (config.mode === 'blocker-summary') { + crafted = craftBlockerSummary({ + teams: registry.teams, + releaseVersion: version, + githubRepo: repo, + rcBugs, + }); + } else { + const candidate = { + ...release, + url: release.html_url || release.url, + }; + const selected = selectReleasePr([candidate], version, repo); + pullNumber = selected.number; + const comments = await octokit.paginate(octokit.rest.issues.listComments, { + owner: GITHUB_OWNER, + repo, + issue_number: selected.number, + per_page: 100, + }); + const latestFifty = comments.slice(-50).map((comment) => ({ + body: comment.body ?? '', + url: comment.html_url, + author: { login: comment.user?.login ?? '' }, + })); + const builds = latestBuildFromComments(latestFifty, platformLabel); + const body = selected.body || ''; + const testingPlanLink = extractTestingPlanLink(body); + if (!testingPlanLink) { + console.log( + `OPEN: no docs.google.com/spreadsheets URL in the ${version} PR body. Testing Plan link is empty (597-4 assumption).`, + ); + } + crafted = craftReleaseValidation({ + teams: registry.teams, + platform: platformLabel, + releaseVersion: version, + contributingTeamLabels: contributingTeamLabels(body, registry.teams), + releasePrUrl: selected.html_url || selected.url || '', + releasePrBody: body, + releaseDownloadUrl1: + builds.latestBuildCommentDownloadUrls.downloadUrl1 || '', + releaseDownloadUrl2: + builds.latestBuildCommentDownloadUrls.downloadUrl2 || '', + releaseEpicCreatedAt: selected.created_at || '', + rcBugs, + blockerJql, + jiraBaseUrl: config.jiraBaseUrl, + testingPlanLink, + }); + } + + const channel = postChannel(crafted.slackChannelName, config.testChannel); + const wantsWrite = + shouldWriteReleasePr(config) && Boolean(crafted.updatedReleasePrBody); + const lines = [ + `## ${version}`, + '', + `- Computed channel: \`${crafted.slackChannelName}\``, + `- Post target: \`${channel}\`${config.testChannel ? ' (test-channel override)' : ''}`, + `- Dry run: \`${config.dryRun}\``, + `- Regressions returned: ${regressions.length}`, + `- Blockers returned: ${blockerJql ? blockerIssues.length : 'skipped (OPEN, no blocker JQL)'}`, + `- PR write: ${describePrWrite(config, crafted.updatedReleasePrBody)}`, + ]; + + if (crafted.updatedReleasePrBody) { + lines.push( + '', + '### PR checklist rewrite', + '', + 'Before:', + '', + '```', + checklistSection(release.body || ''), + '```', + '', + 'After:', + '', + '```', + checklistSection(crafted.updatedReleasePrBody), + '```', + ); + } + + lines.push('', '### Message', '', '~~~~', crafted.slackMessage, '~~~~', ''); + writeSummary(lines.join('\n')); + + if (!config.dryRun) { + const result = await post(config.slackBotToken, { + channel, + text: crafted.slackMessage, + username: crafted.slackMessageTitle, + iconEmoji: crafted.slackMessageIcon, + }); + if (result.skipped) { + writeSummary( + `Skipped ${version}: Slack ${result.reason} for \`${channel}\`.\n`, + ); + } + } + + if (wantsWrite) { + await octokit.rest.pulls.update({ + owner: GITHUB_OWNER, + repo, + pull_number: pullNumber, + body: crafted.updatedReleasePrBody, + }); + writeSummary(`Updated pull request #${pullNumber} body for ${version}.\n`); + } +} + +/** + * Describes whether the pull request body will be written. + * + * @param {object} config - Parsed inputs. + * @param {string | undefined} updatedBody - Rewritten body, when the checklist changed. + * @returns {string} Summary phrase. + */ +function describePrWrite(config, updatedBody) { + if (config.mode !== 'release-validation') { + return 'not this mode'; + } + if (!updatedBody) { + return 'checklist unchanged'; + } + if (config.dryRun) { + return 'dry-run, not written'; + } + if (!config.allowPrWrite) { + return 'allow-pr-write is false, not written'; + } + return 'will write'; +} + +/** + * Returns the sign-off checklist section of a pull request body. + * + * @param {string} body - Pull request body. + * @returns {string} Checklist section, or a placeholder. + */ +function checklistSection(body) { + const match = (body || '').match( + /(?:# Team sign-off checklist|## ✅ Team Sign-Off Checklist)[\s\S]*?\n([\s\S]+?)\n\s*\n/u, + ); + return match ? match[1].trim() : '(no checklist section)'; +} + +/** + * Reports whether this file is the Node entrypoint. + * + * @returns {boolean} True when this file is the node entrypoint. + */ +function isDirectRun() { + const entry = process.argv[1]; + if (!entry) { + return false; + } + return import.meta.url === pathToFileURL(realpathSync(entry)).href; +} + +if (isDirectRun()) { + run(readConfig()).catch((error) => { + console.error( + error instanceof Error ? error.stack || error.message : error, + ); + process.exitCode = 1; + }); +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 7cc07802..818fa0cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add the `release-slack-summaries` composite action, a GitHub Actions port of Zapier Zaps 596 and 597 (MCRM-155) + - Jira is read-only. Callers pass short-lived GitHub tokens from `get-token`. + - Dry-run defaults to true, and the release PR checklist is rewritten only when `allow-pr-write` is set. + ## [1.22.0] ### Added diff --git a/package.json b/package.json index 301f87d9..cb9165de 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ "lint:constraints": "yarn constraints", "lint:changelog": "auto-changelog validate --prettier", "lint:dependencies": "depcheck && yarn dedupe", - "lint:eslint": "eslint . --cache --ext js,ts,mts && eslint --no-ignore --cache --ext mjs .github/actions/draft-segment-schema-pr '.github/scripts/**/*.mts'", + "lint:eslint": "eslint . --cache --ext js,ts,mts && eslint --no-ignore --cache --ext mjs .github/actions/draft-segment-schema-pr .github/actions/release-slack-summaries '.github/scripts/**/*.mts'", "lint:fix": "yarn lint:eslint --fix && yarn lint:constraints --fix && yarn lint:misc --write && yarn lint:dependencies", "lint:misc": "prettier '**/*.json' '**/*.md' '**/*.yml' '!.yarnrc.yml' '!.cursor/**' --ignore-path .gitignore --no-error-on-unmatched-pattern", "lint:tsc": "tsc", From c18467ead02f4e9f8683180d1038b658e945d840 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 3 Nov 2026 08:29:33 +0000 Subject: [PATCH 2/3] Link the release-slack-summaries changelog entry to pull request 306 Co-authored-by: Victor Pinto --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 818fa0cc..5b47cbf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Add the `release-slack-summaries` composite action, a GitHub Actions port of Zapier Zaps 596 and 597 (MCRM-155) +- Add the `release-slack-summaries` composite action, a GitHub Actions port of Zapier Zaps 596 and 597 ([#306](https://github.com/MetaMask/github-tools/pull/306)) - Jira is read-only. Callers pass short-lived GitHub tokens from `get-token`. - Dry-run defaults to true, and the release PR checklist is rewritten only when `allow-pr-write` is set. From f99347bfb23bbbd352d199be7b58b3d7cb9f9bb9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Tue, 3 Nov 2026 08:33:06 +0000 Subject: [PATCH 3/3] Refuse release PR writes when a test channel is set A test-channel run posts only to that channel. It does not rewrite the release pull request body, even when allow-pr-write is true, and it logs the refusal. Co-authored-by: Victor Pinto --- .../actions/release-slack-summaries/action.yml | 11 +++++++---- .../release-slack-summaries/gates.test.mjs | 18 ++++++++++++++++++ .../release-slack-summaries/lib/gates.mjs | 15 ++++++++++++--- .../actions/release-slack-summaries/run.mjs | 10 ++++++++++ 4 files changed, 47 insertions(+), 7 deletions(-) diff --git a/.github/actions/release-slack-summaries/action.yml b/.github/actions/release-slack-summaries/action.yml index de21f650..1d2d511c 100644 --- a/.github/actions/release-slack-summaries/action.yml +++ b/.github/actions/release-slack-summaries/action.yml @@ -4,8 +4,9 @@ description: >- summary (Zap 597) to Slack. Jira is read-only. The caller passes short-lived GitHub tokens from `.github/actions/get-token`; this action does not mint tokens. Dry-run defaults to true and writes the message to the job summary. - The release PR checklist is rewritten only when allow-pr-write is true and - dry-run is false. + The release PR checklist is rewritten only when allow-pr-write is true, + dry-run is false, and test-channel is empty. A test channel never writes + a pull request body. inputs: mode: @@ -64,7 +65,8 @@ inputs: default: jiraProject test-channel: description: >- - When set, post only to this channel. Real release channels are not used. + When set, post only to this channel and do not write any release PR body, + even if allow-pr-write is true. Real release channels are not used. required: false default: '' dry-run: @@ -76,7 +78,8 @@ inputs: allow-pr-write: description: >- Default false. Zap 597 rewrites the release PR checklist only when this - is true and dry-run is false. Blocker summary never writes. + is true, dry-run is false, and test-channel is empty. Blocker summary + never writes. required: false default: 'false' github-tools-repository: diff --git a/.github/actions/release-slack-summaries/gates.test.mjs b/.github/actions/release-slack-summaries/gates.test.mjs index 07b431ad..1932fe73 100644 --- a/.github/actions/release-slack-summaries/gates.test.mjs +++ b/.github/actions/release-slack-summaries/gates.test.mjs @@ -84,6 +84,24 @@ describe('safe defaults', () => { }), true, ); + assert.equal( + shouldWriteReleasePr({ + mode: 'release-validation', + dryRun: false, + allowPrWrite: true, + testChannel: '#release-summary-test', + }), + false, + ); + assert.equal( + shouldWriteReleasePr({ + mode: 'release-validation', + dryRun: false, + allowPrWrite: true, + testChannel: ' ', + }), + true, + ); }); it('posts only to the test channel when one is set', () => { diff --git a/.github/actions/release-slack-summaries/lib/gates.mjs b/.github/actions/release-slack-summaries/lib/gates.mjs index 98034bdd..ca361bd7 100644 --- a/.github/actions/release-slack-summaries/lib/gates.mjs +++ b/.github/actions/release-slack-summaries/lib/gates.mjs @@ -1,8 +1,8 @@ /** * Safe defaults for the shared action. * Dry-run posts nothing and writes nothing. A pull request body is written - * only for release validation, when dry-run is off and allow-pr-write is on. - * `test-channel` changes the Slack target only (see the action description). + * only for release validation, when dry-run is off, allow-pr-write is on, + * and test-channel is empty. A test channel never writes a pull request body. */ /** @@ -39,9 +39,18 @@ export function isPrWriteAllowed(value) { * @param {string} args.mode - `blocker-summary` or `release-validation`. * @param {boolean} args.dryRun - Parsed dry-run flag. * @param {boolean} args.allowPrWrite - Parsed allow-pr-write flag. + * @param {string} [args.testChannel] - When set, the write is refused. * @returns {boolean} Whether this run may PATCH a pull request body. */ -export function shouldWriteReleasePr({ mode, dryRun, allowPrWrite }) { +export function shouldWriteReleasePr({ + mode, + dryRun, + allowPrWrite, + testChannel, +}) { + if ((testChannel || '').trim()) { + return false; + } return ( mode === 'release-validation' && dryRun === false && allowPrWrite === true ); diff --git a/.github/actions/release-slack-summaries/run.mjs b/.github/actions/release-slack-summaries/run.mjs index ea82a914..41f837b1 100644 --- a/.github/actions/release-slack-summaries/run.mjs +++ b/.github/actions/release-slack-summaries/run.mjs @@ -5,6 +5,7 @@ * Jira is read-only. GitHub tokens are passed in by the caller (get-token); * this action does not mint them and does not read a personal access token. * Defaults: dry-run, and no pull request write unless `allow-pr-write` is set. + * A set test-channel also refuses the pull request write. */ import { Octokit } from '@octokit/rest'; @@ -205,6 +206,12 @@ export async function run(config, deps = {}) { `OPEN: topology Jira project field "${config.topologyJiraProjectField}" is the PROPOSED name. Teams with a key: ${teamsWithProjects} of ${Object.keys(registry.teams).length}.`, ); openLines.push(...registry.warnings.map((warning) => `OPEN: ${warning}`)); + if (config.testChannel) { + const refusal = + 'test-channel is set. Refusing pull request body writes even if allow-pr-write is true. Zap 597 still rewrites those bodies during the parallel run.'; + console.log(refusal); + openLines.push(refusal); + } writeSummary( [ @@ -423,6 +430,9 @@ function describePrWrite(config, updatedBody) { if (!updatedBody) { return 'checklist unchanged'; } + if (config.testChannel) { + return 'test-channel is set, not written'; + } if (config.dryRun) { return 'dry-run, not written'; }