diff --git a/.github/workflows/ipr-agreement.yml b/.github/workflows/ipr-agreement.yml index a438684199f..34c38d8dd45 100644 --- a/.github/workflows/ipr-agreement.yml +++ b/.github/workflows/ipr-agreement.yml @@ -11,39 +11,40 @@ permissions: pull-requests: write statuses: write -concurrency: - # Per-repo serialization for adcp's own signature writes. GitHub Actions - # concurrency is scoped per-repo, so this does NOT cross-serialize against - # downstream AAO repos using the cross-repo callable workflow — that - # contention is handled by the rebase-retry loop in - # `scripts/ipr/check-and-record.mjs`. - group: adcp-ipr-signature-write - cancel-in-progress: false - # cancel-in-progress: false alone still permits only one pending run, so a - # burst evicts pending checks for unrelated PRs. `queue: max` keeps up to - # 100 pending runs so each PR's check still runs. - # GitHub added this option on 2026-05-07; older validators may not know it. - # https://github.blog/changelog/2026-05-07-github-actions-concurrency-groups-now-allow-larger-queues/ - # https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency#example-queueing-multiple-pending-runs - queue: max +# Concurrency is set per job, not per workflow. +# +# `check` (pull_request_target) only reads the ledger and posts the +# `IPR Policy / Signature` status; it never writes. It gets a per-PR group so +# a newer push cancels a superseded check, and unrelated PRs run in parallel. +# It used to share the repo-wide write group, so every PR's check waited behind +# every other PR's check *and* its runner wait. On 2026-10-15 that queue +# completed one check every 20-45 minutes and blocked every merge for hours. +# +# `record` (sign-phrase comments) writes `signatures/ipr-signatures.json` and +# keeps the repo-wide `adcp-ipr-signature-write` group. Only comments that can +# contain the sign phrase start that job, so other PR comments no longer queue +# in the group. A check that races a signature is resolved in +# `scripts/ipr/check-and-record.mjs`: the check re-reads origin/main after +# posting pending, and the write re-marks the latest PR head after its push. +# +# GitHub Actions concurrency is scoped per repo, so neither group serializes +# against downstream AAO repos using the cross-repo callable workflow. The +# rebase-retry loop in `scripts/ipr/check-and-record.mjs` handles that +# contention. jobs: check: + if: github.event_name == 'pull_request_target' runs-on: ubuntu-latest - # Skip issue comments that can't contain the sign phrase. The script - # re-validates the exact match; this just avoids spinning up the runner for - # every unrelated comment. - if: >- - github.event_name == 'pull_request_target' || - (github.event_name == 'issue_comment' && - github.event.issue.pull_request != null && - contains(github.event.comment.body, 'I have read the IPR Policy')) + concurrency: + group: adcp-ipr-check-pr-${{ github.event.pull_request.number }} + cancel-in-progress: true steps: # The default GITHUB_TOKEN authenticates as github-actions[bot], which # is not in the IPR-signatures ruleset bypass list — pushes to main get # rejected by branch protection (GH013). The aao-ipr-bot App is in the # bypass list, so we mint an installation token from it and use that - # for both the checkout's persisted credentials (git push) and the + # for both the checkout's persisted credentials (git fetch/push) and the # script's API calls. Same pattern as ipr-check-callable.yml. - name: Mint AAO IPR Bot installation token id: app-token @@ -67,6 +68,55 @@ jobs: with: node-version: '24' + - name: Check IPR signature + env: + GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} + run: node scripts/ipr/check-and-record.mjs + + record: + # Skip issue comments that can't contain the sign phrase. The script + # re-validates the exact match; this keeps unrelated comments from starting + # a runner. Because the group is on this job rather than the workflow, a + # comment that fails this `if` is skipped instead of waiting in the group. + if: >- + github.event_name == 'issue_comment' && + github.event.issue.pull_request != null && + contains(github.event.comment.body, 'I have read the IPR Policy') + runs-on: ubuntu-latest + concurrency: + group: adcp-ipr-signature-write + cancel-in-progress: false + # cancel-in-progress: false alone still permits only one pending job, so + # a burst evicts pending signature writes. `queue: max` keeps up to 100 + # pending. GitHub added this option on 2026-05-07; older validators may + # not know it. + # https://github.blog/changelog/2026-05-07-github-actions-concurrency-groups-now-allow-larger-queues/ + # https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency#example-queueing-multiple-pending-runs + queue: max + steps: + # See the `check` job for why this uses the aao-ipr-bot App token. + - name: Mint AAO IPR Bot installation token + id: app-token + uses: actions/create-github-app-token@v3.2.0 + with: + app-id: ${{ secrets.IPR_APP_ID }} + private-key: ${{ secrets.IPR_APP_PRIVATE_KEY }} + owner: adcontextprotocol + repositories: adcp + + - name: Checkout default branch + uses: actions/checkout@v7.0.1 + with: + ref: main + fetch-depth: 1 + token: ${{ steps.app-token.outputs.token }} + persist-credentials: true + + - name: Setup Node + uses: actions/setup-node@v7 + with: + node-version: '24' + - name: Check and record IPR signature env: GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} diff --git a/.github/workflows/ipr-check-callable.yml b/.github/workflows/ipr-check-callable.yml index cd74a1d198e..a5cef2fa289 100644 --- a/.github/workflows/ipr-check-callable.yml +++ b/.github/workflows/ipr-check-callable.yml @@ -38,31 +38,24 @@ on: required: true description: 'PEM private key for the AAO IPR Bot (org-level secret)' -# Per-repo serialization. GitHub Actions concurrency is scoped per-repo, so -# this group only serializes signatures landing from THIS caller repo. The -# rebase-retry loop in `scripts/ipr/check-and-record.mjs` handles contention -# across sibling AAO repos pushing to the same JSON file. -concurrency: - group: adcp-ipr-signature-write - cancel-in-progress: false - # cancel-in-progress: false alone still permits only one pending run, so a - # burst evicts pending checks for unrelated PRs. `queue: max` keeps up to - # 100 pending runs so each PR's check still runs. - # GitHub added this option on 2026-05-07; older validators may not know it. - # https://github.blog/changelog/2026-05-07-github-actions-concurrency-groups-now-allow-larger-queues/ - # https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency#example-queueing-multiple-pending-runs - queue: max +# Concurrency is set per job, mirroring adcp's own ipr-agreement.yml (see the +# comment there for the incident that motivated it): +# - `check` (pull_request_target) only reads the ledger and posts the status. +# It gets a per-PR group so unrelated PRs never wait behind each other. +# - `record` (sign-phrase comments) writes the ledger and keeps the per-repo +# `adcp-ipr-signature-write` group. +# GitHub Actions concurrency is scoped per-repo (the caller's repo here), so +# the write group only serializes signatures landing from THIS caller repo. +# The rebase-retry loop in `scripts/ipr/check-and-record.mjs` handles +# contention across sibling AAO repos pushing to the same JSON file. jobs: check: + if: github.event_name == 'pull_request_target' runs-on: ubuntu-latest - # Skip issue comments that can't contain the sign phrase. Same filter as - # adcp's own workflow — avoids spinning up a runner for every comment. - if: >- - github.event_name == 'pull_request_target' || - (github.event_name == 'issue_comment' && - github.event.issue.pull_request != null && - contains(github.event.comment.body, 'I have read the IPR Policy')) + concurrency: + group: ipr-check-pr-${{ github.event.pull_request.number }} + cancel-in-progress: true # SECURITY: do not add a checkout of the caller repo to this job. The # App token + caller's GITHUB_TOKEN both live in this job's env; a step # that runs PR-head code (e.g. `npm ci`, build scripts, anything that @@ -103,3 +96,56 @@ jobs: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} LEDGER_DIR: ${{ github.workspace }}/.ipr-ledger run: node ${{ github.workspace }}/.ipr-ledger/scripts/ipr/check-and-record.mjs + + record: + # Skip issue comments that can't contain the sign phrase. Same filter as + # adcp's own workflow — avoids spinning up a runner for every comment, and + # because the group is on this job, unrelated comments never wait in it. + if: >- + github.event_name == 'issue_comment' && + github.event.issue.pull_request != null && + contains(github.event.comment.body, 'I have read the IPR Policy') + runs-on: ubuntu-latest + concurrency: + group: adcp-ipr-signature-write + cancel-in-progress: false + # cancel-in-progress: false alone still permits only one pending job, so + # a burst evicts pending signature writes. `queue: max` keeps up to 100 + # pending. GitHub added this option on 2026-05-07; older validators may + # not know it. + # https://github.blog/changelog/2026-05-07-github-actions-concurrency-groups-now-allow-larger-queues/ + # https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency#example-queueing-multiple-pending-runs + queue: max + # SECURITY: same constraint as `check` — never check out or run caller-repo + # code in this job. + steps: + - name: Mint AAO IPR Bot installation token (scoped to adcp) + id: app-token + uses: actions/create-github-app-token@v3.2.0 + with: + app-id: ${{ secrets.IPR_APP_ID }} + private-key: ${{ secrets.IPR_APP_PRIVATE_KEY }} + owner: adcontextprotocol + repositories: adcp + + - name: Checkout central IPR ledger + uses: actions/checkout@v7.0.1 + with: + repository: adcontextprotocol/adcp + ref: main + token: ${{ steps.app-token.outputs.token }} + path: .ipr-ledger + fetch-depth: 1 + persist-credentials: true + + - name: Setup Node + uses: actions/setup-node@v7 + with: + node-version: '24' + + - name: Check and record IPR signature + env: + # See the `check` job for which token is used for what. + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + LEDGER_DIR: ${{ github.workspace }}/.ipr-ledger + run: node ${{ github.workspace }}/.ipr-ledger/scripts/ipr/check-and-record.mjs diff --git a/governance/ipr-bot-setup.md b/governance/ipr-bot-setup.md index b650c3127c2..849cdee31d1 100644 --- a/governance/ipr-bot-setup.md +++ b/governance/ipr-bot-setup.md @@ -56,7 +56,12 @@ The `.pem` file should not be checked into any repo. After generation, paste its ### `adcp` — local flow -`.github/workflows/ipr-agreement.yml` runs in adcp on PR + comment events. It checks out `main` with the default `GITHUB_TOKEN`, runs `scripts/ipr/check-and-record.mjs`, and commits + pushes signature updates back to adcp. No App involvement. +`.github/workflows/ipr-agreement.yml` runs in adcp on PR + comment events. It mints an AAO IPR Bot installation token (the default `GITHUB_TOKEN` is not in the ledger ruleset's bypass list), checks out `main` with it, and runs `scripts/ipr/check-and-record.mjs`. It has two jobs: + +- `check` (`pull_request_target`) reads the ledger and posts the `IPR Policy / Signature` status. It never writes, so it uses a per-PR concurrency group that cancels superseded checks. PRs never wait behind each other. +- `record` (comments containing the sign phrase) records new signatures and pushes them to adcp. It keeps the repo-wide `adcp-ipr-signature-write` group. + +A push that races a signature is resolved in the script. The check re-reads `origin/main` after posting `pending`, and the write re-marks the PR's latest head after its push. Whichever finishes last, the head ends up `success`. A failed re-read leaves the status `pending` (fail closed). ### Downstream — cross-repo flow @@ -67,7 +72,7 @@ Each downstream repo has a tiny caller workflow (~15 lines) that invokes the reu 3. Runs `scripts/ipr/check-and-record.mjs` with `LEDGER_DIR=.ipr-ledger`. The script reads/writes signatures there; `git push` from inside the directory uses the installation token configured by the checkout step. 4. API calls back to the event repo (comments, status check) use the caller repo's default `GITHUB_TOKEN` — no cross-repo write required for those. -Per-repo concurrency groups (`adcp-ipr-signature-write` in each repo) serialize signature writes within each repo. GitHub Actions concurrency is scoped per-repo, so the cross-repo race is handled by a rebase-retry loop in the script — when a push fails because adcp's main moved, the script pulls with `--rebase` and retries up to 5 times. +The callable uses the same `check` / `record` split as adcp's own workflow. Per-repo concurrency groups (`adcp-ipr-signature-write` in each repo, on the `record` job only) serialize signature writes within each repo. GitHub Actions concurrency is scoped per-repo, so the cross-repo race is handled by a rebase-retry loop in the script — when a push fails because adcp's main moved, the script pulls with `--rebase` and retries up to 5 times. ## Rotation diff --git a/scripts/ipr/check-and-record.mjs b/scripts/ipr/check-and-record.mjs index b471ae4e10a..79df28f75cd 100644 --- a/scripts/ipr/check-and-record.mjs +++ b/scripts/ipr/check-and-record.mjs @@ -27,14 +27,17 @@ import fs from 'node:fs'; import { execFileSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; import { GitHubClient } from './github.mjs'; import { isLedgerRemoteAllowed } from './ledger-remote.mjs'; import { SIGN_PHRASE, + SIGNATURES_PATH, addSignature, findSignature, hasSigned, isSignPhrase, + parseSignatures, readSignatures, writeSignatures, } from './signatures.mjs'; @@ -141,6 +144,35 @@ function commitSignaturesChange(message, branch = 'main') { throw new Error('Failed to push signature update after retries'); } +// Read the ledger at the current tip of origin/main rather than the checkout. +// The check-only job (pull_request_target) does not share a concurrency group +// with the signature-write job, so a signature can land on main after this +// job's checkout. Returns null when the fetch fails so callers fail closed +// (leave the status pending) instead of guessing. +function readLatestSignatures(branch = 'main') { + try { + git(['fetch', '--depth=1', 'origin', branch]); + return parseSignatures(git(['show', `FETCH_HEAD:${SIGNATURES_PATH}`])); + } catch (err) { + console.warn(`Could not re-read ledger from origin/${branch}: ${err.message ?? err}`); + return null; + } +} + +// The handlers reach the ledger only through this object so tests can drive +// them without a git checkout. +export function createGitLedger() { + return { + read: () => readSignatures(LEDGER_DIR), + readLatest: () => readLatestSignatures(), + write: (data) => writeSignatures(data, LEDGER_DIR), + commit: (message) => { + configureGitIdentity(); + return commitSignaturesChange(message); + }, + }; +} + async function setStatus(gh, eventRepo, sha, { state, description }) { if (!sha) return; await gh.createStatus(eventRepo.owner, eventRepo.repo, sha, { @@ -193,7 +225,7 @@ function confirmCommentBody(login) { ].join('\n'); } -async function handleIssueComment(gh, event, eventRepo) { +export async function handleIssueComment(gh, event, eventRepo, ledger = createGitLedger()) { const comment = event.comment; const issue = event.issue; if (!issue?.pull_request) { @@ -231,7 +263,7 @@ async function handleIssueComment(gh, event, eventRepo) { return; } - const signatures = readSignatures(LEDGER_DIR); + const signatures = ledger.read(); if (hasSigned(signatures, prAuthor.id)) { const existing = findSignature(signatures, prAuthor.id); console.log(`${prAuthor.login} already signed on ${existing.created_at} — no-op.`); @@ -256,10 +288,9 @@ async function handleIssueComment(gh, event, eventRepo) { if (!added) { throw new Error(`Unexpected: ${prAuthor.login} already signed after hasSigned check`); } - writeSignatures(next, LEDGER_DIR); + ledger.write(next); - configureGitIdentity(); - const committed = commitSignaturesChange( + const committed = ledger.commit( `chore(ipr): record signature for @${prAuthor.login} (${eventRepo.owner}/${eventRepo.repo}#${issue.number})`, ); if (!committed) { @@ -267,13 +298,28 @@ async function handleIssueComment(gh, event, eventRepo) { } await ensureComment(gh, eventRepo, issue.number, CONFIRM_COMMENT_MARKER, confirmCommentBody(prAuthor.login)); - await setStatus(gh, eventRepo, headSha, { - state: 'success', - description: `@${prAuthor.login} signed just now`, - }); + + // A check job for a push that raced this signature may have read the ledger + // before the push above landed and marked its head pending. Re-read the PR + // head now that the signature is on main and mark it as well. Together with + // the post-pending re-read in handlePullRequestTarget, every interleaving + // ends with the latest head marked success. + const shas = new Set([headSha]); + try { + const latest = await gh.getPullRequest(eventRepo.owner, eventRepo.repo, issue.number); + if (latest?.head?.sha) shas.add(latest.head.sha); + } catch (err) { + console.warn(`Could not re-read PR head after recording: ${err.message ?? err}`); + } + for (const sha of shas) { + await setStatus(gh, eventRepo, sha, { + state: 'success', + description: `@${prAuthor.login} signed just now`, + }); + } } -async function handlePullRequestTarget(gh, event, eventRepo) { +export async function handlePullRequestTarget(gh, event, eventRepo, ledger = createGitLedger()) { const pr = event.pull_request; if (!pr) { console.log('No pull_request payload — skipping.'); @@ -291,23 +337,33 @@ async function handlePullRequestTarget(gh, event, eventRepo) { return; } - const signatures = readSignatures(LEDGER_DIR); - if (hasSigned(signatures, prAuthor.id)) { - const existing = findSignature(signatures, prAuthor.id); - await setStatus(gh, eventRepo, headSha, { - state: 'success', - description: `@${prAuthor.login} signed on ${existing.created_at.slice(0, 10)}`, - }); - return; - } + if (await setStatusIfSigned(gh, eventRepo, headSha, prAuthor, ledger.read())) return; await setStatus(gh, eventRepo, headSha, { state: 'pending', description: `Awaiting IPR Policy signature from @${prAuthor.login}`, }); + + // This job runs outside the signature-write concurrency group, so the + // checkout can predate a signature the author recorded while this job was + // starting. Re-read origin/main *after* posting pending: a signature that + // landed meanwhile overwrites the pending status here, and the write job + // re-marks the latest head after its push to cover the opposite order. + if (await setStatusIfSigned(gh, eventRepo, headSha, prAuthor, ledger.readLatest())) return; + await ensureComment(gh, eventRepo, pr.number, CLAIM_COMMENT_MARKER, requestCommentBody(prAuthor)); } +async function setStatusIfSigned(gh, eventRepo, headSha, prAuthor, signatures) { + if (!signatures || !hasSigned(signatures, prAuthor.id)) return false; + const existing = findSignature(signatures, prAuthor.id); + await setStatus(gh, eventRepo, headSha, { + state: 'success', + description: `@${prAuthor.login} signed on ${existing.created_at.slice(0, 10)}`, + }); + return true; +} + async function main() { const gh = new GitHubClient(); const eventName = process.env.GITHUB_EVENT_NAME; @@ -326,7 +382,21 @@ async function main() { } } -main().catch((err) => { - console.error(err.stack || err.message); - process.exit(1); -}); +// Run only when invoked as a script so tests can import the handlers. Compare +// real paths: Node resolves symlinks for the main module's import.meta.url but +// not for argv[1], and a false negative here would silently skip the status. +function invokedDirectly() { + if (!process.argv[1]) return false; + try { + return fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url)); + } catch { + return false; + } +} + +if (invokedDirectly()) { + main().catch((err) => { + console.error(err.stack || err.message); + process.exit(1); + }); +} diff --git a/scripts/ipr/signatures.mjs b/scripts/ipr/signatures.mjs index 0dbc15419a0..96f10d0b1b0 100644 --- a/scripts/ipr/signatures.mjs +++ b/scripts/ipr/signatures.mjs @@ -15,9 +15,12 @@ export function readSignatures(repoRoot = process.cwd()) { if (!fs.existsSync(full)) { return { signedContributors: [] }; } - const raw = fs.readFileSync(full, 'utf8'); + return parseSignatures(fs.readFileSync(full, 'utf8')); +} + +export function parseSignatures(raw) { const parsed = JSON.parse(raw); - if (!Array.isArray(parsed.signedContributors)) { + if (!Array.isArray(parsed?.signedContributors)) { throw new Error(`Malformed ${SIGNATURES_PATH}: missing signedContributors array`); } return parsed; diff --git a/tests/ipr-check-and-record.test.mjs b/tests/ipr-check-and-record.test.mjs new file mode 100644 index 00000000000..7afd2d747ad --- /dev/null +++ b/tests/ipr-check-and-record.test.mjs @@ -0,0 +1,209 @@ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, it, expect, vi } from 'vitest'; +import YAML from 'yaml'; +import { handleIssueComment, handlePullRequestTarget } from '../scripts/ipr/check-and-record.mjs'; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const eventRepo = { owner: 'adcontextprotocol', repo: 'adcp' }; +const author = { id: 101, login: 'contributor', type: 'User' }; +const signedLedger = { + signedContributors: [ + { name: 'contributor', id: 101, created_at: '2026-01-02T00:00:00Z', method: 'pr_comment' }, + ], +}; +const emptyLedger = { signedContributors: [] }; + +function fakeGitHub({ pr } = {}) { + const statuses = []; + const comments = []; + return { + statuses, + comments, + getPullRequest: vi.fn(async () => pr), + async *paginate() { + for (const c of comments) yield c; + }, + createIssueComment: vi.fn(async (_o, _r, _n, body) => { + const c = { id: comments.length + 1, body }; + comments.push(c); + return c; + }), + updateIssueComment: vi.fn(async (_o, _r, id, body) => { + const c = comments.find((x) => x.id === id); + c.body = body; + return c; + }), + createStatus: vi.fn(async (_o, _r, sha, { state, context }) => { + statuses.push({ sha, state, context }); + }), + }; +} + +function fakeLedger({ checkout, latest }) { + return { + read: vi.fn(() => checkout), + readLatest: vi.fn(() => latest), + write: vi.fn(), + commit: vi.fn(() => true), + }; +} + +const prEvent = { pull_request: { number: 42, user: author, head: { sha: 'head-1' } } }; + +describe('handlePullRequestTarget (check-only path)', () => { + it('passes an already-signed author from the checkout without re-fetching', async () => { + const gh = fakeGitHub(); + const ledger = fakeLedger({ checkout: signedLedger, latest: null }); + await handlePullRequestTarget(gh, prEvent, eventRepo, ledger); + expect(gh.statuses).toEqual([{ sha: 'head-1', state: 'success', context: 'IPR Policy / Signature' }]); + expect(ledger.readLatest).not.toHaveBeenCalled(); + expect(ledger.commit).not.toHaveBeenCalled(); + }); + + it('never writes the ledger', async () => { + const gh = fakeGitHub(); + const ledger = fakeLedger({ checkout: emptyLedger, latest: emptyLedger }); + await handlePullRequestTarget(gh, prEvent, eventRepo, ledger); + expect(ledger.write).not.toHaveBeenCalled(); + expect(ledger.commit).not.toHaveBeenCalled(); + }); + + it('re-reads origin/main after posting pending and flips to success when a signature landed meanwhile', async () => { + const gh = fakeGitHub(); + const ledger = fakeLedger({ checkout: emptyLedger, latest: signedLedger }); + await handlePullRequestTarget(gh, prEvent, eventRepo, ledger); + expect(gh.statuses.map((s) => s.state)).toEqual(['pending', 'success']); + expect(gh.comments).toHaveLength(0); + }); + + it('stays pending and requests a signature when the author has not signed', async () => { + const gh = fakeGitHub(); + const ledger = fakeLedger({ checkout: emptyLedger, latest: emptyLedger }); + await handlePullRequestTarget(gh, prEvent, eventRepo, ledger); + expect(gh.statuses.map((s) => s.state)).toEqual(['pending']); + expect(gh.comments).toHaveLength(1); + expect(gh.comments[0].body).toContain(''); + }); + + it('fails closed (pending) when the fresh re-read fails', async () => { + const gh = fakeGitHub(); + const ledger = fakeLedger({ checkout: emptyLedger, latest: null }); + await handlePullRequestTarget(gh, prEvent, eventRepo, ledger); + expect(gh.statuses.map((s) => s.state)).toEqual(['pending']); + }); + + it('auto-passes bot authors', async () => { + const gh = fakeGitHub(); + const ledger = fakeLedger({ checkout: emptyLedger, latest: emptyLedger }); + const event = { pull_request: { number: 7, user: { id: 9, login: 'renovate[bot]', type: 'Bot' }, head: { sha: 'b' } } }; + await handlePullRequestTarget(gh, event, eventRepo, ledger); + expect(gh.statuses.map((s) => s.state)).toEqual(['success']); + expect(ledger.read).not.toHaveBeenCalled(); + }); +}); + +describe('handleIssueComment (signature-write path)', () => { + const commentEvent = { + issue: { number: 42, pull_request: {} }, + comment: { + id: 555, + body: 'I have read the IPR Policy', + user: author, + created_at: '2026-10-15T10:00:00Z', + html_url: 'https://github.com/adcontextprotocol/adcp/pull/42#issuecomment-555', + }, + }; + + it('records the signature and marks both the commented head and a newer head success', async () => { + const gh = fakeGitHub(); + // First lookup (before the write) sees head-1; the re-read after the push + // sees head-2, a push that raced the signature. + gh.getPullRequest + .mockResolvedValueOnce({ user: author, head: { sha: 'head-1' } }) + .mockResolvedValueOnce({ user: author, head: { sha: 'head-2' } }); + const ledger = fakeLedger({ checkout: emptyLedger, latest: null }); + await handleIssueComment(gh, commentEvent, eventRepo, ledger); + + expect(ledger.write).toHaveBeenCalledTimes(1); + const written = ledger.write.mock.calls[0][0]; + expect(written.signedContributors.map((c) => c.id)).toEqual([101]); + expect(ledger.commit).toHaveBeenCalledTimes(1); + const success = gh.statuses.filter((s) => s.state === 'success').map((s) => s.sha); + expect(success).toEqual(['head-1', 'head-2']); + }); + + it('marks the head once when it has not moved', async () => { + const gh = fakeGitHub({ pr: { user: author, head: { sha: 'head-1' } } }); + const ledger = fakeLedger({ checkout: emptyLedger, latest: null }); + await handleIssueComment(gh, commentEvent, eventRepo, ledger); + expect(gh.statuses.map((s) => s.sha)).toEqual(['head-1']); + }); + + it('ignores a sign phrase from someone other than the PR author', async () => { + const gh = fakeGitHub({ pr: { user: { id: 202, login: 'owner', type: 'User' }, head: { sha: 'h' } } }); + const ledger = fakeLedger({ checkout: emptyLedger, latest: null }); + await handleIssueComment(gh, commentEvent, eventRepo, ledger); + expect(ledger.write).not.toHaveBeenCalled(); + expect(gh.statuses).toHaveLength(0); + }); +}); + +describe('CLI entry point', () => { + // The workflows run the script directly. If the import guard ever stopped + // recognizing that, the job would exit 0 without posting a status and the + // required check would sit pending forever. + it('runs main() when invoked as a script', () => { + const env = { ...process.env }; + delete env.GITHUB_TOKEN; + delete env.GH_TOKEN; + const res = spawnSync(process.execPath, [path.join(repoRoot, 'scripts/ipr/check-and-record.mjs')], { + cwd: os.tmpdir(), + env, + encoding: 'utf8', + }); + expect(res.status).toBe(1); + expect(res.stderr).toContain('GitHubClient requires a token'); + }); +}); + +// The required `IPR Policy / Signature` status blocks every merge, so the +// workflow shape is load-bearing: check-only runs must not wait behind each +// other, and only sign-phrase comments may enter the write group. +describe.each([ + ['.github/workflows/ipr-agreement.yml'], + ['.github/workflows/ipr-check-callable.yml'], +])('%s concurrency shape', (rel) => { + const wf = YAML.parse(fs.readFileSync(path.join(repoRoot, rel), 'utf8')); + + it('has no workflow-level concurrency group', () => { + expect(wf.concurrency).toBeUndefined(); + }); + + it('runs the check job per PR, cancelling superseded checks', () => { + const { check } = wf.jobs; + expect(check.if).toBe("github.event_name == 'pull_request_target'"); + expect(check.concurrency.group).toContain('${{ github.event.pull_request.number }}'); + expect(check.concurrency.group).not.toContain('signature-write'); + expect(check.concurrency['cancel-in-progress']).toBe(true); + }); + + it('serializes only sign-phrase comments in the write group', () => { + const { record } = wf.jobs; + expect(record.if).toContain("github.event_name == 'issue_comment'"); + expect(record.if).toContain('github.event.issue.pull_request != null'); + expect(record.if).toContain("contains(github.event.comment.body, 'I have read the IPR Policy')"); + expect(record.concurrency).toEqual({ + group: 'adcp-ipr-signature-write', + 'cancel-in-progress': false, + queue: 'max', + }); + }); + + it('has exactly the check and record jobs', () => { + expect(Object.keys(wf.jobs).sort()).toEqual(['check', 'record']); + }); +});