AI-native design editor. Open-source Figma alternative.
build: collect changelog entries from per-pull-request fragments (#1102)
Danila Poyarkov1128aa2eeb2c
diff --git a/.gitattributes b/.gitattributesindex fbf7dc8ca..135363b1d 100644--- a/.gitattributes+++ b/.gitattributes@@ -1,3 +1,2 @@tests/fixtures/*.fig filter=lfs diff=lfs merge=lfs -texttests/fixtures/fonts/*.ttf filter=lfs diff=lfs merge=lfs -text-CHANGELOG.md merge=uniondiff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex 54558bde8..9a53e5dc6 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -25,4 +25,4 @@ Models: None<!-- List commands actually run and their results, plus relevant checks not run and why. Note changelog status. Replace these examples; do not claim unperformed validation. -->- Checks/tests: commands and results, or not run and why.-- Changelog: updated, or not needed and why.+- Changelog: fragment added under `changes/<PR>/`, or not needed and why.diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex dc1be21a1..177e96433 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -80,6 +80,8 @@ jobs:with:persist-credentials: false- uses: ./.github/actions/setup-bun+ - name: Validate the changelog and its fragments+ run: bun run check:changelog- name: Build documentation type dependenciesrun: bun run build:packages- name: Validate documentation and generated references@@ -172,6 +174,9 @@ jobs:- name: Validate documentation links and structurerun: bun run check:docs+ - name: Validate the changelog and its fragments+ run: bun run check:changelog+- name: Audit critical dependency vulnerabilitiesrun: bun run check:auditdiff --git a/AGENTS.md b/AGENTS.mdindex 1e5a6a0ba..abcf4a0e6 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -93,10 +93,10 @@ Follow `packages/docs/development/testing.md` and `tests/AGENTS.md`. Package-loc## Documentation and changelog- `CHANGELOG.md` — curated user-facing changes by version; `Unreleased` stays first. `README.md` — concise features, setup, CLI, and overview. `AGENTS.md` files — contributor/agent rules. `packages/docs/` — public site (`packages/docs/AGENTS.md`). Keep internal plans in ignored `scratch/`.-- For user-facing work add one present-tense outcome under the single appropriate `Unreleased` category: `Breaking changes`, `Added`, `Changed`, `Fixed`, `Performance`, or `Security`. Treat it as release notes: omit tests, benchmarks, CI, internal refactors/tooling, and bugs both introduced and fixed since the last release. End sentences with periods and retain issue/PR references. Update `README.md` when appropriate and the owning `AGENTS.md` when architecture or conventions change.-- `CHANGELOG.md` merges with git's `union` driver (`.gitattributes`), so two branches adding entries combine instead of conflicting; the driver concatenates blindly, which is why the pass below is load-bearing rather than tidy-up.-- After merges, compare the whole section with changes since the latest release, preserve important outcomes, consolidate related work, and remove duplicate bullets and headings.-- Before finalizing `Unreleased`: compare released behavior at the latest tag with the final implementation, not commit subjects; verify questionable fixes existed at that tag and fold fixes to newly added features into the feature bullet; check public exports, model/config/data contracts, and peer requirements for `Breaking changes`; remove superseded intermediate behavior; state platform requirements and concrete supported behavior instead of unqualified claims; run `bun run check:changelog`. Keep historical sections unchanged, except beta sections the final release folds in (`tools/AGENTS.md`, Releases).+- For user-facing work add one present-tense outcome as a bullet in `changes/<PR>/<category>.md`, never in `CHANGELOG.md`, so pull requests never conflict over it; the category is `breaking`, `added`, `changed`, `fixed`, `performance`, or `security` (`changes/README.md`). Treat it as release notes: omit tests, benchmarks, CI, internal refactors/tooling, and bugs both introduced and fixed since the last release; end sentences with periods. Update `README.md` when appropriate and the owning `AGENTS.md` when architecture or conventions change.+- `bun run check:changelog` validates the fragments as they will read once assembled and fails on any entry written under `Unreleased` in `CHANGELOG.md`; at release, `bun run changelog:assemble` moves them under `Unreleased` and deletes them (`tools/release/release-packages/tests/changelog/fragments.test.ts`).+- After assembling, compare the whole section with changes since the latest release, preserve important outcomes, consolidate related work, and remove duplicate bullets and headings.+- Before finalizing `Unreleased`: compare released behavior at the latest tag with the final implementation, not commit subjects; verify questionable fixes existed at that tag and fold fixes to newly added features into the feature bullet; check public exports, model/config/data contracts, and peer requirements for `Breaking changes`; remove superseded intermediate behavior; state platform requirements and concrete supported behavior instead of unqualified claims; run `bun run check:changelog --release`. Keep historical sections unchanged, except beta sections the final release folds in (`tools/AGENTS.md`, Releases).## Commits, PRs, and issuesdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 84666528a..f309d2f5f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,34 +2,6 @@## Unreleased-### Breaking changes--- `computeImageHash` from `@open-pencil/core` and `@open-pencil/scene-graph` returns the hex SHA-1 of the bytes, the name Figma gives an image, instead of an OpenPencil-only hash of the same length. New images are stored under that name, so `.fig` files and the Figma clipboard carry it as it is; images in documents saved before keep their names.--### Added--- Settings → Cloud storage offers the OpenPencil Cloud waitlist: the web app signs you up there, with a confirmation email, and the desktop app opens the sign-up on openpencil.dev.-- Drop design token files, `.tokens`, `.tokens.json`, or `.resolver.json`, on the editor to import them into the document's variables, as the Variables dialog's Import button does.--### Changed--- Trackpads and mouse wheels pan and zoom the canvas as in Figma. A two-finger pan moves the canvas twice as far, up to 120 px per scroll event. A pinch zooms as far in the desktop app and Safari as in other browsers, where it zooms a little less than before. In the desktop app and Safari, a pinch over Preview's live controls or comment pins now zooms the canvas, where it did nothing. On Windows each mouse wheel notch pans 16 px instead of 100 px, and notches less than 50 ms apart pan up to 120 px each.--### Fixed--- The thumbnail in a `.fig` file shows its page's own background between layers. Before, it took the colour of the page open in the editor, and files written from the CLI always showed light grey.-- People in a shared room see the overrides of instances in the shared document: text, slot content, and every other overridden field arrived empty, and editing such an instance could throw. Rooms opened by earlier builds do not meet rooms opened by this one.-- Showing or hiding a layer of an instance that a boolean component property drives sets the property, as in Figma, so every layer it drives follows and Figma shows the instance as OpenPencil does. Before, only that layer changed, which Figma ignored.-- Figma shows shader fills and images from older documents in `.fig` files OpenPencil writes: every image is stored under the SHA-1 of its bytes, the only name Figma reads, and a shader keeps its preset through `.fig` files and the Figma clipboard.-- HTML, Vue, and React exports name a JPEG, GIF, or WebP image fill by its own type in the data URL instead of calling every image PNG.-- Saving an opened `.fig` file writes only what an edit changed in a layer or variable, and keeps the rest as Figma saved it. That includes data OpenPencil does not model, an instance's library link and saved overrides, and an edited text's letter spacing in percent and font names. Before, saving rewrote each edited layer whole. Importing design tokens or adding a mode also rewrote every layer and variable in the file that uses variable modes.-- Variables that alias library variables still point at the library after a save, and a collection's modes keep their order in Figma.-- Importing design tokens adds them to the file's own collections, never to a collection copied from a library, where Figma did not show them. A token collection named like a library's, such as Tokens in Preline UI files, becomes a new collection of the file.--### Performance--- Shader fills store their still frame as JPEG when no pixel is transparent, about 25 times smaller than PNG, so documents with shaders save and open faster; frames with transparency stay PNG. Figma opens both.-## 0.16.0-beta.2 — 2026-10-12This is a pre-release that lists changes since 0.16.0-beta.1: npm packages are published under the `next` tag, and installed apps on the stable release do not update to it. Linux package managers see `0.16.0-beta.2` as newer than `0.16.0`, so `.deb` and `.rpm` users should remove the beta before installing the final 0.16.0.diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 67e03167e..7d5d44063 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -33,7 +33,7 @@ APPLE_SIGNING_IDENTITY=- bun run tauri build -c '{"bundle": { "createUpdaterArti- Before adding a helper, type, component, state mechanism, parser, or test utility, inspect the owning folder, nearby implementations, existing dependencies, and tests. Reuse or extend the established mechanism; extract genuinely shared logic instead of introducing a parallel implementation.- Keep package boundaries and public exports intact. Keep pull requests focused: no temporary scaffolding, unrelated refactors, or changelog claims not represented by the diff.-- Update `CHANGELOG.md` for user-facing changes following the rules in `AGENTS.md` (Documentation and changelog).+- For user-facing changes add a changelog fragment under `changes/<PR>/` instead of editing `CHANGELOG.md`, following `changes/README.md` and the rules in `AGENTS.md` (Documentation and changelog).- Tests follow the [testing architecture](packages/docs/development/testing.md) and `tests/AGENTS.md`. Extend an existing `tests/engine/**` suite until its domain migrates; do not create a duplicate home.- `.fig` fixtures in `tests/fixtures/` are Git LFS. Use `git push --no-verify` to skip the slow LFS pre-push hook unless you changed `.fig` files.diff --git a/changes/1103/added.md b/changes/1103/added.mdnew file mode 100644index 000000000..513807b7c--- /dev/null+++ b/changes/1103/added.md@@ -0,0 +1 @@+- Drop design token files, `.tokens`, `.tokens.json`, or `.resolver.json`, on the editor to import them into the document's variables, as the Variables dialog's Import button does.diff --git a/changes/1103/fixed.md b/changes/1103/fixed.mdnew file mode 100644index 000000000..663b7442f--- /dev/null+++ b/changes/1103/fixed.md@@ -0,0 +1,3 @@+- Saving an opened `.fig` file writes only what an edit changed in a layer or variable, and keeps the rest as Figma saved it. That includes data OpenPencil does not model, an instance's library link and saved overrides, and an edited text's letter spacing in percent and font names. Before, saving rewrote each edited layer whole. Importing design tokens or adding a mode also rewrote every layer and variable in the file that uses variable modes.+- Variables that alias library variables still point at the library after a save, and a collection's modes keep their order in Figma.+- Importing design tokens adds them to the file's own collections, never to a collection copied from a library, where Figma did not show them. A token collection named like a library's, such as Tokens in Preline UI files, becomes a new collection of the file.diff --git a/changes/1107/fixed.md b/changes/1107/fixed.mdnew file mode 100644index 000000000..9997fd432--- /dev/null+++ b/changes/1107/fixed.md@@ -0,0 +1 @@+- HTML, Vue, and React exports name a JPEG, GIF, or WebP image fill by its own type in the data URL instead of calling every image PNG.diff --git a/changes/1107/performance.md b/changes/1107/performance.mdnew file mode 100644index 000000000..05f270a6a--- /dev/null+++ b/changes/1107/performance.md@@ -0,0 +1 @@+- Shader fills store their still frame as JPEG when no pixel is transparent, about 25 times smaller than PNG, so documents with shaders save and open faster; frames with transparency stay PNG. Figma opens both.diff --git a/changes/1108/breaking.md b/changes/1108/breaking.mdnew file mode 100644index 000000000..aff8fb345--- /dev/null+++ b/changes/1108/breaking.md@@ -0,0 +1 @@+- `computeImageHash` from `@open-pencil/core` and `@open-pencil/scene-graph` returns the hex SHA-1 of the bytes, the name Figma gives an image, instead of an OpenPencil-only hash of the same length. New images are stored under that name, so `.fig` files and the Figma clipboard carry it as it is; images in documents saved before keep their names.diff --git a/changes/1108/fixed.md b/changes/1108/fixed.mdnew file mode 100644index 000000000..a06c8e959--- /dev/null+++ b/changes/1108/fixed.md@@ -0,0 +1 @@+- Figma shows shader fills and images from older documents in `.fig` files OpenPencil writes: every image is stored under the SHA-1 of its bytes, the only name Figma reads, and a shader keeps its preset through `.fig` files and the Figma clipboard.diff --git a/changes/1109/changed.md b/changes/1109/changed.mdnew file mode 100644index 000000000..9ba09d7dd--- /dev/null+++ b/changes/1109/changed.md@@ -0,0 +1 @@+- Trackpads and mouse wheels pan and zoom the canvas as in Figma. A two-finger pan moves the canvas twice as far, up to 120 px per scroll event. A pinch zooms as far in the desktop app and Safari as in other browsers, where it zooms a little less than before. In the desktop app and Safari, a pinch over Preview's live controls or comment pins now zooms the canvas, where it did nothing. On Windows each mouse wheel notch pans 16 px instead of 100 px, and notches less than 50 ms apart pan up to 120 px each.diff --git a/changes/1111/added.md b/changes/1111/added.mdnew file mode 100644index 000000000..27be9b546--- /dev/null+++ b/changes/1111/added.md@@ -0,0 +1 @@+- Settings → Cloud storage offers the OpenPencil Cloud waitlist: the web app signs you up there, with a confirmation email, and the desktop app opens the sign-up on openpencil.dev.diff --git a/changes/1113/fixed.md b/changes/1113/fixed.mdnew file mode 100644index 000000000..696ae6c05--- /dev/null+++ b/changes/1113/fixed.md@@ -0,0 +1 @@+- Showing or hiding a layer of an instance that a boolean component property drives sets the property, as in Figma, so every layer it drives follows and Figma shows the instance as OpenPencil does. Before, only that layer changed, which Figma ignored.diff --git a/changes/1121/fixed.md b/changes/1121/fixed.mdnew file mode 100644index 000000000..6152c9f93--- /dev/null+++ b/changes/1121/fixed.md@@ -0,0 +1 @@+- People in a shared room see the overrides of instances in the shared document: text, slot content, and every other overridden field arrived empty, and editing such an instance could throw. Rooms opened by earlier builds do not meet rooms opened by this one.diff --git a/changes/1129/fixed.md b/changes/1129/fixed.mdnew file mode 100644index 000000000..22fe4d404--- /dev/null+++ b/changes/1129/fixed.md@@ -0,0 +1 @@+- The thumbnail in a `.fig` file shows its page's own background between layers. Before, it took the colour of the page open in the editor, and files written from the CLI always showed light grey.diff --git a/changes/README.md b/changes/README.mdnew file mode 100644index 000000000..22ae9dc88--- /dev/null+++ b/changes/README.md@@ -0,0 +1,15 @@+# Unreleased changes++Each pull request with a user-facing change adds its changelog bullets here instead of editing `CHANGELOG.md`, so two pull requests never touch the same file:++```+changes/<pull request>/<category>.md+```++`<category>` is `breaking`, `added`, `changed`, `fixed`, `performance`, or `security`. A file holds one bulleted list, written as it will read in the changelog:++```md+- Text keeps a case, a link, and variable bindings for any range of its characters, as in Figma.+```++Open the pull request first, then name the folder after its number. `bun run check:changelog` validates the fragments as they will read once assembled, and fails on entries written under `## Unreleased` in `CHANGELOG.md`. At release, `bun run changelog:assemble` moves them under `## Unreleased` and deletes the folders; the release pass in `AGENTS.md` then curates the section.diff --git a/package.json b/package.jsonindex 06e4cae65..6900711b7 100644--- a/package.json+++ b/package.json@@ -59,7 +59,8 @@"format:check": "bun run format && status=$(git status --porcelain -uall) && test -z \"$status\" || (echo \"$status\" && exit 1)","check": "bun run check:icons && bun run build:packages && bun run lint && tsgo --noEmit && bun run check:vue && bun run check:native-test && bun run check:i18n && bun run check:docs && bun run check:changelog && bun run check:packages && bun run check:deps && bun run check:audit && bun run check:secrets && bun run check:monorepo && bun run check:arch && bun run check:test-homes && bun run check:test-types && bun run test:type-shapes && bun run check:tools && bun run test:tools && bun run test:dupes","check:commits": "commitlint",- "check:changelog": "bun tools/release/release-packages/src/check-changelog.ts",+ "check:changelog": "bun tools/release/release-packages/src/changelog/check.ts",+ "changelog:assemble": "bun tools/release/release-packages/src/changelog/assemble.ts","check:deps": "knip --include unlisted,unresolved,binaries","check:docs": "bun --filter @open-pencil/docs check && bun run check:authoring-reference","check:authoring-reference": "bun tools/generate/authoring-reference/src/check.ts",diff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex 7569c00c9..543effbe8 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -27,7 +27,7 @@ Private tooling lives under `tools/<role>/<domain>/{src,tests}`; Steiger enforce## Releases-- Update versions in the root and publishable package manifests plus `desktop/tauri.conf.json` and `desktop/Cargo.toml`; move `Unreleased` into `## x.y.z — YYYY-MM-DD`; commit `Release vX.Y.Z`; tag and push `vX.Y.Z`. A pre-release uses `X.Y.Z-beta.N` throughout.+- Update versions in the root and publishable package manifests plus `desktop/tauri.conf.json` and `desktop/Cargo.toml`; run `bun run changelog:assemble`, curate `Unreleased` (`bun run check:changelog --release`), and move it into `## x.y.z — YYYY-MM-DD`; commit `Release vX.Y.Z`; tag and push `vX.Y.Z`. A pre-release uses `X.Y.Z-beta.N` throughout.- `.github/workflows/build.yml` is the source of truth: `v*` tags (or dispatches for an immutable stable tag) build shared frontend/package outputs once, build signed desktop artifacts in parallel, verify and attest one complete same-run artifact set, publish npm packages, and replace the draft release assets using the exact changelog section. Policy, provenance, and recovery: `tools/release/release-packages/README.md`.- Public workspace packages are discovered by the package-artifacts catalog. Bun source exports require the complete `src` directory in package contents; Node exports use `dist`. Release preparation must preserve resolution maps. Prepared publish directories receive the root `LICENSE` when a package has none of its own, and every package needs a `README.md` because npm renders it. Publishing uses prepared npm tarballs verified through the shared Node/Bun consumer checks; never publish package directories manually. `test:packages` first runs the packaging guards in `tools/checks/package-quality/src/smoke/guards.ts`: fixture manifests packed with the real `npm pack` that must trip the tarball inspector and the Node/Bun consumer checks before those checks vouch for real packages.- Pre-releases are only `vX.Y.Z-beta.N`: they publish to npm's `next` dist-tag, draft as a GitHub pre-release that is never latest, install on Windows as MSI `X.Y.Z.N`, and skip the app and docs deploys (`tools/release/release-packages/src/version.ts`).diff --git a/tools/ci/policy/src/policy.ts b/tools/ci/policy/src/policy.tsindex 4a3b31c49..c08f9f65c 100644--- a/tools/ci/policy/src/policy.ts+++ b/tools/ci/policy/src/policy.ts@@ -4,7 +4,7 @@ const DOC_ASSET = /\.(?:md|png|jpe?g|gif|webp|svg|ico|pdf|woff2?|ttf)$/i/** `verified`: a merge queue commit whose exact tree already passed its pull request's CI. */export type ChangeScope = 'docs' | 'code' | 'verified'-/** Root docs, package READMEs, and every AGENTS.md guide are docs-only; unknown paths, executable docs, and runtime prompt Markdown require the code checks. */+/** Root docs, changelog fragments, package READMEs, and every AGENTS.md guide are docs-only; unknown paths, executable docs, and runtime prompt Markdown require the code checks. */export function classifyPaths(paths: readonly string[]): Exclude<ChangeScope, 'verified'> {if (paths.length === 0) return 'code'return paths.every((path) => {@@ -12,6 +12,7 @@ export function classifyPaths(paths: readonly string[]): Exclude<ChangeScope, 'vif (/(?:^|\/)AGENTS\.md$/.test(path)) return trueif (path.startsWith('packages/docs/')) return DOC_ASSET.test(path)if (path.startsWith('openspec/')) return path.endsWith('.md')+ if (path.startsWith('changes/')) return path.endsWith('.md')if (path.startsWith('skills/')) return path.endsWith('.md') || path.endsWith('/LICENSE.txt')return false})diff --git a/tools/ci/policy/tests/policy.test.ts b/tools/ci/policy/tests/policy.test.tsindex d2aab0104..b864200f1 100644--- a/tools/ci/policy/tests/policy.test.ts+++ b/tools/ci/policy/tests/policy.test.ts@@ -14,6 +14,8 @@ const documentation = ['README.md','AGENTS.md','CHANGELOG.md',+ 'changes/README.md',+ 'changes/1095/added.md','packages/vue/README.md','packages/core/README.md','packages/core/AGENTS.md',@@ -37,6 +39,7 @@ const code = ['packages/docs/.vitepress/config.ts','packages/docs/demo.vue','skills/open-pencil/scripts/create.ts',+ 'changes/1095/notes.txt','package.json','bun.lock','.github/workflows/ci.yml',diff --git a/tools/release/release-packages/package.json b/tools/release/release-packages/package.jsonindex 3fc13b7dd..aff6c4df7 100644--- a/tools/release/release-packages/package.json+++ b/tools/release/release-packages/package.json@@ -6,7 +6,7 @@"#release/*": "./src/*.ts"},"scripts": {- "check-changelog": "bun src/check-changelog.ts",+ "check-changelog": "bun src/changelog/check.ts ../../..","build": "bun src/cli.ts build","prepare-publish-dirs": "bun src/cli.ts prepare","pack": "bun src/cli.ts pack",diff --git a/tools/release/release-packages/src/changelog/assemble.ts b/tools/release/release-packages/src/changelog/assemble.tsnew file mode 100644index 000000000..da89d7afb--- /dev/null+++ b/tools/release/release-packages/src/changelog/assemble.ts@@ -0,0 +1,30 @@+import { readFile, writeFile } from 'node:fs/promises'+import { resolve } from 'node:path'++import { assembleUnreleased, readFragments, removeFragments } from './fragments'+import { validateChangelog } from './validate'++const root = resolve(process.argv[2] ?? '.')+const changelogPath = resolve(root, 'CHANGELOG.md')+const changesPath = resolve(root, 'changes')++const { fragments, errors } = await readFragments(changesPath)+if (errors.length > 0) {+ process.stderr.write(`Fix these fragments first:\n${errors.map((e) => `- ${e}`).join('\n')}\n`)+ process.exit(1)+}++const assembled = assembleUnreleased(await readFile(changelogPath, 'utf8'), fragments)+const { errors: changelogErrors } = validateChangelog(assembled)+if (changelogErrors.length > 0) {+ process.stderr.write(+ `The assembled changelog is invalid:\n${changelogErrors.map((e) => `- ${e}`).join('\n')}\n`+ )+ process.exit(1)+}++await writeFile(changelogPath, assembled)+await removeFragments(changesPath, fragments)+process.stdout.write(+ `Moved ${fragments.length} fragments from ${new Set(fragments.map((f) => f.pullRequest)).size} pull requests into Unreleased. Curate the section before the release commit.\n`+)diff --git a/tools/release/release-packages/src/changelog/check.ts b/tools/release/release-packages/src/changelog/check.tsnew file mode 100644index 000000000..ded4ba16d--- /dev/null+++ b/tools/release/release-packages/src/changelog/check.ts@@ -0,0 +1,37 @@+import { readFile } from 'node:fs/promises'+import { resolve } from 'node:path'++import { assembleUnreleased, readFragments } from './fragments'+import { unreleasedContentLine, validateChangelog } from './validate'++// `--release` allows entries under Unreleased while a release curates them after+// `changelog:assemble`; without it, they belong in fragments.+const args = process.argv.slice(2)+const release = args.includes('--release')+const root = resolve(args.find((arg) => !arg.startsWith('--')) ?? '.')+const changelogPath = resolve(root, 'CHANGELOG.md')++const { fragments, errors: fragmentErrors } = await readFragments(resolve(root, 'changes'))+// Validated as it will read once the fragments are assembled, so duplicates across pull+// requests and fragments in an empty category are caught now rather than at release.+const changelog = await readFile(changelogPath, 'utf8')+const { errors: changelogErrors } = validateChangelog(assembleUnreleased(changelog, fragments))+const errors = [...fragmentErrors, ...changelogErrors]++const pending = release ? null : unreleasedContentLine(changelog)+if (pending !== null) {+ errors.unshift(+ `CHANGELOG.md line ${pending}: Unreleased stays empty; move the entry into changes/<PR>/<category>.md (changes/README.md).`+ )+}++if (errors.length > 0) {+ process.stderr.write(+ `Changelog validation failed:\n${errors.map((error) => `- ${error}`).join('\n')}\n`+ )+ process.exit(1)+}++process.stdout.write(+ `Changelog validation passed: ${changelogPath} and ${fragments.length} fragments in changes/\n`+)diff --git a/tools/release/release-packages/src/changelog/fragments.ts b/tools/release/release-packages/src/changelog/fragments.tsnew file mode 100644index 000000000..f7c655949--- /dev/null+++ b/tools/release/release-packages/src/changelog/fragments.ts@@ -0,0 +1,166 @@+import { readdir, readFile, rm } from 'node:fs/promises'+import { join } from 'node:path'++import type { List, ListItem, Root, RootContent } from 'mdast'+import { fromMarkdown } from 'mdast-util-from-markdown'++import { ALLOWED_CATEGORIES, headingText, sectionEnd } from './validate'++type Category = (typeof ALLOWED_CATEGORIES)[number]++/** Fragment file names, `changes/<PR>/<file>.md`, and the changelog heading each one fills. */+export const FRAGMENT_CATEGORIES = {+ breaking: 'Breaking changes',+ added: 'Added',+ changed: 'Changed',+ fixed: 'Fixed',+ performance: 'Performance',+ security: 'Security'+} as const satisfies Record<string, Category>++export type FragmentCategory = keyof typeof FRAGMENT_CATEGORIES++export interface ChangeFragment {+ pullRequest: number+ category: FragmentCategory+ /** Each bullet's Markdown, starting with `- `, as it will appear in the changelog. */+ bullets: string[]+}++export interface FragmentReadResult {+ fragments: ChangeFragment[]+ errors: string[]+}++const isFragmentCategory = (name: string): name is FragmentCategory =>+ Object.hasOwn(FRAGMENT_CATEGORIES, name)++/** The bullets of one fragment file: one unordered list, each item a sentence ending in a period. */+export function parseFragmentBullets(+ source: string,+ path: string+): { bullets: string[]; errors: string[] } {+ const tree = fromMarkdown(source) as Root+ const errors: string[] = []+ const lists = tree.children.filter((node): node is List => node.type === 'list' && !node.ordered)+ if (lists.length !== 1 || tree.children.length !== 1) {+ errors.push(`${path}: a fragment holds exactly one bulleted list and nothing else.`)+ return { bullets: [], errors }+ }+ const bullets = lists[0].children.map((item) => listItemMarkdown(source, item))+ for (const bullet of bullets) {+ if (!bullet.endsWith('.')) errors.push(`${path}: end every bullet with a period: ${bullet}`)+ }+ return { bullets, errors }+}++/** Reads every `changes/<PR>/<category>.md`; anything else under `changes/` is reported. */+export async function readFragments(directory: string): Promise<FragmentReadResult> {+ const fragments: ChangeFragment[] = []+ const errors: string[] = []+ const entries = await readdir(directory, { withFileTypes: true }).catch((error: unknown) => {+ // No `changes/` folder means nothing is pending; any other failure must not pass as that.+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return []+ throw error+ })+ for (const entry of entries) {+ if (entry.isFile() && entry.name === 'README.md') continue+ if (!entry.isDirectory() || !/^[1-9]\d*$/.test(entry.name)) {+ errors.push(`changes/${entry.name}: expected a folder named after its pull request number.`)+ continue+ }+ const pullRequest = Number(entry.name)+ for (const file of await readdir(join(directory, entry.name), { withFileTypes: true })) {+ const path = `changes/${entry.name}/${file.name}`+ const category = file.name.replace(/\.md$/, '')+ if (!file.isFile() || !file.name.endsWith('.md') || !isFragmentCategory(category)) {+ errors.push(+ `${path}: expected one of ${Object.keys(FRAGMENT_CATEGORIES)+ .map((name) => `${name}.md`)+ .join(', ')}.`+ )+ continue+ }+ const parsed = parseFragmentBullets(+ await readFile(join(directory, entry.name, file.name), 'utf8'),+ path+ )+ errors.push(...parsed.errors)+ if (parsed.bullets.length > 0)+ fragments.push({ pullRequest, category, bullets: parsed.bullets })+ }+ }+ fragments.sort((a, b) => a.pullRequest - b.pullRequest)+ // Directory listings come in no fixed order; sorted errors read the same on every machine.+ return { fragments, errors: errors.toSorted() }+}++function listItemMarkdown(source: string, item: ListItem): string {+ return source.slice(item.position?.start.offset ?? 0, item.position?.end.offset ?? 0).trimEnd()+}++/**+ * The bullets `## Unreleased` already holds, by category. Anything assembly could not carry+ * over, such as prose or a list outside a category, is refused rather than dropped.+ */+function unreleasedBullets(changelog: string, nodes: RootContent[]): Map<Category, string[]> {+ const bullets = new Map<Category, string[]>(ALLOWED_CATEGORIES.map((category) => [category, []]))+ let current: Category | undefined+ for (const node of nodes) {+ const at = `CHANGELOG.md line ${node.position?.start.line ?? '?'}`+ if (node.type === 'heading') {+ const text = headingText(node)+ current = ALLOWED_CATEGORIES.find((category) => category === text)+ if (node.depth !== 3 || !current) {+ throw new Error(`${at}: "${text}" is not an Unreleased category.`)+ }+ } else if (node.type === 'list' && !node.ordered && current) {+ bullets.get(current)?.push(...node.children.map((item) => listItemMarkdown(changelog, item)))+ } else {+ throw new Error(`${at}: Unreleased holds content outside a category bullet list.`)+ }+ }+ return bullets+}++function renderUnreleased(bullets: Map<Category, string[]>): string {+ const sections = ALLOWED_CATEGORIES.flatMap((category) => {+ const items = bullets.get(category) ?? []+ return items.length > 0 ? [`### ${category}\n\n${items.join('\n')}\n`] : []+ })+ return ['## Unreleased\n', ...sections].join('\n')+}++/**+ * The changelog with every fragment's bullets added under `## Unreleased`, after the bullets it+ * already holds, in category order and by pull request within a category.+ */+export function assembleUnreleased(changelog: string, fragments: ChangeFragment[]): string {+ const tree = fromMarkdown(changelog) as Root+ const headingIndex = tree.children.findIndex(+ (node) => node.type === 'heading' && node.depth === 2 && headingText(node) === 'Unreleased'+ )+ if (headingIndex === -1) throw new Error('CHANGELOG.md has no "## Unreleased" section.')+ const end = sectionEnd(tree.children, headingIndex)++ const bullets = unreleasedBullets(changelog, tree.children.slice(headingIndex + 1, end))+ for (const fragment of fragments) {+ bullets.get(FRAGMENT_CATEGORIES[fragment.category])?.push(...fragment.bullets)+ }++ const sectionStart = tree.children[headingIndex].position?.start.offset ?? 0+ const sectionStop = tree.children[end]?.position?.start.offset ?? changelog.length+ const after = changelog.slice(sectionStop)+ return `${changelog.slice(0, sectionStart)}${renderUnreleased(bullets)}${after ? `\n${after}` : ''}`+}++/** Removes the assembled fragment folders, keeping `changes/README.md`. */+export async function removeFragments(+ directory: string,+ fragments: ChangeFragment[]+): Promise<void> {+ const folders = new Set(fragments.map((fragment) => String(fragment.pullRequest)))+ await Promise.all(+ [...folders].map((folder) => rm(join(directory, folder), { recursive: true, force: true }))+ )+}diff --git a/tools/release/release-packages/src/changelog.ts b/tools/release/release-packages/src/changelog/validate.tssimilarity index 88%rename from tools/release/release-packages/src/changelog.tsrename to tools/release/release-packages/src/changelog/validate.tsindex dca11f86d..bb179a204 100644--- a/tools/release/release-packages/src/changelog.ts+++ b/tools/release/release-packages/src/changelog/validate.ts@@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises'import type { Heading, List, ListItem, Root, RootContent } from 'mdast'import { fromMarkdown } from 'mdast-util-from-markdown'-const ALLOWED_CATEGORIES = [+export const ALLOWED_CATEGORIES = ['Breaking changes','Added','Changed',@@ -23,7 +23,7 @@ interface PositionedNode {position?: { start: { line: number } }}-function headingText(heading: Heading): string {+export function headingText(heading: Heading): string {return heading.children.map((child) => ('value' in child && typeof child.value === 'string' ? child.value : '')).join('')@@ -41,7 +41,7 @@ function listItemSource(source: string, item: ListItem): string {return source.slice(start, end).trim().replace(/\s+/g, ' ')}-function sectionEnd(children: RootContent[], start: number): number {+export function sectionEnd(children: RootContent[], start: number): number {for (let index = start + 1; index < children.length; index++) {const node = children[index]if (node?.type === 'heading' && node.depth === 2) return index@@ -186,6 +186,20 @@ export function validateChangelog(source: string): ChangelogValidationResult {return { errors }}+/**+ * The line of the first content under `## Unreleased`, or null when the section is empty, as it+ * is on every commit: pull requests write fragments, and a release moves the section away.+ */+export function unreleasedContentLine(source: string): number | null {+ const tree = fromMarkdown(source) as Root+ const index = tree.children.findIndex(+ (node) => node.type === 'heading' && node.depth === 2 && headingText(node) === 'Unreleased'+ )+ if (index === -1) return null+ const first = tree.children[index + 1]+ return first && sectionEnd(tree.children, index) > index + 1 ? line(first) : null+}+export async function validateChangelogFile(path: string): Promise<ChangelogValidationResult> {return validateChangelog(await readFile(path, 'utf8'))}diff --git a/tools/release/release-packages/src/check-changelog.ts b/tools/release/release-packages/src/check-changelog.tsdeleted file mode 100644index c25596111..000000000--- a/tools/release/release-packages/src/check-changelog.ts+++ /dev/null@@ -1,15 +0,0 @@-import { resolve } from 'node:path'--import { validateChangelogFile } from './changelog'--const path = resolve(process.argv[2] ?? 'CHANGELOG.md')-const { errors } = await validateChangelogFile(path)--if (errors.length > 0) {- process.stderr.write(- `Changelog validation failed:\n${errors.map((error) => `- ${error}`).join('\n')}\n`- )- process.exit(1)-}--process.stdout.write(`Changelog validation passed: ${path}\n`)diff --git a/tools/release/release-packages/tests/changelog/fragments.test.ts b/tools/release/release-packages/tests/changelog/fragments.test.tsnew file mode 100644index 000000000..dc29a08b9--- /dev/null+++ b/tools/release/release-packages/tests/changelog/fragments.test.ts@@ -0,0 +1,115 @@+import { describe, expect, test } from 'bun:test'+import { mkdir, mkdtemp, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import {+ assembleUnreleased,+ parseFragmentBullets,+ readFragments+} from '#release/changelog/fragments'+import { validateChangelog } from '#release/changelog/validate'++describe('changelog fragments', () => {+ test('read bullets as written, with continuation lines and formatting', () => {+ const { bullets, errors } = parseFragmentBullets(+ '- Add **rich** notes,\n wrapped over two lines.\n- Keep links like [docs](https://openpencil.dev).\n',+ 'changes/12/added.md'+ )++ expect(errors).toEqual([])+ expect(bullets).toEqual([+ '- Add **rich** notes,\n wrapped over two lines.',+ '- Keep links like [docs](https://openpencil.dev).'+ ])+ })++ test('refuse headings, prose outside a list, and bullets without a closing period', () => {+ expect(+ parseFragmentBullets('### Added\n\n- Add it.\n', 'changes/1/added.md').errors+ ).toHaveLength(1)+ expect(parseFragmentBullets('Add it.\n', 'changes/1/added.md').errors).toHaveLength(1)+ expect(parseFragmentBullets('- Add it\n', 'changes/1/added.md').errors).toEqual([+ 'changes/1/added.md: end every bullet with a period: - Add it'+ ])+ })++ test('assemble after existing bullets, in category order and by pull request', () => {+ const changelog =+ '# Changelog\n\n## Unreleased\n\n### Fixed\n\n- Keep user data.\n\n## 1.0.0 — 2026-01-01\n\n### Added\n\n- Ship it.\n'+ const assembled = assembleUnreleased(changelog, [+ { pullRequest: 7, category: 'fixed', bullets: ['- Stop the crash.'] },+ { pullRequest: 9, category: 'breaking', bullets: ['- Remove the old API.'] },+ { pullRequest: 8, category: 'added', bullets: ['- Add export.', '- Add import.'] }+ ])++ expect(assembled).toBe(+ '# Changelog\n\n## Unreleased\n\n### Breaking changes\n\n- Remove the old API.\n\n### Added\n\n- Add export.\n- Add import.\n\n### Fixed\n\n- Keep user data.\n- Stop the crash.\n\n## 1.0.0 — 2026-01-01\n\n### Added\n\n- Ship it.\n'+ )+ expect(validateChangelog(assembled).errors).toEqual([])+ })++ test('refuse to assemble over Unreleased content it would drop', () => {+ const prose =+ '# Changelog\n\n## Unreleased\n\nA note.\n\n### Fixed\n\n- Keep user data.\n\n## 1.0.0 — 2026-01-01\n\n### Added\n\n- Ship it.\n'+ const uncategorized =+ '# Changelog\n\n## Unreleased\n\n- Loose bullet.\n\n## 1.0.0 — 2026-01-01\n\n### Added\n\n- Ship it.\n'++ expect(() => assembleUnreleased(prose, [])).toThrow('line 5: Unreleased holds content outside')+ expect(() => assembleUnreleased(uncategorized, [])).toThrow('line 5')+ })++ test('leave an empty Unreleased section as it is when nothing is pending', () => {+ const changelog =+ '# Changelog\n\n## Unreleased\n\n## 1.0.0 — 2026-01-01\n\n### Added\n\n- Ship it.\n'++ expect(assembleUnreleased(changelog, [])).toBe(changelog)+ })++ test('flag the same bullet added by two pull requests once assembled', () => {+ const changelog =+ '# Changelog\n\n## Unreleased\n\n## 1.0.0 — 2026-01-01\n\n### Added\n\n- Ship it.\n'+ const assembled = assembleUnreleased(changelog, [+ { pullRequest: 3, category: 'fixed', bullets: ['- Stop the crash.'] },+ { pullRequest: 4, category: 'fixed', bullets: ['- Stop the crash.'] }+ ])++ expect(validateChangelog(assembled).errors).toEqual([+ expect.stringContaining('duplicate Unreleased bullet')+ ])+ })+})++describe('readFragments', () => {+ test('treat a missing changes folder as nothing pending', async () => {+ const directory = join(await mkdtemp(join(tmpdir(), 'changes-')), 'absent')++ expect(await readFragments(directory)).toEqual({ fragments: [], errors: [] })+ })++ test('fail when the changes folder cannot be read', async () => {+ const file = join(await mkdtemp(join(tmpdir(), 'changes-')), 'not-a-folder')+ await writeFile(file, '')++ await expect(readFragments(file)).rejects.toThrow()+ })++ test('read pull request folders and report anything that does not fit', async () => {+ const directory = await mkdtemp(join(tmpdir(), 'changes-'))+ await mkdir(join(directory, '42'))+ await writeFile(join(directory, '42', 'fixed.md'), '- Stop the crash.\n')+ await writeFile(join(directory, '42', 'notes.md'), '- Not a category.\n')+ await mkdir(join(directory, 'draft'))+ await writeFile(join(directory, 'README.md'), '# Unreleased changes\n')++ const { fragments, errors } = await readFragments(directory)++ expect(fragments).toEqual([+ { pullRequest: 42, category: 'fixed', bullets: ['- Stop the crash.'] }+ ])+ expect(errors).toEqual([+ expect.stringContaining('changes/42/notes.md: expected one of breaking.md'),+ 'changes/draft: expected a folder named after its pull request number.'+ ])+ })+})diff --git a/tools/release/release-packages/tests/changelog.test.ts b/tools/release/release-packages/tests/changelog/validate.test.tssimilarity index 87%rename from tools/release/release-packages/tests/changelog.test.tsrename to tools/release/release-packages/tests/changelog/validate.test.tsindex 46c720c3e..085fc03b9 100644--- a/tools/release/release-packages/tests/changelog.test.ts+++ b/tools/release/release-packages/tests/changelog/validate.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from 'bun:test'-import { validateChangelog } from '#release/changelog'+import { unreleasedContentLine, validateChangelog } from '#release/changelog/validate'const validChangelog = `# Changelog@@ -144,3 +144,15 @@ describe('validateChangelog', () => {)})})++describe('unreleasedContentLine', () => {+ test('finds the first entry under Unreleased, which belongs in a fragment', () => {+ expect(unreleasedContentLine(validChangelog)).toBe(5)+ })++ test('is null when Unreleased is empty, as on every commit', () => {+ const empty =+ '# Changelog\n\n## Unreleased\n\n## 1.2.0 — 2026-08-16\n\n### Added\n\n- Ship it.\n'+ expect(unreleasedContentLine(empty)).toBeNull()+ })+})