Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

ci(ok): derive shipped version from GitOrigin-RevId; add anchor guard (#2953)

Andrew Mikofalvybe39a2f070d9
diff --git a/.github/scripts/resolve-shipped-version.mjs b/.github/scripts/resolve-shipped-version.mjs
new file mode 100644
index 000000000..094caf90c
--- /dev/null
+++ b/.github/scripts/resolve-shipped-version.mjs
@@ -0,0 +1,337 @@
+#!/usr/bin/env node
+/**
+ * Answer "which stable version shipped this fix?" for a fix that merged on the
+ * private monorepo and reached this repo through the Copybara mirror.
+ *
+ * Why this is not a one-liner. The mirror rewrites commit SHAs, and the
+ * mirrored commits have no pull requests in the repo where the release tags
+ * live — so the usual `release commits -> associatedPullRequests -> closing
+ * keywords` walk that every off-the-shelf release notifier uses returns
+ * nothing here. What the mirror *does* write unconditionally is a
+ * `GitOrigin-RevId: <source-sha>` trailer, so the chain runs the other way:
+ *
+ * private PR -> merge commit SHA -> GitOrigin-RevId match -> mirrored
+ * commit -> lowest stable tag whose history contains it
+ *
+ * The last hop is TAG CONTAINMENT, not pull-request association, which is why
+ * the mirror break above does not affect it.
+ *
+ * "Most recent release published after the merge date" is NOT the answer and
+ * gets this wrong in practice: mirrored commit eb52a625cd86859a8ec43ddc8f96e9b418d092a7
+ * is absent from v0.35.0 through v0.35.6 and first appears in v0.36.0, even
+ * though three of those v0.35.x stables published after its source merged. The
+ * colocated test pins that case.
+ *
+ * Relationship to the Linear release stamping workflow: that workflow answers
+ * the inverse question (given a release, which tickets does it carry) by
+ * scanning commit text, and writes to Linear. This script writes nowhere and
+ * reads only git; the two do not overlap in mechanism or in output.
+ *
+ * Usage:
+ * node .github/scripts/resolve-shipped-version.mjs <sha | pr-url | #N | N>
+ *
+ * Must run inside a full clone of this repo (`fetch-depth: 0`, `fetch-tags:
+ * true`) — the containment walk needs every stable tag and the mirror lookup
+ * needs full history.
+ *
+ * Emits JSON to stdout and, under Actions, appends
+ * shipped / version / tag / private_sha / mirrored_sha
+ * to $GITHUB_OUTPUT. Logs go to stderr.
+ *
+ * Fail-loud contract, matching the sibling selection script: "not mirrored
+ * yet" and "mirrored but not in any stable yet" are real ANSWERS and exit 0 —
+ * a caller that must refuse rather than guess reads `shipped: false` and
+ * declines. Every other failure (bad ref, git/gh error, ambiguous input) exits
+ * non-zero. An infra error must never collapse into "not shipped", because a
+ * caller cannot distinguish that from the truth and would either stay silent
+ * forever or, worse, name the wrong version.
+ *
+ * The pure core takes its git/gh boundary as injected dependencies so the
+ * tests need no live repo, no network, and no tags.
+ */
+import { execFileSync, spawnSync } from 'node:child_process';
+import { appendFileSync } from 'node:fs';
+import { pathToFileURL } from 'node:url';
+
+const STABLE_TAG_RE = /^v(\d+)\.(\d+)\.(\d+)$/;
+const FULL_SHA_RE = /^[0-9a-f]{40}$/i;
+// Copybara emits the trailer on its own line. Matched case-insensitively on
+// the key and anchored to a line start so a trailer quoted inside a prose body
+// (a squash message that pasted another commit's footer) cannot outrank the
+// real one.
+const REV_ID_RE = /^[ \t]*GitOrigin-RevId:[ \t]*([0-9a-f]{7,40})[ \t]*$/gim;
+// Accepts both hosts' PR URL shapes plus the bare `#N` / `N` forms an operator
+// is likely to paste.
+const PR_URL_RE = /^https?:\/\/[^/]*github\.com\/([^/]+)\/([^/]+)\/pull\/(\d+)(?:[/?#].*)?$/i;
+const PR_NUMBER_RE = /^#?(\d+)$/;
+
+const DEFAULT_PRIVATE_REPO = 'inkeep/agents-private';
+
+function log(...args) {
+ process.stderr.write(`${args.join(' ')}\n`);
+}
+
+/**
+ * Every `GitOrigin-RevId` value in a commit message, in order of appearance.
+ * A message normally carries exactly one; more than one means the message
+ * embedded someone else's footer, which the caller resolves by exact match
+ * rather than by position.
+ */
+export function parseGitOriginRevIds(commitMessage) {
+ const ids = [];
+ for (const m of String(commitMessage ?? '').matchAll(REV_ID_RE)) {
+ ids.push(m[1].toLowerCase());
+ }
+ return ids;
+}
+
+/**
+ * Parse the operator-facing fix reference into something resolvable.
+ * { kind: 'sha', sha } — a full 40-hex commit SHA
+ * { kind: 'pr', owner, repo, number } — a PR URL, `#N`, or `N`
+ * Throws on anything else: guessing at a malformed ref is how a caller ends up
+ * naming a version that belongs to a different change.
+ */
+export function parseFixRef(raw, { defaultRepo = DEFAULT_PRIVATE_REPO } = {}) {
+ const ref = String(raw ?? '').trim();
+ if (!ref) throw new Error('missing fix reference (expected a commit SHA, a PR URL, or #N)');
+
+ if (FULL_SHA_RE.test(ref)) return { kind: 'sha', sha: ref.toLowerCase() };
+
+ const urlMatch = PR_URL_RE.exec(ref);
+ if (urlMatch) {
+ return { kind: 'pr', owner: urlMatch[1], repo: urlMatch[2], number: Number(urlMatch[3]) };
+ }
+
+ const numMatch = PR_NUMBER_RE.exec(ref);
+ if (numMatch) {
+ const [owner, repo] = defaultRepo.split('/');
+ if (!owner || !repo) throw new Error(`invalid default repo '${defaultRepo}' (expected owner/repo)`);
+ return { kind: 'pr', owner, repo, number: Number(numMatch[1]) };
+ }
+
+ // An abbreviated SHA is rejected rather than expanded: this repo cannot
+ // resolve a private-repo abbreviation, and a 7-char prefix is not unique
+ // enough to trust across two repositories.
+ throw new Error(
+ `unrecognized fix reference '${ref}' (expected a full 40-character commit SHA, a PR URL, or #N)`,
+ );
+}
+
+/** Sort `vX.Y.Z` tags ascending by numeric semver, dropping non-conforming refs. */
+export function sortStableTagsAscending(rawTags) {
+ const parsed = [];
+ for (const line of rawTags) {
+ const m = STABLE_TAG_RE.exec(String(line).trim());
+ if (m) parsed.push({ tag: m[0], key: [Number(m[1]), Number(m[2]), Number(m[3])] });
+ }
+ parsed.sort((a, b) => a.key[0] - b.key[0] || a.key[1] - b.key[1] || a.key[2] - b.key[2]);
+ return parsed.map((p) => p.tag);
+}
+
+/**
+ * Lowest-version stable tag whose history contains `sha`, or null if none does.
+ *
+ * The walk is linear rather than a binary search because containment is NOT
+ * monotonic across the tag order: a point release is cut off the previous
+ * stable rather than off `main`, so a higher tag can contain a commit that a
+ * lower one does not and vice versa. Bisecting an unsorted-by-containment
+ * sequence would silently skip the real first hit.
+ *
+ * Any throw from `contains` propagates — an unreadable tag is an infra error,
+ * not evidence of non-containment.
+ */
+export function firstContainingStableTag({ sortedStableTags, sha, contains }) {
+ for (const tag of sortedStableTags) {
+ if (contains(tag, sha)) return tag;
+ }
+ return null;
+}
+
+/**
+ * Pure decision core. Boundaries are injected:
+ * findMirroredCommits(privateSha) -> [{ sha, message }] (candidates; may over-match)
+ * contains(tag, sha) -> boolean (sha is in tag's history)
+ *
+ * Returns one of:
+ * { shipped: true, privateSha, mirroredSha, mirroredShas, tag, version }
+ * { shipped: false, reason: 'not-mirrored', privateSha, mirroredShas: [] }
+ * { shipped: false, reason: 'not-in-any-stable', privateSha, mirroredShas }
+ */
+export function resolveShippedVersion({ privateSha, stableTags, findMirroredCommits, contains }) {
+ if (!FULL_SHA_RE.test(String(privateSha ?? ''))) {
+ throw new Error(`privateSha must be a full 40-character commit SHA, got '${privateSha}'`);
+ }
+ const wanted = String(privateSha).toLowerCase();
+
+ // `git log --grep` is a substring match over the whole message, so a commit
+ // that merely quotes the trailer would come back too. Re-check each
+ // candidate against the parsed trailer values and keep only exact matches.
+ const mirroredShas = [];
+ for (const commit of findMirroredCommits(wanted) ?? []) {
+ if (parseGitOriginRevIds(commit.message).includes(wanted)) {
+ mirroredShas.push(String(commit.sha).toLowerCase());
+ }
+ }
+ if (mirroredShas.length === 0) {
+ return { shipped: false, reason: 'not-mirrored', privateSha: wanted, mirroredShas: [] };
+ }
+
+ const sorted = sortStableTagsAscending(stableTags);
+ const rank = new Map(sorted.map((tag, i) => [tag, i]));
+
+ // A fix can exist at more than one mirrored SHA: a point release cherry-picks
+ // it onto a synthetic off-`main` tag, and a cherry-pick carries the trailer
+ // with it. The installable answer is then the LOWEST version among the
+ // per-commit first-containing tags, not the one the `main`-line commit
+ // reaches, which would over-report and send a reporter past the point release
+ // that already carried their fix.
+ let best = null;
+ for (const mirroredSha of mirroredShas) {
+ const tag = firstContainingStableTag({ sortedStableTags: sorted, sha: mirroredSha, contains });
+ if (!tag) continue;
+ if (best === null || rank.get(tag) < rank.get(best.tag)) {
+ best = { tag, mirroredSha };
+ }
+ }
+ if (best === null) {
+ return { shipped: false, reason: 'not-in-any-stable', privateSha: wanted, mirroredShas };
+ }
+
+ return {
+ shipped: true,
+ privateSha: wanted,
+ mirroredSha: best.mirroredSha,
+ mirroredShas,
+ tag: best.tag,
+ version: best.tag.slice(1),
+ };
+}
+
+// --- workflow-runtime wiring (real git / gh boundary) ---
+
+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()}`);
+ }
+ return String(res.stdout || '');
+}
+
+function realStableTags() {
+ return runGit(['tag', '--list', 'v*', '--sort=version:refname']).split('\n');
+}
+
+// Record separator between commits and a unit separator between the SHA and
+// the raw body, so a message containing blank lines (every squash message
+// does) cannot be mistaken for a record boundary.
+const REC_SEP = '\x1e';
+const UNIT_SEP = '\x1f';
+
+function realFindMirroredCommits(privateSha) {
+ // `--all` rather than HEAD: a point release lives on a synthetic off-`main`
+ // tag, so the cherry-picked copy of a fix is unreachable from the checked-out
+ // branch. `--fixed-strings` keeps the SHA from being read as a pattern.
+ const out = runGit([
+ 'log',
+ '--all',
+ '--fixed-strings',
+ `--grep=GitOrigin-RevId: ${privateSha}`,
+ `--format=%H${UNIT_SEP}%B${REC_SEP}`,
+ ]);
+ const commits = [];
+ for (const record of out.split(REC_SEP)) {
+ const trimmed = record.replace(/^\n+/, '');
+ if (!trimmed.trim()) continue;
+ const sep = trimmed.indexOf(UNIT_SEP);
+ if (sep === -1) continue;
+ commits.push({ sha: trimmed.slice(0, sep).trim(), message: trimmed.slice(sep + 1) });
+ }
+ return commits;
+}
+
+function realContains(tag, sha) {
+ // Distinguish a clean "not an ancestor" (exit 1) from an infra failure (any
+ // other non-zero), which must fail loud rather than read as "not contained".
+ const res = spawnSync('git', ['merge-base', '--is-ancestor', sha, `${tag}^{commit}`], {
+ encoding: 'utf8',
+ });
+ if (res.status === 0) return true;
+ if (res.status === 1) return false;
+ throw new Error(
+ `git merge-base --is-ancestor ${sha} ${tag} failed (exit ${res.status}): ${String(res.stderr || '').trim()}`,
+ );
+}
+
+// The private repo is not checked out here, so the PR -> merge-commit hop goes
+// through the API. An unmerged or squash-less PR has no merge commit and is a
+// hard error: there is no fix to locate.
+function realResolvePrMergeSha({ owner, repo, number }) {
+ let out;
+ try {
+ out = execFileSync('gh', ['api', `repos/${owner}/${repo}/pulls/${number}`, '--jq', '.merged_at,.merge_commit_sha'], {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ } catch (err) {
+ throw new Error(
+ `gh api repos/${owner}/${repo}/pulls/${number} failed: ${String(err?.stderr || err?.message || '').trim()}`,
+ );
+ }
+ const [mergedAt, sha] = out.split('\n').map((s) => s.trim());
+ if (!mergedAt || mergedAt === 'null') {
+ throw new Error(`${owner}/${repo}#${number} is not merged; there is no fix commit to resolve.`);
+ }
+ if (!FULL_SHA_RE.test(sha || '')) {
+ throw new Error(`${owner}/${repo}#${number} has no usable merge_commit_sha (got '${sha}').`);
+ }
+ return sha.toLowerCase();
+}
+
+export function resolvePrivateSha(fixRef, { resolvePrMergeSha }) {
+ return fixRef.kind === 'sha' ? fixRef.sha : resolvePrMergeSha(fixRef);
+}
+
+function main() {
+ let result;
+ let fixRef;
+ try {
+ fixRef = parseFixRef(process.argv[2], { defaultRepo: process.env.PRIVATE_REPO || DEFAULT_PRIVATE_REPO });
+ const privateSha = resolvePrivateSha(fixRef, { resolvePrMergeSha: realResolvePrMergeSha });
+ result = resolveShippedVersion({
+ privateSha,
+ stableTags: realStableTags(),
+ findMirroredCommits: realFindMirroredCommits,
+ contains: realContains,
+ });
+ } catch (err) {
+ console.error(`::error::resolve-shipped-version: ${err.message}`);
+ process.exit(1);
+ }
+
+ if (result.shipped) {
+ log(`Shipped: ${result.privateSha.slice(0, 12)} -> mirrored ${result.mirroredSha.slice(0, 12)} -> ${result.tag}.`);
+ } else if (result.reason === 'not-mirrored') {
+ log(`Not shipped: no mirrored commit carries GitOrigin-RevId ${result.privateSha} yet.`);
+ } else {
+ log(`Not shipped: mirrored as ${result.mirroredShas.join(', ')}, but no stable tag contains it yet.`);
+ }
+
+ console.log(JSON.stringify(result));
+
+ if (process.env.GITHUB_OUTPUT) {
+ const lines = [
+ `shipped=${result.shipped ? 'true' : 'false'}`,
+ `version=${result.version ?? ''}`,
+ `tag=${result.tag ?? ''}`,
+ `private_sha=${result.privateSha ?? ''}`,
+ `mirrored_sha=${result.mirroredSha ?? ''}`,
+ ];
+ appendFileSync(process.env.GITHUB_OUTPUT, `${lines.join('\n')}\n`);
+ }
+}
+
+// Run main() only as a CLI, not when imported by the test file.
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main();
+}
diff --git a/.github/scripts/resolve-shipped-version.test.mjs b/.github/scripts/resolve-shipped-version.test.mjs
new file mode 100644
index 000000000..a28fc6a64
--- /dev/null
+++ b/.github/scripts/resolve-shipped-version.test.mjs
@@ -0,0 +1,346 @@
+import { describe, expect, test } from 'vitest';
+import {
+ firstContainingStableTag,
+ parseFixRef,
+ parseGitOriginRevIds,
+ resolvePrivateSha,
+ resolveShippedVersion,
+ sortStableTagsAscending,
+} from './resolve-shipped-version.mjs';
+
+// The real chain, captured from the mirror. The private merge commit, its
+// mirrored counterpart, and the containment verdict for every stable tag in
+// the surrounding range were read off the mirror repo tag by tag.
+const PRIVATE_SHA = 'da71f0c698ccaac11da915169ca6c7d585d5eb97';
+const MIRRORED_SHA = 'eb52a625cd86859a8ec43ddc8f96e9b418d092a7';
+
+// Verbatim shape of the mirrored commit message: subject with the source PR
+// number, the squashed commit subjects, then the trailer. The body did not
+// survive the mirror, which is exactly why the trailer is the carrier.
+const MIRRORED_MESSAGE = [
+ 'Increase detached server memory limit (#2767)',
+ '',
+ '* fix',
+ '* fix(desktop): raise server heap ceiling to 16 GiB',
+ '* lint(desktop): migrate spawn resolver test to vitest',
+ '',
+ `GitOrigin-RevId: ${PRIVATE_SHA}`,
+ '',
+].join('\n');
+
+// Every stable tag in the window around the fix, deliberately shuffled so the
+// tests prove the sort is applied rather than inherited from input order.
+const STABLE_TAGS_SHUFFLED = [
+ 'v0.35.4',
+ 'v0.36.0',
+ 'v0.35.0',
+ 'v0.35.6',
+ 'v0.35.2',
+ 'v0.35.1',
+ 'v0.35.3',
+ 'v0.35.5',
+];
+
+// Containment truth for MIRRORED_SHA: absent from the whole v0.35.x line,
+// present from v0.36.0 onward.
+const containsMirrored = (tag, sha) => {
+ if (sha !== MIRRORED_SHA) return false;
+ return tag === 'v0.36.0';
+};
+
+const finderFor = (commits) => () => commits;
+
+describe('parseGitOriginRevIds', () => {
+ test('extracts the trailer from a real mirrored commit message', () => {
+ expect(parseGitOriginRevIds(MIRRORED_MESSAGE)).toEqual([PRIVATE_SHA]);
+ });
+
+ test('ignores a trailer that is not on its own line', () => {
+ expect(parseGitOriginRevIds(`see GitOrigin-RevId: ${PRIVATE_SHA} for context`)).toEqual([]);
+ });
+
+ test('returns every trailer when a message embeds more than one', () => {
+ const other = 'a'.repeat(40);
+ const msg = `subject\n\nGitOrigin-RevId: ${other}\nGitOrigin-RevId: ${PRIVATE_SHA}\n`;
+ expect(parseGitOriginRevIds(msg)).toEqual([other, PRIVATE_SHA]);
+ });
+
+ test('is case-insensitive on the key and normalizes the value', () => {
+ expect(parseGitOriginRevIds(`gitorigin-revid: ${PRIVATE_SHA.toUpperCase()}`)).toEqual([PRIVATE_SHA]);
+ });
+
+ test('empty / missing message yields no trailers', () => {
+ expect(parseGitOriginRevIds('')).toEqual([]);
+ expect(parseGitOriginRevIds(undefined)).toEqual([]);
+ });
+});
+
+describe('parseFixRef', () => {
+ test('accepts a full 40-character SHA', () => {
+ expect(parseFixRef(PRIVATE_SHA)).toEqual({ kind: 'sha', sha: PRIVATE_SHA });
+ });
+
+ test('lowercases an uppercase SHA', () => {
+ expect(parseFixRef(PRIVATE_SHA.toUpperCase())).toEqual({ kind: 'sha', sha: PRIVATE_SHA });
+ });
+
+ test('accepts a PR URL and keeps its owner/repo', () => {
+ expect(parseFixRef('https://github.com/inkeep/agents-private/pull/2767')).toEqual({
+ kind: 'pr',
+ owner: 'inkeep',
+ repo: 'agents-private',
+ number: 2767,
+ });
+ });
+
+ test('accepts a PR URL with trailing path or query junk', () => {
+ expect(parseFixRef('https://github.com/inkeep/agents-private/pull/2767/files').number).toBe(2767);
+ expect(parseFixRef('https://github.com/inkeep/agents-private/pull/2767#issuecomment-1').number).toBe(2767);
+ });
+
+ test('resolves a bare #N / N against the default repo', () => {
+ expect(parseFixRef('#2767')).toEqual({ kind: 'pr', owner: 'inkeep', repo: 'agents-private', number: 2767 });
+ expect(parseFixRef('2767', { defaultRepo: 'acme/widgets' })).toEqual({
+ kind: 'pr',
+ owner: 'acme',
+ repo: 'widgets',
+ number: 2767,
+ });
+ });
+
+ test('rejects an abbreviated SHA rather than expanding it', () => {
+ expect(() => parseFixRef('eb52a62')).toThrow(/unrecognized fix reference/);
+ });
+
+ test('rejects an empty or missing ref', () => {
+ expect(() => parseFixRef('')).toThrow(/missing fix reference/);
+ expect(() => parseFixRef(undefined)).toThrow(/missing fix reference/);
+ });
+});
+
+describe('sortStableTagsAscending', () => {
+ test('sorts numerically, not lexically, and drops non-stable refs', () => {
+ const raw = ['v0.9.0', 'v0.36.0', 'v0.35.10', 'v0.35.2', 'v0.35.2-beta.4', 'main', '', 'v1.0.0'];
+ expect(sortStableTagsAscending(raw)).toEqual(['v0.9.0', 'v0.35.2', 'v0.35.10', 'v0.36.0', 'v1.0.0']);
+ });
+
+ test('tolerates surrounding whitespace from raw git output', () => {
+ expect(sortStableTagsAscending([' v0.2.0 ', '\tv0.1.0'])).toEqual(['v0.1.0', 'v0.2.0']);
+ });
+
+ test('empty input yields no tags', () => {
+ expect(sortStableTagsAscending([])).toEqual([]);
+ });
+});
+
+describe('firstContainingStableTag', () => {
+ test('returns the lowest tag whose history contains the commit', () => {
+ const tag = firstContainingStableTag({
+ sortedStableTags: sortStableTagsAscending(STABLE_TAGS_SHUFFLED),
+ sha: MIRRORED_SHA,
+ contains: containsMirrored,
+ });
+ expect(tag).toBe('v0.36.0');
+ });
+
+ test('returns null when no tag contains the commit', () => {
+ const tag = firstContainingStableTag({
+ sortedStableTags: ['v0.35.0', 'v0.35.1'],
+ sha: MIRRORED_SHA,
+ contains: containsMirrored,
+ });
+ expect(tag).toBeNull();
+ });
+
+ test('does not bisect: a lower tag that contains the commit wins over a higher one', () => {
+ // Point-release shape. v0.35.7 is cut off v0.35.6 and carries the fix;
+ // v0.36.0 carries it too. Containment is therefore not monotonic across
+ // the sorted sequence, and only a linear walk finds the lower answer.
+ const contains = (tag) => tag === 'v0.35.7' || tag === 'v0.36.0';
+ const tag = firstContainingStableTag({
+ sortedStableTags: ['v0.35.6', 'v0.35.7', 'v0.36.0'],
+ sha: MIRRORED_SHA,
+ contains,
+ });
+ expect(tag).toBe('v0.35.7');
+ });
+
+ test('propagates an infra error instead of reading it as not-contained', () => {
+ expect(() =>
+ firstContainingStableTag({
+ sortedStableTags: ['v0.35.0'],
+ sha: MIRRORED_SHA,
+ contains: () => {
+ throw new Error('git merge-base failed (exit 128)');
+ },
+ }),
+ ).toThrow(/exit 128/);
+ });
+});
+
+describe('resolveShippedVersion', () => {
+ const resolve = (over) =>
+ resolveShippedVersion({
+ privateSha: PRIVATE_SHA,
+ stableTags: STABLE_TAGS_SHUFFLED,
+ findMirroredCommits: finderFor([{ sha: MIRRORED_SHA, message: MIRRORED_MESSAGE }]),
+ contains: containsMirrored,
+ ...over,
+ });
+
+ // The load-bearing regression. A "most recent release published after the
+ // merge date" heuristic answers v0.35.2 here and is wrong: three v0.35.x
+ // stables published after the source merged and none of them carry the fix.
+ test('pinned fixture: the memory-limit fix resolves to v0.36.0', () => {
+ expect(resolve()).toEqual({
+ shipped: true,
+ privateSha: PRIVATE_SHA,
+ mirroredSha: MIRRORED_SHA,
+ mirroredShas: [MIRRORED_SHA],
+ tag: 'v0.36.0',
+ version: '0.36.0',
+ });
+ });
+
+ test('pinned fixture: it is contained in NONE of v0.35.0 through v0.35.6', () => {
+ for (const tag of ['v0.35.0', 'v0.35.1', 'v0.35.2', 'v0.35.3', 'v0.35.4', 'v0.35.5', 'v0.35.6']) {
+ expect(containsMirrored(tag, MIRRORED_SHA)).toBe(false);
+ }
+ // And with v0.36.0 withheld from the tag set there is no answer at all,
+ // rather than a fallback onto the newest v0.35.x.
+ const withoutTarget = resolve({ stableTags: STABLE_TAGS_SHUFFLED.filter((t) => t !== 'v0.36.0') });
+ expect(withoutTarget).toMatchObject({ shipped: false, reason: 'not-in-any-stable' });
+ });
+
+ test('no mirrored commit yet is an answer, not an error', () => {
+ expect(resolve({ findMirroredCommits: finderFor([]) })).toEqual({
+ shipped: false,
+ reason: 'not-mirrored',
+ privateSha: PRIVATE_SHA,
+ mirroredShas: [],
+ });
+ });
+
+ test('discards a candidate whose message only quotes the trailer', () => {
+ // `git log --grep` substring-matches the whole message, so a commit that
+ // pasted someone else's footer comes back as a candidate and must not be
+ // treated as the mirrored commit.
+ const quoted = { sha: 'f'.repeat(40), message: `chore: cite GitOrigin-RevId: ${PRIVATE_SHA} inline` };
+ expect(resolve({ findMirroredCommits: finderFor([quoted]) })).toMatchObject({
+ shipped: false,
+ reason: 'not-mirrored',
+ });
+ });
+
+ test('keeps a candidate whose message carries the trailer alongside another', () => {
+ const other = 'b'.repeat(40);
+ const msg = `subject\n\nGitOrigin-RevId: ${other}\nGitOrigin-RevId: ${PRIVATE_SHA}\n`;
+ const r = resolve({ findMirroredCommits: finderFor([{ sha: MIRRORED_SHA, message: msg }]) });
+ expect(r).toMatchObject({ shipped: true, tag: 'v0.36.0' });
+ });
+
+ test('a cherry-picked point release wins over the main-line commit', () => {
+ const pointReleaseSha = 'c'.repeat(40);
+ const r = resolve({
+ stableTags: ['v0.35.6', 'v0.35.7', 'v0.36.0'],
+ findMirroredCommits: finderFor([
+ { sha: MIRRORED_SHA, message: MIRRORED_MESSAGE },
+ { sha: pointReleaseSha, message: MIRRORED_MESSAGE },
+ ]),
+ contains: (tag, sha) => {
+ if (sha === MIRRORED_SHA) return tag === 'v0.36.0';
+ if (sha === pointReleaseSha) return tag === 'v0.35.7';
+ return false;
+ },
+ });
+ expect(r).toMatchObject({ shipped: true, tag: 'v0.35.7', version: '0.35.7', mirroredSha: pointReleaseSha });
+ expect(r.mirroredShas).toEqual([MIRRORED_SHA, pointReleaseSha]);
+ });
+
+ test('mirrored but not yet in any stable is an answer, not an error', () => {
+ expect(resolve({ contains: () => false })).toEqual({
+ shipped: false,
+ reason: 'not-in-any-stable',
+ privateSha: PRIVATE_SHA,
+ mirroredShas: [MIRRORED_SHA],
+ });
+ });
+
+ test('no stable tags at all (bootstrap repo) is not-in-any-stable', () => {
+ expect(resolve({ stableTags: [] })).toMatchObject({ shipped: false, reason: 'not-in-any-stable' });
+ });
+
+ test('propagates an infra error from the containment boundary (fail loud)', () => {
+ expect(() =>
+ resolve({
+ contains: () => {
+ throw new Error('gh/git infra error');
+ },
+ }),
+ ).toThrow(/infra error/);
+ });
+
+ test('propagates an infra error from the mirror lookup (fail loud)', () => {
+ expect(() =>
+ resolve({
+ findMirroredCommits: () => {
+ throw new Error('git log infra error');
+ },
+ }),
+ ).toThrow(/infra error/);
+ });
+
+ test('rejects a non-SHA privateSha rather than searching for it', () => {
+ expect(() => resolve({ privateSha: 'eb52a62' })).toThrow(/full 40-character commit SHA/);
+ expect(() => resolve({ privateSha: '' })).toThrow(/full 40-character commit SHA/);
+ });
+
+ test('accepts an uppercase privateSha and matches the lowercase trailer', () => {
+ expect(resolve({ privateSha: PRIVATE_SHA.toUpperCase() })).toMatchObject({
+ shipped: true,
+ privateSha: PRIVATE_SHA,
+ });
+ });
+});
+
+describe('resolvePrivateSha', () => {
+ test('passes a SHA ref straight through without touching the API', () => {
+ const sha = resolvePrivateSha(
+ { kind: 'sha', sha: PRIVATE_SHA },
+ {
+ resolvePrMergeSha: () => {
+ throw new Error('must not be called for a SHA ref');
+ },
+ },
+ );
+ expect(sha).toBe(PRIVATE_SHA);
+ });
+
+ test('resolves a PR ref through the injected boundary', () => {
+ const seen = [];
+ const sha = resolvePrivateSha(
+ { kind: 'pr', owner: 'inkeep', repo: 'agents-private', number: 2767 },
+ {
+ resolvePrMergeSha: (ref) => {
+ seen.push(ref);
+ return PRIVATE_SHA;
+ },
+ },
+ );
+ expect(sha).toBe(PRIVATE_SHA);
+ expect(seen).toEqual([{ kind: 'pr', owner: 'inkeep', repo: 'agents-private', number: 2767 }]);
+ });
+
+ test('propagates an unmerged-PR failure instead of returning nothing', () => {
+ expect(() =>
+ resolvePrivateSha(
+ { kind: 'pr', owner: 'inkeep', repo: 'agents-private', number: 1 },
+ {
+ resolvePrMergeSha: () => {
+ throw new Error('is not merged; there is no fix commit to resolve.');
+ },
+ },
+ ),
+ ).toThrow(/not merged/);
+ });
+});
diff --git a/scripts/compute-next-beta.mjs b/scripts/compute-next-beta.mjs
index 59e2f10e3..9799f74f3 100644
--- a/scripts/compute-next-beta.mjs
+++ b/scripts/compute-next-beta.mjs
@@ -47,7 +47,12 @@
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
-const FIXED_GROUP_ANCHOR = '@inkeep/open-knowledge';
+// The fixed release group's anchor package. Its `initialVersions` entry in
+// pre.json is the version the last stable consolidation left behind, so it is
+// also what a stale-anchor check compares against the newest stable tag.
+// Exported so that check reads the same key rather than carrying a copy that
+// can drift.
+export const FIXED_GROUP_ANCHOR = '@inkeep/open-knowledge';
const PRE_PATH = '.changeset/pre.json';
const CHANGESET_DIR = '.changeset';
// Repo this release runs against; derived from the workflow env so it follows
diff --git a/scripts/compute-stable-version.mjs b/scripts/compute-stable-version.mjs
index 96eddd6f0..5979904d3 100644
--- a/scripts/compute-stable-version.mjs
+++ b/scripts/compute-stable-version.mjs
@@ -25,13 +25,21 @@
* clean `merge-base --is-ancestor` false exits non-zero (retry next tick) rather
* than folding an infra error into a promote/no-op decision.
*
+ * Second mode: node scripts/compute-stable-version.mjs --anchor-guard
+ * See `evaluateAnchorGuard` below. Appends anchor_ok / anchor_version /
+ * latest_stable_version / anchor_drift to $GITHUB_OUTPUT. Exit 0 when level,
+ * 2 when drifted, 1 on an infra/format error — the drifted and broken cases
+ * carry different exit codes so a caller can tell "wait for the reset" from
+ * "something is wrong". The mode is additive; the beta-tag contract above is
+ * unchanged, because sibling workflows already depend on it.
+ *
* The pure core (`computeStablePromotion`) takes its git boundary as an injected
* dependency so tests need no live repo (mirrors promote-stable-auto.mjs).
*/
import { spawnSync } from 'node:child_process';
-import { appendFileSync } from 'node:fs';
+import { appendFileSync, readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
-import { bumpSemver, maxBumpType, parseFrontmatterBumpType } from './compute-next-beta.mjs';
+import { FIXED_GROUP_ANCHOR, bumpSemver, maxBumpType, parseFrontmatterBumpType } from './compute-next-beta.mjs';
const BETA_TAG_RE = /^v\d+\.\d+\.\d+-beta\.\d+$/;
const STABLE_TAG_RE = /^v\d+\.\d+\.\d+$/;
@@ -128,6 +136,89 @@ export function computeStablePromotion(betaTag, git) {
};
}
+/**
+ * Is the changeset anchor still level with the newest stable tag?
+ *
+ * The anchor is `pre.json#initialVersions[<fixed group anchor>]`, which a
+ * stable promotion's main-reset advances once it has consolidated that
+ * promotion's changesets. Between the tag landing and the reset landing, the
+ * anchor is BEHIND the newest stable, and any version computed off it in that
+ * window lands on a version that is already taken or already shipped. The
+ * window is real: the reset travels back through a merge queue and a mirror
+ * round-trip, so it can stay open for a long time.
+ *
+ * This function only reports; it never sleeps and never retries. Callers
+ * inside the shared release-cadence concurrency group must REFUSE on `ok:
+ * false` (exit non-zero, holding no lock) rather than wait, because waiting
+ * there holds the lock every beta cut and every other promotion needs, which
+ * would stall the very fast path a stale anchor is delaying. Waiting belongs
+ * in an evaluator that carries its own concurrency group and can simply
+ * decline this tick and re-evaluate on the next one.
+ *
+ * `latestStableTag` of "" means no stable exists yet. That is the bootstrap
+ * shape the promotion path already handles, and there is no drift to detect
+ * against a stable that does not exist, so it passes.
+ *
+ * Malformed inputs THROW rather than returning `ok: false`: an unreadable
+ * anchor is an infrastructure problem, and reporting it as drift would send an
+ * operator to look for a pending main-reset that does not exist.
+ *
+ * Returns { ok, anchorVersion, latestStableVersion, drift, reason } where
+ * drift is 'none' | 'behind' | 'ahead' | 'bootstrap'.
+ */
+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}.`,
+ };
+ }
+ // Direction is worth naming: behind is the ordinary pending-reset case an
+ // operator waits out, ahead means the anchor advanced past a stable that was
+ // never tagged, which is a different investigation.
+ 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;
+}
+
// --- workflow-runtime wiring (real git boundary) ---
function runGit(args) {
@@ -168,7 +259,65 @@ const realGit = {
bumpTypeOf: (sha, id) => parseFrontmatterBumpType(runGit(['show', `${sha}:.changeset/${id}.md`])),
};
+// Both sides must be read from the same clone, and that clone has to be the
+// release repo: the anchor is the mirrored pre.json in the checked-out tree,
+// 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() {
+ 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.
+ 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) {
+ // Refuse, do not wait: this mode is called from inside the shared
+ // release-cadence group, where sleeping would block every other cut.
+ console.error(`::error::${result.reason}`);
+ process.exit(2);
+ }
+ log(result.reason);
+}
+
function main() {
+ if (process.argv[2] === '--anchor-guard') {
+ anchorGuardMain();
+ 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 3194de19b..0b268a3c9 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 } from './compute-stable-version.mjs';
+import { 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.
@@ -109,3 +109,80 @@ describe('computeStablePromotion', () => {
expect(() => computeStablePromotion('garbage', fakeGit())).toThrow();
});
});
+
+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', () => {
+ // Reporting an unreadable anchor as drift would send an operator looking
+ // for a pending reset that does not exist.
+ 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', () => {
+ // The guard is called from inside the shared release-cadence group, where
+ // blocking would stall every other cut. Two calls with identical inputs
+ // must return identical verdicts with no elapsed-time dependence.
+ 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);
+ });
+});