From d455254edec1d73bab6304f3834d80953b707100 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesus=20Manuel=20Pi=C3=B1eiro=20Cid?= Date: Wed, 11 Nov 2026 13:01:29 +0100 Subject: [PATCH 1/3] chore: initial commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jesus Manuel Piñeiro Cid From f32d7175d7034b829c3334257034ebfd4051f83f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesus=20Manuel=20Pi=C3=B1eiro=20Cid?= Date: Wed, 11 Nov 2026 13:25:03 +0100 Subject: [PATCH 2/3] feat(tooling): generate CHANGELOG.md entries from closing issues Port changelog-from-prs.mjs from weavejs: the release job writes [Unreleased] from the issues merged PRs close, so PRs no longer edit CHANGELOG.md. Adds the Changelog / Closing issue check (warn-only), a two-pass release preview, and removes the hand-edit gates and the skip-changelog label. Closes #300 --- .github/pull_request_template.md | 13 + .github/scripts/changelog-from-prs.mjs | 862 ++++++++++++++++++ .github/scripts/changelog-from-prs.test.mjs | 478 ++++++++++ .github/scripts/sanitize-changelog.mjs | 2 +- .github/workflows/code-changelog-check.yml | 63 ++ .github/workflows/code-npm_node-pr-verify.yml | 123 +-- ...-npm_node-publish-release-and-snapshot.yml | 12 + .github/workflows/code-release_preview.yml | 74 +- .../workflows/docs/code-changelog-check.md | 27 + ...e-npm_node-publish-release-and-snapshot.md | 1 + .../workflows/docs/code-release_preview.md | 17 +- .opencode/skills/changelog/SKILL.md | 230 ++--- AGENTS.md | 26 +- CONTRIBUTING.md | 26 +- README.md | 4 +- code/CHANGELOG.md | 9 +- docs/src/modules/main/pages/contributing.adoc | 6 +- .../.openspec.yaml | 2 + .../design.md | 40 + .../proposal.md | 35 + .../specs/changelog-generation/spec.md | 112 +++ .../tasks.md | 25 + 22 files changed, 1851 insertions(+), 336 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 .github/scripts/changelog-from-prs.mjs create mode 100644 .github/scripts/changelog-from-prs.test.mjs create mode 100644 .github/workflows/code-changelog-check.yml create mode 100644 .github/workflows/docs/code-changelog-check.md create mode 100644 openspec/changes/generate-changelog-from-closing-issues/.openspec.yaml create mode 100644 openspec/changes/generate-changelog-from-closing-issues/design.md create mode 100644 openspec/changes/generate-changelog-from-closing-issues/proposal.md create mode 100644 openspec/changes/generate-changelog-from-closing-issues/specs/changelog-generation/spec.md create mode 100644 openspec/changes/generate-changelog-from-closing-issues/tasks.md diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..a4b114e6 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ + + +Closes # + +## Summary + + diff --git a/.github/scripts/changelog-from-prs.mjs b/.github/scripts/changelog-from-prs.mjs new file mode 100644 index 00000000..44d65a72 --- /dev/null +++ b/.github/scripts/changelog-from-prs.mjs @@ -0,0 +1,862 @@ +#!/usr/bin/env node + +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +// Generates the `## [Unreleased]` entries of code/CHANGELOG.md from the +// issues that merged pull requests close, so contributors no longer edit the +// changelog by hand. +// +// The link between a PR and its issues is GitHub's *closing reference*: a +// closing keyword in the PR body (`Closes #N`) or the Development sidebar. A +// plain `#N` mention is not one. Each closed issue gives one line: +// +// - [#N](https://github.com///issues/N) +// +// filed under a section picked from the issue labels (see SECTION_RULES). +// The title is read when the script runs, so renaming the issue before the +// release renames the entry, and relabelling it moves the entry. +// +// One script, two modes, sharing the same code so they cannot drift: +// +// - PR mode (`--pr N`): read-only check and preview of a single pull +// request. Reports the lines it would generate, their sections and any +// warnings. Without a linked issue it warns, or fails with `--enforce`, +// unless the PR is bypassed (`skip-release` label, or opened by +// Dependabot). +// - Range mode (default): maps every first-parent commit in `--from..--to` +// to its merged pull requests and collects their closing issues. `--from` +// defaults to the last release tag reachable from `--to`. Used by the +// release job before `keep-a-changelog bump`, and with `--dry-run` to +// validate the output against a released section by hand. +// +// With `--changelog ` (and no `--dry-run`) the lines are written into +// `## [Unreleased]` only: manual lines already there are kept, issues already +// listed there are not repeated, and the rest of the file is left untouched +// (checked before writing). Running it twice gives the same file. +// +// `skip-release` waives the linked-issue rule, it does not drop entries: most +// PRs are merged with it and released together by a later PR, so the issues +// they close still belong in that release. A bypassed PR without an issue +// simply gets no entry. +// +// Any API or git error exits non-zero, so the release job stops before +// `bump`, the commit and the tag. + +import { execFileSync } from 'node:child_process'; +import { appendFileSync, existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; +import { parseArgs } from 'node:util'; +import { normalizeInvisibleWhitespace } from './sanitize-changelog.mjs'; + +export const BYPASS_LABEL = 'skip-release'; + +// Dependabot is `dependabot[bot]` in REST payloads and `dependabot` in GraphQL. +const EXEMPT_AUTHORS = new Set(['dependabot', 'dependabot[bot]']); + +// First match wins. Anything without one of these labels (and without an +// EXCLUDED_LABELS one) goes to FALLBACK_SECTION with a "section guessed" +// warning, never skipped silently. +export const SECTION_RULES = [ + { labels: ['kind/security'], section: 'Security' }, + { labels: ['kind/bug'], section: 'Fixed' }, + { labels: ['kind/enhancement'], section: 'Added' }, + { labels: ['kind/documentation'], section: 'Documentation' }, + { labels: ['kind/deprecated'], section: 'Deprecated' }, + { labels: ['kind/removed'], section: 'Removed' }, +]; +export const FALLBACK_SECTION = 'Changed'; + +// Issues with only these labels (no SECTION_RULES category) are out of scope +// for the changelog: `kind/epic` is a size flag and `kind/internal` means no +// user-facing effect. A real category label wins over them. They are listed +// in the report instead of the changelog, never dropped silently. +export const EXCLUDED_LABELS = ['kind/internal', 'kind/epic']; + +// Keep a Changelog order, used only to place a section that does not exist yet. +const SECTION_ORDER = ['Added', 'Changed', 'Deprecated', 'Removed', 'Fixed', 'Security', 'Documentation']; + +const RELEASE_TAG_PATTERN = '[0-9]*'; + +export function sectionFor(labels) { + const names = new Set(labels.map((label) => label.toLowerCase())); + for (const rule of SECTION_RULES) { + if (rule.labels.some((label) => names.has(label))) { + return { section: rule.section, guessed: false }; + } + } + return { section: FALLBACK_SECTION, guessed: true }; +} + +// Verbatim apart from whitespace: NBSP and friends would trip +// sanitize-changelog.mjs at release time, and a newline would break the list. +export function normalizeTitle(title) { + return normalizeInvisibleWhitespace(title).replace(/\s+/g, ' ').trim(); +} + +export function issueRef(issue, repo) { + return issue.repo === repo ? `#${issue.number}` : `${issue.repo}#${issue.number}`; +} + +export function formatEntry(issue, repo) { + return `- [${issueRef(issue, repo)}](${issue.url}) ${normalizeTitle(issue.title)}`; +} + +const ENTRY_LINE = /^(- \[[^\]\n]+\]\([^)\n]+\) )(\S.*)$/; + +// Preview only: a code span keeps `@user` and `@org/team` in an issue title +// from notifying anyone when the text is posted as a PR comment. Only the +// title after the leading issue link is wrapped; other lines pass through. +export function wrapTitle(line) { + const match = ENTRY_LINE.exec(line); + if (!match) { + return line; + } + const [, prefix, title] = match; + const longestRun = Math.max(0, ...(title.match(/`+/g) ?? []).map((run) => run.length)); + const fence = '`'.repeat(longestRun + 1); + const pad = title.startsWith('`') || title.endsWith('`') ? ' ' : ''; + return `${prefix}${fence}${pad}${title}${pad}${fence}`; +} + +export function wrapTitles(text) { + return text.split('\n').map(wrapTitle).join('\n'); +} + +export function bypassReason(pr) { + if (pr.labels.includes(BYPASS_LABEL)) { + return `has the \`${BYPASS_LABEL}\` label`; + } + if (EXEMPT_AUTHORS.has(pr.author)) { + return 'was opened by Dependabot'; + } + return null; +} + +// `prs` must be ordered newest merge first: entries keep that order. +export function buildEntries(prs, { repo }) { + const entries = []; + const warnings = []; + const bypassed = []; + const excluded = []; + const seen = new Set(); + + for (const pr of prs) { + if (pr.issues.length === 0) { + const reason = bypassReason(pr); + if (reason) { + bypassed.push({ pr: pr.number, reason }); + } else { + warnings.push(`PR #${pr.number} has no linked issue, so it gets no changelog entry.`); + } + continue; + } + for (const issue of pr.issues) { + const key = `${issue.repo}#${issue.number}`; + if (seen.has(key)) { + continue; + } + seen.add(key); + const { section, guessed } = sectionFor(issue.labels); + const outOfScope = guessed && issue.labels.find((label) => EXCLUDED_LABELS.includes(label.toLowerCase())); + if (outOfScope) { + excluded.push({ ref: issueRef(issue, repo), pr: pr.number, label: outOfScope }); + continue; + } + if (guessed) { + warnings.push( + `Section guessed for ${issueRef(issue, repo)}: the issue has none of the labels ` + + `${SECTION_RULES.flatMap((rule) => rule.labels).map((label) => `\`${label}\``).join(', ')}, ` + + `so it is filed under ${FALLBACK_SECTION}. Label the issue to change it.` + ); + } + entries.push({ + section, + guessed, + pr: pr.number, + ref: issueRef(issue, repo), + url: issue.url, + line: formatEntry(issue, repo), + }); + } + } + + return { entries, warnings, bypassed, excluded }; +} + +// Issue URL -> version of the newest released section listing it. With +// `olderThan`, only sections below `## [olderThan]` count, so a `--dry-run` +// of an already released range is compared with what came before it. +export function releasedUrls(text, { olderThan } = {}) { + const urls = new Map(); + let version = null; + let counting = olderThan === undefined; + for (const line of text.split('\n')) { + const heading = /^## \[([^\]]+)\]/.exec(line); + if (heading) { + version = heading[1].toLowerCase() === 'unreleased' ? null : heading[1]; + if (heading[1] === olderThan) { + counting = true; + version = null; + } + continue; + } + if (version && counting) { + for (const url of listedUrls([line])) { + if (!urls.has(url)) { + urls.set(url, version); + } + } + } + } + return urls; +} + +// An issue closed again by a later PR (a follow-up fix) is not listed in a +// second release: the entry is skipped with a warning. +export function dropReleased(result, released) { + const entries = []; + for (const entry of result.entries) { + const version = released.get(entry.url); + if (version) { + result.warnings.push(`${entry.ref} is already listed in the [${version}] release, so it is not listed again.`); + } else { + entries.push(entry); + } + } + return { ...result, entries }; +} + +function findUnreleased(lines) { + const start = lines.findIndex((line) => /^## \[Unreleased\]\s*$/i.test(line)); + if (start === -1) { + throw new Error('The changelog has no "## [Unreleased]" heading.'); + } + let end = lines.findIndex((line, index) => index > start && /^## /.test(line)); + if (end === -1) { + end = lines.length; + } + return { start, end }; +} + +function trimBlankLines(lines) { + let first = 0; + let last = lines.length; + while (first < last && lines[first].trim() === '') first++; + while (last > first && lines[last - 1].trim() === '') last--; + return lines.slice(first, last); +} + +// Issue URLs of the entries in `lines`: only the leading `- [ref](url)` of a +// list item counts, so a link inside the text of another entry (or inside an +// issue title) is not mistaken for that issue's entry. +function listedUrls(lines) { + const urls = []; + for (const line of lines) { + const match = /^- \[[^\]]*\]\(([^)\s]+)\)/.exec(line); + if (match) { + urls.push(match[1]); + } + } + return urls; +} + +// Writes `entries` into `## [Unreleased]`. Returns the new text plus which +// entries were added and which were already listed there. +export function applyEntries(text, entries) { + if (text.includes('\r')) { + throw new Error('The changelog has CRLF line endings; convert it to LF first.'); + } + const lines = text.split('\n'); + const { start, end } = findUnreleased(lines); + const body = lines.slice(start + 1, end); + const listed = new Set(listedUrls(body)); + + const added = []; + const alreadyListed = []; + for (const entry of entries) { + (listed.has(entry.url) ? alreadyListed : added).push(entry); + } + if (added.length === 0) { + return { text, added, alreadyListed }; + } + + const preamble = []; + const sections = []; + let current = null; + for (const line of body) { + const heading = /^### (.+?)\s*$/.exec(line); + if (heading) { + current = { name: heading[1], lines: [] }; + sections.push(current); + } else { + (current ? current.lines : preamble).push(line); + } + } + + for (const entry of added) { + let section = sections.find((candidate) => candidate.name.toLowerCase() === entry.section.toLowerCase()); + if (!section) { + section = { name: entry.section, lines: [] }; + const rank = SECTION_ORDER.indexOf(entry.section); + const before = sections.findIndex((candidate) => SECTION_ORDER.indexOf(candidate.name) > rank); + sections.splice(before === -1 ? sections.length : before, 0, section); + } + section.lines = [...trimBlankLines(section.lines), entry.line]; + } + + const blocks = []; + const intro = trimBlankLines(preamble); + if (intro.length > 0) { + blocks.push(intro.join('\n')); + } + for (const section of sections) { + const sectionLines = trimBlankLines(section.lines); + blocks.push(sectionLines.length > 0 ? `### ${section.name}\n\n${sectionLines.join('\n')}` : `### ${section.name}`); + } + + const head = lines.slice(0, start + 1).join('\n'); + const tail = lines.slice(end).join('\n'); + const result = tail === '' ? `${head}\n\n${blocks.join('\n\n')}\n` : `${head}\n\n${blocks.join('\n\n')}\n\n${tail}`; + + assertOnlyUnreleasedChanged(text, result, added); + return { text: result, added, alreadyListed }; +} + +// Guard for "an unexpected result must stop the release": everything outside +// `## [Unreleased]` is byte-identical, and every added entry is there once. +function assertOnlyUnreleasedChanged(before, after, added) { + const beforeLines = before.split('\n'); + const afterLines = after.split('\n'); + const old = findUnreleased(beforeLines); + const now = findUnreleased(afterLines); + const same = (a, b) => a.length === b.length && a.every((line, index) => line === b[index]); + if (!same(beforeLines.slice(0, old.start + 1), afterLines.slice(0, now.start + 1))) { + throw new Error('Refusing to write: the text before "## [Unreleased]" would change.'); + } + if (!same(beforeLines.slice(old.end), afterLines.slice(now.end))) { + throw new Error('Refusing to write: the text after the "## [Unreleased]" section would change.'); + } + const urls = listedUrls(afterLines.slice(now.start + 1, now.end)); + for (const entry of added) { + if (urls.filter((url) => url === entry.url).length !== 1) { + throw new Error(`Refusing to write: ${entry.url} is not listed exactly once in "## [Unreleased]".`); + } + } +} + +// Lines of the `## []` section, used by `--dry-run` to compare. +export function releasedSection(text, version) { + const lines = text.split('\n'); + const start = lines.findIndex((line) => line.startsWith(`## [${version}]`)); + if (start === -1) { + return null; + } + let end = lines.findIndex((line, index) => index > start && /^## /.test(line)); + if (end === -1) { + end = lines.length; + } + const entries = new Map(); + let section = null; + for (const line of lines.slice(start + 1, end)) { + const heading = /^### (.+?)\s*$/.exec(line); + if (heading) { + section = heading[1]; + } else if (line.startsWith('- ')) { + entries.set(line, section); + } + } + return entries; +} + +// --------------------------------------------------------------------------- +// GitHub API + +const PR_FIELDS = ` + number + url + merged + mergedAt + baseRefName + headRefOid + author { login } + labels(first: 100) { pageInfo { hasNextPage } nodes { name } } + closingIssuesReferences(first: 50) { + pageInfo { hasNextPage } + nodes { + number + title + url + repository { nameWithOwner } + labels(first: 100) { pageInfo { hasNextPage } nodes { name } } + } + } +`; + +const PR_QUERY = `query($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { ${PR_FIELDS} } + } +}`; + +const COMMIT_QUERY = `query($owner: String!, $name: String!, $oid: GitObjectID!) { + repository(owner: $owner, name: $name) { + object(oid: $oid) { + ... on Commit { + associatedPullRequests(first: 20) { pageInfo { hasNextPage } nodes { ${PR_FIELDS} } } + } + } + } +}`; + +// The limits are far above real use; hitting one fails instead of silently +// dropping an issue or a label that picks the section. +function assertComplete(connection, what, field) { + if (connection.pageInfo?.hasNextPage) { + throw new Error( + `Too many ${what} to read in one page, so the changelog would be incomplete. Nothing was written ` + + 'and, in the release job, nothing was tagged or published. Raise the `first:` limit of ' + + `\`${field}\` in .github/scripts/changelog-from-prs.mjs and run the workflow again.` + ); + } + return connection.nodes; +} + +function toPullRequest(node) { + assertComplete(node.labels, `labels on PR #${node.number}`, 'labels'); + assertComplete(node.closingIssuesReferences, `issues closed by PR #${node.number}`, 'closingIssuesReferences'); + for (const issue of node.closingIssuesReferences.nodes) { + assertComplete(issue.labels, `labels on issue ${issue.url}`, 'labels'); + } + return { + number: node.number, + url: node.url, + merged: node.merged, + mergedAt: node.mergedAt, + baseRefName: node.baseRefName, + headRefOid: node.headRefOid, + author: node.author?.login ?? null, + labels: node.labels.nodes.map((label) => label.name), + issues: node.closingIssuesReferences.nodes.map((issue) => ({ + number: issue.number, + title: issue.title, + url: issue.url, + repo: issue.repository.nameWithOwner, + labels: issue.labels.nodes.map((label) => label.name), + })), + }; +} + +class RetryableError extends Error {} + +export function createGitHubClient({ + token, + repo, + endpoint = process.env.GITHUB_GRAPHQL_URL || 'https://api.github.com/graphql', + fetchImpl = globalThis.fetch, + retries = 4, + baseDelayMs = 1000, + sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), +}) { + if (!token) { + throw new Error('Set GITHUB_TOKEN (or GH_TOKEN) to read pull requests and issues.'); + } + const [owner, name] = repo.split('/'); + + async function attempt(query, variables) { + let response; + try { + response = await fetchImpl(endpoint, { + method: 'POST', + headers: { + authorization: `bearer ${token}`, + 'content-type': 'application/json', + 'user-agent': 'docouture-changelog-from-prs', + }, + body: JSON.stringify({ query, variables }), + }); + } catch (error) { + throw new RetryableError(`GitHub API request failed: ${error.message}`); + } + const rateLimited = + response.status === 403 && + (response.headers.get('retry-after') !== null || response.headers.get('x-ratelimit-remaining') === '0'); + if (response.status >= 500 || response.status === 429 || rateLimited) { + throw new RetryableError(`GitHub API responded ${response.status}.`); + } + if (!response.ok) { + throw new Error(`GitHub API responded ${response.status}: ${await response.text()}`); + } + const payload = await response.json(); + if (payload.errors?.length) { + const message = payload.errors.map((error) => error.message).join('; '); + if (payload.errors.some((error) => error.type === 'RATE_LIMITED')) { + throw new RetryableError(`GitHub API rate limit: ${message}`); + } + throw new Error(`GitHub API error: ${message}`); + } + return payload.data; + } + + async function graphql(query, variables) { + for (let tries = 0; ; tries++) { + try { + return await attempt(query, { owner, name, ...variables }); + } catch (error) { + if (!(error instanceof RetryableError) || tries >= retries) { + throw error; + } + const delay = baseDelayMs * 2 ** tries; + console.error(`${error.message} Retrying in ${delay} ms (${tries + 1}/${retries}).`); + await sleep(delay); + } + } + } + + return { + async pullRequest(number) { + const data = await graphql(PR_QUERY, { number }); + const node = data.repository?.pullRequest; + if (!node) { + throw new Error(`Pull request #${number} not found in ${repo}.`); + } + return toPullRequest(node); + }, + async commitPullRequests(oid) { + const data = await graphql(COMMIT_QUERY, { oid }); + const commit = data.repository?.object; + if (!commit?.associatedPullRequests) { + throw new Error(`Commit ${oid} not found in ${repo}.`); + } + return assertComplete(commit.associatedPullRequests, `pull requests for commit ${oid}`, 'associatedPullRequests').map(toPullRequest); + }, + }; +} + +// Merged PRs behind the first-parent commits of the range, newest merge first. +export async function pullRequestsForCommits(client, commits, { branch }) { + const prs = new Map(); + const orphanCommits = []; + for (const commit of commits) { + const merged = (await client.commitPullRequests(commit.sha)).filter( + (pr) => pr.merged && pr.baseRefName === branch + ); + if (merged.length === 0) { + orphanCommits.push(commit); + } + for (const pr of merged) { + prs.set(pr.number, pr); + } + } + const ordered = [...prs.values()].sort((a, b) => (a.mergedAt < b.mergedAt ? 1 : a.mergedAt > b.mergedAt ? -1 : 0)); + return { prs: ordered, orphanCommits }; +} + +// --------------------------------------------------------------------------- +// git + +function git(args) { + return execFileSync('git', args, { encoding: 'utf8' }).trim(); +} + +export function lastReleaseTag(ref) { + try { + return git(['describe', '--tags', '--abbrev=0', `--match=${RELEASE_TAG_PATTERN}`, ref]); + } catch { + throw new Error(`No release tag matching "${RELEASE_TAG_PATTERN}" is reachable from ${ref}.`); + } +} + +function firstParentCommits(from, to) { + const out = git(['log', '--first-parent', '--format=%H%x09%s', `${from}..${to}`]); + return out === '' + ? [] + : out.split('\n').map((line) => { + const [sha, ...subject] = line.split('\t'); + return { sha, subject: subject.join('\t') }; + }); +} + +function defaultRepo() { + if (process.env.GITHUB_REPOSITORY) { + return process.env.GITHUB_REPOSITORY; + } + const url = git(['remote', 'get-url', 'origin']); + const match = /github\.com[:/]([^/]+\/[^/]+?)(?:\.git)?$/.exec(url); + if (!match) { + throw new Error(`Cannot infer the repository from origin (${url}); pass --repo owner/name.`); + } + return match[1]; +} + +// --------------------------------------------------------------------------- +// Report + +function renderEntries(entries, render = (line) => line) { + const out = []; + for (const section of [...SECTION_ORDER, ...new Set(entries.map((entry) => entry.section))]) { + const lines = entries.filter((entry) => entry.section === section); + if (lines.length > 0 && !out.includes(`**${section}**`)) { + out.push(`**${section}**`, '', ...lines.map((entry) => render(entry.line)), ''); + } + } + return out; +} + +function renderExcluded(result) { + if (result.excluded.length === 0) { + return []; + } + return [ + `**Out of scope** (labelled ${EXCLUDED_LABELS.map((label) => `\`${label}\``).join(' or ')}, no entry)`, + '', + ...result.excluded.map((item) => `- ${item.ref} (\`${item.label}\`, PR #${item.pr})`), + '', + ]; +} + +export function renderPullRequestReport({ pr, result, enforce }) { + const out = ['### Changelog', '']; + const reason = bypassReason(pr); + const skipRelease = pr.labels.includes(BYPASS_LABEL); + if (pr.issues.length === 0 && reason) { + out.push( + skipRelease + ? `This PR has the \`${BYPASS_LABEL}\` label and no linked issue: merging it publishes no release and adds no changelog entry.` + : `This PR ${reason}, so it is exempt from the linked-issue rule and gets no changelog entry.` + ); + } else if (pr.issues.length === 0) { + out.push( + `${enforce ? ':x:' : ':warning:'} This PR is not linked to an issue, so it would get no changelog entry.`, + '', + 'Add `Closes #` to the PR description, or link the issue from the Development sidebar. ' + + 'A plain `#` mention does not count.' + + (pr.baseRefName === 'main' + ? '' + : ` GitHub only reads closing keywords on PRs to the default branch: for \`${pr.baseRefName}\`, use the Development sidebar.`), + '', + `A maintainer can waive the rule with the \`${BYPASS_LABEL}\` label, which also skips the release on merge.` + ); + } else if (result.entries.length === 0) { + out.push('The issues this PR closes get no changelog entry (see below).', ''); + } else { + out.push( + skipRelease + ? `This PR has the \`${BYPASS_LABEL}\` label: merging it publishes no release. These entries go into the next release:` + : 'When this PR is released, `code/CHANGELOG.md` gets:', + '', + ...renderEntries(result.entries, wrapTitle) + ); + out.push('The text is the issue title, read at release time: edit the issue title or labels to change it.'); + } + if (result.excluded.length > 0) { + out.push('', ...renderExcluded(result)); + } + const warnings = result.warnings.filter((warning) => !warning.startsWith(`PR #${pr.number} has no linked issue`)); + if (warnings.length > 0) { + out.push('', '**Warnings**', '', ...warnings.map((warning) => `- ${warning}`)); + } + out.push('', `_As of ${pr.headRefOid}._`, ''); + return out.join('\n'); +} + +export function renderRangeReport({ from, to, prs, result, applied, orphanCommits, comparison }) { + const out = [`### Changelog entries for ${from}..${to}`, '']; + out.push( + `${prs.length} merged pull request(s), ${result.entries.length} entr${result.entries.length === 1 ? 'y' : 'ies'}.`, + '' + ); + out.push(...(result.entries.length > 0 ? renderEntries(result.entries) : ['_No entries._', ''])); + if (applied?.alreadyListed.length) { + out.push('**Already listed in [Unreleased], kept as written**', ''); + out.push(...applied.alreadyListed.map((entry) => `- ${entry.url}`), ''); + } + if (result.warnings.length > 0) { + out.push('**Warnings**', '', ...result.warnings.map((warning) => `- ${warning}`), ''); + } + out.push(...renderExcluded(result)); + if (result.bypassed.length > 0) { + out.push('**Bypassed pull requests**', '', ...result.bypassed.map((item) => `- #${item.pr} ${item.reason}`), ''); + } + if (orphanCommits.length > 0) { + out.push('**Commits without a merged pull request**', ''); + out.push(...orphanCommits.map((commit) => `- ${commit.sha.slice(0, 8)} ${commit.subject}`), ''); + } + if (comparison) { + out.push(`**Compared with the hand-written [${comparison.version}] section**`, ''); + if (comparison.onlyGenerated.length === 0 && comparison.onlyWritten.length === 0 && comparison.moved.length === 0) { + out.push('Identical.', ''); + } + for (const [title, items] of [ + ['Only generated', comparison.onlyGenerated], + ['Only hand-written', comparison.onlyWritten], + ['Different section (generated vs hand-written)', comparison.moved], + ]) { + if (items.length > 0) { + out.push(`_${title}:_`, '', ...items.map((item) => `- ${item}`), ''); + } + } + } + return out.join('\n'); +} + +export function compareWithReleased(entries, released, version) { + const generated = new Map(entries.map((entry) => [entry.line, entry.section])); + const onlyGenerated = []; + const moved = []; + for (const [line, section] of generated) { + if (!released.has(line)) { + onlyGenerated.push(`${line} (${section})`); + } else if (released.get(line) !== section) { + moved.push(`${line} (${section} vs ${released.get(line)})`); + } + } + const onlyWritten = [...released].filter(([line]) => !generated.has(line)).map(([line, section]) => `${line} (${section})`); + return { version, onlyGenerated, onlyWritten, moved }; +} + +// --------------------------------------------------------------------------- +// CLI + +function annotate(level, message) { + if (process.env.GITHUB_ACTIONS === 'true') { + console.log(`::${level}::${message.replace(/%/g, '%25').replace(/\r/g, '%0D').replace(/\n/g, '%0A')}`); + } +} + +function writeReport(path, report) { + console.log(report); + if (path) { + appendFileSync(path, `${report}\n`); + } +} + +function readChangelog(path) { + if (!existsSync(path)) { + throw new Error(`${path} does not exist.`); + } + return readFileSync(path, 'utf8'); +} + +function applyToChangelog(path, entries, dryRun) { + const before = readFileSync(path, 'utf8'); + const applied = applyEntries(before, entries); + if (!dryRun && applied.text !== before) { + writeFileSync(path, applied.text); + } + return applied; +} + +const USAGE = `usage: + changelog-from-prs.mjs --pr [--enforce] [--changelog ] [--report ] + changelog-from-prs.mjs --wrap-titles < changelog-section.md + changelog-from-prs.mjs [--from ] [--to ] [--branch ] [--changelog ] [--dry-run] [--report ] + +options: + --repo defaults to $GITHUB_REPOSITORY, then the origin remote + --from defaults to the last tag matching "${RELEASE_TAG_PATTERN}" reachable from --to + --to defaults to HEAD + --branch base branch the PRs were merged into (default: main) + --changelog write the entries into its [Unreleased] section + --dry-run never write; in range mode, compare with the [--to] section of --changelog + --enforce PR mode: fail when the PR has no linked issue and no bypass + --report also append the Markdown report to this file (e.g. $GITHUB_STEP_SUMMARY) + --wrap-titles filter stdin to stdout, putting each entry title in a code span so @mentions + do not notify when posted as a PR comment`; + +export async function main(argv = process.argv.slice(2)) { + const { values } = parseArgs({ + args: argv, + options: { + pr: { type: 'string' }, + repo: { type: 'string' }, + from: { type: 'string' }, + to: { type: 'string', default: 'HEAD' }, + branch: { type: 'string', default: 'main' }, + changelog: { type: 'string' }, + 'dry-run': { type: 'boolean', default: false }, + enforce: { type: 'boolean', default: false }, + report: { type: 'string' }, + 'wrap-titles': { type: 'boolean', default: false }, + help: { type: 'boolean', default: false }, + }, + }); + if (values.help) { + console.log(USAGE); + return 0; + } + if (values['wrap-titles']) { + process.stdout.write(wrapTitles(readFileSync(0, 'utf8'))); + return 0; + } + + const repo = values.repo ?? defaultRepo(); + const client = createGitHubClient({ token: process.env.GITHUB_TOKEN || process.env.GH_TOKEN, repo }); + const dryRun = values['dry-run']; + + if (values.pr !== undefined) { + const number = Number(values.pr); + if (!Number.isInteger(number) || number <= 0) { + throw new Error(`--pr expects a pull request number, got "${values.pr}".`); + } + const pr = await client.pullRequest(number); + let result = buildEntries([pr], { repo }); + if (values.changelog) { + result = dropReleased(result, releasedUrls(readChangelog(values.changelog))); + } + if (values.changelog && result.entries.length > 0) { + applyToChangelog(values.changelog, result.entries, dryRun); + } + writeReport(values.report, renderPullRequestReport({ pr, result, enforce: values.enforce })); + for (const warning of result.warnings) { + annotate('warning', warning); + } + if (!bypassReason(pr) && pr.issues.length === 0) { + const message = `PR #${number} is not linked to an issue. Add "Closes #" to the description or link it from the Development sidebar.`; + if (values.enforce) { + annotate('error', message); + console.error(message); + return 1; + } + } + return 0; + } + + const to = values.to; + const from = values.from ?? lastReleaseTag(to); + const commits = firstParentCommits(from, to); + const { prs, orphanCommits } = await pullRequestsForCommits(client, commits, { branch: values.branch }); + let result = buildEntries(prs, { repo }); + + let applied = null; + let comparison = null; + if (values.changelog) { + const text = readChangelog(values.changelog); + const released = dryRun ? releasedSection(text, to) : null; + result = dropReleased(result, releasedUrls(text, { olderThan: released ? to : undefined })); + applied = applyToChangelog(values.changelog, result.entries, dryRun); + if (released) { + comparison = compareWithReleased(result.entries, released, to); + } + } + + writeReport(values.report, renderRangeReport({ from, to, prs, result, applied, orphanCommits, comparison })); + for (const warning of result.warnings) { + annotate('warning', warning); + } + return 0; +} + +// Compared as resolved file URLs so spaces, non-ASCII characters or a +// symlink in the path cannot make the CLI silently do nothing. +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) { + main().then( + (code) => process.exit(code), + (error) => { + annotate('error', error.message); + console.error(error.message); + process.exit(1); + } + ); +} diff --git a/.github/scripts/changelog-from-prs.test.mjs b/.github/scripts/changelog-from-prs.test.mjs new file mode 100644 index 00000000..744711c9 --- /dev/null +++ b/.github/scripts/changelog-from-prs.test.mjs @@ -0,0 +1,478 @@ +// SPDX-FileCopyrightText: 2026 INDUSTRIA DE DISEÑO TEXTIL S.A. (INDITEX S.A.) +// +// SPDX-License-Identifier: Apache-2.0 + +// Run with: node --test .github/scripts/changelog-from-prs.test.mjs + +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { + applyEntries, + buildEntries, + compareWithReleased, + createGitHubClient, + dropReleased, + formatEntry, + normalizeTitle, + pullRequestsForCommits, + releasedSection, + releasedUrls, + renderPullRequestReport, + sectionFor, + wrapTitle, + wrapTitles, +} from './changelog-from-prs.mjs'; + +const REPO = 'InditexTech/docouture'; + +function issue(number, title, labels = []) { + return { number, title, labels, repo: REPO, url: `https://github.com/${REPO}/issues/${number}` }; +} + +function pr(number, issues, { labels = [], author = 'someone', mergedAt = '2026-10-01T00:00:00Z', base = 'main' } = {}) { + return { + number, + url: `https://github.com/${REPO}/pull/${number}`, + merged: true, + mergedAt, + baseRefName: base, + headRefOid: 'abc123', + author, + labels, + issues, + }; +} + +const CHANGELOG = `# Changelog + +Intro. + +## [Unreleased] + +## [5.7.1] - 2026-10-27 + +### Fixed + +- [#1246](https://github.com/InditexTech/docouture/issues/1246) Old entry + +[Unreleased]: https://github.com/InditexTech/docouture/compare/5.7.1...HEAD +`; + +describe('sectionFor', () => { + it('applies the rules in order, first match wins', () => { + assert.deepEqual(sectionFor(['kind/bug', 'kind/security']), { section: 'Security', guessed: false }); + assert.deepEqual(sectionFor(['kind/enhancement', 'kind/bug']), { section: 'Fixed', guessed: false }); + assert.deepEqual(sectionFor(['Kind/Enhancement']), { section: 'Added', guessed: false }); + }); + + it('maps every kind/* category', () => { + for (const [label, section] of [ + ['kind/security', 'Security'], + ['kind/bug', 'Fixed'], + ['kind/enhancement', 'Added'], + ['kind/documentation', 'Documentation'], + ['kind/deprecated', 'Deprecated'], + ['kind/removed', 'Removed'], + ]) { + assert.deepEqual(sectionFor([label]), { section, guessed: false }); + } + }); + + it('falls back to Changed and flags the guess', () => { + assert.deepEqual(sectionFor([]), { section: 'Changed', guessed: true }); + assert.deepEqual(sectionFor(['documentation', 'bug']), { section: 'Changed', guessed: true }); + }); +}); + +describe('normalizeTitle / formatEntry', () => { + it('keeps the title verbatim apart from whitespace', () => { + assert.equal(normalizeTitle(' Feature request: Shift and\tAlt​ '), 'Feature request: Shift and Alt'); + assert.equal(normalizeTitle('Use `require()` on Node 20.19+'), 'Use `require()` on Node 20.19+'); + }); + + it('formats the line, qualifying issues from other repositories', () => { + assert.equal( + formatEntry(issue(12, 'Title'), REPO), + '- [#12](https://github.com/InditexTech/docouture/issues/12) Title' + ); + assert.equal( + formatEntry({ ...issue(3, 'Other'), repo: 'InditexTech/other', url: 'https://github.com/InditexTech/other/issues/3' }, REPO), + '- [InditexTech/other#3](https://github.com/InditexTech/other/issues/3) Other' + ); + }); +}); + +describe('buildEntries', () => { + it('gives one line per closed issue, deduplicated across PRs', () => { + const { entries, warnings } = buildEntries( + [pr(2, [issue(10, 'Ten', ['kind/bug']), issue(11, 'Eleven', ['kind/enhancement'])]), pr(1, [issue(10, 'Ten', ['kind/bug'])])], + { repo: REPO } + ); + assert.deepEqual( + entries.map((entry) => [entry.section, entry.pr, entry.line]), + [ + ['Fixed', 2, '- [#10](https://github.com/InditexTech/docouture/issues/10) Ten'], + ['Added', 2, '- [#11](https://github.com/InditexTech/docouture/issues/11) Eleven'], + ] + ); + assert.deepEqual(warnings, []); + }); + + it('warns about PRs without a linked issue and guessed sections', () => { + const { entries, warnings } = buildEntries([pr(1, []), pr(2, [issue(5, 'Five')])], { repo: REPO }); + assert.equal(entries.length, 1); + assert.equal(warnings.length, 2); + assert.match(warnings[0], /PR #1 has no linked issue/); + assert.match(warnings[1], /Section guessed for #5/); + }); + + it('skip-release waives the link rule but keeps the entries of linked issues', () => { + const { entries, warnings, bypassed } = buildEntries( + [pr(1, [], { labels: ['skip-release'] }), pr(2, [issue(7, 'Seven', ['kind/bug'])], { labels: ['skip-release'] })], + { repo: REPO } + ); + assert.deepEqual(entries.map((entry) => entry.pr), [2]); + assert.deepEqual(warnings, []); + assert.deepEqual(bypassed.map((item) => item.pr), [1]); + }); + + it('lists internal/epic-only issues as out of scope instead of writing them', () => { + const { entries, excluded, warnings } = buildEntries( + [pr(1, [issue(40, 'Release docs 5.7.0', ['kind/internal']), issue(41, 'Container', ['kind/epic']), issue(42, 'Real', ['kind/bug'])])], + { repo: REPO } + ); + assert.deepEqual(entries.map((entry) => entry.ref), ['#42']); + assert.deepEqual(excluded, [ + { ref: '#40', pr: 1, label: 'kind/internal' }, + { ref: '#41', pr: 1, label: 'kind/epic' }, + ]); + assert.deepEqual(warnings, []); + }); + + it('a real category wins over kind/internal and kind/epic', () => { + const { entries, excluded } = buildEntries( + [pr(1, [issue(50, 'Big', ['kind/epic', 'kind/enhancement']), issue(51, 'Odd', ['kind/internal', 'kind/bug'])])], + { repo: REPO } + ); + assert.deepEqual(entries.map((entry) => [entry.ref, entry.section]), [['#50', 'Added'], ['#51', 'Fixed']]); + assert.deepEqual(excluded, []); + }); + + it('ignores skip-changelog: the issue labels alone decide', () => { + const { entries, warnings } = buildEntries( + [pr(1, [issue(60, 'Fix', ['kind/bug'])], { labels: ['skip-changelog'] })], + { repo: REPO } + ); + assert.deepEqual(entries.map((entry) => entry.section), ['Fixed']); + assert.deepEqual(warnings, []); + }); + + it('exempts Dependabot', () => { + for (const author of ['dependabot', 'dependabot[bot]']) { + const { warnings, bypassed } = buildEntries([pr(1, [], { author })], { repo: REPO }); + assert.deepEqual(warnings, []); + assert.equal(bypassed.length, 1); + } + }); +}); + +describe('applyEntries', () => { + const entries = buildEntries( + [pr(2, [issue(20, 'Twenty', ['kind/bug']), issue(21, 'Twenty-one', ['kind/security'])]), pr(1, [issue(19, 'Nineteen', ['kind/enhancement'])])], + { repo: REPO } + ).entries; + + it('writes only the [Unreleased] section, in Keep a Changelog order', () => { + const { text, added } = applyEntries(CHANGELOG, entries); + assert.equal(added.length, 3); + assert.equal( + text, + CHANGELOG.replace( + '## [Unreleased]\n\n', + `## [Unreleased] + +### Added + +- [#19](https://github.com/InditexTech/docouture/issues/19) Nineteen + +### Fixed + +- [#20](https://github.com/InditexTech/docouture/issues/20) Twenty + +### Security + +- [#21](https://github.com/InditexTech/docouture/issues/21) Twenty-one + +` + ) + ); + }); + + it('is idempotent', () => { + const once = applyEntries(CHANGELOG, entries).text; + const twice = applyEntries(once, entries); + assert.equal(twice.text, once); + assert.equal(twice.added.length, 0); + assert.equal(twice.alreadyListed.length, 3); + }); + + it('keeps manual lines and does not repeat an issue already listed', () => { + const manual = CHANGELOG.replace( + '## [Unreleased]\n', + `## [Unreleased] + +### Fixed + +- [#20](https://github.com/InditexTech/docouture/issues/20) Hand-written wording +- Manual line without an issue +` + ); + const { text, added, alreadyListed } = applyEntries(manual, entries); + assert.deepEqual(alreadyListed.map((entry) => entry.url), ['https://github.com/InditexTech/docouture/issues/20']); + assert.equal(added.length, 2); + assert.match( + text, + /### Added\n\n- \[#19\].*\n\n### Fixed\n\n- \[#20\]\(.*\) Hand-written wording\n- Manual line without an issue\n\n### Security\n\n- \[#21\]/ + ); + assert.ok(text.endsWith(manual.slice(manual.indexOf('## [5.7.1]')))); + }); + + it('works when [Unreleased] is the last section', () => { + const { text } = applyEntries('# Changelog\n\n## [Unreleased]\n', entries.slice(0, 1)); + assert.equal(text, '# Changelog\n\n## [Unreleased]\n\n### Fixed\n\n- [#20](https://github.com/InditexTech/docouture/issues/20) Twenty\n'); + }); + + it('leaves the text untouched when there is nothing to add', () => { + assert.equal(applyEntries(CHANGELOG, []).text, CHANGELOG); + }); + + it('only counts the leading link of a list item as an issue entry', () => { + const mentioned = CHANGELOG.replace( + '## [Unreleased]\n', + '## [Unreleased]\n\n### Changed\n\n- Refactor X (see [#20](https://github.com/InditexTech/docouture/issues/20))\n' + ); + const { added } = applyEntries(mentioned, entries); + assert.ok(added.some((entry) => entry.url.endsWith('/issues/20'))); + + const sneaky = buildEntries( + [pr(1, [issue(30, 'Breaks [#31](https://github.com/InditexTech/docouture/issues/31)', ['kind/bug']), issue(31, 'Real', ['kind/bug'])])], + { repo: REPO } + ).entries; + const { text } = applyEntries(CHANGELOG, sneaky); + assert.match(text, /- \[#31\]\(https:\/\/github.com\/InditexTech\/docouture\/issues\/31\) Real/); + }); + + it('refuses CRLF changelogs', () => { + assert.throws(() => applyEntries(CHANGELOG.replace(/\n/g, '\r\n'), entries), /CRLF/); + }); + + it('fails without an [Unreleased] heading', () => { + assert.throws(() => applyEntries('# Changelog\n\n## [1.0.0]\n', entries), /no "## \[Unreleased\]" heading/); + }); +}); + +describe('releasedUrls / dropReleased', () => { + const history = `${CHANGELOG.replace('[Unreleased]: ', '')} +## [5.7.0] - 2026-10-26 + +### Fixed + +- [#1147](https://github.com/InditexTech/docouture/issues/1147) Fixed earlier +`; + + it('skips an issue that an earlier release already lists, with a warning', () => { + const result = buildEntries([pr(1, [issue(1147, 'Fixed earlier', ['kind/bug']), issue(1300, 'New', ['kind/bug'])])], { repo: REPO }); + const kept = dropReleased(result, releasedUrls(history)); + assert.deepEqual(kept.entries.map((entry) => entry.ref), ['#1300']); + assert.deepEqual(kept.warnings, ['#1147 is already listed in the [5.7.0] release, so it is not listed again.']); + }); + + it('maps each issue to the newest release listing it and ignores [Unreleased]', () => { + const urls = releasedUrls( + history.replace('## [Unreleased]\n', '## [Unreleased]\n\n- [#1300](https://github.com/InditexTech/docouture/issues/1300) Pending\n') + ); + assert.equal(urls.get('https://github.com/InditexTech/docouture/issues/1246'), '5.7.1'); + assert.equal(urls.get('https://github.com/InditexTech/docouture/issues/1147'), '5.7.0'); + assert.equal(urls.has('https://github.com/InditexTech/docouture/issues/1300'), false); + }); + + it('with olderThan, only counts the releases below that version', () => { + const urls = releasedUrls(history, { olderThan: '5.7.1' }); + assert.equal(urls.has('https://github.com/InditexTech/docouture/issues/1246'), false); + assert.equal(urls.get('https://github.com/InditexTech/docouture/issues/1147'), '5.7.0'); + }); +}); + +describe('releasedSection / compareWithReleased', () => { + it('reports differences with a hand-written section', () => { + const released = releasedSection(CHANGELOG, '5.7.1'); + const generated = buildEntries( + [pr(1, [issue(1246, 'Old entry', ['kind/enhancement']), issue(1247, 'New', ['kind/bug'])])], + { repo: REPO } + ).entries; + const comparison = compareWithReleased(generated, released, '5.7.1'); + assert.equal(comparison.onlyGenerated.length, 1); + assert.equal(comparison.onlyWritten.length, 0); + assert.equal(comparison.moved.length, 1); + assert.match(comparison.moved[0], /\(Added vs Fixed\)$/); + }); +}); + +describe('renderPullRequestReport', () => { + it('explains how to link an issue, with the sidebar hint off the default branch', () => { + const report = renderPullRequestReport({ pr: pr(1, [], { base: 'main-5' }), result: buildEntries([pr(1, [])], { repo: REPO }), enforce: true }); + assert.match(report, /:x: This PR is not linked to an issue/); + assert.match(report, /use the Development sidebar/); + assert.match(report, /_As of abc123._/); + }); + + it('states both effects of skip-release', () => { + const bare = pr(1, [], { labels: ['skip-release'] }); + assert.match( + renderPullRequestReport({ pr: bare, result: buildEntries([bare], { repo: REPO }), enforce: false }), + /publishes no release and adds no changelog entry/ + ); + const linked = pr(2, [issue(9, 'Nine', ['kind/bug'])], { labels: ['skip-release'] }); + const report = renderPullRequestReport({ pr: linked, result: buildEntries([linked], { repo: REPO }), enforce: false }); + assert.match(report, /publishes no release\. These entries go into the next release/); + assert.match(report, /\*\*Fixed\*\*\n\n- \[#9\]/); + }); + + it('says why a linked PR gets no entry when its issues are internal', () => { + const tracking = pr(3, [issue(40, 'Release docs 5.7.0', ['kind/internal'])]); + const report = renderPullRequestReport({ pr: tracking, result: buildEntries([tracking], { repo: REPO }), enforce: true }); + assert.match(report, /get no changelog entry \(see below\)/); + assert.match(report, /\*\*Out of scope\*\*.*\n\n- #40 \(`kind\/internal`, PR #3\)/); + assert.doesNotMatch(report, /:x:/); + }); +}); + +describe('wrapTitle / preview', () => { + const link = '[#9](https://github.com/InditexTech/docouture/issues/9)'; + + it('puts the title in a code span so mentions do not notify', () => { + assert.equal( + wrapTitle(`- ${link} Fix @InditexTech/docouture-admins crash`), + `- ${link} \`Fix @InditexTech/docouture-admins crash\`` + ); + }); + + it('uses a longer fence when the title has backticks', () => { + assert.equal(wrapTitle(`- ${link} Fix \`a\` bug`), `- ${link} \`\`Fix \`a\` bug\`\``); + assert.equal(wrapTitle(`- ${link} \`a\``), `- ${link} \`\` \`a\` \`\``); + }); + + it('leaves headings, references and manual bullets alone', () => { + const text = '## [5.8.0] - 2026-11-11\n### Added\n- Manual @someone line\n[Unreleased]: https://x/compare/a...b'; + assert.equal(wrapTitles(text), text); + }); + + it('wraps only in the PR report; the changelog line stays verbatim', () => { + const linked = pr(5, [issue(9, 'Fix @InditexTech/docouture-admins crash', ['kind/bug'])]); + const result = buildEntries([linked], { repo: REPO }); + assert.match( + renderPullRequestReport({ pr: linked, result, enforce: false }), + /- \[#9\]\(.*\) `Fix @InditexTech\/docouture-admins crash`/ + ); + assert.equal(result.entries[0].line, `- ${link} Fix @InditexTech/docouture-admins crash`); + assert.ok(applyEntries(CHANGELOG, result.entries).text.includes(`${link} Fix @InditexTech/docouture-admins crash\n`)); + }); +}); + +describe('createGitHubClient', () => { + const prNode = { + number: 4, + url: 'u', + merged: true, + mergedAt: '2026-10-01T00:00:00Z', + baseRefName: 'main', + headRefOid: 'sha', + author: { login: 'dev' }, + labels: { nodes: [{ name: 'skip-release' }] }, + closingIssuesReferences: { + nodes: [{ number: 3, title: 'T', url: 'i', repository: { nameWithOwner: REPO }, labels: { nodes: [{ name: 'kind/bug' }] } }], + }, + }; + + function response(status, body, headers = {}) { + return { status, ok: status >= 200 && status < 300, headers: new Map(Object.entries(headers)), json: async () => body, text: async () => JSON.stringify(body) }; + } + + it('retries transient failures with backoff', async () => { + const delays = []; + const replies = [ + () => Promise.reject(new TypeError('socket hang up')), + () => response(502, {}), + () => response(200, { errors: [{ type: 'RATE_LIMITED', message: 'slow down' }] }), + () => response(200, { data: { repository: { pullRequest: prNode } } }), + ]; + const client = createGitHubClient({ + token: 't', + repo: REPO, + fetchImpl: async () => replies.shift()(), + sleep: async (ms) => delays.push(ms), + baseDelayMs: 10, + }); + const result = await client.pullRequest(4); + assert.deepEqual(delays, [10, 20, 40]); + assert.deepEqual(result.labels, ['skip-release']); + assert.deepEqual(result.issues, [{ number: 3, title: 'T', url: 'i', repo: REPO, labels: ['kind/bug'] }]); + }); + + it('gives up after the last retry and does not retry real errors', async () => { + const flaky = createGitHubClient({ token: 't', repo: REPO, fetchImpl: async () => response(503, {}), sleep: async () => {}, retries: 2 }); + await assert.rejects(flaky.pullRequest(4), /responded 503/); + + let calls = 0; + const broken = createGitHubClient({ + token: 't', + repo: REPO, + fetchImpl: async () => { + calls++; + return response(200, { errors: [{ message: 'Field does not exist' }] }); + }, + sleep: async () => {}, + }); + await assert.rejects(broken.pullRequest(4), /Field does not exist/); + assert.equal(calls, 1); + }); + + it('fails instead of truncating a paginated list', async () => { + const client = createGitHubClient({ + token: 't', + repo: REPO, + fetchImpl: async () => + response(200, { + data: { + repository: { + pullRequest: { ...prNode, closingIssuesReferences: { ...prNode.closingIssuesReferences, pageInfo: { hasNextPage: true } } }, + }, + }, + }), + }); + await assert.rejects( + client.pullRequest(4), + /Too many issues closed by PR #4 .*nothing was tagged or published\. Raise the `first:` limit of `closingIssuesReferences`/ + ); + }); + + it('requires a token', () => { + assert.throws(() => createGitHubClient({ token: '', repo: REPO }), /GITHUB_TOKEN/); + }); +}); + +describe('pullRequestsForCommits', () => { + it('keeps merged PRs into the branch, newest first, and reports commits without one', async () => { + const byCommit = { + a: [pr(1, [], { mergedAt: '2026-10-01T00:00:00Z' })], + b: [pr(2, [], { mergedAt: '2026-10-03T00:00:00Z' }), { ...pr(3, []), merged: false }], + c: [pr(4, [], { base: 'main-5' })], + d: [pr(2, [], { mergedAt: '2026-10-03T00:00:00Z' })], + }; + const client = { commitPullRequests: async (sha) => byCommit[sha] }; + const commits = ['a', 'b', 'c', 'd'].map((sha) => ({ sha, subject: sha })); + const { prs, orphanCommits } = await pullRequestsForCommits(client, commits, { branch: 'main' }); + assert.deepEqual(prs.map((item) => item.number), [2, 1]); + assert.deepEqual(orphanCommits.map((commit) => commit.sha), ['c']); + }); +}); diff --git a/.github/scripts/sanitize-changelog.mjs b/.github/scripts/sanitize-changelog.mjs index 63806f71..100ed797 100644 --- a/.github/scripts/sanitize-changelog.mjs +++ b/.github/scripts/sanitize-changelog.mjs @@ -60,7 +60,7 @@ function stripStrayEscapes(text) { return out; } -function normalizeInvisibleWhitespace(text) { +export function normalizeInvisibleWhitespace(text) { return text.replace(ZERO_WIDTH, '').replace(SPACE_LIKE, ' '); } diff --git a/.github/workflows/code-changelog-check.yml b/.github/workflows/code-changelog-check.yml new file mode 100644 index 00000000..a2be5a7f --- /dev/null +++ b/.github/workflows/code-changelog-check.yml @@ -0,0 +1,63 @@ +--- +name: code-changelog-check + +# Every pull request must be linked to the issue it closes: the release job +# generates the CHANGELOG.md entries from those issues. See +# .github/scripts/changelog-from-prs.mjs. + +concurrency: + group: changelog-check-${{ github.event.pull_request.number }} + cancel-in-progress: true + +on: + pull_request: + # `edited` because the link lives in the PR body; `labeled`/`unlabeled` + # because `skip-release` waives the rule. + types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled, edited] + branches: ["main", "main-*"] + +permissions: {} + +env: + # 'true' fails a PR that has no linked issue and no bypass. 'false' only + # warns: flip it to 'true' in a follow-up PR once a release has run end to + # end with the generated changelog. + CHANGELOG_LINK_ENFORCE: "false" + +jobs: + closing-issue: + name: Changelog / Closing issue + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + pull-requests: read + issues: read + steps: + - name: Checkout + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4 + with: + persist-credentials: false + + - name: Setup Node + uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4 + with: + node-version-file: code/.tool-versions + + - name: Test the changelog script + run: node --test .github/scripts/changelog-from-prs.test.mjs + + # Fork PRs get a read-only token, so the result goes to the job summary + # rather than a PR comment. + - name: Check the closing issue + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + # --dry-run: reads code/CHANGELOG.md to report issues already + # released, never writes it. + ARGS=(--pr "$PR_NUMBER" --changelog code/CHANGELOG.md --dry-run --report "$GITHUB_STEP_SUMMARY") + if [[ "$CHANGELOG_LINK_ENFORCE" == 'true' ]]; then + ARGS+=(--enforce) + fi + node .github/scripts/changelog-from-prs.mjs "${ARGS[@]}" diff --git a/.github/workflows/code-npm_node-pr-verify.yml b/.github/workflows/code-npm_node-pr-verify.yml index 1c25f710..733ff1a6 100644 --- a/.github/workflows/code-npm_node-pr-verify.yml +++ b/.github/workflows/code-npm_node-pr-verify.yml @@ -5,28 +5,15 @@ concurrency: cancel-in-progress: true # Least privilege: this workflow only ever checks out the PR and runs -# read-only verification (changelog check, lint/test/build) — no step here -# pushes, comments, or otherwise writes back to GitHub, so the default -# broad token scope is more than it needs. `issues: read` and -# `pull-requests: read` are needed by the changelog-label check below, which -# reads the PR's own labels and, when it has none of its own, the labels of -# any issue it closes (see the `changelog` skill for why: a change's real -# `kind/*` category often lives on its tracking issue, not on the PR). +# read-only verification (lint/test/build) — no step here pushes, comments, +# or otherwise writes back to GitHub, so the default broad token scope is +# more than it needs. CHANGELOG.md entries are not checked here: they are +# generated at release time (see code-changelog-check.yml). permissions: contents: read - issues: read - pull-requests: read on: pull_request: - # `labeled`/`unlabeled` alongside the defaults (opened/synchronize/reopened): - # `github.event.pull_request.labels` is a snapshot taken when each webhook - # event fires, not a live read — a `kind/internal`/`kind/epic`/ - # `skip-changelog` label added *after* the code was pushed would otherwise - # never re-trigger this check with the label actually visible to it, - # leaving `Code / Verify` stuck on a stale FAILURE until an unrelated commit - # forces a fresh `synchronize` event. - types: [opened, synchronize, reopened, labeled, unlabeled] paths: - "code/**" - ".github/workflows/code-npm_node-pr-verify.yml" @@ -41,108 +28,6 @@ jobs: steps: - name: Checkout uses: actions/checkout@v4 - with: - # 0 rather than the default shallow clone: the CHANGELOG.md check - # below diffs against the PR's base commit, which needs to be - # present locally, not just the tip being verified. - fetch-depth: 0 - - # Resolves whether this PR needs a CHANGELOG.md entry and, if so, whether - # it's properly labeled — see the `changelog` skill for the full rules. - # Six labels (`kind/enhancement`, `kind/bug`, `kind/documentation`, - # `kind/deprecated`, `kind/removed`, `kind/security`) are "real" - # categories that require an entry; `kind/internal` and `kind/epic` mean - # no entry is needed. `skip-release` is NOT exempt here — it only blocks - # the version bump (see `release-flow/keep-a-changelog-action`'s `bump` - # command in the publish workflow), it does not exempt a PR from still - # documenting its change in [Unreleased]. The PR's own labels are checked - # first; if it carries none of the six real categories itself, this - # falls back to the labels of any issue it closes (`closingIssuesReferences` - # via the GraphQL API — not exposed by `gh pr view --json`), because the - # real category commonly lives on the tracking issue while its - # implementing PR(s) are deliberately `skip-release`. The exemption - # (`kind/internal`/`kind/epic`) is resolved the same way — checked on - # the PR AND on any issue it closes — since that label just as often - # lives on the tracking issue rather than the implementing PR. - # - # `skip-changelog` is a separate, PR-only override: unlike - # `kind/internal`/`kind/epic` (which say the change has no user-facing - # effect), it says the change IS real but the merger is deliberately - # choosing not to give it its own entry — so it overrides even a real - # `kind/*` category, and it is checked only on the PR itself, never on - # an issue it closes (it's a judgment call about this diff, not a - # property of the tracked issue). - - name: Resolve changelog requirement from labels - id: changelog-requirement - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - PR_LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }} - PR_NUMBER: ${{ github.event.pull_request.number }} - REPO_OWNER: ${{ github.repository_owner }} - REPO_NAME: ${{ github.event.repository.name }} - run: | - CATEGORY_LABELS="kind/enhancement kind/bug kind/documentation kind/deprecated kind/removed kind/security" - EXEMPT_LABELS="kind/internal kind/epic" - OVERRIDE_LABELS="skip-changelog" - - has_any() { - local haystack=",$1," needle - for needle in $2; do - [[ "$haystack" == *",$needle,"* ]] && return 0 - done - return 1 - } - - issue_labels=$(gh api graphql -f query=' - query($owner:String!,$repo:String!,$num:Int!){ - repository(owner:$owner,name:$repo){ - pullRequest(number:$num){ - closingIssuesReferences(first:10){ nodes { labels(first:20){ nodes { name } } } } - } - } - }' -f owner="$REPO_OWNER" -f repo="$REPO_NAME" -F num="$PR_NUMBER" \ - --jq '[.data.repository.pullRequest.closingIssuesReferences.nodes[].labels.nodes[].name] | join(",")') - - needs_entry=false - has_any "$PR_LABELS" "$CATEGORY_LABELS" && needs_entry=true - has_any "$issue_labels" "$CATEGORY_LABELS" && needs_entry=true - - exempt=false - has_any "$PR_LABELS" "$EXEMPT_LABELS" && exempt=true - has_any "$issue_labels" "$EXEMPT_LABELS" && exempt=true - - override=false - has_any "$PR_LABELS" "$OVERRIDE_LABELS" && override=true - - echo "needs-entry=$needs_entry" >> "$GITHUB_OUTPUT" - echo "exempt=$exempt" >> "$GITHUB_OUTPUT" - echo "override=$override" >> "$GITHUB_OUTPUT" - - # Homologated with weave.js's code-release_preview.yml: every PR that - # touches code/** must add its own entry to CHANGELOG.md's [Unreleased] - # section (code-npm_node-publish-release-and-snapshot.yml later promotes - # that section wholesale — nothing is invented at release time). - - name: Require CHANGELOG.md update - if: ${{ steps.changelog-requirement.outputs.needs-entry == 'true' && steps.changelog-requirement.outputs.override != 'true' }} - run: | - if git diff --quiet "${{ github.event.pull_request.base.sha }}" HEAD -- code/CHANGELOG.md; then - echo "::error title=No CHANGELOG.md changes::code/CHANGELOG.md's [Unreleased] section wasn't updated. Add an entry describing this change, label the PR (or the issue it closes) 'kind/internal'/'kind/epic' if it has no user-facing effect, or label the PR itself 'skip-changelog' if you're deliberately choosing not to document it. (skip-release alone does not exempt it — that label only blocks the version bump.)" - exit 1 - fi - - # Catches the labeling gap the requirement-resolution step above can't - # paper over: a PR that isn't exempt (not kind-internal/kind-epic-only) - # but also has no real `kind/*` category anywhere — neither on itself - # nor on an issue it closes. Without this, such a PR would silently - # skip the CHANGELOG.md requirement above instead of failing loudly. - # `skip-changelog` does not exempt a PR from this check — it still needs - # a real category or the internal/epic exemption; it only waives the - # *entry*, not the classification. - - name: Require a changelog category label - if: ${{ steps.changelog-requirement.outputs.needs-entry == 'false' && steps.changelog-requirement.outputs.exempt == 'false' }} - run: | - echo "::error title=Missing changelog category label::This PR needs one of kind/enhancement, kind/bug, kind/documentation, kind/deprecated, kind/removed or kind/security — on the PR itself or on an issue it closes — or kind/internal/kind/epic if it has no user-facing effect. (skip-release alone does not exempt it. skip-changelog does not apply here either — it waives the entry, not the classification.)" - exit 1 # Homologated with weave.js's code-npm_node-PR_verify.yml: same asdf # setup pattern (cache keyed on .tool-versions, install skipped on diff --git a/.github/workflows/code-npm_node-publish-release-and-snapshot.yml b/.github/workflows/code-npm_node-publish-release-and-snapshot.yml index 4c833860..b9f085da 100644 --- a/.github/workflows/code-npm_node-publish-release-and-snapshot.yml +++ b/.github/workflows/code-npm_node-publish-release-and-snapshot.yml @@ -675,6 +675,18 @@ jobs: git config commit.gpgsign true git config tag.gpgsign true + # Writes the entries of the issues closed by the PRs merged since the + # last release tag into [Unreleased], so the bump below and the signed + # CHANGELOG commit include them. Any error stops the job here, before + # the bump, the commit and the tag. See + # .github/scripts/changelog-from-prs.mjs for the rules. + - name: Generate CHANGELOG.md entries from merged pull requests + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + node .github/scripts/changelog-from-prs.mjs --branch "$BASELINE_BRANCH" \ + --changelog code/CHANGELOG.md --report "$GITHUB_STEP_SUMMARY" + - name: Update CHANGELOG.md id: update-changelog uses: release-flow/keep-a-changelog-action@74931dec7ecdbfc8e38ac9ae7e8dd84c08db2f32 # v3.0.0 diff --git a/.github/workflows/code-release_preview.yml b/.github/workflows/code-release_preview.yml index 38abcc8b..7d906724 100644 --- a/.github/workflows/code-release_preview.yml +++ b/.github/workflows/code-release_preview.yml @@ -2,7 +2,7 @@ # Same name, filename and job shape as weave.js's code-release_preview.yml, so # the two repos' release processes read identically at a glance. Divergences # from the weave.js original are called out inline where docouture' toolchain -# (release-type/* labels + CHANGELOG.md, already used identically by +# (release-type/* labels + generated CHANGELOG.md, already used identically by # code-npm_node-publish-release-and-snapshot.yml) or its trunk-based-only # development flow (no gitflow/hotfix merge-strategy distinction to preview) # forces one. See docs/code-release_preview.md for the job-by-job walkthrough. @@ -46,6 +46,8 @@ jobs: if: ${{ contains(join(github.event.pull_request.labels.*.name, ', '), 'release-type') && needs.check-changes-in-paths.outputs.detected == 'true' }} runs-on: ubuntu-24.04 permissions: + contents: read + issues: read pull-requests: write env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} @@ -76,21 +78,26 @@ jobs: if: contains(github.event.pull_request.labels.*.name, 'release-type/major') run: echo "RELEASE_VERSION=major" >> "$GITHUB_ENV" - - name: Check if CHANGELOG.md has changes + - name: Setup Node + uses: actions/setup-node@cdca7365b2dadb8aad0a33bc7601856ffabcc48e # v4 + with: + node-version-file: code/.tool-versions + + # Same script as the release job. Into the local [Unreleased] it writes + # the entries already pending on the base branch (PRs merged since the + # last release tag, usually with skip-release) and then this PR's, so + # the bump below previews the whole release. HEAD is the merge commit, + # so HEAD^1 is the base branch. Whether the PR is linked at all is + # checked by code-changelog-check.yml. + - name: Generate CHANGELOG.md entries for the release env: - IS_FORK: ${{ github.event.pull_request.head.repo.full_name != github.repository }} + PR_NUMBER: ${{ github.event.pull_request.number }} + BASE_REF: ${{ github.event.pull_request.base.ref }} run: | - if git diff --quiet HEAD^ HEAD -- code/CHANGELOG.md; then - echo "::error title={No CHANGELOG.md changes}::{No CHANGELOG.md changes were found. Update the UNRELEASED section with the new changes.}" - # Fork PRs get a read-only GITHUB_TOKEN: the annotation above is - # the only feedback they can receive, the comment would fail. - if [[ "$IS_FORK" != "true" ]]; then - gh pr comment ${{ github.event.number }} --body " - ### :x: No changes in the \`CHANGELOG.md\` file - No changes were found in the \`CHANGELOG.md\` file. Please, update the UNRELEASED section, listing the new changes that applies to this release." - fi - exit 1 - fi + node .github/scripts/changelog-from-prs.mjs --to HEAD^1 --branch "$BASE_REF" \ + --changelog code/CHANGELOG.md --report "$GITHUB_STEP_SUMMARY" + node .github/scripts/changelog-from-prs.mjs --pr "$PR_NUMBER" \ + --changelog code/CHANGELOG.md --report "$RUNNER_TEMP/changelog-report.md" - name: Update CHANGELOG.md id: update-changelog @@ -103,15 +110,17 @@ jobs: keep-unreleased-section: true tag-prefix: "" + # Titles go into code spans here so an @user or @org/team in an issue + # title cannot notify anyone from the comment. CHANGELOG.md is untouched. # docouture is trunk-based only (main + PRs, no gitflow/hotfix branches to # squash-vs-merge-commit between) — weave.js's "Check merge strategy" # step and its "Merge Strategy" comment line have no docouture equivalent # and are dropped here. - # Fork PRs get a read-only GITHUB_TOKEN, so `gh pr comment` cannot post. - - name: Add PR comment with release preview - if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} + - name: Build release preview + env: + NEXT_VERSION: ${{ steps.update-changelog.outputs.version }} run: | - TASKS=$(awk -v version="${{ steps.update-changelog.outputs.version }}" ' + TASKS=$(awk -v version="$NEXT_VERSION" ' BEGIN { capture=0; found_version=0 } $0 ~ "## \\[" version "\\] -" { capture=1; found_version=1; print; next } capture && $0 ~ /^## \[.*\] -/ { capture=0 } @@ -125,15 +134,28 @@ jobs: } } } - ' code/CHANGELOG.md) - MESSAGE=" - - ### :rocket: Release Preview Success - You are going to release the version **${RELEASE_VERSION}** with the following changes: - $TASKS - " + ' code/CHANGELOG.md | node .github/scripts/changelog-from-prs.mjs --wrap-titles) + { + echo "### :rocket: Release Preview Success" + echo "You are going to release the version **${NEXT_VERSION}** (${RELEASE_VERSION}) with the following changes:" + echo "$TASKS" + echo "" + cat "$RUNNER_TEMP/changelog-report.md" + echo "" + echo "_With the \`skip-release\` label, merging publishes no release: the entries of the issues this PR closes go into the next release. Without a linked issue, the PR gets no entry._" + } > "$RUNNER_TEMP/release-preview.md" + + # Fork PRs get a read-only GITHUB_TOKEN, so `gh pr comment` cannot post: + # the preview goes to the job summary instead. + - name: Add PR comment with release preview + if: ${{ github.event.pull_request.head.repo.full_name == github.repository }} + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + run: gh pr comment "$PR_NUMBER" --body-file "$RUNNER_TEMP/release-preview.md" - gh pr comment ${{ github.event.number }} --body "$(echo -e "$MESSAGE")" + - name: Add release preview to the job summary + if: ${{ github.event.pull_request.head.repo.full_name != github.repository }} + run: cat "$RUNNER_TEMP/release-preview.md" >> "$GITHUB_STEP_SUMMARY" release-preview-no-code-changes: name: Add PR comment with configuration management information diff --git a/.github/workflows/docs/code-changelog-check.md b/.github/workflows/docs/code-changelog-check.md new file mode 100644 index 00000000..cc81b551 --- /dev/null +++ b/.github/workflows/docs/code-changelog-check.md @@ -0,0 +1,27 @@ +# `code-changelog-check` + +[`code-changelog-check.yml`](../code-changelog-check.yml) checks that every pull request is linked to the issue it closes, because the release job generates the `CHANGELOG.md` entries from those issues. + +## Trigger + +Any pull request to `main` or `main-*` that is `opened`, `synchronize`d, `reopened`, `ready_for_review`, `labeled`, `unlabeled` or `edited` (the link lives in the PR body). It runs on every PR, whatever paths it changes. + +## Where does it run? + +`ubuntu-24.04` GitHub infrastructure. + +## Rule + +- The link is a GitHub closing reference: a closing keyword in the PR body (`Closes #N`) or the Development sidebar. A plain `#N` mention is not one. GitHub only reads closing keywords on PRs to the default branch, so PRs to `main-*` need the sidebar. +- A maintainer can waive the rule with the `skip-release` label, which also skips the release on merge. The issues such a PR does close still get entries in the next release. +- Dependabot PRs are exempt. +- Issues labelled only `kind/internal` or `kind/epic` (no `kind/*` category) count as a link but get no entry, and an issue already listed in an earlier release is not listed again. Both are shown in the report. `skip-changelog` has no effect. +- The check is warn-only for now: `CHANGELOG_LINK_ENFORCE` is `'false'`. Setting it to `'true'` (a follow-up PR, once a release has run end to end) makes a PR with no linked issue and no bypass fail. + +## Jobs + +- ### `closing-issue` + - **Steps** + - Checkout the pull request and setup Node from `code/.tool-versions`. + - Run the tests of `.github/scripts/changelog-from-prs.mjs`. + - Run `.github/scripts/changelog-from-prs.mjs --pr `, which writes the entries the PR will generate, their sections and any warnings to the job summary. diff --git a/.github/workflows/docs/code-npm_node-publish-release-and-snapshot.md b/.github/workflows/docs/code-npm_node-publish-release-and-snapshot.md index 803d9de9..a7dfaa7f 100644 --- a/.github/workflows/docs/code-npm_node-publish-release-and-snapshot.md +++ b/.github/workflows/docs/code-npm_node-publish-release-and-snapshot.md @@ -80,6 +80,7 @@ Permissions are scoped at the job level following the principle of least privile - Install dependencies and run `lint`, `typecheck`, `format:check`, and `test` before releasing. - Determine the release type from labels. - Prepare committer information and configure GPG signing (gpg-agent with loopback-pinentry and preset-passphrase). + - Generate `[Unreleased]` in `CHANGELOG.md` from the issues closed by the PRs merged since the last numeric tag (`.github/scripts/changelog-from-prs.mjs --branch `); issues labelled only `kind/internal`/`kind/epic`, or already listed in an earlier release, are reported instead of written. Any error fails the job before the bump, the commit and the tag. - Update CHANGELOG.md and calculate next version using `release-flow/keep-a-changelog-action`. - Bump every package to the released version (same `npm run version:release` + `npm run release:prepare` pair as the snapshot job). - Build (`pnpm build`) and locate the `ui-bundle` release artifact. diff --git a/.github/workflows/docs/code-release_preview.md b/.github/workflows/docs/code-release_preview.md index 7e514a6e..586d0cad 100644 --- a/.github/workflows/docs/code-release_preview.md +++ b/.github/workflows/docs/code-release_preview.md @@ -1,6 +1,6 @@ # `code-release-preview` -[`code-release_preview.yml`](../code-release_preview.yml) is the same workflow (name, filename, job shape, triggers) as weave.js's workflow of the same name, adapted to docouture' own `release-type/*` label + `CHANGELOG.md` convention (already used identically by [`code-npm_node-publish-release-and-snapshot.yml`](../code-npm_node-publish-release-and-snapshot.yml)) and to docouture being trunk-based only. +[`code-release_preview.yml`](../code-release_preview.yml) is the same workflow (name, filename, job shape, triggers) as weave.js's workflow of the same name, adapted to docouture' own `release-type/*` label + generated `CHANGELOG.md` convention (already used identically by [`code-npm_node-publish-release-and-snapshot.yml`](../code-npm_node-publish-release-and-snapshot.yml)) and to docouture being trunk-based only. ## Triggers @@ -12,20 +12,20 @@ Any pull request targeting `main`/`main-*`, on `labeled`, `synchronize`, `ready_ ## How does it work? -Three jobs, gated by a shared `check-changes-in-paths` job (`dorny/paths-filter` on `code/**` and `.github/workflows/code**`, same paths `code-npm_node-pr-verify.yml` requires a `CHANGELOG.md` entry for) and by whether the PR carries a `release-type/*` label: +Three jobs, gated by a shared `check-changes-in-paths` job (`dorny/paths-filter` on `code/**` and `.github/workflows/code**`, same paths `code-npm_node-pr-verify.yml` builds for) and by whether the PR carries a `release-type/*` label: - Label present + matching path changes → `release-preview`. - Label present, no matching path changes → `release-preview-no-code-changes`. - No label, matching path changes → `release-preview-no-release-labels`. -None of these jobs release anything — they only comment on the PR with what _would_ happen, so a reviewer can catch a missing `CHANGELOG.md` entry or a missing label before merge, the same way weave.js's does. +None of these jobs release anything — they only comment on the PR with what _would_ happen, so a reviewer can see the generated `CHANGELOG.md` entries and catch a missing label before merge, the same way weave.js's does. ## Divergences from weave.js's workflow of the same name - **No merge-strategy preview**: weave.js's `release-preview` job also computes and comments a "Merge Strategy" line (squash vs. merge-commit), driven by a `DEVELOPMENT_FLOW` repo variable and hotfix-branch-name heuristics for its gitflow-style branching. docouture is trunk-based only (main + PRs, no long-lived develop/hotfix branches to choose a strategy between — see `code-npm_node-publish-release-and-snapshot.md`'s "No gitflow sync-to-develop PR" note), so that step, its "Check merge strategy" logic and its comment line are dropped entirely. - **No `DEVELOPMENT_FLOW`-gated no-labels job**: weave.js only shows `release-preview-no-release-labels` when `vars.DEVELOPMENT_FLOW != 'trunk-based-development'`. Since docouture is always trunk-based, this job always fires when a matching-path PR carries no `release-type/*` label — no variable to gate on. - **Explicit `GITHUB_TOKEN`/`pull-requests: write` per job**: weave.js's workflow leaves these implicit (no `permissions:` block, no job-level `env:` for the token in its `release-preview` job's final comment step). Ported here with an explicit `permissions: pull-requests: write` and job-level `GITHUB_TOKEN` env in all three jobs, matching the least-privilege style `code-npm_node-publish-release-and-snapshot.yml` already uses. -- **Path filter**: `code/**` and `.github/workflows/code**`, not weave.js's bare `code/**` — matching the filter `code-npm_node-pr-verify.yml` already uses for its own `CHANGELOG.md` check. +- **Path filter**: `code/**` and `.github/workflows/code**`, not weave.js's bare `code/**` — matching the filter `code-npm_node-pr-verify.yml` already uses. - **Action pins**: `dorny/paths-filter` and `release-flow/keep-a-changelog-action` are pinned to the same commit SHAs `code-npm_node-publish-release-and-snapshot.yml` already uses, rather than weave.js's own (potentially different) pins. ## Fork pull requests @@ -34,9 +34,9 @@ On a `pull_request` from a fork, GitHub gives the workflow a read-only `GITHUB_T | | same-repo PR | fork PR | |---|---|---| -| `CHANGELOG.md` diff check | runs | runs, fails the job if missing (annotation only, no comment) | +| `[Unreleased]` generation | runs | runs (read-only token is enough) | | version bump computation | runs | runs | -| PR comments | posted | skipped | +| PR comments | posted | skipped (preview goes to the job summary) | ## Jobs @@ -50,9 +50,10 @@ On a `pull_request` from a fork, GitHub gives the workflow a read-only `GITHUB_T - Checkout the merge commit. - Map the `release-type/*` label to a semver bump (`hotfix`/`multi-hotfix`/`patch` → `patch`, `minor` → `minor`, `major` → `major`). - - Fail with a PR comment if `code/CHANGELOG.md` has no diff against the previous commit. + - Setup Node from `code/.tool-versions`. + - Generate `[Unreleased]` with `.github/scripts/changelog-from-prs.mjs` in two passes: the entries already pending on the base branch (`--to HEAD^1 --branch `, the merge commit's first parent), then this PR's (`--pr `). Contributors no longer edit `CHANGELOG.md`. - Compute the next version via `release-flow/keep-a-changelog-action` (dry-run bump, same action the real release workflow uses). - - Comment on the PR with the version that will be released and the `[Unreleased]` entries that will move under it. + - Comment on the PR with the version that will be released and the `[Unreleased]` entries that will move under it, followed by the PR's own changelog report. Titles are wrapped in code spans so an `@mention` in an issue title cannot notify anyone. Fork PRs get the same text in the job summary instead. - ### `release-preview-no-code-changes` diff --git a/.opencode/skills/changelog/SKILL.md b/.opencode/skills/changelog/SKILL.md index 3a1d7f7a..e553c6df 100644 --- a/.opencode/skills/changelog/SKILL.md +++ b/.opencode/skills/changelog/SKILL.md @@ -1,183 +1,105 @@ --- name: changelog -description: "How code/CHANGELOG.md is written and grouped in this monorepo — the entry format, which GitHub label puts a change under which Keep a Changelog section, and the issue/PR two-tier convention that decides what gets an entry at all. USE WHEN adding or editing a CHANGELOG.md entry, deciding whether a PR needs one, choosing which section (Added/Fixed/Documentation/...) an entry belongs in, labeling a PR or issue, or touching the pr-verify CHANGELOG gate. EXAMPLES: 'add a changelog entry for this PR', 'does this PR need a changelog line', 'which section does a kind/internal change go in', 'why does pr-verify say my CHANGELOG entry is missing a label', 'the changelog action failed to bump the version'." +description: "How code/CHANGELOG.md is generated and grouped in this monorepo — the entry format, which GitHub issue label puts a change under which Keep a Changelog section, and the rule that every PR must close an issue. USE WHEN deciding whether a PR needs a CHANGELOG entry, choosing which section (Added/Fixed/Documentation/...) an entry belongs in, labeling a PR or issue, writing or reviewing an issue title, or touching changelog-from-prs.mjs or the changelog CI checks. EXAMPLES: 'does this PR need a changelog line', 'which section does a kind/internal change go in', 'how do I change the wording of a changelog entry', 'why does the changelog check say my PR closes no issue', 'the changelog action failed to bump the version'." metadata: internal: true --- # CHANGELOG.md conventions -> **Common mistake — read this before deciding "no entry needed":** -> `skip-release` is NOT a stop condition. It only tells the release-flow bump action to -> defer the version bump; it says nothing about whether a CHANGELOG entry is needed. The -> **only** labels that mean "no entry" are `kind/internal` and/or `kind/epic` (checked on -> the PR, else the closing issue), or `skip-changelog` **on the PR itself** (a deliberate -> override that wins even over a real `kind/*` category — see below). If you catch -> yourself writing "labeled skip-release → no entry", stop: go check for `skip-changelog` -> on the PR or the closing issue's `kind/*` label instead (see "Two-tier" below for the -> lookup command). +**Contributors do not edit `code/CHANGELOG.md`.** The `[Unreleased]` entries are generated +at release time from the issues that merged PRs close (GitHub `closingIssuesReferences`), +by `.github/scripts/changelog-from-prs.mjs`. What a contributor controls is the PR's +closing issue: its title and its `kind/*` label. `code/CHANGELOG.md` follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) + [SemVer](https://semver.org/). Version bumps are performed by `release-flow/keep-a-changelog-action`'s `bump` command, called from -`.github/workflows/code-npm_node-publish-release-and-snapshot.yml`. That action only -parses the `## [Unreleased]` / `## [x.y.z]` H2 boundary (see its `src/types.ts` — -`ReleaseHeading` keys off H2 headings only); the `### `-level section names underneath -are a **repo convention we control**, not something the action validates or requires to -match Keep a Changelog's canonical vocabulary. Which semver segment gets bumped is decided -separately, by the `release-type/{major,minor,patch,hotfix,multi-hotfix}` label on the -merged/closing PR — that label is completely orthogonal to which CHANGELOG section an -entry lands in. +`.github/workflows/code-npm_node-publish-release-and-snapshot.yml`, right after the +generator ran. That action only parses the `## [Unreleased]` / `## [x.y.z]` H2 boundary; +the `### `-level section names are a repo convention. Which semver segment gets bumped is +decided separately, by the `release-type/{major,minor,patch,hotfix,multi-hotfix}` label on +the merged PR — orthogonal to which section an entry lands in. + +``` +PR opened/edited/labeled -> Changelog / Closing issue -> changelog-from-prs.mjs --pr N +PR merged (release) -> release job -> changelog-from-prs.mjs (last tag..HEAD) -> [Unreleased] + -> keep-a-changelog bump -> sanitize -> signed commit -> tag +``` + +## The rule: every PR closes an issue + +Link it with a closing keyword (`Closes #N`) or the Development sidebar. A plain `#N` +does not count. Exempt: PRs labelled `skip-release`, and Dependabot. An exempt PR with no +issue simply gets no entry; a `skip-release` PR that **does** close an issue still gets +its entry (those PRs are released later). `skip-release` is otherwise only the "don't +bump the version yet" label. + +There is no `skip-changelog` label anymore: it has no effect. Whether an issue produces an +entry is decided only by its labels. ## Entry format ``` -- [#PR_ID](PR_URL) PR_NAME +- [#ISSUE_ID](ISSUE_URL) ISSUE_TITLE ``` -`PR_ID`/`PR_URL` always point at the **PR that shipped the code** (not a tracking issue — -issues aren't browsable diffs and don't have a merge). `PR_NAME` is the PR's title, and -the PR's title must be kept identical to its linked issue's title, scope tag included -(e.g. `[ui-bundle] Header toolbar`) — see "Two-tier: issue vs PR" below for why the issue -owns the canonical name. +The title is the issue title verbatim, only normalising NBSP/zero-width whitespace. To fix +the wording of an entry, edit the issue title (keep the `[scope]` tag, e.g. +`[ui-bundle] Header toolbar`). Entries are deduplicated by issue number, so several PRs +closing the same issue produce one line, and an issue already listed in an earlier +released section is not listed again (it is reported as a warning). Entries up to +1.3.2 link PRs instead; `changelog-pages.js` reads both. -## Label → section mapping +## Label → section mapping (on the issue, first match wins) | Label | Section | | --- | --- | -| `kind/enhancement` | `### Added` | +| `kind/security` | `### Security` | | `kind/bug` | `### Fixed` | -| `kind/documentation` | `### Documentation` (not canonical Keep a Changelog vocabulary, but this repo ships a docs generator, so doc-only changes are common enough to deserve their own bucket instead of being buried in Added) | +| `kind/enhancement` | `### Added` | +| `kind/documentation` | `### Documentation` | | `kind/deprecated` | `### Deprecated` | | `kind/removed` | `### Removed` | -| `kind/security` | `### Security` | -| `kind/internal` | **no entry** (see below) | -| `kind/epic` | not a section — a size/container flag only, never on its own decides anything | -| `skip-release` | **not exempt on its own** — blocks the version bump only, still needs a normal entry unless `kind/internal`/`kind/epic` also applies (see below) | -| `skip-changelog` | **no entry** — but unlike every other row, this one is PR-only (never resolved via the closing issue) and overrides regardless of category (see below) | - -Omit empty section headings entirely rather than leaving them with no bullets under them. - -### `kind/internal` and `kind/epic` mean "no changelog entry" — `skip-release` does not - -If, after resolving labels (below), the only labels that apply are `kind/internal` and/or -`kind/epic` — with none of the six real category labels above also present — the PR/issue -gets **no CHANGELOG entry at all**. `kind/epic` by itself never produces an entry either -way; it just flags that an issue is a large, multi-PR unit of work. If a change is *both* -e.g. `kind/enhancement` and `kind/epic`, the real category wins and it gets a normal -`### Added` entry. - -`skip-release` is a **separate, orthogonal concern**: it tells the release-flow bump -action not to cut a version for this PR (e.g. one slice of a multi-PR issue where only -the last PR should trigger the release). It does **not** exempt the PR from the -CHANGELOG.md requirement — a `skip-release` PR still needs its entry in `[Unreleased]` -if it (or its closing issue) carries a real category label; the entry just gets promoted -into a versioned section later, whenever some other PR does trigger the bump. - -### `skip-changelog`: a deliberate per-PR override, distinct from `kind/internal`/`kind/epic` - -`kind/internal`/`kind/epic` say the change **has no user-facing effect** — that's a fact -about the change itself, and it's just as true whoever reviews it. `skip-changelog` says -something different: the change is real (it may well carry `kind/security`, `kind/bug`, -etc.) but the person merging this specific PR is **consciously choosing** not to give it -its own line — e.g. a narrow CI/tooling fixup on a PR whose substantive change was already -documented, or a judgment call that this diff doesn't need its own entry despite its -category. - -Because it's a judgment call about *this diff*, not a property of the tracked issue, it's -checked **only on the PR itself** — never resolved via the closing issue the way every -other label in this table is. It overrides even a real `kind/*` category: a PR labeled -both `kind/security` and `skip-changelog` gets no entry. It does not, however, exempt the -PR from needing a real category or the internal/epic exemption in the first place (see -"Require a changelog category label" in CI enforcement below) — it only waives the entry, -not the classification. - -Reach for it rarely, and leave a one-line reason in the PR description when you do (not -CI-enforced, just convention — the label alone doesn't explain itself to the next reader -of `git log`). - -## Two-tier: issue vs PR, and how to resolve the label - -This repo tracks larger changes with a GitHub **issue** (the user-facing unit of work, -carrying the real `kind/*` category label and often a `[scope]` prefix in its title, e.g. -`[cli]`, `[ui-bundle]`, `[tooling]`) that's implemented by one or more **PRs** (the -concrete shipped diffs). Because an issue can span several PRs, those implementing PRs are -routinely labeled `skip-release` — merging one slice of a multi-PR issue shouldn't bump -the version yet, but each slice still gets its own CHANGELOG entry as it merges. The real -category most often lives on the issue, not the PR. - -Resolution order when writing/reviewing an entry: - -1. **The PR's own label wins if it carries one of the six real category labels - directly** — a PR can legitimately be more/less user-facing than the issue it belongs - to (e.g. an issue is `kind/enhancement` overall, but one of its PRs was pure internal - scaffolding and is itself labeled `kind/internal` — that PR gets no entry even though - its issue would otherwise qualify). -2. **Otherwise, fall back to the label(s) of the issue the PR closes** (GitHub's "Closes - #N" / `closingIssuesReferences`). -3. If a PR closes more than one issue, prefer the **non-epic** issue as the source of - truth for the title/category — `kind/epic` issues are containers, not the concrete - change being shipped. -4. If neither the PR nor any closed issue carries a real category label, and it isn't - `kind/internal`/`kind/epic` either, that's a labeling gap — fix the label on GitHub - before merging, don't guess a section. (`skip-release` alone never resolves this gap — - it doesn't carry a category and doesn't exempt the PR.) - -To find a PR's closing issue(s) from the CLI: - -```bash -gh api graphql -f query=' - query($owner:String!,$repo:String!,$num:Int!){ - repository(owner:$owner,name:$repo){ - pullRequest(number:$num){ - title - closingIssuesReferences(first:5){ nodes { number title labels(first:10){nodes{name}} } } - } - } - }' -f owner=InditexTech -f repo=docouture -F num= -``` - -(`gh pr view --json closingIssuesReferences` doesn't expose this field; it has to go -through `gh api graphql`.) - -## Keeping PR titles aligned to their issue - -Whenever a PR's title drifts from its linked issue's title (common — PRs tend to get a -shorter, code-focused title while the issue keeps the fuller/scoped one), rename the PR to -match the issue **verbatim, scope tag included**, before writing the CHANGELOG entry: +| `kind/internal` / `kind/epic` alone | **no entry** (listed in the report as out of scope, never dropped silently) | +| none of the above | `### Changed`, with a "section guessed" warning — fix the label | + +A real category label wins over `kind/internal`/`kind/epic`; `kind/epic` is a size flag +only. Empty sections are omitted. + +## Where it runs + +- `.github/workflows/code-changelog-check.yml` — every PR to `main`/`main-*` (not + path-filtered): runs the script's tests, then previews the entry in the job summary and + flags a PR that closes no issue. Warn-only while `CHANGELOG_LINK_ENFORCE` is `"false"`; + flip it to `"true"` to fail the check instead. +- `.github/workflows/code-release_preview.yml` — two passes into the local `[Unreleased]`: + the entries already pending on the base branch (`--to HEAD^1 --branch `), then this + PR's (`--pr N`), before the dry-run bump that feeds the PR comment. Titles are wrapped in + code spans (`--wrap-titles`) so an `@user` in an issue title cannot notify anyone. +- Release job in `code-npm_node-publish-release-and-snapshot.yml` — generates before the + bump with `--branch "$BASELINE_BRANCH"`; any error fails the job before the tag exists. + The snapshot job does not generate. +- `.github/scripts/sanitize-changelog.mjs` still runs after every bump (and as + `--check` in pr-verify) to keep invisible whitespace out of the file; the generator + reuses its `normalizeInvisibleWhitespace` for titles. + +## Running it locally ```bash -# gh pr edit can fail on this workspace's pinned gh CLI version (2.20.2) with a -# "Projects (classic)" GraphQL error even for pure title edits — use the REST API instead: -gh api repos/InditexTech/docouture/pulls/ -X PATCH -f title="" +export GITHUB_TOKEN=$(gh auth token) +# what would 1.3.1..1.3.2 produce? Compares with the hand-written [1.3.2] section (read-only) +node .github/scripts/changelog-from-prs.mjs --dry-run --from 1.3.1 --to 1.3.2 --changelog code/CHANGELOG.md +# preview one PR +node .github/scripts/changelog-from-prs.mjs --pr 297 +# tests +node --test .github/scripts/changelog-from-prs.test.mjs ``` -## Adding a CHANGELOG entry for a new PR — checklist - -1. Is the PR itself labeled `skip-changelog`? → no entry needed, stop here — this - overrides even a real category, but doesn't exempt the PR from needing one (see step 2 - below still applying for labeling-hygiene purposes). -2. Otherwise, is the PR (or its closing issue, per the resolution order above) labeled - only `kind/internal`/`kind/epic`, with no real category label anywhere? → no entry - needed, stop here. (`skip-release` by itself does **not** stop here — keep going.) -3. Otherwise it needs exactly one of the six real category labels (`kind/enhancement`, - `kind/bug`, `kind/documentation`, `kind/deprecated`, `kind/removed`, `kind/security`), - resolved per the order above. If none is present, add the correct label on GitHub - first. -4. Make sure the PR's title matches its issue's title verbatim (rename via the `gh api` - command above if not). -5. Add `- [#]() ` under the matching `###` section in - `[Unreleased]`, newest-first within the section. - -## CI enforcement - -`.github/workflows/code-npm_node-pr-verify.yml` fails a PR touching `code/**` that doesn't -update `code/CHANGELOG.md`, unless the PR (or its closing issue) is `kind/internal`/ -`kind/epic`-only, or the PR itself carries `skip-changelog`. `skip-release` is -deliberately **not** in that exemption list — it only affects -`release-flow/keep-a-changelog-action`'s version-bump step in the publish workflow, so a -`skip-release` PR still fails this check if it hasn't added its entry. The same job also -fails when `CHANGELOG.md` **is** touched but neither the PR nor its closing issue carries -exactly one of the six real category labels — closing the gap where an entry gets added -under the wrong (or no) section. `skip-changelog` does not exempt a PR from that second -check either — it waives the entry, not the classification. +Range mode finds PRs from first-parent commits since +`git describe --tags --abbrev=0 --match '[0-9]*'` (which skips `docs/*` tags), keeps only +PRs merged into `--branch` (default `main`), and with `--changelog` writes only +`[Unreleased]`: manual lines are kept, issues already listed there are not repeated, the +rest of the file is verified byte-identical before writing, and it is idempotent. Any API +or git error exits non-zero. Hitting a pagination limit also fails instead of silently +dropping an issue or label. diff --git a/AGENTS.md b/AGENTS.md index 7ca31ee8..20a398fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -112,20 +112,18 @@ npx skills@latest add InditexTech/docouture --all -## CHANGELOG entries — critical rule (do not get this wrong again) - -`skip-release` does **NOT** mean "no CHANGELOG entry". It only blocks the version bump. -The **only** labels that mean no entry are `kind/internal`/`kind/epic` alone (checked on -the PR, else on the issue it closes). A `skip-release` PR whose issue is -`kind/enhancement`/`kind/bug`/`kind/documentation`/`kind/deprecated`/`kind/removed`/ -`kind/security` still needs its `- [#PR](URL) title` line in `code/CHANGELOG.md`'s -`[Unreleased]` — **unless the PR itself** (not the issue) also carries `skip-changelog`, -a deliberate per-PR override: unlike `kind/internal`/`kind/epic` (which say the change has -no user-facing effect), `skip-changelog` says the change is real but the merger is -consciously choosing not to give it its own entry, and it wins even over a real `kind/*` -category. Full rules: `.opencode/skills/changelog/SKILL.md` — but if that skill's own tool -output ever contradicts this paragraph or the file on disk, trust this file and the actual -file/`.github/workflows/code-npm_node-pr-verify.yml`, not the tool output. +## CHANGELOG entries — do not hand-edit + +`code/CHANGELOG.md`'s `[Unreleased]` entries are generated at release time from the issues +that merged PRs close (`.github/scripts/changelog-from-prs.mjs`). Do not add entries by +hand. Every PR must close an issue (`Closes #N` or the Development sidebar; a plain `#N` +does not count) — the entry is `- [#N](issue URL) `, in the section given by +the issue's `kind/*` label. `kind/internal`/`kind/epic` alone means no entry. `skip-release` +(and Dependabot) exempt a PR from needing an issue but do **not** stop an issue it does +close from getting its entry. `skip-changelog` no longer exists and has no effect. To change +an entry's wording, edit the issue title. Full rules: +`.opencode/skills/changelog/SKILL.md` — if that skill ever contradicts this paragraph or +the script, trust the script and `.github/workflows/code-changelog-check.yml`. ## GitHub issue titles — critical rule (do not get this wrong again) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 77c475d3..41cea27a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -86,11 +86,27 @@ logo is ever redesigned, update both locations. ### Before Submitting - Run `just check` — lint, typecheck and formatting, the same checks CI runs. -- Update `code/CHANGELOG.md`'s `[Unreleased]` section with an entry describing - your change. CI enforces this on every PR that touches `code/**` unless the - PR is labelled `skip-release` (for changes with no user-facing effect — - internal tooling, CI config, etc.). -- Link the corresponding issue in your pull request. +- Link the issue your PR resolves: add `Closes #ISSUE_ID` to the PR description (the PR + template has the line), or link the issue from the Development sidebar. A plain + `#ISSUE_ID` mention does not count. GitHub only reads closing keywords on PRs to the + default branch, so for a `main-*` branch use the Development sidebar. + - Do not edit `code/CHANGELOG.md`: the release job generates one entry per linked issue, + `- [#ISSUE_ID](https://github.com/InditexTech/docouture/issues/ISSUE_ID) ISSUE_TITLE`, + with the **verbatim title of the issue** at release time. + - The section comes from the issue's `kind/*` label, first match wins: `kind/security` → + Security, `kind/bug` → Fixed, `kind/enhancement` → Added, `kind/documentation` → + Documentation, `kind/deprecated` → Deprecated, `kind/removed` → Removed, anything else → + Changed (flagged as guessed). + - Issues labelled only `kind/internal` or `kind/epic` get no entry, and an issue already + listed in an earlier release is not listed again. Both are shown in the report. + - To change the wording of an entry, edit the issue title; to change its section, change + the issue labels. + - Releases up to 1.3.2 keep their hand-written changelog sections as history. + - The `Changelog / Closing issue` check reports the entries the PR will generate, and + (once enforced) fails if the PR has no linked issue and no `skip-release` label. + Dependabot PRs are exempt. A maintainer adds `skip-release` for a PR that publishes no + release and does not need an issue; the issues it does close still get entries in the + next release. ## License diff --git a/README.md b/README.md index 410c0976..61a29987 100644 --- a/README.md +++ b/README.md @@ -152,8 +152,8 @@ dependencies. ## Contributing See [`CONTRIBUTING.md`](CONTRIBUTING.md) for the contribution workflow, -including the CLA prerequisite and the `code/CHANGELOG.md` entry every PR -touching `code/**` is expected to carry. +including the CLA prerequisite and the closing issue every PR must link +(its changelog entry is generated from it at release time). ## License diff --git a/code/CHANGELOG.md b/code/CHANGELOG.md index 4238e6b5..a58d4b62 100644 --- a/code/CHANGELOG.md +++ b/code/CHANGELOG.md @@ -5,10 +5,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -Each entry is `- [#PR_ID](PR_URL) PR_NAME`, where `PR_NAME` matches the title of the -GitHub issue that tracks the change (see the `changelog` skill for the full convention: -which GitHub label maps to which section below, and why some merged PRs carry no entry -at all). +The `[Unreleased]` entries are generated at release time from the issues that merged +PRs close, so do not edit them by hand. Each entry is `- [#ISSUE_ID](ISSUE_URL) ISSUE_TITLE` +and its section comes from the issue's `kind/*` label (see the `changelog` skill for the +full convention, including why some issues produce no entry at all). Entries below +`[1.3.2]` predate this and link the PR that shipped the change. ## [Unreleased] diff --git a/docs/src/modules/main/pages/contributing.adoc b/docs/src/modules/main/pages/contributing.adoc index 0f5f53b9..848910e3 100644 --- a/docs/src/modules/main/pages/contributing.adoc +++ b/docs/src/modules/main/pages/contributing.adoc @@ -17,9 +17,9 @@ what actually applies; see `CONTRIBUTING.md` in that repository for the full tex . Open an issue to discuss the change first. . Fork, branch, and make the change. . Run `just check` (lint, typecheck, formatting — what CI runs). -. Update `code/CHANGELOG.md`'s `[Unreleased]` section — required on every PR touching - `code/**`, unless labelled `skip-release` for a change with no user-facing effect. -. Open a pull request linking the issue. +. Open a pull request that closes the issue (`Closes #N`; a plain `#N` does not count). + Do not edit `code/CHANGELOG.md`: its entries are generated at release time from the + closing issue's title and `kind/*` label. A PR labelled `skip-release` may omit the issue. == Contributing to this site specifically diff --git a/openspec/changes/generate-changelog-from-closing-issues/.openspec.yaml b/openspec/changes/generate-changelog-from-closing-issues/.openspec.yaml new file mode 100644 index 00000000..2a7773d6 --- /dev/null +++ b/openspec/changes/generate-changelog-from-closing-issues/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-11 diff --git a/openspec/changes/generate-changelog-from-closing-issues/design.md b/openspec/changes/generate-changelog-from-closing-issues/design.md new file mode 100644 index 00000000..3eb83d6e --- /dev/null +++ b/openspec/changes/generate-changelog-from-closing-issues/design.md @@ -0,0 +1,40 @@ +# Design + +## Context + +See proposal.md. Today `code-npm_node-pr-verify.yml` gates on a hand-edited `[Unreleased]` and a category label; the release job (`workflow_dispatch` ACTION=release in `code-npm_node-publish-release-and-snapshot.yml`) runs `keep-a-changelog bump` then `sanitize-changelog.mjs`. A second bump exists in the snapshot job and must stay untouched. `code/packages/antora-extensions/lib/changelog-pages.js` parses `[#N](url)` entries. Reference implementation: weavejs#1236 / PRs #1252, #1286. + +## Goals / Non-Goals + +**Goals:** +- One script, two modes (range, `--pr N`) sharing the same resolution code. +- Release never silently produces a wrong changelog; failures happen before tagging. + +**Non-Goals:** +- Retro-rewriting existing changelog sections. +- Keeping `skip-changelog`. +- Enforcing on day one. + +## Decisions + +- **Port the weavejs implementation rather than rewrite it.** `/Users/jesusmpc/Inditex/weavejs/.github/scripts/changelog-from-prs.mjs` already carries the already-released guard, pagination guard, write verification, `--wrap-titles` and rate-limit retry, and keeping the two repos aligned eases future syncs. Only the label mapping, the exclusion rule and metadata are adapted. A first from-scratch version was discarded for lacking those safeguards. +- **Issue as source of truth, PR as locator.** PRs found by first-parent commits since `git describe --tags --abbrev=0 --match '[0-9]*'`, mapped via GraphQL `associatedPullRequests` (merged, base = `--branch`) to `closingIssuesReferences`. Alternative: date ranges, rejected as fragile across hotfix branches (`main-*`). +- **Link to the issue, dedupe by issue number.** Handles multi-PR issues; verified compatible with `changelog-pages.js`. +- **Title verbatim, reusing `sanitize-changelog.mjs` normalisation.** Wording fixes happen by editing the issue. +- **Exemption = `skip-release` + Dependabot only.** `skip-changelog` dropped: with the issue as sole input there is no multi-PR label conflict, and `kind/internal`/`kind/epic` is the single "no entry" mechanism. +- **Warn-only rollout via `CHANGELOG_LINK_ENFORCE`**, flipped by a follow-up PR after one end-to-end release. +- **Generate step placed before `keep-a-changelog bump` in the release job only**; `fail-on-empty-release-notes: false` is already set, verify an empty `[Unreleased]` is tolerated. +- **Plain Node (.mjs), GraphQL via `fetch` with retry+backoff on 5xx/429/rate limits**, tests with `node --test` and an injected `fetch`, matching existing `.github/scripts` style. Needs only `GITHUB_TOKEN`, no `gh`. +- **Exclusion rule differs from weavejs:** weavejs drops any issue labelled `internal`; here `kind/internal`/`kind/epic` exclude an issue only when no real `kind/*` category is present, preserving the convention that a real category wins. +- **Release preview in two passes** (`--to HEAD^1 --branch `, then `--pr N`) instead of one `--include-pr`, so the preview includes entries pending from `skip-release` PRs and the PR's own report. + +## Risks / Trade-offs + +- [Merge strategy assumption: first-parent maps to PRs] -> confirm the repo's merge strategy; validate with `--dry-run` on `1.2.0..1.3.0` and `1.3.1..1.3.2` against hand-written sections. +- [Hand-written sections up to 1.3.2 link PRs, generated ones link issues, so the already-released guard cannot match old entries] -> only matters for issues released before the first generated release; accepted. +- [Always-on check not in required checks, cf. "Code / Verify never reports"] -> list branch-protection update as a manual step in the PR. +- [Fork PR token is read-only] -> job-summary fallback. +- [Issue link format changes from PR to issue] -> confirm `changelog-pages.js` output. +- [No-issue PRs (#232, #249, #250, #294 style)] -> warn-only period, then `skip-release` bypass. +- [Legacy `skip-changelog` labels linger] -> ignored; retire label manually. +- [Maintenance branches `main-*`] -> `git describe` resolves by ancestry; test explicitly. diff --git a/openspec/changes/generate-changelog-from-closing-issues/proposal.md b/openspec/changes/generate-changelog-from-closing-issues/proposal.md new file mode 100644 index 00000000..7196ca93 --- /dev/null +++ b/openspec/changes/generate-changelog-from-closing-issues/proposal.md @@ -0,0 +1,35 @@ +# Proposal + +## Why + +Every PR touching `code/**` must hand-edit `[Unreleased]` in `code/CHANGELOG.md`. This causes merge conflicts on the same lines, forgotten entries, and drift between PR title, issue title and changelog line. The entry format is already mechanical. InditexTech/weavejs solved this (weavejs#1236) by generating entries at release time from the issues merged PRs close. See InditexTech/docouture#300. + +## What Changes + +- Port `.github/scripts/changelog-from-prs.mjs` (and its tests) from InditexTech/weavejs#1252/#1286/#1288, adapted to this repo's `kind/*` labels and a Documentation section. Two modes: range mode (last numeric tag..`--to`, restricted to PRs merged into `--branch`, writes `[Unreleased]`) and `--pr N` mode (read-only preview/check), plus `--dry-run` (compares with the hand-written `[--to]` section), `--report`, `--enforce` and `--wrap-titles`. +- Entries are generated from each merged PR's closing issues (GitHub `closingIssuesReferences`): `- [#N](.../issues/N) `, deduplicated by issue number. Section is chosen from the issue's `kind/*` label (first match wins); no label falls back to Changed with a warning; `kind/internal`/`kind/epic` alone produce no entry but are listed in the report. +- Every PR must close an issue (closing keyword or Development sidebar). Bypass: the `skip-release` label; Dependabot is exempt. A bypassed PR with no issue gets no entry; a `skip-release` PR that closes an issue still gets its entry. +- **BREAKING (contributor workflow)**: contributors no longer edit `code/CHANGELOG.md`. The `skip-changelog` label is dropped entirely and has no effect; the issue's labels alone decide whether and where an entry appears. +- The script skips an issue already listed in an earlier released section (with a warning), verifies before writing that only `[Unreleased]` changes and each added entry appears exactly once, and fails instead of silently truncating when a GitHub pagination limit is hit. +- Add an always-on `code-changelog-check.yml` workflow (not path-filtered, `issues: read`, runs the script's tests, warn-only first via `CHANGELOG_LINK_ENFORCE`, job summary for fork PRs). +- Release job in `code-npm_node-publish-release-and-snapshot.yml` runs the script before `keep-a-changelog bump`; the snapshot job is untouched. Script errors fail the job before the tag is created. +- Remove the hand-edit gates in `code-npm_node-pr-verify.yml` ("Require CHANGELOG.md update", "Require a changelog category label", `skip-changelog` resolution) and replace `code-release_preview.yml`'s "CHANGELOG.md has changes" check with a two-pass generation (entries pending on the base branch, then this PR's), titles wrapped in code spans in the comment, and a job-summary preview for fork PRs. +- Add `.github/pull_request_template.md` with a `Closes #` prompt. +- Update `CONTRIBUTING.md`, the `changelog` skill, `AGENTS.md` (rewrite the CHANGELOG critical-rule paragraph), the `code/CHANGELOG.md` intro, and `.github/workflows/docs/*`. +- Reference implementation: `/Users/jesusmpc/Inditex/weavejs` (script, tests, `code-changelog-check.yml`, release job, release preview, docs). +- Rollout: single PR merged with `skip-release`; validate with `--dry-run` on `1.2.0..1.3.0` and `1.3.1..1.3.2`; warn-only first, a follow-up PR enforces. + +## Capabilities + +### New Capabilities +- `changelog-generation`: how `[Unreleased]` entries are derived at release time from merged PRs' closing issues, and how PRs are checked/previewed against that rule. + +### Modified Capabilities + +## Impact + +- Code: new `.github/scripts/changelog-from-prs.mjs` (+ tests); `.github/scripts/sanitize-changelog.mjs` now exports `normalizeInvisibleWhitespace`. +- Workflows: `code-npm_node-pr-verify.yml`, `code-npm_node-publish-release-and-snapshot.yml`, `code-release_preview.yml`, new `code-changelog-check.yml`. +- Docs/meta: `CONTRIBUTING.md`, `AGENTS.md`, `.opencode/skills/changelog/SKILL.md`, `code/CHANGELOG.md` intro, `.github/workflows/docs/*`, new PR template. +- Manual (outside repo): add the new check to branch protection required checks; retire the `skip-changelog` label and update the `skip-release` label description. +- Compat: new entries link issues (`issues/N`) instead of PRs (`pull/N`); `changelog-pages.js` parses `[#N](url)` and must keep working. diff --git a/openspec/changes/generate-changelog-from-closing-issues/specs/changelog-generation/spec.md b/openspec/changes/generate-changelog-from-closing-issues/specs/changelog-generation/spec.md new file mode 100644 index 00000000..1a05eb2c --- /dev/null +++ b/openspec/changes/generate-changelog-from-closing-issues/specs/changelog-generation/spec.md @@ -0,0 +1,112 @@ +# Spec Delta + +## Purpose + +Defines how `code/CHANGELOG.md` `[Unreleased]` entries are generated at release time from the issues closed by merged PRs, and how PRs are checked against the issue-linking rule, so contributors never hand-edit the changelog. + +## ADDED Requirements + +### Requirement: Entries are generated from closing issues +At release time the system SHALL write `[Unreleased]` entries from the closing issues of every PR merged between the last numeric release tag and HEAD, as `- [#N]() `, deduplicated by issue number, and SHALL NOT require contributors to edit `code/CHANGELOG.md`. + +#### Scenario: Multiple PRs close the same issue +- **WHEN** two merged PRs in the range both close issue #N +- **THEN** exactly one entry for #N appears in `[Unreleased]` + +#### Scenario: Docs tags ignored +- **WHEN** the range start is resolved and `docs/*` tags exist +- **THEN** only tags matching `[0-9]*` are considered + +### Requirement: Section chosen from issue labels +The system SHALL place each entry in the section chosen by the first matching issue label: `kind/security` Security, `kind/bug` Fixed, `kind/enhancement` Added, `kind/documentation` Documentation, `kind/deprecated` Deprecated, `kind/removed` Removed. + +#### Scenario: Unlabelled issue +- **WHEN** an issue has none of the mapped `kind/*` labels and is not internal/epic +- **THEN** its entry is placed under Changed and a "section guessed" warning is reported + +#### Scenario: Internal issue +- **WHEN** an issue carries only `kind/internal` and/or `kind/epic` +- **THEN** no entry is written and the issue is listed in the report as out of scope + +#### Scenario: Real category wins +- **WHEN** an issue carries `kind/epic` or `kind/internal` together with a real category label +- **THEN** the entry is written in the section of the real category + +### Requirement: Entry title is the issue title +The system SHALL use the issue title verbatim, normalising only non-breaking and invisible whitespace. + +#### Scenario: NBSP in title +- **WHEN** an issue title contains a NBSP +- **THEN** the entry contains an ordinary space + +### Requirement: PRs must close an issue +Every PR SHALL be linked to an issue through a closing keyword or the Development sidebar; a plain `#N` reference SHALL NOT count. PRs labelled `skip-release` and Dependabot PRs SHALL be exempt. + +#### Scenario: No closing issue +- **WHEN** a non-exempt PR has no closing issue +- **THEN** the check reports it, failing only when enforcement is enabled + +#### Scenario: Bypassed PR without issue +- **WHEN** a `skip-release` PR has no closing issue +- **THEN** the check passes and no entry is generated + +#### Scenario: Bypassed PR with issue +- **WHEN** a `skip-release` PR closes an issue +- **THEN** that issue still produces an entry at the next release + +### Requirement: skip-changelog has no effect +The system SHALL NOT read the `skip-changelog` label; entry presence and section are determined solely by the closing issues' labels. + +#### Scenario: Legacy label present +- **WHEN** a PR carries `skip-changelog` and closes a `kind/bug` issue +- **THEN** the issue's entry is still generated under Fixed + +### Requirement: PR preview and check mode +The system SHALL provide a read-only per-PR mode that reports the entries a PR would produce, and SHALL run it on every PR (not path-filtered), writing a job summary when the token is read-only (fork PRs). + +#### Scenario: Fork PR +- **WHEN** a PR comes from a fork +- **THEN** the report appears in the job summary instead of failing for lack of permissions + +### Requirement: Release fails safely +The generator SHALL retry API calls with backoff, be idempotent, write only the `[Unreleased]` section, and exit non-zero on any error before the release tag is created. + +#### Scenario: API failure +- **WHEN** the GitHub API keeps failing after retries +- **THEN** the release job fails and no tag is created + +#### Scenario: Empty Unreleased +- **WHEN** no entries are generated for the range +- **THEN** the changelog bump still succeeds + +### Requirement: Already-released issues are not listed again +The system SHALL NOT write an entry for an issue already listed in an earlier released section of the changelog, and SHALL report it as a warning. + +#### Scenario: Follow-up PR on a released issue +- **WHEN** a merged PR closes an issue whose URL is already listed under a released version +- **THEN** no new entry is written and a warning names the version + +### Requirement: Safe, bounded writes +The generator SHALL keep manual lines already present in `[Unreleased]`, verify before writing that all text outside `[Unreleased]` is unchanged and each added entry appears exactly once, refuse CRLF changelogs, and fail rather than truncate when a GitHub pagination limit is reached. + +#### Scenario: Unexpected result +- **WHEN** writing would alter text outside `[Unreleased]` +- **THEN** the generator exits non-zero without writing + +#### Scenario: Pagination limit +- **WHEN** a PR has more labels or closing issues than one page returns +- **THEN** the generator fails with a message naming the limit + +### Requirement: Only PRs merged into the release branch count +In range mode the system SHALL only consider PRs that are merged and whose base branch is the release branch (`--branch`). + +#### Scenario: PR merged elsewhere +- **WHEN** a commit in the range is associated with a PR merged into another branch +- **THEN** that PR contributes no entry + +### Requirement: Release preview shows the whole release +The release preview SHALL generate the entries already pending on the base branch and then the previewed PR's, and SHALL wrap issue titles in code spans in the posted text so an `@mention` cannot notify anyone; fork PRs SHALL receive the preview in the job summary. + +#### Scenario: Mention in a title +- **WHEN** an issue title contains `@user` +- **THEN** the preview text shows the title inside a code span and `CHANGELOG.md` is unchanged by the wrapping diff --git a/openspec/changes/generate-changelog-from-closing-issues/tasks.md b/openspec/changes/generate-changelog-from-closing-issues/tasks.md new file mode 100644 index 00000000..5a3c53aa --- /dev/null +++ b/openspec/changes/generate-changelog-from-closing-issues/tasks.md @@ -0,0 +1,25 @@ +# Tasks + +## 1. Generator script + +- [x] 1.1 Port `changelog-from-prs.mjs` and `changelog-from-prs.test.mjs` from `/Users/jesusmpc/Inditex/weavejs/.github/scripts/` to `.github/scripts/`, adapted to `kind/*` labels, a Documentation section and the "real category wins over `kind/internal`/`kind/epic`" rule; verify `node --test .github/scripts/changelog-from-prs.test.mjs` passes (36 tests) +- [x] 1.2 Export `normalizeInvisibleWhitespace` from `sanitize-changelog.mjs`; verify the NBSP title test passes and `sanitize-changelog.mjs --check code/CHANGELOG.md` stays clean on a generated copy +- [x] 1.3 Verify `--dry-run --from 1.2.0 --to 1.3.0` and `--from 1.3.1 --to 1.3.2` against the hand-written sections (differences are only PR-vs-issue links, serializer escaping and docs-only issues), `--pr 297` output, idempotent write on a copy of the changelog, and non-zero exit on a bad ref / missing token +- [x] 1.4 Verify generated entries match the bullet format `changelog-pages.js` parses (`^- [#N](url)`) + +## 2. Workflows + +- [x] 2.1 Add `.github/workflows/code-changelog-check.yml` (every PR to `main`/`main-*`, `issues: read`, runs the script tests, warn-only via `CHANGELOG_LINK_ENFORCE`, SHA-pinned actions, job summary); verify with `actionlint` +- [x] 2.2 Add the generate step (`--branch "$BASELINE_BRANCH" --changelog code/CHANGELOG.md --report`) before `keep-a-changelog bump` in the release job only; verify with `actionlint` that the snapshot job is untouched +- [x] 2.3 Remove "Require CHANGELOG.md update", "Require a changelog category label" and `skip-changelog` resolution from `code-npm_node-pr-verify.yml`; verify `actionlint` passes and the sanitize check step remains +- [x] 2.4 Replace the "CHANGELOG.md has changes" check in `code-release_preview.yml` with the two-pass generation, code-span titles, and fork job-summary preview; verify with `actionlint` + +## 3. Contributor docs + +- [x] 3.1 Add `.github/pull_request_template.md` with a `Closes #` prompt and `.github/workflows/docs/code-changelog-check.md`; verify both files exist and the docs pages for the release preview and publish workflows describe the new steps +- [x] 3.2 Update `CONTRIBUTING.md`, `.opencode/skills/changelog/SKILL.md`, `AGENTS.md`, the `code/CHANGELOG.md` intro and `docs/.../contributing.adoc`; verify `grep -ri skip-changelog` only finds text saying it has no effect + +## 4. End-to-end verification and rollout (tracked in #302 and #303) + +- [ ] 4.1 Verify the check, the release preview comment, the empty-`[Unreleased]` bump and a real release run (InditexTech/docouture#302) +- [ ] 4.2 Add the check to branch protection, retire the `skip-changelog` label, update the `skip-release` label description, and flip `CHANGELOG_LINK_ENFORCE` after one release (InditexTech/docouture#303) From 632aeedcadb6158e655d92665d0c03e3e83abc84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jesus=20Manuel=20Pi=C3=B1eiro=20Cid?= Date: Wed, 11 Nov 2026 13:28:44 +0100 Subject: [PATCH 3/3] style(tooling): format code/CHANGELOG.md with prettier Code / Verify runs prettier --check on code/CHANGELOG.md, which the release bump leaves with blank lines between link references. --- code/CHANGELOG.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/code/CHANGELOG.md b/code/CHANGELOG.md index a58d4b62..72d03f69 100644 --- a/code/CHANGELOG.md +++ b/code/CHANGELOG.md @@ -157,17 +157,10 @@ full convention, including why some issues produce no entry at all). Entries bel - [#33](https://github.com/InditexTech/docouture/pull/33) \[skills] Correct the iop-ds-components skill against the shipped package [Unreleased]: https://github.com/InditexTech/docouture/compare/1.3.2...HEAD - [1.3.2]: https://github.com/InditexTech/docouture/compare/1.3.1...1.3.2 - [1.3.1]: https://github.com/InditexTech/docouture/compare/1.3.0...1.3.1 - [1.3.0]: https://github.com/InditexTech/docouture/compare/1.2.0...1.3.0 - [1.2.0]: https://github.com/InditexTech/docouture/compare/1.1.1...1.2.0 - [1.1.1]: https://github.com/InditexTech/docouture/compare/1.1.0...1.1.1 - [1.1.0]: https://github.com/InditexTech/docouture/compare/1.0.0...1.1.0 - [1.0.0]: https://github.com/InditexTech/docouture/releases/tag/1.0.0