Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Derive Open Knowledge beta versions from published stable tags (PRD-9389) (#6463)
Andrew Mikofalvy0291a6220321
diff --git a/.github/scripts/bug-lane.test.mjs b/.github/scripts/bug-lane.test.mjsindex efc9ec036..0c643ea54 100644--- a/.github/scripts/bug-lane.test.mjs+++ b/.github/scripts/bug-lane.test.mjs@@ -288,7 +288,7 @@ describe('the bug-lane entry points the two jobs run', () => {'.github/scripts/select-beta-to-promote.mjs','.github/scripts/shipped-fix-containment.mjs','scripts/compute-stable-version.mjs',- 'scripts/compute-next-beta.mjs',+ 'scripts/changeset-versions.mjs','scripts/git-clean-env.mjs',];const dirs = [];diff --git a/.github/scripts/point-release-plan.mjs b/.github/scripts/point-release-plan.mjsindex 559bde7a3..9b06e7888 100644--- a/.github/scripts/point-release-plan.mjs+++ b/.github/scripts/point-release-plan.mjs@@ -4,9 +4,7 @@ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';import { pathToFileURL } from 'node:url';import {computePointReleaseVersion,- evaluateAnchorGuard,parseBumpVerdicts,- readAnchorVersion,realGit,recordBumpVerdicts,runGit,@@ -44,20 +42,6 @@ function pass(message) {return { ok: true, code: null, message };}-export function guardAnchor({ anchorVersion, latestStableTag }) {- const verdict = evaluateAnchorGuard({ anchorVersion, latestStableTag });- if (!verdict.ok) {- return refuse(- 'anchor-drift',- `${verdict.reason} Refusing rather than waiting: this lane holds the release-cadence lock, ` +- 'and the consolidation that clears the drift needs it. Re-run once the anchor is level. ' +- 'If main-reset itself keeps failing its version guard, dispatch it with anchor_override=true ' +- '(RELEASES.md, Recovering anchor drift).',- );- }- return pass(verdict.reason);-}-export function parseFixRefs(raw) {const refs = splitList(raw);if (refs.length === 0) {@@ -516,7 +500,6 @@ export function runPointRelease(opts, io) {guards,guardBasePublished({ latestStableTag, publishedTags: io.containment.publishedStableTags() }),);- checkGuard(guards, guardAnchor({ anchorVersion: io.readAnchorVersion(), latestStableTag }));checkGuard(guards, guardRefsOnMain({ fixRefs, isOnMain: io.git.isOnMain }));checkGuard(guards, guardResolvePathsAllowlisted({ resolvePaths }));@@ -747,8 +730,9 @@ function decideMainReset({ anchorDeltaIds, addedIds, bridgeConfigured, guards, w'Skipping the main-reset dispatch: this release forwards no changeset delta, and dispatching an ' +'empty one would consolidate the entire pending pile. Two follow-ups are now yours: land the fix ' +'(for a revert, the revert itself) on main so the pile stops carrying it, and run main-reset with ' +- 'that changeset so the anchor advances past this stable. Until the anchor advances, every ' +- 'version-computing path refuses.',+ 'that changeset so the anchor advances past this stable. Until the anchor advances, every later ' ++ 'automatic main-reset fails its version guard; beta and stable versions come from the stable tags ' ++ 'and are unaffected.',);return { dispatch: false, deltaIds: null, skipReason: 'no-delta-to-forward' };}@@ -815,7 +799,6 @@ export function formatReleaseNotes(plan) {export function realIo() {return {- readAnchorVersion,containment: createShippedFixCheck(),fs: {readWorktreeFile: (path) => readFileSync(path, 'utf8'),diff --git a/.github/scripts/point-release-plan.test.mjs b/.github/scripts/point-release-plan.test.mjsindex 6b1e916aa..f23cbdc6c 100644--- a/.github/scripts/point-release-plan.test.mjs+++ b/.github/scripts/point-release-plan.test.mjs@@ -12,7 +12,6 @@ import {APP_CREDENTIAL_HELPER,deriveEntryLevelResolution,formatReleaseNotes,- guardAnchor,guardBasePublished,guardDeltaMatchesFix,guardMainResetDeltaIds,@@ -105,25 +104,6 @@ const droppedFixVerdict = () => ({],});-describe('guardAnchor', () => {- test('refuses while a stable tag is ahead of the changeset anchor', () => {- const r = guardAnchor({ anchorVersion: '0.32.0', latestStableTag: 'v0.32.1' });- expect(r.ok).toBe(false);- expect(r.code).toBe('anchor-drift');- });-- test('passes when the anchor is level with the newest stable', () => {- const r = guardAnchor({ anchorVersion: '0.32.1', latestStableTag: 'v0.32.1' });- expect(r).toMatchObject({ ok: true, code: null });- });-- test('propagates a malformed anchor instead of reporting it as drift', () => {- expect(() =>- guardAnchor({ anchorVersion: 'not-a-version', latestStableTag: 'v0.32.1' }),- ).toThrow();- });-});-describe('parseFixRefs', () => {test('splits on commas and whitespace, trims, and dedupes', () => {expect(parseFixRefs(' abc123 , def456\ndef456\tghi789 ')).toEqual([@@ -586,7 +566,6 @@ describe('verifyWorkspaceMatchesLockfile', () => {describe('guard codes', () => {test('every guard refuses with its own distinct code', () => {const refusals = [- guardAnchor({ anchorVersion: '0.32.0', latestStableTag: 'v0.32.1' }),guardRefsOnMain({ fixRefs: ['stray'], isOnMain: membership() }),guardResolvePathsAllowlisted({ resolvePaths: ['packages/app/src/main.tsx'] }),guardTagFree({ tag: 'v0.32.1', tagExists: membership('v0.32.1') }),@@ -607,7 +586,6 @@ describe('guard codes', () => {function makeIo(overrides = {}) {const {stableTag = 'v0.32.0',- anchorVersion = '0.32.0',onMain = ['bad1', 'fix1'],existingTags = ['v0.32.0'],changesets = { 'stable-sha': ['keep-a'], 'synthetic-sha': ['keep-a'] },@@ -665,7 +643,6 @@ function makeIo(overrides = {}) {written[path] = content;},},- readAnchorVersion: () => anchorVersion,git: {newestStableTag: () => stableTag,revParse: (ref) => (ref === stableTag ? 'stable-sha' : `${ref}-sha`),@@ -1119,7 +1096,6 @@ describe('runPointRelease cascade', () => {describe('runPointRelease refusals', () => {const cases = [- ['anchor-drift', { anchorVersion: '0.31.0' }, { mode: 'revert', fixRefs: ['bad1'] }],['ref-not-on-main', { onMain: [] }, { mode: 'revert', fixRefs: ['bad1'] }],['tag-exists', { existingTags: ['v0.32.0', 'v0.32.1'] }, { mode: 'revert', fixRefs: ['bad1'] }],[@@ -1169,8 +1145,8 @@ describe('runPointRelease refusals', () => {},);- test('a failing anchor guard stops before the synthetic commit is even built', () => {- const io = makeIo({ anchorVersion: '0.31.0' });+ test('a failing base-published guard stops before the synthetic commit is even built', () => {+ const io = makeIo({ publishedTags: ['v0.31.9'] });expect(() =>runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: false }, io),).toThrow();diff --git a/.github/scripts/release-cascade-shape.test.mjs b/.github/scripts/release-cascade-shape.test.mjsindex dbf6893e9..b8e658594 100644--- a/.github/scripts/release-cascade-shape.test.mjs+++ b/.github/scripts/release-cascade-shape.test.mjs@@ -7,6 +7,7 @@ import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { afterAll, describe, expect, test } from 'vitest';import { parse } from 'yaml';+import { gitCleanEnv } from '../../scripts/git-clean-env.mjs';import { NOTES_SOURCE_MARKER, renderStableNotes } from '../../scripts/render-stable-notes.mjs';import { buildSlackPayload } from './build-smoke-alert-payload.mjs';import { execFileSync } from './child-tripwire.test-helper.mjs';@@ -1636,7 +1637,7 @@ describe('the macOS artifact is attested signed before it can ship', () => {describe('every job that reads changesets installs the Changesets reader first', () => {const OK_ROOT = join(WORKFLOWS, '..', '..');- const READER = join(OK_ROOT, 'scripts', 'compute-next-beta.mjs');+ const READER = join(OK_ROOT, 'scripts', 'changeset-versions.mjs');const importsReader = (file, seen = new Set()) => {if (file === READER) return true;if (seen.has(file) || !existsSync(file)) return false;@@ -2421,6 +2422,7 @@ describe('the release App credential never shares a job with installed packages'};const PUBLISH_STEP = 'Publish to npm via Trusted Publishing';const VALIDATE_STEP = 'Refuse build outputs that are not well-formed versions';+ const LEAD_STEP = 'Refuse a beta base that does not lead the newest stable tag';const replacePublishLine = (workflow, line) => {const step = stepNamed(workflow.jobs.publish, PUBLISH_STEP);step.run = step.run.replace(TARBALL_PUBLISH, line);@@ -2546,8 +2548,8 @@ describe('the release App credential never shares a job with installed packages'`steps > ${VALIDATE_STEP} > if: ${BETA_IF}`,`steps > ${VALIDATE_STEP} > env > BASE_VERSION: needs.build.outputs.base_version`,`steps > ${VALIDATE_STEP} > env > BUILD_VERSION: needs.build.outputs.version`,- `steps > Guard - beta base must lead the latest stable > if: ${BETA_IF}`,- 'steps > Guard - beta base must lead the latest stable > env > BASE_VERSION: needs.build.outputs.base_version',+ `steps > ${LEAD_STEP} > if: ${BETA_IF}`,+ `steps > ${LEAD_STEP} > env > BASE_VERSION: needs.build.outputs.base_version`,`steps > ${RESOLVE} > if: ${BETA_IF}`,`steps > ${RESOLVE} > env > BASE_VERSION: needs.build.outputs.base_version`,`steps > Refuse a beta the build job resolved differently > if: ${BETA_IF}`,@@ -2581,7 +2583,7 @@ describe('the release App credential never shares a job with installed packages'(step) => step !== validate && /needs\.build\.outputs\.(base_version|version)\b/.test(JSON.stringify(step.env ?? {})),);expect(readers.map((step) => step.name)).toEqual([- 'Guard - beta base must lead the latest stable',+ LEAD_STEP,'Resolve -beta.N counter','Refuse a beta the build job resolved differently',]);@@ -2601,6 +2603,47 @@ describe('the release App credential never shares a job with installed packages'}});+ test('the release job refuses a beta base that a stable tagged after build caught up with', () => {+ const { release } = releaseWorkflow.jobs;+ const lead = stepNamed(release, LEAD_STEP);+ expect(lead.if).toBe(BETA_IF);+ expect(steps(release).indexOf(lead)).toBeLessThan(steps(release).indexOf(stepNamed(release, 'Resolve -beta.N counter')));+ const repo = mkdtempSync(join(tmpdir(), 'release-lead-'));+ try {+ const env = gitCleanEnv();+ const git = (...args) => execFileSync('git', args, { cwd: repo, env, encoding: 'utf8' });+ git('init', '-q', '-b', 'main');+ for (const [tag, date] of [+ ['v0.86.1', '2026-01-01T00:00:00Z'],+ ['v0.86.10', '2026-01-02T00:00:00Z'],+ ['v0.86.9', '2026-01-03T00:00:00Z'],+ ['v0.86.11-beta.0', '2026-01-04T00:00:00Z'],+ ]) {+ execFileSync('git', ['-c', 'user.name=t', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', tag], {+ cwd: repo,+ env: { ...env, GIT_COMMITTER_DATE: date, GIT_AUTHOR_DATE: date },+ });+ git('tag', tag);+ }+ const run = (base) => {+ try {+ return { status: 0, stdout: execFileSync('bash', ['-c', lead.run], { cwd: repo, encoding: 'utf8', env: { PATH: process.env.PATH, BASE_VERSION: base }, stdio: ['ignore', 'pipe', 'pipe'] }) };+ } catch (error) {+ if (typeof error.status !== 'number') throw error;+ return { status: error.status, stdout: error.stdout };+ }+ };+ expect(run('0.86.11')).toMatchObject({ status: 0, stdout: expect.stringContaining('leads the newest stable tag v0.86.10') });+ for (const base of ['0.86.10', '0.86.9', '0.85.99']) {+ const refused = run(base);+ expect(refused.status, base).toBe(1);+ expect(refused.stdout).toMatch(/^::error::The build job numbered this beta from base .* does not lead the newest stable tag v0\.86\.10: .*Re-run all jobs/m);+ }+ } finally {+ rmSync(repo, { recursive: true, force: true });+ }+ });+describe('the release job pushes its tag with the job token through a one-command credential helper', () => {const TAG_STEP = 'Tag + create prerelease GitHub Release';const TAG = 'v0.82.0-beta.9';@@ -2894,12 +2937,12 @@ describe('the release App credential never shares a job with installed packages'});});- describe('read-releases hands build the previous beta that a contents: write read sees, drafts included', () => {- const READ_STEP = 'Read the newest beta Release, drafts included, and its body';+ describe('read-releases hands build the previous beta and the stable Releases that a contents: write read sees, drafts included', () => {+ const READ_STEP = 'Read the newest beta Release and its body, and list the stable Releases, drafts included';const COMPUTE_STEP = 'Compute next beta base version + render release notes';const BETA_PATH = "github.event_name == 'push' || github.event_name == 'workflow_dispatch'";- test('read-releases always runs, runs only gh release list and view, and build takes its outputs under their own names', () => {+ test('read-releases always runs, runs only gh release list and view and the stable Release listing, and build takes its outputs under their own names', () => {const { 'read-releases': readReleases, build } = releaseWorkflow.jobs;expect(readReleases.if).toBeUndefined();expect(readReleases.needs).toBeUndefined();@@ -2909,7 +2952,7 @@ describe('the release App credential never shares a job with installed packages'expect(read.if).toBe(BETA_PATH);expect(read.if).toBe(stepNamed(build, COMPUTE_STEP).if);expect(read.env).toEqual({ GH_TOKEN: '${{ github.token }}' });- expect(commands(read).match(/\bgh\s+\S+\s+\S+/g)).toEqual(['gh release list', 'gh release view']);+ expect(commands(read).match(/\bgh\s+\S+\s+\S+/g)).toEqual(['gh release list', 'gh release view', 'gh api -X']);expect(build.needs).toBe('read-releases');const names = Object.keys(readReleases.outputs);expect(names.length).toBeGreaterThan(0);@@ -2938,9 +2981,14 @@ describe('the release App credential never shares a job with installed packages''const args = process.argv.slice(2);',"appendFileSync(process.env.STUB_LOG, `${JSON.stringify(args)}\\n`);",'const world = JSON.parse(process.env.STUB_WORLD);',- 'const failure = (world.fail ?? {})[args[1]];',+ "const failure = (world.fail ?? {})[args[0] === 'api' ? 'api' : args[1]];","if (failure) { process.stderr.write(failure.stderr ?? ''); process.exit(failure.status); }","const visible = world.releases.filter((release) => world.token === 'write' || !release.isDraft);",+ "if (args[0] === 'api') {",+ ' const stable = visible.filter((release) => /^v[0-9]+\\.[0-9]+\\.[0-9]+$/.test(release.tagName));',+ " process.stdout.write(stable.map((release) => `${JSON.stringify({ tag_name: release.tagName, draft: release.isDraft })}\\n`).join(''));",+ ' process.exit(0);',+ '}',"if (args[1] === 'list') {",' const first = visible.find((release) => release.isPrerelease && /^v[0-9]+\\.[0-9]+\\.[0-9]+-beta\\.[0-9]+$/.test(release.tagName));'," process.stdout.write(`${first ? first.tagName : ''}\\n`);",@@ -3020,11 +3068,13 @@ describe('the release App credential never shares a job with installed packages'};const marker = (ids) => `Notes for the beta.\n\n<!-- ok-consumed-set: ${JSON.stringify(ids)} -->\n\n`;const beta = (tagName, body, isDraft = false) => ({ tagName, isDraft, isPrerelease: true, body });+ const stable = (tagName, isDraft = false) => ({ tagName, isDraft, isPrerelease: false, body: 'Stable.' });const draftNewest = {releases: [beta('v0.82.0-beta.9', marker(['a', 'b']), true),+ stable('v0.81.5', true),beta('v0.82.0-beta.8', marker(['a'])),- { tagName: 'v0.81.4', isDraft: false, isPrerelease: false, body: 'Stable.' },+ stable('v0.81.4'),],};const worlds = {@@ -3035,15 +3085,24 @@ describe('the release App credential never shares a job with installed packages''the body has no marker': { releases: [beta('v0.82.0-beta.9', 'Notes without a marker.\n')] },'the marker is not JSON': { releases: [beta('v0.82.0-beta.9', 'Notes.\n<!-- ok-consumed-set: [a, b] -->')] },'the marker is not a string array': { releases: [beta('v0.82.0-beta.9', 'Notes.\n<!-- ok-consumed-set: [1, 2] -->')] },+ 'the stable listing fails': { releases: draftNewest.releases, fail: { api: { status: 1, stderr: 'HTTP 502: Bad Gateway\n' } } },};test.each(Object.keys(worlds))('when %s, build replays exactly what a contents: write gh read returns', async (name) => {- const { previousBeta, recordedReleases, RELEASE_LIST_ARGS, releaseViewArgs } = await import('../../scripts/compute-next-beta.mjs');+ const { previousBeta, recordedReleases, RELEASE_LIST_ARGS, releaseViewArgs, STABLE_RELEASES_ARGS } = await import(+ '../../scripts/compute-next-beta.mjs'+ );+ const { parseReleaseListing } = await import('./shipped-fix-containment.mjs');const world = worlds[name];const { env, calls } = throughTheWorkflow(releaseWorkflow, world, RELEASE_LIST_ARGS[3]);const replayed = previousBeta(recordedReleases(env));expect(replayed).toEqual(previousBeta(directly(world, 'write')));- expect(calls).toEqual(replayed.prevBetaTag ? [RELEASE_LIST_ARGS, releaseViewArgs(replayed.prevBetaTag)] : [RELEASE_LIST_ARGS]);+ const listing = (res) => ({ status: res.status, releases: res.status === 0 ? parseReleaseListing(res.stdout) : null });+ expect(listing(recordedReleases(env)(STABLE_RELEASES_ARGS))).toEqual(listing(directly(world, 'write')(STABLE_RELEASES_ARGS)));+ expect(calls).toEqual([+ ...(replayed.prevBetaTag ? [RELEASE_LIST_ARGS, releaseViewArgs(replayed.prevBetaTag)] : [RELEASE_LIST_ARGS]),+ STABLE_RELEASES_ARGS,+ ]);});test('with the previous beta still a draft, the replay is the draft and not what a contents: read token sees', async () => {@@ -3052,6 +3111,19 @@ describe('the release App credential never shares a job with installed packages'expect(previousBeta(recordedReleases(env))).toEqual({ prevBetaTag: 'v0.82.0-beta.9', recovered: ['a', 'b'] });expect(previousBeta(directly(draftNewest, 'read'))).toEqual({ prevBetaTag: 'v0.82.0-beta.8', recovered: ['a'] });});++ test('the stable listing carries the draft stable a contents: read token cannot see', async () => {+ const { recordedReleases, RELEASE_LIST_ARGS, STABLE_RELEASES_ARGS } = await import('../../scripts/compute-next-beta.mjs');+ const { parseReleaseListing } = await import('./shipped-fix-containment.mjs');+ const { env } = throughTheWorkflow(releaseWorkflow, draftNewest, RELEASE_LIST_ARGS[3]);+ expect(parseReleaseListing(recordedReleases(env)(STABLE_RELEASES_ARGS).stdout)).toEqual([+ { tag_name: 'v0.81.5', draft: true },+ { tag_name: 'v0.81.4', draft: false },+ ]);+ expect(parseReleaseListing(directly(draftNewest, 'read')(STABLE_RELEASES_ARGS).stdout)).toEqual([+ { tag_name: 'v0.81.4', draft: false },+ ]);+ });});test('the build job packs the only public workspace package and runs the only publish-time script it declares', () => {diff --git a/.github/scripts/select-beta-to-promote.test.mjs b/.github/scripts/select-beta-to-promote.test.mjsindex c8557b4fb..fc3d269c5 100644--- a/.github/scripts/select-beta-to-promote.test.mjs+++ b/.github/scripts/select-beta-to-promote.test.mjs@@ -948,7 +948,7 @@ describe('the selector entry points the two jobs run', () => {'.github/scripts/select-beta-to-promote.mjs','.github/scripts/shipped-fix-containment.mjs','scripts/compute-stable-version.mjs',- 'scripts/compute-next-beta.mjs',+ 'scripts/changeset-versions.mjs','scripts/git-clean-env.mjs',];const dirs = [];diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex 1b61dd27d..12c91dd84 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -145,8 +145,9 @@ jobs:platforms: ${{ steps.stage.outputs.platforms }}steps:- name: Link to triggering run- # Back-link: promote-stable forwards its run URL in- # client_payload.dispatched_by. Blank on manual / beta paths.+ # Back-link: client_payload.dispatched_by carries promote-stable.yml's+ # own run URL, or the dispatched_by that point-release.yml received+ # (blank when it ran by hand). Blank on manual / beta paths.env:DISPATCHED_BY: ${{ github.event.client_payload.dispatched_by }}run: |@@ -163,14 +164,15 @@ jobs:ref: ${{ github.event.client_payload.release_tag || inputs.release_tag }}fetch-depth: 0- # Detect channel from the release TAG (not package.json#version). Under- # the zero-commit-bump cadence (release.yml header lines 7-10), the- # tag is the only source of truth for the release's version — the- # public repo's commits at the tagged SHA carry the cycle-base version (e.g.- # `0.5.0-beta.5`), not the tag's version. Tag also drives manifest- # selection (beta-* vs latest-* channel files) for the stable-promotion- # case where tag (`v0.4.0`) and on-disk package.json (`0.4.0-beta.N`)- # diverge.+ # Detect channel from the release TAG (not package.json#version). No+ # release commits a version (release.yml's header describes the+ # transient override for each path), so the tag is the only source+ # of truth for the release's version — the public repo's commits at+ # the tagged SHA carry the version the last main reset wrote+ # (normally the previous stable), never the tag's and never a+ # `-beta.N`. Tag also drives manifest selection (beta-* vs latest-*+ # channel files), since tag (`v0.4.0` or `v0.4.0-beta.N`) and on-disk+ # package.json (`0.3.2`) always diverge.## Fail-fast on anything other than `-beta.*` or plain semver —# `-rc.*` / `-canary.*` etc. would ship manifests with a channel@@ -413,10 +415,10 @@ jobs:rustup toolchain install --no-self-updaterustc -vV- # PRD-6650: under the zero-commit-bump cadence (release.yml header- # lines 7-10), workspace package.json files on disk at the tagged SHA- # always lag the release tag. `tsdown` inlines- # `import pkgJson from "../package.json"` into+ # PRD-6650: no release commits a version (release.yml's header+ # describes the transient override), so workspace package.json+ # files on disk at the tagged SHA always lag the release tag.+ # `tsdown` inlines `import pkgJson from "../package.json"` into# `packages/cli/dist/constants-*.mjs` at build time, and# `packages/cli/build:skill-asset` composes + copies both# `packages/server/assets/skills/{project,discovery}/SKILL.md` intodiff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.ymlindex 21a8d4d13..8094d274b 100644--- a/.github/workflows/promote-stable.yml+++ b/.github/workflows/promote-stable.yml@@ -20,7 +20,7 @@ name: Promote stable# 4. Creates a non-prerelease GitHub Release at vX.Y.Z as a DRAFT.# desktop-release.yml fires automatically and builds the stable DMG with# --config.extraMetadata.version=X.Y.Z (override since the public repo's-# commit still has -beta.N in package.json).+# commit carries the previous stable's version in package.json).# 5. desktop-release.yml smokes that DMG, promotes the draft to published,# and only then dispatches publish-stable to release.yml, which promotes# the npm `latest` dist-tag using a transient package.json#versiondiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex e3c9c0429..d49390666 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -25,9 +25,11 @@ name: Release# 1. event_name=push (auto-cadence beta):# Fires when Copybara mirrors a commit touching `.changeset/**`.# Workflow:-# - Runs `compute-next-beta.mjs` to read `.changeset/*.md` + `pre.json`,-# compute the delta,-# and emit { baseVersion, maxBumpType, releaseNotes }. Empty delta+# - Runs `compute-next-beta.mjs` to read `.changeset/*.md`, the+# stable tags and which of their Releases are published, compute+# the delta, and emit { baseVersion, maxBumpType, releaseNotes }.+# The base is the newest stable tag bumped by the pending+# changesets its tree lacks. Empty delta# (e.g., Copybara import that only touched non-changeset files# matching the paths filter) → skip cleanly.# - Resolves -beta.N counter from existing vX.Y.Z-beta.* tags@@ -46,22 +48,22 @@ name: Release# to re-fire from the current# main HEAD without waiting for a new mirror import.#-# 3. repository_dispatch type=publish-stable (fired by promote-stable.yml-# on this same repo, once it has tagged vX.Y.Z + created the-# non-prerelease GitHub Release):+# 3. repository_dispatch type=publish-stable (fired by desktop-release.yml+# on this same repo, after its DMG smoke gate passes and it has+# published the vX.Y.Z GitHub Release that promote-stable.yml or+# point-release.yml drafted):# client_payload: { ref: "vX.Y.Z", version: "X.Y.Z" }# Workflow:-# - Checks out the stable tag (= the same SHA as the corresponding-# beta tag).+# - Checks out the stable tag (the promoted beta's SHA, or the+# synthetic commit a point release tags).# - Overrides every fixed-group package.json#version to the clean-# X.Y.Z (the public repo's commit at that SHA carries whatever-# agents-private mirrored, which is a `0.0.0` placeholder under-# the zero-commit-bump cadence).+# X.Y.Z (the public repo's commit at that SHA carries the version+# the last main reset wrote, normally the previous stable).# - Publishes @inkeep/[email protected] to npm with# `--tag latest --provenance`.-# promote-stable.yml separately fires its own `desktop-release`-# dispatch so the stable DMG + `latest-mac.yml` land on the stable-# Release.+# desktop-release.yml is dispatched by promote-stable.yml or+# point-release.yml; it lands the stable DMG + `latest-mac.yml` on the+# stable Release and then sends this one.## Why explicit `repository_dispatch` for the beta path here instead of# relying on `release: published` to cascade: GitHub deliberately@@ -105,7 +107,7 @@ env:jobs:read-releases:- name: Read the previous beta Release+ name: Read the previous beta Release and the stable Releasesruns-on: ubuntu-24.04cache-mode: nonetimeout-minutes: 5@@ -118,8 +120,11 @@ jobs:release_view_tag: ${{ steps.read.outputs.release_view_tag }}release_view_status: ${{ steps.read.outputs.release_view_status }}release_view_stdout: ${{ steps.read.outputs.release_view_stdout }}+ stable_releases_status: ${{ steps.read.outputs.stable_releases_status }}+ stable_releases_stdout: ${{ steps.read.outputs.stable_releases_stdout }}+ stable_releases_stderr: ${{ steps.read.outputs.stable_releases_stderr }}steps:- - name: Read the newest beta Release, drafts included, and its body+ - name: Read the newest beta Release and its body, and list the stable Releases, drafts includedif: github.event_name == 'push' || github.event_name == 'workflow_dispatch'id: readenv:@@ -153,6 +158,18 @@ jobs:record release_view_stdout "$view_stdout"fiecho "Previous beta Release: ${list_stdout:-none} (list exit ${list_status}${view_status:+, view exit ${view_status}})"+ stable_stderr_file=$(mktemp)+ if stable_stdout=$(gh api -X GET "repos/${GITHUB_REPOSITORY}/releases?per_page=100" --paginate --jq '.[] | select(.tag_name | test("^v[0-9]+[.][0-9]+[.][0-9]+$")) | {tag_name, draft}' 2>"$stable_stderr_file"); then+ stable_status=0+ else+ stable_status=$?+ fi+ stable_stderr=$(cat "$stable_stderr_file")+ cat "$stable_stderr_file" >&2+ record stable_releases_status "$stable_status"+ record stable_releases_stdout "$stable_stdout"+ record stable_releases_stderr "$stable_stderr"+ echo "Stable Release listing: exit ${stable_status}"build:name: Build + pack (${{ github.event.action || github.event_name }})@@ -169,7 +186,7 @@ jobs:version: ${{ steps.resolve-beta.outputs.version }}steps:- name: Link to triggering run- # Back-link: on the publish-stable path, promote-stable forwards its run+ # Back-link: on the publish-stable path, desktop-release forwards its run# URL in client_payload.dispatched_by. Blank on the beta push path.env:DISPATCHED_BY: ${{ github.event.client_payload.dispatched_by }}@@ -185,9 +202,9 @@ jobs:with:fetch-depth: 0persist-credentials: false- # publish-stable: client_payload.ref carries the stable tag- # created by promote-stable.yml (= same SHA as the source- # beta tag).+ # publish-stable: client_payload.ref carries the stable tag,+ # on the promoted beta's SHA or on the synthetic commit a+ # point release tags.# push / workflow_dispatch (beta path): no client_payload — fall# through to github.sha, which IS the just-pushed Copybara# import for `push` events (no race; this is the off-by-one@@ -309,14 +326,15 @@ jobs:# --- BETA PATH (push + workflow_dispatch) ---# Compute baseVersion + maxBumpType + rendered release notes locally- # from the changeset pile that Copybara mirrored into the just-pushed- # commit. compute-next-beta.mjs reads `.changeset/*.md` and `pre.json`;- # emits `{skip: true, reason}` when no new changesets exist- # since the last beta (e.g., a Copybara import that touched- # `.changeset/config.json` but no `.md` files, or main-reset- # consolidation cycles). The script MUTATES the working tree- # (pre.json + CHANGELOG.md + package.json + deletes .changeset/*.md);- # the final `Restore working tree` step cleans up.+ # from the changesets in the just-pushed commit that no published+ # stable tag's tree holds. compute-next-beta.mjs reads `.changeset/*.md`,+ # the stable tags (fetch-depth: 0 has them all) and the stable Release+ # listing read-releases recorded; emits `{skip: true, reason}` when no+ # new changesets exist since the last beta (e.g., a Copybara import+ # that touched `.changeset/config.json` but no `.md` files). The+ # script MUTATES the working tree (a transient pre.json + CHANGELOG.md+ # + package.json + deletes .changeset/*.md); the final `Restore+ # working tree` step cleans up.- name: Compute next beta base version + render release notesif: github.event_name == 'push' || github.event_name == 'workflow_dispatch'id: compute-beta@@ -327,6 +345,9 @@ jobs:RELEASE_VIEW_TAG: ${{ needs.read-releases.outputs.release_view_tag }}RELEASE_VIEW_STATUS: ${{ needs.read-releases.outputs.release_view_status }}RELEASE_VIEW_STDOUT: ${{ needs.read-releases.outputs.release_view_stdout }}+ STABLE_RELEASES_STATUS: ${{ needs.read-releases.outputs.stable_releases_status }}+ STABLE_RELEASES_STDOUT: ${{ needs.read-releases.outputs.stable_releases_stdout }}+ STABLE_RELEASES_STDERR: ${{ needs.read-releases.outputs.stable_releases_stderr }}run: |set -euo pipefailOUTPUT=$(node scripts/compute-next-beta.mjs)@@ -340,22 +361,6 @@ jobs:exit 0fiBASE=$(echo "$OUTPUT" | jq -r .baseVersion)- # Defer (don't fail) while the anchor is catching up to a fresh stable.- # Right after a stable promotion, pre.json's anchor still trails the- # just-shipped stable until main-reset advances it (a cross-repo PR +- # Copybara round-trip — minutes). Any mirror push landing in that window- # computes BASE == the fresh stable. Cutting it would regress `@latest`;- # hard-failing pages on a transient, self-healing condition. Skip this- # cut instead — a later push re-cuts automatically once the anchor leads.- # A base strictly BEHIND the stable is NOT this transient window; that is- # left to the Guard step below to hard-fail. fetch-depth:0 has all tags.- LATEST_STABLE_TAG=$(git tag --list 'v*' --sort=-v:refname \- | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n1 || true)- if [[ -n "$LATEST_STABLE_TAG" && "$BASE" == "${LATEST_STABLE_TAG#v}" ]]; then- echo "::warning::Beta base ${BASE} equals the latest stable ${LATEST_STABLE_TAG#v} — pre.json's anchor has not been advanced by main-reset yet. Deferring this beta cut; it re-cuts automatically once the anchor leads."- echo "skip=true" >> "$GITHUB_OUTPUT"- exit 0- fiBUMP=$(echo "$OUTPUT" | jq -r .maxBumpType)COUNT=$(echo "$OUTPUT" | jq -r .pendingCount)NOTES_B64=$(echo "$OUTPUT" | jq -r .releaseNotes | base64 | tr -d '\n')@@ -372,35 +377,6 @@ jobs:} >> "$GITHUB_OUTPUT"echo "Computed: base=$BASE bump=$BUMP pending=$COUNT"- # Anchor-drift backstop: the computed beta base must not be BEHIND the- # latest published stable. The common post-promotion case (base EQUAL to- # the fresh stable, anchor not yet advanced by main-reset) is now handled- # upstream in compute-beta as a deferred skip, so run_beta is only 'true'- # here when base != stable. A base strictly BEHIND stable is genuine anchor- # drift — not the transient window — and would cut a `-beta.N` that is- # semver-BEHIND `@latest`; fail loud with the recovery action. Uses the- # latest stable tag (no network) — fetch-depth:0 has all tags locally.- - name: Guard - beta base must lead the latest stable- if: steps.compute-beta.outputs.run_beta == 'true'- env:- BASE_VERSION: ${{ steps.compute-beta.outputs.base_version }}- run: |- set -euo pipefail- LATEST_STABLE_TAG=$(git tag --list 'v*' --sort=-v:refname \- | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n1 || true)- if [[ -z "$LATEST_STABLE_TAG" ]]; then- echo "No stable tag yet; skipping lead check (bootstrap)."- exit 0- fi- STABLE="${LATEST_STABLE_TAG#v}"- TOP=$(printf '%s\n%s\n' "$BASE_VERSION" "$STABLE" | sort -V | tail -n1)- if [[ "$TOP" != "$BASE_VERSION" ]]; then- echo "::error::Computed beta base ${BASE_VERSION} is BEHIND the latest stable ${STABLE} — genuine anchor drift, not the transient post-promotion window (base==stable is deferred upstream)."- echo "::error::Run public-open-knowledge-main-reset.yml with stable_version=${STABLE} on agents-private, then re-cut. If that reset fails its version guard, re-dispatch it with -f anchor_override=true (RELEASES.md, Recovering anchor drift)."- exit 1- fi- echo "Beta base ${BASE_VERSION} leads latest stable ${STABLE}."-# Resolve the -beta.N counter inside this concurrency slot so# concurrent push events (e.g., two rapid Copybara imports that each# carry a changeset) see different N's and never collide on tag@@ -579,26 +555,23 @@ jobs:exit 1fi- - name: Guard - beta base must lead the latest stable+ - name: Refuse a beta base that does not lead the newest stable tagif: needs.build.outputs.run_beta == 'true'env:BASE_VERSION: ${{ needs.build.outputs.base_version }}run: |set -euo pipefail- LATEST_STABLE_TAG=$(git tag --list 'v*' --sort=-v:refname \- | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | head -n1 || true)- if [[ -z "$LATEST_STABLE_TAG" ]]; then- echo "No stable tag yet; skipping lead check (bootstrap)."- exit 0+ NEWEST_STABLE=$(git tag --list 'v*' --sort=-version:refname | grep -E -m1 '^v[0-9]+\.[0-9]+\.[0-9]+$' || true)+ if [[ -z "$NEWEST_STABLE" ]]; then+ echo "::error::This checkout has no vX.Y.Z tag, so it cannot confirm that beta base ${BASE_VERSION} leads every stable."+ exit 1fi- STABLE="${LATEST_STABLE_TAG#v}"- TOP=$(printf '%s\n%s\n' "$BASE_VERSION" "$STABLE" | sort -V | tail -n1)- if [[ "$TOP" != "$BASE_VERSION" ]]; then- echo "::error::Computed beta base ${BASE_VERSION} is BEHIND the latest stable ${STABLE} — genuine anchor drift, not the transient post-promotion window (base==stable is deferred upstream)."- echo "::error::Run public-open-knowledge-main-reset.yml with stable_version=${STABLE} on agents-private, then re-cut. If that reset fails its version guard, re-dispatch it with -f anchor_override=true (RELEASES.md, Recovering anchor drift)."+ TOP=$(printf '%s\n%s\n' "$BASE_VERSION" "${NEWEST_STABLE#v}" | sort -V | tail -n1)+ if [[ "$BASE_VERSION" == "${NEWEST_STABLE#v}" || "$TOP" != "$BASE_VERSION" ]]; then+ echo "::error::The build job numbered this beta from base ${BASE_VERSION}, which does not lead the newest stable tag ${NEWEST_STABLE}: a stable was tagged after build ran. Use \"Re-run all jobs\", not \"Re-run failed jobs\", so build numbers the beta again."exit 1fi- echo "Beta base ${BASE_VERSION} leads latest stable ${STABLE}."+ echo "Beta base ${BASE_VERSION} leads the newest stable tag ${NEWEST_STABLE}."- name: Resolve -beta.N counterif: needs.build.outputs.run_beta == 'true'diff --git a/AGENTS.md b/AGENTS.mdindex 6b9db9f07..66ebccaca 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -89,9 +89,10 @@ Shell scripts are declared in scope by `no-comments.config.jsonc`, but the sweepEvery behavior-changing PR ships a `.changeset/<kebab-name>.md` file. The body becomes the user-facing entry on the next beta's GitHub Release and on the aggregated stable Release notes — that's how npm consumers and desktop auto-update users learn what changed. Write release-note copy, not a commit-message reprise.- Create one with `pnpm run changeset`, or hand-write a file named `.changeset/<descriptive-kebab-slug>.md`.+- Use a name no shipped changeset has used. A stable that carried the name counts it as released, so the new notes would never appear; the PR check refuses the file and asks for a rename.- Front-matter: at minimum `'@inkeep/open-knowledge': patch`. OpenKnowledge follows semver with a **pre-1.0 shift-down**: while we're below `1.0.0`, what semver would call a major (breaking API change) is encoded as `minor`, and what semver would call a minor (new feature) is encoded as `patch`. Most changesets are `patch`. `minor` is rare — reserve it for large API contract changes or large feature additions. **Never declare `major` pre-1.0** (see the `"//"` line in `.changeset/config.json`).-**Changelog authoring and review.** Use one short sentence for the user-visible outcome; a second only for a necessary qualification or upgrade action. Maximum 50 words per changeset body, across all paragraphs and bullets. Omit implementation details, internal identifiers and exhaustive edge cases; link migration instructions. Reviewers check accuracy, required actions and brevity; request technical detail in docs. Never split one explanation across changesets to evade the budget.+**Changelog authoring and review.** Use one short sentence for the user-visible outcome; a second only for a necessary qualification or upgrade action. Maximum 50 words per changeset body, across paragraphs and bullets. Omit implementation details, internal identifiers and exhaustive edge cases; link migration instructions. Reviewers check accuracy, required actions and brevity; request technical detail in docs. Never split one explanation across changesets to evade the budget.- Don't write inline references to sibling-package versions (e.g. `@inkeep/[email protected]`) — the fixed-group lock-step bumps are computed at release time and any number you'd write would be wrong.- Skip changesets for docs-only edits, test-only edits, or CI-only edits that don't change runtime behavior.diff --git a/scripts/changeset-versions.mjs b/scripts/changeset-versions.mjsnew file mode 100644index 000000000..cb962b2f0--- /dev/null+++ b/scripts/changeset-versions.mjs@@ -0,0 +1,49 @@+import { createRequire } from 'node:module';+import { join } from 'node:path';+import { fileURLToPath } from 'node:url';++export const FIXED_GROUP_ANCHOR = '@inkeep/open-knowledge';+const BUMP_RANK = { patch: 1, minor: 2, major: 3 };+const OK_ROOT = fileURLToPath(new URL('..', import.meta.url));++export function bumpSemver(version, type) {+ const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);+ if (!m) throw new Error(`Invalid version: ${version}`);+ const [major, minor, patch] = m.slice(1).map(Number);+ if (type === 'major') return `${major + 1}.0.0`;+ if (type === 'minor') return `${major}.${minor + 1}.0`;+ if (type === 'patch') return `${major}.${minor}.${patch + 1}`;+ throw new Error(`Invalid bump type: ${type}`);+}++export function maxBumpType(bumpTypes) {+ let max = 'patch';+ for (const t of bumpTypes) {+ if (t && BUMP_RANK[t] > BUMP_RANK[max]) max = t;+ }+ return max;+}++export function fixedGroupOf(config) {+ const group = (config?.fixed ?? []).find((members) => members.includes(FIXED_GROUP_ANCHOR));+ return group ?? [FIXED_GROUP_ANCHOR];+}++export function loadChangesets(root = OK_ROOT) {+ const cliRequire = createRequire(+ createRequire(join(root, 'package.json')).resolve('@changesets/cli/package.json'),+ );+ const readerRequire = createRequire(cliRequire.resolve('@changesets/read'));+ return {+ read: cliRequire('@changesets/read').default,+ parse: readerRequire('@changesets/parse').default,+ };+}++export function maxReleaseType(releases) {+ let maxType = null;+ for (const { type } of releases) {+ if (BUMP_RANK[type] && (!maxType || BUMP_RANK[type] > BUMP_RANK[maxType])) maxType = type;+ }+ return maxType;+}diff --git a/scripts/changeset-versions.test.mjs b/scripts/changeset-versions.test.mjsnew file mode 100644index 000000000..7bc40ec00--- /dev/null+++ b/scripts/changeset-versions.test.mjs@@ -0,0 +1,66 @@+import { describe, expect, test } from 'vitest';+import { bumpSemver, maxBumpType, maxReleaseType } from './changeset-versions.mjs';++describe('bumpSemver', () => {+ test('bumps each level', () => {+ expect(bumpSemver('0.5.0', 'patch')).toBe('0.5.1');+ expect(bumpSemver('0.5.0', 'minor')).toBe('0.6.0');+ expect(bumpSemver('0.4.7', 'major')).toBe('1.0.0');+ });++ test('minor/major zero out lower components', () => {+ expect(bumpSemver('0.5.3', 'minor')).toBe('0.6.0');+ expect(bumpSemver('1.2.3', 'major')).toBe('2.0.0');+ });++ test('throws on a non X.Y.Z version', () => {+ expect(() => bumpSemver('0.5', 'patch')).toThrow(/Invalid version/);+ expect(() => bumpSemver('0.5.0-beta.1', 'patch')).toThrow(/Invalid version/);+ });++ test('throws on an unknown bump type', () => {+ expect(() => bumpSemver('0.5.0', 'mega')).toThrow(/Invalid bump type/);+ });+});++describe('maxBumpType', () => {+ test('floors to patch on empty / null-only input', () => {+ expect(maxBumpType([])).toBe('patch');+ expect(maxBumpType([null, null])).toBe('patch');+ });++ test('returns the highest declared bump', () => {+ expect(maxBumpType(['patch', 'patch'])).toBe('patch');+ expect(maxBumpType(['patch', 'minor'])).toBe('minor');+ expect(maxBumpType(['minor', 'major', 'patch'])).toBe('major');+ expect(maxBumpType([null, 'minor', null])).toBe('minor');+ });+});++describe('maxReleaseType', () => {+ test('returns the max bump across the releases Changesets read from one changeset', () => {+ const releases = [+ { name: '@inkeep/open-knowledge', type: 'minor' },+ { name: '@inkeep/open-knowledge-app', type: 'patch' },+ ];+ expect(maxReleaseType(releases)).toBe('minor');+ });++ test('returns major when any release is major', () => {+ expect(maxReleaseType([{ name: '@inkeep/open-knowledge', type: 'major' }])).toBe('major');+ });++ test('returns null for a changeset that declares no release', () => {+ expect(maxReleaseType([])).toBeNull();+ });++ test('ignores a none release, which bumps nothing', () => {+ expect(maxReleaseType([{ name: '@inkeep/open-knowledge', type: 'none' }])).toBeNull();+ expect(+ maxReleaseType([+ { name: '@inkeep/open-knowledge', type: 'none' },+ { name: '@inkeep/open-knowledge-app', type: 'patch' },+ ]),+ ).toBe('patch');+ });+});diff --git a/scripts/check-no-major-changeset.mjs b/scripts/check-no-major-changeset.mjsindex 957569081..502686a01 100644--- a/scripts/check-no-major-changeset.mjs+++ b/scripts/check-no-major-changeset.mjs@@ -1,7 +1,7 @@import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';import { join } from 'node:path';import { fileURLToPath } from 'node:url';-import { loadChangesets } from './compute-next-beta.mjs';+import { loadChangesets } from './changeset-versions.mjs';const PASS = "No 'major' bumps in changesets.";const root = fileURLToPath(new URL('..', import.meta.url));diff --git a/scripts/compute-next-beta.mjs b/scripts/compute-next-beta.mjsindex 08bd58087..cfe375020 100644--- a/scripts/compute-next-beta.mjs+++ b/scripts/compute-next-beta.mjs@@ -1,63 +1,25 @@#!/usr/bin/env nodeimport { spawnSync } from 'node:child_process';-import { existsSync, readFileSync, writeFileSync } from 'node:fs';-import { createRequire } from 'node:module';-import { join } from 'node:path';-import { fileURLToPath, pathToFileURL } from 'node:url';+import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { pathToFileURL } from 'node:url';+import {+ createShippedFixCheck,+ parseReleaseListing,+} from '../.github/scripts/shipped-fix-containment.mjs';+import { bumpSemver, fixedGroupOf, loadChangesets, maxBumpType, maxReleaseType } from './changeset-versions.mjs';+import { gitAt, releasedChangesetIds } from './compute-stable-version.mjs';-export const FIXED_GROUP_ANCHOR = '@inkeep/open-knowledge';const PRE_PATH = '.changeset/pre.json';+const CONFIG_PATH = '.changeset/config.json';+const STABLE_TAG_RE = /^v\d+\.\d+\.\d+$/;const PUBLIC_REPO = process.env.GITHUB_REPOSITORY || 'inkeep/open-knowledge';const CHANGELOG_PKGS = ['cli', 'core', 'server', 'app', 'desktop'];const CONSUMED_MARKER_RE = /<!--\s*ok-consumed-set:\s*(\[[^\]]*\])\s*-->/;-const BUMP_RANK = { patch: 1, minor: 2, major: 3 };-const OK_ROOT = fileURLToPath(new URL('..', import.meta.url));function log(...args) {process.stderr.write(`${args.join(' ')}\n`);}-export function bumpSemver(version, type) {- const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);- if (!m) throw new Error(`Invalid version: ${version}`);- const [major, minor, patch] = m.slice(1).map(Number);- if (type === 'major') return `${major + 1}.0.0`;- if (type === 'minor') return `${major}.${minor + 1}.0`;- if (type === 'patch') return `${major}.${minor}.${patch + 1}`;- throw new Error(`Invalid bump type: ${type}`);-}--export function maxBumpType(bumpTypes) {- let max = 'patch';- for (const t of bumpTypes) {- if (t && BUMP_RANK[t] > BUMP_RANK[max]) max = t;- }- return max;-}--export function computeBaseVersion(anchor, bumpTypes) {- return bumpSemver(anchor, maxBumpType(bumpTypes));-}--export function loadChangesets(root = OK_ROOT) {- const cliRequire = createRequire(- createRequire(join(root, 'package.json')).resolve('@changesets/cli/package.json'),- );- const readerRequire = createRequire(cliRequire.resolve('@changesets/read'));- return {- read: cliRequire('@changesets/read').default,- parse: readerRequire('@changesets/parse').default,- };-}--export function maxReleaseType(releases) {- let maxType = null;- for (const { type } of releases) {- if (BUMP_RANK[type] && (!maxType || BUMP_RANK[type] > BUMP_RANK[maxType])) maxType = type;- }- return maxType;-}-export const RELEASE_LIST_ARGS = ['release','list',@@ -71,6 +33,16 @@ export const RELEASE_LIST_ARGS = ['[.[] | select(.isPrerelease) | select(.tagName | test("^v[0-9]+\\\\.[0-9]+\\\\.[0-9]+-beta\\\\.[0-9]+$")) | .tagName] | first // ""',];+export const STABLE_RELEASES_ARGS = [+ 'api',+ '-X',+ 'GET',+ `repos/${PUBLIC_REPO}/releases?per_page=100`,+ '--paginate',+ '--jq',+ '.[] | select(.tag_name | test("^v[0-9]+[.][0-9]+[.][0-9]+$")) | {tag_name, draft}',+];+export function releaseViewArgs(tag) {return ['release', 'view', tag, '--repo', PUBLIC_REPO, '--json', 'body', '--jq', '.body'];}@@ -93,6 +65,13 @@ export function recordedReleases(env) {if (env.RELEASE_VIEW_TAG && sameArgs(args, releaseViewArgs(env.RELEASE_VIEW_TAG))) {return { status: status('RELEASE_VIEW_STATUS'), stdout: env.RELEASE_VIEW_STDOUT, stderr: '' };}+ if (sameArgs(args, STABLE_RELEASES_ARGS)) {+ return {+ status: status('STABLE_RELEASES_STATUS'),+ stdout: env.STABLE_RELEASES_STDOUT,+ stderr: env.STABLE_RELEASES_STDERR,+ };+ }throw new Error(`the read-releases job recorded no result for gh ${args.join(' ')}`);};}@@ -137,6 +116,53 @@ export function previousBeta(gh) {return { prevBetaTag, recovered: prevBetaTag ? recoverConsumedSet(prevBetaTag, gh) : null };}+export function publishedStableTags(gh, readListing) {+ const unusable = (reason) => {+ console.error(+ `::warning::compute-next-beta: ${reason}. Counting every stable tag as released, so while the newest stable ` ++ "is still a draft this beta's notes and consumed set leave out that stable's changesets.",+ );+ return null;+ };+ const res = gh(STABLE_RELEASES_ARGS);+ if (res.status !== 0) {+ const stderr = String(res.stderr ?? '').trim().replace(/\s+/g, ' ').slice(0, 300);+ return unusable(`listing the stable Releases failed (exit ${res.status}${stderr ? `: ${stderr}` : ''})`);+ }+ try {+ return readListing(res.stdout);+ } catch (err) {+ return unusable(`the stable Release listing is unusable (${err instanceof Error ? err.message : String(err)})`);+ }+}++export function betaBase({ changesets, newestStableTag, releasedIds, anchorIds }) {+ if (!STABLE_TAG_RE.test(String(newestStableTag ?? ''))) {+ throw new Error(+ `'${newestStableTag}' is not a vX.Y.Z stable tag; a beta is numbered from the newest stable tag, ` ++ 'so the checkout needs every tag.',+ );+ }+ const pending = changesets.filter(({ id }) => !releasedIds.has(id));+ const beyondAnchor = pending.filter(({ id }) => !anchorIds.has(id));+ const bump = maxBumpType(beyondAnchor.map(({ releases }) => maxReleaseType(releases)));+ return {+ pending,+ beyondAnchorCount: beyondAnchor.length,+ maxBumpType: bump,+ baseVersion: bumpSemver(newestStableTag.slice(1), bump),+ };+}++export function transientPreState({ fixedGroup, anchorVersion, consumed }) {+ return {+ mode: 'pre',+ tag: 'beta',+ initialVersions: Object.fromEntries(fixedGroup.map((name) => [name, anchorVersion])),+ changesets: consumed,+ };+}+function readChangelogs() {const out = {};for (const pkg of CHANGELOG_PKGS) {@@ -250,28 +276,40 @@ export function renderNotes({ packageDeltas, newConsumedSet, prevBetaTag, newCou}async function main() {- const pre = JSON.parse(readFileSync(PRE_PATH, 'utf8'));- if (pre.mode !== 'pre') {- throw new Error(`Expected pre.json mode=pre, got mode=${pre.mode}`);- }- const anchor = pre.initialVersions?.[FIXED_GROUP_ANCHOR];- if (!anchor) {- throw new Error(`No initialVersion for ${FIXED_GROUP_ANCHOR} in pre.json`);- }+ const git = gitAt();+ const newestStableTag = git.newestStableTag();+ const gh = recordedReleases(process.env);const changesets = await loadChangesets().read(process.cwd());- if (changesets.length === 0) {+ const stableTags = new Set(git.stableTags());+ const publishedTags = publishedStableTags(gh, (stdout) =>+ createShippedFixCheck({+ listReleases: () => parseReleaseListing(stdout),+ git: { stableTags: () => stableTags },+ }).publishedStableTags(),+ );+ const { pending, beyondAnchorCount, maxBumpType: cycleMaxBump, baseVersion } = betaBase({+ changesets,+ newestStableTag,+ releasedIds: releasedChangesetIds(git, { releasedTags: publishedTags }),+ anchorIds: new Set(newestStableTag ? git.changesetIds(newestStableTag) : []),+ });+ log(+ `Beta base ${baseVersion}: ${cycleMaxBump} over the newest stable tag ${newestStableTag}, from ` ++ `${beyondAnchorCount} of ${pending.length} pending changesets (the rest are already in its tree). Released means ` ++ `in the tree of ${publishedTags === null ? 'any stable tag' : `one of ${publishedTags.length} published stable tags`}.`,+ );+ if (pending.length === 0) {console.log(JSON.stringify({ skip: true, reason: 'no pending changesets' }));return;}- const allIds = changesets.map(({ id }) => id);- const allIdsSet = new Set(allIds);+ const pendingIds = pending.map(({ id }) => id);+ const pendingSet = new Set(pendingIds);- const { prevBetaTag, recovered } = previousBeta(recordedReleases(process.env));- let priorConsumed = [];- if (recovered) priorConsumed = recovered.filter((id) => allIdsSet.has(id));+ const { prevBetaTag, recovered } = previousBeta(gh);+ const priorConsumed = recovered ? recovered.filter((id) => pendingSet.has(id)) : [];const priorSet = new Set(priorConsumed);- const newIds = allIds.filter((id) => !priorSet.has(id));+ const newIds = pendingIds.filter((id) => !priorSet.has(id));if (newIds.length === 0) {console.log(@@ -283,15 +321,22 @@ async function main() {return;}- const cycleBumpTypes = changesets.map(({ releases }) => maxReleaseType(releases));- const cycleMaxBump = maxBumpType(cycleBumpTypes);- const baseVersion = bumpSemver(anchor, cycleMaxBump);-const changelogsBefore = readChangelogs();+ for (const { id } of changesets) {+ if (!pendingSet.has(id)) rmSync(`.changeset/${id}.md`);+ }writeFileSync(PRE_PATH,- `${JSON.stringify({ ...pre, changesets: priorConsumed }, null, 2)}\n`,+ `${JSON.stringify(+ transientPreState({+ fixedGroup: fixedGroupOf(JSON.parse(readFileSync(CONFIG_PATH, 'utf8'))),+ anchorVersion: newestStableTag.slice(1),+ consumed: priorConsumed,+ }),+ null,+ 2,+ )}\n`,);const versionRes = spawnSync('pnpm', ['exec', 'changeset', 'version'], {@@ -322,6 +367,7 @@ async function main() {skip: false,baseVersion,maxBumpType: cycleMaxBump,+ newestStableTag,pendingCount: newIds.length,releaseNotes,}),@@ -329,5 +375,11 @@ async function main() {}if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {- await main();+ try {+ await main();+ } catch (err) {+ console.error(err);+ console.error(`::error::compute-next-beta: ${err instanceof Error ? err.message : String(err)}`);+ process.exitCode = 1;+ }}diff --git a/scripts/compute-next-beta.test.mjs b/scripts/compute-next-beta.test.mjsindex 3d7f3d541..8c9f91ec7 100644--- a/scripts/compute-next-beta.test.mjs+++ b/scripts/compute-next-beta.test.mjs@@ -1,22 +1,26 @@-import { execFileSync } from 'node:child_process';-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { fileURLToPath } from 'node:url';import { afterAll, describe, expect, test } from 'vitest';+import { configureTestGitRepository } from '../test-support/configure-git-fixture.test-helper.ts';+import { fixedGroupOf } from './changeset-versions.mjs';import {- bumpSemver,- computeBaseVersion,+ betaBase,extractDeltaSection,- maxBumpType,- maxReleaseType,parseSection,previousBeta,+ publishedStableTags,RELEASE_LIST_ARGS,recordedReleases,releaseViewArgs,renderNotes,+ STABLE_RELEASES_ARGS,+ transientPreState,} from './compute-next-beta.mjs';+import { releasedChangesetIds } from './compute-stable-version.mjs';+import { gitCleanEnv } from './git-clean-env.mjs';describe('extractDeltaSection', () => {test('returns content between first ## heading and second ## heading, excluding the heading line', () => {@@ -360,107 +364,6 @@ describe('round-trip: extractDeltaSection → parseSection → renderNotes', ()});});-describe('bumpSemver', () => {- test('bumps each level', () => {- expect(bumpSemver('0.5.0', 'patch')).toBe('0.5.1');- expect(bumpSemver('0.5.0', 'minor')).toBe('0.6.0');- expect(bumpSemver('0.4.7', 'major')).toBe('1.0.0');- });-- test('minor/major zero out lower components', () => {- expect(bumpSemver('0.5.3', 'minor')).toBe('0.6.0');- expect(bumpSemver('1.2.3', 'major')).toBe('2.0.0');- });-- test('throws on a non X.Y.Z version', () => {- expect(() => bumpSemver('0.5', 'patch')).toThrow(/Invalid version/);- expect(() => bumpSemver('0.5.0-beta.1', 'patch')).toThrow(/Invalid version/);- });-- test('throws on an unknown bump type', () => {- expect(() => bumpSemver('0.5.0', 'mega')).toThrow(/Invalid bump type/);- });-});--describe('maxBumpType', () => {- test('floors to patch on empty / null-only input', () => {- expect(maxBumpType([])).toBe('patch');- expect(maxBumpType([null, null])).toBe('patch');- });-- test('returns the highest declared bump', () => {- expect(maxBumpType(['patch', 'patch'])).toBe('patch');- expect(maxBumpType(['patch', 'minor'])).toBe('minor');- expect(maxBumpType(['minor', 'major', 'patch'])).toBe('major');- expect(maxBumpType([null, 'minor', null])).toBe('minor');- });-});--describe('computeBaseVersion — normative cadence vectors', () => {- const ANCHOR = '0.5.0';-- test('V1 — linear patches stay on one base', () => {- expect(computeBaseVersion(ANCHOR, ['patch'])).toBe('0.5.1');- expect(computeBaseVersion(ANCHOR, ['patch', 'patch'])).toBe('0.5.1');- expect(computeBaseVersion(ANCHOR, ['patch', 'patch', 'patch'])).toBe('0.5.1');- });-- test('V2 — a minor mid-cycle raises the base', () => {- expect(computeBaseVersion(ANCHOR, ['patch'])).toBe('0.5.1');- expect(computeBaseVersion(ANCHOR, ['patch', 'minor'])).toBe('0.6.0');- expect(computeBaseVersion(ANCHOR, ['patch', 'minor', 'patch'])).toBe('0.6.0');- });-- test('V3 — a major dominates the whole cycle', () => {- expect(computeBaseVersion(ANCHOR, ['major'])).toBe('1.0.0');- expect(computeBaseVersion(ANCHOR, ['major', 'minor'])).toBe('1.0.0');- expect(computeBaseVersion(ANCHOR, ['major', 'minor', 'patch'])).toBe('1.0.0');- });-- test('V4 — batched minors collapse to one minor base', () => {- expect(computeBaseVersion(ANCHOR, ['minor'])).toBe('0.6.0');- expect(computeBaseVersion(ANCHOR, ['minor', 'minor'])).toBe('0.6.0');- expect(computeBaseVersion(ANCHOR, ['minor', 'minor', 'patch'])).toBe('0.6.0');- });-- test('patch floor — a cycle with no recognizable bump still advances a patch', () => {- expect(computeBaseVersion(ANCHOR, [])).toBe('0.5.1');- expect(computeBaseVersion(ANCHOR, [null])).toBe('0.5.1');- });-- test('propagates an invalid anchor as a throw', () => {- expect(() => computeBaseVersion('0.5', ['patch'])).toThrow(/Invalid version/);- });-});--describe('maxReleaseType', () => {- test('returns the max bump across the releases Changesets read from one changeset', () => {- const releases = [- { name: '@inkeep/open-knowledge', type: 'minor' },- { name: '@inkeep/open-knowledge-app', type: 'patch' },- ];- expect(maxReleaseType(releases)).toBe('minor');- });-- test('returns major when any release is major', () => {- expect(maxReleaseType([{ name: '@inkeep/open-knowledge', type: 'major' }])).toBe('major');- });-- test('returns null for a changeset that declares no release', () => {- expect(maxReleaseType([])).toBeNull();- });-- test('ignores a none release, which bumps nothing', () => {- expect(maxReleaseType([{ name: '@inkeep/open-knowledge', type: 'none' }])).toBeNull();- expect(- maxReleaseType([- { name: '@inkeep/open-knowledge', type: 'none' },- { name: '@inkeep/open-knowledge-app', type: 'patch' },- ]),- ).toBe('patch');- });-});-describe('previousBeta reads the previous beta through the gh calls it is handed', () => {const TAG = 'v0.82.0-beta.8';const answering = (list, view) => (args) => {@@ -554,36 +457,351 @@ describe('recordedReleases replays what the read-releases job recorded', () => {});});-describe('the compute-next-beta CLI takes the previous beta from the read-releases job, never from gh', () => {- const root = mkdtempSync(join(tmpdir(), 'compute-next-beta-cli-'));- afterAll(() => rmSync(root, { recursive: true, force: true }));+describe('recordedReleases replays the stable Release listing the read-releases job recorded', () => {+ const listing = '{"tag_name":"v0.86.13","draft":true}\n{"tag_name":"v0.86.12","draft":false}';++ test('answers the listing call with its status, stdout and stderr', () => {+ const gh = recordedReleases({ STABLE_RELEASES_STATUS: '0', STABLE_RELEASES_STDOUT: listing, STABLE_RELEASES_STDERR: '' });+ expect(gh(STABLE_RELEASES_ARGS)).toEqual({ status: 0, stdout: listing, stderr: '' });+ });++ test('fails loudly when the listing status never reached the step', () => {+ expect(() => recordedReleases({ STABLE_RELEASES_STDOUT: listing })(STABLE_RELEASES_ARGS)).toThrow(+ "STABLE_RELEASES_STATUS is missing, not an exit status: the read-releases job's outputs did not reach this step",+ );+ });++ test('lists every stable Release with its draft flag, the shape the shipped-fix listing reads', () => {+ expect(STABLE_RELEASES_ARGS.slice(0, 3)).toEqual(['api', '-X', 'GET']);+ expect(STABLE_RELEASES_ARGS[3]).toMatch(/^repos\/[^/]+\/[^/]+\/releases\?per_page=100$/);+ expect(STABLE_RELEASES_ARGS).toContain('--paginate');+ expect(STABLE_RELEASES_ARGS.at(-1)).toBe(+ '.[] | select(.tag_name | test("^v[0-9]+[.][0-9]+[.][0-9]+$")) | {tag_name, draft}',+ );+ });+});++describe('publishedStableTags', () => {+ const ok = (stdout) => () => ({ status: 0, stdout, stderr: '' });++ test('reads the listing it is handed through the reader', () => {+ const seen = [];+ const tags = publishedStableTags(ok('LISTING'), (stdout) => {+ seen.push(stdout);+ return ['v0.86.12'];+ });+ expect(tags).toEqual(['v0.86.12']);+ expect(seen).toEqual(['LISTING']);+ });++ test('asks gh for exactly the stable Release listing', () => {+ const calls = [];+ publishedStableTags((args) => {+ calls.push(args);+ return { status: 0, stdout: '', stderr: '' };+ }, () => []);+ expect(calls).toEqual([STABLE_RELEASES_ARGS]);+ });++ test('a failed listing is null, which counts every stable tag as released', () => {+ expect(publishedStableTags(() => ({ status: 1, stdout: '', stderr: 'HTTP 502' }), () => ['never'])).toBeNull();+ });++ test('an unreadable listing is null rather than a throw', () => {+ expect(+ publishedStableTags(ok('not json'), () => {+ throw new Error('bad listing');+ }),+ ).toBeNull();+ });+});++const OK = '@inkeep/open-knowledge';+const changeset = (id, type = 'patch') => ({ id, releases: [{ name: OK, type }] });++function baseFor({ tags, published, commit }) {+ const git = { stableTags: () => Object.keys(tags), changesetIds: (tag) => tags[tag] ?? [] };+ const newestStableTag = Object.keys(tags).sort((a, b) => b.localeCompare(a, 'en', { numeric: true }))[0];+ const result = betaBase({+ changesets: commit.map(([id, type]) => changeset(id, type)),+ newestStableTag,+ releasedIds: releasedChangesetIds(git, { releasedTags: published }),+ anchorIds: new Set(tags[newestStableTag]),+ });+ return { ...result, pending: result.pending.map(({ id }) => id) };+}++describe('betaBase cadence vectors over the newest stable tag', () => {+ const base = (types) =>+ betaBase({+ changesets: types.map((type, i) => ({ id: `c${i}`, releases: type ? [{ name: '@inkeep/open-knowledge', type }] : [] })),+ newestStableTag: 'v0.5.0',+ releasedIds: new Set(),+ anchorIds: new Set(),+ }).baseVersion;++ test('V1 — linear patches stay on one base', () => {+ expect(base(['patch'])).toBe('0.5.1');+ expect(base(['patch', 'patch'])).toBe('0.5.1');+ expect(base(['patch', 'patch', 'patch'])).toBe('0.5.1');+ });++ test('V2 — a minor mid-cycle raises the base', () => {+ expect(base(['patch', 'minor'])).toBe('0.6.0');+ expect(base(['patch', 'minor', 'patch'])).toBe('0.6.0');+ });++ test('V3 — a major dominates the whole cycle', () => {+ expect(base(['major'])).toBe('1.0.0');+ expect(base(['major', 'minor', 'patch'])).toBe('1.0.0');+ });++ test('V4 — batched minors collapse to one minor base', () => {+ expect(base(['minor', 'minor'])).toBe('0.6.0');+ expect(base(['minor', 'minor', 'patch'])).toBe('0.6.0');+ });++ test('patch floor — a cycle with no recognizable bump still advances a patch', () => {+ expect(base([])).toBe('0.5.1');+ expect(base([null])).toBe('0.5.1');+ });+});++describe('betaBase numbers a beta from the newest stable tag and the changesets no published stable holds', () => {+ test('a pending patch over the newest stable tag is its next patch', () => {+ expect(+ baseFor({ tags: { 'v0.86.13': ['a'] }, published: ['v0.86.13'], commit: [['b', 'patch']] }),+ ).toMatchObject({ baseVersion: '0.86.14', maxBumpType: 'patch', pending: ['b'], beyondAnchorCount: 1 });+ });++ test('a pending minor is the next minor', () => {+ expect(+ baseFor({ tags: { 'v0.86.13': ['a'] }, published: ['v0.86.13'], commit: [['b', 'patch'], ['c', 'minor']] }),+ ).toMatchObject({ baseVersion: '0.87.0', maxBumpType: 'minor', pending: ['b', 'c'] });+ });++ test('a consumed changeset still on main counts as released, so its minor bumps nothing', () => {+ expect(+ baseFor({+ tags: { 'v0.86.0': ['a'] },+ published: ['v0.86.0'],+ commit: [['a', 'minor'], ['b', 'patch']],+ }),+ ).toMatchObject({ baseVersion: '0.86.1', maxBumpType: 'patch', pending: ['b'] });+ });++ test('a changeset some published stable held stays released after a revert drops it from later tags', () => {+ expect(+ baseFor({+ tags: { 'v0.85.0': ['r'], 'v0.86.0': [] },+ published: ['v0.85.0', 'v0.86.0'],+ commit: [['r', 'minor']],+ }),+ ).toMatchObject({ baseVersion: '0.86.1', pending: [] });+ });++ describe('while the newest stable tag is a draft', () => {+ const tags = { 'v0.86.12': ['x'], 'v0.86.13': ['x', 'y'] };+ const commit = [+ ['x', 'patch'],+ ['y', 'minor'],+ ['z', 'patch'],+ ];++ test('its changesets are pending for the notes but its own bump is already in its number', () => {+ expect(baseFor({ tags, published: ['v0.86.12'], commit })).toMatchObject({+ baseVersion: '0.86.14',+ maxBumpType: 'patch',+ pending: ['y', 'z'],+ beyondAnchorCount: 1,+ });+ });++ test('the base does not move when the draft publishes', () => {+ expect(baseFor({ tags, published: ['v0.86.12', 'v0.86.13'], commit })).toMatchObject({+ baseVersion: '0.86.14',+ pending: ['z'],+ });+ });++ test('a beta that holds only the draft changesets is still numbered past it', () => {+ expect(baseFor({ tags, published: ['v0.86.12'], commit: [['y', 'minor']] })).toMatchObject({+ baseVersion: '0.86.14',+ pending: ['y'],+ beyondAnchorCount: 0,+ });+ });++ test('an unreadable listing counts the draft as released', () => {+ expect(baseFor({ tags, published: null, commit })).toMatchObject({ baseVersion: '0.86.14', pending: ['z'] });+ });+ });++ test.each([[''], ['v0.86.13-beta.2'], [undefined]])('refuses %j as the newest stable tag', (tag) => {+ expect(() =>+ betaBase({ changesets: [], newestStableTag: tag, releasedIds: new Set(), anchorIds: new Set() }),+ ).toThrow(/is not a vX\.Y\.Z stable tag/);+ });+});++describe('transientPreState', () => {+ test('starts every fixed-group member at the newest stable version and carries the consumed set', () => {+ const config = { fixed: [['@inkeep/open-knowledge', '@inkeep/open-knowledge-core']] };+ expect(+ transientPreState({ fixedGroup: fixedGroupOf(config), anchorVersion: '0.86.13', consumed: ['a'] }),+ ).toEqual({+ mode: 'pre',+ tag: 'beta',+ initialVersions: { '@inkeep/open-knowledge': '0.86.13', '@inkeep/open-knowledge-core': '0.86.13' },+ changesets: ['a'],+ });+ });+});++describe('the compute-next-beta CLI numbers from the stable tags and reads only what the read-releases job recorded', () => {+ const roots = [];+ afterAll(() => {+ for (const root of roots) rmSync(root, { recursive: true, force: true });+ });const script = fileURLToPath(new URL('./compute-next-beta.mjs', import.meta.url));+ const changesetsCli = join(fileURLToPath(new URL('..', import.meta.url)), 'node_modules', '@changesets', 'cli', 'bin.js');++ function git(cwd, args) {+ const res = spawnSync('git', args, { cwd, env: gitCleanEnv(), encoding: 'utf8' });+ if (res.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${res.stderr}`);+ }- test('a recorded previous beta that consumed every pending changeset skips the cut without running gh', () => {+ function fixture({ tags = true } = {}) {+ const root = mkdtempSync(join(tmpdir(), 'compute-next-beta-cli-'));+ roots.push(root);mkdirSync(join(root, '.changeset'));writeFileSync(join(root, '.changeset', 'pre.json'),- JSON.stringify({ mode: 'pre', tag: 'beta', initialVersions: { '@inkeep/open-knowledge': '0.81.4' }, changesets: [] }),+ JSON.stringify({ mode: 'pre', tag: 'beta', initialVersions: { [OK]: '0.81.4' }, changesets: [] }),);- writeFileSync(join(root, '.changeset', 'fixture-change.md'), "---\n'@inkeep/open-knowledge': patch\n---\n\nFixture change.\n");+ writeFileSync(join(root, '.changeset', 'config.json'), JSON.stringify({ fixed: [[OK]] }));+ writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'fixture-root', private: true }));+ writeFileSync(join(root, 'pnpm-workspace.yaml'), 'packages:\n - packages/*\n');+ mkdirSync(join(root, 'packages', 'cli'), { recursive: true });+ writeFileSync(join(root, 'packages', 'cli', 'package.json'), JSON.stringify({ name: OK, version: '0.81.4' }));+ git(root, ['init', '-q', '-b', 'main']);+ configureTestGitRepository(root);+ const commit = (name, bump, body) => {+ writeFileSync(join(root, '.changeset', `${name}.md`), `---\n'${OK}': ${bump}\n---\n\n${body}\n`);+ git(root, ['add', '-A']);+ git(root, ['-c', 'user.name=t', '-c', '[email protected]', 'commit', '-q', '-m', name]);+ };+ commit('shipped', 'patch', 'Shipped in v0.86.12.');+ if (tags) git(root, ['tag', 'v0.86.12']);+ commit('drafted', 'minor', 'Drafted in v0.86.13.');+ if (tags) git(root, ['tag', 'v0.86.13']);+ commit('fixture-change', 'patch', 'A fresh fix.');+ symlinkSync(join(fileURLToPath(new URL('..', import.meta.url)), 'node_modules'), join(root, 'node_modules'));const bin = join(root, 'bin');mkdirSync(bin);const tripwire = join(root, 'gh-calls.log');writeFileSync(join(bin, 'gh'), `#!/bin/sh\necho "$*" >> '${tripwire}'\nexit 1\n`, { mode: 0o755 });- const out = execFileSync(process.execPath, [script], {+ writeFileSync(+ join(bin, 'pnpm'),+ `#!/bin/sh\n[ "$1" = exec ] && [ "$2" = changeset ] || { echo "unexpected pnpm $*" >&2; exit 97; }\nshift 2\nexec '${process.execPath}' '${changesetsCli}' "$@"\n`,+ { mode: 0o755 },+ );+ return { root, bin, tripwire };+ }++ const publishedThrough12 = {+ STABLE_RELEASES_STATUS: '0',+ STABLE_RELEASES_STDOUT: '{"tag_name":"v0.86.13","draft":true}\n{"tag_name":"v0.86.12","draft":false}',+ STABLE_RELEASES_STDERR: '',+ };++ const noPreviousBeta = { RELEASE_LIST_STATUS: '0', RELEASE_LIST_STDOUT: '', RELEASE_LIST_STDERR: '' };++ const previousBetaConsumed = (ids) => ({+ RELEASE_LIST_STATUS: '0',+ RELEASE_LIST_STDOUT: 'v0.86.14-beta.0',+ RELEASE_LIST_STDERR: '',+ RELEASE_VIEW_TAG: 'v0.86.14-beta.0',+ RELEASE_VIEW_STATUS: '0',+ RELEASE_VIEW_STDOUT: `Draft notes.\n<!-- ok-consumed-set: ${JSON.stringify(ids)} -->`,+ });++ function run({ root, bin }, env) {+ return spawnSync(process.execPath, [script], {cwd: root,encoding: 'utf8',- env: {- PATH: `${bin}:${process.env.PATH}`,- RELEASE_LIST_STATUS: '0',- RELEASE_LIST_STDOUT: 'v0.81.5-beta.0',- RELEASE_LIST_STDERR: '',- RELEASE_VIEW_TAG: 'v0.81.5-beta.0',- RELEASE_VIEW_STATUS: '0',- RELEASE_VIEW_STDOUT: 'Draft notes.\n<!-- ok-consumed-set: ["fixture-change"] -->',- },+ env: { PATH: `${bin}:${process.env.PATH}`, HOME: process.env.HOME, ...env },+ });+ }++ test('a cut while the newest stable is a draft is numbered past it and its notes keep the draft changesets', () => {+ const fx = fixture();+ const res = run(fx, { ...noPreviousBeta, ...publishedThrough12 });+ expect(res.status, res.stderr).toBe(0);+ const out = JSON.parse(res.stdout);+ expect(out).toMatchObject({+ skip: false,+ baseVersion: '0.86.14',+ maxBumpType: 'patch',+ newestStableTag: 'v0.86.13',+ pendingCount: 2,+ });+ expect(out.releaseNotes).toContain('- Drafted in v0.86.13.');+ expect(out.releaseNotes).toContain('- A fresh fix.');+ expect(out.releaseNotes).not.toContain('Shipped in v0.86.12.');+ expect(out.releaseNotes).toContain('<!-- ok-consumed-set: ["drafted","fixture-change"] -->');+ expect(existsSync(fx.tripwire)).toBe(false);+ });++ test("a cut after a previous beta renders only what that beta did not consume, and carries its consumed set forward", () => {+ const fx = fixture();+ const res = run(fx, { ...previousBetaConsumed(['drafted']), ...publishedThrough12 });+ expect(res.status, res.stderr).toBe(0);+ const out = JSON.parse(res.stdout);+ expect(out).toMatchObject({ skip: false, baseVersion: '0.86.14', pendingCount: 1 });+ expect(out.releaseNotes).toContain('- A fresh fix.');+ expect(out.releaseNotes).not.toContain('Drafted in v0.86.13.');+ expect(out.releaseNotes).toContain('<!-- ok-consumed-set: ["drafted","fixture-change"] -->');+ });++ test('a draft newest stable keeps its changesets pending and the stale anchor in pre.json is ignored', () => {+ const fx = fixture();+ const res = run(fx, { ...previousBetaConsumed(['drafted', 'fixture-change']), ...publishedThrough12 });+ expect(res.status, res.stderr).toBe(0);+ expect(JSON.parse(res.stdout)).toEqual({ skip: true, reason: 'no new changesets since v0.86.14-beta.0' });+ expect(res.stderr).toContain(+ 'Beta base 0.86.14: patch over the newest stable tag v0.86.13, from 1 of 2 pending changesets',+ );+ expect(res.stderr).toContain('in the tree of one of 1 published stable tags');+ expect(existsSync(fx.tripwire)).toBe(false);+ });++ test('a failed stable listing warns and counts every stable tag as released', () => {+ const fx = fixture();+ const res = run(fx, {+ ...previousBetaConsumed(['fixture-change']),+ STABLE_RELEASES_STATUS: '1',+ STABLE_RELEASES_STDOUT: '',+ STABLE_RELEASES_STDERR: 'HTTP 502',+ });+ expect(res.status, res.stderr).toBe(0);+ expect(JSON.parse(res.stdout)).toEqual({ skip: true, reason: 'no new changesets since v0.86.14-beta.0' });+ expect(res.stderr).toContain('::warning::compute-next-beta: listing the stable Releases failed (exit 1: HTTP 502). Counting every stable tag as released');+ expect(res.stderr).toContain('from 1 of 1 pending changesets');+ expect(res.stderr).toContain('in the tree of any stable tag');+ expect(existsSync(fx.tripwire)).toBe(false);+ });++ test('a checkout without stable tags refuses to number a beta', () => {+ const fx = fixture({ tags: false });+ const res = run(fx, {+ ...previousBetaConsumed([]),+ STABLE_RELEASES_STATUS: '0',+ STABLE_RELEASES_STDOUT: '',+ STABLE_RELEASES_STDERR: '',});- expect(JSON.parse(out)).toEqual({ skip: true, reason: 'no new changesets since v0.81.5-beta.0' });- expect(existsSync(tripwire)).toBe(false);+ expect(res.status).not.toBe(0);+ expect(res.stderr).toContain("'' is not a vX.Y.Z stable tag");+ expect(existsSync(fx.tripwire)).toBe(false);});});diff --git a/scripts/compute-stable-version.mjs b/scripts/compute-stable-version.mjsindex d3782a8b7..1e861f4b2 100644--- a/scripts/compute-stable-version.mjs+++ b/scripts/compute-stable-version.mjs@@ -1,9 +1,9 @@#!/usr/bin/env nodeimport { spawnSync } from 'node:child_process';-import { appendFileSync, readFileSync } from 'node:fs';+import { appendFileSync } from 'node:fs';import { pathToFileURL } from 'node:url';import { gitCleanEnv } from './git-clean-env.mjs';-import { FIXED_GROUP_ANCHOR, bumpSemver, loadChangesets, maxBumpType, maxReleaseType } from './compute-next-beta.mjs';+import { bumpSemver, loadChangesets, maxBumpType, maxReleaseType } from './changeset-versions.mjs';const BETA_TAG_RE = /^v\d+\.\d+\.\d+-beta\.\d+$/;const STABLE_TAG_RE = /^v\d+\.\d+\.\d+$/;@@ -104,56 +104,6 @@ export function computePointReleaseVersion({ syntheticSha, latestStableTag, latereturn { version, tag: `v${version}`, latestStableVersion, addedIds, removedIds, bump };}-export function evaluateAnchorGuard({ anchorVersion, latestStableTag }) {- const anchor = String(anchorVersion ?? '').trim();- if (!/^\d+\.\d+\.\d+$/.test(anchor)) {- throw new Error(`anchor version '${anchorVersion}' is not a bare X.Y.Z version.`);- }- const tag = String(latestStableTag ?? '').trim();- if (tag === '') {- return {- ok: true,- anchorVersion: anchor,- latestStableVersion: '',- drift: 'bootstrap',- reason: `No stable tag exists yet; the anchor (${anchor}) cannot be stale against it.`,- };- }- if (!STABLE_TAG_RE.test(tag)) {- throw new Error(`latest stable tag '${latestStableTag}' is not in the expected vX.Y.Z format.`);- }- const latestStableVersion = tag.slice(1);- if (anchor === latestStableVersion) {- return {- ok: true,- anchorVersion: anchor,- latestStableVersion,- drift: 'none',- reason: `Anchor ${anchor} matches the newest stable ${tag}.`,- };- }- const drift = compareVersions(anchor, latestStableVersion) < 0 ? 'behind' : 'ahead';- return {- ok: false,- anchorVersion: anchor,- latestStableVersion,- drift,- reason:- drift === 'behind'- ? `Anchor ${anchor} is behind the newest stable ${tag}; a main-reset consolidation is still pending.`- : `Anchor ${anchor} is ahead of the newest stable ${tag}; a consolidation advanced without a matching stable tag.`,- };-}--function compareVersions(a, b) {- const pa = a.split('.').map(Number);- const pb = b.split('.').map(Number);- for (let i = 0; i < 3; i++) {- if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1;- }- return 0;-}-export function runGit(args, cwd) {const res = spawnSync('git', args, { cwd, encoding: 'utf8', env: gitCleanEnv() });if (res.status !== 0) {@@ -300,50 +250,6 @@ export const recordBumpVerdicts = (git, verdicts) => recordVerdicts(git, 'bumpTyexport const withBumpVerdicts = (git, verdicts) =>withVerdicts(git, 'bumpTypeOf', verdicts, BUMP_VERDICTS);-export function readAnchorVersion() {- const pre = JSON.parse(readFileSync('.changeset/pre.json', 'utf8'));- if (pre.mode !== 'pre') {- throw new Error(`Expected .changeset/pre.json mode=pre, got mode=${pre.mode}; the anchor is not meaningful.`);- }- const anchor = pre.initialVersions?.[FIXED_GROUP_ANCHOR];- if (!anchor) throw new Error(`No initialVersion for ${FIXED_GROUP_ANCHOR} in .changeset/pre.json`);- return anchor;-}--function anchorGuardMain() {- let result;- try {- result = evaluateAnchorGuard({- anchorVersion: readAnchorVersion(),- latestStableTag: realGit.newestStableTag(),- });- } catch (err) {- console.error(`::error::compute-stable-version --anchor-guard: ${err.message}`);- process.exit(1);- }-- console.log(JSON.stringify(result));-- if (process.env.GITHUB_OUTPUT) {- appendFileSync(- process.env.GITHUB_OUTPUT,- [- `anchor_ok=${result.ok ? 'true' : 'false'}`,- `anchor_version=${result.anchorVersion}`,- `latest_stable_version=${result.latestStableVersion}`,- `anchor_drift=${result.drift}`,- '',- ].join('\n'),- );- }-- if (!result.ok) {- console.error(`::error::${result.reason}`);- process.exit(2);- }- log(result.reason);-}-function pointReleaseMain() {let result;try {@@ -388,11 +294,6 @@ function pointReleaseMain() {}function main() {- if (process.argv[2] === '--anchor-guard') {- anchorGuardMain();- return;- }-if (process.argv[2] === '--point-release') {pointReleaseMain();return;diff --git a/scripts/compute-stable-version.test.mjs b/scripts/compute-stable-version.test.mjsindex f998b3786..478312953 100644--- a/scripts/compute-stable-version.test.mjs+++ b/scripts/compute-stable-version.test.mjs@@ -5,12 +5,11 @@ import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { afterEach, describe, expect, test } from 'vitest';import { configureTestGitRepository } from '../test-support/configure-git-fixture.test-helper.ts';-import { loadChangesets, maxReleaseType } from './compute-next-beta.mjs';+import { loadChangesets, maxReleaseType } from './changeset-versions.mjs';import {changesetIdsFromTreePaths,computePointReleaseVersion,computeStablePromotion,- evaluateAnchorGuard,gitAt,parseBumpVerdicts,recordBumpVerdicts,@@ -160,78 +159,6 @@ describe('releasedChangesetIds', () => {});});-describe('evaluateAnchorGuard', () => {- test('level anchor passes', () => {- expect(evaluateAnchorGuard({ anchorVersion: '0.41.0', latestStableTag: 'v0.41.0' })).toMatchObject({- ok: true,- drift: 'none',- anchorVersion: '0.41.0',- latestStableVersion: '0.41.0',- });- });-- test('anchor behind the newest stable fails and names the pending consolidation', () => {- const r = evaluateAnchorGuard({ anchorVersion: '0.41.0', latestStableTag: 'v0.41.1' });- expect(r.ok).toBe(false);- expect(r.drift).toBe('behind');- expect(r.reason).toMatch(/main-reset consolidation is still pending/);- });-- test('anchor ahead of the newest stable fails and is reported as a different shape', () => {- const r = evaluateAnchorGuard({ anchorVersion: '0.42.0', latestStableTag: 'v0.41.0' });- expect(r.ok).toBe(false);- expect(r.drift).toBe('ahead');- expect(r.reason).toMatch(/ahead of the newest stable/);- });-- test('compares numerically, not lexically, across a double-digit component', () => {- expect(evaluateAnchorGuard({ anchorVersion: '0.9.0', latestStableTag: 'v0.10.0' }).drift).toBe('behind');- expect(evaluateAnchorGuard({ anchorVersion: '0.35.10', latestStableTag: 'v0.35.9' }).drift).toBe('ahead');- expect(evaluateAnchorGuard({ anchorVersion: '0.35.10', latestStableTag: 'v0.35.10' }).ok).toBe(true);- });-- test('bootstrap: no stable tag yet cannot be stale', () => {- expect(evaluateAnchorGuard({ anchorVersion: '0.1.0', latestStableTag: '' })).toMatchObject({- ok: true,- drift: 'bootstrap',- latestStableVersion: '',- });- });-- test('tolerates surrounding whitespace from raw git / json input', () => {- expect(evaluateAnchorGuard({ anchorVersion: ' 0.41.0 ', latestStableTag: 'v0.41.0\n' }).ok).toBe(true);- });-- test('a malformed anchor throws rather than reporting drift', () => {- expect(() => evaluateAnchorGuard({ anchorVersion: '0.41', latestStableTag: 'v0.41.0' })).toThrow(- /bare X\.Y\.Z version/,- );- expect(() => evaluateAnchorGuard({ anchorVersion: undefined, latestStableTag: 'v0.41.0' })).toThrow(- /bare X\.Y\.Z version/,- );- expect(() => evaluateAnchorGuard({ anchorVersion: 'v0.41.0', latestStableTag: 'v0.41.0' })).toThrow(- /bare X\.Y\.Z version/,- );- });-- test('a malformed stable tag throws rather than reporting drift', () => {- expect(() => evaluateAnchorGuard({ anchorVersion: '0.41.0', latestStableTag: 'v0.41.0-beta.3' })).toThrow(- /vX\.Y\.Z format/,- );- expect(() => evaluateAnchorGuard({ anchorVersion: '0.41.0', latestStableTag: 'garbage' })).toThrow(- /vX\.Y\.Z format/,- );- });-- test('reports only: it never sleeps, retries, or mutates', () => {- const before = Date.now();- const a = evaluateAnchorGuard({ anchorVersion: '0.41.0', latestStableTag: 'v0.41.1' });- const b = evaluateAnchorGuard({ anchorVersion: '0.41.0', latestStableTag: 'v0.41.1' });- expect(a).toEqual(b);- expect(Date.now() - before).toBeLessThan(500);- });-});-describe('computePointReleaseVersion', () => {test('cherry-pick mode: one patch fix over the latest stable lands on the next patch', () => {const git = fakeGit({ changesets: { S: ['c0'], SYN: ['c0', 'fix1'] } });@@ -476,6 +403,35 @@ describe('gitAt reads a commit\'s changesets the way Changesets reads the same texpect(gitAt(root).changesetIds('v1.1.0')).toEqual(['plain']);});+ test('newestStableTag orders by version, not by string order', () => {+ const root = committedChangesets({ 'plain.md': bump(`"${OK}": patch`) });+ for (const tag of ['v0.86.10', 'v0.86.9', 'v0.86.11-beta.0', 'v0.9.99'])+ git(root, ['tag', tag]);+ expect(gitAt(root).newestStableTag()).toBe('v0.86.10');+ });++ test('newestStableTag orders by version, not by creation order', () => {+ const root = committedChangesets({ 'plain.md': bump(`"${OK}": patch`) });+ const created = [+ ['v0.86.1', '2026-01-01T00:00:00Z'],+ ['v0.86.10', '2026-01-02T00:00:00Z'],+ ['v0.86.9', '2026-01-03T00:00:00Z'],+ ];+ for (const [tag, date] of created) {+ const res = spawnSync(+ 'git',+ ['-c', 'user.name=t', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', tag],+ { cwd: root, env: { ...gitCleanEnv(), GIT_COMMITTER_DATE: date, GIT_AUTHOR_DATE: date }, encoding: 'utf8' },+ );+ expect(res.status, res.stderr).toBe(0);+ git(root, ['tag', tag]);+ }+ for (const key of ['creatordate', '-creatordate', 'refname', '-refname']) {+ expect(git(root, ['tag', '--list', 'v*', `--sort=${key}`]).split('\n')[0], key).not.toBe('v0.86.10');+ }+ expect(gitAt(root).newestStableTag()).toBe('v0.86.10');+ });+test('a changeset Changesets cannot parse fails the read instead of counting as no bump', () => {const root = committedChangesets({ 'broken.md': bump(`"${OK}": Major`) });expect(() => gitAt(root).bumpTypeOf('HEAD', 'broken')).toThrow();@@ -528,7 +484,7 @@ describe('bump verdicts carry a read from one job to another by blob id', () =>describe('the promote job computes the stable version with no node_modules at all', () => {const SCRIPTS = dirname(fileURLToPath(import.meta.url));- const SCRIPT_FILES = ['compute-stable-version.mjs', 'compute-next-beta.mjs', 'git-clean-env.mjs'];+ const SCRIPT_FILES = ['compute-stable-version.mjs', 'changeset-versions.mjs', 'git-clean-env.mjs'];function promotionFixture() {const root = mkdtempSync(join(tmpdir(), 'stable-version-promotion-'));diff --git a/scripts/render-stable-notes.mjs b/scripts/render-stable-notes.mjsindex 91c52664b..25b206090 100644--- a/scripts/render-stable-notes.mjs+++ b/scripts/render-stable-notes.mjs@@ -5,7 +5,7 @@ import {createShippedFixCheck,parseReleaseListing,} from '../.github/scripts/shipped-fix-containment.mjs';-import { FIXED_GROUP_ANCHOR, loadChangesets, maxReleaseType } from './compute-next-beta.mjs';+import { FIXED_GROUP_ANCHOR, fixedGroupOf, loadChangesets, maxReleaseType } from './changeset-versions.mjs';import {gitAt,parseVerdicts,@@ -45,11 +45,6 @@ export function changesetSummary(text) {return match[2].trim();}-export function fixedGroupOf(config) {- const group = (config?.fixed ?? []).find((members) => members.includes(FIXED_GROUP_ANCHOR));- return group ?? [FIXED_GROUP_ANCHOR];-}-export function noteLevel(releases, fixedGroup) {const cli = releases.filter(({ name, type }) => name === FIXED_GROUP_ANCHOR && type !== 'none');return maxReleaseType(diff --git a/scripts/render-stable-notes.test.mjs b/scripts/render-stable-notes.test.mjsindex 2298d707e..5e5f01ffe 100644--- a/scripts/render-stable-notes.test.mjs+++ b/scripts/render-stable-notes.test.mjs@@ -18,12 +18,12 @@ import {NOTES_SOURCE_MARKER as DOCS_NOTES_SOURCE_MARKER,markedNotes,} from '../docs/src/lib/releases.ts';+import { fixedGroupOf } from './changeset-versions.mjs';import { gitCleanEnv } from './git-clean-env.mjs';import {changesetSummary,collectStableNotes,EMPTY_NOTES,- fixedGroupOf,NOTES_SOURCE_MARKER,noteLevel,noteReaderAt,@@ -522,7 +522,7 @@ describe('the release job renders the notes with no node_modules at all', () =>const SCRIPT_FILES = ['render-stable-notes.mjs','compute-stable-version.mjs',- 'compute-next-beta.mjs',+ 'changeset-versions.mjs','git-clean-env.mjs',];