Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Add the Open Knowledge point-release lane with revert mode (#2958)

Andrew Mikofalvy39a369cc5560
diff --git a/.github/scripts/point-release-plan.mjs b/.github/scripts/point-release-plan.mjs
new file mode 100644
index 000000000..015c92cd5
--- /dev/null
+++ b/.github/scripts/point-release-plan.mjs
@@ -0,0 +1,766 @@
+#!/usr/bin/env node
+/**
+ * Preconditions for the point-release lane: the checks that decide whether
+ * `lastStable + one fix` may be tagged and published as the new `latest`.
+ *
+ * Why they are predicates in a module rather than steps in the workflow. Every
+ * one of them must hold BEFORE a tag exists, because the cascade they gate is
+ * not reversible: once the tag is pushed and the GitHub Release is created, a
+ * downstream refusal leaves a half-shipped state (a stable tag users can see,
+ * no npm publish) on the exact channel this lane exists to repair. Written as
+ * pure functions over an injected boundary, each one can be proven to refuse in
+ * a unit test with no repo, no tags, and no network, which is the only way to
+ * have any confidence in a path that is exercised a handful of times a year and
+ * always under time pressure.
+ *
+ * Each guard returns `{ ok, code, message }` and every refusing `code` is
+ * distinct, so an operator reading a failed run learns which precondition broke
+ * rather than that "the point release failed".
+ */
+import { spawnSync } from 'node:child_process';
+import { appendFileSync } from 'node:fs';
+import { pathToFileURL } from 'node:url';
+import {
+ computePointReleaseVersion,
+ evaluateAnchorGuard,
+ readAnchorVersion,
+ realGit,
+ runGit,
+} from '../../scripts/compute-stable-version.mjs';
+
+function refuse(code, message) {
+ return { ok: false, code, message };
+}
+
+function pass(message) {
+ return { ok: true, code: null, message };
+}
+
+/**
+ * Is the changeset anchor still level with the newest stable tag?
+ *
+ * Delegates wholly to `evaluateAnchorGuard`, which owns the drift comparison
+ * for every version-computing path; a second implementation here would drift
+ * from it and disagree about the same repo state. This wrapper only adapts its
+ * verdict to the guard shape.
+ *
+ * A refusal is final for this run. The lane holds the shared release-cadence
+ * lock, so waiting out a pending main-reset here would block every beta cut and
+ * promotion that the reset itself has to travel through, which is the deadlock
+ * `evaluateAnchorGuard`'s contract exists to prevent.
+ */
+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.',
+ );
+ }
+ return pass(verdict.reason);
+}
+
+/**
+ * Split the operator's `fix_refs` input into individual refs.
+ *
+ * Commas and whitespace are both accepted because the input arrives from a
+ * `workflow_dispatch` text box, where an operator pasting two SHAs separates
+ * them with whichever they reach for first. Duplicates are collapsed rather
+ * than applied twice: a ref repeated by a copy-paste slip would otherwise
+ * cherry-pick cleanly the first time and hard-fail as an empty pick the second,
+ * which reads like a conflict rather than like the typo it is.
+ *
+ * An input that parses to nothing throws instead of returning `[]`. Zero refs
+ * would otherwise build a synthetic commit identical to the last stable and cut
+ * a release containing no change at all.
+ */
+export function parseFixRefs(raw) {
+ const refs = splitList(raw);
+ if (refs.length === 0) {
+ throw new Error(`no fix ref found in '${raw ?? ''}' (expected one or more commit SHAs, comma or space separated)`);
+ }
+ return refs;
+}
+
+/**
+ * Split the operator's `anchor_delta_ids` input into changeset ids.
+ *
+ * Unlike `parseFixRefs` this returns an empty list rather than throwing: the
+ * input is optional, and "the operator named nothing" is a decision the caller
+ * makes (skip the main-reset dispatch), not an error.
+ *
+ * JSON array punctuation is stripped so an operator can paste a prior run's
+ * `delta_ids` output verbatim. `["a","b"]` and `a, b` are the same list;
+ * changeset ids are word-shaped, so nothing legitimate is lost.
+ */
+export function parseDeltaIds(raw) {
+ return splitList(raw);
+}
+
+function splitList(raw) {
+ const items = [];
+ for (const piece of String(raw ?? '').split(/[\s,[\]"']+/)) {
+ const item = piece.trim();
+ if (item !== '' && !items.includes(item)) items.push(item);
+ }
+ return items;
+}
+
+/**
+ * Is every fix ref already contained in the public repo's `main`?
+ *
+ * A point release ships ahead of the soak, so its content must still be code
+ * that landed through the normal review path. A ref that is not on `main` is
+ * either a typo or an attempt to ship unreviewed work straight to the default
+ * install channel, and this lane is the one place where that would not be
+ * caught downstream.
+ *
+ * Every offender is named, not just the first: an operator who mistyped two of
+ * three refs should learn that in one run rather than one refusal at a time.
+ * `isOnMain` is injected and any throw propagates, because an unreadable ref is
+ * an infra failure and silently reading it as "not on main" would refuse a
+ * legitimate release with a message pointing at the wrong problem.
+ */
+export function guardRefsOnMain({ fixRefs, isOnMain }) {
+ const offenders = fixRefs.filter((ref) => !isOnMain(ref));
+ if (offenders.length > 0) {
+ return refuse(
+ 'ref-not-on-main',
+ `Not contained in main: ${offenders.join(', ')}. A point release may only ship commits that ` +
+ 'already landed on main through review; check for a typo, or land the fix first.',
+ );
+ }
+ return pass(`All ${fixRefs.length} fix ref(s) are contained in main.`);
+}
+
+/**
+ * Is the computed tag still free?
+ *
+ * An occupied tag means the version arithmetic landed on a release that already
+ * exists, which happens when a concurrent promotion won the race between the
+ * version being computed and this run reaching the push. Pushing anyway either
+ * fails at the remote or, worse, moves a tag users have already installed from.
+ */
+export function guardTagFree({ tag, tagExists }) {
+ if (tagExists(tag)) {
+ return refuse(
+ 'tag-exists',
+ `Tag ${tag} already exists. Either another release reached this version first, in which case ` +
+ 're-run so the version is recomputed against the current stable, or a prior run of this lane ' +
+ 'pushed the tag and then failed before finishing its cascade, in which case see RELEASES.md, ' +
+ '"Recovery: a point release failed partway" — that state needs the tag removed, not a re-run.',
+ );
+ }
+ return pass(`Tag ${tag} is free.`);
+}
+
+/**
+ * Does the synthetic commit's changeset delta contain exactly the applied fix
+ * and nothing else?
+ *
+ * This is the check that the release is actually isolated from the unsoaked
+ * pile. The version arithmetic upstream is a set difference against the last
+ * stable, so anything that leaked into the synthetic tree, an unrelated
+ * changeset dragged along by an over-broad ref, is indistinguishable from the
+ * fix at that layer and would ship unsoaked work under a patch bump.
+ *
+ * `fixChangesetIds` is the union of the changesets each fix ref introduced on
+ * its own, so the comparison is over sets: pick order is git's, not the
+ * operator's, and ordering carries no meaning here.
+ *
+ * Revert mode expects an EMPTY delta and ignores `fixChangesetIds`. A revert
+ * restores shipped behavior and adds no changeset; if reverting produced one,
+ * the operator named a ref that adds work rather than removing it.
+ */
+export function guardDeltaMatchesFix({ mode, addedIds, fixChangesetIds }) {
+ if (mode === 'revert') {
+ if (addedIds.length > 0) {
+ return refuse(
+ 'delta-mismatch',
+ `Revert mode added changesets: ${addedIds.join(', ')}. A revert removes work and must add none; ` +
+ 'the named ref probably is not the commit that introduced the bug.',
+ );
+ }
+ return pass('Revert added no changeset, as expected.');
+ }
+
+ const expected = new Set(fixChangesetIds);
+ const actual = new Set(addedIds);
+ const unexpected = [...actual].filter((id) => !expected.has(id));
+ const missing = [...expected].filter((id) => !actual.has(id));
+ if (unexpected.length > 0 || missing.length > 0) {
+ const parts = [];
+ if (unexpected.length > 0) parts.push(`unrelated changesets came along: ${unexpected.join(', ')}`);
+ if (missing.length > 0) parts.push(`the fix's own changesets are absent: ${missing.join(', ')}`);
+ return refuse(
+ 'delta-mismatch',
+ `The synthetic commit's changeset delta is not exactly the picked fix (${parts.join('; ')}). ` +
+ 'Shipping it would carry unsoaked work onto the default install channel.',
+ );
+ }
+ return pass(`Delta is exactly the picked fix (${addedIds.length} changeset(s)).`);
+}
+
+/**
+ * Is this release a patch?
+ *
+ * A point release exists to ship one self-contained fix over the current
+ * stable, and it deliberately skips the soak. A minor or major bump means the
+ * delta carries a feature or a break, which is the pile's work and belongs in
+ * the normal promotion path where it gets soaked.
+ */
+export function guardPatchOnly({ bump }) {
+ if (bump !== 'patch') {
+ return refuse(
+ 'bump-not-patch',
+ `Computed bump is '${bump}', not 'patch'. This lane skips the soak, so it only ships patches; ` +
+ 'promote through the normal stable path instead.',
+ );
+ }
+ return pass('Computed bump is a patch.');
+}
+
+/**
+ * Would the npm publish survive its native-config provenance check?
+ *
+ * The publish workflow stages prebuilt native binaries from the newest
+ * successful prebuild run on `main` and, on the stable path only, HARD-FAILS
+ * when that run's head commit is not an ancestor of the commit being released.
+ * The synthetic commit is built on the last stable, so it does not contain any
+ * main commit that landed after it, and a native-config change on `main` since
+ * the last stable puts the newest prebuild out of reach.
+ *
+ * The reason to check it here is ordering, not novelty: that failure happens
+ * after the tag and the GitHub Release already exist, leaving a version users
+ * can see with nothing published behind it, on the exact channel this lane is
+ * supposed to be repairing. Checking the same condition before anything is
+ * created turns it into a clean refusal.
+ *
+ * An absent head sha refuses for the same reason. No successful prebuild run
+ * means the publish has nothing to stage and hard-fails one branch earlier in
+ * the same step.
+ */
+export function guardNativeConfigProvenance({ prebuildHeadSha, syntheticSha, isAncestor }) {
+ const head = String(prebuildHeadSha ?? '').trim();
+ if (head === '') {
+ return refuse(
+ 'native-config-drift',
+ 'No successful native-config-prebuild run found on main. The stable publish stages its native ' +
+ 'binaries from that run and refuses without them, so this release would fail after tagging.',
+ );
+ }
+ if (!isAncestor(head, syntheticSha)) {
+ return refuse(
+ 'native-config-drift',
+ `The newest native-config-prebuild commit (${head}) is not contained in the synthetic commit, so ` +
+ 'packages/native-config changed on main after the last stable. The stable publish would refuse ' +
+ 'to stage those binaries and fail after the tag exists. Promote through the normal stable path ' +
+ 'instead, so the release contains the native-config change its binaries were built from.',
+ );
+ }
+ return pass(`native-config prebuild ${head} is contained in the synthetic commit.`);
+}
+
+/**
+ * Would this main-reset dispatch consolidate more than the point release
+ * shipped?
+ *
+ * main-reset branches on `delta_ids != "null" && length > 0`, so an empty array
+ * and an absent value both fall through to its consolidate-the-whole-pending-pile
+ * branch. Dispatching either would consume every unsoaked changeset in one
+ * sweep, which is precisely the outcome this lane exists to avoid, and it would
+ * happen silently because from main-reset's side the dispatch looks like an
+ * ordinary manual run.
+ *
+ * A caller with no delta to forward must SKIP the dispatch rather than send an
+ * empty one.
+ */
+export function guardMainResetDeltaIds({ deltaIds }) {
+ if (!Array.isArray(deltaIds) || deltaIds.length === 0) {
+ return refuse(
+ 'empty-delta-ids',
+ 'Refusing to dispatch main-reset without an explicit changeset delta: it treats an empty or absent ' +
+ 'delta as consolidate-the-whole-pending-pile, which would consume every unsoaked changeset. ' +
+ 'Supply the delta, or skip the dispatch entirely.',
+ );
+ }
+ return pass(`main-reset would consolidate exactly ${deltaIds.length} changeset(s).`);
+}
+
+// The cross-repo target for the changeset consolidation. The public release
+// repo is a mirror; the changesets it consumes live in the monorepo, so the
+// reset has to land there.
+const MAIN_RESET_REPO = 'inkeep/agents-private';
+
+/**
+ * A precondition said no. Distinct from an ordinary Error so the CLI can exit
+ * with its own status: a refusal means the repo is fine and the operator has
+ * something to do, while a plain Error means the run could not decide at all.
+ */
+export class PointReleaseRefusal extends Error {
+ constructor(code, message) {
+ super(message);
+ this.name = 'PointReleaseRefusal';
+ this.code = code;
+ }
+}
+
+function checkGuard(trail, verdict) {
+ trail.push(verdict);
+ if (!verdict.ok) throw new PointReleaseRefusal(verdict.code, verdict.message);
+ return verdict;
+}
+
+/**
+ * Run the point-release lane: build `lastStable + one fix` and ship it as the
+ * new `latest`, skipping the soak the pending pile is still serving.
+ *
+ * `io` is the entire outside world, injected. Splitting it this way is not
+ * decoration: the lane's central promise is that a dry run computes the whole
+ * plan and changes nothing anyone can see, and the only way to prove that
+ * without a live repo, live tags, and a live GitHub is for every remote-visible
+ * effect to be a member of an object a test can hand in and then count.
+ *
+ * io.readAnchorVersion() -> 'X.Y.Z' changeset anchor in the checked-out tree
+ * io.git.newestStableTag / revParse / isOnMain / tagExists / isAncestor /
+ * changesetIds / bumpTypeOf (read-only)
+ * io.git.checkoutDetached / cherryPick / revert / headSha (local only)
+ * io.git.tag / pushTag (REMOTE)
+ * io.gh.newestNativeConfigPrebuildHeadSha (read-only)
+ * io.gh.createRelease / dispatch (REMOTE)
+ *
+ * The four REMOTE members are the ones a dry run must never reach. Building the
+ * synthetic commit is deliberately NOT one of them: a dry run that skipped the
+ * cherry-pick would not find out whether the fix applies, which is most of what
+ * the operator wants to learn before arming a real run. It happens on a
+ * detached head in the runner's throwaway clone, so nothing survives the job.
+ *
+ * A dry run creates no tag at all, not even locally. "Leaves the repo
+ * unchanged" is worth reading strictly, and a leftover local tag would make a
+ * real re-run in the same checkout look like it had already shipped.
+ *
+ * Returns the plan (see the `plan` object below) or throws: PointReleaseRefusal
+ * when a precondition says no, a plain Error when the boundary itself failed.
+ */
+export function runPointRelease(opts, io) {
+ const { mode, fixRefs, anchorDeltaIds, dryRun = true, dispatchedBy = '', selfRepo = '', bridgeConfigured = true } =
+ opts;
+
+ if (mode !== 'cherry-pick' && mode !== 'revert') {
+ throw new Error(`Point-release mode '${mode}' is not one of: cherry-pick, revert.`);
+ }
+ if (!Array.isArray(fixRefs) || fixRefs.length === 0) {
+ throw new Error('Point-release requires at least one fix ref.');
+ }
+
+ const guards = [];
+ const warnings = [];
+
+ const latestStableTag = io.git.newestStableTag();
+ if (!latestStableTag) {
+ throw new Error('No stable tag exists in this clone; a point release is a patch over an existing stable.');
+ }
+ const latestStableSha = io.git.revParse(latestStableTag);
+
+ checkGuard(guards, guardAnchor({ anchorVersion: io.readAnchorVersion(), latestStableTag }));
+ checkGuard(guards, guardRefsOnMain({ fixRefs, isOnMain: io.git.isOnMain }));
+
+ const resolvedRefs = fixRefs.map((ref) => ({ ref, sha: io.git.revParse(ref), onMain: true }));
+
+ // Build the synthetic commit. Detaching first is what keeps the pile out of
+ // the release: the tree starts as the last stable, so the only thing the
+ // release can contain beyond it is what the picks add.
+ io.git.checkoutDetached(latestStableSha);
+ for (const { ref } of resolvedRefs) {
+ applyFix(mode, ref, io);
+ }
+ const syntheticSha = io.git.headSha();
+
+ const version = computePointReleaseVersion({ syntheticSha, latestStableTag, latestStableSha, mode }, io.git);
+
+ checkGuard(guards, guardTagFree({ tag: version.tag, tagExists: io.git.tagExists }));
+ checkGuard(
+ guards,
+ guardDeltaMatchesFix({
+ mode,
+ addedIds: version.addedIds,
+ fixChangesetIds: mode === 'cherry-pick' ? changesetsIntroducedBy(resolvedRefs, io) : [],
+ }),
+ );
+ checkGuard(guards, guardPatchOnly({ bump: version.bump }));
+ checkGuard(
+ guards,
+ guardNativeConfigProvenance({
+ prebuildHeadSha: io.gh.newestNativeConfigPrebuildHeadSha(),
+ syntheticSha,
+ isAncestor: io.git.isAncestor,
+ }),
+ );
+
+ const mainReset = decideMainReset({ anchorDeltaIds, addedIds: version.addedIds, bridgeConfigured, guards, warnings });
+
+ const plan = {
+ mode,
+ dryRun,
+ latestStableTag,
+ latestStableVersion: version.latestStableVersion,
+ latestStableSha,
+ fixRefs: resolvedRefs,
+ syntheticSha,
+ syntheticTree: {
+ sha: syntheticSha,
+ changesetCount: io.git.changesetIds(syntheticSha).length,
+ addedIds: version.addedIds,
+ removedIds: version.removedIds,
+ },
+ version: version.version,
+ tag: version.tag,
+ bump: version.bump,
+ addedIds: version.addedIds,
+ removedIds: version.removedIds,
+ mainReset,
+ guards,
+ warnings,
+ };
+
+ if (dryRun) return plan;
+
+ io.git.tag(plan.tag, syntheticSha);
+ io.git.pushTag(plan.tag);
+
+ // Past this point the tag is public and every remaining step is a remote,
+ // non-idempotent call. A failure here leaves a half-shipped state, and unlike
+ // `promote-stable.yml` this lane cannot make it resumable by checking whether
+ // the tag already sits at the expected sha: that workflow tags an EXISTING
+ // beta commit, which is byte-identical across retries, whereas this one
+ // synthesizes a commit whose sha changes every run because cherry-pick and
+ // revert both stamp a fresh committer date. A re-run therefore always collides
+ // at a different sha, and skipping on that would tag the previous run's
+ // commit. So the recovery is deliberately manual, and the job of this marker
+ // is to make sure the operator is TOLD what exists rather than left to infer
+ // it from a bare API error.
+ try {
+ // Draft, exactly as the ordinary promotion does. desktop-release.yml flips it
+ // to published after the DMG and its update manifest are attached; publishing
+ // here would put a release in the auto-updater's feed with no build behind it.
+ io.gh.createRelease({
+ tag: plan.tag,
+ targetSha: syntheticSha,
+ title: plan.tag,
+ draft: true,
+ notes: formatReleaseNotes(plan),
+ });
+
+ // The ONLY cascade dispatch for the release itself, matching what
+ // promote-stable.yml now does. desktop-release.yml builds the DMG, smokes
+ // it, promotes the draft Release, and only then dispatches publish-stable
+ // to release.yml for npm. Dispatching publish-stable from here as well
+ // would move npm `latest` before the smoke had a chance to refuse, which is
+ // the failure that gate exists to prevent, and would publish twice.
+ io.gh.dispatch({
+ repo: selfRepo,
+ eventType: 'desktop-release',
+ clientPayload: { release_tag: plan.tag, ref: plan.tag, dispatched_by: dispatchedBy },
+ });
+ if (mainReset.dispatch) {
+ io.gh.dispatch({
+ repo: MAIN_RESET_REPO,
+ eventType: 'main-reset',
+ clientPayload: { stable_version: plan.version, delta_ids: mainReset.deltaIds, dispatched_by: dispatchedBy },
+ });
+ }
+ } catch (err) {
+ // Normalize rather than annotate-if-Error: the half-shipped warning is the
+ // most consequential thing this run can say, and gating it on the thrown
+ // value's type would drop it for exactly the unexpected failure where the
+ // operator most needs to be told the tag is already public.
+ const marked = err instanceof Error ? err : new Error(String(err));
+ marked.pushedTag = plan.tag;
+ throw marked;
+ }
+
+ return plan;
+}
+
+/**
+ * Apply one fix onto the detached last-stable head.
+ *
+ * git already fails on a conflict, so the catch adds only context; it re-throws
+ * and never swallows. The context is worth the wrapper: git's own message says
+ * which paths collided, which reads as a mechanical problem an operator might
+ * try to hand-resolve, when the actual finding is that the fix depends on
+ * something between last stable and now and therefore cannot ship alone.
+ *
+ * There is deliberately no strategy or conflict-resolution option to reach for.
+ * Any resolution would produce a tree that is neither last stable nor the fix
+ * as reviewed, shipped straight to the default install channel with no soak.
+ */
+function applyFix(mode, ref, io) {
+ try {
+ if (mode === 'revert') io.git.revert(ref);
+ else io.git.cherryPick(ref);
+ } catch (err) {
+ throw new PointReleaseRefusal(
+ 'apply-conflict',
+ `Applying ${ref} onto the last stable hit a conflict (${mode}): ${err.message}. The fix is not ` +
+ 'self-contained over the current stable, so it cannot ship as a point release. Promote through ' +
+ 'the normal stable path, or pick the smaller commit that is self-contained.',
+ );
+ }
+}
+
+// The changesets each fix ref introduced on its own, which is what the delta
+// guard compares the synthetic commit against. Read per ref against its own
+// parent rather than against last stable, so a ref that merely touches a
+// changeset already present in stable does not read as introducing it.
+function changesetsIntroducedBy(resolvedRefs, io) {
+ const introduced = [];
+ for (const { ref } of resolvedRefs) {
+ const before = new Set(io.git.changesetIds(`${ref}^`));
+ for (const id of io.git.changesetIds(ref)) {
+ if (!before.has(id) && !introduced.includes(id)) introduced.push(id);
+ }
+ }
+ return introduced;
+}
+
+/**
+ * Decide whether to forward a changeset delta to the main-reset consolidation,
+ * and with what.
+ *
+ * The delta is the operator's `anchor_delta_ids` when they named one, and the
+ * synthetic commit's own added changesets otherwise. Naming one is how revert
+ * mode participates at all: a revert adds no changeset, so there is nothing to
+ * derive, and the operator has to say which changeset they landed on main to
+ * represent it.
+ *
+ * With nothing to forward the dispatch is SKIPPED, never sent empty: main-reset
+ * reads an empty delta as consolidate-the-whole-pending-pile, so an empty
+ * dispatch would sweep up every unsoaked changeset, which is the outcome this
+ * whole lane exists to avoid.
+ *
+ * Skipping leaves the anchor behind the new stable, and every version-computing
+ * path refuses on that drift, so the warning names both follow-ups rather than
+ * leaving the next operator to discover the block.
+ */
+function decideMainReset({ anchorDeltaIds, addedIds, bridgeConfigured, guards, warnings }) {
+ const named = String(anchorDeltaIds ?? '').trim() !== '';
+ const deltaIds = named ? parseDeltaIds(anchorDeltaIds) : addedIds;
+
+ if (!named && deltaIds.length === 0) {
+ warnings.push(
+ '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.',
+ );
+ return { dispatch: false, deltaIds: null, skipReason: 'no-delta-to-forward' };
+ }
+
+ // Reached only when the operator named a delta or one was derived, so a
+ // refusal here means they named something that parsed to nothing.
+ checkGuard(guards, guardMainResetDeltaIds({ deltaIds }));
+
+ if (!bridgeConfigured) {
+ warnings.push(
+ 'Skipping the main-reset dispatch: the cross-repo bridge App is not configured on this repo. Run ' +
+ `main-reset manually with delta_ids ${JSON.stringify(deltaIds)} so the anchor advances past this stable.`,
+ );
+ return { dispatch: false, deltaIds, skipReason: 'bridge-not-configured' };
+ }
+
+ return { dispatch: true, deltaIds, skipReason: null };
+}
+
+function formatReleaseNotes(plan) {
+ const lines = [
+ `Point release over ${plan.latestStableTag}: the current stable plus ${plan.fixRefs.length} applied ` +
+ `commit(s), isolated from the changes still soaking on main.`,
+ '',
+ `Mode: ${plan.mode}`,
+ `Applied: ${plan.fixRefs.map((r) => `${r.ref} (${r.sha})`).join(', ')}`,
+ ];
+ if (plan.addedIds.length > 0) lines.push(`Changesets added: ${plan.addedIds.join(', ')}`);
+ if (plan.removedIds.length > 0) lines.push(`Changesets removed: ${plan.removedIds.join(', ')}`);
+ return `${lines.join('\n')}\n`;
+}
+
+// --- workflow-runtime wiring (real git + gh boundary) ---
+
+// Built on compute-stable-version's `realGit` rather than beside it, so the
+// read-only members every version-computing path already shares keep exactly
+// one implementation.
+function realIo() {
+ return {
+ readAnchorVersion,
+ git: {
+ ...realGit,
+ // Containment in the public repo's main, which the run's own checkout
+ // tracks. fetch-depth 0 is what makes this answerable at all.
+ isOnMain: (ref) => realGit.isAncestor(ref, 'origin/main'),
+ // Three-way, matching `isAncestor`: exit 0 is a hit, exit 1 a clean miss,
+ // anything else an infra failure that must fail loud. A one-way
+ // `status === 0` reads a spawn failure (`status` is null when git cannot be
+ // invoked at all) as "the tag is free", and this is the guard standing
+ // between a concurrent promotion and a colliding tag.
+ tagExists: (tag) => {
+ const res = spawnSync('git', ['rev-parse', '--verify', '--quiet', `refs/tags/${tag}`], { encoding: 'utf8' });
+ if (res.status === 0) return true;
+ if (res.status === 1) return false;
+ throw new Error(
+ `git rev-parse --verify refs/tags/${tag} failed (exit ${res.status}): ${res.error?.message ?? String(res.stderr || '').trim()}`,
+ );
+ },
+ checkoutDetached: (sha) => void runGit(['checkout', '--detach', sha]),
+ cherryPick: (ref) => void runGit(['cherry-pick', ref]),
+ // --no-edit only suppresses the message editor; the pick is otherwise
+ // whatever git produces, and a conflict still fails.
+ revert: (ref) => void runGit(['revert', '--no-edit', ref]),
+ headSha: () => runGit(['rev-parse', 'HEAD']).trim(),
+ tag: (tag, sha) => void runGit(['tag', tag, sha]),
+ pushTag: (tag) => void runGit(['push', 'origin', tag]),
+ },
+ gh: {
+ newestNativeConfigPrebuildHeadSha: () => {
+ // Same filters the publish path uses to pick the run it stages
+ // binaries from. `--event push` is load-bearing: the prebuild workflow
+ // also runs on pull_request, including external PRs against the public
+ // mirror, so without it the newest green run can be unmerged source.
+ const res = spawnSync(
+ 'gh',
+ [
+ 'run',
+ 'list',
+ '--workflow=native-config-prebuild.yml',
+ '--branch',
+ 'main',
+ '--event',
+ 'push',
+ '--status',
+ 'success',
+ '--limit',
+ '1',
+ '--json',
+ 'headSha',
+ '--jq',
+ '.[0].headSha // empty',
+ ],
+ { encoding: 'utf8' },
+ );
+ // An unreadable answer is not an empty answer. Returning '' on an auth
+ // or rate-limit failure would refuse the release naming native-config
+ // drift, sending the operator to investigate a repo state that is fine.
+ if (res.status !== 0) {
+ throw new Error(`gh run list for native-config-prebuild failed: ${String(res.stderr || '').trim()}`);
+ }
+ return String(res.stdout || '').trim();
+ },
+ createRelease: ({ tag, targetSha, title, draft, notes }) => {
+ const args = ['release', 'create', tag, '--target', targetSha, '--title', title, '--notes', notes];
+ if (draft) args.push('--draft');
+ const res = spawnSync('gh', args, { encoding: 'utf8' });
+ if (res.status !== 0) {
+ throw new Error(`gh release create ${tag} failed: ${String(res.stderr || '').trim()}`);
+ }
+ },
+ dispatch: ({ repo, eventType, clientPayload }) => {
+ const res = spawnSync('gh', ['api', '-X', 'POST', `repos/${repo}/dispatches`, '--input', '-'], {
+ encoding: 'utf8',
+ input: JSON.stringify({ event_type: eventType, client_payload: clientPayload }),
+ // The cross-repo consolidation runs on a different repo than the
+ // release, so it needs the bridge App's token rather than this run's.
+ env:
+ repo === MAIN_RESET_REPO && process.env.BRIDGE_GH_TOKEN
+ ? { ...process.env, GH_TOKEN: process.env.BRIDGE_GH_TOKEN }
+ : process.env,
+ });
+ if (res.status !== 0) {
+ throw new Error(`gh dispatch ${eventType} to ${repo} failed: ${String(res.stderr || '').trim()}`);
+ }
+ },
+ },
+ };
+}
+
+function log(...args) {
+ process.stderr.write(`${args.join(' ')}\n`);
+}
+
+function main() {
+ // Only a literal 'false' arms a real run. Anything else, including an unset
+ // variable or a typo, stays a dry run: the failure mode of an accidental dry
+ // run is a wasted minute, and of an accidental real one an unsoaked release
+ // on the default install channel.
+ const dryRun = process.env.DRY_RUN !== 'false';
+
+ let plan;
+ try {
+ plan = runPointRelease(
+ {
+ mode: process.env.MODE,
+ fixRefs: parseFixRefs(process.env.FIX_REFS),
+ anchorDeltaIds: process.env.ANCHOR_DELTA_IDS,
+ dryRun,
+ dispatchedBy: process.env.DISPATCHED_BY || '',
+ selfRepo: process.env.GITHUB_REPOSITORY || '',
+ bridgeConfigured: process.env.BRIDGE_CONFIGURED === 'true',
+ },
+ realIo(),
+ );
+ } catch (err) {
+ // `String(err)` for the non-Error case: reading `.message` off a thrown
+ // non-Error annotates the run with the word "undefined" and nothing else.
+ const message = err instanceof Error ? err.message : String(err);
+ if (err instanceof PointReleaseRefusal) {
+ console.error(`::error::point-release-plan (${err.code}): ${message}`);
+ process.exit(2);
+ }
+ // The tag reached the remote and the cascade behind it did not finish. Say
+ // so out loud: the operator's instinct is to re-run, and a re-run cannot
+ // clear this on its own.
+ if (err instanceof Error && err.pushedTag) {
+ console.error(
+ `::error::point-release-plan: ${message} | HALF-SHIPPED: tag ${err.pushedTag} IS already on ` +
+ 'the public repo but its cascade did not finish. Re-running will NOT resume it, because the ' +
+ 'next run synthesizes a new commit whose tag collides at a different sha. Either finish the ' +
+ `cascade by hand, or delete the tag ("git push origin :refs/tags/${err.pushedTag}") and its ` +
+ 'draft Release, then re-run. See RELEASES.md, "Recovery: a point release failed partway".',
+ );
+ process.exit(1);
+ }
+ console.error(`::error::point-release-plan: ${message}`);
+ process.exit(1);
+ }
+
+ for (const warning of plan.warnings) console.error(`::warning::${warning}`);
+ for (const guard of plan.guards) log(`ok: ${guard.message}`);
+ log(
+ `${dryRun ? 'DRY RUN — nothing was pushed. Plan' : 'Shipped'}: ${plan.tag} (${plan.bump} over ` +
+ `${plan.latestStableTag}) from ${plan.syntheticSha} = ${plan.latestStableTag} + ${plan.mode} of ` +
+ `${plan.fixRefs.map((r) => r.ref).join(', ')}.`,
+ );
+ console.log(JSON.stringify(plan));
+
+ if (process.env.GITHUB_OUTPUT) {
+ appendFileSync(
+ process.env.GITHUB_OUTPUT,
+ [
+ `dry_run=${dryRun ? 'true' : 'false'}`,
+ `point_release_tag=${plan.tag}`,
+ `point_release_version=${plan.version}`,
+ `latest_stable_tag=${plan.latestStableTag}`,
+ `synthetic_sha=${plan.syntheticSha}`,
+ `delta_ids=${JSON.stringify(plan.mainReset.deltaIds ?? [])}`,
+ `main_reset_dispatched=${plan.mainReset.dispatch ? 'true' : 'false'}`,
+ '',
+ ].join('\n'),
+ );
+ }
+}
+
+// Run main() only as a CLI, not when the test file imports the predicates.
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main();
+}
diff --git a/.github/scripts/point-release-plan.test.mjs b/.github/scripts/point-release-plan.test.mjs
new file mode 100644
index 000000000..fe68e4d41
--- /dev/null
+++ b/.github/scripts/point-release-plan.test.mjs
@@ -0,0 +1,646 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, test } from 'vitest';
+import {
+ guardAnchor,
+ guardDeltaMatchesFix,
+ guardMainResetDeltaIds,
+ guardNativeConfigProvenance,
+ guardPatchOnly,
+ guardRefsOnMain,
+ guardTagFree,
+ parseFixRefs,
+ runPointRelease,
+} from './point-release-plan.mjs';
+
+// Build an isOnMain / tagExists boundary from a plain list. The sentinel
+// 'THROW' simulates an infra failure (an unreadable ref), which must propagate
+// rather than read as a clean "not on main".
+const membership = (...members) => {
+ const set = new Set(members);
+ return (value) => {
+ if (value === 'THROW') throw new Error('simulated git infra error');
+ return set.has(value);
+ };
+};
+
+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(['abc123', 'def456', 'ghi789']);
+ });
+
+ test('throws when no ref survives parsing', () => {
+ expect(() => parseFixRefs(' , ,\n ')).toThrow(/no fix ref/i);
+ });
+
+ test('throws on missing input', () => {
+ expect(() => parseFixRefs(undefined)).toThrow(/no fix ref/i);
+ });
+});
+
+describe('guardRefsOnMain', () => {
+ test('passes when every fix ref is contained in main', () => {
+ const r = guardRefsOnMain({ fixRefs: ['abc', 'def'], isOnMain: membership('abc', 'def') });
+ expect(r).toMatchObject({ ok: true, code: null });
+ });
+
+ test('refuses naming every ref that is not on main', () => {
+ const r = guardRefsOnMain({ fixRefs: ['abc', 'stray', 'other'], isOnMain: membership('abc') });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('ref-not-on-main');
+ expect(r.message).toContain('stray');
+ expect(r.message).toContain('other');
+ });
+
+ test('propagates an ancestry infra error instead of reading it as not-on-main', () => {
+ expect(() => guardRefsOnMain({ fixRefs: ['THROW'], isOnMain: membership() })).toThrow(/infra error/);
+ });
+});
+
+describe('guardTagFree', () => {
+ test('passes when the computed tag does not exist yet', () => {
+ const r = guardTagFree({ tag: 'v0.32.1', tagExists: membership('v0.32.0') });
+ expect(r).toMatchObject({ ok: true, code: null });
+ });
+
+ test('refuses when the computed tag is already taken', () => {
+ const r = guardTagFree({ tag: 'v0.32.1', tagExists: membership('v0.32.1') });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('tag-exists');
+ expect(r.message).toContain('v0.32.1');
+ });
+
+ test('propagates a tag-lookup infra error instead of reading it as a free tag', () => {
+ // The direction matters more here than for the sibling guards: reading an
+ // unreadable tag as "free" is what lets a run push over a tag it never
+ // actually checked.
+ expect(() => guardTagFree({ tag: 'THROW', tagExists: membership() })).toThrow(/infra error/);
+ });
+});
+
+describe('guardDeltaMatchesFix', () => {
+ test('cherry-pick passes when the added delta is exactly the fix own changesets', () => {
+ const r = guardDeltaMatchesFix({
+ mode: 'cherry-pick',
+ addedIds: ['brave-pandas-sing', 'wise-moths-hum'],
+ // Order differs from addedIds: the comparison is over sets, since the
+ // pick order is not something the operator controls.
+ fixChangesetIds: ['wise-moths-hum', 'brave-pandas-sing'],
+ });
+ expect(r).toMatchObject({ ok: true, code: null });
+ });
+
+ test('cherry-pick refuses when the delta carries a changeset the fix did not bring', () => {
+ const r = guardDeltaMatchesFix({
+ mode: 'cherry-pick',
+ addedIds: ['brave-pandas-sing', 'unrelated-pile-work'],
+ fixChangesetIds: ['brave-pandas-sing'],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('delta-mismatch');
+ expect(r.message).toContain('unrelated-pile-work');
+ });
+
+ test('cherry-pick refuses when a changeset the fix brought is missing from the delta', () => {
+ const r = guardDeltaMatchesFix({
+ mode: 'cherry-pick',
+ addedIds: [],
+ fixChangesetIds: ['brave-pandas-sing'],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('delta-mismatch');
+ expect(r.message).toContain('brave-pandas-sing');
+ });
+
+ test('revert passes when the revert added no changeset', () => {
+ // fixChangesetIds is deliberately non-empty: the reverted commit owned a
+ // changeset, and revert mode must judge the delta, not the culprit.
+ const r = guardDeltaMatchesFix({
+ mode: 'revert',
+ addedIds: [],
+ fixChangesetIds: ['brave-pandas-sing'],
+ });
+ expect(r).toMatchObject({ ok: true, code: null });
+ });
+
+ test('revert refuses when the delta added a changeset', () => {
+ const r = guardDeltaMatchesFix({
+ mode: 'revert',
+ addedIds: ['brave-pandas-sing'],
+ fixChangesetIds: [],
+ });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('delta-mismatch');
+ expect(r.message).toContain('brave-pandas-sing');
+ });
+});
+
+describe('guardPatchOnly', () => {
+ test('passes on a patch bump', () => {
+ expect(guardPatchOnly({ bump: 'patch' })).toMatchObject({ ok: true, code: null });
+ });
+
+ test('refuses a minor bump', () => {
+ const r = guardPatchOnly({ bump: 'minor' });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('bump-not-patch');
+ expect(r.message).toContain('minor');
+ });
+});
+
+describe('guardNativeConfigProvenance', () => {
+ test('passes when the prebuild head is contained in the synthetic commit', () => {
+ const r = guardNativeConfigProvenance({
+ prebuildHeadSha: 'prebuild',
+ syntheticSha: 'synthetic',
+ isAncestor: membership('prebuild'),
+ });
+ expect(r).toMatchObject({ ok: true, code: null });
+ });
+
+ test('refuses when the prebuild head is not contained in the synthetic commit', () => {
+ const r = guardNativeConfigProvenance({
+ prebuildHeadSha: 'prebuild',
+ syntheticSha: 'synthetic',
+ isAncestor: membership(),
+ });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('native-config-drift');
+ expect(r.message).toContain('native-config');
+ });
+
+ test('refuses when no successful prebuild run exists to stage from', () => {
+ // An absent head sha must be diagnosed as "no run to stage from", not run
+ // through the ancestry check, where the real git boundary would raise an
+ // infra error on an empty rev rather than answer cleanly.
+ const r = guardNativeConfigProvenance({
+ prebuildHeadSha: '',
+ syntheticSha: 'synthetic',
+ isAncestor: membership('prebuild'),
+ });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('native-config-drift');
+ expect(r.message).toMatch(/No successful native-config-prebuild run/i);
+ });
+
+ test('propagates an ancestry infra error instead of reading it as drift', () => {
+ expect(() =>
+ guardNativeConfigProvenance({
+ prebuildHeadSha: 'THROW',
+ syntheticSha: 'synthetic',
+ isAncestor: membership(),
+ }),
+ ).toThrow(/infra error/);
+ });
+});
+
+describe('guardMainResetDeltaIds', () => {
+ test('passes on a non-empty delta', () => {
+ expect(guardMainResetDeltaIds({ deltaIds: ['brave-pandas-sing'] })).toMatchObject({ ok: true, code: null });
+ });
+
+ test('refuses an empty array, which main-reset reads as consolidate-everything', () => {
+ const r = guardMainResetDeltaIds({ deltaIds: [] });
+ expect(r.ok).toBe(false);
+ expect(r.code).toBe('empty-delta-ids');
+ });
+
+ test('refuses an absent delta for the same reason', () => {
+ expect(guardMainResetDeltaIds({ deltaIds: null })).toMatchObject({ ok: false, code: 'empty-delta-ids' });
+ });
+});
+
+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() }),
+ guardTagFree({ tag: 'v0.32.1', tagExists: membership('v0.32.1') }),
+ guardDeltaMatchesFix({ mode: 'revert', addedIds: ['x'], fixChangesetIds: [] }),
+ guardPatchOnly({ bump: 'major' }),
+ guardNativeConfigProvenance({ prebuildHeadSha: 'p', syntheticSha: 's', isAncestor: membership() }),
+ guardMainResetDeltaIds({ deltaIds: [] }),
+ ];
+ expect(refusals.every((r) => r.ok === false)).toBe(true);
+ const codes = refusals.map((r) => r.code);
+ expect(new Set(codes).size).toBe(codes.length);
+ // Every refusal carries an operator-readable message, not just a code.
+ expect(refusals.every((r) => typeof r.message === 'string' && r.message.length > 0)).toBe(true);
+ });
+});
+
+// A whole io boundary built from a fixture. Every remote-mutating member counts
+// its calls, which is what makes "a dry run touches nothing" a real assertion
+// rather than a claim.
+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'] },
+ bumpTypes = {},
+ prebuildHeadSha = 'prebuild-sha',
+ ancestries = [['prebuild-sha', 'synthetic-sha']],
+ cherryPick,
+ revert,
+ } = overrides;
+
+ const calls = { tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 };
+ const dispatches = [];
+ const releases = [];
+ const applied = [];
+ const checkedOut = [];
+
+ return {
+ calls,
+ dispatches,
+ releases,
+ applied,
+ checkedOut,
+ readAnchorVersion: () => anchorVersion,
+ git: {
+ newestStableTag: () => stableTag,
+ revParse: (ref) => (ref === stableTag ? 'stable-sha' : `${ref}-sha`),
+ isOnMain: (ref) => onMain.includes(ref),
+ tagExists: (t) => existingTags.includes(t),
+ isAncestor: (a, b) => ancestries.some(([x, y]) => x === a && y === b),
+ changesetIds: (sha) => changesets[sha] ?? [],
+ bumpTypeOf: (_sha, id) => bumpTypes[id] ?? 'patch',
+ checkoutDetached: (sha) => checkedOut.push(sha),
+ cherryPick: cherryPick ?? ((ref) => applied.push(['cherry-pick', ref])),
+ revert: revert ?? ((ref) => applied.push(['revert', ref])),
+ headSha: () => 'synthetic-sha',
+ tag: () => calls.tag++,
+ pushTag: () => calls.pushTag++,
+ },
+ gh: {
+ newestNativeConfigPrebuildHeadSha: () => prebuildHeadSha,
+ createRelease: (r) => {
+ calls.createRelease++;
+ releases.push(r);
+ },
+ dispatch: (d) => {
+ calls.dispatch++;
+ dispatches.push(d);
+ },
+ },
+ };
+}
+
+describe('runPointRelease dry run', () => {
+ test('revert mode over v0.32.0 plans v0.32.1 and touches nothing remote', () => {
+ const io = makeIo();
+ const plan = runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: true }, io);
+ expect(plan.tag).toBe('v0.32.1');
+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });
+ });
+
+ test('cherry-pick mode reports the delta and touches nothing remote', () => {
+ const io = makeIo({
+ changesets: {
+ 'stable-sha': ['keep-a'],
+ 'synthetic-sha': ['keep-a', 'shiny-fix'],
+ fix1: ['keep-a', 'shiny-fix'],
+ 'fix1^': ['keep-a'],
+ },
+ });
+ const plan = runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: true }, io);
+ expect(plan.tag).toBe('v0.32.1');
+ expect(plan.addedIds).toEqual(['shiny-fix']);
+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });
+ });
+
+ test('cherry-pick with two refs unions their changesets without double-counting', () => {
+ // fix2 lands on top of fix1, so reading each ref against its own parent
+ // reports fix1-cs twice. The delta must still be the union, or a legitimate
+ // two-commit point release refuses with a bogus delta mismatch.
+ const io = makeIo({
+ onMain: ['fix1', 'fix2'],
+ changesets: {
+ 'stable-sha': ['keep-a'],
+ 'synthetic-sha': ['keep-a', 'fix1-cs', 'fix2-cs'],
+ fix1: ['keep-a', 'fix1-cs'],
+ 'fix1^': ['keep-a'],
+ fix2: ['keep-a', 'fix1-cs', 'fix2-cs'],
+ 'fix2^': ['keep-a', 'fix1-cs'],
+ },
+ });
+ const plan = runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1', 'fix2'], dryRun: true }, io);
+ expect(plan.addedIds).toEqual(['fix1-cs', 'fix2-cs']);
+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });
+ });
+
+ test('throws when the clone holds no stable tag to patch over', () => {
+ // A point release is defined as a patch over an existing stable. With no
+ // stable tag there is no base to compute against, and proceeding would cut
+ // a first-ever release out of this lane rather than out of the normal path.
+ const io = makeIo({ stableTag: '' });
+ expect(() => runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: true }, io)).toThrow(
+ /patch over an existing stable/,
+ );
+ // Refusing before touching the clone is the point: the throw sits ahead of
+ // the detach, so a run with no stable to patch over leaves no working state
+ // behind for the next one to trip over.
+ expect(io.checkedOut).toEqual([]);
+ expect(io.applied).toEqual([]);
+ });
+
+ test('the plan carries what an operator needs to decide whether to arm a real run', () => {
+ const io = makeIo();
+ const plan = runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: true }, io);
+ expect(plan.latestStableTag).toBe('v0.32.0');
+ expect(plan.fixRefs).toEqual([{ ref: 'bad1', sha: 'bad1-sha', onMain: true }]);
+ expect(plan.version).toBe('0.32.1');
+ expect(plan.syntheticTree).toMatchObject({ sha: 'synthetic-sha', changesetCount: 1 });
+ expect(plan.guards.length).toBeGreaterThanOrEqual(6);
+ });
+
+ test('the synthetic commit is still built, so a dry run finds out whether the fix applies', () => {
+ const io = makeIo();
+ runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: true }, io);
+ expect(io.checkedOut).toEqual(['stable-sha']);
+ expect(io.applied).toEqual([['revert', 'bad1']]);
+ });
+});
+
+describe('runPointRelease cascade', () => {
+ const cherryPickIo = () =>
+ makeIo({
+ changesets: {
+ 'stable-sha': ['keep-a'],
+ 'synthetic-sha': ['keep-a', 'shiny-fix'],
+ fix1: ['keep-a', 'shiny-fix'],
+ 'fix1^': ['keep-a'],
+ },
+ });
+
+ test('dispatches the cascade payloads in the shapes the existing workflows read', () => {
+ const io = cherryPickIo();
+ runPointRelease(
+ {
+ mode: 'cherry-pick',
+ fixRefs: ['fix1'],
+ dryRun: false,
+ dispatchedBy: 'https://run/1',
+ selfRepo: 'inkeep/open-knowledge',
+ },
+ io,
+ );
+ // No publish-stable here. desktop-release.yml fires it once the DMG it
+ // builds has passed the smoke gate, so dispatching it from this lane too
+ // would both double-publish and move npm `latest` ahead of the gate.
+ expect(io.dispatches).toEqual([
+ {
+ repo: 'inkeep/open-knowledge',
+ eventType: 'desktop-release',
+ clientPayload: { release_tag: 'v0.32.1', ref: 'v0.32.1', dispatched_by: 'https://run/1' },
+ },
+ {
+ repo: 'inkeep/agents-private',
+ eventType: 'main-reset',
+ clientPayload: { stable_version: '0.32.1', delta_ids: ['shiny-fix'], dispatched_by: 'https://run/1' },
+ },
+ ]);
+ });
+
+ test('tags the synthetic commit and creates the Release as a draft', () => {
+ const io = cherryPickIo();
+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false }, io);
+ expect(io.calls).toMatchObject({ tag: 1, pushTag: 1, createRelease: 1 });
+ expect(io.releases[0]).toMatchObject({ tag: 'v0.32.1', targetSha: 'synthetic-sha', draft: true });
+ });
+
+ test('revert with no named delta skips main-reset and names both follow-ups', () => {
+ const io = makeIo();
+ const plan = runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: false }, io);
+ expect(plan.mainReset).toMatchObject({ dispatch: false, skipReason: 'no-delta-to-forward' });
+ expect(io.dispatches.map((d) => d.eventType)).toEqual(['desktop-release']);
+ expect(io.dispatches.every((d) => d.clientPayload.delta_ids === undefined)).toBe(true);
+ const warning = plan.warnings.join(' ');
+ expect(warning).toMatch(/on main/i);
+ expect(warning).toMatch(/anchor advances/i);
+ });
+
+ test('revert forwards the changeset the operator landed to represent it', () => {
+ const io = makeIo();
+ runPointRelease({ mode: 'revert', fixRefs: ['bad1'], anchorDeltaIds: '["undo-bad"]', dryRun: false }, io);
+ const mainReset = io.dispatches.find((d) => d.eventType === 'main-reset');
+ expect(mainReset.clientPayload.delta_ids).toEqual(['undo-bad']);
+ });
+
+ test('refuses when the operator names a delta that parses to nothing', () => {
+ const io = makeIo();
+ let refusal;
+ try {
+ runPointRelease({ mode: 'revert', fixRefs: ['bad1'], anchorDeltaIds: '[]', dryRun: false }, io);
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal?.code).toBe('empty-delta-ids');
+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });
+ });
+
+ test('skips main-reset when the cross-repo bridge App is absent, without failing the run', () => {
+ const io = cherryPickIo();
+ const plan = runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false, bridgeConfigured: false }, io);
+ expect(plan.mainReset).toMatchObject({ dispatch: false, skipReason: 'bridge-not-configured' });
+ expect(io.dispatches.map((d) => d.eventType)).toEqual(['desktop-release']);
+ expect(plan.warnings.join(' ')).toContain('shiny-fix');
+ });
+
+ test('a cascade failure after the tag is pushed marks the error with the pushed tag', () => {
+ // The marker is what lets main() say "this half-shipped, a re-run will not
+ // clear it" instead of surfacing a bare API error. Nothing else observes it,
+ // so without this test a refactor could drop it silently.
+ const io = cherryPickIo();
+ io.gh.createRelease = () => {
+ throw new Error('gh API 503');
+ };
+
+ let caught;
+ try {
+ runPointRelease({ mode: 'cherry-pick', fixRefs: ['fix1'], dryRun: false }, io);
+ } catch (err) {
+ caught = err;
+ }
+
+ expect(caught?.pushedTag).toBe('v0.32.1');
+ expect(caught?.message).toContain('gh API 503');
+ // Pins the try boundary as much as the marker: the tag push must have
+ // happened OUTSIDE the guarded block, or the state this annotation warns
+ // about would not exist and the message would be a lie.
+ expect(io.calls.tag).toBe(1);
+ expect(io.calls.pushTag).toBe(1);
+ });
+});
+
+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'] }],
+ [
+ 'delta-mismatch',
+ { changesets: { 'stable-sha': ['keep-a'], 'synthetic-sha': ['keep-a', 'sneaky'] } },
+ { mode: 'revert', fixRefs: ['bad1'] },
+ ],
+ [
+ 'bump-not-patch',
+ {
+ bumpTypes: { 'shiny-fix': 'minor' },
+ changesets: {
+ 'stable-sha': ['keep-a'],
+ 'synthetic-sha': ['keep-a', 'shiny-fix'],
+ fix1: ['keep-a', 'shiny-fix'],
+ 'fix1^': ['keep-a'],
+ },
+ },
+ { mode: 'cherry-pick', fixRefs: ['fix1'] },
+ ],
+ ['native-config-drift', { ancestries: [] }, { mode: 'revert', fixRefs: ['bad1'] }],
+ ];
+
+ test.each(cases)('refuses with %s and mutates nothing, even in a real run', (code, ioOpts, runOpts) => {
+ const io = makeIo(ioOpts);
+ let refusal;
+ try {
+ runPointRelease({ ...runOpts, dryRun: false }, io);
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal?.code).toBe(code);
+ expect(refusal?.message).toBeTruthy();
+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });
+ });
+
+ test('a failing anchor guard stops before the synthetic commit is even built', () => {
+ const io = makeIo({ anchorVersion: '0.31.0' });
+ expect(() => runPointRelease({ mode: 'revert', fixRefs: ['bad1'], dryRun: false }, io)).toThrow();
+ expect(io.checkedOut).toEqual([]);
+ expect(io.applied).toEqual([]);
+ });
+
+ test.each([
+ ['cherry-pick', 'cherryPick'],
+ ['revert', 'revert'],
+ ])('a %s conflict is a hard fail', (mode, member) => {
+ const io = makeIo({
+ [member]: () => {
+ throw new Error('CONFLICT (content): Merge conflict in packages/cli/src/index.ts');
+ },
+ changesets: {
+ 'stable-sha': ['keep-a'],
+ 'synthetic-sha': ['keep-a', 'shiny-fix'],
+ fix1: ['keep-a', 'shiny-fix'],
+ 'fix1^': ['keep-a'],
+ },
+ });
+ let refusal;
+ try {
+ runPointRelease({ mode, fixRefs: [mode === 'revert' ? 'bad1' : 'fix1'], dryRun: false }, io);
+ } catch (err) {
+ refusal = err;
+ }
+ expect(refusal?.code).toBe('apply-conflict');
+ expect(refusal?.message).toMatch(/conflict/i);
+ expect(io.calls).toEqual({ tag: 0, pushTag: 0, createRelease: 0, dispatch: 0 });
+ });
+
+ test('offers no conflict-resolution escape hatch to reach for', () => {
+ const source = readFileSync(new URL('./point-release-plan.mjs', import.meta.url), 'utf8');
+ // Git's merge-strategy and pick-continuation affordances, in the forms they
+ // would actually appear in an argv array. Bare 'ours'/'theirs' are matched
+ // quoted so ordinary prose like "now yours" does not trip the check.
+ const escapes = [
+ '--strategy',
+ '-Xours',
+ '-Xtheirs',
+ "'ours'",
+ "'theirs'",
+ '--continue',
+ '--skip',
+ '--abort',
+ '--no-commit',
+ ];
+ for (const escape of escapes) {
+ expect(source).not.toContain(escape);
+ }
+ });
+
+ test('rejects a mode it does not recognize rather than defaulting to cherry-pick', () => {
+ const io = makeIo();
+ expect(() => runPointRelease({ mode: 'rebase', fixRefs: ['bad1'], dryRun: true }, io)).toThrow(/not one of/);
+ expect(io.applied).toEqual([]);
+ });
+});
+
+// The workflow and this script are two files that have to agree on a set of
+// literal names: the env vars the workflow sets and the script reads, and the
+// step outputs the script writes and the workflow reads back. Nothing at runtime
+// catches a rename on either side — a mistyped env name degrades to a dry run
+// that still reports success, and a mistyped output name prints an empty summary
+// — so the agreement is pinned here, the one place both files can be read
+// together.
+describe('point-release.yml contract with this script', () => {
+ const workflow = readFileSync(new URL('../workflows/point-release.yml', import.meta.url), 'utf8');
+ const source = readFileSync(new URL('./point-release-plan.mjs', import.meta.url), 'utf8');
+
+ // Just the step that runs the script. Bounded at the next step so a name the
+ // summary step happens to set cannot stand in for one this step forgot.
+ const stepStart = workflow.indexOf('- name: Run the point release');
+ const runStep = workflow.slice(stepStart, workflow.indexOf('\n - name:', stepStart + 1));
+ const provided = new Set([...runStep.matchAll(/^ {10}([A-Z][A-Z0-9_]*): /gm)].map((m) => m[1]));
+
+ test('runs this script with every environment variable it reads', () => {
+ expect(runStep).toContain('node .github/scripts/point-release-plan.mjs');
+ expect(provided.size).toBeGreaterThan(0);
+
+ // Supplied by the Actions runtime itself, never by an env: block.
+ const fromRunner = new Set(['GITHUB_REPOSITORY', 'GITHUB_OUTPUT']);
+ const read = [...source.matchAll(/process\.env\.([A-Z][A-Z0-9_]*)/g)].map((m) => m[1]);
+ expect(read.length).toBeGreaterThan(0);
+
+ expect([...new Set(read)].filter((name) => !provided.has(name) && !fromRunner.has(name))).toEqual([]);
+ });
+
+ test('reads back only step outputs this script writes', () => {
+ const outputBlock = source.slice(source.indexOf('if (process.env.GITHUB_OUTPUT)'));
+ const emitted = new Set([...outputBlock.matchAll(/`([a-z_]+)=\$\{/g)].map((m) => m[1]));
+ expect(emitted.size).toBeGreaterThan(0);
+
+ const consumed = [...new Set([...workflow.matchAll(/steps\.plan\.outputs\.([a-z_]+)/g)].map((m) => m[1]))];
+ expect(consumed.length).toBeGreaterThan(0);
+
+ expect(consumed.filter((name) => !emitted.has(name))).toEqual([]);
+ });
+
+ test('defaults to a dry run and passes that default through to the script', () => {
+ const inputStart = workflow.indexOf(' dry_run:');
+ const input = workflow.slice(inputStart, workflow.indexOf('\n dispatched_by:', inputStart));
+ expect(input).toContain('type: boolean');
+ expect(input).toContain('default: true');
+
+ // The script arms a real run only on the literal string 'false', so the
+ // wiring has to be the input itself and not a constant or a fallback that
+ // could resolve to 'false' on an unattended path.
+ expect(runStep).toMatch(/DRY_RUN: \$\{\{ inputs\.dry_run \}\}/);
+ expect(source).toContain("process.env.DRY_RUN !== 'false'");
+ });
+});
diff --git a/.github/workflows/point-release.yml b/.github/workflows/point-release.yml
new file mode 100644
index 000000000..68a729b08
--- /dev/null
+++ b/.github/workflows/point-release.yml
@@ -0,0 +1,234 @@
+name: Point release
+
+# On-demand point release on inkeep/open-knowledge: ship the current stable plus
+# ONE self-contained fix to the npm `latest` channel, leaving everything still
+# soaking behind it exactly where it is.
+#
+# Why the lane exists. A stable tag lands on a main SHA, and on one linear
+# history there is no commit that is "last stable plus this one fix" without
+# also being a prefix of everything else merged since. So when a critical fix
+# has to reach users now, the ordinary promotion path offers only two options:
+# wait out the 24h soak, or ship the entire unsoaked pile. This workflow builds
+# the missing commit instead — it detaches at the last stable tag and applies
+# the fix there — so the release contains that fix and nothing else.
+#
+# Two modes. `cherry-pick` ships a forward fix. `revert` undoes a bad commit
+# already inside the current stable; it exists because the desktop auto-updater
+# is roll-forward only, so a bad unattended stable cannot be recalled, only
+# superseded.
+#
+# Dry run is the default, and that default is the safety model. A dry run
+# resolves the last stable, builds the synthetic commit locally, computes the
+# version and runs every guard, then stops before the first remote mutation —
+# no tag, no Release, no dispatch. Arming a real run means unchecking dry_run
+# deliberately, having read the plan a dry run printed.
+#
+# All decision logic lives in .github/scripts/point-release-plan.mjs, which is
+# unit-tested; this file only supplies credentials, a full-history checkout and
+# a committer identity. Keeping the guards in tested JavaScript rather than
+# inline bash matters more here than elsewhere: this lane skips the soak, so its
+# preconditions are the only thing between a mistaken input and an unvalidated
+# release on the channel every default install follows.
+#
+# Cascade. On a real run the script tags, creates a DRAFT Release, and dispatches
+# the same three consumers the ordinary promotion does — release.yml (npm
+# publish), desktop-release.yml (signed DMG, which also flips the draft to
+# published), and main-reset on agents-private (changeset consolidation). Their
+# input contracts are untouched: this is a different way to reach the existing
+# cascade, not a second one.
+#
+# Token model, inherited from promote-stable.yml. The synthetic commit carries
+# the LAST STABLE's .github/workflows/ tree, which differs from main whenever any
+# workflow changed since — so pushing a tag at that commit is a workflow-touching
+# push and the App-token policy refuses it without `workflows: write`. The tag
+# push therefore runs under an INTERNAL_CI_APP installation token holding that
+# grant, not under GITHUB_TOKEN, which cannot be granted `workflows` at all
+# (it is not a valid permissions: key). See promote-stable.yml's header for the
+# full rejection signature and the one-time installation grant it requires.
+#
+# Concurrency group is shared with release.yml and promote-stable.yml so a point
+# release never races a beta cut or an ordinary promotion.
+
+on:
+ workflow_dispatch:
+ inputs:
+ mode:
+ description: "cherry-pick a forward fix onto the current stable, or revert a bad commit already in it."
+ required: true
+ type: choice
+ options:
+ - cherry-pick
+ - revert
+ default: cherry-pick
+ fix_refs:
+ description: "Commit SHA(s) to apply, comma- or space-separated. Each must already be on main."
+ required: true
+ type: string
+ anchor_delta_ids:
+ description: "Changeset id(s) for main-reset to consolidate. Revert mode has none of its own — name one here or the main-reset dispatch is skipped and the anchor stays behind."
+ required: false
+ type: string
+ dry_run:
+ description: "Compute and print the plan without touching anything remote. Uncheck to actually ship."
+ required: false
+ type: boolean
+ default: true
+ dispatched_by:
+ description: "URL of the run that dispatched this release (run-to-run link). Blank for manual runs."
+ required: false
+ type: string
+
+permissions:
+ # Every identity-asserting call (tag push, Release creation, repository_dispatch)
+ # runs under an App-minted token, not this one; see the token-model comment
+ # above. contents: write keeps the workflow-default GITHUB_TOKEN usable for the
+ # ordinary checkout. npm publishing is delegated to release.yml over
+ # repository_dispatch, so no id-token is needed here — the dispatched run keeps
+ # its own OIDC identity, which is what npm Trusted Publishing binds against.
+ contents: write
+ # Read-only: lets the plan script resolve the newest green native-config
+ # prebuild run, which its provenance guard checks the synthetic commit against.
+ actions: read
+
+concurrency:
+ group: ok-release-cadence
+ cancel-in-progress: false
+
+jobs:
+ point-release:
+ name: ${{ inputs.dry_run && 'Plan' || 'Ship' }} point release (${{ inputs.mode }})
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - name: Generate GitHub App token
+ # See the token-model comment at the top of this file. The minted token
+ # only clears the App-token workflow-change policy if this App's
+ # installation on this repo carries `workflows: write`.
+ id: app-token
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ # Public client ID for inkeep-internal-ci (non-secret; supersedes the deprecated app-id input).
+ client-id: Iv23liNt1mrrdgVKHn8K
+ private-key: ${{ secrets.INTERNAL_CI_APP_PRIVATE_KEY }}
+
+ - name: Checkout
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ # Full history AND all tags. Three separate things need it: resolving
+ # the newest stable tag, diffing .changeset/*.md between that tag and
+ # the synthetic commit, and walking ancestry to prove each fix ref is
+ # already on main.
+ fetch-depth: 0
+ # Persist the App token into .git/config so the later `git push origin
+ # <tag>` runs as the App. Without this the push falls back to
+ # GITHUB_TOKEN and hits the workflow-change policy on any stable whose
+ # .github/workflows/ tree differs from main HEAD.
+ token: ${{ steps.app-token.outputs.token }}
+
+ - name: Set up Node
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
+ with:
+ node-version: "24"
+
+ - name: Prepare git for the synthetic commit
+ run: |
+ set -euo pipefail
+ # The refs-on-main guard asks whether each fix ref is an ancestor of
+ # origin/main. Checkout only creates the remote-tracking ref for the
+ # branch the run was dispatched from, so fetch main explicitly rather
+ # than let a non-default-branch dispatch turn the guard into a git
+ # error about a missing ref.
+ git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
+
+ # cherry-pick and revert both write a commit, and a runner has no
+ # committer identity configured, so without this the apply step fails
+ # with git's "please tell me who you are" before any guard is reached.
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+
+ - name: Detect bridge App for cross-repo dispatch
+ # main-reset runs on agents-private, and neither GITHUB_TOKEN nor the
+ # INTERNAL_CI_APP token can write there. The "Inkeep OK Release Bridge"
+ # App supplies that credential. Absence is not an error: the release
+ # still ships and the plan warns the operator to run main-reset by hand.
+ # Secrets are unreadable in `if:` expressions, so the presence check runs
+ # as a step and gates the mint through an output.
+ id: bridge-check
+ env:
+ OK_RELEASE_BRIDGE_APP_ID: ${{ secrets.OK_RELEASE_BRIDGE_APP_ID }}
+ run: |
+ set -euo pipefail
+ if [[ -n "${OK_RELEASE_BRIDGE_APP_ID:-}" ]]; then
+ echo "configured=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "configured=false" >> "$GITHUB_OUTPUT"
+ echo "OK_RELEASE_BRIDGE_APP_ID not set — the main-reset dispatch will be skipped; run it manually on agents-private."
+ fi
+
+ - name: Mint cross-repo dispatch token (bridge App)
+ if: steps.bridge-check.outputs.configured == 'true'
+ id: bridge-token
+ uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
+ with:
+ # Public client ID for inkeep-ok-release-bridge (non-secret; supersedes the deprecated app-id input).
+ client-id: Iv23lii4qS2FAc6tkzfI
+ private-key: ${{ secrets.OK_RELEASE_BRIDGE_APP_PRIVATE_KEY }}
+ # The bridge App is installed on agents-private, not on the repo this
+ # workflow runs on; owner + repositories scope the token to it.
+ owner: inkeep
+ repositories: agents-private
+
+ - name: Run the point release
+ id: plan
+ env:
+ # Every value reaches the shell through env rather than direct ${{ }}
+ # substitution: an expression is expanded textually before bash parses
+ # the line, so a crafted input would run as shell. Defense-in-depth,
+ # since dispatching this workflow already needs repo write access.
+ GH_TOKEN: ${{ steps.app-token.outputs.token }}
+ # Empty when the bridge App is absent; the script reads that as
+ # "no cross-repo credential" and skips the main-reset dispatch.
+ BRIDGE_GH_TOKEN: ${{ steps.bridge-token.outputs.token }}
+ BRIDGE_CONFIGURED: ${{ steps.bridge-check.outputs.configured }}
+ MODE: ${{ inputs.mode }}
+ FIX_REFS: ${{ inputs.fix_refs }}
+ ANCHOR_DELTA_IDS: ${{ inputs.anchor_delta_ids }}
+ # The script arms a real run only on the literal string "false", so any
+ # other value — including an unset variable — stays a dry run.
+ DRY_RUN: ${{ inputs.dry_run }}
+ DISPATCHED_BY: ${{ inputs.dispatched_by }}
+ # Writes the plan as JSON to stdout and dry_run / point_release_tag /
+ # point_release_version / latest_stable_tag / synthetic_sha / delta_ids /
+ # main_reset_dispatched to GITHUB_OUTPUT. Exit 2 is a guard refusing
+ # (a named precondition said no); exit 1 is an infra failure. Either way
+ # nothing remote has been touched — every mutation happens after the
+ # last guard. Logic + tests: .github/scripts/point-release-plan.{mjs,test.mjs}.
+ run: node .github/scripts/point-release-plan.mjs
+
+ - name: Summarize
+ env:
+ DRY_RUN: ${{ steps.plan.outputs.dry_run }}
+ POINT_RELEASE_TAG: ${{ steps.plan.outputs.point_release_tag }}
+ LATEST_STABLE_TAG: ${{ steps.plan.outputs.latest_stable_tag }}
+ SYNTHETIC_SHA: ${{ steps.plan.outputs.synthetic_sha }}
+ DELTA_IDS: ${{ steps.plan.outputs.delta_ids }}
+ MAIN_RESET_DISPATCHED: ${{ steps.plan.outputs.main_reset_dispatched }}
+ MODE: ${{ inputs.mode }}
+ FIX_REFS: ${{ inputs.fix_refs }}
+ run: |
+ set -euo pipefail
+ {
+ if [[ "$DRY_RUN" == "true" ]]; then
+ echo "### Point release plan — DRY RUN, nothing was pushed"
+ else
+ echo "### Point release ${POINT_RELEASE_TAG} shipped"
+ fi
+ echo "- Tag: \`${POINT_RELEASE_TAG}\` at \`${SYNTHETIC_SHA}\`"
+ echo "- Over stable: \`${LATEST_STABLE_TAG}\`"
+ echo "- Mode: \`${MODE}\` of \`${FIX_REFS}\`"
+ echo "- Changeset delta for main-reset: \`${DELTA_IDS}\` (dispatched: ${MAIN_RESET_DISPATCHED})"
+ if [[ "$DRY_RUN" == "true" ]]; then
+ echo ""
+ echo "Re-run with **dry_run unchecked** to ship this plan."
+ fi
+ } >> "$GITHUB_STEP_SUMMARY"
diff --git a/scripts/compute-stable-version.mjs b/scripts/compute-stable-version.mjs
index 5979904d3..a28a91cea 100644
--- a/scripts/compute-stable-version.mjs
+++ b/scripts/compute-stable-version.mjs
@@ -33,6 +33,13 @@
* "something is wrong". The mode is additive; the beta-tag contract above is
* unchanged, because sibling workflows already depend on it.
*
+ * Third mode: node scripts/compute-stable-version.mjs --point-release <mode> <sha>
+ * See `computePointReleaseVersion` below. The point-release lane builds a
+ * synthetic commit that no tag names, so it cannot ask the beta-tag mode for a
+ * version. Appends point_release_version / point_release_tag / bump /
+ * added_ids / removed_ids / latest_stable_version / latest_stable_sha to
+ * $GITHUB_OUTPUT. Also additive.
+ *
* The pure core (`computeStablePromotion`) takes its git boundary as an injected
* dependency so tests need no live repo (mirrors promote-stable-auto.mjs).
*/
@@ -136,6 +143,66 @@ export function computeStablePromotion(betaTag, git) {
};
}
+/**
+ * The stable version a POINT RELEASE lands on: one bump over the current
+ * stable, computed from the changeset delta of an arbitrary synthetic commit
+ * instead of a beta tag.
+ *
+ * Why this is a second entry point rather than a widened `computeStablePromotion`.
+ * That function's input is a beta TAG, and two of its branches are correct for
+ * the soak lane and wrong here. A point release builds its own commit that no
+ * tag names, so there is nothing to `revParse`. And in revert mode the added
+ * changeset delta is legitimately empty, which the promotion path reads as
+ * "nothing to promote" and declines. The version arithmetic underneath is the
+ * same set difference, so it is reused; the decision wrapped around it is not.
+ *
+ * Where the bump comes from depends on `mode`:
+ * 'cherry-pick' — max bump across the changesets the picked fix brought in,
+ * the same rule the soak lane applies.
+ * 'revert' — the constant 'patch'. A revert restores already-shipped
+ * behavior and adds no changeset, so there is no frontmatter
+ * to read and nothing that could justify minor or major.
+ *
+ * `removedIds` is reported, never acted on here. A revert dropping a still
+ * pending changeset from the synthetic tree is expected; the same in
+ * cherry-pick mode means the operator picked a ref that undoes pending work,
+ * and the caller's delta guard needs both halves of the difference to say so.
+ *
+ * A missing or malformed `latestStableTag` throws instead of bootstrapping.
+ * There is no bootstrap shape here by construction: a point release is a patch
+ * OVER an existing stable, so no stable at all means the wrong lane, not a
+ * first release.
+ *
+ * Returns { version, tag, latestStableVersion, addedIds, removedIds, bump }.
+ */
+export function computePointReleaseVersion({ syntheticSha, latestStableTag, latestStableSha, mode }, git) {
+ if (mode !== 'cherry-pick' && mode !== 'revert') {
+ // An unrecognized mode would otherwise fall through to the cherry-pick
+ // branch and read frontmatter off changesets a revert never added.
+ throw new Error(`Point-release mode '${mode}' is not one of: cherry-pick, revert.`);
+ }
+ const sha = String(syntheticSha ?? '').trim();
+ if (sha === '') throw new Error('Point-release requires a synthetic commit sha.');
+ const stableSha = String(latestStableSha ?? '').trim();
+ if (stableSha === '') throw new Error('Point-release requires the latest stable commit sha.');
+ const stableTag = String(latestStableTag ?? '').trim();
+ if (!STABLE_TAG_RE.test(stableTag)) {
+ throw new Error(`latest stable tag '${latestStableTag}' is not in the expected vX.Y.Z format.`);
+ }
+
+ const latestStableVersion = stableTag.slice(1);
+ const stableIdList = git.changesetIds(stableSha);
+ const syntheticIdList = git.changesetIds(sha);
+ const stableIds = new Set(stableIdList);
+ const syntheticIds = new Set(syntheticIdList);
+ const addedIds = syntheticIdList.filter((id) => !stableIds.has(id));
+ const removedIds = stableIdList.filter((id) => !syntheticIds.has(id));
+
+ const bump = mode === 'revert' ? 'patch' : maxBumpType(addedIds.map((id) => git.bumpTypeOf(sha, id)));
+ const version = bumpSemver(latestStableVersion, bump);
+ return { version, tag: `v${version}`, latestStableVersion, addedIds, removedIds, bump };
+}
+
/**
* Is the changeset anchor still level with the newest stable tag?
*
@@ -220,8 +287,15 @@ function compareVersions(a, b) {
}
// --- workflow-runtime wiring (real git boundary) ---
+//
+// `runGit`, `realGit` and `readAnchorVersion` are exported because
+// .github/scripts/point-release-plan.mjs builds its own boundary on top of
+// them. Keeping one implementation matters most for `isAncestor` and
+// `changesetIds`: a second copy that read a clean "not an ancestor" and an
+// infra failure the same way would let a release path decide confidently on a
+// git error.
-function runGit(args) {
+export function runGit(args) {
const res = spawnSync('git', args, { encoding: 'utf8' });
if (res.status !== 0) {
throw new Error(`git ${args.join(' ')} failed (exit ${res.status}): ${String(res.stderr || '').trim()}`);
@@ -229,7 +303,7 @@ function runGit(args) {
return String(res.stdout || '');
}
-const realGit = {
+export const realGit = {
revParse: (ref) => runGit(['rev-parse', '--verify', `${ref}^{commit}`]).trim(),
newestStableTag: () => {
for (const line of runGit(['tag', '--list', 'v*', '--sort=-version:refname']).split('\n')) {
@@ -264,7 +338,7 @@ const realGit = {
// while the stable tags only exist where releases are cut. Run this in the
// source monorepo instead and `newestStableTag` returns a different product's
// `v*` tags, so the guard refuses on every invocation.
-function readAnchorVersion() {
+export function readAnchorVersion() {
const pre = JSON.parse(readFileSync('.changeset/pre.json', 'utf8'));
// Outside pre mode `initialVersions` is whatever the last cycle left behind,
// which would read as a plausible anchor and yield a confident wrong verdict.
@@ -312,12 +386,60 @@ function anchorGuardMain() {
log(result.reason);
}
+function pointReleaseMain() {
+ let result;
+ try {
+ const latestStableTag = realGit.newestStableTag();
+ if (!latestStableTag) {
+ throw new Error('No stable tag exists in this clone; a point release is a patch over an existing stable.');
+ }
+ result = computePointReleaseVersion(
+ {
+ syntheticSha: process.argv[4],
+ latestStableTag,
+ latestStableSha: realGit.revParse(latestStableTag),
+ mode: process.argv[3],
+ },
+ realGit,
+ );
+ } catch (err) {
+ console.error(`::error::compute-stable-version --point-release: ${err.message}`);
+ process.exit(1);
+ }
+
+ log(
+ `Point release -> ${result.tag} (${result.bump} over v${result.latestStableVersion}; ` +
+ `${result.addedIds.length} added, ${result.removedIds.length} removed changesets).`,
+ );
+ console.log(JSON.stringify(result));
+
+ if (process.env.GITHUB_OUTPUT) {
+ appendFileSync(
+ process.env.GITHUB_OUTPUT,
+ [
+ `point_release_version=${result.version}`,
+ `point_release_tag=${result.tag}`,
+ `latest_stable_version=${result.latestStableVersion}`,
+ `bump=${result.bump}`,
+ `added_ids=${JSON.stringify(result.addedIds)}`,
+ `removed_ids=${JSON.stringify(result.removedIds)}`,
+ '',
+ ].join('\n'),
+ );
+ }
+}
+
function main() {
if (process.argv[2] === '--anchor-guard') {
anchorGuardMain();
return;
}
+ if (process.argv[2] === '--point-release') {
+ pointReleaseMain();
+ return;
+ }
+
const betaTag = process.argv[2];
if (!betaTag) {
log('::error::compute-stable-version: missing beta tag argument (usage: compute-stable-version.mjs <vX.Y.Z-beta.N>).');
diff --git a/scripts/compute-stable-version.test.mjs b/scripts/compute-stable-version.test.mjs
index 0b268a3c9..e0038d849 100644
--- a/scripts/compute-stable-version.test.mjs
+++ b/scripts/compute-stable-version.test.mjs
@@ -1,5 +1,5 @@
import { describe, expect, test } from 'vitest';
-import { computeStablePromotion, evaluateAnchorGuard } from './compute-stable-version.mjs';
+import { computePointReleaseVersion, computeStablePromotion, evaluateAnchorGuard } from './compute-stable-version.mjs';
// Injected git boundary so tests need no repo. Defaults: unknown changeset bump
// types resolve to 'patch' (the patch floor), isAncestor false.
@@ -186,3 +186,168 @@ describe('evaluateAnchorGuard', () => {
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'] } });
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'cherry-pick' },
+ git,
+ );
+ expect(r).toMatchObject({
+ version: '0.32.1',
+ tag: 'v0.32.1',
+ latestStableVersion: '0.32.0',
+ bump: 'patch',
+ addedIds: ['fix1'],
+ removedIds: [],
+ });
+ });
+
+ test('revert mode over the canonical shape: the culprit changeset leaves, nothing arrives', () => {
+ const git = fakeGit({ changesets: { S: ['c0', 'bad'], SYN: ['c0'] } });
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'revert' },
+ git,
+ );
+ expect(r).toMatchObject({
+ version: '0.32.1',
+ tag: 'v0.32.1',
+ bump: 'patch',
+ addedIds: [],
+ removedIds: ['bad'],
+ });
+ });
+
+ test('revert mode reads no changeset frontmatter even when the delta is non-empty', () => {
+ // With a real boundary the read is `git show <sha>:.changeset/<id>.md`, so
+ // routing revert through the cherry-pick bump path would fail the run
+ // outright whenever the revert deleted the file being read. The fake throws
+ // to pin that the call never happens.
+ const git = {
+ ...fakeGit({ changesets: { S: ['c0'], SYN: ['c0', 'leftover'] } }),
+ bumpTypeOf: () => {
+ throw new Error('revert mode must not read changeset frontmatter');
+ },
+ };
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'revert' },
+ git,
+ );
+ expect(r).toMatchObject({ version: '0.32.1', bump: 'patch', addedIds: ['leftover'] });
+ });
+
+ test('revert mode stays a patch even when the synthetic tree gained a major changeset', () => {
+ // Guards against a future refactor routing revert through the cherry-pick
+ // bump path: a stray added changeset must not silently escalate the version.
+ const git = fakeGit({ changesets: { S: ['c0'], SYN: ['c0', 'stray'] }, bumps: { stray: 'major' } });
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'revert' },
+ git,
+ );
+ expect(r).toMatchObject({ version: '0.32.1', bump: 'patch', addedIds: ['stray'] });
+ });
+
+ test('cherry-pick mode takes the max bump across the added changesets', () => {
+ const git = fakeGit({
+ changesets: { S: ['c0'], SYN: ['c0', 'p1', 'm1'] },
+ bumps: { p1: 'patch', m1: 'minor' },
+ });
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.4', latestStableSha: 'S', mode: 'cherry-pick' },
+ git,
+ );
+ expect(r).toMatchObject({ version: '0.33.0', tag: 'v0.33.0', bump: 'minor', addedIds: ['p1', 'm1'] });
+ });
+
+ test('removedIds reports the changesets the stable had and the synthetic tree lost', () => {
+ const git = fakeGit({ changesets: { S: ['keep', 'gone'], SYN: ['keep', 'new'] } });
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'cherry-pick' },
+ git,
+ );
+ expect(r.addedIds).toEqual(['new']);
+ expect(r.removedIds).toEqual(['gone']);
+ });
+
+ test('an empty added delta still yields a patch bump in cherry-pick mode', () => {
+ // maxBumpType floors at 'patch' for an empty list, so the version is always
+ // computable; refusing an empty delta is the caller's guard, not this one's.
+ const git = fakeGit({ changesets: { S: ['c0'], SYN: ['c0'] } });
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'cherry-pick' },
+ git,
+ );
+ expect(r).toMatchObject({ version: '0.32.1', bump: 'patch', addedIds: [], removedIds: [] });
+ });
+
+ test('double-digit version components bump numerically', () => {
+ const git = fakeGit({ changesets: { S: [], SYN: ['fix'] } });
+ expect(
+ computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.35.19', latestStableSha: 'S', mode: 'revert' },
+ git,
+ ).tag,
+ ).toBe('v0.35.20');
+ expect(
+ computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.9.0', latestStableSha: 'S', mode: 'cherry-pick' },
+ git,
+ ).tag,
+ ).toBe('v0.9.1');
+ });
+
+ test('a malformed or absent latest stable tag throws rather than bootstrapping', () => {
+ // A point release is a patch OVER an existing stable; no stable at all means
+ // the operator is on the wrong lane, not that this is a first release.
+ const git = fakeGit();
+ const call = (latestStableTag) =>
+ computePointReleaseVersion({ syntheticSha: 'SYN', latestStableTag, latestStableSha: 'S', mode: 'revert' }, git);
+ expect(() => call('')).toThrow(/vX\.Y\.Z format/);
+ expect(() => call('v0.32.0-beta.4')).toThrow(/vX\.Y\.Z format/);
+ expect(() => call('garbage')).toThrow(/vX\.Y\.Z format/);
+ expect(() => call(undefined)).toThrow(/vX\.Y\.Z format/);
+ });
+
+ test('an unrecognized mode throws instead of defaulting to a bump rule', () => {
+ const git = fakeGit({ changesets: { S: [], SYN: ['fix'] } });
+ expect(() =>
+ computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'revrt' },
+ git,
+ ),
+ ).toThrow(/not one of: cherry-pick, revert/);
+ expect(() =>
+ computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: undefined },
+ git,
+ ),
+ ).toThrow(/not one of: cherry-pick, revert/);
+ });
+
+ test('a missing commit sha on either side throws a named error', () => {
+ const git = fakeGit({ changesets: { S: [], SYN: [] } });
+ expect(() =>
+ computePointReleaseVersion(
+ { syntheticSha: '', latestStableTag: 'v0.32.0', latestStableSha: 'S', mode: 'revert' },
+ git,
+ ),
+ ).toThrow(/synthetic commit sha/);
+ expect(() =>
+ computePointReleaseVersion(
+ { syntheticSha: 'SYN', latestStableTag: 'v0.32.0', latestStableSha: undefined, mode: 'revert' },
+ git,
+ ),
+ ).toThrow(/latest stable commit sha/);
+ });
+
+ test('tolerates surrounding whitespace from raw git output', () => {
+ const git = fakeGit({ changesets: { S: ['c0'], SYN: ['c0', 'fix'] } });
+ const r = computePointReleaseVersion(
+ { syntheticSha: 'SYN\n', latestStableTag: ' v0.32.0\n', latestStableSha: ' S ', mode: 'cherry-pick' },
+ git,
+ );
+ expect(r.tag).toBe('v0.32.1');
+ expect(r.addedIds).toEqual(['fix']);
+ });
+});