Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Retire Open Knowledge outside pull request intake (#7589)

Nick Gomezad59031aa6c4
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 08f23ebf8..a48ca3195 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -72,7 +72,7 @@ body:
id: code-pointers
attributes:
label: Relevant code
- description: Files, functions or links to lines you think are involved, with the fix described in words. Please don't paste a full patch. If you want to write the fix yourself, say so here and wait for a maintainer to accept the issue (a `help wanted` label or an explicit go-ahead for a pull request).
+ description: Files, functions or links to lines you think are involved, with the fix described in words. Please don't paste a full patch or open a pull request.
validations:
required: false
- type: textarea
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
index 23fd5913d..1ba4996fd 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.yml
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -31,7 +31,7 @@ body:
id: code-pointers
attributes:
label: Relevant code
- description: Files, functions or links to lines you think are involved, with the change described in words. Please don't paste a full patch. If you want to write the change yourself, say so here and wait for a maintainer to accept the issue (a `help wanted` label or an explicit go-ahead for a pull request).
+ description: Files, functions or links to lines you think are involved, with the change described in words. Please don't paste a full patch or open a pull request.
validations:
required: false
- type: dropdown
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 0e70962ca..e290c0b14 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -1,34 +1,7 @@
-<!--
-Beyond a small fix, a pull request needs an issue a maintainer has accepted, or it may be closed without review.
-The rules are in the "Pull requests" section of CONTRIBUTING.md.
--->
+# Please file an issue instead
-## Accepted issue
+We do not accept pull requests, including small fixes and translation changes.
-<!-- Paste the full issue URL, e.g. https://github.com/inkeep/open-knowledge/issues/123. Write "small fix" if this is a typo, link, docs or translation correction. -->
+Please [file a detailed issue](https://github.com/inkeep/open-knowledge/issues/new/choose) describing the problem, steps to reproduce it, or the outcome you want. See [Write an issue we can build from](https://github.com/inkeep/open-knowledge/blob/main/CONTRIBUTING.md#write-an-issue-we-can-build-from).
-## What & why
-
-<!-- One or two sentences on the change and the motivation. -->
-
-## How this was verified
-
-<!-- How you tested: `pnpm check` output, manual steps, before/after screenshots for UI changes. -->
-
-## Checklist
-
-- [ ] Linked an accepted issue above, or this is a small fix
-- [ ] I have read and run every line of this change, and can answer questions about it
-- [ ] Ran `pnpm check` (lint, typecheck, tests) locally
-- [ ] Added a changeset (`pnpm changeset`) if this changes behavior
-- [ ] Updated docs if this changes a user-facing surface
-- [ ] I have read [CONTRIBUTING.md](../CONTRIBUTING.md) and agree to license my contribution under the project's terms (CLA)
-
----
-
-### After you open this PR
-
-- A maintainer will review your PR if it is a small fix or links an accepted issue. If you don't hear back within a few business days, a comment to nudge is welcome.
-- When your change is accepted, this PR closes automatically — that's how it merges, and your authorship is preserved.
-
-See [CONTRIBUTING.md](../CONTRIBUTING.md) for details.
+Filing an issue does not commit the maintainers to building the change.
diff --git a/.github/scripts/bridge-public-pr-to-monorepo.mjs b/.github/scripts/bridge-public-pr-to-monorepo.mjs
deleted file mode 100644
index 2a3a40f17..000000000
--- a/.github/scripts/bridge-public-pr-to-monorepo.mjs
+++ /dev/null
@@ -1,1153 +0,0 @@
-import { execFileSync } from 'node:child_process';
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { pathToFileURL } from 'node:url';
-
-import { applyClaGate } from './cla-gate.mjs';
-
-const OSS_SYNC_BOT_NAME = 'inkeep-oss-sync[bot]';
-const OSS_SYNC_BOT_EMAIL = '274976938+inkeep-oss-sync[bot]@users.noreply.github.com';
-const MAX_COMMAND_ERROR_LENGTH = 4096;
-const MAX_COMMAND_LABEL_LENGTH = 256;
-
-function sanitizeErrorMessage(value) {
- if (typeof value !== 'string') return value;
- return value.replace(/https:\/\/x-access-token:[^@\s]+@/g, 'https://x-access-token:***@');
-}
-
-function run(command, args, options = {}) {
- const { preserveOutput = false, ...execOptions } = options;
- const {
- GIT_DIR: _d,
- GIT_WORK_TREE: _w,
- GIT_COMMON_DIR: _c,
- GIT_INDEX_FILE: _i,
- GIT_OBJECT_DIRECTORY: _o,
- GIT_ALTERNATE_OBJECT_DIRECTORIES: _a,
- GIT_NAMESPACE: _n,
- GIT_PREFIX: _p,
- ...cleanEnv
- } = { ...process.env, ...execOptions.env };
- try {
- const output = execFileSync(command, args, {
- encoding: 'utf8',
- stdio: ['ignore', 'pipe', 'pipe'],
- ...execOptions,
- env: cleanEnv,
- });
- return preserveOutput ? output : output.trim();
- } catch (error) {
- const invocation = sanitizeErrorMessage(`${command} ${args.join(' ')}`);
- const commandLabel =
- invocation.length > MAX_COMMAND_LABEL_LENGTH
- ? `${invocation.slice(0, MAX_COMMAND_LABEL_LENGTH)}...`
- : invocation;
- if (error.code === 'ENOBUFS') {
- const limit =
- execOptions.maxBuffer === undefined
- ? 'the configured limit'
- : `${execOptions.maxBuffer} bytes`;
- throw new Error(
- `${commandLabel} exceeded the output buffer limit (${limit}).`.slice(
- 0,
- MAX_COMMAND_ERROR_LENGTH,
- ),
- );
- }
- const stderr = sanitizeErrorMessage(error.stderr?.toString().trim() ?? '');
- const stdout = sanitizeErrorMessage(error.stdout?.toString().trim() ?? '');
- const details =
- [stderr, stdout].filter(Boolean).join('\n') || sanitizeErrorMessage(error.message);
- throw new Error(`${commandLabel} failed: ${details}`.slice(0, MAX_COMMAND_ERROR_LENGTH));
- }
-}
-
-async function githubRequest({ token, method = 'GET', path: requestPath, body }) {
- const response = await fetch(`https://api.github.com${requestPath}`, {
- method,
- headers: {
- Accept: 'application/vnd.github+json',
- Authorization: `Bearer ${token}`,
- 'User-Agent': 'inkeep-public-pr-bridge',
- ...(body ? { 'Content-Type': 'application/json' } : {}),
- },
- body: body ? JSON.stringify(body) : undefined,
- });
-
- const text = await response.text();
- if (!response.ok) {
- const error = new Error(`${method} ${requestPath} failed (${response.status}): ${text}`);
- error.status = response.status;
- throw error;
- }
-
- return text ? JSON.parse(text) : null;
-}
-
-async function githubGraphql({ token, query, variables }) {
- const result = await githubRequest({
- token,
- method: 'POST',
- path: '/graphql',
- body: { query, variables },
- });
- if (result?.errors?.length) {
- throw new Error(`GraphQL error: ${result.errors.map((e) => e.message).join(', ')}`);
- }
- return result;
-}
-
-function requireEnv(name) {
- const value = process.env[name];
- if (!value) {
- throw new Error(`Missing required environment variable: ${name}`);
- }
- return value;
-}
-
-function getPublicPrBranchName(prefix, prNumber) {
- return `${prefix}-${prNumber}`;
-}
-
-function parseJsonEnv(name, fallback) {
- const value = process.env[name];
- if (!value) {
- return fallback;
- }
-
- try {
- return JSON.parse(value);
- } catch (error) {
- throw new Error(`Invalid JSON in ${name}: ${error.message}`);
- }
-}
-
-function hasSourceCommit(internalRepoDir, sha) {
- try {
- return run('git', ['-C', internalRepoDir, 'cat-file', '-t', sha]) === 'commit';
- } catch {
- return false;
- }
-}
-
-function fetchSourceCommit({ internalRepoDir, remoteUrl, sha, role }) {
- if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(sha)) {
- throw new Error(`Bridge: recorded public ${role} commit has an invalid SHA.`);
- }
- if (hasSourceCommit(internalRepoDir, sha)) return;
- try {
- run('git', ['-C', internalRepoDir, 'fetch', '--no-tags', remoteUrl, sha]);
- } catch (error) {
- throw new Error(
- `Bridge: recorded public ${role} commit ${sha} is unavailable: ${error.message}`,
- );
- }
- if (!hasSourceCommit(internalRepoDir, sha)) {
- throw new Error(`Bridge: recorded public ${role} commit ${sha} is unavailable.`);
- }
-}
-
-function diffRecordedPublicCommits(internalRepoDir, baseSha, headSha) {
- return run(
- 'git',
- [
- '-C',
- internalRepoDir,
- 'diff',
- '--no-ext-diff',
- '--no-textconv',
- '--binary',
- '--full-index',
- `${baseSha}...${headSha}`,
- ],
- { maxBuffer: 50 * 1024 * 1024, preserveOutput: true },
- );
-}
-
-function filterDiffByPath(patch, excludedPrefixes) {
- if (!excludedPrefixes || excludedPrefixes.length === 0) return patch;
-
- const sections = patch.split(/(?=^diff --git )/m);
- const kept = [];
- const dropped = [];
-
- for (const section of sections) {
- if (!section.startsWith('diff --git ')) {
- kept.push(section);
- continue;
- }
- const match = section.match(/^diff --git a\/(.+?) b\/(.+?)\n/);
- if (!match) {
- kept.push(section);
- continue;
- }
- const aPath = match[1].replace(/^"(.+)"$/, '$1');
- const bPath = match[2].replace(/^"(.+)"$/, '$1');
-
- const isExcluded = excludedPrefixes.some(
- (prefix) => aPath.startsWith(prefix) || bPath.startsWith(prefix),
- );
-
- if (isExcluded) {
- dropped.push(aPath === bPath ? aPath : `${aPath} -> ${bPath}`);
- } else {
- kept.push(section);
- }
- }
-
- if (dropped.length > 0) {
- const preview = dropped.slice(0, 20).join('\n ');
- const more = dropped.length > 20 ? `\n ...and ${dropped.length - 20} more` : '';
- console.log(
- `Bridge: filtered ${dropped.length} diff section(s) matching excluded prefixes:\n ${preview}${more}`,
- );
- }
-
- return kept.join('');
-}
-
-function prefixPatchPaths(patch, prefix, pathRewrites = {}) {
- const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, '');
- const prefixedPath = (value) => {
- if (value === '/dev/null') {
- return value;
- }
-
- const unquoted = value.replace(/^"(.+)"$/, '$1');
-
- const segments = unquoted.split('/');
- if (segments.some((s) => s === '..' || s === '.')) {
- throw new Error(`Rejecting patch with path traversal: ${unquoted}`);
- }
-
- const rewrite = pathRewrites[unquoted];
- if (rewrite) {
- const rewriteSegments = rewrite.split('/');
- if (rewriteSegments.some((s) => s === '..' || s === '.')) {
- throw new Error(`Rejecting patch rewrite with path traversal: ${rewrite}`);
- }
- }
-
- const nextValue = rewrite ?? `${normalizedPrefix}/${unquoted}`.replace(/\/+/g, '/');
- return value.startsWith('"') ? `"${nextValue}"` : nextValue;
- };
-
- return patch
- .split('\n')
- .map((line) => {
- if (line.startsWith('diff --git a/')) {
- const match = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
- if (!match) {
- return line;
- }
- return `diff --git a/${prefixedPath(match[1])} b/${prefixedPath(match[2])}`;
- }
- if (line.startsWith('--- a/')) {
- return `--- a/${prefixedPath(line.slice(6))}`;
- }
- if (line.startsWith('+++ b/')) {
- return `+++ b/${prefixedPath(line.slice(6))}`;
- }
- if (line.startsWith('rename from ')) {
- return `rename from ${prefixedPath(line.slice('rename from '.length))}`;
- }
- if (line.startsWith('rename to ')) {
- return `rename to ${prefixedPath(line.slice('rename to '.length))}`;
- }
- if (line.startsWith('copy from ')) {
- return `copy from ${prefixedPath(line.slice('copy from '.length))}`;
- }
- if (line.startsWith('copy to ')) {
- return `copy to ${prefixedPath(line.slice('copy to '.length))}`;
- }
- return line;
- })
- .join('\n');
-}
-
-function internalPullRequestTitle(publicPr) {
- return `Sync ${publicPr.base.repo.full_name} public PR #${publicPr.number}: ${publicPr.title}`;
-}
-
-function singleLineCommitSubject(value) {
- return String(value ?? '')
- .replace(/\s+/g, ' ')
- .trim();
-}
-
-function bridgeCommitSubject({ publicRepo, publicPr, hasConflicts }) {
- const title = singleLineCommitSubject(publicPr.title);
- const suffix = hasConflicts ? ` (${CONFLICT_COMMIT_MARKER})` : '';
- return [
- `sync(oss): mirror ${publicRepo}#${publicPr.number}`,
- title ? `: ${title}` : '',
- suffix,
- ].join('');
-}
-
-function buildBridgeMetadata(publicPr, mirrorPath, internalHeadSha) {
- return [
- '<!-- public-pr-sync',
- `public_repo=${publicPr.base.repo.full_name}`,
- `public_pr_number=${publicPr.number}`,
- `public_head_sha=${publicPr.head.sha}`,
- `internal_head_sha=${internalHeadSha ?? ''}`,
- `public_pr_url=${publicPr.html_url}`,
- `public_author_login=${publicPr.user.login}`,
- `public_author_id=${publicPr.user.id}`,
- `mirror_path=${mirrorPath}`,
- '-->',
- ].join('\n');
-}
-
-function readImportMetadata(internalPr) {
- const marker = [...(internalPr.body ?? '').matchAll(/<!-- public-pr-sync\n([\s\S]*?)\n-->/g)].at(
- -1,
- );
- if (!marker) return null;
- return Object.fromEntries(
- marker[1].split('\n').map((line) => {
- const separator = line.indexOf('=');
- return [line.slice(0, separator), line.slice(separator + 1)];
- }),
- );
-}
-
-function importedHeadMatches({ internalPr, publicPr, publicRepo, branchName }) {
- const metadata = readImportMetadata(internalPr);
- return (
- internalPr.state === 'open' &&
- internalPr.head.ref === branchName &&
- metadata?.public_repo === publicRepo &&
- metadata?.public_pr_number === String(publicPr.number) &&
- metadata?.public_head_sha === publicPr.head.sha &&
- metadata?.internal_head_sha === internalPr.head.sha
- );
-}
-
-function legacyImportNeedsRebuild({ internalPr, publicPr, publicRepo, branchName }) {
- const metadata = readImportMetadata(internalPr);
- return (
- internalPr.state === 'open' &&
- internalPr.head.ref === branchName &&
- metadata?.public_repo === publicRepo &&
- metadata?.public_pr_number === String(publicPr.number) &&
- !Object.hasOwn(metadata, 'public_head_sha') &&
- !Object.hasOwn(metadata, 'internal_head_sha')
- );
-}
-
-function publicPrAuthor(publicPr) {
- return {
- name: publicPr.user.login,
- email: `${publicPr.user.id}+${publicPr.user.login}@users.noreply.github.com`,
- };
-}
-
-function normalizeGitHubUserAuthor(user) {
- const login = user?.login?.trim();
- const id = user?.id;
- if (!login || id === undefined || id === null) return null;
- return {
- name: login,
- email: `${id}+${login}@users.noreply.github.com`,
- };
-}
-
-function normalizeCommitAuthor(author) {
- const name = author?.name?.trim();
- const email = author?.email?.trim();
- if (!name || !email?.includes('@')) return null;
- if (/[\r\n<>]/.test(name) || /[\r\n<>]/.test(email)) return null;
- return { name, email };
-}
-
-function parseCoauthorTrailer(line) {
- const match = line.match(/^Co-authored-by:\s*(.+?)\s*<([^<>\s]+@[^<>\s]+)>\s*$/i);
- if (!match) return null;
- return normalizeCommitAuthor({ name: match[1], email: match[2] });
-}
-
-function coauthorsFromCommitMessage(message) {
- return normalizeCommitMessage(message)
- .split('\n')
- .map((line) => parseCoauthorTrailer(line.trim()))
- .filter(Boolean);
-}
-
-function uniqueCommitAuthors(authors) {
- const unique = new Map();
- for (const author of authors) {
- const normalized = normalizeCommitAuthor(author);
- if (!normalized) continue;
- unique.set(`${normalized.name.toLowerCase()} <${normalized.email.toLowerCase()}>`, normalized);
- }
- return [...unique.values()];
-}
-
-function normalizePublicPrCommit(commit) {
- return {
- sha: typeof commit?.sha === 'string' ? commit.sha : null,
- author: normalizeGitHubUserAuthor(commit?.author) ?? commit?.commit?.author,
- message: typeof commit?.commit?.message === 'string' ? commit.commit.message : '',
- };
-}
-
-async function listPublicPrCommits({ token, repo, prNumber, request = githubRequest }) {
- const publicCommits = [];
- let page = 1;
- while (true) {
- const commits = await request({
- token,
- path: `/repos/${repo}/pulls/${prNumber}/commits?per_page=100&page=${page}`,
- });
- publicCommits.push(...commits.map((commit) => normalizePublicPrCommit(commit)));
- if (commits.length < 100) break;
- page++;
- }
- return publicCommits;
-}
-
-function normalizeCommitMessage(message) {
- if (typeof message !== 'string') return '';
- return message.replace(/\r\n?/g, '\n').replace(/\0/g, '').trim();
-}
-
-function formatOriginalCommitMessages(commitMessages, publicRepo) {
- const entries = commitMessages
- .map((commit) => {
- const message = normalizeCommitMessage(commit?.message);
- if (!message) return null;
- const rawSha = typeof commit?.sha === 'string' ? commit.sha : '';
- const sha = /^[0-9a-f]{7,40}$/i.test(rawSha) ? rawSha : null;
- const shortSha = sha ? sha.slice(0, 7) : null;
- const author = normalizeCommitAuthor(commit?.author);
- return { author, sha, shortSha, message };
- })
- .filter(Boolean);
-
- if (entries.length === 0) return '';
-
- const formatted = entries.map((entry) => {
- const lines = [];
- if (entry.sha && entry.shortSha && publicRepo) {
- lines.push(`[${entry.shortSha}](https://github.com/${publicRepo}/commit/${entry.sha})`);
- } else if (entry.shortSha) {
- lines.push(entry.shortSha);
- } else {
- lines.push('Commit');
- }
- if (entry.author) {
- lines.push(`Author: ${entry.author.name} <${entry.author.email}>`);
- }
- lines.push('');
- lines.push(entry.message);
- return lines.join('\n');
- });
-
- return ['Commits:', '', formatted.join('\n\n')].join('\n');
-}
-
-function buildCommitAttribution({ commitAuthors, commitMessages = [], publicRepo }) {
- const authors = uniqueCommitAuthors([
- ...commitAuthors,
- ...commitMessages.map((commit) => commit?.author),
- ...commitMessages.flatMap((commit) => coauthorsFromCommitMessage(commit?.message)),
- ]);
- const trailers = authors.map((author) => `Co-authored-by: ${author.name} <${author.email}>`);
- const originalCommitMessages = formatOriginalCommitMessages(commitMessages, publicRepo);
- const body = [originalCommitMessages, trailers.join('\n')].filter(Boolean).join('\n\n');
- return { trailers, originalCommitMessages, body };
-}
-
-const GITHUB_PR_BODY_LIMIT = 65536;
-
-function buildInternalPrBody({ publicPr, branchName, mirrorPath, internalHeadSha }) {
- const rawOriginal = publicPr.body?.trim()
- ? publicPr.body.trim()
- : '_No public PR body was provided._';
-
- const compose = (original) => `## Summary
-Mirror public PR [#${publicPr.number}](${publicPr.html_url}) from \`${publicPr.base.repo.full_name}\` into \`inkeep/agents-private\` for internal review and merge.
-
-## Attribution
-- Original author: @${publicPr.user.login}
-- Public branch: \`${publicPr.head.label}\`
-- Monorepo branch: \`${branchName}\`
-- Monorepo path: \`${mirrorPath}\`
-
-## Original PR Body
-<details>
-<summary>Expand</summary>
-
-${original}
-
-</details>
-
-## Notes
-- Do not edit this PR directly. This branch is fully managed by the public PR bridge and may be overwritten on the next sync.
-- Do not merge the public repo PR. Public mirror PRs cannot land changes directly.
-- To accept the contribution, merge this monorepo PR. The change will sync back to the public repo automatically, and the public PR will close automatically.
-- To make edits or updates to these changes, they should be made directly to the public PR. Contributor updates there will sync back into this monorepo PR.
-
-${buildBridgeMetadata(publicPr, mirrorPath, internalHeadSha)}`;
-
- let body = compose(rawOriginal);
- if (body.length > GITHUB_PR_BODY_LIMIT) {
- const footer = `\n\n_...truncated. Original body exceeded GitHub's ${GITHUB_PR_BODY_LIMIT}-char PR body limit; see [original PR](${publicPr.html_url}) for full content._`;
- const scaffolding = body.length - rawOriginal.length;
- const budget = GITHUB_PR_BODY_LIMIT - scaffolding - footer.length - 100;
- const truncated = rawOriginal.slice(0, Math.max(budget, 0)) + footer;
- console.log(
- `Bridge: PR body exceeded GitHub's ${GITHUB_PR_BODY_LIMIT}-char limit ` +
- `(original: ${rawOriginal.length} chars, truncated to: ${truncated.length} chars).`,
- );
- body = compose(truncated);
- }
- return body;
-}
-
-function buildWelcomePublicComment() {
- return `Thanks for the contribution!
-
-**What happens next:**
-
-- A maintainer will review your PR if it is a small fix (typo, broken link, docs or translation correction) or links an issue a maintainer has accepted. Other pull requests may be closed without review; a detailed issue is the faster path for those.
-- If you don't hear back within a few business days, please comment here to nudge our team.
-- This repository is maintained through an internal mirror. When your change is accepted, this PR will close automatically. Don't be alarmed when it closes — that's how it merges, and your authorship is preserved.`;
-}
-
-async function createIssueComment({ token, repo, issueNumber, body }) {
- const created = await githubRequest({
- token,
- method: 'POST',
- path: `/repos/${repo}/issues/${issueNumber}/comments`,
- body: { body },
- });
- return created.html_url;
-}
-
-async function acknowledgePublicPr() {
- const publicToken = requireEnv('PUBLIC_TOKEN');
- const publicRepo = requireEnv('PUBLIC_REPO');
- const publicPrNumber = Number.parseInt(requireEnv('PUBLIC_PR_NUMBER'), 10);
-
- await createIssueComment({
- token: publicToken,
- repo: publicRepo,
- issueNumber: publicPrNumber,
- body: buildWelcomePublicComment(),
- });
-}
-
-async function findOpenInternalPr({ token, repo, owner, branchName }) {
- const pulls = await githubRequest({
- token,
- path: `/repos/${repo}/pulls?state=open&head=${encodeURIComponent(`${owner}:${branchName}`)}`,
- });
- return pulls[0] ?? null;
-}
-
-async function ensureDraftState({ token, pullRequest, shouldBeDraft }) {
- if (Boolean(pullRequest.draft) === Boolean(shouldBeDraft)) {
- return;
- }
-
- const query = shouldBeDraft
- ? `mutation($id: ID!) { convertPullRequestToDraft(input: { pullRequestId: $id }) { pullRequest { id } } }`
- : `mutation($id: ID!) { markPullRequestReadyForReview(input: { pullRequestId: $id }) { pullRequest { id } } }`;
-
- await githubGraphql({
- token,
- query,
- variables: { id: pullRequest.node_id },
- });
-}
-
-async function readCommitClaStatus({ token, repo, sha, request = githubRequest }) {
- const result = await request({
- token,
- path: `/repos/${repo}/commits/${sha}/status?per_page=100`,
- });
- const cla = (result.statuses ?? []).find((s) => s.context === 'license/cla');
- return cla ? cla.state : null;
-}
-
-async function checkOrgMembership({ token, org, login, request = githubRequest }) {
- try {
- await request({ token, path: `/orgs/${org}/members/${encodeURIComponent(login)}` });
- return true;
- } catch (error) {
- if (error?.status === 404) {
- return false;
- }
- throw error;
- }
-}
-
-async function postCommitStatus({
- token,
- repo,
- sha,
- state,
- context,
- description,
- request = githubRequest,
-}) {
- await request({
- token,
- method: 'POST',
- path: `/repos/${repo}/statuses/${sha}`,
- body: { state, context, description },
- });
-}
-
-function createClaGateGh({
- publicToken,
- publicRepo,
- internalToken,
- internalRepo,
- request = githubRequest,
-}) {
- const org = internalRepo.split('/')[0];
- return {
- readClaStatus: (pr) =>
- readCommitClaStatus({ token: publicToken, repo: publicRepo, sha: pr.head.sha, request }),
- isOrgMember: (login) => checkOrgMembership({ token: internalToken, org, login, request }),
- setDraft: (pr, shouldBeDraft) =>
- ensureDraftState({ token: internalToken, pullRequest: pr, shouldBeDraft }),
- setVerifiedStatus: (pr, state, description) =>
- postCommitStatus({
- token: internalToken,
- repo: internalRepo,
- sha: pr.head.sha,
- state,
- context: 'cla/verified',
- description,
- request,
- }),
- };
-}
-
-async function refreshPublicPrCla() {
- if (requireEnv('PUBLIC_STATUS_CONTEXT') !== 'license/cla') {
- console.log('Bridge: skipped CLA refresh for an unrelated public status.');
- return;
- }
- const sha = requireEnv('PUBLIC_STATUS_SHA');
- const publicToken = requireEnv('PUBLIC_TOKEN');
- const internalToken = requireEnv('INTERNAL_TOKEN');
- const publicRepo = requireEnv('PUBLIC_REPO');
- const internalRepo = requireEnv('INTERNAL_REPO');
- const internalBranchPrefix = requireEnv('INTERNAL_BRANCH_PREFIX');
- const owner = internalRepo.split('/')[0];
- let matchedPublicPrs = 0;
- for (let page = 1; ; page += 1) {
- const openPrs = await githubRequest({
- token: publicToken,
- path: `/repos/${publicRepo}/pulls?state=open&per_page=100&page=${page}`,
- });
- for (const candidate of openPrs) {
- if (candidate.head?.sha !== sha) continue;
- matchedPublicPrs += 1;
- const publicPr = await githubRequest({
- token: publicToken,
- path: `/repos/${publicRepo}/pulls/${candidate.number}`,
- });
- const publicHead = `public PR #${publicPr.number} head ${sha}`;
- if (
- publicPr.state !== 'open' ||
- publicPr.head.sha !== sha ||
- publicPr.base.repo.full_name !== publicRepo ||
- (publicPr.head.repo?.full_name === publicRepo && publicPr.head.ref === 'copybara/sync')
- ) {
- console.log(`Bridge: skipped ${publicHead}; public PR is no longer eligible.`);
- continue;
- }
- const branchName = getPublicPrBranchName(internalBranchPrefix, publicPr.number);
- const linkedPr = await findOpenInternalPr({
- token: internalToken,
- repo: internalRepo,
- owner,
- branchName,
- });
- if (!linkedPr) {
- console.log(`Bridge: skipped ${publicHead}; no linked import is open.`);
- continue;
- }
- const internalPr = linkedPr;
- if (!importedHeadMatches({ internalPr, publicPr, publicRepo, branchName })) {
- console.log(`Bridge: skipped ${publicHead}; recorded import does not match.`);
- continue;
- }
- const headCommit = await githubRequest({
- token: internalToken,
- path: `/repos/${internalRepo}/commits/${internalPr.head.sha}`,
- });
- const currentPublicPr = await githubRequest({
- token: publicToken,
- path: `/repos/${publicRepo}/pulls/${publicPr.number}`,
- });
- const currentInternalPr = await githubRequest({
- token: internalToken,
- path: `/repos/${internalRepo}/pulls/${internalPr.number}`,
- });
- if (
- currentPublicPr.state !== 'open' ||
- currentPublicPr.head.sha !== sha ||
- currentInternalPr.head.sha !== internalPr.head.sha ||
- !importedHeadMatches({
- internalPr: currentInternalPr,
- publicPr: currentPublicPr,
- publicRepo,
- branchName,
- })
- ) {
- console.log(`Bridge: skipped ${publicHead}; public PR or import changed during refresh.`);
- continue;
- }
- await applyClaGate({
- gh: createClaGateGh({ publicToken, publicRepo, internalToken, internalRepo }),
- publicPr: currentPublicPr,
- internalPr: currentInternalPr,
- forceDraft: commitIndicatesConflicts(headCommit.commit.message),
- });
- console.log(`Bridge: refreshed CLA for ${publicHead}.`);
- }
- if (openPrs.length < 100) break;
- }
- if (matchedPublicPrs === 0) {
- console.log(`Bridge: no open public PR has head ${sha}.`);
- }
-}
-
-const CONFLICT_COMMIT_MARKER = 'with conflicts; needs manual resolution';
-
-function commitIndicatesConflicts(commitMessage) {
- return typeof commitMessage === 'string' && commitMessage.includes(CONFLICT_COMMIT_MARKER);
-}
-
-function applyPatchWithConflictDetection(internalRepoDir, patchFile) {
- try {
- run('git', ['-C', internalRepoDir, 'apply', '--index', '--3way', patchFile]);
- return { outcome: 'clean', conflictedPaths: [], message: '' };
- } catch (error) {
- let conflictedPaths = [];
- try {
- const unmerged = run('git', [
- '-C',
- internalRepoDir,
- 'diff',
- '--name-only',
- '--diff-filter=U',
- ]);
- conflictedPaths = unmerged ? unmerged.split('\n').filter(Boolean) : [];
- } catch (probeError) {
- console.warn(
- `Bridge: git diff --diff-filter=U probe threw after a failed apply; routing as 'failed'. Probe error: ${probeError.message}`,
- );
- conflictedPaths = [];
- }
- if (conflictedPaths.length > 0) {
- return { outcome: 'conflicts', conflictedPaths, message: error.message };
- }
- return { outcome: 'failed', conflictedPaths: [], message: error.message };
- }
-}
-
-async function syncPublicPr() {
- const publicToken = requireEnv('PUBLIC_TOKEN');
- const internalToken = requireEnv('INTERNAL_TOKEN');
- const publicRepo = requireEnv('PUBLIC_REPO');
- const internalRepo = requireEnv('INTERNAL_REPO');
- const internalRepoDir = requireEnv('INTERNAL_REPO_DIR');
- const mirrorPath = requireEnv('MONOREPO_PATH_PREFIX');
- const internalBaseRef = requireEnv('INTERNAL_BASE_REF');
- const internalBranchPrefix = requireEnv('INTERNAL_BRANCH_PREFIX');
- const publicPrAction = process.env.PUBLIC_PR_ACTION ?? 'opened';
- const publicPrNumber = Number.parseInt(requireEnv('PUBLIC_PR_NUMBER'), 10);
- const pathRewrites = parseJsonEnv('PUBLIC_PR_PATH_REWRITES', {});
- const internalOwner = internalRepo.split('/')[0];
- const branchName = getPublicPrBranchName(internalBranchPrefix, publicPrNumber);
-
- const publicPr = await githubRequest({
- token: publicToken,
- path: `/repos/${publicRepo}/pulls/${publicPrNumber}`,
- });
-
- let internalPr = await findOpenInternalPr({
- token: internalToken,
- repo: internalRepo,
- owner: internalOwner,
- branchName,
- });
-
- const metadataAction =
- publicPrAction === 'edited' ||
- publicPrAction === 'ready_for_review' ||
- publicPrAction === 'converted_to_draft';
- const legacyNeedsRebuild =
- internalPr &&
- metadataAction &&
- legacyImportNeedsRebuild({ internalPr, publicPr, publicRepo, branchName });
- const metadataOnlyAction = internalPr && metadataAction && !legacyNeedsRebuild;
-
- if (legacyNeedsRebuild) {
- console.log(
- `Bridge: public PR #${publicPr.number} head ${publicPr.head.sha} has a legacy import; rebuilding after approval.`,
- );
- }
-
- let hasStagedChanges = false;
- let hasConflicts = false;
- if (!metadataOnlyAction) {
- run('git', ['-C', internalRepoDir, 'fetch', 'origin', internalBaseRef, '--prune']);
- run('git', ['-C', internalRepoDir, 'checkout', '-B', branchName, `origin/${internalBaseRef}`]);
-
- const sourceRemote = `bridge-public-${publicPrNumber}`;
- const sourceBaseRef = `refs/remotes/${sourceRemote}/pr-base`;
- const sourceHeadRef = `refs/remotes/${sourceRemote}/pr-head`;
- const publicRepoUrl = `https://x-access-token:${publicToken}@github.com/${publicRepo}.git`;
- const publicHeadRepo = publicPr.head.repo?.full_name ?? publicRepo;
- const publicHeadRepoUrl = `https://x-access-token:${publicToken}@github.com/${publicHeadRepo}.git`;
-
- try {
- run('git', ['-C', internalRepoDir, 'remote', 'remove', sourceRemote]);
- } catch {}
- run('git', ['-C', internalRepoDir, 'remote', 'add', sourceRemote, publicRepoUrl]);
-
- try {
- try {
- run('git', [
- '-C',
- internalRepoDir,
- 'fetch',
- '--no-tags',
- sourceRemote,
- `+refs/pull/${publicPrNumber}/head:${sourceHeadRef}`,
- `+refs/heads/${publicPr.base.ref}:${sourceBaseRef}`,
- ]);
- } catch (error) {
- console.warn(`Bridge: public PR refs were unavailable: ${error.message}`);
- }
-
- fetchSourceCommit({
- internalRepoDir,
- remoteUrl: publicRepoUrl,
- sha: publicPr.base.sha,
- role: 'base',
- });
- fetchSourceCommit({
- internalRepoDir,
- remoteUrl: publicHeadRepoUrl,
- sha: publicPr.head.sha,
- role: 'head',
- });
- const rawPatch = diffRecordedPublicCommits(
- internalRepoDir,
- publicPr.base.sha,
- publicPr.head.sha,
- );
- const excludedPrefixes = parseJsonEnv('BRIDGE_EXCLUDED_PATHS', []);
- const patch = filterDiffByPath(rawPatch, excludedPrefixes);
-
- if (!patch.trim()) {
- console.log(
- `Bridge: public PR #${publicPr.number} head ${publicPr.head.sha} has no importable diff; no new import recorded.`,
- );
- return;
- }
-
- const tempDir = mkdtempSync(path.join(tmpdir(), 'public-pr-bridge-'));
- const patchFile = path.join(tempDir, 'public-pr.patch');
- writeFileSync(patchFile, prefixPatchPaths(patch, mirrorPath, pathRewrites), 'utf8');
-
- try {
- const applyResult = applyPatchWithConflictDetection(internalRepoDir, patchFile);
-
- if (applyResult.outcome === 'failed') {
- throw new Error(applyResult.message || 'git apply failed');
- }
-
- hasConflicts = applyResult.outcome === 'conflicts';
-
- if (hasConflicts) {
- run('git', ['-C', internalRepoDir, 'add', '-A']);
- }
-
- hasStagedChanges = (() => {
- try {
- run('git', ['-C', internalRepoDir, 'diff', '--cached', '--quiet']);
- return false;
- } catch {
- return true;
- }
- })();
-
- if (hasStagedChanges) {
- run('git', ['-C', internalRepoDir, 'config', 'user.name', OSS_SYNC_BOT_NAME]);
- run('git', ['-C', internalRepoDir, 'config', 'user.email', OSS_SYNC_BOT_EMAIL]);
-
- let publicCommits = [];
- try {
- publicCommits = await listPublicPrCommits({
- token: publicToken,
- repo: publicRepo,
- prNumber: publicPr.number,
- });
- } catch (error) {
- console.warn(
- `Bridge: could not fetch public PR commits for message context: ${error.message}`,
- );
- }
- const { body: commitBody } = buildCommitAttribution({
- commitAuthors: [publicPrAuthor(publicPr)],
- commitMessages: publicCommits,
- publicRepo,
- });
- const commitMessage = bridgeCommitSubject({ publicRepo, publicPr, hasConflicts });
- run('git', [
- '-C',
- internalRepoDir,
- 'commit',
- '--cleanup=verbatim',
- '-m',
- commitMessage,
- '-m',
- commitBody,
- ]);
-
- run('git', [
- '-C',
- internalRepoDir,
- 'push',
- '--force-with-lease',
- '--set-upstream',
- 'origin',
- branchName,
- ]);
- }
- } finally {
- rmSync(tempDir, { recursive: true, force: true });
- }
- } finally {
- try {
- run('git', ['-C', internalRepoDir, 'remote', 'remove', sourceRemote]);
- } catch {}
- }
-
- internalPr = await findOpenInternalPr({
- token: internalToken,
- repo: internalRepo,
- owner: internalOwner,
- branchName,
- });
-
- if (!internalPr && !hasStagedChanges) {
- console.log(
- `Bridge: public PR #${publicPr.number} head ${publicPr.head.sha} produced no staged change; no import recorded.`,
- );
- return;
- }
- }
-
- if (
- !hasStagedChanges &&
- internalPr &&
- !importedHeadMatches({ internalPr, publicPr, publicRepo, branchName })
- ) {
- const reason = metadataOnlyAction
- ? 'recorded import does not match the current heads'
- : 'produced no staged change and has no matching import';
- console.log(
- `Bridge: public PR #${publicPr.number} head ${publicPr.head.sha} ${reason}; no new receipt recorded.`,
- );
- return;
- }
-
- if (metadataOnlyAction && internalPr) {
- const headCommit = await githubRequest({
- token: internalToken,
- path: `/repos/${internalRepo}/commits/${internalPr.head.sha}`,
- });
- if (headCommit?.commit?.message == null) {
- console.warn(
- `Bridge: missing commit message for ${internalPr.head.sha}; conflict hold not re-derived on metadata re-sync.`,
- );
- }
- hasConflicts = commitIndicatesConflicts(headCommit?.commit?.message);
- }
-
- const internalHeadSha = hasStagedChanges
- ? run('git', ['-C', internalRepoDir, 'rev-parse', 'HEAD'])
- : internalPr.head.sha;
- const currentPublicPr = await githubRequest({
- token: publicToken,
- path: `/repos/${publicRepo}/pulls/${publicPr.number}`,
- });
- if (currentPublicPr.state !== 'open' || currentPublicPr.head.sha !== publicPr.head.sha) {
- console.log(
- `Bridge: public PR #${publicPr.number} head ${publicPr.head.sha} changed during sync; no matching receipt recorded.`,
- );
- if (hasStagedChanges) {
- await createClaGateGh({
- publicToken,
- publicRepo,
- internalToken,
- internalRepo,
- }).setVerifiedStatus(
- { head: { sha: internalHeadSha } },
- 'failure',
- 'Public head changed during sync; awaiting the next approved sync.',
- );
- }
- return;
- }
- const title = internalPullRequestTitle(currentPublicPr);
- const body = buildInternalPrBody({
- publicPr: currentPublicPr,
- branchName,
- mirrorPath,
- internalHeadSha,
- });
-
- if (internalPr) {
- internalPr = await githubRequest({
- token: internalToken,
- method: 'PATCH',
- path: `/repos/${internalRepo}/pulls/${internalPr.number}`,
- body: { title, body },
- });
- } else {
- internalPr = await githubRequest({
- token: internalToken,
- method: 'POST',
- path: `/repos/${internalRepo}/pulls`,
- body: {
- title,
- head: branchName,
- base: internalBaseRef,
- body,
- draft: currentPublicPr.draft,
- },
- });
- }
-
- internalPr.head.sha = internalHeadSha;
-
- await applyClaGate({
- gh: createClaGateGh({ publicToken, publicRepo, internalToken, internalRepo }),
- publicPr: currentPublicPr,
- internalPr,
- forceDraft: hasConflicts,
- });
- console.log(
- `Bridge: applied CLA gate for public PR #${publicPr.number} head ${publicPr.head.sha}.`,
- );
-}
-
-async function closeLinkedInternalPr() {
- const publicToken = requireEnv('PUBLIC_TOKEN');
- const internalToken = requireEnv('INTERNAL_TOKEN');
- const publicRepo = requireEnv('PUBLIC_REPO');
- const internalRepo = requireEnv('INTERNAL_REPO');
- const internalBranchPrefix = requireEnv('INTERNAL_BRANCH_PREFIX');
- const publicPrNumber = Number.parseInt(requireEnv('PUBLIC_PR_NUMBER'), 10);
- const internalOwner = internalRepo.split('/')[0];
- const branchName = getPublicPrBranchName(internalBranchPrefix, publicPrNumber);
-
- const publicPr = await githubRequest({
- token: publicToken,
- path: `/repos/${publicRepo}/pulls/${publicPrNumber}`,
- });
-
- const internalPr = await findOpenInternalPr({
- token: internalToken,
- repo: internalRepo,
- owner: internalOwner,
- branchName,
- });
-
- if (!internalPr) {
- return;
- }
-
- if (publicPr.merged_at) {
- return;
- }
-
- await githubRequest({
- token: internalToken,
- method: 'POST',
- path: `/repos/${internalRepo}/issues/${internalPr.number}/comments`,
- body: {
- body: `Closing because the linked public PR [#${publicPr.number}](${publicPr.html_url}) was closed without merge.`,
- },
- });
-
- await githubRequest({
- token: internalToken,
- method: 'PATCH',
- path: `/repos/${internalRepo}/pulls/${internalPr.number}`,
- body: { state: 'closed' },
- });
-
- try {
- await githubRequest({
- token: internalToken,
- method: 'DELETE',
- path: `/repos/${internalRepo}/git/refs/heads/${branchName}`,
- });
- } catch {}
-}
-
-async function main() {
- const mode = process.argv[2];
- if (mode === 'acknowledge') {
- await acknowledgePublicPr();
- return;
- }
-
- if (mode === 'sync') {
- await syncPublicPr();
- return;
- }
-
- if (mode === 'refresh-cla') {
- await refreshPublicPrCla();
- return;
- }
-
- if (mode === 'close') {
- await closeLinkedInternalPr();
- return;
- }
-
- throw new Error(`Unsupported mode: ${mode}`);
-}
-
-if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
- main().catch((error) => {
- console.error(error.stack || error.message);
- process.exitCode = 1;
- });
-}
-
-export {
- applyPatchWithConflictDetection,
- bridgeCommitSubject,
- buildCommitAttribution,
- buildInternalPrBody,
- buildWelcomePublicComment,
- checkOrgMembership,
- commitIndicatesConflicts,
- createClaGateGh,
- listPublicPrCommits,
- normalizeGitHubUserAuthor,
- postCommitStatus,
- prefixPatchPaths,
- readCommitClaStatus,
- refreshPublicPrCla,
- syncPublicPr,
-};
diff --git a/.github/scripts/bridge-public-pr-to-monorepo.test.mjs b/.github/scripts/bridge-public-pr-to-monorepo.test.mjs
deleted file mode 100644
index 63fcc04fc..000000000
--- a/.github/scripts/bridge-public-pr-to-monorepo.test.mjs
+++ /dev/null
@@ -1,1364 +0,0 @@
-import { execFileSync } from 'node:child_process';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import path from 'node:path';
-import { describe, expect, test } from 'vitest';
-import { gitCleanEnv } from '../../scripts/git-clean-env.mjs';
-import { configureTestGitRepository } from '../../test-support/configure-git-fixture.test-helper.ts';
-import * as bridge from './bridge-public-pr-to-monorepo.mjs';
-import {
- applyPatchWithConflictDetection,
- bridgeCommitSubject,
- buildCommitAttribution,
- buildWelcomePublicComment,
- checkOrgMembership,
- commitIndicatesConflicts,
- createClaGateGh,
- listPublicPrCommits,
- normalizeGitHubUserAuthor,
- postCommitStatus,
- readCommitClaStatus,
- syncPublicPr,
-} from './bridge-public-pr-to-monorepo.mjs';
-import { expectNoAutomaticGitMaintenance } from './git-fixture-maintenance.test-helper.mjs';
-
-const fakeRequest = (response) => {
- const calls = [];
- const request = async (args) => {
- calls.push(args);
- return response;
- };
- return { request, calls };
-};
-
-describe('buildCommitAttribution', () => {
- test('credits every unique contributor with native coauthor trailers', () => {
- const attribution = buildCommitAttribution({
- commitAuthors: [
- { name: 'Sarah Inkeep', email: '[email protected]' },
- {
- name: 'github-actions[bot]',
- email: '41898282+github-actions[bot]@users.noreply.github.com',
- },
- { name: 'Sarah Inkeep', email: '[email protected]' },
- { name: 'Robert Inkeep', email: '[email protected]' },
- ],
- });
-
- expect(attribution.trailers).toEqual([
- 'Co-authored-by: Sarah Inkeep <[email protected]>',
- 'Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>',
- 'Co-authored-by: Robert Inkeep <[email protected]>',
- ]);
- });
-
- test('lists commits for readability and builds a deduped GitHub attribution block', () => {
- const attribution = buildCommitAttribution({
- commitAuthors: [{ name: 'octocat', email: '[email protected]' }],
- commitMessages: [
- {
- sha: '1234567890abcdef',
- author: { name: 'Sarah Inkeep', email: '[email protected]' },
- message: 'Add search\n\nExplain the indexing path.',
- },
- {
- sha: 'fedcba9876543210',
- author: { name: 'Robert Inkeep', email: '[email protected]' },
- message: 'Fix empty query\r\n\r\nCo-authored-by: A <[email protected]>',
- },
- ],
- publicRepo: 'inkeep/open-knowledge',
- });
-
- expect(attribution.originalCommitMessages).toBe(
- [
- 'Commits:',
- '',
- '[1234567](https://github.com/inkeep/open-knowledge/commit/1234567890abcdef)',
- 'Author: Sarah Inkeep <[email protected]>',
- '',
- 'Add search',
- '',
- 'Explain the indexing path.',
- '',
- '[fedcba9](https://github.com/inkeep/open-knowledge/commit/fedcba9876543210)',
- 'Author: Robert Inkeep <[email protected]>',
- '',
- 'Fix empty query',
- '',
- 'Co-authored-by: A <[email protected]>',
- ].join('\n'),
- );
- expect(attribution.trailers).toEqual([
- 'Co-authored-by: octocat <[email protected]>',
- 'Co-authored-by: Sarah Inkeep <[email protected]>',
- 'Co-authored-by: Robert Inkeep <[email protected]>',
- 'Co-authored-by: A <[email protected]>',
- ]);
- });
-
- test('allows an empty attribution block when no author normalizes', () => {
- const attribution = buildCommitAttribution({
- commitAuthors: [{ name: 'Bad\nName', email: '[email protected]' }],
- commitMessages: [],
- });
-
- expect(attribution.trailers).toEqual([]);
- expect(attribution.body).toBe('');
- });
-});
-
-describe('bridgeCommitSubject', () => {
- test('includes the original public PR title while keeping the sync prefix', () => {
- expect(
- bridgeCommitSubject({
- publicRepo: 'inkeep/open-knowledge',
- publicPr: { number: 361, title: 'Preserve contributor commit messages' },
- hasConflicts: false,
- }),
- ).toBe('sync(oss): mirror inkeep/open-knowledge#361: Preserve contributor commit messages');
- });
-
- test('normalizes multiline titles and preserves the conflict marker', () => {
- expect(
- bridgeCommitSubject({
- publicRepo: 'inkeep/open-knowledge',
- publicPr: { number: 361, title: 'Fix bridge\n\nsubject' },
- hasConflicts: true,
- }),
- ).toBe(
- 'sync(oss): mirror inkeep/open-knowledge#361: Fix bridge subject (with conflicts; needs manual resolution)',
- );
- });
-});
-
-describe('listPublicPrCommits', () => {
- test('returns public PR commit authors and messages', async () => {
- const { request } = fakeRequest([
- {
- sha: 'abcdef1234567890',
- author: { login: 'linked-author', id: 7 },
- commit: {
- author: { name: 'Raw Author', email: '[email protected]' },
- message: 'Add bridge attribution\n\nKeep the public commit message.',
- },
- },
- ]);
-
- await expect(
- listPublicPrCommits({
- token: 't',
- repo: 'owner/repo',
- prNumber: 123,
- request,
- }),
- ).resolves.toEqual([
- {
- sha: 'abcdef1234567890',
- author: { name: 'linked-author', email: '[email protected]' },
- message: 'Add bridge attribution\n\nKeep the public commit message.',
- },
- ]);
- });
-
- test('paginates until a page returns fewer than 100 commits', async () => {
- const calls = [];
- const pageOne = Array.from({ length: 100 }, (_, index) => ({
- sha: `${index.toString(16).padStart(7, '0')}abcdef`,
- author: { login: `author-${index}`, id: index + 1 },
- commit: {
- author: { name: `Raw Author ${index}`, email: `raw-${index}@example.com` },
- message: `Commit ${index}`,
- },
- }));
- const pageTwo = [
- {
- sha: 'feedbee',
- author: { login: 'last-author', id: 101 },
- commit: {
- author: { name: 'Raw Last', email: '[email protected]' },
- message: 'Commit 100',
- },
- },
- ];
- const request = async (args) => {
- calls.push(args);
- return calls.length === 1 ? pageOne : pageTwo;
- };
-
- const commits = await listPublicPrCommits({
- token: 't',
- repo: 'owner/repo',
- prNumber: 123,
- request,
- });
-
- expect(commits).toHaveLength(101);
- expect(commits[0]).toEqual({
- sha: '0000000abcdef',
- author: { name: 'author-0', email: '[email protected]' },
- message: 'Commit 0',
- });
- expect(commits.at(-1)).toEqual({
- sha: 'feedbee',
- author: { name: 'last-author', email: '[email protected]' },
- message: 'Commit 100',
- });
- expect(calls.map((call) => call.path)).toEqual([
- '/repos/owner/repo/pulls/123/commits?per_page=100&page=1',
- '/repos/owner/repo/pulls/123/commits?per_page=100&page=2',
- ]);
- });
-});
-
-describe('normalizeGitHubUserAuthor', () => {
- test('uses the GitHub-resolved user id/login noreply identity', () => {
- expect(normalizeGitHubUserAuthor({ login: 'rtran9', id: 11001605 })).toEqual({
- name: 'rtran9',
- email: '[email protected]',
- });
- });
-
- test('ignores unresolved users but preserves bots as valid contributors', () => {
- expect(normalizeGitHubUserAuthor(null)).toBeNull();
- expect(normalizeGitHubUserAuthor({ login: 'github-actions[bot]', id: 41898282 })).toEqual({
- name: 'github-actions[bot]',
- email: '41898282+github-actions[bot]@users.noreply.github.com',
- });
- });
-});
-
-describe('readCommitClaStatus', () => {
- test('extracts the license/cla state from the combined status', async () => {
- const { request } = fakeRequest({
- statuses: [
- { context: 'ci/build', state: 'success' },
- { context: 'license/cla', state: 'success' },
- ],
- });
- expect(await readCommitClaStatus({ token: 't', repo: 'o/r', sha: 'abc', request })).toBe(
- 'success',
- );
- });
-
- test('returns null when the license/cla context is absent', async () => {
- const { request } = fakeRequest({ statuses: [{ context: 'ci/build', state: 'failure' }] });
- expect(await readCommitClaStatus({ token: 't', repo: 'o/r', sha: 'abc', request })).toBeNull();
- });
-
- test('returns null for an empty status set', async () => {
- const { request } = fakeRequest({ statuses: [] });
- expect(await readCommitClaStatus({ token: 't', repo: 'o/r', sha: 'abc', request })).toBeNull();
- });
-
- test("requests the combined status with per_page=100 so license/cla can't fall off page 1", async () => {
- const { request, calls } = fakeRequest({ statuses: [] });
- await readCommitClaStatus({ token: 't', repo: 'owner/repo', sha: 'deadbeef', request });
- expect(calls).toHaveLength(1);
- expect(calls[0].path).toBe('/repos/owner/repo/commits/deadbeef/status?per_page=100');
- });
-});
-
-describe('postCommitStatus', () => {
- test("POSTs the given state/context/description to the commit's statuses endpoint", async () => {
- const { request, calls } = fakeRequest(undefined);
- await postCommitStatus({
- token: 't',
- repo: 'owner/repo',
- sha: 'abc123',
- state: 'failure',
- context: 'cla/verified',
- description: 'held',
- request,
- });
- expect(calls).toHaveLength(1);
- expect(calls[0]).toMatchObject({
- method: 'POST',
- path: '/repos/owner/repo/statuses/abc123',
- body: { state: 'failure', context: 'cla/verified', description: 'held' },
- });
- });
-});
-
-describe('checkOrgMembership', () => {
- test('returns true on a 204 (member)', async () => {
- const { request, calls } = fakeRequest(null);
- expect(await checkOrgMembership({ token: 't', org: 'inkeep', login: 'octocat', request })).toBe(
- true,
- );
- expect(calls[0].path).toBe('/orgs/inkeep/members/octocat');
- });
-
- test('returns false on a 404 (non-member)', async () => {
- const request = async () => {
- const error = new Error('not found (404)');
- error.status = 404;
- throw error;
- };
- expect(
- await checkOrgMembership({ token: 't', org: 'inkeep', login: 'outsider', request }),
- ).toBe(false);
- });
-
- test('propagates non-404 errors so the gate fails closed', async () => {
- const request = async () => {
- const error = new Error('forbidden (403)');
- error.status = 403;
- throw error;
- };
- await expect(
- checkOrgMembership({ token: 't', org: 'inkeep', login: 'x', request }),
- ).rejects.toThrow(/403/);
- });
-});
-
-describe('createClaGateGh', () => {
- const deps = {
- publicToken: 'public-token',
- publicRepo: 'inkeep/open-knowledge',
- internalToken: 'internal-token',
- internalRepo: 'inkeep/agents-private',
- };
-
- test('readClaStatus reads license/cla from the public PR head, on the public token', async () => {
- const { request, calls } = fakeRequest({
- statuses: [{ context: 'license/cla', state: 'pending' }],
- });
- const gh = createClaGateGh({ ...deps, request });
- const state = await gh.readClaStatus({ head: { sha: 'public-head' } });
- expect(state).toBe('pending');
- expect(calls[0].token).toBe('public-token');
- expect(calls[0].path).toBe(
- '/repos/inkeep/open-knowledge/commits/public-head/status?per_page=100',
- );
- });
-
- test('setVerifiedStatus posts the cla/verified context to the internal PR head', async () => {
- const { request, calls } = fakeRequest(undefined);
- const gh = createClaGateGh({ ...deps, request });
- await gh.setVerifiedStatus({ head: { sha: 'internal-head' } }, 'failure', 'needs signature');
- expect(calls).toHaveLength(1);
- expect(calls[0].token).toBe('internal-token');
- expect(calls[0].path).toBe('/repos/inkeep/agents-private/statuses/internal-head');
- expect(calls[0].body).toEqual({
- state: 'failure',
- context: 'cla/verified',
- description: 'needs signature',
- });
- });
-
- test("isOrgMember checks the internal repo's org on the internal token", async () => {
- const { request, calls } = fakeRequest(null);
- const gh = createClaGateGh({ ...deps, request });
- expect(await gh.isOrgMember('octocat')).toBe(true);
- expect(calls[0].token).toBe('internal-token');
- expect(calls[0].path).toBe('/orgs/inkeep/members/octocat');
- });
-});
-
-const git = (dir, ...args) =>
- execFileSync('git', ['-C', dir, ...args], {
- encoding: 'utf8',
- env: {
- ...gitCleanEnv(),
- ...(existsSync(path.join(dir, '.git'))
- ? { GIT_TRACE2_EVENT: path.join(dir, '.git', 'fixture-maintenance.jsonl') }
- : {}),
- },
- }).trim();
-
-function setupBridgeRepo({ baseContent, oursContent, theirsContent }) {
- const root = mkdtempSync(path.join(tmpdir(), 'bridge-canary-'));
- const repoDir = path.join(root, 'repo');
- mkdirSync(repoDir);
- git(repoDir, 'init', '-q');
- configureTestGitRepository(repoDir, (args) => git(repoDir, ...args));
- git(repoDir, 'config', 'user.email', '[email protected]');
- git(repoDir, 'config', 'user.name', 'canary');
- writeFileSync(path.join(repoDir, 'f.ts'), baseContent);
- git(repoDir, 'add', '-A');
- git(repoDir, 'commit', '-qm', 'base');
- const base = git(repoDir, 'rev-parse', 'HEAD');
- const defaultBranch = git(repoDir, 'rev-parse', '--abbrev-ref', 'HEAD');
- git(repoDir, 'checkout', '-q', '-b', 'contributor');
- writeFileSync(path.join(repoDir, 'f.ts'), theirsContent);
- git(repoDir, 'commit', '-qam', 'contributor change');
- const patch = git(repoDir, 'diff', base, 'HEAD');
- const patchFile = path.join(root, 'contributor.patch');
- writeFileSync(patchFile, `${patch}\n`);
- git(repoDir, 'checkout', '-q', defaultBranch);
- writeFileSync(path.join(repoDir, 'f.ts'), oursContent);
- git(repoDir, 'commit', '-qam', 'internal (comment-rich)');
- return {
- repoDir,
- patchFile,
- cleanup: () => rmSync(root, { recursive: true, force: true }),
- };
-}
-
-const STRIPPED_BASE = 'export const A = 1;\nexport const B = 2;\nexport const C = 3;\n';
-
-describe('applyPatchWithConflictDetection (graceful conflict routing canary)', () => {
- test("a comment-adjacency 3-way conflict is classified 'conflicts', not a hard failure", () => {
- const { repoDir, patchFile, cleanup } = setupBridgeRepo({
- baseContent: STRIPPED_BASE,
- theirsContent: 'export const A = 1;\nexport const B = 22;\nexport const C = 3;\n',
- oursContent:
- 'export const A = 1;\nexport const B = 2; // important constant (mirror strips this)\nexport const C = 3;\n',
- });
- try {
- const result = applyPatchWithConflictDetection(repoDir, patchFile);
- expect(result.outcome).toBe('conflicts');
- expect(result.conflictedPaths).toContain('f.ts');
- } finally {
- cleanup();
- }
- });
-
- test("a divergence far from the contributor's edit applies 'clean'", () => {
- const longBase =
- 'export const A = 1;\nexport const B = 2;\n' +
- 'const p = 0;\nconst q = 0;\nconst r = 0;\nconst s = 0;\nconst u = 0;\nconst v = 0;\n' +
- 'export const C = 3;\n';
- const { repoDir, patchFile, cleanup } = setupBridgeRepo({
- baseContent: longBase,
- theirsContent: longBase.replace('export const B = 2;', 'export const B = 22;'),
- oursContent: longBase.replace(
- 'export const C = 3;',
- 'export const C = 3; // note on C (mirror strips this)',
- ),
- });
- try {
- const result = applyPatchWithConflictDetection(repoDir, patchFile);
- expect(result.outcome).toBe('clean');
- expect(result.conflictedPaths).toHaveLength(0);
- } finally {
- cleanup();
- }
- });
-
- test("a genuinely un-appliable patch stays 'failed' (fail-closed, not swallowed)", () => {
- const root = mkdtempSync(path.join(tmpdir(), 'bridge-canary-failed-'));
- const repoDir = path.join(root, 'repo');
- mkdirSync(repoDir);
- git(repoDir, 'init', '-q');
- configureTestGitRepository(repoDir, (args) => git(repoDir, ...args));
- git(repoDir, 'config', 'user.email', '[email protected]');
- git(repoDir, 'config', 'user.name', 'canary');
- writeFileSync(path.join(repoDir, 'f.ts'), STRIPPED_BASE);
- git(repoDir, 'add', '-A');
- git(repoDir, 'commit', '-qm', 'base');
- const ghostPatch = [
- 'diff --git a/ghost.ts b/ghost.ts',
- 'index 1111111..2222222 100644',
- '--- a/ghost.ts',
- '+++ b/ghost.ts',
- '@@ -1 +1 @@',
- '-old',
- '+new',
- '',
- ].join('\n');
- const patchFile = path.join(root, 'ghost.patch');
- writeFileSync(patchFile, ghostPatch);
- try {
- const result = applyPatchWithConflictDetection(repoDir, patchFile);
- expect(result.outcome).toBe('failed');
- expect(result.conflictedPaths).toHaveLength(0);
- expect(result.message).toBeTruthy();
- expectNoAutomaticGitMaintenance(repoDir);
- } finally {
- rmSync(root, { recursive: true, force: true });
- }
- });
-
- test('welcome comment sets contributor expectations without implementation details', () => {
- const body = buildWelcomePublicComment();
-
- expect(body).toContain('Thanks for the contribution!');
- expect(body).toContain('A maintainer will review your PR if it is a small fix');
- expect(body).toContain('links an issue a maintainer has accepted');
- expect(body).toContain('may be closed without review');
- expect(body).toContain('internal mirror');
- expect(body).toContain('authorship is preserved');
- expect(body).not.toContain('Copybara');
- expect(body).not.toContain('rebase');
- expect(body).not.toContain('<!-- monorepo-pr-bridge -->');
- });
-});
-
-describe('commitIndicatesConflicts (metadata-re-sync conflict-hold guard)', () => {
- test('true for a conflict-marker mirror commit message', () => {
- expect(
- commitIndicatesConflicts(
- 'sync(oss): mirror inkeep/open-knowledge#310 (with conflicts; needs manual resolution)',
- ),
- ).toBe(true);
- });
-
- test('false for a clean mirror commit message', () => {
- expect(commitIndicatesConflicts('sync(oss): mirror inkeep/open-knowledge#310')).toBe(false);
- });
-
- test('false for absent / non-string input', () => {
- expect(commitIndicatesConflicts(undefined)).toBe(false);
- expect(commitIndicatesConflicts(null)).toBe(false);
- expect(commitIndicatesConflicts(42)).toBe(false);
- });
-});
-
-const CONFLICT_HEAD =
- 'sync(oss): mirror inkeep/open-knowledge#310 (with conflicts; needs manual resolution)';
-const CLEAN_HEAD = 'sync(oss): mirror inkeep/open-knowledge#310';
-
-async function runBridgeSync({
- headCommitMessage = CLEAN_HEAD,
- internalPrStartsDraft = false,
- internalRepoDir = '/tmp/unused-on-metadata-path',
- action = 'edited',
- claStatus = 'success',
- existingPr = true,
- readHead = () => 'internal-head-sha',
- patchHead = readHead,
- mode = 'sync',
- publicHead = 'public-head-sha',
- publicBase = 'public-base-sha',
- publicHeadOnReread = publicHead,
- changedPublicHeadAfterCommit = false,
- changedInternalHeadAfterCommit = false,
- importedPublicHead = 'public-head-sha',
- importedRepo = 'inkeep/open-knowledge',
- importedPrNumber = 310,
- importedInternalHead = readHead(),
- eventSha = 'public-head-sha',
- eventContext = 'license/cla',
- eventState = 'success',
- publicState = 'open',
- internalState = 'open',
- hasMarker = true,
- markerHeadFields = 'current',
- earlierMarker = '',
- headRef = 'contribution',
- headRepo = 'octocat/open-knowledge',
- internalHeadRef = 'public-pr/open-knowledge-310',
- associations = [{ number: 310 }],
- publicCandidates,
-}) {
- const recorded = {
- draftMutation: null,
- comment: null,
- statuses: [],
- validationRequests: [],
- internalBodies: [],
- };
- const marker = [
- '<!-- public-pr-sync',
- `public_repo=${importedRepo}`,
- `public_pr_number=${importedPrNumber}`,
- ...(markerHeadFields === 'current' || markerHeadFields === 'partial'
- ? [`public_head_sha=${importedPublicHead}`]
- : []),
- ...(markerHeadFields === 'current' || markerHeadFields === 'internal-only'
- ? [`internal_head_sha=${importedInternalHead}`]
- : []),
- '-->',
- ].join('\n');
- const internalPr = {
- number: 42,
- node_id: 'PR_node_42',
- draft: internalPrStartsDraft,
- head: { sha: readHead(), ref: internalHeadRef, repo: { full_name: 'inkeep/agents-private' } },
- state: internalState,
- base: { ref: 'main' },
- body: earlierMarker + (hasMarker ? marker : ''),
- html_url: 'https://github.com/inkeep/agents-private/pull/42',
- };
- const publicPr = {
- number: 310,
- title: 'Fix something',
- body: 'body',
- html_url: 'https://github.com/inkeep/open-knowledge/pull/310',
- user: { login: 'octocat', id: 99 },
- base: { ref: 'main', sha: publicBase, repo: { full_name: 'inkeep/open-knowledge' } },
- head: { label: 'octocat:branch', sha: publicHead, ref: headRef, repo: { full_name: headRepo } },
- state: publicState,
- draft: false,
- };
- const json = (obj, status = 200) => ({
- ok: status < 400,
- status,
- text: async () => JSON.stringify(obj),
- });
-
- let publicReads = 0;
- let internalHeadOverride;
- const apiHead = () => internalHeadOverride ?? readHead();
- const candidatePrs = publicCandidates ?? [{ number: 310, head: { sha: publicHead } }];
- const realFetch = globalThis.fetch;
- globalThis.fetch = async (url, init = {}) => {
- const method = init.method || 'GET';
- if (method === 'GET' && url.includes('/pulls/310/commits?')) return json([]);
- if (method === 'GET' && /\/commits\/[^/]+\/pulls\?/.test(url)) {
- const page = Number(new URL(url).searchParams.get('page') ?? 1);
- return json(associations.slice((page - 1) * 100, page * 100));
- }
- if (method === 'GET' && url.includes('/repos/inkeep/agents-private/pulls/42'))
- return json({ ...internalPr, head: { ...internalPr.head, sha: apiHead() } });
- if (method === 'GET' && url.includes('/repos/inkeep/open-knowledge/pulls/311'))
- return json({ ...publicPr, number: 311, head: { ...publicPr.head, sha: 'another-head' } });
- if (method === 'GET' && url.includes('/repos/inkeep/open-knowledge/pulls/310')) {
- publicReads += 1;
- return json({
- ...publicPr,
- head: {
- ...publicPr.head,
- sha:
- publicReads > 1
- ? changedPublicHeadAfterCommit
- ? publicPr.head.sha
- : publicHeadOnReread
- : publicPr.head.sha,
- },
- });
- }
- if (method === 'GET' && url.includes('/repos/inkeep/open-knowledge/pulls?state=open')) {
- const page = Number(new URL(url).searchParams.get('page') ?? 1);
- return json(candidatePrs.slice((page - 1) * 100, page * 100));
- }
- if (method === 'GET' && url.includes('/pulls?state=open'))
- return json(
- existingPr ? [{ ...internalPr, head: { ...internalPr.head, sha: readHead() } }] : [],
- );
- if (
- method === 'GET' &&
- url.includes('/commits/internal-head-sha') &&
- !url.includes('/status')
- ) {
- if (changedPublicHeadAfterCommit) publicPr.head.sha = 'new-public-head';
- if (changedInternalHeadAfterCommit) {
- internalHeadOverride = 'new-internal-head';
- internalPr.body = internalPr.body.replace(
- `internal_head_sha=${importedInternalHead}`,
- `internal_head_sha=${internalHeadOverride}`,
- );
- }
- return json({ commit: { message: headCommitMessage } });
- }
- if (method === 'PATCH' && url.includes('/pulls/42')) {
- const update = JSON.parse(init.body);
- recorded.internalBodies.push(update.body);
- return json({ ...internalPr, ...update, head: { ...internalPr.head, sha: patchHead() } });
- }
- if (method === 'POST' && url.endsWith('/repos/inkeep/agents-private/pulls')) {
- const update = JSON.parse(init.body);
- recorded.internalBodies.push(update.body);
- return json({
- ...internalPr,
- body: update.body,
- head: { ...internalPr.head, sha: patchHead() },
- });
- }
- if (method === 'GET' && url.includes('/orgs/')) return json({ message: 'Not Found' }, 404);
- if (method === 'GET' && url.includes(`/commits/${publicHead}/status`)) {
- return json({ statuses: [{ context: 'license/cla', state: claStatus }] });
- }
- if (method === 'GET' && url.includes('/actions/workflows/')) {
- const requestUrl = new URL(url);
- recorded.validationRequests.push({
- method,
- path: requestUrl.pathname,
- authorization: init.headers.Authorization,
- query: Object.fromEntries(requestUrl.searchParams),
- });
- return json({ workflow_runs: [] });
- }
- if (method === 'POST' && url.includes('/actions/runs/')) {
- recorded.validationRequests.push({
- method,
- path: new URL(url).pathname,
- authorization: init.headers.Authorization,
- verifiedStatus: recorded.statuses.at(-1),
- });
- return json(null, 201);
- }
- if (method === 'POST' && url.endsWith('/graphql')) {
- const q = JSON.parse(init.body).query;
- recorded.draftMutation = q.includes('convertPullRequestToDraft')
- ? 'to-draft'
- : q.includes('markPullRequestReadyForReview')
- ? 'to-ready'
- : 'unknown';
- return json({ data: {} });
- }
- if (method === 'POST' && url.includes('/statuses/')) {
- recorded.statuses.push({
- sha: new URL(url).pathname.split('/').at(-1),
- ...JSON.parse(init.body),
- });
- return json({});
- }
- if (method === 'POST' && url.includes('/issues/310/comments')) {
- recorded.comment = JSON.parse(init.body).body;
- return json({ html_url: 'https://github.com/x/comments/1' });
- }
- throw new Error(`unrouted request: ${method} ${url}`);
- };
-
- const setKeys = {
- PUBLIC_TOKEN: 'pub',
- INTERNAL_TOKEN: 'int',
- PUBLIC_REPO: 'inkeep/open-knowledge',
- INTERNAL_REPO: 'inkeep/agents-private',
- INTERNAL_REPO_DIR: internalRepoDir,
- MONOREPO_PATH_PREFIX: 'public/open-knowledge',
- INTERNAL_BASE_REF: 'main',
- INTERNAL_BRANCH_PREFIX: 'public-pr/open-knowledge',
- PUBLIC_PR_NUMBER: '310',
- PUBLIC_PR_ACTION: action,
- PUBLIC_STATUS_SHA: eventSha,
- PUBLIC_STATUS_CONTEXT: eventContext,
- PUBLIC_STATUS_STATE: eventState,
- GIT_ALLOW_PROTOCOL: 'file',
- };
- const saved = {};
- for (const k of Object.keys(setKeys)) saved[k] = process.env[k];
- Object.assign(process.env, setKeys);
- try {
- if (mode === 'sync') await syncPublicPr();
- else await bridge.refreshPublicPrCla();
- } finally {
- globalThis.fetch = realFetch;
- for (const k of Object.keys(setKeys)) {
- if (saved[k] === undefined) delete process.env[k];
- else process.env[k] = saved[k];
- }
- }
- return recorded;
-}
-
-describe('syncPublicPr metadata-event composition (conflict-hold fail-open guard)', () => {
- test('a metadata event on a DRAFT conflict PR keeps it draft and posts no public comment', async () => {
- const r = await runBridgeSync({
- headCommitMessage: CONFLICT_HEAD,
- internalPrStartsDraft: true,
- });
- expect(r.draftMutation).toBeNull();
- expect(r.comment).toBeNull();
- });
-
- test('a metadata event on a clean PR readies it and posts no public comment', async () => {
- const r = await runBridgeSync({ headCommitMessage: CLEAN_HEAD, internalPrStartsDraft: true });
- expect(r.draftMutation).toBe('to-ready');
- expect(r.comment).toBeNull();
- });
-
- test('a metadata event on a non-draft PR whose head now carries conflicts re-drafts it without a public comment', async () => {
- const r = await runBridgeSync({
- headCommitMessage: CONFLICT_HEAD,
- internalPrStartsDraft: false,
- });
- expect(r.draftMutation).toBe('to-draft');
- expect(r.comment).toBeNull();
- });
-});
-
-describe('bridge CLA status refresh', () => {
- test('a successful sync only posts status and never drives Actions', async () => {
- const result = await runBridgeSync({ claStatus: 'success' });
- expect(result.validationRequests).toEqual([]);
- });
-
- test.each(['success', 'failure', 'pending', null])(
- 'uses the current API status %s for the imported public head',
- async (claStatus) => {
- const result = await runBridgeSync({
- mode: 'refresh-cla',
- claStatus,
- eventState: claStatus === 'success' ? 'failure' : 'success',
- });
- expect(result.statuses).toEqual([
- expect.objectContaining({
- sha: 'internal-head-sha',
- context: 'cla/verified',
- state: claStatus === 'success' ? 'success' : 'failure',
- }),
- ]);
- expect(result.validationRequests).toEqual([]);
- expect(result.internalBodies).toEqual([]);
- },
- );
-
- test.each([
- ['other status context', { eventContext: 'another-check' }],
- [
- 'replaced public head',
- { publicHead: 'new-public-head', importedPublicHead: 'new-public-head' },
- ],
- ['other imported repository', { importedRepo: 'another/repository' }],
- ['other imported PR', { importedPrNumber: 311 }],
- ['pending import', { importedPublicHead: 'previous-public-head' }],
- ['replaced internal head', { importedInternalHead: 'previous-internal-head' }],
- ['public head changed during refresh', { changedPublicHeadAfterCommit: true }],
- ['internal head changed during refresh', { changedInternalHeadAfterCommit: true }],
- ['missing marker', { hasMarker: false }],
- ['closed public PR', { publicState: 'closed' }],
- ['closed internal PR', { internalState: 'closed' }],
- ['missing internal PR', { existingPr: false }],
- ['other internal branch', { internalHeadRef: 'fix/ordinary' }],
- ['mirror sync PR', { headRepo: 'inkeep/open-knowledge', headRef: 'copybara/sync' }],
- ])('leaves %s unchanged', async (_name, overrides) => {
- const result = await runBridgeSync({
- mode: 'refresh-cla',
- internalPrStartsDraft: true,
- ...overrides,
- });
- expect(result.statuses).toEqual([]);
- expect(result.draftMutation).toBeNull();
- expect(result.internalBodies).toEqual([]);
- });
-
- test('uses the final sync marker after the original PR body', async () => {
- const result = await runBridgeSync({
- mode: 'refresh-cla',
- earlierMarker:
- '<!-- public-pr-sync\npublic_head_sha=previous-public-head\ninternal_head_sha=previous-internal-head\n-->\n',
- });
- expect(result.statuses).toEqual([
- expect.objectContaining({ sha: 'internal-head-sha', state: 'success' }),
- ]);
- });
-
- test('finds the current public PR after a page of other open PRs', async () => {
- const result = await runBridgeSync({
- mode: 'refresh-cla',
- associations: [],
- publicCandidates: [
- ...Array.from({ length: 100 }, () => ({ number: 311, head: { sha: 'other-head' } })),
- { number: 310, head: { sha: 'public-head-sha' } },
- ],
- });
- expect(result.statuses).toEqual([
- expect.objectContaining({ sha: 'internal-head-sha', state: 'success' }),
- ]);
- });
-
- test('finds a fork PR when commit associations are empty', async () => {
- const result = await runBridgeSync({ mode: 'refresh-cla', associations: [] });
- expect(result.statuses).toEqual([
- expect.objectContaining({
- sha: 'internal-head-sha',
- context: 'cla/verified',
- state: 'success',
- }),
- ]);
- expect(result.internalBodies).toEqual([]);
- });
-
- test('refresh preserves the conflict hold on an imported head', async () => {
- const result = await runBridgeSync({
- mode: 'refresh-cla',
- headCommitMessage: CONFLICT_HEAD,
- internalPrStartsDraft: true,
- });
- expect(result.statuses).toEqual([expect.objectContaining({ state: 'success' })]);
- expect(result.draftMutation).toBeNull();
- });
-
- test('metadata edits do not attest to a public head that has not been imported', async () => {
- const result = await runBridgeSync({
- publicHead: 'new-public-head',
- internalPrStartsDraft: true,
- });
- expect(result.statuses).toEqual([]);
- expect(result.draftMutation).toBeNull();
- expect(result.internalBodies).toEqual([]);
- });
-});
-
-function setupSyncRepo({ sourceContent = 'updated\n', mapForkToSource = true } = {}) {
- const root = mkdtempSync(path.join(tmpdir(), 'bridge-head-status-'));
- const remote = path.join(root, 'remote.git');
- const internal = path.join(root, 'internal');
- const branch = 'public-pr/open-knowledge-310';
- git(root, 'init', '--bare', '--initial-branch=main', remote);
- configureTestGitRepository(remote, (args) => git(root, ...args));
- git(root, 'init', '--initial-branch=main', internal);
- configureTestGitRepository(internal, (args) => git(root, ...args));
- git(internal, 'config', 'user.name', 'Fixture');
- git(internal, 'config', 'user.email', '[email protected]');
- mkdirSync(path.join(internal, 'public/open-knowledge'), { recursive: true });
- const file = path.join(internal, 'public/open-knowledge/fixture.txt');
- writeFileSync(file, 'base\n');
- git(internal, 'add', 'public/open-knowledge/fixture.txt');
- git(internal, 'commit', '-m', 'Base');
- git(internal, 'remote', 'add', 'origin', remote);
- git(internal, 'push', '-u', 'origin', 'main');
- git(internal, 'checkout', '-b', branch);
- writeFileSync(file, 'previous\n');
- git(internal, 'commit', '-am', 'Previous head');
- git(internal, 'push', '-u', 'origin', branch);
- const oldHead = git(internal, 'rev-parse', 'HEAD');
- git(internal, 'checkout', 'main');
- const source = path.join(root, 'public');
- const sourceRepoDir = path.join(root, 'public.git');
- git(root, 'init', '--bare', '--initial-branch=main', sourceRepoDir);
- configureTestGitRepository(sourceRepoDir, (args) => git(root, ...args));
- git(root, 'init', '--initial-branch=main', source);
- configureTestGitRepository(source, (args) => git(root, ...args));
- git(source, 'config', 'user.name', 'Contributor');
- git(source, 'config', 'user.email', '[email protected]');
- writeFileSync(path.join(source, 'fixture.txt'), 'base\n');
- git(source, 'add', 'fixture.txt');
- git(source, 'commit', '-m', 'Base');
- const baseHead = git(source, 'rev-parse', 'HEAD');
- git(source, 'remote', 'add', 'origin', sourceRepoDir);
- git(source, 'push', 'origin', 'main');
- git(source, 'checkout', '-b', 'contribution');
- writeFileSync(path.join(source, 'fixture.txt'), sourceContent);
- git(source, 'commit', '-am', 'Recorded head');
- const approvedHead = git(source, 'rev-parse', 'HEAD');
- git(source, 'push', 'origin', 'HEAD:refs/pull/310/head');
- const rewriteKey = `url.${sourceRepoDir}.insteadOf`;
- git(
- internal,
- 'config',
- '--add',
- rewriteKey,
- 'https://x-access-token:[email protected]/inkeep/open-knowledge.git',
- );
- if (mapForkToSource) {
- git(
- internal,
- 'config',
- '--add',
- rewriteKey,
- 'https://x-access-token:[email protected]/octocat/open-knowledge.git',
- );
- }
- return {
- root,
- internal,
- remote,
- branch,
- oldHead,
- source,
- sourceRepoDir,
- baseHead,
- approvedHead,
- publishedHead: () => git(remote, 'rev-parse', `refs/heads/${branch}`),
- cleanup: () => rmSync(root, { recursive: true, force: true }),
- };
-}
-
-function setupSyncSourceRepo() {
- const fixture = setupSyncRepo({ sourceContent: 'approved' });
- writeFileSync(path.join(fixture.source, 'fixture.txt'), 'later');
- git(fixture.source, 'commit', '-am', 'Later head');
- git(fixture.source, 'push', 'origin', 'HEAD:refs/pull/310/head');
- return fixture;
-}
-
-function setupForkOnlySyncRepo() {
- const fixture = setupSyncRepo({ mapForkToSource: false });
- const fork = path.join(fixture.root, 'fork');
- const forkRepoDir = path.join(fixture.root, 'fork.git');
- git(fixture.root, 'init', '--bare', '--initial-branch=main', forkRepoDir);
- configureTestGitRepository(forkRepoDir, (args) => git(fixture.root, ...args));
- git(fixture.root, 'clone', fixture.sourceRepoDir, fork);
- configureTestGitRepository(fork, (args) => git(fixture.root, ...args));
- git(fork, 'config', 'user.name', 'Fork Contributor');
- git(fork, 'config', 'user.email', '[email protected]');
- writeFileSync(path.join(fork, 'fixture.txt'), 'fork-only\n');
- git(fork, 'commit', '-am', 'Fork-only head');
- const forkHead = git(fork, 'rev-parse', 'HEAD');
- git(fork, 'remote', 'add', 'fork', forkRepoDir);
- git(fork, 'push', 'fork', 'HEAD:main');
- git(
- fixture.internal,
- 'config',
- '--add',
- `url.${forkRepoDir}.insteadOf`,
- 'https://x-access-token:[email protected]/octocat/open-knowledge.git',
- );
- return { ...fixture, forkHead };
-}
-
-test.each([
- ['patch', () => setupBridgeRepo({ baseContent: 'base\n', oursContent: 'ours\n', theirsContent: 'theirs\n' }), (fixture) => fixture.repoDir],
- ['sync internal', () => setupSyncRepo(), (fixture) => fixture.internal],
- ['sync public', () => setupSyncRepo(), (fixture) => fixture.source],
- ['fork', () => setupForkOnlySyncRepo(), (fixture) => path.join(fixture.root, 'fork')],
-])('bridge fixture Git operations do not launch automatic maintenance: %s', (_name, create, repository) => {
- const fixture = create();
- try {
- expect(() => expectNoAutomaticGitMaintenance(repository(fixture))).not.toThrow();
- } finally {
- fixture.cleanup();
- }
-});
-
-async function captureBridgeLogs(action) {
- const logs = [];
- const originalLog = console.log;
- const originalWarn = console.warn;
- console.log = (...parts) => logs.push(parts.join(' '));
- console.warn = (...parts) => logs.push(parts.join(' '));
- try {
- return { result: await action(), logs };
- } finally {
- console.log = originalLog;
- console.warn = originalWarn;
- }
-}
-
-describe('syncPublicPr legacy metadata import', () => {
- test('an approved metadata event rebuilds content and records the current public head', async () => {
- const fixture = setupSyncRepo();
- try {
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'edited',
- markerHeadFields: 'legacy',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- });
- const publishedHead = fixture.publishedHead();
- expect(publishedHead).not.toBe(fixture.oldHead);
- expect(
- git(fixture.remote, 'show', `${fixture.branch}:public/open-knowledge/fixture.txt`),
- ).toBe('updated');
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${fixture.approvedHead}`);
- expect(recorded.internalBodies.at(-1)).toContain(`internal_head_sha=${publishedHead}`);
- expect(recorded.statuses).toContainEqual(
- expect.objectContaining({
- sha: publishedHead,
- context: 'cla/verified',
- state: 'success',
- }),
- );
- } finally {
- fixture.cleanup();
- }
- });
-
- test.each([
- ['partial marker', { markerHeadFields: 'partial' }],
- ['internal-only marker', { markerHeadFields: 'internal-only' }],
- ['modern mismatch', { importedPublicHead: 'previous-public-head' }],
- ['other repository', { markerHeadFields: 'legacy', importedRepo: 'another/repository' }],
- ['other PR', { markerHeadFields: 'legacy', importedPrNumber: 311 }],
- ['other branch', { markerHeadFields: 'legacy', internalHeadRef: 'fix/ordinary' }],
- ])('leaves %s without a new receipt or status', async (_name, overrides) => {
- const fixture = setupSyncRepo();
- try {
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'edited',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- ...overrides,
- });
- expect(fixture.publishedHead()).toBe(fixture.oldHead);
- expect(recorded.internalBodies).toEqual([]);
- expect(recorded.statuses).toEqual([]);
- } finally {
- fixture.cleanup();
- }
- });
-
- test('an empty pinned diff leaves a legacy head without a receipt or status and explains why', async () => {
- const fixture = setupSyncRepo();
- try {
- git(fixture.source, 'checkout', 'main');
- git(fixture.source, 'merge', '--ff-only', 'contribution');
- git(fixture.source, 'push', 'origin', 'main');
- git(fixture.source, 'checkout', 'contribution');
- git(fixture.source, 'commit', '--allow-empty', '-m', 'Empty change');
- const emptyHead = git(fixture.source, 'rev-parse', 'HEAD');
- git(fixture.source, 'push', 'origin', 'HEAD:refs/pull/310/head');
- const { result, logs } = await captureBridgeLogs(() =>
- runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'edited',
- markerHeadFields: 'legacy',
- publicHead: emptyHead,
- publicBase: fixture.approvedHead,
- readHead: fixture.publishedHead,
- }),
- );
- expect(fixture.publishedHead()).toBe(fixture.oldHead);
- expect(result.internalBodies).toEqual([]);
- expect(result.statuses).toEqual([]);
- expect(
- logs.some(
- (line) =>
- line.includes('PR #310') &&
- line.includes(emptyHead) &&
- line.includes('no new import recorded'),
- ),
- ).toBe(true);
- expect(logs.join('\n')).not.toContain(fixture.oldHead);
- } finally {
- fixture.cleanup();
- }
- });
-
- test('an already present change leaves a legacy head without a receipt or status and explains why', async () => {
- const fixture = setupSyncRepo();
- try {
- writeFileSync(path.join(fixture.internal, 'public/open-knowledge/fixture.txt'), 'updated\n');
- git(fixture.internal, 'commit', '-am', 'Already present');
- git(fixture.internal, 'push', 'origin', 'main');
- const { result, logs } = await captureBridgeLogs(() =>
- runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'edited',
- markerHeadFields: 'legacy',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- }),
- );
- expect(fixture.publishedHead()).toBe(fixture.oldHead);
- expect(result.internalBodies).toEqual([]);
- expect(result.statuses).toEqual([]);
- expect(
- logs.some(
- (line) =>
- line.includes('PR #310') &&
- line.includes(fixture.approvedHead) &&
- line.includes('no new receipt recorded'),
- ),
- ).toBe(true);
- expect(logs.join('\n')).not.toContain(fixture.oldHead);
- } finally {
- fixture.cleanup();
- }
- });
-});
-
-describe('syncPublicPr published-head status', () => {
- test('imports a recorded head reachable only from its fork', async () => {
- const fixture = setupForkOnlySyncRepo();
- try {
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: fixture.forkHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- });
- expect(
- git(fixture.remote, 'show', `${fixture.branch}:public/open-knowledge/fixture.txt`),
- ).toBe('fork-only');
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${fixture.forkHead}`);
- expect(recorded.statuses).toContainEqual(
- expect.objectContaining({
- sha: fixture.publishedHead(),
- context: 'cla/verified',
- state: 'success',
- }),
- );
- } finally {
- fixture.cleanup();
- }
- });
-
- test('publishes the recorded public head when its ref advances', async () => {
- const fixture = setupSyncSourceRepo();
- try {
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- });
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${fixture.approvedHead}`);
- expect(
- git(fixture.remote, 'show', `${fixture.branch}:public/open-knowledge/fixture.txt`),
- ).toBe('approved');
- } finally {
- fixture.cleanup();
- }
- });
-
- test('fetches the recorded head commit after the public ref moves to another history', async () => {
- const fixture = setupSyncRepo({ sourceContent: 'approved' });
- try {
- git(fixture.source, 'push', 'origin', `${fixture.approvedHead}:refs/heads/saved-head`);
- git(fixture.source, 'reset', '--hard', fixture.baseHead);
- writeFileSync(path.join(fixture.source, 'fixture.txt'), 'later');
- git(fixture.source, 'commit', '-am', 'Later head');
- git(fixture.source, 'push', 'origin', '+HEAD:refs/pull/310/head');
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- });
- expect(
- git(fixture.remote, 'show', `${fixture.branch}:public/open-knowledge/fixture.txt`),
- ).toBe('approved');
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${fixture.approvedHead}`);
- } finally {
- fixture.cleanup();
- }
- });
-
- test('publishes the recorded diff when the base ref advances', async () => {
- const fixture = setupSyncRepo();
- try {
- git(fixture.source, 'checkout', 'main');
- git(fixture.source, 'merge', '--ff-only', 'contribution');
- git(fixture.source, 'push', 'origin', 'main');
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- });
- expect(
- git(fixture.remote, 'show', `${fixture.branch}:public/open-knowledge/fixture.txt`),
- ).toBe('updated');
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${fixture.approvedHead}`);
- } finally {
- fixture.cleanup();
- }
- });
-
- test('stops before publication when the recorded head commit is unavailable', async () => {
- const fixture = setupSyncRepo();
- try {
- await expect(
- runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: 'f'.repeat(40),
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- }),
- ).rejects.toThrow();
- expect(fixture.publishedHead()).toBe(fixture.oldHead);
- } finally {
- fixture.cleanup();
- }
- });
-
- test('publishes a large diff with complete text bytes', async () => {
- const fixture = setupSyncRepo();
- const largeContent = `${'x'.repeat(1024 * 1024 + 1)}\n`;
- try {
- writeFileSync(path.join(fixture.source, 'fixture.txt'), largeContent);
- git(fixture.source, 'commit', '-am', 'Large text change');
- const largeHead = git(fixture.source, 'rev-parse', 'HEAD');
- git(fixture.source, 'push', 'origin', 'HEAD:refs/pull/310/head');
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: largeHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- });
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${largeHead}`);
- expect(
- readFileSync(path.join(fixture.internal, 'public/open-knowledge/fixture.txt'), 'utf8'),
- ).toBe(largeContent);
- } finally {
- fixture.cleanup();
- }
- });
-
- test('publishes binary file bytes from the recorded commit', async () => {
- const fixture = setupSyncRepo();
- const binaryContent = Buffer.from([0, 1, 2, 127, 128, 255]);
- try {
- writeFileSync(path.join(fixture.source, 'asset.bin'), binaryContent);
- git(fixture.source, 'add', 'asset.bin');
- git(fixture.source, 'commit', '-m', 'Add binary file');
- const binaryHead = git(fixture.source, 'rev-parse', 'HEAD');
- git(fixture.source, 'push', 'origin', 'HEAD:refs/pull/310/head');
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: binaryHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- });
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${binaryHead}`);
- expect(readFileSync(path.join(fixture.internal, 'public/open-knowledge/asset.bin'))).toEqual(
- binaryContent,
- );
- } finally {
- fixture.cleanup();
- }
- });
-
- test('does not record an imported head when the public head changed during sync', async () => {
- const fixture = setupSyncRepo();
- try {
- const result = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- readHead: fixture.publishedHead,
- publicHeadOnReread: 'new-public-head',
- });
- expect(result.internalBodies).toEqual([]);
- expect(result.statuses).toEqual([
- expect.objectContaining({
- sha: fixture.publishedHead(),
- context: 'cla/verified',
- state: 'failure',
- }),
- ]);
- } finally {
- fixture.cleanup();
- }
- });
-
- test.each([
- ['success', 'stale metadata', 'existing'],
- ['failure', 'stale metadata', 'existing'],
- ['success', 'stale reads', 'existing'],
- ['failure', 'stale reads', 'existing'],
- ['success', 'current metadata', 'existing'],
- ['failure', 'current metadata', 'existing'],
- ['success', 'stale metadata', 'new'],
- ['failure', 'stale metadata', 'new'],
- ])('posts %s on the published head with %s for %s PRs', async (claStatus, freshness, entry) => {
- const fixture = setupSyncRepo();
- try {
- const recorded = await runBridgeSync({
- internalRepoDir: fixture.internal,
- action: 'synchronize',
- publicHead: fixture.approvedHead,
- publicBase: fixture.baseHead,
- claStatus,
- existingPr: entry === 'existing',
- readHead: freshness === 'stale reads' ? () => fixture.oldHead : fixture.publishedHead,
- patchHead: freshness === 'current metadata' ? fixture.publishedHead : () => fixture.oldHead,
- });
- const head = fixture.publishedHead();
- expect(recorded.internalBodies.at(-1)).toContain(`public_head_sha=${fixture.approvedHead}`);
- expect(recorded.internalBodies.at(-1)).toContain(`internal_head_sha=${head}`);
- expect(head).not.toBe(fixture.oldHead);
- expect(
- git(fixture.remote, 'show', `${fixture.branch}:public/open-knowledge/fixture.txt`),
- ).toBe('updated');
- expect(recorded.statuses).toContainEqual(
- expect.objectContaining({
- sha: head,
- context: 'cla/verified',
- state: claStatus,
- }),
- );
- } finally {
- fixture.cleanup();
- }
- });
-});
diff --git a/.github/scripts/cache-mode-shape.test.mjs b/.github/scripts/cache-mode-shape.test.mjs
index 3806f8216..56de09d68 100644
--- a/.github/scripts/cache-mode-shape.test.mjs
+++ b/.github/scripts/cache-mode-shape.test.mjs
@@ -68,12 +68,7 @@ describe('credentialed jobs in public/open-knowledge/.github/workflows declare t
'desktop-release.yml#finalize': 'none',
'desktop-release.yml#release-consumers': 'none',
'desktop-release.yml#alert': 'none',
- 'linear-pr-relay.yml#relay': 'none',
'linear-release.yml#stamp': 'none',
- 'monorepo-pr-bridge.yml#acknowledge': 'none',
- 'monorepo-pr-bridge.yml#sync': 'none',
- 'monorepo-pr-bridge.yml#close': 'none',
- 'monorepo-pr-bridge.yml#refresh-cla': 'none',
'point-release.yml#point-release': 'none',
'promote-stable.yml#promote': 'none',
'publish-linux-repo.yml#publish': 'none',
@@ -85,7 +80,6 @@ describe('credentialed jobs in public/open-knowledge/.github/workflows declare t
'select-beta-to-promote.yml#page-smoke-incident': 'write-only',
'share-contract-deployment-gate.yml#reader-contract': 'none',
'share-contract-monitor.yml#probe': 'none',
- 'stale.yml#stale': 'none',
'write-back.yml#notify': 'none',
});
});
diff --git a/.github/scripts/cla-gate.mjs b/.github/scripts/cla-gate.mjs
deleted file mode 100644
index a5fc85f95..000000000
--- a/.github/scripts/cla-gate.mjs
+++ /dev/null
@@ -1,69 +0,0 @@
-export const BOT_ALLOWLIST = [
- "inkeep-oss-sync[bot]",
- "inkeep-internal-ci[bot]",
- "copilot-swe-agent[bot]",
-];
-
-export function isBot(login, bots = BOT_ALLOWLIST) {
- if (!login) return false;
- const lower = login.toLowerCase();
- return bots.some((entry) => entry.toLowerCase() === lower);
-}
-
-export function evaluateClaGate({ claStatus, exempt = false }) {
- if (exempt) {
- return { gated: false, reason: "exempt" };
- }
- if (claStatus === "success") {
- return { gated: false, reason: "cla-signed" };
- }
- if (claStatus === "failure") {
- return { gated: true, reason: "cla-unsigned" };
- }
- if (claStatus === "error") {
- return { gated: true, reason: "cla-errored" };
- }
- return { gated: true, reason: "cla-pending" };
-}
-
-function describeReason(reason) {
- switch (reason) {
- case "cla-signed":
- return "CLA signed.";
- case "exempt":
- return "Author is an Inkeep org member or an allowlisted bot; no CLA required.";
- case "cla-unsigned":
- return "CLA not signed. Sign the CLA on the public pull request.";
- case "cla-errored":
- return "CLA check errored on the public pull request; holding until it can be confirmed.";
- case "cla-read-error":
- return "Could not verify CLA status; holding the PR until it can be confirmed.";
- default:
- return "Awaiting CLA signature on the public pull request.";
- }
-}
-
-export async function applyClaGate({ gh, publicPr, internalPr, forceDraft = false }) {
- const author = publicPr?.user?.login;
- let gate;
- try {
- let exempt = isBot(author);
- if (!exempt && author) {
- exempt = await gh.isOrgMember(author);
- }
- const claStatus = exempt ? null : await gh.readClaStatus(publicPr);
- gate = evaluateClaGate({ claStatus, exempt });
- } catch (error) {
- console.warn(`Bridge: CLA gate read failed for ${author}: ${error.message}`);
- gate = { gated: true, reason: "cla-read-error" };
- }
-
- const shouldBeDraft = Boolean(publicPr?.draft) || gate.gated || forceDraft;
- await gh.setDraft(internalPr, shouldBeDraft);
- await gh.setVerifiedStatus(
- internalPr,
- gate.gated ? "failure" : "success",
- describeReason(gate.reason),
- );
- return gate;
-}
diff --git a/.github/scripts/cla-gate.test.mjs b/.github/scripts/cla-gate.test.mjs
deleted file mode 100644
index 16be1fa69..000000000
--- a/.github/scripts/cla-gate.test.mjs
+++ /dev/null
@@ -1,200 +0,0 @@
-import { describe, expect, test } from 'vitest';
-import { applyClaGate, BOT_ALLOWLIST, evaluateClaGate, isBot } from './cla-gate.mjs';
-
-describe('evaluateClaGate', () => {
- test('an exempt author is released regardless of status', () => {
- for (const claStatus of ['failure', 'pending', 'error', null, undefined]) {
- expect(evaluateClaGate({ claStatus, exempt: true })).toEqual({
- gated: false,
- reason: 'exempt',
- });
- }
- });
-
- test('a signed non-exempt author is released', () => {
- expect(evaluateClaGate({ claStatus: 'success' })).toEqual({
- gated: false,
- reason: 'cla-signed',
- });
- });
-
- test('an unsigned (failure) non-exempt author is gated', () => {
- expect(evaluateClaGate({ claStatus: 'failure' })).toEqual({
- gated: true,
- reason: 'cla-unsigned',
- });
- });
-
- test('absent or pending status fails closed', () => {
- for (const claStatus of [null, undefined, 'pending']) {
- expect(evaluateClaGate({ claStatus })).toEqual({ gated: true, reason: 'cla-pending' });
- }
- });
-
- test('errored status fails closed with a distinct infra-error reason', () => {
- expect(evaluateClaGate({ claStatus: 'error' })).toEqual({ gated: true, reason: 'cla-errored' });
- });
-
- test('failure (unsigned) and error (infra) are distinct reasons', () => {
- expect(evaluateClaGate({ claStatus: 'failure' }).reason).toBe('cla-unsigned');
- expect(evaluateClaGate({ claStatus: 'error' }).reason).toBe('cla-errored');
- });
-});
-
-describe('isBot', () => {
- test('matches listed bots case-insensitively', () => {
- expect(isBot('inkeep-oss-sync[bot]')).toBe(true);
- expect(isBot('Copilot-SWE-Agent[bot]')).toBe(true);
- });
-
- test('non-bots and empty logins are not bots', () => {
- expect(isBot('outsider')).toBe(false);
- expect(isBot(null)).toBe(false);
- expect(isBot(undefined)).toBe(false);
- });
-
- test('the published BOT_ALLOWLIST holds only bot actors, no humans', () => {
- expect(BOT_ALLOWLIST.length).toBeGreaterThan(0);
- expect(BOT_ALLOWLIST.every((login) => login.endsWith('[bot]'))).toBe(true);
- });
-});
-
-describe('applyClaGate', () => {
- const fakeGh = (
- claStatus,
- { isMember = false, throwOnRead = false, throwOnMembership = false } = {},
- ) => {
- const recorded = {
- draft: undefined,
- status: undefined,
- description: undefined,
- reads: 0,
- memberChecks: 0,
- };
- return {
- recorded,
- isOrgMember: async () => {
- recorded.memberChecks += 1;
- if (throwOnMembership) throw new Error('membership api unavailable');
- return isMember;
- },
- readClaStatus: async () => {
- recorded.reads += 1;
- if (throwOnRead) throw new Error('status api unavailable');
- return claStatus;
- },
- setDraft: async (_pr, shouldBeDraft) => {
- recorded.draft = shouldBeDraft;
- },
- setVerifiedStatus: async (_pr, state, description) => {
- recorded.status = state;
- recorded.description = description;
- },
- };
- };
- const publicPr = (login, draft = false) => ({
- user: { login },
- draft,
- head: { sha: 'public-sha' },
- });
- const internalPr = { head: { sha: 'internal-sha' } };
-
- test('unsigned non-member external PR is held draft with a failing cla/verified status', async () => {
- const gh = fakeGh('failure');
- const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
- expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe('failure');
- expect(gate).toMatchObject({ gated: true, reason: 'cla-unsigned' });
- });
-
- test('signed non-member external PR is set ready with a success status', async () => {
- const gh = fakeGh('success');
- const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
- expect(gh.recorded.draft).toBe(false);
- expect(gh.recorded.status).toBe('success');
- expect(gate.gated).toBe(false);
- });
-
- test('an org member is released without reading the CLA status', async () => {
- const gh = fakeGh(null, { isMember: true });
- const gate = await applyClaGate({ gh, publicPr: publicPr('employee'), internalPr });
- expect(gate).toMatchObject({ gated: false, reason: 'exempt' });
- expect(gh.recorded.reads).toBe(0);
- expect(gh.recorded.draft).toBe(false);
- expect(gh.recorded.status).toBe('success');
- });
-
- test('a listed bot is released without any membership or status read', async () => {
- const gh = fakeGh(null);
- const gate = await applyClaGate({ gh, publicPr: publicPr('inkeep-oss-sync[bot]'), internalPr });
- expect(gate).toMatchObject({ gated: false, reason: 'exempt' });
- expect(gh.recorded.memberChecks).toBe(0);
- expect(gh.recorded.reads).toBe(0);
- });
-
- test('a membership read failure fails closed', async () => {
- const gh = fakeGh('success', { throwOnMembership: true });
- const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
- expect(gate.reason).toBe('cla-read-error');
- expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe('failure');
- });
-
- test('a status read failure fails closed', async () => {
- const gh = fakeGh(null, { throwOnRead: true });
- const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
- expect(gate.reason).toBe('cla-read-error');
- expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe('failure');
- });
-
- test("an errored CLA check is held but not told to 'sign the CLA'", async () => {
- const gh = fakeGh('error');
- const gate = await applyClaGate({ gh, publicPr: publicPr('outsider'), internalPr });
- expect(gate.reason).toBe('cla-errored');
- expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.description).not.toMatch(/sign the cla/i);
- });
-
- test('re-sync after a new unsigned head re-blocks a released PR', async () => {
- const signed = fakeGh('success');
- await applyClaGate({ gh: signed, publicPr: publicPr('outsider'), internalPr });
- expect(signed.recorded.draft).toBe(false);
-
- const reUnsigned = fakeGh('failure');
- await applyClaGate({ gh: reUnsigned, publicPr: publicPr('outsider'), internalPr });
- expect(reUnsigned.recorded.draft).toBe(true);
- expect(reUnsigned.recorded.status).toBe('failure');
- });
-
- test('a signed PR that is itself a draft upstream stays draft, with success status', async () => {
- const gh = fakeGh('success');
- await applyClaGate({ gh, publicPr: publicPr('outsider', true), internalPr });
- expect(gh.recorded.draft).toBe(true);
- expect(gh.recorded.status).toBe('success');
- });
-
- test('forceDraft holds a signed, ungated PR draft (conflict markers need manual resolution)', async () => {
- const gh = fakeGh('success');
- const gate = await applyClaGate({
- gh,
- publicPr: publicPr('outsider'),
- internalPr,
- forceDraft: true,
- });
- expect(gh.recorded.draft).toBe(true);
- expect(gate.gated).toBe(false);
- expect(gh.recorded.status).toBe('success');
- });
-
- test('a missing author is gated (no bot or member match, fails closed on status)', async () => {
- const gh = fakeGh(null);
- const gate = await applyClaGate({
- gh,
- publicPr: { draft: false, head: { sha: 's' } },
- internalPr,
- });
- expect(gate.gated).toBe(true);
- expect(gh.recorded.memberChecks).toBe(0);
- });
-});
diff --git a/.github/scripts/monorepo-pr-bridge-shape.test.mjs b/.github/scripts/monorepo-pr-bridge-shape.test.mjs
deleted file mode 100644
index 75abbb7e9..000000000
--- a/.github/scripts/monorepo-pr-bridge-shape.test.mjs
+++ /dev/null
@@ -1,61 +0,0 @@
-import { readFileSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
-
-const WORKFLOW = join(dirname(fileURLToPath(import.meta.url)), '..', 'workflows', 'monorepo-pr-bridge.yml');
-const bridge = readFileSync(WORKFLOW, 'utf8');
-
-function jobCondition(name) {
- const body = bridge.split(new RegExp(`^ ${name}:$`, 'm'))[1];
- expect(body, `job ${name} exists`).toBeDefined();
- const ifBlock = /^ {4}if: >-\n((?: {6}.*\n)+)/m.exec(body);
- expect(ifBlock, `job ${name} declares a folded if:`).not.toBeNull();
- return ifBlock[1]
- .split('\n')
- .map((l) => l.trim())
- .filter((l) => l && !l.startsWith('#'))
- .join(' ');
-}
-
-const JOBS = ['acknowledge', 'sync', 'close'];
-
-describe('the bridge identifies Copybara PRs by provenance, not by a forgeable name', () => {
- test.each(JOBS)('%s keys on the head repository', (job) => {
- expect(jobCondition(job)).toMatch(/github\.event\.pull_request\.head\.repo\.full_name != github\.repository/);
- });
-
- test.each(JOBS)('%s never tests the branch name outside the provenance group', (job) => {
- const condition = jobCondition(job);
- const group = /\(github\.event\.pull_request\.head\.repo\.full_name != github\.repository \|\| github\.event\.pull_request\.head\.ref != 'copybara\/sync'\)/;
- expect(condition).toMatch(group);
- expect(condition.match(/head\.ref != 'copybara\/sync'/g)).toHaveLength(1);
- });
-
- test.each(JOBS)('%s parenthesises the provenance group, which is load-bearing', (job) => {
- const condition = jobCondition(job);
- const actionClause = /github\.event\.action [!=]= 'closed'|github\.event\.action == 'opened'/;
- expect(condition).toMatch(actionClause);
- const groupStart = condition.indexOf('(github.event.pull_request.head.repo.full_name');
- const actionIndex = condition.search(actionClause);
- expect(groupStart, 'the provenance group is parenthesised').toBeGreaterThan(-1);
- expect(actionIndex, 'the action clause precedes the group it is ANDed with').toBeLessThan(groupStart);
- });
-});
-
-describe('the bridge keeps the properties the approval gate depends on', () => {
- test('only the sync job sits behind the inkeep-oss-sync environment', () => {
- expect(bridge.match(/environment: inkeep-oss-sync/g)).toHaveLength(1);
- const sync = bridge.split(/^ sync:$/m)[1];
- expect(sync).toMatch(/environment: inkeep-oss-sync/);
- });
-
- test('no job checks out the contributor branch', () => {
- const directives = bridge
- .split('\n')
- .filter((l) => !/^\s*#/.test(l))
- .join('\n');
- expect(directives).not.toMatch(/ref:\s*\$\{\{\s*github\.event\.pull_request\.head/);
- expect(directives).not.toMatch(/ref:\s*\$\{\{\s*github\.event\.pull_request\.merge_commit_sha/);
- });
-});
diff --git a/.github/scripts/release-signing-environment-shape.test.mjs b/.github/scripts/release-signing-environment-shape.test.mjs
index 0aa989afb..6fd347411 100644
--- a/.github/scripts/release-signing-environment-shape.test.mjs
+++ b/.github/scripts/release-signing-environment-shape.test.mjs
@@ -33,13 +33,11 @@ const OTHER_SECRETS = [
'LINUX_REPO_R2_SECRET_ACCESS_KEY',
'OK_RELEASE_BRIDGE_APP_ID',
'OK_RELEASE_BRIDGE_APP_PRIVATE_KEY',
- 'OSS_SYNC_APP_ID',
- 'OSS_SYNC_APP_PRIVATE_KEY',
'SLACK_RELEASES_WEBHOOK_URL',
'SLACK_WEBHOOK_URL',
];
const SIGNING_ENVIRONMENT = 'release-signing';
-const OTHER_ENVIRONMENTS = ['inkeep-oss-sync'];
+const OTHER_ENVIRONMENTS = [];
const MAIN_ONLY = "${{ github.ref == 'refs/heads/main' && 'release-signing' || '' }}";
const EXPECTED = {
'desktop-build-win-linux.yml#build-windows': MAIN_ONLY,
@@ -164,6 +162,21 @@ describe('release-signing environment', () => {
'jobs reading',
],
['an unclassified secret', withJob(step('${{ secrets.NEW_SIGNING_KEY }}')), 'classify it'],
+ [
+ 'a retired import app ID',
+ withJob(step('${{ secrets.OSS_SYNC_APP_ID }}')),
+ 'reads secret OSS_SYNC_APP_ID',
+ ],
+ [
+ 'a retired import private key',
+ withJob(step('${{ secrets.OSS_SYNC_APP_PRIVATE_KEY }}')),
+ 'reads secret OSS_SYNC_APP_PRIVATE_KEY',
+ ],
+ [
+ 'a retired import environment',
+ withJob({ environment: 'inkeep-oss-sync', steps: [] }),
+ 'not in OTHER_ENVIRONMENTS',
+ ],
[
'a computed environment name',
withJob({ environment: '${{ vars.SIGNING_ENV }}', steps: [] }),
@@ -187,7 +200,6 @@ describe('release-signing environment', () => {
['GITHUB_TOKEN in another casing', withJob(step('${{ Secrets.github_token }}'))],
['a classified non-signing secret', withJob(step("${{ secrets['SLACK_WEBHOOK_URL'] }}"))],
['a property named secrets on another context', withJob(step('${{ inputs.secrets }}'))],
- ['an allowlisted environment', withJob({ environment: 'inkeep-oss-sync', steps: [] })],
])('a fabricated job using %s keeps the contract', (_form, entries) => {
expect(contractProblems(entries)).toEqual([]);
});
diff --git a/.github/workflows/linear-pr-relay.yml b/.github/workflows/linear-pr-relay.yml
deleted file mode 100644
index 6467691d2..000000000
--- a/.github/workflows/linear-pr-relay.yml
+++ /dev/null
@@ -1,91 +0,0 @@
-name: Linear PR Relay
-
-# Relay the NUMBER of every community pull request to agents-private, which files
-# or updates its Linear ticket.
-#
-# WHY THIS JOB HOLDS NO LINEAR SECRET AND CHECKS OUT NO CODE
-# This repo already stores LINEAR_API_KEY, but every workflow that reads it
-# (write-back, select-beta-to-promote, bug-lane, linear-release) fires only on
-# schedule / push / *_dispatch — triggers that require write access here.
-# Nothing fork-reachable has ever held that key, and this workflow deliberately
-# does not change that.
-#
-# Filing a Linear ticket from a PR means reading the PR's title and body, which
-# are contributor-controlled on a fork. Doing that in a job that also holds the
-# Linear key would put the workspace one shell-injection away from a public,
-# endlessly probeable workflow file. So this job passes a bare integer over the
-# boundary and nothing else. agents-private re-reads everything it needs from
-# the GitHub API itself and does the Linear work with its own key.
-#
-# There is no `actions/checkout` here on purpose: `gh` is preinstalled on the
-# runner, so the job never materializes a working tree at all. Nothing about a
-# contributor's branch is fetched, let alone executed.
-#
-# WHY THE PAYLOAD IS ONLY A NUMBER
-# `github.event.pull_request.number` comes from GitHub's own event payload, not
-# from anything a contributor typed, and it reaches the shell through `env:`
-# rather than through `${{ }}` interpolation into the run body. The receiver
-# validates the shape again before acting on it.
-
-on:
- pull_request_target:
- types: [opened, reopened, synchronize, edited, ready_for_review, converted_to_draft, closed]
-
-permissions:
- contents: read
-
-concurrency:
- # Safe to cancel: the receiver is a reconciler that reads live PR state, so a
- # superseded relay carries no information the next one lacks. Unlike the
- # contributor bridge, this job has no `environment:`, so a cancelled run leaves
- # no failed deployment record behind.
- group: linear-pr-relay-${{ github.event.pull_request.number }}
- cancel-in-progress: true
-
-jobs:
- relay:
- # FORK PRs ONLY. The tickets this produces carry `source:gh-pr`, meaning
- # "originated from an external GitHub pull request", so the predicate is
- # provenance rather than branch name.
- #
- # Pushing a branch to this repo requires write access, so every same-repo PR
- # is internal by construction: Copybara's own `copybara/sync`, a maintainer's
- # patch branch, or Dependabot. None is a community contribution. Excluding
- # same-repo wholesale subsumes the Copybara case rather than restating it,
- # and it is unforgeable — a contributor picks their branch name, not which
- # repository it lives in.
- if: github.event.pull_request.head.repo.full_name != github.repository
- name: Relay the pull request number to agents-private
- runs-on: ubuntu-26.04
- cache-mode: none
- timeout-minutes: 5
- steps:
- - name: Generate agents-private dispatch token
- id: app-token
- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
- with:
- app-id: ${{ secrets.OSS_SYNC_APP_ID }}
- private-key: ${{ secrets.OSS_SYNC_APP_PRIVATE_KEY }}
- owner: inkeep
- repositories: agents-private
- # Without this the token carries every permission the installation
- # holds, which for inkeep-oss-sync includes `workflows: write` on the
- # private monorepo. `POST /dispatches` needs only `contents: write`.
- # Nothing untrusted executes in this job today, so this is blast radius
- # rather than an active hole: it is what keeps a future maintenance
- # mistake here from escalating into private-monorepo write. Same
- # `permission-*` pattern as write-back.yml.
- permission-contents: write
-
- - name: Dispatch
- env:
- GH_TOKEN: ${{ steps.app-token.outputs.token }}
- PR_NUMBER: ${{ github.event.pull_request.number }}
- run: |
- set -euo pipefail
- # -F sends the value as a JSON number rather than a string, which is
- # what the receiver's integer check expects.
- gh api repos/inkeep/agents-private/dispatches \
- -f event_type=public-pr-linear-sync \
- -F "client_payload[pr]=${PR_NUMBER}"
- echo "::notice::relayed PR #${PR_NUMBER} to agents-private"
diff --git a/.github/workflows/monorepo-pr-bridge.yml b/.github/workflows/monorepo-pr-bridge.yml
deleted file mode 100644
index 3a7f08b07..000000000
--- a/.github/workflows/monorepo-pr-bridge.yml
+++ /dev/null
@@ -1,214 +0,0 @@
-name: Monorepo PR Bridge
-
-on:
- status:
- pull_request_target:
- types: [opened, reopened, synchronize, ready_for_review, converted_to_draft, edited, closed]
-
-permissions:
- contents: read
- pull-requests: write
- issues: write
-
-concurrency:
- group: monorepo-pr-bridge-${{ github.event_name == 'status' && format('status-{0}-{1}', github.event.context, github.event.sha) || github.event.pull_request.number }}
- cancel-in-progress: true
-
-jobs:
- acknowledge:
- # Public-facing acknowledgement should happen immediately on a new PR and
- # stay decoupled from the inkeep-oss-sync environment approval that imports
- # the PR into agents-private.
- #
- # The Copybara skip is keyed on the head REPOSITORY, not the branch name
- # alone: a fork chooses its own branch name, so a contributor who happened to
- # call theirs `copybara/sync` would silently receive no acknowledgement, never
- # be imported, and never be told why. Only this repo can own a branch here.
- if: >-
- github.event_name == 'pull_request_target'
- && github.event.action == 'opened'
- && (github.event.pull_request.head.repo.full_name != github.repository
- || github.event.pull_request.head.ref != 'copybara/sync')
- runs-on: ubuntu-26.04
- cache-mode: none
- timeout-minutes: 5
- steps:
- - name: Checkout public repo automation
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- fetch-depth: 1
-
- - name: Setup Node.js
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
- with:
- node-version-file: .node-version
-
- - name: Acknowledge public PR
- env:
- PUBLIC_PR_NUMBER: ${{ github.event.pull_request.number }}
- PUBLIC_REPO: ${{ github.repository }}
- PUBLIC_TOKEN: ${{ github.token }}
- run: node .github/scripts/bridge-public-pr-to-monorepo.mjs acknowledge
-
- sync:
- # Pause before minting the agents-private App token or writing any internal
- # branch/PR. The environment has required reviewers configured in the public
- # repo, so every public PR revision needs maintainer approval before crossing
- # into agents-private.
- if: >-
- github.event_name == 'pull_request_target'
- && github.event.action != 'closed'
- && (github.event.pull_request.head.repo.full_name != github.repository
- || github.event.pull_request.head.ref != 'copybara/sync')
- environment: inkeep-oss-sync
- runs-on: ubuntu-26.04
- cache-mode: none
- timeout-minutes: 15
- steps:
- - name: Checkout public repo automation
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- fetch-depth: 1
-
- - name: Setup Node.js
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
- with:
- node-version-file: .node-version
-
- - name: Generate inkeep-oss-sync App token
- id: app-token
- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
- with:
- app-id: ${{ secrets.OSS_SYNC_APP_ID }}
- private-key: ${{ secrets.OSS_SYNC_APP_PRIVATE_KEY }}
- owner: inkeep
- repositories: agents-private
-
- - name: Checkout agents-private
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- repository: inkeep/agents-private
- ref: main
- fetch-depth: 0
- token: ${{ steps.app-token.outputs.token }}
- path: agents-private
-
- - name: Sync public PR into agents-private
- env:
- INTERNAL_BASE_REF: main
- INTERNAL_BRANCH_PREFIX: public-pr/open-knowledge
- INTERNAL_REPO: inkeep/agents-private
- INTERNAL_REPO_DIR: ${{ github.workspace }}/agents-private
- INTERNAL_TOKEN: ${{ steps.app-token.outputs.token }}
- MONOREPO_PATH_PREFIX: public/open-knowledge
- PUBLIC_PR_ACTION: ${{ github.event.action }}
- PUBLIC_PR_NUMBER: ${{ github.event.pull_request.number }}
- PUBLIC_REPO: ${{ github.repository }}
- PUBLIC_TOKEN: ${{ github.token }}
- # Only the 4 root-level overlay-mapped files need explicit rewrites.
- # Workflow + script files now live in-tree at
- # public/open-knowledge/.github/, so MONOREPO_PATH_PREFIX maps them
- # correctly without an entry here. Stale entries pointing at the
- # deleted overlay .github/ paths would route bridged PR diffs to
- # non-existent locations.
- PUBLIC_PR_PATH_REWRITES: >-
- {
- "README.md": "copybara/public-open-knowledge-overlay/README.md",
- "CONTRIBUTING.md": "copybara/public-open-knowledge-overlay/CONTRIBUTING.md",
- "AGENTS.md": "copybara/public-open-knowledge-overlay/AGENTS.md",
- ".gitignore": "copybara/public-open-knowledge-overlay/.gitignore"
- }
- # Drop pre-cutover internal-only paths from the bridged diff. Old
- # `inkeep/open-knowledge-legacy` branches predate the agents-private cutover
- # and contain reports/specs/etc. that the public mirror no longer
- # exports; bridging those paths back through this workflow would
- # re-introduce content that is already authoritative on
- # agents-private under different intent.
- BRIDGE_EXCLUDED_PATHS: >-
- [".codex/", ".claude/", ".cursor/", ".openhands/", ".ok/",
- "specs/", "reports/", "projects/", "stories/", "strategy/",
- "private/", "ARCHITECTURE.md", "PRECEDENTS.md"]
- run: node .github/scripts/bridge-public-pr-to-monorepo.mjs sync
-
- close:
- # Skip PRs that originated from agents-private via Copybara, identified by
- # head repository rather than branch name for the same reason as above.
- if: >-
- github.event_name == 'pull_request_target'
- && github.event.action == 'closed'
- && (github.event.pull_request.head.repo.full_name != github.repository
- || github.event.pull_request.head.ref != 'copybara/sync')
- runs-on: ubuntu-26.04
- cache-mode: none
- timeout-minutes: 15
- steps:
- - name: Checkout public repo automation
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- fetch-depth: 1
-
- - name: Setup Node.js
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
- with:
- node-version-file: .node-version
-
- - name: Generate inkeep-oss-sync App token
- id: app-token
- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
- with:
- app-id: ${{ secrets.OSS_SYNC_APP_ID }}
- private-key: ${{ secrets.OSS_SYNC_APP_PRIVATE_KEY }}
- owner: inkeep
- repositories: agents-private
-
- - name: Handle public PR closure
- env:
- INTERNAL_BRANCH_PREFIX: public-pr/open-knowledge
- INTERNAL_REPO: inkeep/agents-private
- INTERNAL_TOKEN: ${{ steps.app-token.outputs.token }}
- PUBLIC_PR_NUMBER: ${{ github.event.pull_request.number }}
- PUBLIC_REPO: ${{ github.repository }}
- PUBLIC_TOKEN: ${{ github.token }}
- run: node .github/scripts/bridge-public-pr-to-monorepo.mjs close
-
- refresh-cla:
- if: github.event_name == 'status' && github.event.context == 'license/cla'
- permissions:
- contents: read
- pull-requests: read
- statuses: read
- runs-on: ubuntu-26.04
- cache-mode: none
- timeout-minutes: 15
- steps:
- - name: Checkout public repo automation
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- ref: ${{ github.event.repository.default_branch }}
- persist-credentials: false
- - name: Setup Node.js
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
- with:
- node-version-file: .node-version
- - name: Generate inkeep-oss-sync App token
- id: app-token
- uses: actions/create-github-app-token@1b10c78c7865c340bc4f6099eb2f838309f1e8c3 # v3.1.1
- with:
- app-id: ${{ secrets.OSS_SYNC_APP_ID }}
- private-key: ${{ secrets.OSS_SYNC_APP_PRIVATE_KEY }}
- owner: inkeep
- repositories: agents-private
- permission-contents: read
- permission-members: read
- permission-pull-requests: write
- permission-statuses: write
- - name: Refresh CLA status on the imported head
- env:
- INTERNAL_BRANCH_PREFIX: public-pr/open-knowledge
- INTERNAL_REPO: inkeep/agents-private
- INTERNAL_TOKEN: ${{ steps.app-token.outputs.token }}
- PUBLIC_REPO: ${{ github.repository }}
- PUBLIC_TOKEN: ${{ github.token }}
- PUBLIC_STATUS_CONTEXT: ${{ github.event.context }}
- PUBLIC_STATUS_SHA: ${{ github.event.sha }}
- run: node .github/scripts/bridge-public-pr-to-monorepo.mjs refresh-cla
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
deleted file mode 100644
index 060979da0..000000000
--- a/.github/workflows/stale.yml
+++ /dev/null
@@ -1,55 +0,0 @@
-name: Mark stale pull requests
-
-on:
- schedule:
- # Run daily at midnight UTC
- - cron: "0 0 * * *"
- workflow_dispatch:
- # Allow manual triggering for testing
-
-permissions:
- pull-requests: write
- issues: write
- contents: write
-
-jobs:
- stale:
- runs-on: ubuntu-26.04
- cache-mode: none
-
- steps:
- - name: Mark stale pull requests
- uses: actions/stale@b5d41d4e1d5dceea10e7104786b73624c18a190f # v10.2.0
- with:
- stale-pr-message: |
- This pull request has been automatically marked as stale because it has not had recent activity.
- It will be closed in 7 days if no further activity occurs.
-
- If this PR is still relevant:
- - Rebase it on the latest main branch
- - Add a comment explaining its current status
- - Request a review if it's ready
-
- Thank you for your contributions!
-
- close-pr-message: |
- This pull request has been automatically closed due to inactivity.
-
- If you'd like to continue working on this, please:
- 1. Create a new branch from the latest main
- 2. Cherry-pick your commits or rebase your changes
- 3. Open a new pull request
-
- Thank you for your understanding!
-
- days-before-pr-stale: 7
- days-before-pr-close: 7
- stale-pr-label: "stale"
- exempt-pr-labels: "pinned,security,work-in-progress"
- exempt-draft-pr: true
- exempt-all-pr-assignees: true
- delete-branch: true
- sort-by: "updated"
-
- days-before-issue-stale: -1
- days-before-issue-close: -1
diff --git a/AGENTS.md b/AGENTS.md
index 7902b7d28..91e2a27de 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -79,7 +79,7 @@ Shell scripts are declared in scope by `no-comments.config.jsonc`, but the sweep
## Public Mirror Rules
- This repo is generated from an allowlist. Do not rely on hidden source-only folders being present.
-- Maintainers review public PRs that are small fixes or link an accepted issue; others may be closed without review (see the Pull requests section of `CONTRIBUTING.md`). A detailed issue is the preferred contribution. Accepted changes sync back here automatically. A PR may close rather than show as merged; that is expected for this mirror.
+- Do not open pull requests here. Report bugs, feature requests and translation corrections as detailed issues using `CONTRIBUTING.md`. Maintainers publish changes through the mirror; its sync pull requests are automation.
- Top-level public docs such as `README.md`, `CONTRIBUTING.md`, and `AGENTS.md` are overlay files. Keep them public-safe and standalone.
- Do not add secrets, private customer context, internal-only specs, local paths, or generated debug artifacts.
- Keep dependency updates paired with `pnpm-lock.yaml`. Run `pnpm run notices` when third-party notices may change.
diff --git a/CLA.md b/CLA.md
index e95acadb7..99185dff0 100644
--- a/CLA.md
+++ b/CLA.md
@@ -1,3 +1,5 @@
+> Historical agreement for earlier code contributions. OpenKnowledge no longer accepts pull requests; please [file a detailed issue](./CONTRIBUTING.md#write-an-issue-we-can-build-from). This agreement is retained as a record, and no signature is requested for issues.
+
> Based on the Apache Individual Contributor License Agreement (ICLA) V2.2, with Inkeep, Inc. as the grantee. It is a copyright and patent **license**, not an assignment, so you keep full ownership of your contributions. The license-grant and representation clauses (sections 1 to 8) are the verbatim Apache text; the Foundation's nonprofit-specific covenant and the paper contact-form fields are omitted.
# Inkeep Individual Contributor License Agreement
@@ -25,7 +27,3 @@ You accept and agree to the following terms and conditions for Your present and
**7.** Should You wish to submit work that is not Your original creation, You may submit it to Inkeep separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which You are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [named here]".
**8.** You agree to notify Inkeep of any facts or circumstances of which You become aware that would make these representations inaccurate in any respect.
-
----
-
-**How to sign.** Open a pull request on the public repository. The CLA-assistant bot will comment with a link to sign this Agreement — a one-time, roughly 30-second authenticated click recorded against your GitHub identity that covers all of your future contributions. Inkeep employees and project bots are allowlisted and are not prompted.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index b4b6eb564..335020c5e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,11 +1,10 @@
# Contributing to OpenKnowledge
-Thanks for helping. The most useful thing you can send us is a detailed issue, not a pull request.
+Thanks for helping. We do not accept pull requests. Please [file a detailed issue](https://github.com/inkeep/open-knowledge/issues/new/choose) so we can understand the problem and consider it for our work.
- **Found a bug or have an idea?** [Open an issue](https://github.com/inkeep/open-knowledge/issues/new/choose). This is the main way to contribute; see [Write an issue we can build from](#write-an-issue-we-can-build-from).
- **Question or setup help?** Ask in [Discord](https://discord.gg/VRKk2EaGHN).
- **Read a language other than English?** Most of our interface translations are machine-translated and have never been read by a native speaker, and we ship them anyway rather than hide them from the people who could fix them. Correcting one is the most useful thing you can do for it — see [Translate the interface](https://openknowledge.ai/docs/contribute/translations).
-- **Want to write the code yourself?** Read [Pull requests](#pull-requests) before you start.
## Why issues come first
@@ -18,15 +17,14 @@ Use the bug report or feature request form. The issues we can act on fastest:
- **Start with the problem, not the solution.** Say what you were doing, what happened, and why it matters to you.
- **For a bug,** give steps that reproduce it, your version and platform, and any logs or screenshots.
- **For a feature,** describe what you would see if it worked. That tells us when it is done.
-- **Point at the code if you found it.** A file, a function or a link to a line helps. Describe the fix in words.
-- **Don't paste a full patch.** Describe the fix in words. If you want to write it yourself, say so in the issue; once a maintainer accepts it (see [Pull requests](#pull-requests)), open a pull request so the change comes with the [Contributor License Agreement](./CLA.md).
+- **Point at the code if you found it.** A file, a function or a link to a line helps.
+- **Describe a proposed fix in words.** Please do not paste a full patch or open a pull request.
-When a fix ships, we close your issue, and our release automation usually comments on it with the version the fix shipped in.
+Filing an issue does not commit us to building the change. When a fix ships, we close your issue, and our release automation usually comments on it with the version the fix shipped in.
## How credit works
-- **Code contributors** are people whose pull requests we accept. The commit that lands credits you as a co-author, which makes you a contributor to this repository. Code contributions require the CLA.
-- **Issue authors** are credited on the issue itself, which stays linked to the problem you found and is closed when we fix it. Filing an issue does not make you a code contributor, and it does not require the CLA.
+Issue authors are credited on the issue itself, which stays linked to the problem they found. Filing an issue does not require a Contributor License Agreement. Earlier code contributions keep their existing attribution.
## Development setup
@@ -102,25 +100,7 @@ If lint stops you, the diagnostic names the class of comment, the fix, and links
## Pull requests
-We still accept pull requests, on these terms:
-
-- **Small fixes are welcome any time:** typos, broken links, documentation corrections and translation fixes.
-- **Anything larger needs an accepted issue first.** Open the issue and wait for a maintainer to label it `help wanted` or say in the thread that we would take a pull request. Link that issue in your PR description.
-- **A pull request without an accepted issue may be closed without review.** If the idea is good, we track it as an issue and build it ourselves.
-- **You are responsible for every line.** AI-assisted code is fine when you understand it, have run it, and can answer questions about it. We close pull requests that read as unreviewed AI output.
-
-First-time contributors are asked to sign our [Contributor License Agreement](./CLA.md) — a bot comments a one-click signing link on your PR (Inkeep employees are exempt automatically). Please follow the checklist in our [Pull Request Template](./.github/PULL_REQUEST_TEMPLATE.md):
-
-- Keep PRs focused and small enough to review.
-- Add tests — or a clear manual-verification note — for behavior changes.
-- Write no code comments outside the allowlist above — `pnpm run lint` fails on the rest.
-- Add a changeset by running `pnpm run changeset` if your pull request changes user-facing or programmatic behavior. Open Knowledge is pre-1.0, so a breaking change rides as `minor` and a `major` changeset is rejected — reaching 1.0.0 is a team decision, not one a single changeset makes.
-- Run `pnpm run check` and `pnpm run check:drift:guards` and confirm both pass.
-- Commit `pnpm-lock.yaml` when dependencies change, and run `pnpm run notices` to refresh `THIRD_PARTY_NOTICES.md` if third-party packages changed.
-- Never include secrets, credentials, customer data, or local machine paths.
-- Enable **Allow edits from maintainers** so reviewers can push fixes to your branch.
-
-A maintainer reviews pull requests that are small fixes or link an accepted issue; if you don't hear back within a few business days, a friendly nudge on the thread is welcome. Accepted changes land on `main` with your authorship preserved (your PR may show as closed rather than merged).
+We do not accept pull requests, including small fixes and translation changes. Please use the [issue forms](https://github.com/inkeep/open-knowledge/issues/new/choose) and the guidance above instead.
## License
diff --git a/README.md b/README.md
index bba4c38d0..492ecb067 100644
--- a/README.md
+++ b/README.md
@@ -76,7 +76,7 @@ Docs for general usage: <https://openknowledge.ai/docs>.
## Contributions
-The best way to contribute is a detailed [issue](https://github.com/inkeep/open-knowledge/issues/new/choose): we build and review the change ourselves. Pull requests are welcome for small fixes, and for larger changes once a maintainer has accepted the issue.
+We do not accept pull requests. Please file a detailed [issue](https://github.com/inkeep/open-knowledge/issues/new/choose) with the problem, steps to reproduce it or the outcome you want. We use issues to consider and track changes.
See [CONTRIBUTING.md](./CONTRIBUTING.md) for details.
diff --git a/docs/content/contribute/translations.mdx b/docs/content/contribute/translations.mdx
index 4fc1e1045..c9059fc2a 100644
--- a/docs/content/contribute/translations.mdx
+++ b/docs/content/contribute/translations.mdx
@@ -15,7 +15,7 @@ Language is an app appearance setting and can be set directly in the config [con
## How you can help
- Fix errors, improve existing translations
-- Add new language sets
+- Request support for another language
## Run OpenKnowledge in the language you're checking
@@ -32,37 +32,19 @@ Reading the interface in your own language is the best review there is, and the
On the desktop app, the `OK_LANG` environment variable additionally overrides the **native menus** for a single run, which is the quickest way to check menu translations without touching config. The rest of the window follows `appearance.language`, so set both if you want everything in one language at once.
-## Make the change
+## Report a translation correction
-Translations live in [`inkeep/open-knowledge`](https://github.com/inkeep/open-knowledge), one gettext catalog per language:
+Choose **Feature request** in the [issue chooser](https://github.com/inkeep/open-knowledge/issues/new/choose). In **What problem are you trying to solve?**, include:
-```
-packages/app/src/locales/<locale>/messages.po
-```
-
-1. **Edit the `msgstr` values.** Leave every `msgid` alone. It is the key the app uses to look the translation up. For most entries it is the English source string. For a few entries it is a key such as `troubleshooting.claude-desktop.per-tool-approval`, and the English text is that entry's `msgstr` in `en/messages.po`. An empty `msgstr` means "untranslated" and falls back to English, so don't blank one out to flag a problem; open an issue instead.
-
- The catalog does not say where a string appears or what a placeholder like `{0}` holds. To find out, search `packages/app/src`, for example with GitHub code search:
-
- - For plain text, search for a distinctive part of the English that sits outside any `{...}` placeholder or `<0>` tag.
- - For a plural or select message such as `{0, plural, one {# file} other {# files}}`, search for the words inside one branch. `#` is the count.
- - For a key such as `troubleshooting.claude-desktop.per-tool-approval`, search for the key itself.
-
- The code around the match shows the screen the string belongs to and the value each placeholder takes.
-
-2. **Follow the glossary.** [`GLOSSARY.md`](https://github.com/inkeep/open-knowledge/blob/main/packages/app/src/locales/GLOSSARY.md), in the same folder, pins one form per language for the words that recur everywhere (*document*, *folder*, *branch*, and so on) and lists what is never translated at all: the product name, format names such as Markdown and YAML, and placeholders like `{count}`. If a glossary entry is wrong for your language, change that row and sweep every message that uses it in the same pull request. A catalog holding two words for one concept is worse than either word on its own.
-
-3. **Normalize the catalog.** CI checks that each `.po` file is exactly what the extractor writes. Run:
-
- ```bash
- cd packages/app && pnpm run i18n
- ```
+- The language you are checking and whether you speak it natively.
+- The screen or menu where the text appears, with a screenshot when useful.
+- The current text.
- Commit every `.po` file that you edited or that the command rewrote. The app compiles a `messages.json` from each `.po` before it builds or runs, and git ignores those files, so there is nothing else to commit.
+Put your suggested wording and why it is clearer in **Proposed solution**.
-4. **Open a pull request.** Say which language you read and whether you speak it natively.
+If you found the entry in `packages/app/src/locales/<locale>/messages.po`, include its `msgid` so we can locate it. The [glossary](https://github.com/inkeep/open-knowledge/blob/main/packages/app/src/locales/GLOSSARY.md) lists the words we use consistently; mention any glossary wording that needs correcting too.
-[CONTRIBUTING.md](https://github.com/inkeep/open-knowledge/blob/main/CONTRIBUTING.md) covers the rest: toolchain, `pnpm run check`, and the Contributor License Agreement.
+We do not accept pull requests for translations. See [CONTRIBUTING.md](https://github.com/inkeep/open-knowledge/blob/main/CONTRIBUTING.md) for issue guidance.
## What is and isn't translated
@@ -74,4 +56,4 @@ packages/app/src/locales/<locale>/messages.po
## A language that isn't on the list
-Open an [issue](https://github.com/inkeep/open-knowledge/issues) before starting work on one, and wait for a maintainer to accept it: a new language is larger than a small fix, so it follows the [pull request rules](https://github.com/inkeep/open-knowledge/blob/main/CONTRIBUTING.md#pull-requests). Then follow the instructions above to provide a complete language set. Don't forget to add the language to the list of available UI languages so other users can select your translation set from within the desktop application!
+Choose **Feature request** in the [issue chooser](https://github.com/inkeep/open-knowledge/issues/new/choose), name the language and describe who would benefit. Filing an issue does not commit the maintainers to adding it.
diff --git a/lint-plugins/no-comments/README.md b/lint-plugins/no-comments/README.md
index bee106ad2..3bd02d9ee 100644
--- a/lint-plugins/no-comments/README.md
+++ b/lint-plugins/no-comments/README.md
@@ -123,8 +123,7 @@ the `{ts,tsx,mjs}` paths it names. In the public repository none of that lane ex
commit-time lane replaces it: the mirror ships the rule but not the sweep, the codemod or the hook,
and it ships no `.husky/` directory either, so `prepare` returns without installing a git hook and
the `lint-staged` block the mirrored `package.json` still carries is never invoked. There the rule
-is reached by running `pnpm run lint` — or `pnpm run check`, which begins with it — and by the
-monorepo-side gate a bridged pull request reaches.
+is reached by running `pnpm run lint` or `pnpm run check`, which begins with it.
Where the hook fails open for a reason the author can act on — for instance a scope config it
cannot read, a valve that suppressed a deny, or an evaluator that threw or crashed — it
@@ -532,9 +531,8 @@ The matcher is hand-rolled for the same reason the two lexers are, and the reaso
rather than a preference: `scope.mjs` sits inside the write-time hook's import closure, which
`scripts/no-comments-hook.test.mjs` pins to `node:` built-ins and this directory's own modules, so
nothing it reaches may import an installed package. Like the hook itself, that test is
-upstream-only and no mirrored test replaces it, so on a public clone the constraint is a rule
-without a gate: adding an installed dependency here reds nothing locally and surfaces only when
-the change is bridged back. The named analog is `picomatch` — zero runtime
+upstream-only and no mirrored test replaces it, so a public clone has no local test for this
+constraint; maintainers validate it upstream. The named analog is `picomatch` — zero runtime
dependencies, `makeRe(glob)` returning a `RegExp` — already resolved in this workspace's lockfile,
so availability is not what rules it out. It is also the referent the refusals measure against:
where `expandBraces` says "the reference expanders", the expanders are `picomatch` and
diff --git a/packages/app/src/locales/REVIEW.md b/packages/app/src/locales/REVIEW.md
index 448b12b17..a48c423ba 100644
--- a/packages/app/src/locales/REVIEW.md
+++ b/packages/app/src/locales/REVIEW.md
@@ -13,8 +13,7 @@ have not had is a reader — someone who reads the language telling us the words
backwards: the people who could tell us a translation was wrong were the same people who could
never encounter it, because it was not offered to them. So the eleven ship, they ship labelled as
machine-translated where that is what they are, and corrections come back through
-[the translation page](https://openknowledge.ai/docs/contribute/translations) as ordinary pull
-requests.
+[the translation page](https://openknowledge.ai/docs/contribute/translations) as detailed issues.
What that does not do is let us claim they are reviewed. The table below is the whole of that
claim, and most rows say `unreviewed` for as long as that is true.
@@ -129,8 +128,8 @@ review than the packet. The packet exists so that not being able to do it is not
### 2. Send it out
-Community translation runs through public pull requests against `inkeep/open-knowledge`. Attach
-the packet, or paste it into the issue or PR thread. Ask for what the packet asks for: a list of
+Community translation feedback goes through detailed issues in `inkeep/open-knowledge`. Attach
+the packet, or paste it into the issue thread. Ask for what the packet asks for: a list of
numbered strings to change, and what they should say.
### 3. Land what comes back