Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): route contributor-PR-bridge conflicts to a draft maintainer PR (#2189)
Nick Gomez5418e8bbb568
diff --git a/.github/scripts/bridge-public-pr-to-monorepo.mjs b/.github/scripts/bridge-public-pr-to-monorepo.mjsindex 3546f6e63..9bd24b0b1 100644--- a/.github/scripts/bridge-public-pr-to-monorepo.mjs+++ b/.github/scripts/bridge-public-pr-to-monorepo.mjs@@ -15,6 +15,11 @@ import { applyClaGate } from './cla-gate.mjs';// contributor-CLA enforcement — an OK-only divergence. That module ships to the// same repo via Copybara, so the import resolves on the mirror; the "no shared// code" rule still holds (no module is shared ACROSS the three repos).+// The OK copy also routes 3-way-apply conflicts to a draft maintainer PR rather+// than hard-failing (the OK mirror strips comments, so contributor patches+// conflict against the comment-rich internal tree); the sibling copies keep the+// hard-fail behavior. No drift check enforces shape alignment, so this OK-only+// divergence is intentional and scoped here.const BRIDGE_COMMENT_MARKER = '<!-- monorepo-pr-bridge -->';// Strip x-access-token credentials from any string that might end up in an@@ -388,6 +393,15 @@ This public PR was merged directly in the public repo. The matching monorepo PR${details}`;}+ if (status === 'conflicts') {+ return `${BRIDGE_COMMENT_MARKER}+Thanks for the contribution! Your PR has been mirrored into Inkeep's internal monorepo, but it **could not be merged automatically**: the change overlaps edits in the internal source that aren't visible on this public mirror, so it needs a maintainer to reconcile by hand.++**No action is needed from you.** Your PR is already based on the latest \`${publicPr.base.repo.full_name}\` main; the divergence is internal to the mirror, not something to fix from your branch. Your commit attribution is preserved as @${publicPr.user.login}.++An Inkeep maintainer will resolve the conflicts on the internal mirror PR and land it; this PR will close automatically once it merges internally. This comment will be updated as the bridge state changes.`;+ }+return `${BRIDGE_COMMENT_MARKER}I could not sync this public PR into \`agents-private\` automatically.@@ -532,6 +546,62 @@ function createClaGateGh({};}+// Marker appended to the bridge's mirror commit when the 3-way apply left+// conflicts, so the conflict draft-hold survives a metadata-only re-sync (where+// the apply block is skipped) instead of being silently lost.+const CONFLICT_COMMIT_MARKER = 'with conflicts; needs manual resolution';++// True when an internal mirror commit message marks a conflict-carrying bridge+// commit (see CONFLICT_COMMIT_MARKER), used to keep that PR held draft across+// metadata-only re-syncs.+function commitIndicatesConflicts(commitMessage) {+ return typeof commitMessage === 'string' && commitMessage.includes(CONFLICT_COMMIT_MARKER);+}++// Apply the prefixed PR patch onto the internal checkout and classify the+// outcome. `git apply --index --3way` exits non-zero BOTH when the patch cannot+// apply at all AND when it applies but leaves conflict markers, so the exit code+// alone can't tell a genuine failure from a conflict a maintainer can resolve.+// Distinguish them by the index: a 3-way merge that conflicted leaves unmerged+// (stage > 0) entries; a genuine non-apply leaves none.+// - 'clean' — applied with no conflicts (exit 0)+// - 'conflicts' — applied WITH conflict markers (unmerged entries present)+// - 'failed' — could not apply (no unmerged entries); `message` carries the+// sanitized git output for the contributor-facing comment+function applyPatchWithConflictDetection(internalRepoDir, patchFile) {+ try {+ run('git', ['-C', internalRepoDir, 'apply', '--index', '--3way', patchFile]);+ return { outcome: 'clean', conflictedPaths: [], message: '' };+ } catch (error) {+ // `run()` has already stripped any x-access-token URL from error.message.+ // Guard the unmerged-index probe: if even it throws (corrupt/locked index),+ // fall through to 'failed' rather than escaping the classifier. Fail-closed,+ // never route a real error as a resolvable conflict.+ let conflictedPaths = [];+ try {+ const unmerged = run('git', [+ '-C',+ internalRepoDir,+ 'diff',+ '--name-only',+ '--diff-filter=U',+ ]);+ conflictedPaths = unmerged ? unmerged.split('\n').filter(Boolean) : [];+ } catch (probeError) {+ // Fail-closed routing to 'failed' is still correct, but surface the probe+ // failure so a maintainer can tell "no unmerged entries" from "probe broke".+ 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');@@ -566,6 +636,7 @@ async function syncPublicPr() {publicPrAction === 'converted_to_draft');let hasStagedChanges = false;+ let hasConflicts = false;if (!metadataOnlyAction) {// Bring agents-private's main into the local clone and check out the new// branch first. We need this in place before the public-PR-refs fetch so@@ -679,27 +750,47 @@ async function syncPublicPr() {writeFileSync(patchFile, prefixPatchPaths(patch, mirrorPath, pathRewrites), 'utf8');try {- try {- run('git', ['-C', internalRepoDir, 'apply', '--index', '--3way', patchFile]);- } catch (error) {- // error.message has already been routed through `run()` which- // sanitizes any embedded x-access-token URL, so it's safe to surface- // verbatim. Including the actual git output makes the failure- // actionable for external contributors who can't read internal- // workflow logs (matches agents-optional-local-dev's behavior).- await upsertIssueComment({- token: publicToken,- repo: publicRepo,- issueNumber: publicPrNumber,- body: buildPublicComment({- publicPr,- status: 'failed',- details:- 'Patch application failed. The diff could not be applied cleanly. ' +- `Try rebasing your PR on the latest base branch.\n\n\`\`\`\n${error.message}\n\`\`\``,- }),- });- throw error;+ const applyResult = applyPatchWithConflictDetection(internalRepoDir, patchFile);++ if (applyResult.outcome === 'failed') {+ // Genuine non-apply (not a resolvable conflict) — surface it and fail.+ // `run()` sanitized the git output, so it's safe to include; it makes+ // the failure actionable. NOT a "rebase" case: the contributor is+ // already on the latest public base — this is a bridge-side problem.+ // Wrap the comment post so a GitHub API failure here can't mask the+ // actual git apply diagnostic in the error thrown below.+ try {+ await upsertIssueComment({+ token: publicToken,+ repo: publicRepo,+ issueNumber: publicPrNumber,+ body: buildPublicComment({+ publicPr,+ status: 'failed',+ details:+ 'The diff could not be applied to the internal monorepo. This is a ' ++ 'bridge-side issue, not a problem with your PR (which is already based ' ++ 'on the latest public base); an Inkeep maintainer will look into it.' ++ `\n\n\`\`\`\n${applyResult.message}\n\`\`\``,+ }),+ });+ } catch (commentError) {+ console.warn(+ `Bridge: could not post 'failed' comment to public PR: ${commentError.message}`,+ );+ }+ throw new Error(applyResult.message || 'git apply failed');+ }++ hasConflicts = applyResult.outcome === 'conflicts';++ // A conflicted 3-way apply leaves unmerged (stage > 0) entries with+ // conflict markers in the working tree; `git apply --index` already+ // staged the cleanly-merged files. Stage the marker versions too so the+ // commit captures the full state for a maintainer to resolve on the+ // internal PR (the markers make it un-mergeable; it's held draft below).+ if (hasConflicts) {+ run('git', ['-C', internalRepoDir, 'add', '-A']);}hasStagedChanges = (() => {@@ -722,6 +813,9 @@ async function syncPublicPr() {]);const authorEmail = `${publicPr.user.id}+${publicPr.user.login}@users.noreply.github.com`;+ const commitMessage = hasConflicts+ ? `chore(sync): mirror ${publicRepo}#${publicPr.number} (${CONFLICT_COMMIT_MARKER})`+ : `chore(sync): mirror ${publicRepo}#${publicPr.number}`;run('git', ['-C',internalRepoDir,@@ -729,7 +823,7 @@ async function syncPublicPr() {'--author',`${publicPr.user.login} <${authorEmail}>`,'-m',- `chore(sync): mirror ${publicRepo}#${publicPr.number}`,+ commitMessage,]);run('git', [@@ -778,6 +872,28 @@ async function syncPublicPr() {}}+ // On a metadata-only re-sync (edited / ready_for_review / converted_to_draft)+ // the apply block above is skipped, so `hasConflicts` is still its initial+ // false even for a PR previously bridged with conflicts. Re-derive the conflict+ // hold from the existing internal PR's head-commit marker, otherwise a metadata+ // event (e.g. the contributor editing their PR body) would un-draft a+ // conflict-carrying PR and overwrite its comment with 'synced'.+ if (metadataOnlyAction && internalPr) {+ const headCommit = await githubRequest({+ token: internalToken,+ path: `/repos/${internalRepo}/commits/${internalPr.head.sha}`,+ });+ if (headCommit?.commit?.message == null) {+ // A structurally unexpected 200 (no commit message) would silently default+ // hasConflicts to false and un-draft a conflict-carrying PR. The endpoint is+ // stable so this is defensive, but make the implicit fail-open observable.+ 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 title = internalPullRequestTitle(publicPr);const body = buildInternalPrBody({ publicPr, branchName, mirrorPath });@@ -807,11 +923,13 @@ async function syncPublicPr() {// PR, but the bridge re-commits under a new SHA here, so that status can't gate// the internal PR directly. Hold the internal PR (draft + a failing// `cla/verified` status) until signed, re-checked on every sync. This also- // takes over draft-state mirroring: shouldBeDraft = publicPr.draft || gated.+ // takes over draft-state mirroring: shouldBeDraft = publicPr.draft || gated ||+ // hasConflicts (a conflict-carrying PR must stay a draft until reconciled).await applyClaGate({gh: createClaGateGh({ publicToken, publicRepo, internalToken, internalRepo }),publicPr,internalPr,+ forceDraft: hasConflicts,});await upsertIssueComment({@@ -821,7 +939,7 @@ async function syncPublicPr() {body: buildPublicComment({publicPr,internalPr,- status: 'synced',+ status: hasConflicts ? 'conflicts' : 'synced',}),});}@@ -929,11 +1047,15 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)}export {+ applyPatchWithConflictDetection,buildInternalPrBody,+ commitIndicatesConflicts,buildPublicComment,checkOrgMembership,createClaGateGh,postCommitStatus,prefixPatchPaths,readCommitClaStatus,+ // Exported solely for the metadata-event composition test.+ syncPublicPr,};diff --git a/.github/scripts/bridge-public-pr-to-monorepo.test.mjs b/.github/scripts/bridge-public-pr-to-monorepo.test.mjsindex aef2d63c9..34afcf266 100644--- a/.github/scripts/bridge-public-pr-to-monorepo.test.mjs+++ b/.github/scripts/bridge-public-pr-to-monorepo.test.mjs@@ -1,9 +1,17 @@import { describe, expect, test } from "bun:test";+import { execFileSync } from "node:child_process";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";import {+ applyPatchWithConflictDetection,+ buildPublicComment,checkOrgMembership,+ commitIndicatesConflicts,createClaGateGh,postCommitStatus,readCommitClaStatus,+ syncPublicPr,} from "./bridge-public-pr-to-monorepo.mjs";// A fake `githubRequest`: records every call and returns the queued response.@@ -146,3 +154,299 @@ describe("createClaGateGh", () => {expect(calls[0].path).toBe("/orgs/inkeep/members/octocat");});});++// --- Graceful conflict routing canary (real `git apply --index --3way`) ------+//+// Guards the conflict-classification invariant: a contributor patch built+// against the comment-STRIPPED public mirror must NOT hard-fail the bridge when+// it 3-way-conflicts with the comment-RICH internal tree — it must be classified+// as a resolvable 'conflicts' outcome (routed to a draft maintainer PR), while a+// genuine non-apply stays 'failed' (fail-closed). Exercises the bridge's REAL+// command, not a mock.++const git = (dir, ...args) =>+ execFileSync("git", ["-C", dir, ...args], { encoding: "utf8" }).trim();++// Build a real temp git repo: BASE = the comment-stripped public version (so the+// patch's base blob is reachable for the 3-way), a patch = the contributor's+// change against BASE, and the working tree = OURS (the comment-rich internal+// version) the bridge applies onto. Returns { repoDir, patchFile, cleanup }.+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");+ 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");+ // theirs = the contributor's change against the stripped base, captured as a diff+ 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`);+ // ours = the comment-rich internal version, checked out as the apply target+ 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", () => {+ // OURS adds a comment on the SAME line the contributor edits — the exact+ // comment-strip divergence that broke the bridge. Guaranteed 3-way conflict.+ 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'", () => {+ // The contributor edits B (top); OURS's comment divergence is at C (bottom),+ // separated by filler so they land in DIFFERENT diff hunks → 3-way merges+ // cleanly. (Adjacent divergences share a hunk and conflict — see the test+ // above; that's exactly why the bridge conflicts on comment-dense regions.)+ 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");+ 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");+ // A patch against a file that does not exist, whose base blobs are absent —+ // git apply --3way can neither apply it directly nor reconstruct a 3-way 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();+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ test("conflict and failure comments give accurate guidance and never advise a rebase", () => {+ const publicPr = {+ user: { login: "octocat" },+ base: { repo: { full_name: "inkeep/open-knowledge" } },+ };+ const conflicts = buildPublicComment({ publicPr, status: "conflicts" });+ const failed = buildPublicComment({+ publicPr,+ status: "failed",+ details: "The diff could not be applied to the internal monorepo.",+ });+ for (const body of [conflicts, failed]) {+ expect(body.toLowerCase()).not.toContain("rebase");+ }+ expect(conflicts).toContain("No action is needed from you");+ expect(conflicts).toContain("@octocat");+ // upsertIssueComment finds+updates the existing comment by this marker; if the+ // conflicts branch dropped it, every metadata re-sync would post a duplicate.+ expect(conflicts).toContain("<!-- monorepo-pr-bridge -->");+ });+});++describe("commitIndicatesConflicts (metadata-re-sync conflict-hold guard)", () => {+ test("true for a conflict-marker mirror commit message", () => {+ expect(+ commitIndicatesConflicts(+ "chore(sync): mirror inkeep/open-knowledge#310 (with conflicts; needs manual resolution)",+ ),+ ).toBe(true);+ });++ test("false for a clean mirror commit message", () => {+ expect(commitIndicatesConflicts("chore(sync): 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);+ });+});++// --- Metadata-event composition test (guards the conflict-hold fail-open) -----+//+// On a metadata-only re-sync (e.g. a contributor editing their PR body)+// syncPublicPr skips the apply block, so hasConflicts must be re-derived from+// the internal PR's head-commit marker; otherwise a conflict-carrying DRAFT PR+// is silently un-drafted (markPullRequestReadyForReview) and its comment flips+// to 'synced'. Per-predicate unit tests (canary, predicate, forceDraft) cannot+// reach this wiring. This runs the REAL syncPublicPr metadata path (zero git+// ops) with the GitHub API faked at the true external boundary, asserting the+// observable draft/comment OUTCOME, not call counts.++const CONFLICT_HEAD =+ "chore(sync): mirror inkeep/open-knowledge#310 (with conflicts; needs manual resolution)";+const CLEAN_HEAD = "chore(sync): mirror inkeep/open-knowledge#310";++// Drive the real syncPublicPr through a metadata-only ('edited') event with the+// GitHub API faked. Returns the load-bearing observable mutations it made.+async function runMetadataSync({ headCommitMessage, internalPrStartsDraft }) {+ const recorded = { draftMutation: null, comment: null };+ const internalPr = {+ number: 42,+ node_id: "PR_node_42",+ draft: internalPrStartsDraft,+ head: { sha: "internal-head-sha" },+ 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", repo: { full_name: "inkeep/open-knowledge" } },+ head: { label: "octocat:branch", sha: "public-head-sha" },+ draft: false,+ };+ const json = (obj, status = 200) => ({+ ok: status < 400,+ status,+ text: async () => JSON.stringify(obj),+ });++ const realFetch = globalThis.fetch;+ globalThis.fetch = async (url, init = {}) => {+ const method = init.method || "GET";+ if (method === "GET" && url.includes("/repos/inkeep/open-knowledge/pulls/310")) return json(publicPr);+ if (method === "GET" && url.includes("/pulls?state=open")) return json([internalPr]);+ if (method === "GET" && url.includes("/commits/internal-head-sha") && !url.includes("/status")) {+ return json({ commit: { message: headCommitMessage } });+ }+ if (method === "PATCH" && url.includes("/pulls/42")) return json(internalPr);+ if (method === "GET" && url.includes("/orgs/")) return json({ message: "Not Found" }, 404); // non-member+ if (method === "GET" && url.includes("/commits/public-head-sha/status")) {+ return json({ statuses: [{ context: "license/cla", state: "success" }] }); // CLA signed -> not gated+ }+ 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/")) return json({});+ if (method === "GET" && url.includes("/issues/310/comments")) 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: "/tmp/unused-on-metadata-path",+ MONOREPO_PATH_PREFIX: "public/open-knowledge",+ INTERNAL_BASE_REF: "main",+ INTERNAL_BRANCH_PREFIX: "public-pr/open-knowledge",+ PUBLIC_PR_NUMBER: "310",+ PUBLIC_PR_ACTION: "edited",+ };+ const saved = {};+ for (const k of Object.keys(setKeys)) saved[k] = process.env[k];+ Object.assign(process.env, setKeys);+ try {+ await syncPublicPr();+ } 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 'conflicts' (not un-draft + 'synced')", async () => {+ const r = await runMetadataSync({ headCommitMessage: CONFLICT_HEAD, internalPrStartsDraft: true });+ // Without the conflict-hold re-derivation, this fires+ // markPullRequestReadyForReview. Correct: the conflict hold is re-derived+ // true -> shouldBeDraft true -> already draft -> NO transition fires.+ expect(r.draftMutation).toBeNull();+ expect(r.comment).toContain("No action is needed from you");+ expect(r.comment.toLowerCase()).not.toContain("rebase");+ expect(r.comment).not.toContain("review and merge happen"); // not the 'synced' body+ });++ test("a metadata event on a clean PR readies it and posts 'synced'", async () => {+ const r = await runMetadataSync({ headCommitMessage: CLEAN_HEAD, internalPrStartsDraft: true });+ expect(r.draftMutation).toBe("to-ready");+ expect(r.comment).toContain("review and merge happen"); // the 'synced' body+ });++ test("a metadata event on a non-draft PR whose head now carries conflicts re-drafts it", async () => {+ const r = await runMetadataSync({ headCommitMessage: CONFLICT_HEAD, internalPrStartsDraft: false });+ // Symmetric to the draft case: the conflict hold is re-derived true ->+ // shouldBeDraft true -> PR is currently ready -> convertPullRequestToDraft fires.+ expect(r.draftMutation).toBe("to-draft");+ expect(r.comment).toContain("No action is needed from you");+ });+});diff --git a/.github/scripts/cla-gate.mjs b/.github/scripts/cla-gate.mjsindex 1120801be..8d51ffce8 100644--- a/.github/scripts/cla-gate.mjs+++ b/.github/scripts/cla-gate.mjs@@ -101,10 +101,13 @@ function describeReason(reason) {* - setVerifiedStatus(internalPr, state, description) => Promise<void> posts `cla/verified`* @param {object} input.publicPr Public PR: { user: { login }, draft, head: { sha } }.* @param {object} input.internalPr Internal PR: { head: { sha } }.+ * @param {boolean} [input.forceDraft] When true, hold the PR as a draft regardless+ * of CLA/origin draft state — used when the bridged commit carries conflict+ * markers that a maintainer must resolve before the PR can merge.* @returns {Promise<{ gated: boolean, reason: string }>} reason is one of* evaluateClaGate's reasons, or "cla-read-error" when a read threw.*/-export async function applyClaGate({ gh, publicPr, internalPr }) {+export async function applyClaGate({ gh, publicPr, internalPr, forceDraft = false }) {const author = publicPr?.user?.login;let gate;try {@@ -115,11 +118,15 @@ export async function applyClaGate({ gh, publicPr, internalPr }) {// An exempt author never needs the public CLA status, so skip the read.const claStatus = exempt ? null : await gh.readClaStatus(publicPr);gate = evaluateClaGate({ claStatus, exempt });- } catch {+ } catch (error) {+ // Fail closed for the security gate, but surface WHY the read failed+ // (401 / rate limit / API down) so a perpetual cla-read-error hold is+ // triagable; forceDraft routing makes this catch newly load-bearing.+ 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;+ const shouldBeDraft = Boolean(publicPr?.draft) || gate.gated || forceDraft;await gh.setDraft(internalPr, shouldBeDraft);await gh.setVerifiedStatus(internalPr,diff --git a/.github/scripts/cla-gate.test.mjs b/.github/scripts/cla-gate.test.mjsindex 8fd961338..bc49c3f7f 100644--- a/.github/scripts/cla-gate.test.mjs+++ b/.github/scripts/cla-gate.test.mjs@@ -170,6 +170,21 @@ describe("applyClaGate", () => {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);+ // The gate itself is not gated (CLA is signed); the draft is purely the+ // conflict hold, so cla/verified still reports success.+ 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 });