Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Give reporter write-back a token that can read the private monorepo (#3020)

Andrew Mikofalvy2fbca071a06a
diff --git a/.github/scripts/write-back.mjs b/.github/scripts/write-back.mjs
index bbf35e9a3..9b06d25df 100644
--- a/.github/scripts/write-back.mjs
+++ b/.github/scripts/write-back.mjs
@@ -31,9 +31,11 @@
*
* Fail-loud contract: "nothing to notify about" is a real ANSWER and exits 0.
* A missing credential is an answer too. Any infra error (Linear unreachable, a
- * git failure, a malformed GraphQL response) throws and exits non-zero rather
- * than being folded into silence, because a caller cannot tell a quiet run from
- * a broken one and would never look again.
+ * git failure, a malformed GraphQL response) exits non-zero rather than being
+ * folded into silence, because a caller cannot tell a quiet run from a broken
+ * one and would never look again. An error against ONE ticket is deferred, not
+ * softened: the run finishes so the other reporters still hear, and then exits
+ * non-zero carrying every failure it collected.
*/
import { execFileSync, spawnSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';
@@ -147,6 +149,10 @@ export function deriveVersionForFixRefs({
for (const ref of usable) {
const parsed = parseFixRef(ref.channel === 'commit' ? ref.sha : ref.url, { defaultRepo });
const privateSha = resolvePrivateSha(parsed, { resolvePrMergeSha });
+ if (!privateSha) {
+ log(`::notice::write-back: ${ref.url} was closed without merging, so it carries no fix commit.`);
+ return null;
+ }
const result = resolveShippedVersion({ privateSha, stableTags, findMirroredCommits, contains });
if (!result.shipped) {
log(`::notice::write-back: ${ref.url} has not reached a stable release yet (${result.reason}).`);
@@ -235,9 +241,11 @@ export function makeReleaseWindow({
*
* `live` false is the default and performs zero writes of any kind.
*
- * Returns { posted, skipped, dryRun } where `skipped` carries a reason per
+ * Returns { posted, skipped, errored, dryRun }. `skipped` carries a reason per
* candidate, so a run that did nothing can be read as either "correctly quiet"
- * or "quietly broken".
+ * or "quietly broken"; `errored` carries the candidates that threw, which the
+ * caller must turn into a non-zero exit — they are failures that happened to be
+ * survivable, not skips.
*/
export async function runWriteBack({
listCandidates,
@@ -259,9 +267,15 @@ export async function runWriteBack({
const posted = [];
const skipped = [];
+ const errored = [];
const skip = (identifier, reason) => skipped.push({ identifier, reason });
- for (const candidate of await listCandidates()) {
+ // One candidate per attempt, so a ticket whose fix reference cannot be read
+ // does not decide the fate of every reporter behind it in the list. The
+ // failure is collected rather than swallowed: the caller fails the run once
+ // everyone reachable has been told, which is strictly more than aborting on
+ // the first bad reference told anyone.
+ const processCandidate = async (candidate) => {
const { origins, unrepliable, fixReferences } = partitionAttachments(candidate.attachmentUrls ?? []);
const children = await listChildren(candidate.id);
@@ -288,7 +302,7 @@ export async function runWriteBack({
);
}
skip(candidate.identifier, gate.unresolved.length > 0 ? 'version-underivable' : 'fan-in-withheld');
- continue;
+ return;
}
// Scope to the release this run is about. Skips here are the ordinary bulk
@@ -297,7 +311,7 @@ export async function runWriteBack({
const placement = classifyRelease(gate.version);
if (placement !== 'in-window') {
skip(candidate.identifier, placement);
- continue;
+ return;
}
if (origins.length === 0) {
@@ -311,7 +325,7 @@ export async function runWriteBack({
// Not every fix has a reporter. This is the ordinary case, not a fault.
skip(candidate.identifier, 'no-origin');
}
- continue;
+ return;
}
for (const origin of origins) {
@@ -367,13 +381,48 @@ export async function runWriteBack({
log(
`::debug::write-back: marker written for ${origin.url} (${candidate.identifier}); posting reply next.`,
);
- await postReply(origin, text);
+ try {
+ await postReply(origin, text);
+ } catch (err) {
+ // Past the point of no return. Re-raise saying so, because the generic
+ // "could not be processed" this lands in reads as retryable and this
+ // one is not: the marker stands, so no later run will pick it up and
+ // the only remaining fix is a reply posted by hand.
+ throw new Error(
+ `marker for ${origin.url} was written but the reply did NOT send (${err.message}). ` +
+ 'No future run will retry it; post the reply by hand.',
+ );
+ }
log(`::notice::write-back: replied to ${origin.url} for ${candidate.identifier} (v${gate.version}).`);
posted.push({ identifier: candidate.identifier, origin: origin.url, version: gate.version, dryRun: false });
}
+ };
+
+ for (const candidate of await listCandidates()) {
+ try {
+ await processCandidate(candidate);
+ } catch (err) {
+ log(`::warning::write-back: ${candidate.identifier} could not be processed: ${err.message}`);
+ errored.push({ identifier: candidate.identifier, message: err.message });
+ }
}
- return { posted, skipped, dryRun: !live };
+ return { posted, skipped, errored, dryRun: !live };
+}
+
+/**
+ * A run that could not process every candidate is a failed run, even though it
+ * ran to the end and may well have posted to most reporters. The verdict is
+ * returned rather than thrown where it is decided, so that "errors must still
+ * turn the job red" is one expression a test can hold on to instead of a branch
+ * inside an entry point nothing can call.
+ */
+export function runFailureMessage({ errored = [] } = {}) {
+ if (errored.length === 0) return null;
+ return (
+ `${errored.length} of the candidates could not be processed: ` +
+ errored.map((e) => `${e.identifier} (${e.message})`).join('; ')
+ );
}
// --- workflow-runtime wiring (real Linear / git / gh / Discord boundary) ---
@@ -463,34 +512,104 @@ function realContains(tag, sha) {
);
}
-function gh(args) {
- return execFileSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
+/**
+ * Two credentials, chosen per call site rather than one ambient one.
+ *
+ * A fix reference points into the private monorepo, which the workflow's own
+ * token cannot see at all — every read against it 404s, indistinguishable from
+ * a deleted pull request. The App installation token that CAN see it is scoped
+ * to that one repository, so it in turn cannot post the reply back onto an
+ * issue here. Neither token can do both jobs, so the target repo picks.
+ *
+ * Absent a cross-repo token the ambient one is used and the 404 surfaces as an
+ * ordinary per-candidate failure, which is why the entry point warns up front
+ * when there is no such token: so those 404s are not read as deleted pull
+ * requests.
+ */
+export function selectGhToken({ owner, repo, env }) {
+ const crossRepo = String(env.CROSS_REPO_TOKEN ?? '').trim();
+ if (!crossRepo) return null;
+ const self = String(env.GITHUB_REPOSITORY ?? '').trim().toLowerCase();
+ return `${owner}/${repo}`.toLowerCase() === self ? null : crossRepo;
+}
+
+function gh(args, target) {
+ const token = target ? selectGhToken({ ...target, env: process.env }) : null;
+ return execFileSync('gh', args, {
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: token ? { ...process.env, GH_TOKEN: token } : process.env,
+ });
}
function realResolvePrMergeSha({ owner, repo, number }) {
let out;
try {
- out = gh(['api', `repos/${owner}/${repo}/pulls/${number}`, '--jq', '.merged_at,.merge_commit_sha']);
+ out = gh(['api', `repos/${owner}/${repo}/pulls/${number}`, '--jq', '.merged_at,.merge_commit_sha'], {
+ owner,
+ repo,
+ });
} 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.`);
- }
+ return parseMergeShaOutput(out, { owner, repo, number });
+}
+
+/**
+ * The merge commit behind a pull request, or null if it never had one.
+ *
+ * Split out from the `gh` call so the distinction it draws is testable, because
+ * that distinction decides whether a run goes red. A pull request closed
+ * without merging is an ANSWER: there is no fix commit, which happens whenever
+ * a ticket keeps the attachment from a superseded attempt while the fix lands
+ * under a different number. Only a human editing Linear can put that right, so
+ * it routes to the same warn-and-skip as a fix that has not shipped. A reply
+ * shape nobody can account for still throws.
+ */
+export function parseMergeShaOutput(out, { owner, repo, number } = {}) {
+ const [mergedAt, sha] = String(out ?? '')
+ .split('\n')
+ .map((s) => s.trim());
+ if (!mergedAt || mergedAt === 'null') return null;
if (!FULL_SHA_RE.test(sha || '')) {
throw new Error(`${owner}/${repo}#${number} has no usable merge_commit_sha (got '${sha}').`);
}
return sha.toLowerCase();
}
+/**
+ * Where this product's changeset lives, given the repo the fix reference names.
+ *
+ * The monorepo carries three changeset directories and only one of them is this
+ * product's. `public/agents/.changeset/` is a different product's release notes;
+ * quoting it would put another team's copy in front of an Open Knowledge bug
+ * reporter, and it would read plausibly enough that nobody would catch it. So
+ * the directory is chosen by repo rather than found by searching the path for
+ * `.changeset/` — a search matches all three, and the monorepo root has a stray
+ * changeset sitting in it too.
+ *
+ * In the public mirror this subtree IS the repo root, so a fix reference naming
+ * that repo wants the root directory.
+ */
+export function changesetDirFor(repo) {
+ return repo === 'open-knowledge' ? '.changeset/' : 'public/open-knowledge/.changeset/';
+}
+
+/** The one changeset a pull request added, or null if it added none. */
+export function findChangesetPath(filenames, { repo } = {}) {
+ const dir = changesetDirFor(repo);
+ const isChangeset = (name) =>
+ name.startsWith(dir) && /^[^/]+\.md$/.test(name.slice(dir.length)) && !name.endsWith('/README.md');
+ return filenames.map((name) => String(name).trim()).find(isChangeset) ?? null;
+}
+
/**
* The prose quoted back to the reporter is the changeset the fix shipped with,
* which is already public release-notes copy. It is read from the fix pull
- * request's own `.changeset/*.md` addition rather than from the ticket, so no
- * internal field is ever in reach.
+ * request's own changeset addition rather than from the ticket, so no internal
+ * field is ever in reach.
*/
function realReadChangesetProse(_candidate, { fixReferences }) {
const pull = fixReferences.find((ref) => ref.channel === 'pull-request');
@@ -498,33 +617,30 @@ function realReadChangesetProse(_candidate, { fixReferences }) {
let names;
try {
- names = gh([
- 'api',
- `repos/${pull.owner}/${pull.repo}/pulls/${pull.number}/files`,
- '--paginate',
- '--jq',
- '.[].filename',
- ]);
+ names = gh(
+ ['api', `repos/${pull.owner}/${pull.repo}/pulls/${pull.number}/files`, '--paginate', '--jq', '.[].filename'],
+ pull,
+ );
} catch (err) {
throw new Error(`gh api pulls/${pull.number}/files failed: ${String(err?.stderr || err?.message || '').trim()}`);
}
- const changesetPath = names
- .split('\n')
- .map((s) => s.trim())
- .find((name) => /^\.changeset\/[^/]+\.md$/.test(name) && !name.endsWith('/README.md'));
+ const changesetPath = findChangesetPath(names.split('\n'), { repo: pull.repo });
if (!changesetPath) return null;
let raw;
try {
- raw = gh([
- 'api',
- // Read at the PR head rather than at the default branch: the changeset
- // file is consumed and deleted when the release that shipped it was cut.
- `repos/${pull.owner}/${pull.repo}/contents/${changesetPath}?ref=refs/pull/${pull.number}/head`,
- '--jq',
- '.content',
- ]);
+ raw = gh(
+ [
+ 'api',
+ // Read at the PR head rather than at the default branch: the changeset
+ // file is consumed and deleted when the release that shipped it was cut.
+ `repos/${pull.owner}/${pull.repo}/contents/${changesetPath}?ref=refs/pull/${pull.number}/head`,
+ '--jq',
+ '.content',
+ ],
+ pull,
+ );
} catch (err) {
throw new Error(`gh api contents/${changesetPath} failed: ${String(err?.stderr || err?.message || '').trim()}`);
}
@@ -608,6 +724,13 @@ async function main() {
'anything shipped earlier is left alone.',
);
+ if (!String(process.env.CROSS_REPO_TOKEN ?? '').trim()) {
+ log(
+ `::warning::write-back: no CROSS_REPO_TOKEN, so reads against ${DEFAULT_PRIVATE_REPO} run on this repo's own ` +
+ 'token and will 404. Those 404s mean "not authorised", not "no such pull request".',
+ );
+ }
+
const result = await runWriteBack({
listCandidates: () => paginate({ apiKey, query: CANDIDATE_QUERY, variables: {} }),
listChildren: (parentId) => paginate({ apiKey, query: CHILDREN_QUERY, variables: { parentId } }),
@@ -632,7 +755,17 @@ async function main() {
log,
});
- console.log(JSON.stringify({ dryRun: result.dryRun, posted: result.posted.length, skipped: result.skipped }));
+ console.log(
+ JSON.stringify({
+ dryRun: result.dryRun,
+ posted: result.posted.length,
+ skipped: result.skipped,
+ errored: result.errored,
+ }),
+ );
+
+ const failure = runFailureMessage(result);
+ if (failure) throw new Error(failure);
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
diff --git a/.github/scripts/write-back.test.mjs b/.github/scripts/write-back.test.mjs
index d27c1e7fa..7c0596119 100644
--- a/.github/scripts/write-back.test.mjs
+++ b/.github/scripts/write-back.test.mjs
@@ -2,12 +2,17 @@ import { readFileSync } from 'node:fs';
import { describe, expect, test } from 'vitest';
import {
CANDIDATE_QUERY,
+ changesetDirFor,
DEFAULT_RELEASE_LOOKBACK,
deriveVersionForFixRefs,
+ findChangesetPath,
makeReleaseWindow,
notificationMarkerUrl,
parseChangeset,
+ parseMergeShaOutput,
+ runFailureMessage,
runWriteBack,
+ selectGhToken,
} from './write-back.mjs';
const GH_ISSUE = 'https://github.com/inkeep/open-knowledge/issues/769';
@@ -146,6 +151,49 @@ describe('version derivation', () => {
expect(derive({ fixReferences: [] })).toBeNull();
});
+ test('a fix reference naming a pull request that was closed unmerged is an answer, not a fault', () => {
+ // Real shape: PRD-7539 still carries agents-private#2844, which was closed
+ // in favour of #2864. A stale attachment is for a human to fix in Linear,
+ // so it warns and skips rather than painting the run red.
+ const logs = [];
+ expect(
+ derive({
+ fixReferences: [{ channel: 'pull-request', url: GH_PULL }],
+ resolvePrMergeSha: () => null,
+ log: (m) => logs.push(m),
+ }),
+ ).toBeNull();
+ expect(logs.join(' ')).toContain('closed without merging');
+ });
+
+ test('the merge-sha reply distinguishes "never merged" from "cannot be accounted for"', () => {
+ const at = { owner: 'inkeep', repo: 'agents-private', number: 2844 };
+ const sha = 'da71f0c698ccaac11da915169ca6c7d585d5eb97';
+
+ // The real reply for agents-private#2844: closed, so merged_at is null.
+ expect(parseMergeShaOutput('null\n', at)).toBeNull();
+ expect(parseMergeShaOutput('\n', at)).toBeNull();
+ expect(parseMergeShaOutput('2026-07-23T14:19:56Z\n' + sha, at)).toBe(sha);
+ expect(parseMergeShaOutput('2026-07-23T14:19:56Z\n' + sha.toUpperCase(), at)).toBe(sha);
+
+ // Merged but with no usable sha is neither a fix nor an answer.
+ expect(() => parseMergeShaOutput('2026-07-23T14:19:56Z\nnot-a-sha', at)).toThrow(/merge_commit_sha/);
+ });
+
+ test('an unreadable pull request still throws, because that one is not an answer', () => {
+ // The 404 that broke the first live run was authorisation, not data. It
+ // must stay loud; folding it in with the stale-attachment case would make
+ // a repo-wide permission failure look like a tidy row of skips.
+ expect(() =>
+ derive({
+ fixReferences: [{ channel: 'pull-request', url: GH_PULL }],
+ resolvePrMergeSha: () => {
+ throw new Error('gh api pulls/2844 failed: HTTP 404');
+ },
+ }),
+ ).toThrow(/404/);
+ });
+
test('an infra failure in the git boundary propagates rather than reading as not-shipped', () => {
expect(() =>
derive({
@@ -220,8 +268,13 @@ describe('write-back run', () => {
throw new Error('Linear attachmentCreate reported failure');
},
});
- await expect(h.run()).rejects.toThrow(/attachmentCreate/);
+ const result = await h.run();
+ // The at-most-once contract: no marker, therefore no reply. The failure is
+ // carried out as an error rather than a skip so the run still goes red.
expect(h.writes.filter((w) => w.kind === 'post')).toHaveLength(0);
+ expect(result.errored).toHaveLength(1);
+ expect(result.errored[0].message).toMatch(/attachmentCreate/);
+ expect(result.skipped).toEqual([]);
});
test('running twice against the same release posts exactly once', async () => {
@@ -342,6 +395,138 @@ describe('changeset parsing', () => {
// The properties that keep a reporter-facing side effect from ever touching a
// release: its own trigger, its own concurrency group, and no edit to any of
// the three publish workflows.
+describe('locating the changeset a fix shipped with', () => {
+ // The real file list off the pull request the first live run choked on.
+ const MONOREPO_FILES = [
+ 'public/open-knowledge/.changeset/default-theme-tile-own-colors.md',
+ 'public/open-knowledge/packages/app/src/components/ThemeTile.tsx',
+ ];
+
+ test('a monorepo pull request keeps its changeset under the subtree, not at the root', () => {
+ expect(findChangesetPath(MONOREPO_FILES, { repo: 'agents-private' })).toBe(
+ 'public/open-knowledge/.changeset/default-theme-tile-own-colors.md',
+ );
+ });
+
+ test('a pull request against the public mirror keeps it at the root, where that repo puts it', () => {
+ expect(findChangesetPath(['.changeset/some-fix.md'], { repo: 'open-knowledge' })).toBe('.changeset/some-fix.md');
+ });
+
+ test("another product's changeset is never quoted to an Open Knowledge reporter", () => {
+ // The monorepo has three .changeset dirs. Matching any `.changeset/` on the
+ // path would put agents-platform release notes in front of an OK reporter,
+ // and they would read plausibly enough that nobody would catch it.
+ const foreign = ['public/agents/.changeset/some-agents-fix.md', '.changeset/a-stray-root-changeset.md'];
+ expect(findChangesetPath(foreign, { repo: 'agents-private' })).toBeNull();
+ });
+
+ test('the changeset README is never mistaken for a changeset', () => {
+ expect(findChangesetPath(['public/open-knowledge/.changeset/README.md'], { repo: 'agents-private' })).toBeNull();
+ });
+
+ test('a pull request that added no changeset yields nothing rather than a wrong file', () => {
+ expect(findChangesetPath(['public/open-knowledge/packages/app/src/x.ts'], { repo: 'agents-private' })).toBeNull();
+ expect(findChangesetPath([], { repo: 'agents-private' })).toBeNull();
+ });
+
+ test('the directory is chosen by repo, since only the mirror has it at the root', () => {
+ expect(changesetDirFor('open-knowledge')).toBe('.changeset/');
+ expect(changesetDirFor('agents-private')).toBe('public/open-knowledge/.changeset/');
+ });
+});
+
+describe('cross-repo token selection', () => {
+ const env = { CROSS_REPO_TOKEN: 'bridge-token', GITHUB_REPOSITORY: 'inkeep/open-knowledge' };
+
+ test('a read against the private monorepo uses the bridge token', () => {
+ expect(selectGhToken({ owner: 'inkeep', repo: 'agents-private', env })).toBe('bridge-token');
+ });
+
+ test('a read against this repo keeps the ambient token, which the bridge token cannot replace', () => {
+ // The bridge token is scoped to agents-private, so handing it to a call
+ // against this repo would 404 the very thing the ambient token can do.
+ expect(selectGhToken({ owner: 'inkeep', repo: 'open-knowledge', env })).toBeNull();
+ expect(selectGhToken({ owner: 'InKeep', repo: 'Open-Knowledge', env })).toBeNull();
+ });
+
+ test('with no bridge token configured every call falls back to the ambient one', () => {
+ const bare = { GITHUB_REPOSITORY: 'inkeep/open-knowledge' };
+ expect(selectGhToken({ owner: 'inkeep', repo: 'agents-private', env: bare })).toBeNull();
+ expect(selectGhToken({ owner: 'inkeep', repo: 'agents-private', env: { ...bare, CROSS_REPO_TOKEN: ' ' } })).toBeNull();
+ });
+});
+
+describe('one unreadable candidate does not silence the rest', () => {
+ const two = (first, second) => ({
+ listCandidates: async () => [
+ candidate({ id: 'uuid-1', identifier: 'PRD-0001', attachmentUrls: [first, GH_ISSUE] }),
+ candidate({ id: 'uuid-2', identifier: 'PRD-0002', attachmentUrls: [second, GH_ISSUE] }),
+ ],
+ });
+
+ test('a candidate whose fix reference cannot be read is reported, and the next one still posts', async () => {
+ const h = harness({
+ ...two(GH_PULL, GH_PULL),
+ versionFor: async (node) => {
+ if (node.identifier === 'PRD-0001') throw new Error('gh api pulls/2844 failed: HTTP 404');
+ return 'v0.36.0';
+ },
+ });
+ const result = await h.run();
+
+ expect(result.errored.map((e) => e.identifier)).toEqual(['PRD-0001']);
+ expect(result.errored[0].message).toContain('404');
+ expect(result.posted.map((p) => p.identifier)).toEqual(['PRD-0002']);
+ });
+
+ test('a failure is never filed as a skip, so a broken run cannot read as a quiet one', async () => {
+ const h = harness({
+ ...two(GH_PULL, GH_PULL),
+ versionFor: async () => {
+ throw new Error('gh api failed: HTTP 404');
+ },
+ });
+ const result = await h.run();
+
+ expect(result.errored).toHaveLength(2);
+ expect(result.skipped).toEqual([]);
+ });
+
+ test('errors still turn the run red once the reachable reporters have been told', () => {
+ // Surviving a bad candidate must not become a way of passing while broken.
+ expect(runFailureMessage({ posted: [], skipped: [], errored: [] })).toBeNull();
+ expect(runFailureMessage({ skipped: [{ identifier: 'PRD-1', reason: 'no-origin' }], errored: [] })).toBeNull();
+
+ const message = runFailureMessage({
+ errored: [
+ { identifier: 'PRD-0001', message: 'HTTP 404' },
+ { identifier: 'PRD-0002', message: 'HTTP 502' },
+ ],
+ });
+ expect(message).toContain('2 of the candidates');
+ expect(message).toContain('PRD-0001');
+ expect(message).toContain('PRD-0002');
+ });
+
+ test('a reply that fails after its marker was written says so, because no run will retry it', async () => {
+ const h = harness({
+ live: true,
+ postReply: async () => {
+ throw new Error('notify endpoint returned HTTP 502');
+ },
+ });
+ const result = await h.run();
+
+ const [failure] = result.errored;
+ expect(failure.message).toContain('marker');
+ expect(failure.message).toContain('did NOT send');
+ expect(failure.message).toContain('by hand');
+ expect(failure.message).toContain('502');
+ // The marker really was written; that is why the message says what it says.
+ expect(h.writes.map((w) => w.kind)).toEqual(['mark']);
+ });
+});
+
describe('workflow shape', () => {
const read = (name) => readFileSync(new URL(`../workflows/${name}`, import.meta.url), 'utf8');
const workflow = read('write-back.yml');
@@ -381,6 +566,33 @@ describe('workflow shape', () => {
expect(workflow).toContain('WRITE_BACK_MODE');
expect(workflow).toContain('LINEAR_API_KEY');
});
+
+ test('the private monorepo is read with a bridge App token, not with this repo own token', () => {
+ // The default token cannot see agents-private at all, so a run wired with
+ // only `GH_TOKEN` 404s on every fix reference.
+ expect(workflow).toContain('CROSS_REPO_TOKEN: ${{ steps.bridge-token.outputs.token }}');
+ expect(workflow).toMatch(/uses: actions\/create-github-app-token@[0-9a-f]{40}/);
+ expect(workflow).toContain('repositories: agents-private');
+ });
+
+ test('the bridge token is minted read-only, and for both scopes the reads need', () => {
+ // Contents alone finds no changeset (the path comes from the PR file list);
+ // pull-requests alone yields a version with nothing to quote.
+ expect(workflow).toContain('permission-contents: read');
+ expect(workflow).toContain('permission-pull-requests: read');
+ expect(workflow).not.toMatch(/permission-\w+(-\w+)*: write/);
+ });
+
+ test('posting still uses this repo own token, which the scoped bridge token could not do', () => {
+ expect(workflow).toContain('GH_TOKEN: ${{ github.token }}');
+ expect(workflow).toContain('issues: write');
+ });
+
+ test('a missing bridge App degrades to a warning rather than failing the mint', () => {
+ // Secrets are unreadable in `if:`, so the gate is an output from a step.
+ expect(workflow).toMatch(/id: bridge-check/);
+ expect(workflow).toMatch(/if:.*steps\.bridge-check\.outputs\.configured == 'true'/);
+ });
});
describe('release window', () => {
diff --git a/.github/workflows/write-back.yml b/.github/workflows/write-back.yml
index 8d28b54bd..c92d4e643 100644
--- a/.github/workflows/write-back.yml
+++ b/.github/workflows/write-back.yml
@@ -22,6 +22,13 @@ name: Reporter Write-Back
# behind or delay a cut, and no release workflow waits on its result. The
# worst outcome available to a failure here is that nobody gets told.
#
+# WHY THERE ARE TWO TOKENS
+# The reply is posted onto an issue in this repo; the fix pull request and its
+# changeset are read out of the private monorepo. No single credential can do
+# both — this repo's own token cannot see agents-private at all, and the App
+# installation token that can is scoped to that one repository. So both are
+# passed and the script picks per call site by target repo.
+#
# EVERYTHING SHIPS INERT
# With no LINEAR_API_KEY the script emits a notice and enumerates nothing.
# With the key but no WRITE_BACK_MODE it composes replies and logs them
@@ -88,10 +95,47 @@ jobs:
with:
node-version: "24"
+ - name: Check whether the bridge App is configured
+ # Fix references point into the private monorepo, which this repo's own
+ # token cannot read at all. Secrets are unreadable in `if:` expressions,
+ # so the presence check runs here and gates the mint via an output.
+ if: steps.tag.outputs.stable == 'true'
+ 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 "::warning::OK_RELEASE_BRIDGE_APP_ID not set — reads against the private monorepo will 404 and those candidates will be reported as failures."
+ fi
+
+ - name: Mint cross-repo read token (bridge App)
+ if: steps.tag.outputs.stable == 'true' && 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 here. Scoping the
+ # token to that installation is also why it cannot be the only token:
+ # it has no standing to post the reply back onto an issue in this repo.
+ owner: inkeep
+ repositories: agents-private
+ permission-contents: read
+ permission-pull-requests: read
+
- name: Notify reporters whose fix reached this release
if: steps.tag.outputs.stable == 'true'
env:
+ # Posting the reply, which happens against this repo.
GH_TOKEN: ${{ github.token }}
+ # Reading the fix pull request and its changeset, which happen against
+ # agents-private. The script picks per call site by target repo.
+ CROSS_REPO_TOKEN: ${{ steps.bridge-token.outputs.token }}
LINEAR_API_KEY: ${{ secrets.LINEAR_API_KEY }}
# Absent by default. Set to `live` on the repo (a variable, not a
# secret, so it is visible in the settings UI) to arm real posts.