Files
msd-core/scripts/release-notes/format-github-release-notes.cjs
Rezolv 652142521b enhance(#1549): validate PR-title issue-ref convention at open time (#1576)
* enhance(#1549): validate PR-title issue-ref convention at open time

The release changelog is title-driven: release.yml generates "What's Changed"
from PR titles, then format-github-release-notes.cjs buckets each line by its
conventional-commit prefix and relies on a `(#<issue>)` in the title to render
the issue link. Both rules were enforced only socially, so titles like
`fix(core): ...` (no issue link) and `[security] fix(...): ...` (leading tag
defeats the `^fix` bucket anchor -> mis-filed under Enhancement) silently broke
the changelog, landing on the maintainer as release-time cleanup.

Extract the title matcher into one shared module consumed by BOTH the changelog
classifier and a new PR-title CI gate, so a title that passes the gate cannot
mis-bucket in the changelog (single source of truth).

- scripts/lib/conventional-title.cjs (new): classifyBucket + evaluatePrTitle +
  the anchored regexes. One matcher, two consumers.
- scripts/release-notes/format-github-release-notes.cjs: classifyTitle now
  delegates to classifyBucket (behavior preserved; existing tests green).
- .github/workflows/pr-title-validator.yml (new): runs evaluatePrTitle on
  pull_request opened/edited/reopened/synchronize, for ALL authors (the drift
  came from member PRs). Trusted base-ref checkout; WARN_ONLY knob for rollout.
- tests/conventional-title.test.cjs (new): bucket + gate cases incl. the
  leading-tag mis-bucket (backfills the untested classifyTitle case) and a
  cross-check that the classifier delegates to the shared matcher.
- CONTRIBUTING.md: document the `type(#<issue>):` rule and no-leading-tag.

Claude-Session: https://claude.ai/code/session_01UMV5Qr3H4oFikbuiEauGQk

* fix(#1549): check out the PR in pr-title-validator so the new matcher resolves

The workflow checked out the base branch (next) as a trusted policy source, but
the shared matcher (scripts/lib/conventional-title.cjs) is introduced by this PR
and does not exist on next yet — so require() failed and validate-title errored
on its own introducing PR. Check out the PR's merge ref instead: the matcher
under review is present, the check is self-consistent, and a fork pull_request
runs read-only with no secrets, so running the PR's own pure-string regex is
safe.

* fix(#1549): move conventional-title.cjs out of installed scripts/lib/

bin/install.js bundles every file under scripts/lib/ into the user-installed
payload (the changeset CLI's dependencies), and install.test.cjs (#935) asserts
that exact set. The new matcher is release/CI tooling that must NOT ship to
users, so placing it in scripts/lib/ both broke the install manifest test and
would have shipped dead code. Relocate it next to its consumer in
scripts/release-notes/ (which the installer does not copy) and update the three
require paths (classifier, workflow, test) + the CONTRIBUTING reference.

install.test.cjs now 125/125; conventional-title + release-notes suites green;
lint:ci clean.

* fix(#1549): load title matcher from trusted base ref, not PR code

Addresses review (Solvely-Colin + trek-e): the gate checked out the PR
merge ref and require()'d evaluatePrTitle from PR-controlled code, so any
future PR could edit conventional-title.cjs to return { valid: true } and
wave its own malformed title through — a self-bypassable required check.

Load the matcher from a base-branch checkout instead (ref:
github.event.pull_request.base.ref), the same trusted-policy-source pattern
pr-target-validator.yml already uses. The PR can change its title but not
the ruler that measures it. An existsSync bootstrap guard skips the check
when the matcher isn't on the base branch yet (the introducing PR); every
PR after merge is fully gated. This keeps the single shared matcher (#1549's
whole point) rather than forking the regex into the workflow.

Also per review:
- add tests/conventional-title.property.test.cjs (fast-check): any
  `type(#n): summary` round-trips to valid; evaluatePrTitle/classifyBucket
  are total functions (never throw).
- pin the `fix(#):` zero-digit boundary as missing-issue-ref.

Claude-Session: https://claude.ai/code/session_01VqUHNQCh71pEqjo96zkgQL

---------

Co-authored-by: Tom Boucher <trekkie@nomorestars.com>
2026-06-22 22:44:44 -04:00

263 lines
7.6 KiB
JavaScript

'use strict';
const path = require('path');
const os = require('os');
const fs = require('fs');
const { execFileSync } = require('child_process');
const { runMain, ExitError } = require('../lib/cli-exit.cjs');
const { classifyBucket } = require('./conventional-title.cjs');
/**
* Classify a What's-Changed bullet line into 'Feature', 'Fix', or 'Enhancement'.
* @param {string} bulletLine - Full bullet line including the leading `* ` or `- ` marker.
* @returns {'Feature'|'Fix'|'Enhancement'}
*/
function classifyTitle(bulletLine) {
// Strip leading `* ` or `- ` marker
const withoutMarker = bulletLine.replace(/^[*-]\s+/, '');
// Extract title = text before ` by @`
const byIdx = withoutMarker.indexOf(' by @');
const title = (byIdx !== -1 ? withoutMarker.slice(0, byIdx) : withoutMarker).trim();
// Delegate to the shared matcher so the gate and the changelog can never
// disagree on bucketing (#1549 — single source of truth).
return classifyBucket(title);
}
/**
* Reformat GitHub's auto-generated release notes into the repo's hand-curated format.
*
* @param {object} opts
* @param {string} opts.generatedBody - The raw GitHub-generated release body.
* @param {string} opts.version - Version string (e.g. "1.3.0-rc.1"), no leading "v".
* @param {boolean} opts.prerelease - Whether this is a pre-release.
* @param {string} opts.packageName - npm package name (e.g. "@opengsd/gsd-core").
* @returns {string} Formatted release body (no trailing newline).
*/
function formatReleaseNotes({ generatedBody, version, prerelease, packageName }) {
const lines = generatedBody.split('\n');
const featureBullets = [];
const fixBullets = [];
const enhancementBullets = [];
const newContributorBullets = [];
let fullChangelogLine = null;
let inWhatsChanged = false;
let inNewContributors = false;
for (const line of lines) {
const trimmed = line.trim();
// Detect section headings
if (trimmed === '## What\'s Changed') {
inWhatsChanged = true;
inNewContributors = false;
continue;
}
if (trimmed === '## New Contributors') {
inWhatsChanged = false;
inNewContributors = true;
continue;
}
// Full changelog line ends the What's Changed section
if (trimmed.startsWith('**Full Changelog**:')) {
inWhatsChanged = false;
inNewContributors = false;
fullChangelogLine = trimmed;
continue;
}
// Any other `##` heading ends current section
if (trimmed.startsWith('## ')) {
inWhatsChanged = false;
inNewContributors = false;
continue;
}
// Collect bullets
if (inWhatsChanged && (trimmed.startsWith('* ') || trimmed.startsWith('- '))) {
const category = classifyTitle(trimmed);
if (category === 'Feature') featureBullets.push(trimmed);
else if (category === 'Fix') fixBullets.push(trimmed);
else enhancementBullets.push(trimmed);
continue;
}
if (inNewContributors && (trimmed.startsWith('* ') || trimmed.startsWith('- '))) {
newContributorBullets.push(trimmed);
continue;
}
}
// Build Install block
let installBlock;
if (prerelease) {
installBlock = [
'## Install',
'',
'This pre-release is published to npm under the `next` dist-tag.',
'',
'```bash',
`npm i ${packageName}@${version}`,
'# or',
`npm i ${packageName}@next`,
'```',
].join('\n');
} else {
installBlock = [
'## Install',
'',
'```bash',
`npm i ${packageName}@${version}`,
'# or',
`npm i ${packageName}@latest`,
'```',
].join('\n');
}
// Assemble groups (omit empty ones)
const groups = [];
// Group A: Install
groups.push(installBlock);
// Group B: What's Changed heading
groups.push('## What\'s Changed');
// Group C: Features
if (featureBullets.length > 0) {
groups.push('### Feature\n' + featureBullets.join('\n'));
}
// Group D: Enhancements
if (enhancementBullets.length > 0) {
groups.push('### Enhancement\n' + enhancementBullets.join('\n'));
}
// Group E: Fixes
if (fixBullets.length > 0) {
groups.push('### Fix\n' + fixBullets.join('\n'));
}
// Group F: New Contributors
if (newContributorBullets.length > 0) {
groups.push('## New Contributors\n' + newContributorBullets.join('\n'));
}
// Group G: Full Changelog
if (fullChangelogLine) {
groups.push(fullChangelogLine);
}
return groups.join('\n\n');
}
// CLI entry point
function main() {
try {
const argv = process.argv.slice(2);
let tag = null;
let repo = null;
let packageName = null;
let prerelease = null;
let useStdin = false;
let doApply = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === '--tag') {
tag = argv[++i];
} else if (arg === '--repo') {
repo = argv[++i];
} else if (arg === '--package') {
packageName = argv[++i];
} else if (arg === '--prerelease') {
prerelease = true;
} else if (arg === '--latest') {
prerelease = false;
} else if (arg === '--stdin') {
useStdin = true;
} else if (arg === '--apply') {
doApply = true;
}
}
// Derive version from tag
const version = tag ? tag.replace(/^v/, '') : null;
// Resolve package name if not provided
if (!packageName) {
const repoRoot = path.resolve(__dirname, '..', '..');
const pkgJson = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8'));
packageName = pkgJson.name;
}
let generatedBody;
if (useStdin) {
// Read from stdin
if (!version) {
throw new Error('--stdin mode requires --tag or --version to derive version');
}
if (prerelease === null) {
throw new Error('--stdin mode requires --prerelease or --latest');
}
generatedBody = fs.readFileSync('/dev/stdin', 'utf8');
} else {
// Fetch from gh
if (!tag) {
throw new Error('--tag <tag> is required');
}
const ghArgs = ['release', 'view', tag, '--json', 'body', '-q', '.body'];
if (repo) ghArgs.push('--repo', repo);
generatedBody = execFileSync('gh', ghArgs, { encoding: 'utf8' });
// Determine prerelease if not forced
if (prerelease === null) {
try {
const ghPreArgs = ['release', 'view', tag, '--json', 'isPrerelease', '-q', '.isPrerelease'];
if (repo) ghPreArgs.push('--repo', repo);
const result = execFileSync('gh', ghPreArgs, { encoding: 'utf8' }).trim();
prerelease = result === 'true';
} catch (_e) {
// Final fallback: check if tag contains `-` after version digits
prerelease = /-/.test(version);
}
}
}
const formatted = formatReleaseNotes({ generatedBody, version, prerelease, packageName });
if (doApply) {
const tmpFile = path.join(os.tmpdir(), `release-notes-${Date.now()}.md`);
fs.writeFileSync(tmpFile, formatted, 'utf8');
try {
const ghArgs = ['release', 'edit', tag, '--notes-file', tmpFile];
if (repo) ghArgs.push('--repo', repo);
execFileSync('gh', ghArgs, { encoding: 'utf8' });
process.stderr.write(`Release notes updated for ${tag}\n`);
} finally {
fs.unlinkSync(tmpFile);
}
} else {
process.stdout.write(formatted + '\n');
}
} catch (err) {
if (err instanceof ExitError) throw err;
throw new ExitError(1, err && err.message ? err.message : String(err));
}
}
if (require.main === module) {
runMain(main);
}
module.exports = { formatReleaseNotes, classifyTitle };