diff --git a/.github/ci-budgets.json b/.github/ci-budgets.json index 52fb74e730..f220da6538 100644 --- a/.github/ci-budgets.json +++ b/.github/ci-budgets.json @@ -32,6 +32,7 @@ "build": 3, "component list": 1, "component dockerfile (*)": 10, + "release note": 1, "verify": 1 } }, diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 6d5fb84872..a0c81217ba 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -42,8 +42,18 @@ conditional update, `LISTEN`/`NOTIFY` for fan-out. ## Changelog -- [ ] A line in `CHANGELOG.md` under `Unreleased`, or a sentence on why a deployment behaves no - differently afterwards. + ## Proof diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a800246159..46c85cdb80 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,7 +56,9 @@ jobs: # merge queue merged skips the checks the queue's run already passed on that same commit, and runs # only `component dockerfile` and any job whose cache key the push changed, which write the caches # pull requests read. A push to main the queue did not pass, a merge group, the release's own call - # of these checks and a pull request labelled `full-ci` run everything. + # of these checks and a pull request labelled `full-ci` run everything. CHANGELOG.md is never a + # reason to run anything: the release writes it, so a pull request leaves its change out of every + # decision, and a merge group that changes nothing else runs nothing. changes: name: changes # A standard runner: it reads the API for a few seconds, and every other job waits on it, @@ -84,6 +86,7 @@ jobs: webkit_tests: ${{ steps.decide.outputs.webkit_tests }} desktop_browser_tests: ${{ steps.decide.outputs.desktop_browser_tests }} queue_run: ${{ steps.decide.outputs.queue_run }} + ignored_only: ${{ steps.decide.outputs.ignored_only }} steps: # A pull request's history, without file contents (a diff of names needs only the trees); any # other event needs none. @@ -985,8 +988,10 @@ jobs: contents: read # To cancel this run at its first failure (.github/actions/stop-on-failure). actions: write + # Not in a merge group that changes only CHANGELOG.md: its images are the ones main built. + needs: changes if: >- - github.event_name != 'pull_request' || + (github.event_name != 'pull_request' && needs.changes.outputs.ignored_only != 'true') || contains(github.event.pull_request.labels.*.name, 'full-ci') outputs: components: ${{ steps.list.outputs.components }} @@ -1057,6 +1062,52 @@ jobs: - if: failure() uses: $/.github/actions/stop-on-failure + # CHANGELOG.md is the release's, and a pull request's note is in its description, under + # `## Changelog` (scripts/release-note-check.ts): this fails a pull request that changes + # CHANGELOG.md, other than the release's own, one with no note, and one that deprecates part of + # the API without naming it in its note. It runs last, after every other job, and reads the + # description then, so a description edited while the tests run is the one checked; one edited + # after the run re-runs it (release-note-edited.yml). Running last, its stop step + # (.github/actions/stop-on-failure) has nothing left to cancel. A pull request only: a merge group's pull requests each passed it, + # and nothing else has a description. + release-note: + name: release note + if: ${{ !cancelled() && github.event_name == 'pull_request' }} + needs: [changes, static, api, mobile, app-browser, app-browser-webkit, app-browser-desktop, test, test-total, changed-tests, startup, langgraph-ts, python-harness, python-harness-compose, build, component-list, component-dockerfiles] + runs-on: ubuntu-latest + timeout-minutes: 5 # usually seconds + permissions: + contents: read + # To read the pull request's description and files. + pull-requests: read + # To cancel this run at its first failure (.github/actions/stop-on-failure). + actions: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + # The check and what it imports, and the action its last step uses. + sparse-checkout: | + scripts/release-note-check.ts + scripts/release-notes.ts + shared/api-deprecations.ts + shared/client-version.ts + package.json + release-policy.json + .github/actions/stop-on-failure + sparse-checkout-cone-mode: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.4.3 + no-cache: true + - name: CHANGELOG.md is the release's, and the description has the note + env: + GH_TOKEN: ${{ github.token }} + run: bun scripts/release-note-check.ts + # On a failure, cancels the run at once (.github/actions/stop-on-failure). + - if: failure() + uses: $/.github/actions/stop-on-failure + # One check for branch protection to require. A new job above is covered by this without anybody # remembering to add it to a list, and a job that was skipped for the wrong reason is not a pass. # A job `changes` found nothing to do for is skipped and passes; `changes` itself must succeed, so @@ -1069,7 +1120,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 # usually seconds if: always() - needs: [changes, static, api, mobile, app-browser, app-browser-webkit, app-browser-desktop, test, test-total, changed-tests, startup, langgraph-ts, python-harness, python-harness-compose, build, component-list, component-dockerfiles] + needs: [changes, release-note, static, api, mobile, app-browser, app-browser-webkit, app-browser-desktop, test, test-total, changed-tests, startup, langgraph-ts, python-harness, python-harness-compose, build, component-list, component-dockerfiles] permissions: contents: read # To name the jobs that failed. A job that stopped its run at its first failure is recorded diff --git a/.github/workflows/desktop-macos-signing.yml b/.github/workflows/desktop-macos-signing.yml index 8f9f62ec1b..160fc56637 100644 --- a/.github/workflows/desktop-macos-signing.yml +++ b/.github/workflows/desktop-macos-signing.yml @@ -34,7 +34,7 @@ on: required: false # Pull requests and pushes to main run only the credential-free checks; the signing job's `if` # admits a `v*` tag or an explicit dispatch and nothing else, so no pull request reaches the - # environment. + # environment. Markdown is prose nothing here reads (scripts/ci-changes.ts, isDocs). pull_request: paths: - desktop/** @@ -46,7 +46,7 @@ on: - scripts/release-* - scripts/downloads-* - .github/workflows/downloads-sync.yml - - docs/releasing.md + - "!**/*.md" push: branches: [main] tags: ["v*"] @@ -60,7 +60,7 @@ on: - scripts/release-* - scripts/downloads-* - .github/workflows/downloads-sync.yml - - docs/releasing.md + - "!**/*.md" permissions: contents: read diff --git a/.github/workflows/desktop-signing.yml b/.github/workflows/desktop-signing.yml index 3153e165d7..ed8eb7c3a1 100644 --- a/.github/workflows/desktop-signing.yml +++ b/.github/workflows/desktop-signing.yml @@ -33,7 +33,8 @@ on: - .github/workflows/desktop-signing.yml - .github/workflows/publish-release.yml - scripts/release-* - - docs/windows-signing.md + # Prose nothing here reads (scripts/ci-changes.ts, isDocs). + - "!**/*.md" permissions: contents: read diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 9323f62824..ebc4aa3e48 100644 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -9,10 +9,10 @@ name: Desktop # it at runtime with an `expect`, so a bad row panics the window rather than failing a type check. on: pull_request: - paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] + paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml", "!**/*.md"] push: branches: [main] - paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml"] + paths: ["desktop/**", "shared/harnesses.json", "shared/marks/**", "shared/recorder-extension.json", "shared/fixtures/client-version/**", "package.json", ".github/workflows/desktop.yml", ".github/workflows/desktop-build.yml", "!**/*.md"] workflow_call: permissions: diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index 80036796db..9dfbc6c1dc 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -330,6 +330,9 @@ jobs: # their run at its first failure (.github/actions/stop-on-failure). On this push event `changes` # reads nothing and runs every check, and nothing is cancelled. actions: write + # CI's `release note` asks for it, to read a pull request's description. It runs on a pull + # request only, so on this push it is skipped and reads nothing. + pull-requests: read # The images, built once from the commit that passed the checks above, and tagged with this # release's version and `latest`, with the server, computer and supervisor pinned at the tag this diff --git a/.github/workflows/release-note-edited.yml b/.github/workflows/release-note-edited.yml new file mode 100644 index 0000000000..ac6847d976 --- /dev/null +++ b/.github/workflows/release-note-edited.yml @@ -0,0 +1,60 @@ +name: Release note edited + +# A pull request's release note is in its description (scripts/release-note-check.ts), and editing a +# description starts no CI run. So when the description changes after CI's run of the pull request's +# head has finished with its `release note` check failed, this re-runs that run's failed jobs: the +# check reads the description again, and `verify` follows it. Nothing else runs again, since every +# other job of the run passed or is re-run only because it failed. While the run is still going, +# nothing is needed: the check runs last and reads the description then. +# +# Pull requests from this repository: a fork's token is read-only and cannot re-run. A maintainer +# re-runs a fork's failed jobs by hand. +on: + pull_request: + types: [edited] + +permissions: {} + +concurrency: + group: release-note-edited-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + rerun: + name: re-run the release note + if: >- + github.event.pull_request.head.repo.full_name == github.repository && + github.event.changes.body != null + runs-on: ubuntu-latest + timeout-minutes: 5 # seconds + permissions: + # To read CI's runs and re-run one. + actions: write + steps: + - name: Re-run CI's failed release note on the pull request's head + env: + GH_TOKEN: ${{ github.token }} + REPOSITORY: ${{ github.repository }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + run="$(gh api "repos/$REPOSITORY/actions/workflows/ci.yml/runs?head_sha=$HEAD_SHA&event=pull_request&per_page=1" \ + --jq '.workflow_runs[0] | select(.) | "\(.id) \(.status)"')" + if [ -z "$run" ]; then + echo "CI has not run on $HEAD_SHA yet. Its release note check will read this description." + exit 0 + fi + id="${run% *}" + status="${run#* }" + if [ "$status" != completed ]; then + echo "CI's run $id is still going. Its release note check runs last and reads this description." + exit 0 + fi + note="$(gh api "repos/$REPOSITORY/actions/runs/$id/jobs?filter=latest&per_page=100" \ + --jq '[.jobs[] | select(.name == "release note")][0].conclusion // ""')" + if [ "$note" != failure ]; then + echo "CI's run $id has its release note check at '${note:-not run}'. Nothing to re-run." + exit 0 + fi + gh run rerun "$id" --failed --repo "$REPOSITORY" + echo "Re-ran the failed jobs of CI's run $id, so the release note check reads the edited description." diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6d0f7a6d1f..9467df36b6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -102,10 +102,13 @@ jobs: bun-version: 1.4.3 - id: prepare - name: Write the version and promote the notes + name: Write the version and the notes env: BUMP: ${{ inputs.bump }} KIND: ${{ inputs.kind }} + # The notes are read from the descriptions of the pull requests this release ships, + # through the API (scripts/release-collect-notes.ts). + GH_TOKEN: ${{ github.token }} run: | set -euo pipefail current=$(bun -e 'console.log(require("./package.json").version)') @@ -187,9 +190,14 @@ jobs: echo "sha=$(git rev-parse HEAD)" } >> "$GITHUB_OUTPUT" - # Writes the version, the OpenBot image tag, the Cargo files and the changelog, and - # refuses a changelog with nothing under Unreleased. It appends version, base and the path - # of a file holding the notes to $GITHUB_OUTPUT for the steps below. + # Writes the version, the OpenBot image tag, the Cargo files and the changelog. The + # changelog is written here and nowhere else: its section is the notes under `## Changelog` + # in the description of every pull request merged since the previous stable release, with + # whatever still sits under Unreleased (scripts/release-prepare.ts). It refuses a release + # with a pull request whose note is missing or unreadable, naming it (edit that pull + # request's description and run this again), one with no notes at all, and one whose + # changelog would not list a deprecation the API spec makes. It appends version, base and + # the path of a file holding the notes to $GITHUB_OUTPUT for the steps below. bun scripts/release-prepare.ts "$BUMP" "$KIND" # The notes can be longer than the 65,536 characters GitHub allows in a PR body. The action @@ -197,7 +205,7 @@ jobs: # comes first, so the cut only drops the end of the notes. The whole section is still in the # CHANGELOG.md diff of the PR, and the published release reads it from there, not from here. # The notes come through a file: an environment variable over 128 KB makes the shell fail with - # "Argument list too long", and the Unreleased section can grow past that. The notes have no + # "Argument list too long", and a release's notes can grow past that. The notes have no # trailing newline, so the bare echo after cat ends their last line. - name: Write the PR body env: @@ -226,7 +234,7 @@ jobs: echo "changes only the release files, main's passing CI on the commit it merges onto." echo "There is nothing to check about CI here." echo - # A prerelease does not promote the changelog, so these are what is under Unreleased. + # A prerelease writes its notes under Unreleased, and is published from there. echo '```' echo cat "$NOTES_FILE" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e8625279ba..f24ee67563 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,6 +10,30 @@ what it changes and why. optional.** OpenBot is live. Anything a released app uses keeps working for 12 months, and a migration never breaks a running server. CI enforces most of it; the page says what and how. +## The release note goes in the description, not in CHANGELOG.md + +`CHANGELOG.md` is written by the release, and by nothing else. Your pull request's description +carries its note, under `## Changelog` (the template has the heading): what a deployment does +differently afterwards, for the person deciding whether to upgrade, each line under a bold heading +on a line of its own, the way `CHANGELOG.md` groups them. Write `none` when nobody running OpenBot +would notice. Preparing a release collects the notes of every pull request it ships into its section +of `CHANGELOG.md`. + +```md +## Changelog + +**API.** + +- **Added: reading an app with its actions in a body.** What changes for a deployment. +``` + +CI's `release note` check fails a pull request that changes `CHANGELOG.md`, has no note, or +deprecates part of the API without naming it in the note with its sunset. It reads the description +at the end of the run, so an edit made while CI runs counts; after the run, a maintainer re-runs it +for a pull request from a fork, and a branch of this repository's re-runs on its own when the +description is edited. Nothing needs to be pushed. A note can still be corrected after the pull +request merges, by editing its description before the release is prepared. + ## How CI runs on your pull request - **A maintainer approves it first.** CI on a pull request from an outside contributor waits for a diff --git a/api/README.md b/api/README.md index 2fa7790501..f828324b12 100644 --- a/api/README.md +++ b/api/README.md @@ -113,20 +113,28 @@ exception: nothing can count it, so its sunset alone decides (below). description: Deprecated. Send `schedule` instead. ``` -2. List it in [CHANGELOG.md](../CHANGELOG.md), in the Deprecated list under `## Unreleased`'s - "Before upgrading": one line naming it as the server counts it, in backticks, with what replaces - it and its sunset. An operation is its method and path; a part of one adds `query `, - `header `, `body ` or `response `, with `[]` for an array's items. +2. Name it in the pull request's release note, under `## Changelog` in its description and + `**Before upgrading.**` there: one line naming it as the server counts it, in backticks, with + what replaces it and its sunset. The release copies the note into the Deprecated list of its + section of [CHANGELOG.md](../CHANGELOG.md); nobody edits CHANGELOG.md by hand. An operation is + its method and path; a part of one adds `query `, `header `, `body ` or + `response `, with `[]` for an array's items. ```markdown + ## Changelog + + **Before upgrading.** + - **Deprecated.** Each still works, answers with `Deprecation` and `Sunset` headers, and is removed no earlier than its sunset, and only once nothing uses it. - `PATCH /api/v2/organizations/{organizationId}/routines/{routineId} body cron`: send `schedule` instead. Sunset 2027-12-01. ``` -`shared/tests/api-deprecations.test.ts` fails a pull request whose marks are incomplete or whose -deprecations the changelog doesn't list. The server reads the same marks from the spec it is +`shared/tests/api-deprecations.test.ts` fails a pull request whose marks are incomplete, and CI's +`release note` check (scripts/release-note-check.ts) one whose note doesn't name each deprecation +it adds with its sunset. Preparing a release checks the same of every deprecation the spec marks, +against the CHANGELOG.md it writes. The server reads the same marks from the spec it is generated from, so a request that uses a deprecated element is answered with `Deprecation` ([RFC 9745](https://www.rfc-editor.org/rfc/rfc9745.html)), `Sunset` ([RFC 8594](https://www.rfc-editor.org/rfc/rfc8594.html)) and `Link: ; rel="deprecation"`, diff --git a/docs/api-and-migrations.md b/docs/api-and-migrations.md index 124411e152..58dc57ecc9 100644 --- a/docs/api-and-migrations.md +++ b/docs/api-and-migrations.md @@ -38,7 +38,8 @@ This page is the rules. The detail behind them is in [api-versioning.md](api-ver `enum`; the answer gets its own open copy (`PersonRoleAnswer` for `PersonRole`). 6. **Replace beside the old, then deprecate the old.** Mark it `deprecated: true` with `x-deprecation-date` and `x-sunset` (both `YYYY-MM-DD`), the sunset at least 365 days out. Say - in its description what to use instead. List it in `CHANGELOG.md`'s Deprecated list. How: + in its description what to use instead. Name it in the pull request's release note, under + `## Changelog` in its description; the release writes it into `CHANGELOG.md`. How: [api/README.md, "Deprecating"](../api/README.md#deprecating). ```yaml @@ -168,8 +169,8 @@ or a migration runs twice. Fix the change, never the list of releases. - [ ] I read this page. - [ ] Nothing a released app uses is removed, renamed, retyped or tightened in place. - [ ] New request inputs are optional; a response enum that will grow is `x-extensible-enum`. -- [ ] Anything replaced is deprecated with an `x-sunset` at least 365 days out, and listed in the - changelog. +- [ ] Anything replaced is deprecated with an `x-sunset` at least 365 days out, and named in the + release note under `## Changelog` in this pull request's description. - [ ] Nothing new in `api/accepted-breaking-changes.md` takes anything from a client. - [ ] `bun run api:generate` run, and sources, bundle and clients committed together. - [ ] Every database change is an expand, or a contract of what a release already out stopped diff --git a/docs/api-versioning.md b/docs/api-versioning.md index ad6e218e6b..f4d21c4a36 100644 --- a/docs/api-versioning.md +++ b/docs/api-versioning.md @@ -131,9 +131,10 @@ only once nothing uses it. - **Counted per app.** Each use is counted by the app that made it, from the `OpenBot-Client` header: each OpenBot app and release the header names, `unknown` with no header, `other` for a header that names no OpenBot app. The count that decides removal is OpenBot Cloud's. -- **Announced in the changelog.** One line in the Deprecated list under `## Unreleased`'s "Before - upgrading" in [CHANGELOG.md](../CHANGELOG.md), naming it as the server counts it, with its - replacement and its sunset. +- **Announced in the changelog.** One line in the release note of the pull request that deprecates + it, under `## Changelog` in its description and "Before upgrading" there, naming it as the server + counts it, with its replacement and its sunset. The release writes it into the Deprecated list of + its section of [CHANGELOG.md](../CHANGELOG.md). - **Removed when both are true:** its sunset has passed, and nothing has used it over the last 12 months by that count. Otherwise it stays, and its sunset moves later, never earlier. A response property is the one exception: it gets no header and no count, and its sunset alone decides. @@ -318,7 +319,8 @@ The live channels are compared with the base branch only. | Test | Fails when | | --- | --- | -| `shared/tests/api-deprecations.test.ts` | A deprecation mark is incomplete (a date missing or invalid, a sunset before the deprecation, a path parameter marked on its own), or `CHANGELOG.md` doesn't list a deprecation with its sunset. | +| `shared/tests/api-deprecations.test.ts` | A deprecation mark is incomplete (a date missing or invalid, a sunset before the deprecation, a path parameter marked on its own). | +| CI's `release note` (`scripts/release-note-check.ts`) | The pull request's release note doesn't name a deprecation it adds with its sunset. Preparing a release refuses the same for any deprecation its `CHANGELOG.md` would leave out. | | `api/openapi-extensible-enums.test.ts` | A parameter or request body reaches an open enum, or an open enum also has `enum`. | | `app/tests/tolerant-reader.test.ts`, `mobile/tests/tolerant-reader.test.ts` | A generated client throws on an unknown field or enum value. | | `app/tests/unknown-enum-values.test.tsx`, `mobile/tests/unknown-statuses.test.ts` | A screen crashes, says "undefined" or guesses a known value for a status, role or kind it doesn't know. | @@ -349,7 +351,8 @@ Never by dropping a release from the legs. place. - [ ] A new response enum that will grow is `x-extensible-enum`; a request enum stays `enum`. - [ ] Anything replaced is deprecated with `x-deprecation-date` and an `x-sunset` at least 365 days - out, says what to use instead, and is in the changelog's Deprecated list. + out, says what to use instead, and is named in the release note under `## Changelog` in the + pull request's description. - [ ] A line in `accepted-breaking-changes.md` only for a change that takes nothing from a client, with the reason; "no release serves it" only when that is true. - [ ] `bun run api:generate` run, and the sources, the bundle and the generated clients committed diff --git a/docs/installer-runbook.md b/docs/installer-runbook.md index 046580ffc9..f3d78c9dde 100644 --- a/docs/installer-runbook.md +++ b/docs/installer-runbook.md @@ -147,7 +147,10 @@ Use a candidate to test what will become a release. The details are in upgrades from, its database transition, downtime and recovery. Publishing refuses a policy that names another version. Within one release, **Create release PR** moves only its `version` (`v0.3.0`, `v0.3.0-rc.1`, …). -2. Make sure `CHANGELOG.md` has the release notes under `## Unreleased`. +2. Make sure every pull request since the last release has its note under `## Changelog` in its + description, or `none` there: run **Create release PR** with `-f dry_run=true` and read the notes + it shows. To change one, edit that pull request's description; nobody edits `CHANGELOG.md`, which + the release writes. See [Where the notes come from](releasing.md#where-the-notes-come-from). 3. Cut the first candidate from `main`: ```sh diff --git a/docs/releasing.md b/docs/releasing.md index 493f5bf6f8..89e37b9319 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -5,19 +5,19 @@ step involves a terminal, a tag pushed by hand, or an image built on somebody's ## Cutting one -1. Before cutting, [rebuild the changelog from the code](#rebuild-the-changelog-from-the-code). -2. Check `## Unreleased` in [CHANGELOG.md](../CHANGELOG.md) reads the way you want it to. It is the - release notes. Nothing is generated from commit subjects, because a commit subject is written for - the person reading the diff and these notes are for the person deciding whether to upgrade. - Anything the API deprecated since the last release is in the Deprecated list under "Before - upgrading", with its sunset; CI fails a deprecation the changelog doesn't list - ([api/README.md](../api/README.md#deprecating)). -3. Run **Create release PR** from the Actions tab, choosing `patch`, `minor` or `major`. Leave - `kind` as `stable`. Use `dry_run` first if you want to see the version and the notes without - opening anything. -4. Review the pull request it opens. It updates `package.json`, promotes the changelog's - `## Unreleased` heading to `## X.Y.Z`, moves the desktop Cargo package/lockfile to the same - version, and pins `backend-images.env` to `vX.Y.Z`, so a checkout of the release runs the +1. Before cutting, [check the notes against the code](#check-the-notes-against-the-code). +2. Run **Create release PR** from the Actions tab, choosing `patch`, `minor` or `major`, with + `dry_run` first: it shows the version and the notes without opening anything. The notes are + written by the release, from the pull requests it ships (see + [Where the notes come from](#where-the-notes-come-from)). Nothing is generated from commit + subjects, because a commit subject is written for the person reading the diff and these notes are + for the person deciding whether to upgrade. Anything the API deprecated since the last release + must be in the notes, under "Before upgrading", with its sunset; the release refuses to write a + changelog that doesn't list one ([api/README.md](../api/README.md#deprecating)). +3. Run it again without `dry_run`. Leave `kind` as `stable`. +4. Review the pull request it opens. It updates `package.json`, writes the notes into + [CHANGELOG.md](../CHANGELOG.md) under `## X.Y.Z`, below an empty `## Unreleased`, moves the + desktop Cargo package/lockfile to the same version, and pins `backend-images.env` to `vX.Y.Z`, so a checkout of the release runs the OpenBot server, computer and supervisor images of that release. Those images must be published at `vX.Y.Z` before it merges, with their release files (`ghcr.io/copilotkit/openbot:charts-vX.Y.Z`), which carry the two Helm charts and the name of the last migration. Tauri reads its version directly from the root `package.json`. @@ -53,15 +53,33 @@ other three are for a release candidate or beta, and are described under [Release candidates and betas](#release-candidates-and-betas) and [Finishing a candidate](#finishing-a-candidate). -### Rebuild the changelog from the code +### Where the notes come from -Entries added to `## Unreleased` since the last release are claims, not evidence, so none is -trusted as written. Before cutting a release, and before the first candidate or beta of one, go -through every change since the last release tag (`git log vX.Y.Z..origin/main` and each one's diff), -check it in the code, and write `## Unreleased` from what the code shows: keep an entry only where -the code proves it, rewrite one that overstates, understates or misdescribes the change, drop one -the code does not do, and add one for any change no entry mentions. Land it on `main` as a pull -request like any other. +`CHANGELOG.md` is written by the release and by nothing else. No other pull request changes it, and +CI refuses one that does, so two pull requests never conflict over it. Each pull request carries its +note in its own description, under `## Changelog`, in the shape the changelog uses: lines under a +bold heading, such as `**API.**` or `**Before upgrading.**`. One that changes nothing a person +running OpenBot would notice says `none` there. + +Create release PR reads the description of every pull request merged since the previous stable +release (the highest `vX.Y.Z` tag below the new version) and merges their notes: one group per +heading, "Before upgrading" first, the rest in the order their pull requests first merged, and each +group's lines in merge order (scripts/release-prepare.ts, scripts/release-collect-notes.ts). The +release's own pull requests (release PRs, merge-backs, main's images) are skipped. Lines that were +under `## Unreleased` before notes moved into descriptions come first, so none is lost. A pull +request whose note is missing or can't be read stops the run, named, with a link. + +To change a note, edit that pull request's description, even after it merged, and run Create release +PR again. Nobody edits `CHANGELOG.md`. + +### Check the notes against the code + +Notes are claims, not evidence, so none is trusted as written. Before cutting a release, and before +the first candidate or beta of one, run Create release PR with `dry_run`, go through every change +since the last release tag (`git log vX.Y.Z..origin/main` and each one's diff), and check each note +in the code: keep a note only where the code proves it, rewrite one that overstates, understates or +misdescribes the change, drop one the code does not do, and add one for any change no note +mentions. Each fix is an edit to that pull request's description. Then run it again. ## Desktop build versions @@ -509,10 +527,14 @@ replaces it with a signed one, pinned the same way. Until then the first open ne described under [Internal builds](#internal-builds). Link a candidate's installers by its version, as described under [Download links](#download-links). -A candidate does not promote the changelog. Its notes are what is under `## Unreleased` at that -moment, and the final promotes them, so -[rebuild the changelog from the code](#rebuild-the-changelog-from-the-code) on `main` before the -first candidate is cut. A candidate also fixes the CLI choice, as described under +A candidate writes its notes under `## Unreleased` on its release branch, where publishing it reads +them: the notes of every pull request since the previous stable release, as for a stable release +(see [Where the notes come from](#where-the-notes-come-from)), fixes merged into the branch +included. The next candidate and the final write them again from the descriptions, so a note edited +between candidates is the one that ships. What was under `## Unreleased` before notes moved into +descriptions is read from the commit the first candidate was cut from, so it counts once. +[Check the notes against the code](#check-the-notes-against-the-code) before the first candidate is +cut. A candidate also fixes the CLI choice, as described under [Which Intelligence CLI an installer carries](#which-intelligence-cli-an-installer-carries). `release-policy.json` describes one release: the versions it upgrades from, its database transition, @@ -539,7 +561,8 @@ The tip of `release/X.Y` must carry a candidate tag. If the branch has moved on candidate, the run stops with "Cut a new candidate first". A final ships what a candidate was tested as, so it is cut from the commit a candidate was published from and nothing newer. -The final release PR promotes the changelog and moves the same version files as any release. When +The final release PR writes the changelog's `## X.Y.Z` section, with an empty `## Unreleased` +above it, and moves the same version files as any release. When it merges, the publish workflow compares the release against its candidate before it builds anything, and fails if anything else changed. The allowed difference is: diff --git a/scripts/ci-changes.test.ts b/scripts/ci-changes.test.ts index 82d27281cc..2e220ad38f 100644 --- a/scripts/ci-changes.test.ts +++ b/scripts/ci-changes.test.ts @@ -9,9 +9,11 @@ import { type Deps, decide, decideMainPush, + decideMergeGroup, isBunTest, isCode, isDocs, + isIgnored, isTestFile, type PullRequest, PYTHON_HARNESSES, @@ -25,6 +27,99 @@ const ROOT = join(import.meta.dir, ".."); /** Every check a full CI run passes, by the job names the Actions API reports. */ const ALL_CI = [...CI_RULES, SUITE_RULE].flatMap((rule) => rule.checks); +/** The tests that name CHANGELOG.md, as `git grep -l CHANGELOG.md -- '*.test.ts'` finds them. */ +const NAME_CHANGELOG = [ + "scripts/release-candidate-check.test.ts", + "scripts/release-ci-gate.test.ts", + "scripts/release-prepare.test.ts", + "shared/tests/api-deprecations.test.ts", +]; + +/** + * Release v1.2.7's own pull request (#2648), and #2654, the change whose CHANGELOG.md line collided + * with #2646: their files as GitHub lists them. + */ +const RELEASE_1_2_7_FILES = [ + "CHANGELOG.md", + "backend-images.env", + "desktop/src-tauri/Cargo.lock", + "desktop/src-tauri/Cargo.toml", + "package.json", +]; +const PR_2654_FILES = [ + "CHANGELOG.md", + "api/openapi-address-length.test.ts", + "api/openapi-bot-grants.test.ts", + "api/openapi.yaml", + "api/openapi/bot-grants.yaml", + "api/openapi/common.yaml", + "api/openapi/learning.yaml", + "app/src/lib/api/generated/bot-grants/bot-grants.ts", + "app/src/lib/api/generated/learning/learning.ts", + "app/src/lib/api/generated/model/index.ts", + "mobile/src/api/generated/bot-grants/bot-grants.ts", + "mobile/src/api/generated/model/index.ts", +]; + +/** + * Files of this tree that no job, build, lint or test reads: prose, the agents' skills, the + * diagrams, the licence and GitHub's own files. Checked by hand against every test, script, + * workflow and config, and by `realMentions` below against every test that names a path. + */ +const UNREAD_DOCS = [ + "README.md", + "AGENTS.md", + "CONTRIBUTING.md", + "docs/releasing.md", + "docs/windows-signing.md", + "docs/api-and-migrations.md", + "docs/plugins/composio.md", + "docs/assets/architecture-overview-dark.svg", + "app/PRODUCT.md", + "mobile/AGENTS.md", + "desktop/TELEMETRY.md", + ".claude/skills/openbot-copy/SKILL.md", + ".claude/skills/openbot-screen-layout/SKILL.md", + ".github/pull_request_template.md", + ".github/CODEOWNERS", + "LICENSE", +]; + +/** The suite's tests that name any of these paths, found the way ci-changes.ts finds them. */ +function realMentions(paths: string[]): string[] { + const out = Bun.spawnSync( + [ + "git", + "grep", + "-l", + "-z", + "-F", + ...paths.flatMap((path) => ["-e", path]), + "--", + "*.test.ts", + "*.test.tsx", + ], + { cwd: ROOT }, + ).stdout.toString(); + return out.split("\0").filter((file) => file && isBunTest(file)); +} + +const readTracked = (path: string) => { + try { + return readFileSync(join(ROOT, path), "utf8"); + } catch { + return undefined; + } +}; + +/** A test that drives a real browser, as ci-changes.ts tells one. */ +const isBrowserFile = (file: string) => + file.endsWith(".browser.test.ts") || + (readTracked(file)?.includes("OPENBOT_APP_BROWSER") ?? false); + +/** This checkout, as the merge group's `changes` job reads it. */ +const REAL = { mentions: realMentions, read: readTracked }; + const PR: PullRequest = { labels: [], headRef: "fix/a-thing", @@ -111,6 +206,44 @@ describe("what a changed file is", () => { expect(isCode(path)).toBe(true); } }); + + test("this tree's docs are docs; its key, queries, fixtures and editor config under docs-like names are code", () => { + for (const path of [...UNREAD_DOCS, "docs/agent-frameworks.md"]) { + expect({ path, docs: isDocs(path) }).toEqual({ path, docs: true }); + } + for (const path of [ + "docs/cosign.pub", + "docs/telemetry-queries.sql", + "scripts/release-note-check.fixtures/pr-2654.md", + "scripts/release-notes.fixture-1.2.6.json", + "app/tests/fixtures/notes.md", + ".editorconfig", + ".gitattributes", + ]) { + expect({ path, docs: isDocs(path) }).toEqual({ path, docs: false }); + } + }); + + test("every tracked file the rule calls docs is one of the kinds it lists", () => { + const tracked = Bun.spawnSync(["git", "ls-files", "-z"], { cwd: ROOT }) + .stdout.toString() + .split("\0") + .filter(Boolean); + const unexpected = tracked + .filter(isDocs) + .filter( + (path) => + !path.endsWith(".md") && + !path.startsWith(".claude/") && + !/^docs\/.*\.(svg|png|jpe?g|gif|webp)$/.test(path) && + !["LICENSE", ".github/CODEOWNERS"].includes(path), + ); + expect(unexpected).toEqual([]); + // And none of them is a fixture a test reads. + expect( + tracked.filter(isDocs).filter((path) => /fixture/.test(path)), + ).toEqual([]); + }); }); describe("a pull request push", () => { @@ -208,12 +341,54 @@ describe("a pull request push", () => { PR, deps({ passed: { c2: ALL_CI }, - changes: { c2: ["docs/ci.md", "CHANGELOG.md"] }, - mentions: { "CHANGELOG.md": ["tests/release-policy.test.ts"] }, + changes: { c2: ["docs/ci.md", "desktop/TELEMETRY.md"] }, + mentions: { "desktop/TELEMETRY.md": ["tests/api-docs.test.ts"] }, }), ); expect(running(decision)).toEqual(["partial"]); - expect(decision.tests).toEqual(["tests/release-policy.test.ts"]); + expect(decision.tests).toEqual(["tests/api-docs.test.ts"]); + }); + + test("CHANGELOG.md alone runs nothing, not even the tests that name it", () => { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: ["CHANGELOG.md"] }, + mentions: { "CHANGELOG.md": NAME_CHANGELOG }, + }), + ); + expect(running(decision)).toEqual([]); + expect(decision.tests).toEqual([]); + }); + + test("CHANGELOG.md beside code adds nothing to what the code runs", () => { + const code = ["app/src/lib/marks.ts"]; + const withChangelog = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: [...code, "CHANGELOG.md"] }, + mentions: { "CHANGELOG.md": NAME_CHANGELOG }, + }), + ); + const without = decide( + "ci", + PR, + deps({ passed: { c2: ALL_CI }, changes: { c2: code } }), + ); + expect(withChangelog.run).toEqual(without.run); + expect(withChangelog.tests).toEqual(without.tests); + expect(running(withChangelog)).toEqual([ + "api", + "app_browser", + "build", + "startup", + "static", + "suite", + ]); }); test("a document nothing names runs nothing at all", () => { @@ -461,6 +636,126 @@ describe("everything runs", () => { }); }); +describe("CHANGELOG.md", () => { + test("is the one path CI never reacts to", () => { + expect(isIgnored("CHANGELOG.md")).toBe(true); + for (const path of [ + "docs/CHANGELOG.md", + "changelog.md", + "README.md", + "release-policy.json", + ...PR_2654_FILES.filter((path) => path !== "CHANGELOG.md"), + ]) { + expect({ path, ignored: isIgnored(path) }).toEqual({ + path, + ignored: false, + }); + } + }); + + test("a pull request whose real files are code and CHANGELOG.md runs what the code runs", () => { + const decision = decide( + "ci", + PR, + deps({ + passed: { c2: ALL_CI }, + changes: { c2: PR_2654_FILES }, + mentions: { "CHANGELOG.md": NAME_CHANGELOG }, + }), + ); + expect(running(decision)).toEqual([ + "api", + "app_browser", + "build", + "mobile", + "startup", + "static", + "suite", + ]); + }); +}); + +describe("a merge group", () => { + const everyJob = [...CI_RULES.map((rule) => rule.output), "suite"].sort(); + + test("that changes only CHANGELOG.md runs nothing, not even the tests that name it", () => { + const decision = decideMergeGroup("ci", ["CHANGELOG.md"], REAL); + expect(running(decision)).toEqual([]); + expect(decision.ignoredOnly).toBe(true); + expect(decision.reasons[0]).toContain("CHANGELOG.md"); + }); + + test("of this tree's docs runs no job, only the tests that name one", () => { + const decision = decideMergeGroup( + "ci", + [...UNREAD_DOCS, "CHANGELOG.md"], + REAL, + ); + expect(running(decision)).toEqual( + decision.tests.length > 0 ? ["partial"] : [], + ); + expect(decision.tests).toEqual( + realMentions(UNREAD_DOCS) + .filter((file) => !isBrowserFile(file)) + .sort(), + ); + expect(decision.ignoredOnly).toBe(true); + }); + + test("a doc a test reads runs that test, and no job", () => { + const decision = decideMergeGroup("ci", ["docs/agent-frameworks.md"], REAL); + expect(running(decision)).toEqual(["partial"]); + expect(decision.tests).toContain( + "tests/agent-frameworks-receivers.test.ts", + ); + }); + + test("runs everything for a key under docs/, the API's Markdown and a fixture", () => { + for (const path of [ + // scripts/release-files.sh verifies releases with it; tests/release-charts.test.ts reads it. + "docs/cosign.pub", + // The API job reads api/'s Markdown: the accepted breaking changes. + "api/accepted-breaking-changes.md", + // scripts/release-note-check.test.ts reads it as #2654's description. + "scripts/release-note-check.fixtures/pr-2654.md", + ]) { + const decision = decideMergeGroup("ci", [path], REAL); + expect({ path, run: running(decision) }).toEqual({ + path, + run: everyJob, + }); + } + }); + + test("with code in it runs everything, CHANGELOG.md or not", () => { + for (const files of [ + PR_2654_FILES, + RELEASE_1_2_7_FILES, + ["app/src/lib/marks.ts"], + ["README.md", "app/src/lib/marks.ts"], + ]) { + const decision = decideMergeGroup("ci", files, REAL); + expect(running(decision)).toEqual(everyJob); + expect(decision.ignoredOnly).toBe(false); + } + }); + + test("whose files could not be read, or are none, runs everything", () => { + for (const files of [undefined, []]) { + expect(running(decideMergeGroup("ci", files, REAL))).toEqual(everyJob); + } + }); + + test("ci.yml: the image builds, the one check outside `changes`, skip it too", () => { + const parsed = Bun.YAML.parse( + readFileSync(join(ROOT, ".github/workflows/ci.yml"), "utf8"), + ) as { jobs: Record }; + const list = parsed.jobs["component-list"]; + expect(list.needs).toEqual("changes"); + expect(list.if).toContain("needs.changes.outputs.ignored_only != 'true'"); + }); +}); + describe("main's run of a push", () => { const SHA = "cad6dc08eb158054ed3fc37c0aa7b9d0cb3dc4eb"; const REPOSITORY = "CopilotKit/OpenBot"; diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index b5c5b335b0..1de9a4e896 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -15,8 +15,8 @@ * with any test that names one of them, in `tests (changed files)`; `format, lint, types` still * runs, since it formats, lints and type checks the tests. A test file that drives a real browser * runs in one there. - * - Docs only. Nothing runs but the tests that name a changed document (the release tests that read - * CHANGELOG.md, for example). + * - Docs only. Nothing runs but the tests that name a changed document. CHANGELOG.md runs nothing at + * all, not even the tests that name it. * - A release PR: labelled `release`, from this repository's `release/publish/v*` branch, changing * only the release files, each version file only by its version (scripts/release-ci-gate.ts says * which). Only the checks the release gate itself re-runs on such a commit run: `format, lint, @@ -25,8 +25,12 @@ * main's own run of a commit the merge queue merged runs none of CI's checks again: the queue's run * tested that very commit, so it skips them and names that run (decideMainPush), keeping only the * jobs that write a cache the push changed the key of. A push the queue did not test (an admin's - * merge, a direct push) runs everything. So does every other event (a merge group, the release's own - * call of CI, a schedule), and a pull request labelled `full-ci`. + * merge, a direct push) runs everything. So does a merge group (decideMergeGroup), unless all it + * changes is files no check reads (CHANGELOG.md, docs no test names), every other event (the + * release's own call of CI, a schedule), and a pull request labelled `full-ci`. + * + * CHANGELOG.md is never a reason to run anything (isIgnored): the release writes it, and a change + * to it is left out of every decision above. * * Usage, from the root of a checkout with the history (fetch-depth 0): * @@ -59,13 +63,51 @@ const matcher = (...patterns: string[]) => { return (path: string) => globs.some((glob) => glob.match(path)); }; -/** Writing for people: no job compiles, bundles or runs it. A test that names one still runs. */ -export const isDocs = matcher( - "**/*.md", - "docs/**", - ".claude/**", - "LICENSE", - "LICENSE.*", +/** + * What CI never reacts to. CHANGELOG.md is written by the release from the notes in pull requests' + * descriptions (scripts/release-notes.ts), never by hand, and no check runs because it changed: not + * a job, not a test that names it, not in a pull request, a merge group or anywhere else CI decides. + * The release's own gate still holds a release PR's changelog to the release tests + * (publish-release.yml's `checks needed`). + */ +export const isIgnored = (path: string) => path === "CHANGELOG.md"; + +/** + * Writing for people: no job compiles, bundles, lints or runs it, so a change to one runs no job. A + * test that names one by its path still runs (`mentions`), and a job whose rule reads one still does + * (the API job reads api/**'s Markdown). Each kind was checked against every test, script, build, + * lint and workflow in the tree before it was listed: + * + * - `**\/*.md`: the docs, READMEs, AGENTS.md and CLAUDE.md files, the PR template. Biome formats + * and lints no Markdown, no Dockerfile copies one into an image, and no app imports one. + * - `docs/**`'s pictures: the diagrams the docs show. Nothing else under docs/ is: docs/cosign.pub + * is the key scripts/release-files.sh verifies a release with, and docs/telemetry-queries.sql is + * kept as code. + * - `.claude/**`: the coding agents' skills. Tests cite them in comments; none reads one. + * - LICENSE, and .github/CODEOWNERS and issue templates, which only GitHub reads. + * + * Never a test's fixture, whatever its extension: a test reads it by a name that is not its path. + * Not .editorconfig either: Biome formats by it. + */ +export const isDocs = (path: string) => + !isFixture(path) && + matcher( + "**/*.md", + "docs/**/*.{svg,png,jpg,jpeg,gif,webp}", + ".claude/**", + "LICENSE", + "LICENSE.*", + ".github/CODEOWNERS", + ".github/ISSUE_TEMPLATE/**", + )(path); + +/** A test's input, which the test reads however it is named. */ +const isFixture = matcher( + "**/fixtures/**", + "**/*.fixtures/**", + "**/__fixtures__/**", + "**/*.fixture.*", + "**/*.fixture-*", ); /** The TypeScript LangGraph engine's tests are Node's; bunfig.toml keeps the suite out of there. */ @@ -172,7 +214,9 @@ export const CI_RULES: Rule[] = [ { output: "mobile", checks: ["native types"], - reads: (path) => matcher("mobile/**")(path) || ciInputs(path), + // Type checks the phone app: its AGENTS.md and CLAUDE.md are for the people and agents writing it. + reads: (path) => + (!isDocs(path) && matcher("mobile/**")(path)) || ciInputs(path), }, { output: "app_browser", @@ -399,7 +443,9 @@ export function decide( const since = (sha: string) => { let changes = changesSince.get(sha); if (!changes) { - changes = deps.diff(sha, pr.head); + changes = deps + .diff(sha, pr.head) + .filter((change) => !isIgnored(change.path)); changesSince.set(sha, changes); } return changes; @@ -663,6 +709,72 @@ export function decideMainPush( }; } +/** + * Decides a merge group's run. A group's tree is one no run has checked yet, so it runs everything, + * unless all it changes on top of the commit it merges onto is what CI never reacts to (a release + * PR's changelog, say): then that commit's tree, already through main's checks, is what this one + * builds and tests, and nothing runs. `changed` is the group's files, or undefined when they could + * not be read, which runs everything. + */ +export function decideMergeGroup( + workflow: Workflow, + changed: string[] | undefined, + deps: Pick, +): Decision & { ignoredOnly: boolean } { + const rules = rulesOf(workflow); + // A file no job's rule reads: CHANGELOG.md, and the docs. A test that names a doc still runs. + const unread = (path: string) => + isIgnored(path) || + (!unusualPath(path) && rules.every((rule) => !rule.reads(path))); + if (changed && changed.length > 0 && changed.every(unread)) { + const run: Record = { partial: false }; + for (const rule of rules) run[rule.output] = false; + const decision: Decision & { ignoredOnly: boolean } = { + run, + tests: [], + browserTests: [], + webkitTests: [], + desktopBrowserTests: [], + reasons: [ + `A merge group that changes only ${changed.join(", ")}, which no job reads.`, + ], + ignoredOnly: true, + }; + if (workflow === "ci") { + const named = deps + .mentions(changed.filter((path) => !isIgnored(path))) + .filter(isBunTest) + .sort(); + for (const file of named) { + if (!isBrowserTest(file, deps)) decision.tests.push(file); + else if (file.startsWith("desktop/")) + decision.desktopBrowserTests.push(file); + else { + decision.browserTests.push(file); + if (deps.read(file)?.includes("OPENBOT_APP_ENGINES")) + decision.webkitTests.push(file); + } + } + run.partial = named.length > 0; + decision.reasons.push( + run.partial + ? `tests (changed files): ${named.join(", ")}, which name them.` + : "Nothing runs.", + ); + } + return decision; + } + return { + ...everything( + rulesOf(workflow), + changed + ? "A merge group: everything runs." + : "A merge group whose files could not be read: everything runs.", + ), + ignoredOnly: false, + }; +} + function describe(changes: Change[]): string { const shown = changes.slice(0, 5).map((change) => change.path); return changes.length > 5 @@ -795,6 +907,7 @@ type PullRequestEvent = { head: { ref: string; sha: string; repo?: { full_name?: string } | null }; base: { sha: string }; }; + merge_group?: { base_sha: string; head_sha: string }; /** A push's previous head of the branch. */ before?: string; }; @@ -861,7 +974,7 @@ if (import.meta.main) { } const repository = process.env.GITHUB_REPOSITORY ?? ""; const eventName = process.env.GITHUB_EVENT_NAME ?? ""; - let decision: Decision & { queueRun?: CiRun }; + let decision: Decision & { queueRun?: CiRun; ignoredOnly?: boolean }; try { const event = ( process.env.GITHUB_EVENT_PATH @@ -892,6 +1005,16 @@ if (import.meta.main) { repository, pushedFiles(repository, event.before, sha), ); + } else if (eventName === "merge_group" && event.merge_group) { + decision = decideMergeGroup( + workflow, + pushedFiles( + repository, + event.merge_group.base_sha, + event.merge_group.head_sha, + ), + liveDeps(workflow, repository, 0, [repository]), + ); } else { decision = decide( workflow, @@ -917,6 +1040,7 @@ if (import.meta.main) { writeOutput(output, String(value)); } writeOutput("queue_run", decision.queueRun?.html_url ?? ""); + writeOutput("ignored_only", String(decision.ignoredOnly ?? false)); writeOutput("tests", JSON.stringify(decision.tests)); writeOutput("browser_tests", JSON.stringify(decision.browserTests)); writeOutput("webkit_tests", JSON.stringify(decision.webkitTests)); diff --git a/scripts/release-collect-notes.test.ts b/scripts/release-collect-notes.test.ts new file mode 100644 index 0000000000..7e3a2e7496 --- /dev/null +++ b/scripts/release-collect-notes.test.ts @@ -0,0 +1,293 @@ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + type ApiPull, + type CollectDeps, + collectNotes, + firstPrerelease, + isReleaseSystemPull, + NOTES_MODULE, + previousStableTag, +} from "./release-collect-notes"; +import { combineNotes, parseGroups, renderGroups } from "./release-notes"; + +const REPOSITORY = "CopilotKit/OpenBot"; + +/** + * The real 1.2.6 release: its commits and their pull requests as the API returns them, each + * description given the note it would have carried (scripts/release-notes.fixture-1.2.6.json). + */ +const fixture = JSON.parse( + readFileSync( + join(import.meta.dir, "release-notes.fixture-1.2.6.json"), + "utf8", + ), +) as { + version: string; + head: string; + previousTag: string; + commits: string[]; + pulls: Record; +}; + +const CHANGELOG = readFileSync( + join(import.meta.dir, "..", "CHANGELOG.md"), + "utf8", +); + +/** A section of the real CHANGELOG.md, without its heading. */ +function section(heading: string): string { + const lines = CHANGELOG.split("\n"); + const start = lines.indexOf(heading); + const end = lines.findIndex( + (line, index) => index > start && line.startsWith("## "), + ); + return lines + .slice(start + 1, end) + .join("\n") + .trim(); +} + +function deps(overrides: Partial = {}): CollectDeps & { + asked: string[]; +} { + const asked: string[] = []; + return { + asked, + tags: () => ["v1.2.4", "v1.2.5", "v1.2.6", "v1.2.0-rc.1", "v1.10.0-rc.1"], + mergeBase: (a) => { + expect(a).toBe(fixture.previousTag); + return "base"; + }, + commits: (base, head) => { + expect(base).toBe("base"); + expect(head).toBe(fixture.head); + return fixture.commits; + }, + pullsOf: (sha) => { + asked.push(sha); + return structuredClone(fixture.pulls[sha] ?? []); + }, + // Every commit sits on a tree that reads notes from descriptions. + show: (_ref, path) => (path === NOTES_MODULE ? "" : undefined), + ...overrides, + }; +} + +describe("the real 1.2.6 release", () => { + test("its notes, gathered from the descriptions, are the section 1.2.6 shipped", () => { + const collected = collectNotes( + fixture.version, + fixture.head, + REPOSITORY, + deps(), + ); + expect(collected.previousTag).toBe("v1.2.5"); + expect(collected.problems).toEqual([]); + expect(collected.notes.map((note) => note.pull.number)).toEqual([ + 2625, 2631, 2638, + ]); + expect(collected.none.map((pull) => pull.number)).toEqual([2637]); + // The release PR and the PR that ran main's images again, both opened by the release. + expect(collected.skipped.map((pull) => pull.number)).toEqual([2627, 2640]); + + const written = renderGroups( + combineNotes(collected.notes.map((note) => note.groups)), + ); + // Every line is the one 1.2.6 shipped. Only the order of the groups differs: the release puts + // Before upgrading first and the rest in the order their pull requests first merged, where the + // person who wrote 1.2.6 put the newest first. + const shipped = parseGroups(section("## 1.2.6")).groups; + const byHeading = (heading: string) => { + const group = shipped.find((candidate) => candidate.heading === heading); + if (!group) throw new Error(`1.2.6 has no ${heading}`); + return group; + }; + expect(shipped.map((group) => group.heading)).toEqual([ + "Before upgrading.", + "Artifacts.", + "Your account.", + "Conversations.", + ]); + expect(written).toBe( + renderGroups( + [ + "Before upgrading.", + "Conversations.", + "Your account.", + "Artifacts.", + ].map(byHeading), + ), + ); + }); + + test("each commit is matched to the pull request it merged, once", () => { + const live = deps(); + collectNotes(fixture.version, fixture.head, REPOSITORY, live); + expect(live.asked).toEqual(fixture.commits); + }); + + test("a pull request with no note is named, with what to do", () => { + const pulls = structuredClone(fixture.pulls); + const sha = fixture.commits.find((commit) => + pulls[commit].some((pull) => pull.number === 2637), + ) as string; + pulls[sha][0].body = "## What broke\n\nSomething."; + const collected = collectNotes( + fixture.version, + fixture.head, + REPOSITORY, + deps({ pullsOf: (commit) => pulls[commit] ?? [] }), + ); + expect(collected.problems).toEqual([ + { + pull: expect.objectContaining({ number: 2637 }), + problems: ["Its description has no note under ## Changelog."], + }, + ]); + }); + + test("a pull request merged before notes moved into descriptions needs none there", () => { + const pulls = structuredClone(fixture.pulls); + const sha = fixture.commits.find((commit) => + pulls[commit].some((pull) => pull.number === 2637), + ) as string; + pulls[sha][0].body = "## What broke\n\nSomething."; + const collected = collectNotes( + fixture.version, + fixture.head, + REPOSITORY, + deps({ + pullsOf: (commit) => pulls[commit] ?? [], + // No commit's tree had the module yet, as on main before this flow. + show: () => undefined, + }), + ); + expect(collected.problems).toEqual([]); + expect(collected.before.map((pull) => pull.number)).toEqual([2637]); + // A note in its description is still used. + expect(collected.notes.map((note) => note.pull.number)).toEqual([ + 2625, 2631, 2638, + ]); + }); + + test("a pull request that only sits on a commit is not that commit's", () => { + const pulls = structuredClone(fixture.pulls); + const [first, second] = fixture.commits; + // The API also lists open or unrelated pull requests that contain a commit. + pulls[second].push({ + ...pulls[first][0], + number: 9999, + merge_commit_sha: "elsewhere", + }); + const collected = collectNotes( + fixture.version, + fixture.head, + REPOSITORY, + deps({ pullsOf: (commit) => pulls[commit] ?? [] }), + ); + expect( + [...collected.notes.map((note) => note.pull), ...collected.none].map( + (pull) => pull.number, + ), + ).not.toContain(9999); + }); +}); + +describe("where the notes start", () => { + test("the highest stable tag below the version, by number, not by name", () => { + const tags = [ + "v1.2.9", + "v1.2.10", + "v1.3.0-rc.1", + "v1.2.11-rc.1", + "1.2.8", + "v1.3.0", + ]; + expect(previousStableTag(tags, "1.2.11")).toBe("v1.2.10"); + expect(previousStableTag(tags, "1.2.11-rc.1")).toBe("v1.2.10"); + expect(previousStableTag(tags, "1.3.0")).toBe("v1.2.10"); + expect(previousStableTag(tags, "1.4.0")).toBe("v1.3.0"); + expect(previousStableTag(tags, "1.2.9")).toBeUndefined(); + }); + + test("the first candidate or beta of a version, betas first", () => { + const tags = ["v1.3.0-rc.2", "v1.3.0-rc.10", "v1.3.0-rc.1", "v1.2.0-rc.1"]; + expect(firstPrerelease(tags, "1.3.0")).toBe("v1.3.0-rc.1"); + expect(firstPrerelease(tags, "1.3.0-rc.3")).toBe("v1.3.0-rc.1"); + expect(firstPrerelease([...tags, "v1.3.0-beta.2"], "1.3.0")).toBe( + "v1.3.0-beta.2", + ); + expect(firstPrerelease(tags, "1.4.0")).toBeUndefined(); + }); + + test("a later candidate or the final reads the changelog the first candidate was cut from", () => { + const shown: string[] = []; + const collected = collectNotes( + "1.3.0", + "HEAD", + REPOSITORY, + deps({ + tags: () => ["v1.2.6", "v1.3.0-rc.1", "v1.3.0-rc.2"], + mergeBase: () => "base", + commits: () => [], + show: (ref, path) => { + shown.push(`${ref}:${path}`); + return "## Unreleased\n"; + }, + }), + ); + expect(shown).toEqual(["v1.3.0-rc.1^:CHANGELOG.md"]); + expect(collected.startedFrom).toEqual({ + tag: "v1.3.0-rc.1", + changelog: "## Unreleased\n", + }); + }); +}); + +describe("the release system's own pull requests", () => { + const pull = (login: string, ref: string, repo = REPOSITORY): ApiPull => ({ + number: 1, + title: "t", + html_url: "u", + body: null, + user: { login }, + head: { ref, repo: { full_name: repo } }, + merged_at: "2026-12-01T00:00:00Z", + merge_commit_sha: "s", + }); + + test("are told by their author and their branch together", () => { + for (const ref of [ + "release/publish/v1.2.8", + "release/publish/v1.3.0-rc.2", + "merge-back/v1.3.0", + "main-images/v1.2.7", + ]) { + expect( + isReleaseSystemPull(pull("github-actions[bot]", ref), REPOSITORY), + ).toBe(true); + } + // A person on a release branch name, the bot on any other branch, or a fork's branch. + expect( + isReleaseSystemPull( + pull("davidmckayv", "release/publish/v1.2.8"), + REPOSITORY, + ), + ).toBe(false); + expect( + isReleaseSystemPull(pull("github-actions[bot]", "fix/thing"), REPOSITORY), + ).toBe(false); + expect( + isReleaseSystemPull( + pull( + "github-actions[bot]", + "release/publish/v1.2.8", + "someone/OpenBot", + ), + REPOSITORY, + ), + ).toBe(false); + }); +}); diff --git a/scripts/release-collect-notes.ts b/scripts/release-collect-notes.ts new file mode 100644 index 0000000000..bc02519931 --- /dev/null +++ b/scripts/release-collect-notes.ts @@ -0,0 +1,254 @@ +/** + * The release notes of the pull requests a release ships, read from their descriptions. + * + * A release ships every pull request merged since the previous stable release. That release is the + * highest stable tag below the new version, found by its number and not by ancestry: a final is + * tagged on its `release/X.Y` branch, and the merge back into main is squashed, so the tag is not + * an ancestor of main. The notes start where that tag and this commit's history part (their merge + * base), which for a stable release from main is the tag itself and for a final is the commit its + * release branch was cut from. Every commit after it is matched to the pull request that merged it + * (the one whose merge commit it is), and that pull request's description is read for its + * `## Changelog` note (scripts/release-notes.ts). + * + * The release system's own pull requests (the release PRs, the merge back after a final, and the + * one that runs main's images again) carry no note and are skipped. They are told by who opened + * them and from where, never by anything a person types: opened by `github-actions[bot]`, from a + * branch of this repository named the way the release workflows name theirs. + */ + +import { type Group, parseNote } from "./release-notes"; +import { parseVersion } from "./release-version"; + +/** A merged pull request, as `GET /repos/{repo}/commits/{sha}/pulls` describes it. */ +export type ApiPull = { + number: number; + title: string; + html_url: string; + body: string | null; + user: { login: string } | null; + head: { ref: string; repo: { full_name: string } | null }; + merged_at: string | null; + merge_commit_sha: string | null; +}; + +export type CollectDeps = { + /** Every tag of the repository. */ + tags: () => string[]; + /** Where two commits' histories part. */ + mergeBase: (a: string, b: string) => string; + /** The commits after `base` up to `head`, or every commit up to `head` when base is undefined. */ + commits: (base: string | undefined, head: string) => string[]; + /** The pull requests GitHub associates with a commit. */ + pullsOf: (sha: string) => ApiPull[]; + /** A file's text at a commit, or undefined when it isn't there. */ + show: (ref: string, path: string) => string | undefined; +}; + +export type Collected = { + /** The stable release the notes start after, or undefined for the first one. */ + previousTag?: string; + /** + * When this version already has a candidate or beta: the first of them, and CHANGELOG.md on the + * commit it was cut from. A candidate writes its notes under `## Unreleased` on its release + * branch, so the next candidate or the final reads what was there before the release line began + * from here, not from its own branch, and collects every note again without counting one twice. + */ + startedFrom?: { tag: string; changelog?: string }; + /** Pull requests with a note, oldest merge first. */ + notes: { pull: ApiPull; groups: Group[] }[]; + /** Pull requests whose note says none. */ + none: ApiPull[]; + /** Pull requests whose note is missing or can't be read, and why. */ + problems: { pull: ApiPull; problems: string[] }[]; + /** The release system's own pull requests. */ + skipped: ApiPull[]; + /** + * Pull requests merged before notes moved into descriptions, with no note there: theirs were + * written under `## Unreleased` in CHANGELOG.md, which the release reads as well. + */ + before: ApiPull[]; + /** Commits no merged pull request accounts for, such as a direct push. */ + withoutPull: string[]; +}; + +/** + * The module that reads notes from descriptions. A pull request merged onto a tree without it was + * merged before notes moved there, and its note, if it needed one, is under `## Unreleased`. + */ +export const NOTES_MODULE = "scripts/release-notes.ts"; + +const STABLE_TAG = /^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/; + +const compare = (a: number[], b: number[]) => { + for (let index = 0; index < 3; index++) { + if (a[index] !== b[index]) return a[index] - b[index]; + } + return 0; +}; + +/** The highest stable `vX.Y.Z` tag below `version`, by number. */ +export function previousStableTag( + tags: string[], + version: string, +): string | undefined { + const target = parseVersion(version); + const core = [target.major, target.minor, target.patch]; + let best: { tag: string; parts: number[] } | undefined; + for (const tag of tags) { + const match = STABLE_TAG.exec(tag); + if (!match) continue; + const parts = [Number(match[1]), Number(match[2]), Number(match[3])]; + if (compare(parts, core) >= 0) continue; + if (!best || compare(parts, best.parts) > 0) best = { tag, parts }; + } + return best?.tag; +} + +/** The first candidate or beta of `version` (X.Y.Z), betas before candidates, or undefined. */ +export function firstPrerelease( + tags: string[], + version: string, +): string | undefined { + const target = parseVersion(version); + const core = `${target.major}.${target.minor}.${target.patch}`; + const pattern = new RegExp( + `^v${core.replaceAll(".", "\\.")}-(beta|rc)\\.([1-9]\\d*)$`, + ); + const found = tags + .map((tag) => ({ tag, match: pattern.exec(tag) })) + .filter( + (entry): entry is { tag: string; match: RegExpExecArray } => + entry.match !== null, + ) + .sort( + (a, b) => + (a.match[1] === b.match[1] ? 0 : a.match[1] === "beta" ? -1 : 1) || + Number(a.match[2]) - Number(b.match[2]), + ); + return found[0]?.tag; +} + +/** The release workflows' own branches: a release PR, a merge back, main's images again. */ +const RELEASE_SYSTEM_BRANCH = + /^(release\/publish\/v\d+\.\d+\.\d+(-(rc|beta)\.[1-9]\d*)?|merge-back\/v\d+\.\d+\.\d+|main-images\/v\d+\.\d+\.\d+(-(rc|beta)\.[1-9]\d*)?)$/; + +/** Whether the release system opened this pull request, by its author and its branch. */ +export function isReleaseSystemPull( + pull: ApiPull, + repository: string, +): boolean { + return ( + pull.user?.login === "github-actions[bot]" && + (pull.head.repo?.full_name ?? "").toLowerCase() === + repository.toLowerCase() && + RELEASE_SYSTEM_BRANCH.test(pull.head.ref) + ); +} + +/** The notes of every pull request the release of `version` at `head` ships. */ +export function collectNotes( + version: string, + head: string, + repository: string, + deps: CollectDeps, +): Collected { + const tags = deps.tags(); + const previousTag = previousStableTag(tags, version); + const base = previousTag ? deps.mergeBase(previousTag, head) : undefined; + const first = firstPrerelease(tags, version); + const pulls = new Map(); + const withoutPull: string[] = []; + for (const sha of deps.commits(base, head)) { + const merged = deps + .pullsOf(sha) + .filter( + (pull) => pull.merged_at !== null && pull.merge_commit_sha === sha, + ); + if (merged.length === 0) withoutPull.push(sha); + for (const pull of merged) pulls.set(pull.number, pull); + } + const ordered = [...pulls.values()].sort( + (a, b) => + (a.merged_at ?? "").localeCompare(b.merged_at ?? "") || + a.number - b.number, + ); + const collected: Collected = { + previousTag, + startedFrom: first + ? { tag: first, changelog: deps.show(`${first}^`, "CHANGELOG.md") } + : undefined, + notes: [], + none: [], + problems: [], + skipped: [], + before: [], + withoutPull, + }; + for (const pull of ordered) { + if (isReleaseSystemPull(pull, repository)) { + collected.skipped.push(pull); + continue; + } + const note = parseNote(pull.body); + if (note.kind === "notes") { + collected.notes.push({ pull, groups: note.groups }); + } else if ( + pull.merge_commit_sha && + deps.show(`${pull.merge_commit_sha}^`, NOTES_MODULE) === undefined + ) { + // Merged onto a tree that did not read notes from descriptions yet. + collected.before.push(pull); + } else if (note.kind === "none") { + collected.none.push(pull); + } else if (note.kind === "missing") { + collected.problems.push({ + pull, + problems: ["Its description has no note under ## Changelog."], + }); + } else { + collected.problems.push({ pull, problems: note.problems }); + } + } + return collected; +} + +function exec(cmd: string[], cwd: string): string { + const result = Bun.spawnSync(cmd, { cwd, stdout: "pipe", stderr: "pipe" }); + if (result.exitCode !== 0) { + throw new Error(`${cmd.join(" ")}: ${result.stderr.toString().trim()}`); + } + return result.stdout.toString(); +} + +/** Git in `root`, and the GitHub API through `gh` (GH_TOKEN). */ +export function liveCollectDeps(root: string, repository: string): CollectDeps { + return { + tags: () => + exec(["git", "tag", "--list"], root).split("\n").filter(Boolean), + mergeBase: (a, b) => exec(["git", "merge-base", a, b], root).trim(), + commits: (base, head) => + exec(["git", "rev-list", base ? `${base}..${head}` : head], root) + .split("\n") + .filter(Boolean), + show: (ref, path) => { + const result = Bun.spawnSync(["git", "show", `${ref}:${path}`], { + cwd: root, + stdout: "pipe", + stderr: "pipe", + }); + return result.exitCode === 0 ? result.stdout.toString() : undefined; + }, + // A commit is the merge commit of one pull request at most, and sits on a handful more. + pullsOf: (sha) => + JSON.parse( + exec( + [ + "gh", + "api", + `repos/${repository}/commits/${sha}/pulls?per_page=100`, + ], + root, + ), + ) as ApiPull[], + }; +} diff --git a/scripts/release-note-check.fixtures/pr-2654-changelog.md b/scripts/release-note-check.fixtures/pr-2654-changelog.md new file mode 100644 index 0000000000..798ab17942 --- /dev/null +++ b/scripts/release-note-check.fixtures/pr-2654-changelog.md @@ -0,0 +1,17 @@ +**Before upgrading.** + +- **Deprecated.** Each still works, answers with `Deprecation` and `Sunset` headers, and is + removed no earlier than its sunset, and only once nothing uses it. + - `GET /api/v2/organizations/{organizationId}/bots/{botId}/apps/{appId} query actions`: Sunset 2027-12-01. + Send the actions in the body of `POST /api/v2/organizations/{organizationId}/bots/{botId}/apps/{appId}/read` + (`readBotApp`) instead: fifty actions of 300 characters make an address longer than proxies carry. + - `GET /api/v2/organizations/{organizationId}/people/{personId}/recording-titles`: Sunset 2027-12-01. + Send the ids in the body of `POST /api/v2/organizations/{organizationId}/people/{personId}/recording-titles/read` + (`readRecordingTitles`) instead. + +**Smaller addresses.** + +- **Lists travel in a body, not the address.** Reading an app for the actions a Bot needs, and the + titles of the recordings a learned skill came from, now send their lists in a request body, so a + long list never meets a proxy's limit on an address. The web app uses the new operations, and + falls back to the old ones on a server from before them. diff --git a/scripts/release-note-check.fixtures/pr-2654.md b/scripts/release-note-check.fixtures/pr-2654.md new file mode 100644 index 0000000000..8b3e7ba336 --- /dev/null +++ b/scripts/release-note-check.fixtures/pr-2654.md @@ -0,0 +1,24 @@ +Two operations put id lists in a query string: + +- `getBotApp?actions=` allows 50 actions of up to 300 characters each, about 15 KB once encoded. That is past the 8 KB request line common proxies carry. +- `getRecordingTitles?ids=` takes up to 50 recording ids. + +This adds body forms of both, additively: + +- `readBotApp`: `POST /api/v2/organizations/{organizationId}/bots/{botId}/apps/{appId}/read` with `{ actions }`. Same limits, same answer as `getBotApp`. +- `readRecordingTitles`: `POST /api/v2/organizations/{organizationId}/people/{personId}/recording-titles/read` with `{ ids }`. Same limits, same answer as `getRecordingTitles`. + +Both take the required Idempotency-Key, as every POST does, and keep no answer, so a repeat reads again. + +The query forms keep working for released apps. They are deprecated (`x-deprecation-date` 2026-12-01, `x-sunset` 2027-12-01) and listed in the changelog. `getBotApp` without `actions` is unchanged and not deprecated. + +New spec test `api/openapi-address-length.test.ts`: + +- It holds every operation's query under 8 KB, counting each character as its percent-encoded length, unless the operation is deprecated for a body or allowed with a reason. +- On main it fails, because `getBotApp`'s query is over and not deprecated. +- The audit trail's filter queries and `listComponents`' unbounded `kind` are allowed, each with its reason. +- `getRecordingTitles` is not over the limit (50 uuids is about 2 KB), but it moves to a body too, so no list of ids rides in an address. + +This is the first of three changes: spec and client here, then the server, then the web app on the new operations, which falls back to the old ones on a server from before them. + +Checks run: `bun run api:generate` (no drift), `bun run api:lint`, oasdiff breaking against main (none), `shared/tests/api-deprecations.test.ts`, `bun test api`. diff --git a/scripts/release-note-check.test.ts b/scripts/release-note-check.test.ts new file mode 100644 index 0000000000..db28f25670 --- /dev/null +++ b/scripts/release-note-check.test.ts @@ -0,0 +1,264 @@ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + addedDeprecations, + type PullRequestFacts, + releaseNoteProblems, + releaseSystemPullRequest, +} from "./release-note-check"; +import { + combineNotes, + parseGroups, + parseNote, + renderGroups, +} from "./release-notes"; + +const ROOT = join(import.meta.dir, ".."); +const fixture = (name: string) => + readFileSync( + join(import.meta.dir, "release-note-check.fixtures", name), + "utf8", + ); + +/** #2654's real description, which carried no note: its lines went into CHANGELOG.md. */ +const BODY_2654 = fixture("pr-2654.md"); +/** The lines #2654 added to CHANGELOG.md, which its description carries now instead. */ +const NOTE_2654 = fixture("pr-2654-changelog.md"); +const WITH_NOTE = `${BODY_2654}\n## Changelog\n\n${NOTE_2654}`; + +/** #2654 as GitHub describes it: a person's branch, the spec, the clients and CHANGELOG.md. */ +const PR_2654: PullRequestFacts = { + author: "davidmckayv", + authorType: "User", + headRef: "waste/urls", + headRepository: "CopilotKit/OpenBot", + repository: "CopilotKit/OpenBot", + body: BODY_2654, + files: [ + "CHANGELOG.md", + "api/openapi.yaml", + "api/openapi/bot-grants.yaml", + "app/src/lib/api/generated/bot-grants/bot-grants.ts", + ], +}; + +/** Release v1.2.7's own pull request (#2648), as Create release PR opened it. */ +const RELEASE_2648: PullRequestFacts = { + author: "github-actions[bot]", + authorType: "Bot", + headRef: "release/publish/v1.2.7", + headRepository: "CopilotKit/OpenBot", + repository: "CopilotKit/OpenBot", + body: "## Release v1.2.7\n\nMerging this publishes the image, tags the commit and creates the GitHub Release.", + files: [ + "CHANGELOG.md", + "backend-images.env", + "desktop/src-tauri/Cargo.lock", + "desktop/src-tauri/Cargo.toml", + "package.json", + ], +}; + +const SPEC = () => + Bun.YAML.parse(readFileSync(join(ROOT, "api/openapi.yaml"), "utf8")); + +/** The real spec as it was before #2654: its two deprecations (2026-12-01) not yet marked. */ +function before2654(): unknown { + const spec = SPEC(); + const walk = (node: unknown) => { + if (Array.isArray(node)) { + for (const item of node) walk(item); + return; + } + if (typeof node !== "object" || node === null) return; + const record = node as Record; + if ( + record["x-deprecation-date"] === "2026-12-01" && + record["x-sunset"] === "2027-12-01" + ) { + delete record.deprecated; + delete record["x-deprecation-date"]; + delete record["x-sunset"]; + } + for (const value of Object.values(record)) walk(value); + }; + walk(spec); + return spec; +} + +describe("a release note", () => { + test("is read from under ## Changelog, comments and Windows line ends taken out", () => { + const body = `## What this changes\r\n\r\nA fix.\r\n\r\n## Changelog\r\n\r\n\r\n${NOTE_2654.replace(/\n/g, "\r\n")}\r\n## Proof\r\n\r\nRan it.`; + const note = parseNote(body); + expect(note.kind).toBe("notes"); + if (note.kind !== "notes") return; + expect(renderGroups(note.groups)).toBe(NOTE_2654.trim()); + }); + + test("none, for a change nobody running OpenBot would notice", () => { + for (const text of ["none", "None.", "none: CI only", "NONE"]) { + expect(parseNote(`## Changelog\n\n${text}\n`).kind).toBe("none"); + } + }); + + test("missing: no heading, or nothing but the template's comment under it", () => { + expect(parseNote(BODY_2654).kind).toBe("missing"); + expect(parseNote(null).kind).toBe("missing"); + expect( + parseNote( + "## Changelog\n\n\n\n## Proof\n\nx", + ).kind, + ).toBe("missing"); + }); + + test("the old template's checkbox is not a note: it names what to do", () => { + const note = parseNote( + "## Changelog\n\n- [ ] A line in `CHANGELOG.md` under `Unreleased`, or a sentence on why a deployment behaves no\n differently afterwards.\n", + ); + expect(note.kind).toBe("invalid"); + if (note.kind !== "invalid") return; + expect(note.problems[0]).toContain("comes before any heading"); + }); + + test("a heading with nothing under it is refused", () => { + const note = parseNote( + "## Changelog\n\n**API.**\n\n**Signing in.**\n\n- A line.", + ); + expect(note).toEqual({ + kind: "invalid", + problems: ["**API.** has nothing under it."], + }); + }); + + test("CHANGELOG.md's own released sections read back exactly as they are written", () => { + const changelog = readFileSync(join(ROOT, "CHANGELOG.md"), "utf8"); + for (const version of ["1.2.7", "1.2.6", "1.2.5"]) { + const section = changelog + .split(`\n## ${version}\n`)[1] + .split(/\n## /)[0] + .trim(); + const { groups, problems } = parseGroups(section); + expect(problems).toEqual([]); + expect(renderGroups(groups)).toBe(section); + } + }); + + test("notes merge by heading, Before upgrading first, the rest in the order they came", () => { + const desktop = parseGroups( + "**OpenBot Desktop.**\n\n- Desktop's sign-in address stays short.\n\n**API.**\n\n- Added: the scope `openbot`.", + ).groups; + const urls = parseGroups(NOTE_2654).groups; + const more = parseGroups( + "**API.**\n\n- Changed: tokens of OpenBot's own apps.", + ).groups; + expect(renderGroups(combineNotes([desktop, urls, more]))).toBe( + [ + NOTE_2654.split("\n\n**Smaller addresses.**")[0], + "**OpenBot Desktop.**\n\n- Desktop's sign-in address stays short.", + "**API.**\n\n- Added: the scope `openbot`.\n- Changed: tokens of OpenBot's own apps.", + `**Smaller addresses.**${NOTE_2654.split("**Smaller addresses.**")[1].trimEnd()}`, + ].join("\n\n"), + ); + }); +}); + +describe("the release note check", () => { + test("refuses a person's pull request that changes CHANGELOG.md, even with a note", () => { + const problems = releaseNoteProblems({ ...PR_2654, body: WITH_NOTE }); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("CHANGELOG.md is written by the release"); + }); + + test("passes the same pull request once CHANGELOG.md is out of it and the note is in the description", () => { + const pr = { + ...PR_2654, + body: WITH_NOTE, + files: PR_2654.files.filter((file) => file !== "CHANGELOG.md"), + }; + expect( + releaseNoteProblems(pr, addedDeprecations(before2654(), SPEC())), + ).toEqual([]); + }); + + test("refuses a description with no note, and says how to write one", () => { + const problems = releaseNoteProblems({ + ...PR_2654, + files: ["app/src/lib/marks.ts"], + }); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("no release note"); + expect(problems[0]).toContain("none"); + }); + + test("passes none", () => { + expect( + releaseNoteProblems({ + ...PR_2654, + body: `${BODY_2654}\n## Changelog\n\nnone\n`, + files: ["scripts/ci-changes.ts"], + }), + ).toEqual([]); + }); + + test("lets the release's own pull request write CHANGELOG.md, with no note of its own", () => { + expect(releaseSystemPullRequest(RELEASE_2648)).toBe(true); + expect(releaseNoteProblems(RELEASE_2648)).toEqual([]); + for (const headRef of [ + "release/publish/v1.2.8-rc.1", + "merge-back/v1.2.0", + "main-images/v1.2.7", + ]) { + expect(releaseNoteProblems({ ...RELEASE_2648, headRef })).toEqual([]); + } + }); + + test("a person can't pass as the release: not by its branch, its title or a fork", () => { + for (const pr of [ + // A person's pull request from a branch named like the release's. + { ...PR_2654, headRef: "release/publish/v1.2.8" }, + // The release's author from a branch the release never opens. + { ...RELEASE_2648, headRef: "fix/changelog" }, + // A fork's branch, whoever it says opened it. + { ...RELEASE_2648, headRepository: "someone/OpenBot" }, + // A user account named like the bot, which GitHub does not allow, but not a Bot either way. + { ...RELEASE_2648, authorType: "User" }, + ]) { + expect(releaseSystemPullRequest(pr)).toBe(false); + expect(releaseNoteProblems(pr).join("\n")).toContain( + "CHANGELOG.md is written by the release", + ); + } + }); + + test("a new deprecation must be named in the note, with its sunset", () => { + const added = addedDeprecations(before2654(), SPEC()); + expect(added.map((element) => element.key).sort()).toEqual([ + "GET /api/v2/organizations/{organizationId}/bots/{botId}/apps/{appId} query actions", + "GET /api/v2/organizations/{organizationId}/people/{personId}/recording-titles", + ]); + const files = ["api/openapi.yaml"]; + // `none` for a change that deprecates something is not a note. + expect( + releaseNoteProblems( + { ...PR_2654, files, body: "## Changelog\n\nnone" }, + added, + ), + ).toHaveLength(2); + // The note without the recording titles' line misses exactly that one. + const without = WITH_NOTE.split("\n") + .filter((line) => !line.includes("recording-titles`: Sunset")) + .join("\n"); + const problems = releaseNoteProblems( + { ...PR_2654, files, body: without }, + added, + ); + expect(problems).toHaveLength(1); + expect(problems[0]).toContain("recording-titles"); + expect(problems[0]).toContain("2027-12-01"); + }); + + test("the spec's deprecations already released are not this pull request's to note", () => { + expect(addedDeprecations(SPEC(), SPEC())).toEqual([]); + }); +}); diff --git a/scripts/release-note-check.ts b/scripts/release-note-check.ts new file mode 100644 index 0000000000..cf7b125143 --- /dev/null +++ b/scripts/release-note-check.ts @@ -0,0 +1,206 @@ +/** + * The `release note` check of a pull request (ci.yml), part of `verify`. + * + * CHANGELOG.md belongs to the release. A pull request carries its note in its description, under + * `## Changelog` (scripts/release-notes.ts), and preparing a release writes the notes of every pull + * request it ships into CHANGELOG.md. So this check fails a pull request that: + * + * - changes CHANGELOG.md, unless it is one of the release's own pull requests, opened by the release + * workflows with the workflow token from one of their branches (releaseSystemPullRequest): who + * opened it and from where, never anything a person types; + * - has no note: nothing under `## Changelog`, or lines that are not under a bold heading. `none` + * is a note, for a change nobody running OpenBot would notice; + * - deprecates part of the API without saying so in its note: each element api/openapi.yaml newly + * marks deprecated is named in backticks with its sunset, as CHANGELOG.md's Deprecated list + * names it, so the release that ships it announces it (shared/api-deprecations.ts). + * + * The description is read when the check runs, not from the event, so re-running it after editing + * the description reads the new one; .github/workflows/release-note-edited.yml re-runs it on an edit. + * + * Usage, in Actions: `bun scripts/release-note-check.ts`. Env: GITHUB_EVENT_PATH, GITHUB_REPOSITORY + * and GH_TOKEN. + */ + +import { appendFileSync, readFileSync } from "node:fs"; +import { + type DeprecatedElement, + type DeprecationTable, + deprecationsIn, + missingFromChangelog, +} from "../shared/api-deprecations"; +import { NOTE_HEADING, noteSection, parseNote } from "./release-notes"; + +/** The account the release workflows open their pull requests as (GITHUB_TOKEN). */ +export const RELEASE_AUTHOR = "github-actions[bot]"; + +/** The branches the release workflows open their pull requests from. */ +const RELEASE_BRANCHES = [ + // Create release PR (release.yml). + /^release\/publish\/v\d+\.\d+\.\d+(-(rc|beta)\.[1-9]\d*)?$/, + // A final's way back to main, and main's images after a stable release (publish-release.yml). + /^merge-back\/v\d+\.\d+\.\d+$/, + /^main-images\/v\d+\.\d+\.\d+$/, +]; + +export type PullRequestFacts = { + author: string; + authorType: string; + headRef: string; + headRepository: string; + repository: string; + body: string | null; + files: string[]; +}; + +/** One of the release's own pull requests: opened by its workflows, from one of their branches. */ +export function releaseSystemPullRequest(pr: PullRequestFacts): boolean { + return ( + pr.author === RELEASE_AUTHOR && + pr.authorType === "Bot" && + pr.headRepository.toLowerCase() === pr.repository.toLowerCase() && + RELEASE_BRANCHES.some((branch) => branch.test(pr.headRef)) + ); +} + +/** The elements `head` marks deprecated that `base` did not, each with its sunset. */ +export function addedDeprecations( + base: unknown, + head: unknown, +): DeprecatedElement[] { + const known = new Set( + deprecationsIn(base).operations.flatMap((operation) => + operation.elements.map((element) => `${element.key} ${element.sunset}`), + ), + ); + return deprecationsIn(head).operations.flatMap((operation) => + operation.elements.filter( + (element) => !known.has(`${element.key} ${element.sunset}`), + ), + ); +} + +/** Why the pull request fails the check; empty when it passes. */ +export function releaseNoteProblems( + pr: PullRequestFacts, + deprecated: DeprecatedElement[] = [], +): string[] { + if (releaseSystemPullRequest(pr)) return []; + const problems: string[] = []; + if (pr.files.includes("CHANGELOG.md")) { + problems.push( + `CHANGELOG.md is written by the release, from the notes in pull requests' descriptions. Take CHANGELOG.md out of this pull request and put its lines in the description, under ${NOTE_HEADING}.`, + ); + } + const note = parseNote(pr.body); + if (note.kind === "missing") { + problems.push( + `The description has no release note. Under a ${NOTE_HEADING} heading, write what a deployment does differently, grouped under a bold heading such as **API.**, or write none when nobody running OpenBot would notice.`, + ); + } else if (note.kind === "invalid") { + problems.push( + ...note.problems.map((problem) => `The release note: ${problem}`), + ); + } + if (deprecated.length > 0) { + const text = note.kind === "notes" ? (noteSection(pr.body) ?? "") : ""; + const table: DeprecationTable = { + operations: [ + { method: "", path: "", overlaps: [], elements: deprecated }, + ], + }; + for (const element of missingFromChangelog(table, text)) { + problems.push( + `api/openapi.yaml deprecates ${element.key}. Name it in the release note, in backticks with its sunset, under **Before upgrading.**: - \`${element.key}\`: what to use instead. Sunset ${element.sunset}.`, + ); + } + } + return problems; +} + +// --------------------------------------------------------------------------------------------- +// Running it in Actions. + +function gh(args: string[]): string { + const result = Bun.spawnSync(["gh", ...args], { + stdout: "pipe", + stderr: "pipe", + }); + if (result.exitCode !== 0) { + throw new Error(`gh ${args.join(" ")}: ${result.stderr.toString().trim()}`); + } + return result.stdout.toString(); +} + +function specAt(repository: string, sha: string): unknown { + const text = gh([ + "api", + "-H", + "Accept: application/vnd.github.raw", + `repos/${repository}/contents/api/openapi.yaml?ref=${sha}`, + ]); + return Bun.YAML.parse(text); +} + +if (import.meta.main) { + const repository = process.env.GITHUB_REPOSITORY ?? ""; + const event = JSON.parse( + readFileSync(process.env.GITHUB_EVENT_PATH ?? "", "utf8"), + ) as { pull_request?: { number: number } }; + const number = event.pull_request?.number; + if (!number) { + console.log("Not a pull request: nothing to check."); + process.exit(0); + } + // Read now, not from the event, so a re-run after an edit reads the edited description. + const pull = JSON.parse( + gh(["api", `repos/${repository}/pulls/${number}`]), + ) as { + body: string | null; + user: { login: string; type: string }; + head: { ref: string; sha: string; repo?: { full_name?: string } | null }; + base: { sha: string }; + }; + const files = gh([ + "api", + "--paginate", + `repos/${repository}/pulls/${number}/files?per_page=100`, + "--jq", + ".[].filename", + ]) + .split("\n") + .filter(Boolean); + const pr: PullRequestFacts = { + author: pull.user.login, + authorType: pull.user.type, + headRef: pull.head.ref, + headRepository: pull.head.repo?.full_name ?? "", + repository, + body: pull.body, + files, + }; + const deprecated = + files.includes("api/openapi.yaml") && !releaseSystemPullRequest(pr) + ? addedDeprecations( + specAt(repository, pull.base.sha), + specAt(repository, pull.head.sha), + ) + : []; + const problems = releaseNoteProblems(pr, deprecated); + const summary = process.env.GITHUB_STEP_SUMMARY; + if (problems.length === 0) { + const line = releaseSystemPullRequest(pr) + ? "The release's own pull request: it writes CHANGELOG.md, and carries no note of its own." + : `The release note under ${NOTE_HEADING} is there, and CHANGELOG.md is left to the release.`; + console.log(line); + if (summary) appendFileSync(summary, `### Release note\n\n${line}\n`); + process.exit(0); + } + for (const problem of problems) console.log(`::error::${problem}`); + if (summary) { + appendFileSync( + summary, + `### Release note\n\n${problems.map((problem) => `- ${problem}`).join("\n")}\n\nEdit the description and this check runs again.\n`, + ); + } + process.exit(1); +} diff --git a/scripts/release-notes.fixture-1.2.6.json b/scripts/release-notes.fixture-1.2.6.json new file mode 100644 index 0000000000..36d0ef3c1d --- /dev/null +++ b/scripts/release-notes.fixture-1.2.6.json @@ -0,0 +1,131 @@ +{ + "about": "The pull requests of the real 1.2.6 release (v1.2.5..v1.2.6), as GET /repos/{repo}/commits/{sha}/pulls returns them, with each description given the ## Changelog note it would have carried: the lines it added to CHANGELOG.md, as 1.2.6 shipped them.", + "version": "1.2.6", + "head": "20a61fc5ae4f42975544ee75f017fa2024118e67", + "previousTag": "v1.2.5", + "commits": [ + "20a61fc5ae4f42975544ee75f017fa2024118e67", + "2f2d28f84d1389c1832c4f3b4622fe2bccd1ea65", + "d6556a69b63c6feb98ed54c5cd7481fd6a9972dc", + "1e9ba86fb6a3db262ae51291fac00294a5dc8444", + "35b9fe5cb2cf72e1fcfad503f280d1af4e70a445", + "64b7b487f98f04be8cdcad91a8f94a8a3ba40e1d" + ], + "pulls": { + "20a61fc5ae4f42975544ee75f017fa2024118e67": [ + { + "number": 2640, + "title": "Release v1.2.6", + "html_url": "https://github.com/CopilotKit/OpenBot/pull/2640", + "body": "## Release v1.2.6\n\nMerging this publishes the image, tags the commit and creates the GitHub Release.\n\nBefore merging:\n- [ ] The notes below describe what a deployment does differently\n- [ ] The OpenBot server images are published at v1.2.6, the tag\n backend-images.env now names\n- [ ] The smoke journey passed against a licensed deployment, and the result is\n pasted in a comment: `bash scripts/start.sh && bun run test:smoke`,\n with OPENBOT_SMOKE_COOKIE set to a signed-in session (docs/releasing.md)\n\nMerging checks this commit before it builds: the full suite, or, when this PR\nchanges only the release files, main's passing CI on the commit it merges onto.\nThere is nothing to check about CI here. The journey is the part CI cannot do: it\nneeds a licence, and a licence belongs to the machine it was issued for.\n\n```\n\n**Before upgrading.**\n\n- **No migrations.** The database stays at `0206_artifacts_collab`, where 1.2.5 left it, so 1.2.5\n upgrades to 1.2.6 with its servers rolling one by one, with no downtime. Upgrading from 1.2.4 or\n older runs 1.2.5's migrations as well: read 1.2.5's Before upgrading first.\n- **No downtime, and nothing new is required.** No setting is added or changed.\n\n**Artifacts.**\n\n- **Artifacts open in apps signed in before 1.2.5.** 1.2.5 gave artifacts permissions of their own,\n and an app's sign-in keeps the permissions it was first given through every refresh. So OpenBot\n Desktop, the phone app and the CLI, signed in before 1.2.5, were refused every artifact, and the\n card in the conversation and the Artifacts page said each new one \"was deleted, or it isn't shared\n with you any more\". The server now lets such a sign-in open artifacts as it could open the Bots, a\n read for a read and a change for a change, as it does for the other things that got permissions\n of their own later, so they open with no new sign-in and no app update. A browser was never\n affected.\n- **A refused sign-in no longer looks like a deleted artifact.** Only \"not found\" means an artifact\n is gone or isn't the person's now. When a sign-in may not see artifacts, the card, the viewer and\n the Artifacts page say \"This sign-in can't see your artifacts. Sign in again.\" instead.\n\n**Your account.**\n\n- **Deleting your account on OpenBot Cloud finishes.** Since 1.2.4 deleted an account at once, a\n deletion could stop part-way and answer that it couldn't finish (503) when the person's own\n organization was the one made for them when they signed up for OpenBot Cloud, which OpenBot may\n not close. Each try, and each pass of the server's backstop, stopped at the same step. That\n organization now stays with its owner, OpenBot's side of it is deleted with the account, and the\n deletion finishes. A deletion already stopped this way finishes on the person's next try, or on\n the backstop's next pass without them. A failure that may pass, such as the sign-in service out of\n reach, still stops the deletion to be finished later.\n- **Deleting your account while you're the only admin of a shared organization tells you first,\n and deletes nothing.** On OpenBot Cloud an organization with other members can't lose its only\n admin, and that was found out only at the last step, after most of the account was already\n deleted, with a 503 on every try. When the person is the only admin of an organization that has\n other members, including members who have never opened OpenBot, Settings now lists it before\n they press anything (\"You're its only admin: make someone else an admin.\"), and asking anyway is\n refused at once (\"You're the only admin of . Make someone else an admin, then try\n again.\") with nothing deleted. Once someone else is an admin there, the deletion goes ahead and\n they keep the organization.\n\n**Conversations.**\n\n- **A long conversation opens at its newest message.** Opened again, it could show its history\n partway up, with the scroll-to-end button showing, when its newest turn arrived a moment after\n the rest: a read of its history a moment behind, or a turn asked from another device while it was\n closed. That turn was taken for one just sent and lifted to the top of the view, its answer below\n the fold. Only a message sent in the open conversation is lifted now, so a turn sent from another\n device while the conversation is open here is followed to the end instead.\n- **A Bot's wait for a person stops when it can never be carried on.** When a Bot handed its\n browser to a person and the conversation was then deleted, or the person left it, every server\n asked about that wait on every pass, for ever, and logged `person-wait-not-carried-on` each time\n (about 36 times a minute on OpenBot Cloud for three such waits). Such a wait is now given up,\n with the reason kept, and cleared after a week. A wait that may still be carried on, such as one\n whose conversation another server is busy with, waits 30 seconds before it is tried again,\n doubling to 15 minutes, and is given up after about a day. The person sees the same as before:\n once the conversation is free, the turn is carried on with the call answered as it would have\n been.\n\n```\n", + "user": { + "login": "github-actions[bot]" + }, + "head": { + "ref": "release/publish/v1.2.6", + "repo": { + "full_name": "CopilotKit/OpenBot" + } + }, + "merged_at": "2026-12-01T20:06:44Z", + "merge_commit_sha": "20a61fc5ae4f42975544ee75f017fa2024118e67" + } + ], + "2f2d28f84d1389c1832c4f3b4622fe2bccd1ea65": [ + { + "number": 2638, + "title": "Changelog for 1.2.6: artifacts open in apps signed in before 1.2.5", + "html_url": "https://github.com/CopilotKit/OpenBot/pull/2638", + "body": "Adds Eli's artifacts fix to the 1.2.6 notes (`## Unreleased`), under a new Artifacts section:\n\n- **Artifacts open in apps signed in before 1.2.5** (the server's #974). An app's sign-in keeps the permissions it was first given. So OpenBot Desktop, the phone app and the CLI, signed in before 1.2.5, were refused every artifact, and the card and the Artifacts page called each one deleted. Such a sign-in now opens artifacts as it could open the Bots, a read for a read and a change for a change, with no new sign-in and no app update.\n- **A refused sign-in no longer looks like a deleted artifact** (#2637). Only a 404 means gone. A sign-in refusal says \"This sign-in can't see your artifacts. Sign in again.\" on the card, in the viewer and on the Artifacts page, the app's own sentence (`app/src/lib/artifacts/refusal.ts`).\n\nChangelog only. Checked locally: the 13 release-file test files (222 pass), biome, no dashes, and the support window holds.\n\n## Changelog\n\n**Artifacts.**\n\n- **Artifacts open in apps signed in before 1.2.5.** 1.2.5 gave artifacts permissions of their own,\n and an app's sign-in keeps the permissions it was first given through every refresh. So OpenBot\n Desktop, the phone app and the CLI, signed in before 1.2.5, were refused every artifact, and the\n card in the conversation and the Artifacts page said each new one \"was deleted, or it isn't shared\n with you any more\". The server now lets such a sign-in open artifacts as it could open the Bots, a\n read for a read and a change for a change, as it does for the other things that got permissions\n of their own later, so they open with no new sign-in and no app update. A browser was never\n affected.\n- **A refused sign-in no longer looks like a deleted artifact.** Only \"not found\" means an artifact\n is gone or isn't the person's now. When a sign-in may not see artifacts, the card, the viewer and\n the Artifacts page say \"This sign-in can't see your artifacts. Sign in again.\" instead.\n", + "user": { + "login": "davidmckayv" + }, + "head": { + "ref": "changelog-1.2.6-artifacts", + "repo": { + "full_name": "CopilotKit/OpenBot" + } + }, + "merged_at": "2026-12-01T18:52:59Z", + "merge_commit_sha": "2f2d28f84d1389c1832c4f3b4622fe2bccd1ea65" + } + ], + "d6556a69b63c6feb98ed54c5cd7481fd6a9972dc": [ + { + "number": 2637, + "title": "Say an artifact the sign-in can't see as that, not as deleted", + "html_url": "https://github.com/CopilotKit/OpenBot/pull/2637", + "body": "## What broke\n\nOn OpenBot Desktop, every artifact a Bot made showed \"“Sales dashboard (mock data)” was deleted, or it isn't shared with you any more.\" in the conversation, and the Artifacts page failed to load (Eli, #openbot-dogfooding, 1 Dec).\n\n## Why\n\nDesktop, the phone app and the CLI sign in with a token that keeps the permissions it was first given, through every refresh. A sign-in from before 1.2.5 has no artifact permissions, so the server refuses it 403 on every artifact read (\"This sign-in can't see your artifacts. Sign in again and allow it.\"). The card and the viewer took any 403 to mean the artifact was deleted or unshared. The server answers 404 for an artifact a person can't open, so a 403 on a read is never about the artifact.\n\nThe backend fix that lets those older sign-ins read artifacts is in openbot-backend. This PR is the app half: the app now says what actually happened.\n\n## The fix\n\n- `lib/artifacts/refusal.ts`: only a 404 means gone. A 403 that refuses the sign-in reads \"This sign-in can't see your artifacts. Sign in again.\" Any other 403 shows the server's own sentence.\n- The card in the conversation shows that sentence in the same dashed note. The design is unchanged; only the words differ.\n- The Artifacts page's existing error line and the viewer say the same.\n\n## Tests\n\n- `app/tests/artifact-sign-in-refusal-browser.test.tsx` loads the app's card and Artifacts page in a real browser, Chromium and WebKit, light and dark. The server is stood in for at the network with the exact problem bodies the backend sends: 403 PERMISSION_DENIED with the guard's sentence, and 404 ARTIFACT_NOT_FOUND. The refused card and the page must show the sign-in sentence and never \"was deleted\". A not-found card still says it was deleted, in the identical note. It is added to the WebKit job's list, which runs both engines.\n- `app/tests/artifact-viewer-failure.test.ts`: the viewer's sentence for the sign-in refusal.\n- Red on main (5 fail: chromium light/dark, webkit light/dark, viewer), green with the fix (7 pass).\n\n## Changelog\n\nnone\n", + "user": { + "login": "davidmckayv" + }, + "head": { + "ref": "fix/artifact-sign-in-refusal", + "repo": { + "full_name": "CopilotKit/OpenBot" + } + }, + "merged_at": "2026-12-01T18:50:48Z", + "merge_commit_sha": "d6556a69b63c6feb98ed54c5cd7481fd6a9972dc" + } + ], + "1e9ba86fb6a3db262ae51291fac00294a5dc8444": [ + { + "number": 2631, + "title": "Changelog and upgrade policy for 1.2.6", + "html_url": "https://github.com/CopilotKit/OpenBot/pull/2631", + "body": "The release notes and upgrade policy for 1.2.6, written before the cut so the release PR only moves its version.\n\n**Changelog.** `## Unreleased` is written from the code since 1.2.5 (0590f626):\n- Your account: deleting an account on OpenBot Cloud finishes when the person's own organization is the one made at sign-up (the server's #968).\n- Conversations: a Bot's wait for a person is given up when it can never be carried on, and backs off otherwise (#962).\n- Conversations: a long conversation opens at its newest message (#2625). #2625 had put its entry under `## 1.2.5`, which doesn't contain it (it merged after the v1.2.5 release commit), so the entry moves to Unreleased.\n\n**release-policy.json.**\n- `version`: v1.2.6\n- `database.to`: stays `0206_artifacts_collab`. There are no migrations since 1.2.5.\n- `database.from`: adds `0206_artifacts_collab`, 1.2.5's last migration.\n- `upgrade.fromVersions`: adds v1.2.5.\n- `requiresDowntime` stays false.\n\nChecked locally: the 13 test files that read `CHANGELOG.md` or `release-policy.json` (222 pass, 0 fail), biome on both files, no dashes in Unreleased, and `scripts/support-window.ts check` against the published releases (holds).\n\n## Changelog\n\n**Before upgrading.**\n\n- **No migrations.** The database stays at `0206_artifacts_collab`, where 1.2.5 left it, so 1.2.5\n upgrades to 1.2.6 with its servers rolling one by one, with no downtime. Upgrading from 1.2.4 or\n older runs 1.2.5's migrations as well: read 1.2.5's Before upgrading first.\n- **No downtime, and nothing new is required.** No setting is added or changed.\n\n**Your account.**\n\n- **Deleting your account on OpenBot Cloud finishes.** Since 1.2.4 deleted an account at once, a\n deletion could stop part-way and answer that it couldn't finish (503) when the person's own\n organization was the one made for them when they signed up for OpenBot Cloud, which OpenBot may\n not close. Each try, and each pass of the server's backstop, stopped at the same step. That\n organization now stays with its owner, OpenBot's side of it is deleted with the account, and the\n deletion finishes. A deletion already stopped this way finishes on the person's next try, or on\n the backstop's next pass without them. A failure that may pass, such as the sign-in service out of\n reach, still stops the deletion to be finished later.\n- **Deleting your account while you're the only admin of a shared organization tells you first,\n and deletes nothing.** On OpenBot Cloud an organization with other members can't lose its only\n admin, and that was found out only at the last step, after most of the account was already\n deleted, with a 503 on every try. When the person is the only admin of an organization that has\n other members, including members who have never opened OpenBot, Settings now lists it before\n they press anything (\"You're its only admin: make someone else an admin.\"), and asking anyway is\n refused at once (\"You're the only admin of . Make someone else an admin, then try\n again.\") with nothing deleted. Once someone else is an admin there, the deletion goes ahead and\n they keep the organization.\n\n**Conversations.**\n\n- **A Bot's wait for a person stops when it can never be carried on.** When a Bot handed its\n browser to a person and the conversation was then deleted, or the person left it, every server\n asked about that wait on every pass, for ever, and logged `person-wait-not-carried-on` each time\n (about 36 times a minute on OpenBot Cloud for three such waits). Such a wait is now given up,\n with the reason kept, and cleared after a week. A wait that may still be carried on, such as one\n whose conversation another server is busy with, waits 30 seconds before it is tried again,\n doubling to 15 minutes, and is given up after about a day. The person sees the same as before:\n once the conversation is free, the turn is carried on with the call answered as it would have\n been.\n", + "user": { + "login": "davidmckayv" + }, + "head": { + "ref": "release-notes-1.2.6", + "repo": { + "full_name": "CopilotKit/OpenBot" + } + }, + "merged_at": "2026-12-01T17:32:43Z", + "merge_commit_sha": "1e9ba86fb6a3db262ae51291fac00294a5dc8444" + } + ], + "35b9fe5cb2cf72e1fcfad503f280d1af4e70a445": [ + { + "number": 2627, + "title": "Run main's OpenBot images again after v1.2.5", + "html_url": "https://github.com/CopilotKit/OpenBot/pull/2627", + "body": "v1.2.5 pinned `backend-images.env` to its own version, so a checkout of v1.2.5 runs the OpenBot images of that release. This puts main's own line back, so main runs the images built from main again.\n\nA PR opened with GITHUB_TOKEN does not trigger CI. Push an empty commit to main-images/v1.2.5 or close and reopen this PR to run the checks before merging.", + "user": { + "login": "github-actions[bot]" + }, + "head": { + "ref": "main-images/v1.2.5", + "repo": { + "full_name": "CopilotKit/OpenBot" + } + }, + "merged_at": "2026-12-01T16:41:09Z", + "merge_commit_sha": "35b9fe5cb2cf72e1fcfad503f280d1af4e70a445" + } + ], + "64b7b487f98f04be8cdcad91a8f94a8a3ba40e1d": [ + { + "number": 2625, + "title": "Open a long conversation at its newest message", + "html_url": "https://github.com/CopilotKit/OpenBot/pull/2625", + "body": "## What a person saw\n\nFound in the signed 1.2.4 Windows Desktop upgrade test: a long conversation opened again showed its history partway up, with the scroll-to-end button showing. One press of the button showed the newest message.\n\n## Why\n\nHistory keeps arriving after a conversation is drawn. The read taken with the join can be a moment behind, so the turn that ended just before the conversation opened comes in a moment later, with the join's replay or the read after it. A conversation you go back to is drawn from what was kept, and the read then brings what was said meanwhile, for example on a phone.\n\nThe message scroller lifts any person's message appended to it to the top of the view, the way it does for a send, with room under it for the reply. So that late turn's question went to the top of the view, and its answer (a tall picture and the Bot's words, in the case found) stayed below the fold.\n\n## What changed\n\n- `chat-transcript.tsx`: a person's row is a scroll anchor only when it arrived in this view as a send: one turn of their own, in a commit of its own, after the conversation was drawn. It uses the same test the send glide already uses (`arrivedAsOneSend`). History, whether drawn on opening or arriving later, is never an anchor, so the scroller follows the end for it. This also stops the scroller lifting the first history row on a later change that keeps the row count (its \"unhandled anchor\" path).\n- A message you send is still lifted to the top while the reply streams in, as before.\n- One behaviour change: a turn sent from another device while the conversation is open here is now treated as history. If you are at the end, the view follows it to the end, instead of lifting it.\n- No visual design change.\n\n## Tests\n\n- `app/tests/conversation-reopen-end.test.tsx` (new, real browser, Chromium and WebKit, added to the WebKit CI job): the real sidebar and conversation, the app's stylesheet from the first frame, a long conversation with pictures that arrive after the words, and a gateway that replays the thread's runs past the join deadline, as Intelligence does. It opens the conversation by loading it, from the sidebar, going back to it, with the history read a moment behind, and after a turn added from a phone. Each time the view must come to rest at the end, with the newest message in view and no scroll-to-end button.\n - Before the fix: the \"read a moment behind\" and \"turn added from a phone\" cases fail with the view 135 to 199 px above the end, the newest message out of view and the button showing.\n - After the fix: 10 of 10 pass (5 cases, 2 engines).\n- `app/tests/transcript-open.test.tsx`: a fast regression test, also under StrictMode. What a conversation opens with and history arriving are never anchors, and a send is. It fails without the fix.\n- `app/tests/transcript-attachments.test.tsx`: the three anchor tests now send the message into an open conversation, since only a send anchors.\n- These pass locally: the app unit suite (one failure, `workbench/pageDefaults.test.ts`, also fails on main and is not touched here), and in Chromium the browser tests for transcript-room, transcript-rail-clearance, conversation-kept, conversation-switch, first-message-thinking, step-rows-layout, queue-send-now-layout and conversation-reply-toolbar.\n\n## Changelog\n\n**Conversations.**\n\n- **A long conversation opens at its newest message.** Opened again, it could show its history\n partway up, with the scroll-to-end button showing, when its newest turn arrived a moment after\n the rest: a read of its history a moment behind, or a turn asked from another device while it was\n closed. That turn was taken for one just sent and lifted to the top of the view, its answer below\n the fold. Only a message sent in the open conversation is lifted now, so a turn sent from another\n device while the conversation is open here is followed to the end instead.\n", + "user": { + "login": "davidmckayv" + }, + "head": { + "ref": "fix/reopen-lands-at-newest", + "repo": { + "full_name": "CopilotKit/OpenBot" + } + }, + "merged_at": "2026-12-01T14:42:31Z", + "merge_commit_sha": "64b7b487f98f04be8cdcad91a8f94a8a3ba40e1d" + } + ] + }, + "section": "**Before upgrading.**\n\n- **No migrations.** The database stays at `0206_artifacts_collab`, where 1.2.5 left it, so 1.2.5\n upgrades to 1.2.6 with its servers rolling one by one, with no downtime. Upgrading from 1.2.4 or\n older runs 1.2.5's migrations as well: read 1.2.5's Before upgrading first.\n- **No downtime, and nothing new is required.** No setting is added or changed.\n\n**Artifacts.**\n\n- **Artifacts open in apps signed in before 1.2.5.** 1.2.5 gave artifacts permissions of their own,\n and an app's sign-in keeps the permissions it was first given through every refresh. So OpenBot\n Desktop, the phone app and the CLI, signed in before 1.2.5, were refused every artifact, and the\n card in the conversation and the Artifacts page said each new one \"was deleted, or it isn't shared\n with you any more\". The server now lets such a sign-in open artifacts as it could open the Bots, a\n read for a read and a change for a change, as it does for the other things that got permissions\n of their own later, so they open with no new sign-in and no app update. A browser was never\n affected.\n- **A refused sign-in no longer looks like a deleted artifact.** Only \"not found\" means an artifact\n is gone or isn't the person's now. When a sign-in may not see artifacts, the card, the viewer and\n the Artifacts page say \"This sign-in can't see your artifacts. Sign in again.\" instead.\n\n**Your account.**\n\n- **Deleting your account on OpenBot Cloud finishes.** Since 1.2.4 deleted an account at once, a\n deletion could stop part-way and answer that it couldn't finish (503) when the person's own\n organization was the one made for them when they signed up for OpenBot Cloud, which OpenBot may\n not close. Each try, and each pass of the server's backstop, stopped at the same step. That\n organization now stays with its owner, OpenBot's side of it is deleted with the account, and the\n deletion finishes. A deletion already stopped this way finishes on the person's next try, or on\n the backstop's next pass without them. A failure that may pass, such as the sign-in service out of\n reach, still stops the deletion to be finished later.\n- **Deleting your account while you're the only admin of a shared organization tells you first,\n and deletes nothing.** On OpenBot Cloud an organization with other members can't lose its only\n admin, and that was found out only at the last step, after most of the account was already\n deleted, with a 503 on every try. When the person is the only admin of an organization that has\n other members, including members who have never opened OpenBot, Settings now lists it before\n they press anything (\"You're its only admin: make someone else an admin.\"), and asking anyway is\n refused at once (\"You're the only admin of . Make someone else an admin, then try\n again.\") with nothing deleted. Once someone else is an admin there, the deletion goes ahead and\n they keep the organization.\n\n**Conversations.**\n\n- **A long conversation opens at its newest message.** Opened again, it could show its history\n partway up, with the scroll-to-end button showing, when its newest turn arrived a moment after\n the rest: a read of its history a moment behind, or a turn asked from another device while it was\n closed. That turn was taken for one just sent and lifted to the top of the view, its answer below\n the fold. Only a message sent in the open conversation is lifted now, so a turn sent from another\n device while the conversation is open here is followed to the end instead.\n- **A Bot's wait for a person stops when it can never be carried on.** When a Bot handed its\n browser to a person and the conversation was then deleted, or the person left it, every server\n asked about that wait on every pass, for ever, and logged `person-wait-not-carried-on` each time\n (about 36 times a minute on OpenBot Cloud for three such waits). Such a wait is now given up,\n with the reason kept, and cleared after a week. A wait that may still be carried on, such as one\n whose conversation another server is busy with, waits 30 seconds before it is tried again,\n doubling to 15 minutes, and is given up after about a day. The person sees the same as before:\n once the conversation is free, the turn is carried on with the call answered as it would have\n been." +} diff --git a/scripts/release-notes.ts b/scripts/release-notes.ts new file mode 100644 index 0000000000..713717d036 --- /dev/null +++ b/scripts/release-notes.ts @@ -0,0 +1,153 @@ +/** + * A pull request's release note, and how notes become a release's section of CHANGELOG.md. + * + * CHANGELOG.md is written by the release and by nothing else. Each pull request carries its note in + * its own description, under a `## Changelog` heading, in the shape CHANGELOG.md uses: lines grouped + * under a bold heading. A change nobody running OpenBot would notice says `none` there instead. + * + * ## Changelog + * + * **Signing in.** + * + * - **OpenBot Desktop signs in to OpenBot Cloud again.** What changed, for somebody deciding + * whether to upgrade. + * + * Preparing a release reads the notes of every pull request it ships (scripts/release-prepare.ts) + * and merges them here: one group per heading, `Before upgrading.` first, the rest in the order + * they first appear, and each group's lines in the order their pull requests merged. + */ + +/** The heading a pull request's note sits under, in its description. */ +export const NOTE_HEADING = "## Changelog"; + +/** One bold heading of a release's section and the lines under it. */ +export type Group = { heading: string; lines: string[] }; + +/** What a pull request's description says for the release notes. */ +export type Note = + | { kind: "missing" } + | { kind: "none" } + | { kind: "notes"; groups: Group[] } + | { kind: "invalid"; problems: string[] }; + +const HEADING = /^##\s+changelog\s*$/i; +const GROUP = /^\*\*(.+?)\*\*\s*$/; +const NONE = /^none\b/i; + +/** The group that always comes first in a release's section. */ +const FIRST = "before upgrading"; + +/** The text under a description's `## Changelog` heading, comments taken out, or undefined. */ +export function noteSection( + body: string | null | undefined, +): string | undefined { + if (!body) return undefined; + const lines = body + .replace(/\r\n?/g, "\n") + .replace(//g, "") + .split("\n"); + let found = false; + let fenced = false; + const section: string[] = []; + for (const line of lines) { + if (/^\s*(```|~~~)/.test(line)) fenced = !fenced; + if (!found) { + if (!fenced && HEADING.test(line)) found = true; + continue; + } + // The next heading of the same level or above ends the section. + if (!fenced && /^#{1,2}\s/.test(line)) break; + section.push(line); + } + return found ? section.join("\n") : undefined; +} + +/** A heading as groups are matched by: its words, without case or the full stop. */ +export const groupKey = (heading: string) => + heading + .trim() + .replace(/[.:]+$/, "") + .replace(/\s+/g, " ") + .toLowerCase(); + +/** Reads grouped lines: a bold heading on a line of its own, then what belongs under it. */ +export function parseGroups(text: string): { + groups: Group[]; + problems: string[]; +} { + const groups: Group[] = []; + const problems: string[] = []; + let current: Group | undefined; + for (const raw of text.replace(/\r\n?/g, "\n").split("\n")) { + const line = raw.replace(/\s+$/, ""); + const heading = GROUP.exec(line); + if (heading) { + current = { heading: heading[1].trim(), lines: [] }; + groups.push(current); + continue; + } + if (!current) { + if (line.trim() !== "") { + problems.push( + `"${line.trim()}" comes before any heading. Put each line under a bold heading on a line of its own, such as **API.**`, + ); + } + continue; + } + current.lines.push(line); + } + for (const group of groups) { + while (group.lines.length > 0 && group.lines[0].trim() === "") + group.lines.shift(); + while (group.lines.length > 0 && group.lines.at(-1)?.trim() === "") + group.lines.pop(); + if (group.lines.length === 0) { + problems.push(`**${group.heading}** has nothing under it.`); + } + } + return { groups, problems }; +} + +/** What a pull request's description says for the release notes. */ +export function parseNote(body: string | null | undefined): Note { + const section = noteSection(body); + if (section === undefined || section.trim() === "") + return { kind: "missing" }; + const text = section.trim(); + const { groups, problems } = parseGroups(text); + if (groups.length === 0 && NONE.test(text)) return { kind: "none" }; + if (problems.length > 0) return { kind: "invalid", problems }; + if (groups.length === 0) return { kind: "missing" }; + return { kind: "notes", groups }; +} + +/** + * Merges the notes of several pull requests, oldest first, into one section's groups: one group per + * heading, `Before upgrading.` first, the rest in the order they first appear. + */ +export function combineNotes(notes: Group[][]): Group[] { + const byKey = new Map(); + for (const groups of notes) { + for (const group of groups) { + const key = groupKey(group.heading); + const merged = byKey.get(key); + if (merged) { + merged.lines.push(...group.lines); + } else { + byKey.set(key, { heading: group.heading, lines: [...group.lines] }); + } + } + } + const all = [...byKey.values()]; + return [ + ...all.filter((group) => groupKey(group.heading) === FIRST), + ...all.filter((group) => groupKey(group.heading) !== FIRST), + ]; +} + +/** A section's body as CHANGELOG.md writes it, without its `## ` version heading. */ +export function renderGroups(groups: Group[]): string { + return groups + .map((group) => `**${group.heading}**\n\n${group.lines.join("\n")}`) + .join("\n\n"); +} diff --git a/scripts/release-prepare.test.ts b/scripts/release-prepare.test.ts index ef2fdb2117..3ebc76e516 100644 --- a/scripts/release-prepare.test.ts +++ b/scripts/release-prepare.test.ts @@ -9,17 +9,68 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { prepareRelease } from "./release-prepare"; -import type { Kind } from "./release-version"; +import type { ApiPull, Collected } from "./release-collect-notes"; +import { parseGroups } from "./release-notes"; +import { + main, + type PrepareOptions, + prepareRelease as prepareWith, +} from "./release-prepare"; +import type { Bump, Kind } from "./release-version"; const directories: string[] = []; +/** What a release ships when no pull request since the last one carries a note. */ +const nothing = (): Collected => ({ + previousTag: "v0.1.0", + notes: [], + none: [], + problems: [], + skipped: [], + before: [], + withoutPull: [], +}); + +const pull = (number: number, body: string | null): ApiPull => ({ + number, + title: `Change ${number}`, + html_url: `https://github.com/CopilotKit/OpenBot/pull/${number}`, + body, + user: { login: "davidmckayv" }, + head: { ref: `change-${number}`, repo: { full_name: "CopilotKit/OpenBot" } }, + merged_at: "2026-12-01T00:00:00Z", + merge_commit_sha: `sha${number}`, +}); + +/** Notes from pull requests, each given as the text under its `## Changelog`. */ +const fromPulls = + (...notes: string[]) => + (): Collected => ({ + ...nothing(), + notes: notes.map((note, index) => ({ + pull: pull(100 + index, `## Changelog\n\n${note}`), + groups: parseGroups(note).groups, + })), + }); + +/** prepareRelease with no pull requests to read unless a test gives some. */ +const prepareRelease = ( + root: string, + bump: Bump, + kind: Kind, + options: PrepareOptions = {}, +) => prepareWith(root, bump, kind, { collect: nothing, ...options }); + const cargo = (version: string) => `[package]\nname = "openbot-desktop"\nversion = "${version}"\n\n[dependencies]\nexample = "0.0.10"\n`; const lock = (version: string) => `version = 4\n\n[[package]]\nname = "example"\nversion = "0.0.10"\n\n[[package]]\nname = "openbot-desktop"\nversion = "${version}"\ndependencies = ["example"]\n`; -function fixture(version: string, unreleased = "- Something new.\n") { +// What sat under Unreleased before notes moved into pull requests' descriptions. +const LEGACY = "**Changes.**\n\n- Something new.\n"; +const LEGACY_NOTES = "**Changes.**\n\n- Something new."; + +function fixture(version: string, unreleased = LEGACY) { const root = mkdtempSync(join(tmpdir(), "openbot-release-prepare-")); directories.push(root); mkdirSync(join(root, "desktop/src-tauri"), { recursive: true }); @@ -65,10 +116,10 @@ test("a stable patch promotes the changelog and moves Cargo", () => { const result = prepareRelease(root, "patch", "stable"); expect(result.version).toBe("0.2.1"); expect(result.base).toBe("main"); - expect(result.notes).toBe("- Something new."); + expect(result.notes).toBe(LEGACY_NOTES); expect(JSON.parse(read("package.json")).version).toBe("0.2.1"); - expect(read("CHANGELOG.md")).toContain( - "## Unreleased\n\n## 0.2.1\n\n- Something new.", + expect(read("CHANGELOG.md")).toBe( + `# Changelog\n\n## Unreleased\n\n## 0.2.1\n\n${LEGACY_NOTES}\n\n## 0.1.0\n\n- First.\n`, ); expect(read("desktop/src-tauri/Cargo.toml")).toContain('version = "0.2.1"'); expect(read("desktop/src-tauri/Cargo.lock")).toContain( @@ -103,14 +154,18 @@ test("a release refuses a backend-images.env with no single tag line", () => { } }); -test("a minor release candidate leaves the changelog alone", () => { +test("a candidate writes its notes under Unreleased, where publishing it reads them", () => { const { root, read } = fixture("0.2.0"); - const before = read("CHANGELOG.md"); - const result = prepareRelease(root, "minor", "rc"); + const result = prepareRelease(root, "minor", "rc", { + collect: fromPulls("**API.**\n\n- **Added: something.**"), + }); expect(result.version).toBe("0.3.0-rc.1"); expect(result.base).toBe("release/0.3"); - expect(result.notes).toBe("- Something new."); - expect(read("CHANGELOG.md")).toBe(before); + const notes = `${LEGACY_NOTES}\n\n**API.**\n\n- **Added: something.**`; + expect(result.notes).toBe(notes); + expect(read("CHANGELOG.md")).toBe( + `# Changelog\n\n## Unreleased\n\n${notes}\n\n## 0.1.0\n\n- First.\n`, + ); }); test("final finishes a candidate under its own heading", () => { @@ -118,19 +173,119 @@ test("final finishes a candidate under its own heading", () => { const result = prepareRelease(root, "patch", "final"); expect(result.version).toBe("0.3.0"); expect(result.base).toBe("release/0.3"); - expect(result.notes).toBe("- Something new."); - expect(read("CHANGELOG.md")).toContain("## Unreleased\n\n## 0.3.0\n"); + expect(result.notes).toBe(LEGACY_NOTES); + expect(read("CHANGELOG.md")).toContain( + `## Unreleased\n\n## 0.3.0\n\n${LEGACY_NOTES}\n\n## 0.1.0`, + ); +}); + +test("a release's notes are its pull requests' notes, merged by heading, Before upgrading first", () => { + const { root, read } = fixture("0.2.0", "\n"); + const result = prepareRelease(root, "patch", "stable", { + collect: fromPulls( + "**Conversations.**\n\n- **One.** First.", + "**Before upgrading.**\n\n- **No migrations.**\n\n**Conversations.**\n\n- **Two.** Second,\n wrapped.", + ), + }); + const notes = + "**Before upgrading.**\n\n- **No migrations.**\n\n**Conversations.**\n\n- **One.** First.\n- **Two.** Second,\n wrapped."; + expect(result.notes).toBe(notes); + expect(read("CHANGELOG.md")).toBe( + `# Changelog\n\n## Unreleased\n\n## 0.2.1\n\n${notes}\n\n## 0.1.0\n\n- First.\n`, + ); +}); + +test("a later candidate or the final reads Unreleased from where the release line began, so no note counts twice", () => { + // The first candidate wrote the old Unreleased and its pull request's note under Unreleased on + // the release branch. The final reads the old Unreleased from the commit that candidate was cut + // from, and the note from the pull request again. + const note = "**API.**\n\n- **Added: something.**"; + const { root, read } = fixture("0.3.0-rc.1", `${LEGACY_NOTES}\n\n${note}\n`); + const result = prepareRelease(root, "patch", "final", { + collect: () => ({ + ...fromPulls(note)(), + startedFrom: { + tag: "v0.3.0-rc.1", + changelog: `# Changelog\n\n## Unreleased\n\n${LEGACY}\n## 0.1.0\n\n- First.\n`, + }, + }), + }); + expect(result.notes).toBe(`${LEGACY_NOTES}\n\n${note}`); + expect(read("CHANGELOG.md")).toBe( + `# Changelog\n\n## Unreleased\n\n## 0.3.0\n\n${LEGACY_NOTES}\n\n${note}\n\n## 0.1.0\n\n- First.\n`, + ); +}); + +test("a pull request without a note stops the release, named, and nothing is written", () => { + const { root, read } = fixture("0.2.0"); + const before = read("CHANGELOG.md"); + const missing = pull(2646, "## What this changes\n\nA fix."); + expect(() => + prepareRelease(root, "patch", "stable", { + collect: () => ({ + ...nothing(), + problems: [ + { + pull: missing, + problems: ["Its description has no note under ## Changelog."], + }, + ], + }), + }), + ).toThrow( + "- #2646 Change 2646 (https://github.com/CopilotKit/OpenBot/pull/2646): Its description has no note under ## Changelog.", + ); + expect(read("CHANGELOG.md")).toBe(before); + expect(JSON.parse(read("package.json")).version).toBe("0.2.0"); +}); + +test("lines under Unreleased with no heading are refused, not guessed at", () => { + const { root } = fixture("0.2.0", "- Something new.\n"); + expect(() => prepareRelease(root, "patch", "stable")).toThrow( + "The lines under '## Unreleased' in CHANGELOG.md can't be read", + ); }); for (const kind of ["stable", "rc", "beta", "final"] as Kind[]) { - test(`an empty Unreleased throws for ${kind}`, () => { + test(`no note anywhere throws for ${kind}`, () => { const { root } = fixture(kind === "final" ? "0.3.0-rc.1" : "0.2.0", "\n"); expect(() => prepareRelease(root, "patch", kind)).toThrow( - "Nothing under '## Unreleased'", + "A release nobody can describe is not a release.", ); }); } +const deprecatedSpec = `openapi: 3.1.0 +info: { title: t, version: "1" } +paths: + /api/v2/things/{thingId}: + get: + deprecated: true + x-deprecation-date: "2026-12-01" + x-sunset: "2027-12-01" + parameters: + - { name: thingId, in: path, required: true, schema: { type: string } } + responses: { "200": { description: ok } } +`; + +test("a release that would ship a deprecation its changelog doesn't list is refused", () => { + const { root, read } = fixture("0.2.0"); + mkdirSync(join(root, "api")); + writeFileSync(join(root, "api/openapi.yaml"), deprecatedSpec); + expect(() => prepareRelease(root, "patch", "stable")).toThrow( + "- `GET /api/v2/things/{thingId}`: Sunset 2027-12-01", + ); + expect(JSON.parse(read("package.json")).version).toBe("0.2.0"); + + // Listed in a pull request's note, with its sunset, it ships. + const result = prepareRelease(root, "patch", "stable", { + collect: fromPulls( + "**Before upgrading.**\n\n- **Deprecated.**\n - `GET /api/v2/things/{thingId}`: Sunset 2027-12-01.", + ), + }); + expect(result.version).toBe("0.2.1"); +}); + test("a missing Unreleased heading throws", () => { const { root } = fixture("0.2.0"); writeFileSync(join(root, "CHANGELOG.md"), "# Changelog\n"); @@ -235,45 +390,42 @@ test("a stable release never touches a latest CLI", () => { function runCli(unreleased?: string) { const { root } = fixture("0.2.0", unreleased); - copyFileSync( - join(import.meta.dir, "release-prepare.ts"), - join(root, "scripts/release-prepare.ts"), - ); const output = join(root, "github-output.txt"); + const summary = join(root, "step-summary.md"); const temp = join(root, "runner-temp"); mkdirSync(temp); - const run = Bun.spawnSync( - [ - process.execPath, - join(root, "scripts/release-prepare.ts"), - "patch", - "stable", - ], - { - cwd: root, - env: { ...process.env, GITHUB_OUTPUT: output, RUNNER_TEMP: temp }, - }, + const code = main( + ["patch", "stable"], + root, + { GITHUB_OUTPUT: output, GITHUB_STEP_SUMMARY: summary, RUNNER_TEMP: temp }, + { collect: nothing }, ); - return { run, output, temp }; + return { code, output, summary, temp }; } test("the CLI entry writes version and base to GITHUB_OUTPUT, and the notes to a file", () => { - const { run, output, temp } = runCli(); - expect(run.exitCode).toBe(0); + const { code, output, summary, temp } = runCli(); + expect(code).toBe(0); const file = join(temp, "release-notes.md"); expect(readFileSync(output, "utf8")).toBe( `version=0.2.1\nbase=main\nnotes_file=${file}\n`, ); - expect(readFileSync(file, "utf8")).toBe("- Something new."); + expect(readFileSync(file, "utf8")).toBe(LEGACY_NOTES); + expect(readFileSync(summary, "utf8")).toContain("Notes since v0.1.0:"); }); -test("the notes file holds the whole Unreleased body, past what one env var can carry", () => { +test("the notes file holds the whole section, past what one env var can carry", () => { const line = "- A long note.\n"; - const { run, temp } = runCli(line.repeat(20000)); - expect(run.exitCode).toBe(0); + const { code, temp } = runCli(`**Changes.**\n\n${line.repeat(20000)}`); + expect(code).toBe(0); const notes = readFileSync(join(temp, "release-notes.md"), "utf8"); expect(notes.length).toBeGreaterThan(200_000); - expect(notes).toBe(line.repeat(20000).trim()); + expect(notes).toBe(`**Changes.**\n\n${line.repeat(20000).trim()}`); +}); + +test("the CLI entry fails, saying why, on bad arguments", () => { + const { root } = fixture("0.2.0"); + expect(main(["sideways", "stable"], root, {}, { collect: nothing })).toBe(1); }); const policy = (version: string) => diff --git a/scripts/release-prepare.ts b/scripts/release-prepare.ts index 1c49a8d84a..5bc0475b07 100644 --- a/scripts/release-prepare.ts +++ b/scripts/release-prepare.ts @@ -7,6 +7,16 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; +import { + deprecationsIn, + missingFromChangelog, +} from "../shared/api-deprecations"; +import { + type Collected, + collectNotes, + liveCollectDeps, +} from "./release-collect-notes"; +import { combineNotes, parseGroups, renderGroups } from "./release-notes"; import { type Bump, type Kind, @@ -14,7 +24,12 @@ import { releaseBranch, } from "./release-version"; -export type Prepared = { version: string; base: string; notes: string }; +export type Prepared = { + version: string; + base: string; + notes: string; + collected: Collected; +}; // The lines of a "## " section, from the line after its heading to the next // "## " heading. @@ -33,7 +48,40 @@ function sectionBody(changelog: string, heading: string): string { return body.join("\n").trim(); } -export type PrepareOptions = { npmView?: (spec: string) => string }; +/** + * CHANGELOG.md with what sits under `## Unreleased` replaced by `replacement`, which is a section + * body or a whole `## X.Y.Z` section of its own, and the sections after it kept as they are. + */ +function replaceUnreleased(changelog: string, replacement: string): string { + const lines = changelog.split("\n"); + const start = lines.indexOf("## Unreleased"); + let end = lines.findIndex( + (line, index) => index > start && line.startsWith("## "), + ); + if (end === -1) end = lines.length; + const before = lines.slice(0, start + 1).join("\n"); + const after = lines.slice(end).join("\n"); + return after === "" + ? `${before}\n\n${replacement}\n` + : `${before}\n\n${replacement}\n\n${after}`; +} + +export type PrepareOptions = { + npmView?: (spec: string) => string; + /** + * The notes of the pull requests this release ships (scripts/release-collect-notes.ts). By default + * read from this checkout's history and the GitHub API. + */ + collect?: (version: string) => Collected; +}; + +/** The repository the release's pull requests are read from. */ +const repositoryOf = (env: NodeJS.ProcessEnv) => + env.GITHUB_REPOSITORY || "CopilotKit/OpenBot"; + +function describePull(pull: Collected["notes"][number]["pull"]): string { + return `#${pull.number} ${pull.title} (${pull.html_url})`; +} // Asks npm for the version a spec resolves to. function npmViewVersion(spec: string): string { @@ -57,19 +105,90 @@ export function prepareRelease( const pkg = JSON.parse(readFileSync(packagePath, "utf8")); const version = nextVersion(pkg.version, bump, kind); - // CHANGELOG.md is written by hand, for the person deciding whether to upgrade. This - // promotes what is already there; it never generates notes from commit subjects, because a - // commit subject is written for the person reading the diff. + // CHANGELOG.md is written by the release and by nothing else, for the person deciding whether to + // upgrade. Each pull request carries its note in its own description, written by hand under + // `## Changelog` (scripts/release-notes.ts); this gathers the notes of every pull request the + // release ships. It never generates notes from commit subjects, because a commit subject is + // written for the person reading the diff. Whatever still sits under `## Unreleased`, written + // there before notes moved into descriptions, comes first, so no note is lost on the way. const changelogPath = join(root, "CHANGELOG.md"); const changelog = readFileSync(changelogPath, "utf8"); if (!/^## Unreleased$/m.test(changelog)) { throw new Error("CHANGELOG.md has no '## Unreleased' section."); } - const unreleased = sectionBody(changelog, "## Unreleased"); - if (unreleased === "") { + const collect = + options.collect ?? + ((v: string) => + collectNotes( + v, + "HEAD", + repositoryOf(process.env), + liveCollectDeps(root, repositoryOf(process.env)), + )); + const collected = collect(version); + + // What was under Unreleased before this release line began: here, or, once a candidate of this + // version has written its own notes there, on the commit the first candidate was cut from. + const before = collected.startedFrom + ? (collected.startedFrom.changelog ?? "") + : changelog; + const legacy = parseGroups(sectionBody(before, "## Unreleased")); + if (legacy.problems.length > 0) { throw new Error( - "Nothing under '## Unreleased'. A release nobody can describe is not a release.", + `The lines under '## Unreleased' in CHANGELOG.md${collected.startedFrom ? ` before ${collected.startedFrom.tag}` : ""} can't be read:\n${legacy.problems.join("\n")}`, + ); + } + if (collected.problems.length > 0) { + throw new Error( + [ + `These pull requests ship in ${version} without a release note it can read:`, + ...collected.problems.map( + ({ pull, problems }) => + `- ${describePull(pull)}: ${problems.join(" ")}`, + ), + "Edit each one's description: under '## Changelog', write its note under a bold heading, or 'none'. Then run Create release PR again. A merged pull request's description can still be edited.", + ].join("\n"), + ); + } + const groups = combineNotes([ + legacy.groups, + ...collected.notes.map((note) => note.groups), + ]); + if (groups.length === 0) { + throw new Error( + `Nothing to release: no pull request since ${collected.previousTag ?? "the start"} has a release note, and nothing is under '## Unreleased'. A release nobody can describe is not a release.`, + ); + } + const notes = renderGroups(groups); + + // Unreleased becomes the version, and stays as an empty heading above it. A candidate or beta is + // not the release itself: its notes go under Unreleased, where publishing a prerelease reads + // them, and the final writes them again, with whatever shipped since, under its own heading. + const promotes = kind === "stable" || kind === "final"; + const written = replaceUnreleased( + changelog, + promotes ? `## ${version}\n\n${notes}` : notes, + ); + + // A deprecation reaches the people it affects through the changelog, which the Deprecation and + // Sunset headers link to. No release ships one the changelog doesn't list with its sunset. + const specPath = join(root, "api/openapi.yaml"); + if (existsSync(specPath)) { + const missing = missingFromChangelog( + deprecationsIn(Bun.YAML.parse(readFileSync(specPath, "utf8"))), + written, ); + if (missing.length > 0) { + throw new Error( + [ + `CHANGELOG.md for ${version} would not list these deprecations with their sunset:`, + ...missing.map( + (element) => `- \`${element.key}\`: Sunset ${element.sunset}`, + ), + "Add each, in backticks with its sunset, to the note of the pull request that deprecated it, under **Before upgrading.**, then run Create release PR again.", + ].join("\n"), + ); + } } pkg.version = version; @@ -126,24 +245,13 @@ export function prepareRelease( } } - // Unreleased becomes the version, and a fresh empty Unreleased takes its place so the next - // change has somewhere to go without anyone hand-editing a heading. A candidate or beta is - // not the release itself, so it leaves the changelog for the final to promote. - const promotes = kind === "stable" || kind === "final"; - let notes = unreleased; - if (promotes) { - const promoted = changelog.replace( - /^## Unreleased$/m, - `## Unreleased\n\n## ${version}`, - ); - writeFileSync(changelogPath, promoted); - notes = sectionBody(promoted, `## ${version}`); - } + writeFileSync(changelogPath, written); return { version, base: kind === "stable" ? "main" : releaseBranch(version), notes, + collected, }; } @@ -205,38 +313,74 @@ const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; const bumps: Bump[] = ["patch", "minor", "major"]; const kinds: Kind[] = ["stable", "rc", "beta", "final"]; +/** Which pull requests the notes came from, for the run's log and step summary. */ +function sources(collected: Collected): string { + const list = (pulls: { number: number }[]) => + pulls.length > 0 + ? pulls.map((pull) => `#${pull.number}`).join(", ") + : "none"; + return [ + `Notes since ${collected.previousTag ?? "the start"}:`, + `- with a note: ${list(collected.notes.map((note) => note.pull))}`, + `- no note needed: ${list(collected.none)}`, + `- the release's own: ${list(collected.skipped)}`, + `- merged before notes moved into descriptions: ${list(collected.before)}`, + ...(collected.withoutPull.length > 0 + ? [`- commits with no pull request: ${collected.withoutPull.join(", ")}`] + : []), + ].join("\n"); +} + // Runs from the release workflow: `bun scripts/release-prepare.ts `. // The result goes to $GITHUB_OUTPUT so later steps can read it, or to stdout when // run by hand. The notes go to a file and only its path is an output: a step that took them // through an environment variable would fail once they pass 128 KB, the most Linux allows for -// one string. -if (import.meta.main) { - const [bump, kind] = process.argv.slice(2); +// one string. Returns the exit code. +export function main( + args: string[], + root: string, + env: NodeJS.ProcessEnv, + options: PrepareOptions = {}, +): number { + const [bump, kind] = args; if (!bumps.includes(bump as Bump) || !kinds.includes(kind as Kind)) { console.error( `Usage: bun scripts/release-prepare.ts <${bumps.join("|")}> <${kinds.join("|")}>`, ); - process.exit(1); + return 1; } try { - const { version, base, notes } = prepareRelease( - resolve(import.meta.dir, ".."), + const { version, base, notes, collected } = prepareRelease( + root, bump as Bump, kind as Kind, + options, ); const notesFile = join( - process.env.RUNNER_TEMP || mkdtempSync(join(tmpdir(), "release-")), + env.RUNNER_TEMP || mkdtempSync(join(tmpdir(), "release-")), "release-notes.md", ); writeFileSync(notesFile, notes); const text = `version=${version}\nbase=${base}\nnotes_file=${notesFile}\n`; - if (process.env.GITHUB_OUTPUT) { - appendFileSync(process.env.GITHUB_OUTPUT, text); + if (env.GITHUB_OUTPUT) { + appendFileSync(env.GITHUB_OUTPUT, text); } else { process.stdout.write(text); } + const summary = sources(collected); + console.error(summary); + if (env.GITHUB_STEP_SUMMARY) { + appendFileSync(env.GITHUB_STEP_SUMMARY, `${summary}\n`); + } + return 0; } catch (error) { console.error(error instanceof Error ? error.message : error); - process.exit(1); + return 1; } } + +if (import.meta.main) { + process.exit( + main(process.argv.slice(2), resolve(import.meta.dir, ".."), process.env), + ); +} diff --git a/shared/tests/api-deprecations.test.ts b/shared/tests/api-deprecations.test.ts index c5a2c7b29a..2e9e6f0bcc 100644 --- a/shared/tests/api-deprecations.test.ts +++ b/shared/tests/api-deprecations.test.ts @@ -1,8 +1,9 @@ /** - * The deprecations the API spec marks, read from the real spec and held against the real changelog. + * The deprecations the API spec marks, read from the real spec. * * The first test is the check every pull request runs: whatever api/openapi.yaml marks deprecated is - * complete (both dates, in order) and listed in CHANGELOG.md with its sunset. The rest mark real + * complete (both dates, in order). That each is announced with its sunset is checked on the pull + * request's release note and again when a release is prepared. The rest mark real * operations of a copy of the spec deprecated, the way a builder would, and follow the marks through * to the request that uses one and the headers its answer carries. */ @@ -73,9 +74,12 @@ function keys(table: DeprecationTable) { } describe("the spec's own deprecations", () => { - test("are complete, and the changelog lists every one with its sunset", () => { - const table = deprecationsIn(spec()); - expect(missingFromChangelog(table, CHANGELOG)).toEqual([]); + // Each is announced by the release that ships it: the pull request that marks one names it in its + // release note (scripts/release-note-check.ts), and preparing a release refuses notes that leave + // one out (scripts/release-prepare.ts). CHANGELOG.md itself is the release's to write, so it is + // not held to the spec here: a deprecation merged since the last release is in no section yet. + test("are complete", () => { + expect(() => deprecationsIn(spec())).not.toThrow(); }); });