Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

31.2 KB
Raw Blame
import { gitText } from "../../../plugins/codex-security/mcp-app/scripts/git.mjs";
import { execFileSync } from "node:child_process";
import { hash } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import { isDeepStrictEqual } from "node:util";
import { assertStableVersion, releaseVersion } from "./release-automation.mjs";
import { isMain } from "./is-main.mjs";

export const packagePath = "sdk/typescript/package.json";
export const actionPackagePath = "github-action/package.json";
export const actionLockPath = "github-action/package-lock.json";
export const exampleWorkflowPath = "examples/github-actions/codex-security.yml";
export const notesPath = ".github/release-notes.md";
export const statePath = ".github/release-pr-state.json";
const packagePaths = [packagePath, actionPackagePath, actionLockPath];
const templatePath = ".github/PULL_REQUEST_TEMPLATE.md";
const sectionIds = ["highlights", "upgrades"];
const releaseBranchPrefix = "release/next-";
const conventionalTitle = /^([a-z][a-z0-9-]*)(?:\(([^)]*)\))?(!)?: (.+)$/u;
const exampleVersionPattern =
  /^([ \t]*CODEX_SECURITY_VERSION:[ \t]*)(["']?)[0-9]+\.[0-9]+\.[0-9]+\2(?=[ \t]*(?:#[^\r\n]*)?\r?$)/gmu;

function isReleaseTitle(title) {
  const [, type, scope] = conventionalTitle.exec(title) ?? [];
  return type === "release" || (type === "chore" && scope === "release");
}

function isReleasePull(pull) {
  return (
    isReleaseTitle(pull.title) || pull.head.ref.startsWith(releaseBranchPrefix)
  );
}

export function isBreakingChange(change) {
  return (
    conventionalTitle.exec(change.title)?.[3] === "!" ||
    /^(?:BREAKING CHANGE|BREAKING-CHANGE):\s+\S/mu.test(change.body ?? "") ||
    (change.labels ?? []).includes("breaking-change")
  );
}

export function nextReleaseVersion(version, changes) {
  assertStableVersion(version);
  const [major, minor, patch] = version.split(".").map(BigInt);
  if (major !== 0n) {
    throw new Error(
      "Review the release PR version policy before enabling it for 1.x.",
    );
  }
  if (changes.length === 0) return version;
  return changes.some((change) => change.breaking ?? isBreakingChange(change))
    ? `0.${minor + 1n}.0`
    : `0.${minor}.${patch + 1n}`;
}

function markdownText(value) {
  return value.replace(/[\r\n]+/gu, " ").replace(/[\\`*_[\]<>]/gu, "\\$&");
}

function changeLine(change) {
  const description = conventionalTitle.exec(change.title)?.[4] ?? change.title;
  const reference = change.number
    ? `#${change.number}`
    : change.sha.slice(0, 7);
  return `- ${markdownText(description)} ([${reference}](${change.url}))`;
}

function visibleChanges(changes) {
  return changes.filter((change) => {
    const type = conventionalTitle.exec(change.title)?.[1];
    return (
      !(change.labels ?? []).includes("skip-release-notes") &&
      (change.breaking || (type !== "test" && !isReleaseTitle(change.title)))
    );
  });
}

export function generateNoteSections(changes) {
  const visible = visibleChanges(changes);
  const highlights = visible.filter((change) => !change.breaking);
  const breaking = visible.filter((change) => change.breaking);
  return {
    highlights: [
      "## Highlights",
      "",
      highlights.length > 0
        ? [
            "<details>",
            "<summary>Changes to review for highlights</summary>",
            "",
            ...highlights.map(changeLine),
            "",
            "</details>",
          ].join("\n")
        : "No release highlights have been drafted yet.",
    ].join("\n"),
    upgrades: [
      "## Upgrade notes",
      "",
      breaking.length > 0
        ? [
            "<!-- Replace each candidate with the affected users and the action they need to take. -->",
            "",
            ...breaking.map(changeLine),
          ].join("\n")
        : "No additional migration steps are documented for this release.",
    ].join("\n"),
  };
}

function sectionBlock(id, content) {
  return `<!-- release-section: ${id}:start -->\n\n${content}\n\n<!-- release-section: ${id}:end -->`;
}

function findSection(notes, id) {
  const markers = [
    ...notes.matchAll(
      new RegExp(`^<!-- release-section: ${id}:(start|end) -->\\r?$`, "gm"),
    ),
  ];
  if (
    markers.length !== 2 ||
    markers[0][1] !== "start" ||
    markers[1][1] !== "end"
  )
    return null;
  const start = markers[0].index;
  const end = markers[1].index + markers[1][0].length;
  return { start, end, text: notes.slice(start, end) };
}

export function updateReleaseNotes(
  version,
  generated,
  previousNotes,
  previousSections,
) {
  const header = `<!-- release-version: ${version} -->`;
  const sections = {};
  const initial = previousSections === undefined;
  let notes = initial ? null : previousNotes;
  if (notes !== null) {
    notes = /^<!-- release-version: [^\r\n]* -->/u.test(notes)
      ? notes.replace(/^<!-- release-version: [^\r\n]* -->/u, header)
      : `${header}\n\n${notes}`;
  }
  for (const id of sectionIds) {
    const previous = initial ? null : previousSections[id];
    const block = initial || notes === null ? null : findSection(notes, id);
    const humanOwned =
      !initial &&
      previous?.reset !== true &&
      (previous?.humanOwned !== false ||
        block === null ||
        hash("sha256", block.text) !== previous.generatedHash);
    if (humanOwned) {
      sections[id] = {
        generatedHash: previous?.generatedHash ?? null,
        humanOwned: true,
      };
      continue;
    }
    const next = sectionBlock(id, generated[id]);
    if (block === null) {
      notes = `${notes ?? `${header}\n`}\n${next}\n`;
    } else {
      notes = notes.slice(0, block.start) + next + notes.slice(block.end);
    }
    sections[id] = { generatedHash: hash("sha256", next), humanOwned: false };
  }
  return { notes, sections };
}

function updatePackageVersion(packageText, version) {
  const expected = JSON.parse(packageText);
  expected.version = version;
  // Preserve formatting while selecting only the top-level version field.
  for (const match of packageText.matchAll(
    /("version"\s*:\s*)("(?:\\.|[^"\\])*")/gu,
  )) {
    const start = match.index + match[1].length;
    const updated =
      packageText.slice(0, start) +
      JSON.stringify(version) +
      packageText.slice(start + match[2].length);
    if (isDeepStrictEqual(JSON.parse(updated), expected)) return updated;
  }
  throw new Error("Unable to update only the top-level package version.");
}

function updateActionLockVersion(lockText, version) {
  const lock = JSON.parse(lockText);
  lock.version = version;
  lock.packages[""].version = version;
  return `${JSON.stringify(lock, null, 2)}\n`;
}

function updateExampleVersion(exampleText, version) {
  if ([...exampleText.matchAll(exampleVersionPattern)].length !== 1) {
    throw new Error(
      "Unable to update only the GitHub Actions example CLI version.",
    );
  }
  return exampleText.replace(
    exampleVersionPattern,
    (_match, prefix, quote) => `${prefix}${quote}${version}${quote}`,
  );
}

function packageWithoutVersion(text, path) {
  if (text === null) return null;
  const metadata = JSON.parse(text);
  delete metadata.version;
  if (path === actionLockPath && metadata.packages?.[""]) {
    delete metadata.packages[""].version;
  }
  return metadata;
}

export function createReleasePlan(history, previous = null) {
  const { baseVersion, baseCommit, mainSha, packageText, changes } = history;
  if (
    previous &&
    (previous.state.baseVersion !== baseVersion ||
      previous.state.baseCommit !== baseCommit)
  ) {
    throw new Error(
      "The release branch belongs to a different release cycle; review it before continuing.",
    );
  }
  const version = nextReleaseVersion(baseVersion, changes);
  const generated = generateNoteSections(changes);
  const { notes, sections } = updateReleaseNotes(
    version,
    generated,
    previous?.notes ?? null,
    previous?.state.sections,
  );
  const state = { baseVersion, baseCommit, sections };
  const files = {
    [packagePath]: updatePackageVersion(packageText, version),
    [notesPath]: notes,
    [statePath]: `${JSON.stringify(state, null, 2)}\n`,
  };
  if (history.actionPackageText != null) {
    files[actionPackagePath] = updatePackageVersion(
      history.actionPackageText,
      version,
    );
  }
  if (history.actionLockText != null) {
    files[actionLockPath] = updateActionLockVersion(
      history.actionLockText,
      version,
    );
  }
  if (history.exampleWorkflowText != null) {
    files[exampleWorkflowPath] = updateExampleVersion(
      history.exampleWorkflowText,
      version,
    );
  }
  return {
    baseVersion,
    baseCommit,
    mainSha,
    version,
    branch: `${releaseBranchPrefix}${baseVersion}`,
    title: `chore(release): ${version}`,
    changes,
    generated,
    humanOwned: sectionIds.filter((id) => sections[id].humanOwned),
    files,
  };
}

export function createGitRepository(directory, env = process.env) {
  const git = (...args) =>
    gitText(args, { cwd: directory, env, stdio: ["pipe", "pipe", "pipe"] });
  return {
    git,
    ensureCommit(sha) {
      try {
        git("cat-file", "-e", `${sha}^{commit}`);
      } catch {
        git("fetch", "--no-tags", "origin", sha);
      }
    },
    readFile(sha, path) {
      if (git("ls-tree", sha, "--", path).trim() === "") return null;
      return git("show", `${sha}:${path}`);
    },
  };
}

export function readVersionHistory(repo, mainSha) {
  repo.ensureCommit(mainSha);
  const packageText = repo.readFile(mainSha, packagePath);
  const baseVersion = releaseVersion(JSON.parse(packageText));
  let baseCommit = mainSha;
  for (const sha of repo
    .git("log", "--first-parent", "--format=%H", mainSha, "--", packagePath)
    .trim()
    .split("\n")) {
    const packageJson = JSON.parse(repo.readFile(sha, packagePath));
    if (packageJson.version !== baseVersion) break;
    baseCommit = sha;
  }

  return { baseVersion, baseCommit, packageText };
}

export async function readReleaseHistory(repo, mainSha, github) {
  const { baseVersion, baseCommit, packageText } = readVersionHistory(
    repo,
    mainSha,
  );
  const commits = repo
    .git("rev-list", "--first-parent", "--reverse", `${baseCommit}..${mainSha}`)
    .trim()
    .split("\n")
    .filter(Boolean);
  const changes = new Map();
  for (const sha of commits) {
    const body = repo.git("show", "-s", "--format=%B", sha);
    const pulls = await github.list(`commits/${sha}/pulls?per_page=100`);
    const pull = pulls.find(
      (candidate) => candidate.merged_at && candidate.base.ref === "main",
    );
    const change = {
      sha,
      number: pull?.number ?? null,
      title: pull?.title ?? body.split("\n")[0],
      labels: (pull?.labels ?? []).map((label) => label.name),
      url: pull?.html_url ?? `${github.repositoryUrl}/commit/${sha}`,
    };
    change.breaking = isBreakingChange({
      ...change,
      body: [pull?.body ?? "", body].join("\n"),
    });
    const key = pull ? `pr-${pull.number}` : sha;
    if (changes.has(key)) {
      changes.get(key).breaking ||= change.breaking;
    } else {
      changes.set(key, change);
    }
  }
  return {
    baseVersion,
    baseCommit,
    mainSha,
    packageText,
    actionPackageText: repo.readFile(mainSha, actionPackagePath),
    actionLockText: repo.readFile(mainSha, actionLockPath),
    exampleWorkflowText: repo.readFile(mainSha, exampleWorkflowPath),
    changes: [...changes.values()],
  };
}

function readReleaseBranch(repo, mainSha, headSha) {
  repo.ensureCommit(headSha);
  const mergeBase = repo.git("merge-base", mainSha, headSha).trim();
  const paths = repo
    .git("diff", "--no-renames", "--name-only", "-z", mergeBase, headSha)
    .split("\0")
    .filter(Boolean);
  if (
    paths.some(
      (path) =>
        ![...packagePaths, exampleWorkflowPath, notesPath, statePath].includes(
          path,
        ),
    )
  ) {
    return {
      holdReason:
        "The release branch has other file edits. Preserve or merge them before running the updater.",
    };
  }
  for (const path of packagePaths) {
    const originalPackage = packageWithoutVersion(
      repo.readFile(mergeBase, path),
      path,
    );
    const branchPackage = packageWithoutVersion(
      repo.readFile(headSha, path),
      path,
    );
    if (!isDeepStrictEqual(originalPackage, branchPackage)) {
      return {
        holdReason:
          "The release branch has package edits beyond its version. Preserve them before running the updater.",
      };
    }
  }
  const originalExample = repo
    .readFile(mergeBase, exampleWorkflowPath)
    ?.replace(exampleVersionPattern, "$1$2$2");
  const branchExample = repo
    .readFile(headSha, exampleWorkflowPath)
    ?.replace(exampleVersionPattern, "$1$2$2");
  if (originalExample !== branchExample) {
    return {
      holdReason:
        "The release branch has GitHub Actions example edits beyond its CLI version. Preserve them before running the updater.",
    };
  }
  const state = JSON.parse(repo.readFile(headSha, statePath));
  if (!state?.sections) {
    throw new Error(
      "The existing release branch has no note ownership state; it must be reviewed manually.",
    );
  }
  return { state, notes: repo.readFile(headSha, notesPath), mergeBase };
}

function initialPullBody(template) {
  const sections = {
    Summary: "Keep a release proposal current with changes merged into main.",
    Changes:
      "Update the package version and draft release notes. The version header and PR title are maintained by automation. Edit the marked note sections in `.github/release-notes.md`; edited or deleted sections become human-owned. New suggestions appear in subsequent bot comments. The PR description is never regenerated.",
    Testing:
      "The updater does not run package tests. Before merging, verify required CI in the **Checks** tab and Codex review on the current commit. Request a final review if Codex last reviewed an older commit. Post later manual test results in a PR comment or review with the tested commit SHA. Editing the description to update status can trigger CI.",
    "Risk and rollout":
      "Merging this PR starts the existing CI and protected release process. Review migration details and complete the public disclosure review before merging.",
  };
  let body = template;
  for (const [heading, content] of Object.entries(sections)) {
    body = body.replace(
      new RegExp(`(## ${heading}\\n)[\\s\\S]*?(?=\\n## |$)`, "u"),
      `$1\n${content}\n`,
    );
  }
  return body;
}

function reviewComment(
  plan,
  headSha,
  proposalMarker,
  suggestionsMarker,
  requestReview,
) {
  const marker = `<!-- release-pr-head: ${headSha} -->`;
  return [
    marker,
    proposalMarker,
    suggestionsMarker,
    `Release proposal updated through main commit \`${plan.mainSha}\`.`,
    plan.humanOwned.length > 0
      ? `Preserved human-owned sections: ${plan.humanOwned.join(", ")}. The suggestions below have not replaced them.`
      : "The note sections still match the generated draft and were refreshed.",
    "These suggestions use merged titles, not a review of migration requirements. The committed notes remain authoritative.",
    ...sectionIds.map((id) => plan.generated[id]),
    ...(requestReview ? [`@codex review the current head ${headSha}.`] : []),
  ].join("\n\n");
}

async function branchHead(github, branch) {
  try {
    return (await github.request("GET", `git/ref/heads/${branch}`)).object.sha;
  } catch (error) {
    if (error.status === 404) return null;
    throw error;
  }
}

const closedPullReason =
  "The release PR was closed or retargeted during the update. Review it before continuing.";
const pendingHeadReason =
  "GitHub has not exposed the updated PR head yet. Rerun the updater before final review.";
const changedHeadReason =
  "The release head changed. Rerun before final review.";

function pullHoldReason(pull, branch, repository) {
  if (
    pull?.state !== "open" ||
    pull.head.ref !== branch ||
    pull.head.repo?.full_name?.toLowerCase() !== repository.toLowerCase() ||
    pull.base.ref !== "main"
  ) {
    return closedPullReason;
  }
  return null;
}

function conflictingReleaseReason(openPulls, pullNumber, branch, repository) {
  const retargeted = openPulls.find(
    (candidate) =>
      candidate.head.ref === branch &&
      candidate.head.repo?.full_name === repository &&
      candidate.base.ref !== "main",
  );
  if (retargeted)
    return `Release PR #${retargeted.number} was retargeted. Restore its main base before resuming updates.`;
  const other = openPulls.find(
    (candidate) =>
      candidate.number !== pullNumber &&
      candidate.base.ref === "main" &&
      isReleasePull(candidate),
  );
  if (other)
    return `Another release PR is open: #${other.number}. It has not been changed.`;
  return null;
}

function releaseHoldReason(openPulls, pullNumber, branch, repository) {
  const conflict = conflictingReleaseReason(
    openPulls,
    pullNumber,
    branch,
    repository,
  );
  if (conflict) return conflict;
  const current = openPulls.find(
    (candidate) => candidate.number === pullNumber,
  );
  return pullNumber === undefined
    ? null
    : pullHoldReason(current, branch, repository);
}

function nextCursor({ hasNextPage, endCursor }) {
  if (!hasNextPage) return null;
  if (!endCursor)
    throw new Error("GitHub did not return the next page cursor.");
  return endCursor;
}

// Only wait for a commit this run actually replaced. Read the PR, refs,
// competing proposals and review markers together on the final page.
async function reviewComments(github, plan, current, head, previous, wait) {
  const { number } = current;
  if (current.head.sha === head)
    return {
      comments: await github.list(`issues/${number}/comments?per_page=100`),
    };
  if (!previous) return { reason: pendingHeadReason };
  const held = (reason) => ({ action: "held", reason });
  const foreign = (sha) => sha !== head && sha !== previous;
  if (foreign(current.head.sha)) return held(changedHeadReason);
  for (const ms of [0, 1000, 2000, 4000]) {
    if (ms) await wait(ms);
    const comments = [];
    let after = null;
    let openAfter = null;
    for (;;) {
      const page = await github.releaseReviewPage(
        number,
        plan.branch,
        after,
        openAfter,
      );
      const pr = page?.pullRequest;
      if (
        pr?.state !== "OPEN" ||
        pr.baseRefName !== "main" ||
        pr.headRefName !== plan.branch ||
        pr.headRepository?.nameWithOwner.toLowerCase() !==
          github.repository.toLowerCase()
      )
        return held(closedPullReason);
      if (page.main?.target?.oid !== plan.mainSha)
        return held(
          "main advanced after the release branch was updated. Let the next updater run, or rerun it manually before final review.",
        );
      if (page.branch?.target?.oid !== head || foreign(pr.headRefOid))
        return held(changedHeadReason);
      const open = page.open.nodes.map((p) => ({
        number: p.number,
        title: p.title,
        head: {
          ref: p.headRefName,
          sha: p.headRefOid,
          repo: { full_name: p.headRepository?.nameWithOwner },
        },
        base: { ref: p.baseRefName },
      }));
      const hold = conflictingReleaseReason(
        open,
        number,
        plan.branch,
        github.repository,
      );
      if (hold) return held(hold);
      if (open.some((p) => p.number === number && foreign(p.head.sha)))
        return held(changedHeadReason);
      if (pr.headRefOid === previous) break;
      const nextComments = nextCursor(pr.comments.pageInfo);
      const nextOpen = nextCursor(page.open.pageInfo);
      // Keep reading each connection's last page until both are complete.
      // Newly opened or updated PRs are at the end of the open connection.
      if (!nextComments && !nextOpen) {
        comments.push(...pr.comments.nodes);
        // Match the REST issue-comment order used for proposal marker selection.
        return {
          comments: comments.sort((a, b) =>
            Number(BigInt(a.id) - BigInt(b.id)),
          ),
        };
      }
      if (nextComments) {
        comments.push(...pr.comments.nodes);
        after = nextComments;
      }
      if (nextOpen) openAfter = nextOpen;
    }
  }
  return { reason: pendingHeadReason };
}

async function ensurePullRequest(
  github,
  plan,
  pull,
  template,
  headSha,
  currentPulls,
  previousSha,
  waitForHead,
) {
  const holdReason = releaseHoldReason(
    currentPulls ?? (await github.list("pulls?state=open&per_page=100")),
    pull?.number,
    plan.branch,
    github.repository,
  );
  if (holdReason)
    return { action: "held", reason: holdReason, reviewRequested: false };
  if (pull) {
    pull = await github.request("GET", `pulls/${pull.number}`);
    const reason = pullHoldReason(pull, plan.branch, github.repository);
    if (reason)
      return {
        action: "held",
        reason,
        pull: pull.number,
        reviewRequested: false,
      };
    if (pull.title !== plan.title) {
      await github.request("PATCH", `pulls/${pull.number}`, {
        title: plan.title,
      });
    }
  } else {
    pull = await github.request("POST", "pulls", {
      title: plan.title,
      head: plan.branch,
      base: "main",
      draft: false,
      body: initialPullBody(template),
    });
  }
  const current = await github.request("GET", `pulls/${pull.number}`);
  const reason = pullHoldReason(current, plan.branch, github.repository);
  if (reason)
    return {
      action: "held",
      reason,
      pull: current.number,
      reviewRequested: false,
    };
  const { comments, ...stopped } = await reviewComments(
    github,
    plan,
    current,
    headSha,
    previousSha,
    waitForHead,
  );
  if (!comments)
    return { pull: current.number, reviewRequested: false, ...stopped };
  const marker = `<!-- release-pr-head: ${headSha} -->`;
  const proposalMarker = `<!-- release-pr-proposal: ${hash("sha256", JSON.stringify(plan.files))} -->`;
  const suggestionsMarker = `<!-- release-pr-suggestions: ${hash("sha256", JSON.stringify(plan.generated))} -->`;
  const previous = comments.findLast((comment) =>
    comment.body?.startsWith("<!-- release-pr-head: "),
  );
  const requestReview = !previous?.body.includes(proposalMarker);
  const reviewRequested = comments.some(
    (comment) =>
      comment.body?.includes(marker) &&
      comment.body.includes(`@codex review the current head ${headSha}.`),
  );
  if (requestReview || !previous?.body.includes(suggestionsMarker)) {
    await github.request("POST", `issues/${current.number}/comments`, {
      body: reviewComment(
        plan,
        headSha,
        proposalMarker,
        suggestionsMarker,
        requestReview,
      ),
    });
  }
  return {
    pull: current.number,
    reviewRequested: reviewRequested || requestReview,
  };
}

export async function reconcileReleasePullRequest({
  repo,
  github,
  dryRun = true,
  waitForHead = delay,
}) {
  // Rebuild the plan only when main or the proposal actually moves.
  for (;;) {
    const mainSha = await branchHead(github, "main");
    const history = await readReleaseHistory(repo, mainSha, github);
    const branch = `${releaseBranchPrefix}${history.baseVersion}`;
    const openPulls = await github.list("pulls?state=open&per_page=100");
    const pull = openPulls.find(
      (candidate) =>
        candidate.head.ref === branch &&
        candidate.head.repo?.full_name === github.repository,
    );
    let holdReason = releaseHoldReason(
      openPulls,
      pull?.number,
      branch,
      github.repository,
    );
    if (!holdReason && !pull) {
      const previousPulls = await github.list(
        `pulls?state=closed&head=${encodeURIComponent(`${github.owner}:${branch}`)}&per_page=100`,
      );
      if (previousPulls.length > 0)
        holdReason = `Release PR #${previousPulls[0].number} was closed. Reopen it to resume this cycle.`;
    }

    const headSha = holdReason ? null : await branchHead(github, branch);
    const previous = headSha ? readReleaseBranch(repo, mainSha, headSha) : null;
    holdReason ??= previous?.holdReason;
    const plan = createReleasePlan(history, holdReason ? null : previous);
    if (holdReason) return { action: "held", reason: holdReason, dryRun, plan };
    if (pull && !headSha)
      throw new Error("The open release PR has no branch head.");
    if (plan.changes.length === 0)
      return {
        action: "unchanged",
        reason:
          "No changes have reached main since the current release version.",
        dryRun,
        plan,
      };
    const branchChanged =
      !headSha ||
      previous.mergeBase !== mainSha ||
      Object.entries(plan.files).some(
        ([path, content]) => repo.readFile(headSha, path) !== content,
      );
    const changed = branchChanged || pull?.title !== plan.title;
    if (dryRun)
      return {
        action: !pull ? "would-create" : changed ? "would-update" : "unchanged",
        dryRun,
        plan,
      };

    let commitSha = headSha;
    let currentPulls;
    if (branchChanged) {
      if ((await branchHead(github, "main")) !== mainSha) continue;
      const tree = await github.request("POST", "git/trees", {
        base_tree: repo.git("rev-parse", `${mainSha}^{tree}`).trim(),
        tree: Object.entries(plan.files).map(([path, content]) => ({
          path,
          mode: "100644",
          type: "blob",
          ...(content === null ? { sha: null } : { content }),
        })),
      });
      const commit = await github.request("POST", "git/commits", {
        message: plan.title,
        tree: tree.sha,
        parents: [...new Set([headSha, mainSha].filter(Boolean))],
      });
      if ((await branchHead(github, "main")) !== mainSha) continue;
      currentPulls = await github.list("pulls?state=open&per_page=100");
      const holdReason = releaseHoldReason(
        currentPulls,
        pull?.number,
        plan.branch,
        github.repository,
      );
      if (holdReason)
        return { action: "held", reason: holdReason, dryRun, plan };
      try {
        if (headSha) {
          await github.request("PATCH", `git/refs/heads/${plan.branch}`, {
            sha: commit.sha,
            force: false,
          });
        } else {
          await github.request("POST", "git/refs", {
            ref: `refs/heads/${plan.branch}`,
            sha: commit.sha,
          });
        }
      } catch (error) {
        if (
          [409, 422].includes(error.status) &&
          (await branchHead(github, plan.branch)) !== headSha
        )
          continue;
        throw error;
      }
      commitSha = commit.sha;
    }
    if ((await branchHead(github, plan.branch)) !== commitSha) continue;
    const publication = await ensurePullRequest(
      github,
      plan,
      pull,
      repo.readFile(mainSha, templatePath),
      commitSha,
      pull ? currentPulls : undefined,
      pull && branchChanged ? headSha : null,
      waitForHead,
    );
    return {
      action: !pull ? "created" : changed ? "updated" : "unchanged",
      dryRun,
      headSha: commitSha,
      ...publication,
      plan,
    };
  }
}

const releaseReviewQuery = `query ReleaseReviewPage($owner: String!, $name: String!, $number: Int!, $ref: String!, $after: String, $openAfter: String) {
  repository(owner: $owner, name: $name) {
    branch: ref(qualifiedName: $ref) { target { oid } }
    main: ref(qualifiedName: "refs/heads/main") { target { oid } }
    open: pullRequests(states: OPEN, first: 100, after: $openAfter, orderBy: { field: UPDATED_AT, direction: ASC }) {
      nodes { number title baseRefName headRefName headRefOid headRepository { nameWithOwner } }
      pageInfo { hasNextPage endCursor }
    }
    pullRequest(number: $number) {
      state baseRefName headRefName headRefOid headRepository { nameWithOwner }
      comments(first: 100, after: $after) {
        nodes { body id: fullDatabaseId }
        pageInfo { hasNextPage endCursor }
      }
    }
  }
}`;

export function createGitHubClient(
  repository,
  token,
  fetcher = fetch,
  sleep = delay,
) {
  const apiRoot = `https://api.github.com/repos/${repository}/`;
  async function responseFor(method, path, body, reviewQuery = false) {
    const read = method === "GET" || reviewQuery;
    const url = reviewQuery
      ? "https://api.github.com/graphql"
      : `${apiRoot}${path}`;
    for (let retry = 0; ; retry += 1) {
      const retryDelay = 1000 * 2 ** retry;
      let response;
      try {
        response = await fetcher(url, {
          method,
          headers: {
            Accept: "application/vnd.github+json",
            Authorization: `Bearer ${token}`,
            "X-GitHub-Api-Version": "2026-03-10",
            "Content-Type": "application/json",
          },
          body: body === undefined ? undefined : JSON.stringify(body),
        });
        if (response.ok) {
          return { data: await response.json(), headers: response.headers };
        }
      } catch (error) {
        if (!read || retry >= 2 || error instanceof SyntaxError) throw error;
        await sleep(retryDelay);
        continue;
      }
      const retryAfter = response.headers.get("retry-after");
      const minimumDelay = /^\d+$/u.test(retryAfter ?? "")
        ? Number(retryAfter) * 1000
        : Date.parse(retryAfter ?? "") - Date.now() || 0;
      if (
        read &&
        retry < 2 &&
        [500, 502, 503, 504].includes(response.status) &&
        minimumDelay <= retryDelay
      ) {
        await response.body?.cancel().catch(() => undefined);
        await sleep(retryDelay);
        continue;
      }
      const error = new Error(
        `GitHub ${method} ${path} failed with HTTP ${response.status}.` +
          (retryAfter ? ` Retry-After: ${retryAfter}.` : ""),
      );
      error.status = response.status;
      throw error;
    }
  }
  return {
    repository,
    owner: repository.split("/")[0],
    repositoryUrl: `https://github.com/${repository}`,
    async request(method, path, body) {
      return (await responseFor(method, path, body)).data;
    },
    async releaseReviewPage(number, branch, after, openAfter) {
      const [owner, name] = repository.split("/");
      const { data: result } = await responseFor(
        "POST",
        "graphql",
        {
          query: releaseReviewQuery,
          variables: {
            owner,
            name,
            number,
            ref: `refs/heads/${branch}`,
            after,
            openAfter,
          },
        },
        true,
      );
      if (result.errors?.length)
        throw new Error(
          `GitHub release review query failed: ${result.errors.map((e) => e.message).join("; ")}`,
        );
      return result.data.repository;
    },
    async list(path) {
      const items = [];
      for (let page = 1; ; page += 1) {
        const response = await responseFor(
          "GET",
          `${path}${path.includes("?") ? "&" : "?"}page=${page}`,
        );
        items.push(...response.data);
        if (!response.headers.get("link")?.includes('rel="next"')) return items;
      }
    },
  };
}

if (isMain(import.meta.url)) {
  const directory = fileURLToPath(new URL("../../..", import.meta.url));
  const repository = process.env.GITHUB_REPOSITORY ?? "openai/codex-security";
  const token =
    process.env.GH_TOKEN ??
    execFileSync("gh", ["auth", "token"], {
      encoding: "utf8",
      stdio: ["pipe", "pipe", "pipe"],
    }).trim();
  const result = await reconcileReleasePullRequest({
    repo: createGitRepository(directory),
    github: createGitHubClient(repository, token),
    dryRun: process.env.RELEASE_PR_DRY_RUN !== "false",
  });
  console.log(JSON.stringify(result, null, 2));
}