diff --git a/.github/workflows/ipr-agreement.yml b/.github/workflows/ipr-agreement.yml index 34c38d8dd45..a602e90106f 100644 --- a/.github/workflows/ipr-agreement.yml +++ b/.github/workflows/ipr-agreement.yml @@ -29,8 +29,9 @@ permissions: # # 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. +# retry loop in `scripts/ipr/check-and-record.mjs` handles that contention: on +# a rejected push it resets to the new main, re-applies the signature, and +# retries with backoff. jobs: check: diff --git a/.github/workflows/ipr-check-callable.yml b/.github/workflows/ipr-check-callable.yml index a5cef2fa289..534aaf5b029 100644 --- a/.github/workflows/ipr-check-callable.yml +++ b/.github/workflows/ipr-check-callable.yml @@ -46,8 +46,9 @@ on: # `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. +# The retry loop in `scripts/ipr/check-and-record.mjs` handles contention +# across sibling AAO repos pushing to the same JSON file: on a rejected push +# it resets to the new main, re-applies the signature, and retries with backoff. jobs: check: diff --git a/governance/ipr-bot-setup.md b/governance/ipr-bot-setup.md index 849cdee31d1..10ff9cbef74 100644 --- a/governance/ipr-bot-setup.md +++ b/governance/ipr-bot-setup.md @@ -72,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. -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. +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 script handles the cross-repo race. When a push fails because adcp's main moved, the script resets to the new main and applies the signature again, skipping the write if that author is already recorded. It retries up to 5 times with exponential backoff. It does not rebase, because two signatures appended at the same time edit the same lines of the JSON file and would conflict. ## Rotation diff --git a/scripts/ipr/check-and-record.mjs b/scripts/ipr/check-and-record.mjs index 79df28f75cd..6aa5c729f75 100644 --- a/scripts/ipr/check-and-record.mjs +++ b/scripts/ipr/check-and-record.mjs @@ -81,39 +81,30 @@ function parseRepoSlug(slug) { return { owner, repo }; } -function git(args, opts = {}) { +function git(args, { cwd = LEDGER_DIR, ...opts } = {}) { return execFileSync('git', args, { - cwd: LEDGER_DIR, + cwd, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8', ...opts, }); } -function gitStatusPorcelain(pathname) { - return execFileSync('git', ['status', '--porcelain', pathname], { - cwd: LEDGER_DIR, - encoding: 'utf8', - }).trim(); -} - -function configureGitIdentity() { - git(['config', 'user.name', 'github-actions[bot]']); - git(['config', 'user.email', '41898282+github-actions[bot]@users.noreply.github.com']); +function configureGitIdentity(dir) { + git(['config', 'user.name', 'github-actions[bot]'], { cwd: dir }); + git(['config', 'user.email', '41898282+github-actions[bot]@users.noreply.github.com'], { cwd: dir }); } -// The ledger-remote guard protects the push target. GitHub Actions concurrency -// is per-repo, so the rebase-retry loop is the actual serialization mechanism -// against contention from sibling AAO repos all writing to the same ledger. -// Asserting the remote URL here removes a class of "future workflow edit -// changes which checkout backs LEDGER_DIR" footguns. The accept/reject matrix -// lives in tests/ipr-ledger-remote.test.mjs. -function assertLedgerRemote() { +// The ledger-remote guard protects the push target. Asserting the remote URL +// here removes a class of "future workflow edit changes which checkout backs +// LEDGER_DIR" footguns. The accept/reject matrix lives in +// tests/ipr-ledger-remote.test.mjs. +function assertLedgerRemote(dir) { let url; try { - url = git(['remote', 'get-url', 'origin']).trim(); + url = git(['remote', 'get-url', 'origin'], { cwd: dir }).trim(); } catch (err) { - throw new Error(`LEDGER_DIR ${LEDGER_DIR} has no \`origin\` remote: ${err.message ?? err}`); + throw new Error(`LEDGER_DIR ${dir} has no \`origin\` remote: ${err.message ?? err}`); } if (!isLedgerRemoteAllowed(url)) { throw new Error( @@ -122,26 +113,115 @@ function assertLedgerRemote() { } } -function commitSignaturesChange(message, branch = 'main') { - if (!gitStatusPorcelain('signatures/ipr-signatures.json')) return false; - assertLedgerRemote(); - git(['add', 'signatures/ipr-signatures.json']); - git(['commit', '-m', message]); - // Five attempts handles realistic contention from up to ~5 AAO repos - // writing to the same JSON file with no cross-repo concurrency lock. - for (let attempt = 0; attempt < 5; attempt += 1) { +// GitHub Actions concurrency groups are per repo. The write group serializes +// signature writes within one repo, but every AAO repo that calls +// ipr-check-callable.yml writes the same ledger, so writes from different repos +// can still race. This retry loop handles that race. Five attempts covers +// realistic contention from about five repos. +export const RECORD_MAX_ATTEMPTS = 5; +const RECORD_BASE_DELAY_MS = 1000; + +// Exponential backoff plus jitter, so two writers that collided once do not +// retry on the same schedule. +function defaultBackoff(retry) { + return RECORD_BASE_DELAY_MS * 2 ** (retry - 1) + Math.floor(Math.random() * RECORD_BASE_DELAY_MS); +} + +function sleepMs(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * Append `entry` to the ledger and push it, retrying when the push is rejected. + * + * Each attempt applies the signature to a fresh copy of the ledger instead of + * replaying a commit. Two signatures appended to the same JSON array at the + * same time edit the same lines, so a rebase conflicts. After a rejected push, + * the next attempt resets to the new remote head, re-reads the ledger, and adds + * the entry again. If the author is already on the fresh ledger (another run + * recorded them first), it returns without writing. + * + * `ops` is the git-facing surface: + * sync() move the checkout to the remote head + * read()/write() the ledger file + * commit(message) returns false when there is nothing to commit + * push() throws on rejection + * + * Resolves to `{ recorded: true }` or `{ recorded: false, existing }`. + */ +export async function recordSignatureWithRetry(ops, entry, message, { + maxAttempts = RECORD_MAX_ATTEMPTS, + backoff = defaultBackoff, + sleep = sleepMs, +} = {}) { + let lastErr; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + if (attempt > 1) { + await sleep(backoff(attempt - 1)); + try { + ops.sync(); + } catch (err) { + lastErr = err; + console.warn(`Attempt ${attempt}/${maxAttempts}: could not sync the ledger: ${err.message ?? err}`); + continue; + } + } + + const current = ops.read(); + const existing = findSignature(current, entry.id); + if (existing) { + console.log(`@${entry.name} is already on the ledger (${existing.created_at}); not writing.`); + return { recorded: false, existing }; + } + ops.write(addSignature(current, entry).data); + if (!ops.commit(message)) { + // addSignature just added the entry, so an empty diff means the file on + // disk already had it. Treat this like the already-recorded case. + return { recorded: false, existing: null }; + } + try { - git(['push', 'origin', `HEAD:refs/heads/${branch}`], { stdio: 'inherit' }); - return true; - } catch (pushErr) { - if (attempt === 4) throw pushErr; - // Rebase onto a newer main and retry. Rebase failures are not recoverable - // here (conflict on an append-only JSON means something upstream wrote an - // incompatible shape) — rethrow immediately. - git(['pull', '--rebase', 'origin', branch], { stdio: 'inherit' }); + ops.push(); + return { recorded: true }; + } catch (err) { + lastErr = err; + console.warn(`Attempt ${attempt}/${maxAttempts}: push rejected: ${err.message ?? err}`); } } - throw new Error('Failed to push signature update after retries'); + throw new Error( + `Failed to record signature for @${entry.name} after ${maxAttempts} attempts: ${lastErr?.message ?? lastErr}`, + ); +} + +// Git-backed ops for recordSignatureWithRetry. Tests set `assertRemote: false` +// to point the ledger at a local bare repository. Production always checks. +export function createGitLedgerOps(dir = LEDGER_DIR, { branch = 'main', assertRemote = true } = {}) { + let identityConfigured = false; + return { + sync: () => { + git(['fetch', '--depth=1', 'origin', branch], { cwd: dir }); + // Drop this run's rejected commit. The caller re-applies the signature + // to the fresh ledger. + git(['reset', '--hard', 'FETCH_HEAD'], { cwd: dir }); + }, + read: () => readSignatures(dir), + write: (data) => writeSignatures(data, dir), + commit: (message) => { + if (!git(['status', '--porcelain', SIGNATURES_PATH], { cwd: dir }).trim()) return false; + if (assertRemote) assertLedgerRemote(dir); + if (!identityConfigured) { + configureGitIdentity(dir); + identityConfigured = true; + } + git(['add', SIGNATURES_PATH], { cwd: dir }); + git(['commit', '-m', message], { cwd: dir }); + return true; + }, + push: () => { + if (assertRemote) assertLedgerRemote(dir); + git(['push', 'origin', `HEAD:refs/heads/${branch}`], { cwd: dir }); + }, + }; } // Read the ledger at the current tip of origin/main rather than the checkout. @@ -149,10 +229,10 @@ function commitSignaturesChange(message, branch = 'main') { // 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') { +function readLatestSignatures(dir, branch = 'main') { try { - git(['fetch', '--depth=1', 'origin', branch]); - return parseSignatures(git(['show', `FETCH_HEAD:${SIGNATURES_PATH}`])); + git(['fetch', '--depth=1', 'origin', branch], { cwd: dir }); + return parseSignatures(git(['show', `FETCH_HEAD:${SIGNATURES_PATH}`], { cwd: dir })); } catch (err) { console.warn(`Could not re-read ledger from origin/${branch}: ${err.message ?? err}`); return null; @@ -161,15 +241,12 @@ function readLatestSignatures(branch = 'main') { // The handlers reach the ledger only through this object so tests can drive // them without a git checkout. -export function createGitLedger() { +export function createGitLedger(dir = LEDGER_DIR, { assertRemote = true, retry } = {}) { + const ops = createGitLedgerOps(dir, { assertRemote }); return { - read: () => readSignatures(LEDGER_DIR), - readLatest: () => readLatestSignatures(), - write: (data) => writeSignatures(data, LEDGER_DIR), - commit: (message) => { - configureGitIdentity(); - return commitSignaturesChange(message); - }, + read: () => readSignatures(dir), + readLatest: () => readLatestSignatures(dir), + record: (entry, message) => recordSignatureWithRetry(ops, entry, message, retry), }; } @@ -284,17 +361,14 @@ export async function handleIssueComment(gh, event, eventRepo, ledger = createGi comment_id: comment.id, comment_url: comment.html_url, }; - const { data: next, added } = addSignature(signatures, entry); - if (!added) { - throw new Error(`Unexpected: ${prAuthor.login} already signed after hasSigned check`); - } - ledger.write(next); - - const committed = ledger.commit( + // record() re-applies the entry to the remote head on each retry and skips + // the write when a concurrent run already recorded this author. + const { recorded } = await ledger.record( + entry, `chore(ipr): record signature for @${prAuthor.login} (${eventRepo.owner}/${eventRepo.repo}#${issue.number})`, ); - if (!committed) { - console.log('Ledger already up to date at HEAD (concurrent write completed first).'); + if (!recorded) { + console.log('Ledger already records this author at the remote head (concurrent write completed first).'); } await ensureComment(gh, eventRepo, issue.number, CONFIRM_COMMENT_MARKER, confirmCommentBody(prAuthor.login)); diff --git a/tests/ipr-check-and-record.test.mjs b/tests/ipr-check-and-record.test.mjs index 7afd2d747ad..45c49f0055b 100644 --- a/tests/ipr-check-and-record.test.mjs +++ b/tests/ipr-check-and-record.test.mjs @@ -1,11 +1,17 @@ -import { spawnSync } from 'node:child_process'; +import { execFileSync, 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 { afterEach, beforeAll, describe, it, expect, vi } from 'vitest'; import YAML from 'yaml'; -import { handleIssueComment, handlePullRequestTarget } from '../scripts/ipr/check-and-record.mjs'; +import { + createGitLedger, + handleIssueComment, + handlePullRequestTarget, + recordSignatureWithRetry, +} from '../scripts/ipr/check-and-record.mjs'; +import { SIGNATURES_PATH, parseSignatures, writeSignatures } from '../scripts/ipr/signatures.mjs'; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const eventRepo = { owner: 'adcontextprotocol', repo: 'adcp' }; @@ -47,8 +53,7 @@ function fakeLedger({ checkout, latest }) { return { read: vi.fn(() => checkout), readLatest: vi.fn(() => latest), - write: vi.fn(), - commit: vi.fn(() => true), + record: vi.fn(async () => ({ recorded: true })), }; } @@ -61,15 +66,14 @@ describe('handlePullRequestTarget (check-only path)', () => { 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(); + expect(ledger.record).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(); + expect(ledger.record).not.toHaveBeenCalled(); }); it('re-reads origin/main after posting pending and flips to success when a signature landed meanwhile', async () => { @@ -128,10 +132,8 @@ describe('handleIssueComment (signature-write path)', () => { 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); + expect(ledger.record).toHaveBeenCalledTimes(1); + expect(ledger.record.mock.calls[0][0]).toMatchObject({ id: 101, name: 'contributor', method: 'pr_comment' }); const success = gh.statuses.filter((s) => s.state === 'success').map((s) => s.sha); expect(success).toEqual(['head-1', 'head-2']); }); @@ -147,7 +149,182 @@ describe('handleIssueComment (signature-write path)', () => { 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(ledger.record).not.toHaveBeenCalled(); + expect(gh.statuses).toHaveLength(0); + }); +}); + +// Several AAO repos call ipr-check-callable.yml, and Actions concurrency groups +// are per repo, so two signature writes can reach the shared ledger at the same +// time. These tests use real git against a local bare remote. +describe('recording a signature when another repo pushed first', () => { + const tmpRoots = []; + + beforeAll(() => { + // Inside a git hook, GIT_DIR and friends would point every git call + // (including the script's) at the enclosing repository. + for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_OBJECT_DIRECTORY']) { + delete process.env[key]; + } + }); + + afterEach(() => { + vi.restoreAllMocks(); + for (const dir of tmpRoots.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); + }); + + const g = (cwd, ...args) => + execFileSync('git', ['-c', 'user.name=seed', '-c', 'user.email=seed@example.com', ...args], { + cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); + + const seedSignature = { name: 'seed', id: 1, created_at: '2026-01-01T00:00:00Z', method: 'pr_comment' }; + + // A bare "origin" seeded with one signature, plus two shallow clones taken at + // the same commit, the way two workflow runs check out main. + function setupRemote() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ipr-ledger-')); + tmpRoots.push(root); + g(root, 'init', '-q', '--bare', '-b', 'main', 'origin.git'); + const remote = `file://${path.join(root, 'origin.git')}`; + const seed = path.join(root, 'seed'); + g(root, 'clone', '-q', remote, 'seed'); + writeSignatures({ signedContributors: [seedSignature] }, seed); + g(seed, 'add', '.'); + g(seed, 'commit', '-q', '-m', 'seed ledger'); + g(seed, 'push', '-q', 'origin', 'HEAD:refs/heads/main'); + g(root, 'clone', '-q', '--depth=1', remote, 'run-a'); + g(root, 'clone', '-q', '--depth=1', remote, 'run-b'); + return { + root, + runA: path.join(root, 'run-a'), + runB: path.join(root, 'run-b'), + remoteLedger: () => parseSignatures(g(path.join(root, 'origin.git'), 'show', `main:${SIGNATURES_PATH}`)), + remoteHead: () => g(path.join(root, 'origin.git'), 'rev-parse', 'main').trim(), + }; + } + + const noWait = { sleep: async () => {} }; + const otherRepoEntry = (id, login) => ({ + name: login, + id, + created_at: '2026-10-15T10:00:01Z', + method: 'pr_comment', + repo: 'adcontextprotocol/adcp-client', + pullRequestNo: 9, + }); + + function commentEvent() { + return { + 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('re-applies the signature on the new head instead of rebasing a conflicting append', async () => { + const env = setupRemote(); + // Run B (another repo) records first. Run A's checkout still predates it, + // so A's first push is rejected and both appends edit the same lines. + const runB = createGitLedger(env.runB, { assertRemote: false, retry: noWait }); + await expect(runB.record(otherRepoEntry(202, 'other-repo-signer'), 'record b')).resolves.toEqual({ recorded: true }); + + const gh = fakeGitHub({ pr: { user: author, head: { sha: 'head-1' } } }); + const runA = createGitLedger(env.runA, { assertRemote: false, retry: noWait }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + await handleIssueComment(gh, commentEvent(), eventRepo, runA); + + expect(warn.mock.calls.map(([m]) => m)).toEqual([expect.stringMatching(/^Attempt 1\/5: push rejected/)]); + const ids = env.remoteLedger().signedContributors.map((c) => c.id); + expect(ids.sort((a, b) => a - b)).toEqual([1, 101, 202]); + // The ledger stays in writeSignatures' format (sorted, 2-space, newline). + const onDisk = fs.readFileSync(path.join(env.runA, SIGNATURES_PATH), 'utf8'); + expect(g(path.join(env.root, 'origin.git'), 'show', `main:${SIGNATURES_PATH}`)).toBe(onDisk); + expect(gh.statuses).toEqual([{ sha: 'head-1', state: 'success', context: 'IPR Policy / Signature' }]); + }); + + it('does not write again when a concurrent run already recorded the same author', async () => { + const env = setupRemote(); + // The same author signed on another repo's PR at the same moment. + const runB = createGitLedger(env.runB, { assertRemote: false, retry: noWait }); + await runB.record(otherRepoEntry(author.id, author.login), 'record b'); + const headAfterB = env.remoteHead(); + + const gh = fakeGitHub(); + gh.getPullRequest + .mockResolvedValueOnce({ user: author, head: { sha: 'head-1' } }) + .mockResolvedValueOnce({ user: author, head: { sha: 'head-2' } }); + const runA = createGitLedger(env.runA, { assertRemote: false, retry: noWait }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + await handleIssueComment(gh, commentEvent(), eventRepo, runA); + + expect(warn.mock.calls.map(([m]) => m)).toEqual([expect.stringMatching(/^Attempt 1\/5: push rejected/)]); + expect(env.remoteHead()).toBe(headAfterB); + const entries = env.remoteLedger().signedContributors.filter((c) => c.id === author.id); + expect(entries).toHaveLength(1); + expect(entries[0].repo).toBe('adcontextprotocol/adcp-client'); + // The post-write status behaviour is unchanged: both heads get success. + expect(gh.statuses.map((s) => [s.sha, s.state])).toEqual([ + ['head-1', 'success'], + ['head-2', 'success'], + ]); + }); + + it('returns already-recorded from the retry loop without committing', async () => { + let ledger = { signedContributors: [seedSignature] }; + const ops = { + sync: vi.fn(() => { + ledger = { signedContributors: [seedSignature, { ...otherRepoEntry(101, 'contributor') }] }; + }), + read: vi.fn(() => ledger), + write: vi.fn(), + commit: vi.fn(() => true), + push: vi.fn(() => { + throw new Error('! [rejected] HEAD -> main (fetch first)'); + }), + }; + const result = await recordSignatureWithRetry(ops, { ...otherRepoEntry(101, 'contributor') }, 'm', noWait); + expect(result.recorded).toBe(false); + expect(result.existing.id).toBe(101); + expect(ops.commit).toHaveBeenCalledTimes(1); + expect(ops.push).toHaveBeenCalledTimes(1); + }); + + it('gives up after the bounded number of attempts, backing off between them', async () => { + const ops = { + sync: vi.fn(), + read: vi.fn(() => ({ signedContributors: [seedSignature] })), + write: vi.fn(), + commit: vi.fn(() => true), + push: vi.fn(() => { + throw new Error('! [rejected] HEAD -> main (fetch first)'); + }), + }; + const sleep = vi.fn(async () => {}); + const backoff = vi.fn((retry) => retry * 100); + + await expect( + recordSignatureWithRetry(ops, otherRepoEntry(101, 'contributor'), 'm', { maxAttempts: 3, sleep, backoff }), + ).rejects.toThrow(/after 3 attempts.*rejected/); + expect(ops.push).toHaveBeenCalledTimes(3); + // Every retry starts from the fresh remote head and re-applies the entry. + expect(ops.sync).toHaveBeenCalledTimes(2); + expect(ops.write).toHaveBeenCalledTimes(3); + expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([100, 200]); + }); + + it('posts no success status when recording fails', async () => { + const gh = fakeGitHub({ pr: { user: author, head: { sha: 'head-1' } } }); + const ledger = fakeLedger({ checkout: emptyLedger, latest: null }); + ledger.record.mockRejectedValueOnce(new Error('Failed to record signature after 5 attempts')); + await expect(handleIssueComment(gh, commentEvent(), eventRepo, ledger)).rejects.toThrow(/5 attempts/); expect(gh.statuses).toHaveLength(0); }); });