@aviaratech/ai-delivery 0.3.36 → 0.3.38
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -6
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -3
- package/dist/agent.js.map +2 -2
- package/dist/callerErrors.test.js +0 -14
- package/dist/callerErrors.test.js.map +2 -2
- package/dist/cli.js +0 -15
- package/dist/cli.js.map +2 -2
- package/dist/contributorChecks.test.js +5 -2
- package/dist/contributorChecks.test.js.map +2 -2
- package/dist/dispatch.d.ts +1 -1
- package/dist/dispatch.js +1 -15
- package/dist/dispatch.js.map +2 -2
- package/dist/fixtures/discovery.d.ts +16 -16
- package/dist/git.d.ts +0 -3
- package/dist/git.js +2 -25
- package/dist/git.js.map +2 -2
- package/dist/github/commandIdentityPolicy.js +0 -2
- package/dist/github/commandIdentityPolicy.js.map +2 -2
- package/dist/issue.js +7 -2
- package/dist/issue.js.map +2 -2
- package/dist/issueInfoReadback.test.js +59 -1
- package/dist/issueInfoReadback.test.js.map +2 -2
- package/dist/issueIntake.test.js +0 -7
- package/dist/issueIntake.test.js.map +2 -2
- package/dist/mcp/tools.d.ts +0 -36
- package/dist/mcp/tools.js +0 -34
- package/dist/mcp/tools.js.map +2 -2
- package/dist/pluginPackaging.test.js +0 -47
- package/dist/pluginPackaging.test.js.map +2 -2
- package/dist/pr.d.ts +0 -55
- package/dist/pr.js +0 -211
- package/dist/pr.js.map +3 -3
- package/dist/pr.test.js +5 -737
- package/dist/pr.test.js.map +3 -3
- package/dist/prAssociation.test.js +1 -1
- package/dist/prAssociation.test.js.map +2 -2
- package/dist/prDispatch.test.js +4 -31
- package/dist/prDispatch.test.js.map +2 -2
- package/dist/readView.d.ts +1 -0
- package/dist/readView.js +1 -0
- package/dist/readView.js.map +2 -2
- package/dist/readView.test.js +29 -2
- package/dist/readView.test.js.map +2 -2
- package/dist/stdoutRegression.test.js +0 -38
- package/dist/stdoutRegression.test.js.map +2 -2
- package/dist/targetPolicyRoutes.test.js +1 -32
- package/dist/targetPolicyRoutes.test.js.map +2 -2
- package/dist/targetRepositoryExecution.test.js +0 -12
- package/dist/targetRepositoryExecution.test.js.map +2 -2
- package/dist/utils/atomicJson.d.ts +0 -2
- package/dist/utils/atomicJson.js +0 -4
- package/dist/utils/atomicJson.js.map +2 -2
- package/dist/utils/filesystem.d.ts +0 -8
- package/dist/utils/filesystem.js +1 -12
- package/dist/utils/filesystem.js.map +2 -2
- package/dist/verification.d.ts +0 -35
- package/dist/verification.js +1 -47
- package/dist/verification.js.map +2 -2
- package/dist/version.js +24 -2
- package/dist/version.js.map +2 -2
- package/package.json +1 -1
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/cli.js +128 -135
- package/plugins/ai-delivery/runtime/package.json +1 -1
- package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +4 -4
- package/dist/services/deliveryAdmission.d.ts +0 -49
- package/dist/services/deliveryAdmission.js +0 -142
- package/dist/services/deliveryAdmission.js.map +0 -7
- package/dist/services/worktreeRegistry.d.ts +0 -342
- package/dist/services/worktreeRegistry.js +0 -831
- package/dist/services/worktreeRegistry.js.map +0 -7
- package/dist/worktree.d.ts +0 -16
- package/dist/worktree.js +0 -108
- package/dist/worktree.js.map +0 -7
package/dist/pr.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/pr.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod';\nimport { randomUUID } from 'node:crypto';\nimport { DeliveryError } from './errors.js';\nimport * as githubClients from './github/client.js';\nimport type { GitHubClients } from './github/client.js';\nimport { getNativeBlockerRelationships } from './github/relationships.js';\nimport { issueBranch, linkedIssueBranches, startIssueBranch, type DeliveryContext } from './issue.js';\nimport { existsSync } from 'node:fs';\nimport { primaryGitRoot, defaultBaseRef, gitExitCode, git } from './git.js';\nimport { resolveRepoFromRemote } from './github/repo.js';\nimport { removeFinishedIssueSource, type MergeCleanupAttestation } from './worktree.js';\nimport {\n listWorktreesStrict,\n getIssueWorktreeStrict,\n reconcileCompletedIssueWorktreeDelivery,\n} from './services/worktreeRegistry.js';\nimport {\n parseReviewArtifact,\n readRequiredReviewState,\n ReviewSubmissionError,\n submitReview,\n type RequiredReviewState,\n} from './review.js';\nimport { parseIssueBody } from './issueContract.js';\n\nconst Sha = /^[a-f0-9]{40}$/u;\nconst Branch = /^(?!.*(?:\\.\\.|@\\{|\\/\\/))[A-Za-z0-9._/-]+$/u;\n\nexport type PrReadContext = Pick<DeliveryContext, 'clients' | 'repo'>;\n\nconst DeliveryPrFooter = '\\n\\n<!-- ai-delivery:pr@1 -->';\nfunction activeMarkerPositions(text: string, pattern: RegExp): number[] | null {\n // A bounded context reader, not a Markdown renderer. Resolve blocks before inline\n // quoting; unsupported container/HTML interactions cannot prove a usage marker.\n const ignored: Array<[number, number]> = [];\n const uncertain: Array<[number, number]> = [];\n const inline: Array<[number, number]> = [];\n let paragraph: number | null = null;\n let fence: string | null = null;\n let comment = false;\n let htmlEnd: 'blank' | RegExp | null = null;\n let container = false;\n let quoted = false;\n let blank = true;\n const flush = (end: number) => {\n if (paragraph !== null) inline.push([paragraph, end]);\n paragraph = null;\n };\n for (const line of text.matchAll(/[^\\n]*(?:\\n|$)/gu)) {\n if (!line[0]) continue;\n const start = line.index;\n const end = start + line[0].length;\n const content = line[0].replace(/\\r?\\n$/u, '');\n if (comment) {\n const closing = content.indexOf('-->');\n ignored.push([start, closing < 0 ? end : start + closing + 3]);\n if (closing >= 0) comment = false;\n continue;\n }\n if (htmlEnd !== null) {\n if (htmlEnd === 'blank' && !content.trim()) htmlEnd = null;\n else {\n uncertain.push([start, end]);\n if (htmlEnd !== 'blank' && htmlEnd.test(content)) htmlEnd = null;\n continue;\n }\n }\n const edge = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(content);\n if (fence !== null) {\n ignored.push([start, end]);\n if (edge && edge[1]![0] === fence[0] && edge[1]!.length >= fence.length && !edge[2]!.trim()) fence = null;\n continue;\n }\n if (!content.trim()) {\n flush(start);\n quoted = false;\n blank = true;\n continue;\n }\n if (/^ {0,3}>/u.test(content)) {\n flush(start);\n ignored.push([start, end]);\n quoted = true;\n blank = false;\n continue;\n }\n if (blank && /^\\S/u.test(content) && !/^[-+*\\d]/u.test(content)) container = false;\n const indented = /^(?: {4}| {0,3}\\t)/u.test(content);\n if (indented && paragraph === null) {\n (container || quoted ? uncertain : ignored).push([start, end]);\n continue;\n }\n if (edge && (edge[1]![0] !== '`' || !edge[2]!.includes('`'))) {\n flush(start);\n if (container || quoted) uncertain.push([start, text.length]);\n ignored.push([start, end]);\n fence = edge[1]!;\n } else if (/^ {0,3}<!--/u.test(content)) {\n flush(start);\n const opening = content.indexOf('<!--');\n const closing = content.indexOf('-->', opening + 4);\n ignored.push([start + opening + 4, closing < 0 ? end : start + closing + 3]);\n if (closing < 0) comment = true;\n } else if (/^ {0,3}<\\/?[A-Za-z!?]/u.test(content)) {\n flush(start);\n uncertain.push([start, end]);\n const closing = /^ {0,3}<\\?/u.test(content)\n ? /\\?>/u\n : /^ {0,3}<!\\[CDATA\\[/u.test(content)\n ? /\\]\\]>/u\n : /^ {0,3}<!/u.test(content)\n ? />/u\n : /^ {0,3}<(?:pre|script|style|textarea)(?:[ \\t>]|$)/iu.test(content)\n ? /<\\/(?:pre|script|style|textarea)>/iu\n : null;\n htmlEnd = closing === null ? 'blank' : closing.test(content) ? null : closing;\n } else if (\n /^ {0,3}(?:#{1,6}(?:[ \\t]|$)|(?:[-+*]|\\d+[.)])[ \\t])/u.test(content) ||\n /^ {0,3}(?:=+|-+)[ \\t]*$/u.test(content) ||\n /^ {0,3}(?:(?:\\*[ \\t]*){3,}|(?:_[ \\t]*){3,}|(?:-[ \\t]*){3,})$/u.test(content)\n ) {\n flush(start);\n inline.push([start, end]);\n container = /^ {0,3}(?:[-+*]|\\d+[.)])[ \\t]/u.test(content);\n } else {\n if (quoted || container) uncertain.push([start, end]);\n paragraph ??= start;\n }\n blank = false;\n }\n flush(text.length);\n for (const [start, end] of inline) {\n const unit = text.slice(start, end);\n const tokens = /\\\\[\\\\`<]|`+|<!--/gu;\n for (let token = tokens.exec(unit); token; token = tokens.exec(unit)) {\n if (token[0].startsWith('\\\\')) {\n ignored.push([start + token.index + 1, start + tokens.lastIndex]);\n } else if (token[0] === '<!--') {\n const closing = unit.indexOf('-->', tokens.lastIndex);\n if (closing < 0) uncertain.push([start + token.index, end]);\n else {\n ignored.push([start + tokens.lastIndex, start + closing + 3]);\n tokens.lastIndex = closing + 3;\n }\n } else {\n const ticks = /`+/gu;\n ticks.lastIndex = tokens.lastIndex;\n for (let closing = ticks.exec(unit); closing; closing = ticks.exec(unit)) {\n if (closing[0].length !== token[0].length) continue;\n ignored.push([start + token.index, start + ticks.lastIndex]);\n tokens.lastIndex = ticks.lastIndex;\n break;\n }\n }\n }\n }\n const candidates = [...text.matchAll(pattern)].map((match) => match.index);\n if (candidates.some((position) => uncertain.some(([start, end]) => position >= start && position < end))) return null;\n return candidates.filter((position) => !ignored.some(([start, end]) => position >= start && position < end));\n}\n/** A forgeable usage indicator, not publication or merge authority. */\nexport function hasDeliveryPrMarker(body: string): boolean {\n if (!body.endsWith(DeliveryPrFooter)) return false;\n const prefix = body.slice(0, -DeliveryPrFooter.length);\n const active = activeMarkerPositions(body, /<!--\\s*ai-delivery:pr@[^\\n]*?(?:-->|$)/gmu);\n return Boolean(prefix.trim()) && active?.length === 1 && active[0] === prefix.length + 2;\n}\nexport function hasDeliveryMergeTrailer(message: string): boolean {\n const trailer = /\\n\\nDelivered-by: ai-delivery\\n?$/u.exec(message);\n if (!trailer || !message.slice(0, trailer.index).trim()) return false;\n const active = activeMarkerPositions(message, /^Delivered-by: ai-delivery[ \\t]*$/gmu);\n return active?.length === 1 && active[0] === trailer.index + 2;\n}\n\nfunction publicationBody(body: string, previous: string | null | undefined): string {\n function marked(value: string): boolean {\n const active = activeMarkerPositions(value, /<!--\\s*ai-delivery:pr@[^\\n]*?(?:-->|$)/gmu);\n if (active === null || (active.length > 0 && !hasDeliveryPrMarker(value)))\n throw new DeliveryError('PR marker footer is malformed, misplaced or ambiguous; reconcile without repair.');\n return active.length === 1;\n }\n const previousMarked = typeof previous === 'string' && marked(previous);\n const requestedMarked = marked(body);\n if (previous !== undefined && !previousMarked) {\n if (requestedMarked) throw new DeliveryError('Historical unmarked PRs cannot receive a marker footer backfill.');\n return body;\n }\n if (requestedMarked) return body;\n const decorated = body + DeliveryPrFooter;\n if (!hasDeliveryPrMarker(decorated))\n throw new DeliveryError('PR marker footer would be ambiguous; retain the original body without repair.');\n return decorated;\n}\n\nfunction deliverySquashMessage(body: string): string {\n const substantive = hasDeliveryPrMarker(body) ? body.slice(0, -DeliveryPrFooter.length) : body;\n if (hasDeliveryMergeTrailer(substantive)) return substantive;\n const message = `${substantive}\\n\\nDelivered-by: ai-delivery`;\n if (!hasDeliveryMergeTrailer(message))\n throw new DeliveryError('Squash delivery trailer would be ambiguous; reconcile the message without repair.');\n return message;\n}\n\nfunction hasClosingLink(body: string | null, issueNumber: number) {\n const line = `Closes #${issueNumber}`;\n return body === line || body?.startsWith(`${line}\\n`) === true || body?.startsWith(`${line}\\r\\n`) === true;\n}\nfunction closingBody(issue: { number: number; title: string; body?: string | null }, requested?: string) {\n const line = `Closes #${issue.number}`;\n if (requested !== undefined)\n return requested.startsWith(`${line}\\n`) || requested === line ? requested : `${line}\\n\\n${requested}`;\n const { outcome, acceptanceCriteria } = parseIssueBody(issue.body ?? '', { title: issue.title }).issue;\n return [\n line,\n ...(outcome ? [`## Outcome\\n\\n${outcome}`] : []),\n ...(acceptanceCriteria.length\n ? [\n `## Acceptance criteria\\n\\n${acceptanceCriteria.map((ac) => `- [ ] ${ac.behavior}\\n Verified by: ${ac.verifiedBy}`).join('\\n')}`,\n ]\n : []),\n ].join('\\n\\n');\n}\n\n// Conservative refusals also cover Markdown decoration/escaped references.\n// This is a closure safety check, never authority for an issue association.\nfunction refuseClosingDirective(text: unknown): asserts text is string {\n if (typeof text !== 'string') throw new DeliveryError('Incomplete non-closing message readback.');\n const normalized = text.replace(/\\[[^\\]\\r\\n]*\\]\\(([^()\\s]+)\\)/gu, '$1').replace(/[*_~`\\\\<>[\\]]/gu, '');\n if (\n /(?<![\\p{L}\\p{N}_-])(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)(?:\\s*:\\s*|\\s+)(?:#[0-9]+|[A-Za-z0-9.-]+\\/[A-Za-z0-9.-]+#[0-9]+|https?:\\/\\/(?:www\\.)?github\\.com\\/[A-Za-z0-9.-]+\\/[A-Za-z0-9.-]+\\/(?:issues|pull)\\/[0-9]+)/iu.test(\n normalized,\n )\n )\n throw new DeliveryError('Non-closing delivery refuses closing directives in body, title or commit messages.');\n}\nfunction referenceLine(context: DeliveryContext, issueNumber: number) {\n return `References ${context.config.repository}#${issueNumber}`;\n}\nfunction nonClosingBody(context: DeliveryContext, issueNumber: number, requested: string) {\n refuseClosingDirective(requested);\n const line = referenceLine(context, issueNumber);\n const body = requested.startsWith(`${line}\\n`) || requested === line ? requested : `${line}\\n\\n${requested}`;\n verifyReferenceBody(context, issueNumber, body);\n return body;\n}\nfunction hasReferenceBody(context: DeliveryContext, issueNumber: number, body: unknown): boolean {\n try {\n verifyReferenceBody(context, issueNumber, body);\n return true;\n } catch {\n return false;\n }\n}\nfunction verifyReferenceBody(context: DeliveryContext, issueNumber: number, body: unknown): asserts body is string {\n refuseClosingDirective(body);\n const lines = body.split(/\\r?\\n/u);\n if (\n lines[0] !== referenceLine(context, issueNumber) ||\n lines.filter((line) => /^References\\s/iu.test(line)).length !== 1\n )\n throw new DeliveryError('Non-closing PR body must retain one leading canonical References line.');\n}\nfunction pageCursor(connection: { pageInfo?: { hasNextPage: boolean; endCursor: string | null } }, seen: Set<string>) {\n const info = connection.pageInfo;\n if (\n !info ||\n typeof info.hasNextPage !== 'boolean' ||\n !(info.endCursor === null || typeof info.endCursor === 'string')\n )\n throw new DeliveryError('Incomplete non-closing native pagination.');\n if (!info.hasNextPage) return null;\n if (!info.endCursor || seen.has(info.endCursor))\n throw new DeliveryError('Non-closing native pagination did not advance.');\n seen.add(info.endCursor);\n return info.endCursor;\n}\nasync function openReferenceIssue(context: DeliveryContext, issueNumber: number) {\n const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;\n if (\n issue.number !== issueNumber ||\n 'pull_request' in issue ||\n issue.state !== 'open' ||\n typeof issue.node_id !== 'string' ||\n !issue.node_id ||\n typeof issue.title !== 'string' ||\n typeof issue.body !== 'string' ||\n issue.html_url?.toLowerCase() !==\n `https://github.com/${context.config.repository}/issues/${issueNumber}`.toLowerCase()\n )\n throw new DeliveryError('Non-closing delivery requires the exact canonical OPEN issue and complete title/body.');\n return issue;\n}\ntype RemotePr = Awaited<ReturnType<typeof getPr>>;\nfunction sameReferencePr(before: RemotePr, after: RemotePr, expectedMerge = false) {\n if (\n expectedMerge\n ? before.state !== 'open' ||\n before.draft ||\n before.merged ||\n after.state !== 'closed' ||\n after.draft ||\n !after.merged\n : before.state !== after.state || before.draft !== after.draft || before.merged !== after.merged\n )\n throw new DeliveryError('Non-closing PR state/draft/merged readback drifted; reconcile read-only.');\n if (\n before.node_id !== after.node_id ||\n before.head.sha !== after.head.sha ||\n before.head.ref !== after.head.ref ||\n before.base.sha !== after.base.sha ||\n before.base.ref !== after.base.ref ||\n before.body !== after.body ||\n before.title !== after.title ||\n before.user.login.toLowerCase() !== after.user.login.toLowerCase()\n )\n throw new DeliveryError('Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.');\n}\nfunction sameReferenceIssue(\n before: Awaited<ReturnType<typeof openReferenceIssue>>,\n after: Awaited<ReturnType<typeof openReferenceIssue>>,\n) {\n if (before.node_id !== after.node_id || before.title !== after.title || before.body !== after.body)\n throw new DeliveryError('Non-closing issue identity/title/criteria drifted; reconcile read-only.');\n}\nfunction nonClosingMode(value: unknown) {\n if (value !== undefined && typeof value !== 'boolean') throw new DeliveryError('nonClosing must be a boolean.');\n return value === true;\n}\nasync function nonClosingRoute(context: DeliveryContext, base: string) {\n const authorContext =\n context.clients.role === 'author'\n ? context\n : {\n ...context,\n clients: await githubClients.createDeliveryGitHubClients({\n config: context.config,\n ...(context.credentialEnvironment === undefined ? {} : { env: context.credentialEnvironment }),\n identity: context.config.roles.author.identity,\n role: 'author',\n }),\n reviewerClients: context.clients,\n };\n const route = await preflightReviewRoute(authorContext, base);\n if (route.rules.visibility !== 'complete' || route.approvalEligibility === 'insufficient-permission')\n throw new DeliveryError(\n 'Non-closing delivery requires complete native rule visibility and an independent reviewer route.',\n );\n return route;\n}\nasync function verifyNonClosingCommits(context: DeliveryContext, pr: RemotePr) {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const commits = new Map<string, string>();\n let total: number | undefined;\n for (let page = 0; page < 20; page++) {\n const data: {\n repository?: {\n nameWithOwner: string;\n pullRequest?: {\n id: string;\n number: number;\n headRefOid: string;\n baseRefOid: string;\n baseRefName: string;\n commits: {\n totalCount: number;\n nodes: Array<{\n commit: {\n oid: string;\n message: string;\n parents: {\n totalCount: number;\n nodes: Array<{ oid: string }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n };\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n };\n };\n } = await context.clients.graphql(\n 'query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: pr.number, cursor },\n );\n const live = data.repository?.pullRequest;\n const connection = live?.commits;\n if (\n data.repository?.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n live?.id !== pr.node_id ||\n live.number !== pr.number ||\n live.headRefOid !== pr.head.sha ||\n live.baseRefOid !== pr.base.sha ||\n live.baseRefName !== pr.base.ref ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100 ||\n !Number.isSafeInteger(connection.totalCount) ||\n connection.totalCount < 1 ||\n connection.totalCount > 2000 ||\n (total !== undefined && total !== connection.totalCount)\n )\n throw new DeliveryError('Incomplete or moved introduced commit graph at the non-closing head/base.');\n total = connection.totalCount;\n for (const node of connection.nodes) {\n const commit = node?.commit;\n if (\n !commit ||\n !validSha(commit.oid) ||\n commits.has(commit.oid) ||\n !commit.parents ||\n !Array.isArray(commit.parents.nodes) ||\n commit.parents.nodes.length > 100 ||\n !Number.isSafeInteger(commit.parents.totalCount) ||\n commit.parents.totalCount < 1 ||\n commit.parents.totalCount !== commit.parents.nodes.length ||\n commit.parents.pageInfo?.hasNextPage !== false ||\n commit.parents.nodes.some((parent) => !validSha(parent?.oid))\n )\n throw new DeliveryError('Incomplete, duplicate or truncated introduced commit identity/parents.');\n refuseClosingDirective(commit.message);\n commits.set(commit.oid, commit.message);\n }\n cursor = pageCursor(connection, cursors);\n if (cursor === null) {\n if (commits.size !== total || !commits.has(pr.head.sha))\n throw new DeliveryError('Introduced commit count/head is incomplete.');\n return;\n }\n }\n throw new DeliveryError('Non-closing commit graph exceeds the bounded readback window.');\n}\nasync function verifyUnpublishedCommits(context: DeliveryContext, baseSha: string, headSha: string) {\n const commits = new Set<string>();\n let total: number | undefined;\n for (let page = 1; page <= 20; page++) {\n const comparison = (\n await context.clients.rest.repos.compareCommitsWithBasehead({\n ...context.repo,\n basehead: `${baseSha}...${headSha}`,\n per_page: 100,\n page,\n })\n ).data;\n if (\n comparison.base_commit?.sha !== baseSha ||\n !validSha(comparison.merge_base_commit?.sha) ||\n !['ahead', 'diverged'].includes(comparison.status) ||\n !Number.isSafeInteger(comparison.total_commits) ||\n comparison.total_commits < 1 ||\n comparison.total_commits > 2000 ||\n (total !== undefined && total !== comparison.total_commits) ||\n !Array.isArray(comparison.commits) ||\n comparison.commits.length > 100\n )\n throw new DeliveryError('Incomplete introduced commit range before non-closing publication.');\n total = comparison.total_commits;\n for (const commit of comparison.commits) {\n if (\n !validSha(commit.sha) ||\n commits.has(commit.sha) ||\n !Array.isArray(commit.parents) ||\n commit.parents.length < 1 ||\n commit.parents.length > 100 ||\n commit.parents.some((parent) => !validSha(parent.sha))\n )\n throw new DeliveryError('Incomplete or duplicate introduced commit identity.');\n refuseClosingDirective(commit.commit?.message);\n commits.add(commit.sha);\n }\n if (commits.size === total && commits.has(headSha)) return;\n if (comparison.commits.length < 100)\n throw new DeliveryError('Truncated introduced commit range before publication.');\n }\n throw new DeliveryError('Introduced commit range exceeds the bounded readback window.');\n}\nasync function readNonClosingReference(context: DeliveryContext, issueNumber: number, pr: RemotePr, forReview = false) {\n if (\n typeof pr.node_id !== 'string' ||\n !pr.node_id ||\n pr.html_url?.toLowerCase() !== `https://github.com/${context.config.repository}/pull/${pr.number}`.toLowerCase()\n )\n throw new DeliveryError('Incomplete non-closing PR node identity.');\n verifyReferenceBody(context, issueNumber, pr.body);\n refuseClosingDirective(pr.title);\n const issue = await openReferenceIssue(context, issueNumber);\n const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;\n if (\n repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() ||\n pr.base.ref !== repository.default_branch ||\n typeof repository.node_id !== 'string' ||\n !repository.node_id\n )\n throw new DeliveryError('Non-closing PR must target the canonical default repository/base.');\n const route = await nonClosingRoute(context, pr.base.ref);\n if (pr.user.login.toLowerCase() !== route.author.actorLogin.toLowerCase())\n throw new DeliveryError('Non-closing PR author differs from the configured author.');\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const events = new Map<string, string>();\n let matched = false;\n let closesTarget: boolean | undefined;\n for (let page = 0; page < 20; page++) {\n type Subject = {\n __typename: string;\n id: string;\n number: number;\n repository: { id: string; nameWithOwner: string };\n };\n const data: {\n repository?: {\n id: string;\n nameWithOwner: string;\n issue?: {\n id: string;\n number: number;\n state: string;\n timelineItems: {\n nodes: Array<{\n id: string;\n actor: { login: string } | null;\n isCrossRepository: boolean;\n willCloseTarget: boolean;\n source: Subject;\n target: Subject;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n };\n };\n } = await context.clients.graphql(\n 'query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: issueNumber, cursor },\n );\n const target = data.repository?.issue;\n const connection = target?.timelineItems;\n if (\n data.repository?.id !== repository.node_id ||\n data.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n target?.id !== issue.node_id ||\n target.number !== issueNumber ||\n target.state !== 'OPEN' ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100\n )\n throw new DeliveryError('Incomplete or conflicting native non-closing issue identity.');\n for (const event of connection.nodes) {\n const source = event?.source;\n const referenced = event?.target;\n if (\n !event ||\n !nativeId(event.id) ||\n !source ||\n !referenced ||\n !['Issue', 'PullRequest'].includes(source.__typename) ||\n !nativeId(source.id) ||\n !Number.isSafeInteger(source.number) ||\n source.number <= 0 ||\n !nativeId(source.repository?.id) ||\n typeof source.repository.nameWithOwner !== 'string' ||\n referenced.__typename !== 'Issue' ||\n referenced.id !== issue.node_id ||\n referenced.number !== issueNumber ||\n referenced.repository?.id !== repository.node_id ||\n referenced.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n typeof event.isCrossRepository !== 'boolean' ||\n typeof event.willCloseTarget !== 'boolean' ||\n !nativeId(event.actor?.login)\n )\n throw new DeliveryError('Incomplete native cross-reference event identity/actor.');\n const signature = JSON.stringify([\n source.__typename,\n source.id,\n source.number,\n source.repository.id,\n source.repository.nameWithOwner.toLowerCase(),\n referenced.id,\n referenced.number,\n referenced.repository.id,\n referenced.repository.nameWithOwner.toLowerCase(),\n event.actor.login.toLowerCase(),\n event.isCrossRepository,\n event.willCloseTarget,\n ]);\n if (events.has(event.id) && events.get(event.id) !== signature)\n throw new DeliveryError('Conflicting duplicate native reference event.');\n events.set(event.id, signature);\n if (\n source.id === pr.node_id ||\n (source.__typename === 'PullRequest' &&\n source.number === pr.number &&\n source.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase())\n ) {\n if (\n source.__typename !== 'PullRequest' ||\n source.id !== pr.node_id ||\n source.number !== pr.number ||\n source.repository.id !== repository.node_id ||\n source.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() ||\n event.isCrossRepository ||\n event.actor.login.toLowerCase() !== route.author.actorLogin.toLowerCase()\n )\n throw new DeliveryError('Conflicting, closing or unauthorized native PR reference.');\n if (closesTarget !== undefined && closesTarget !== event.willCloseTarget)\n throw new DeliveryError('Conflicting native PR closing-reference semantics.');\n closesTarget = event.willCloseTarget;\n matched = true;\n }\n }\n cursor = pageCursor(connection, cursors);\n if (cursor === null) break;\n if (page === 19) throw new DeliveryError('Native non-closing references exceed the bounded readback window.');\n }\n if (!matched) throw new DeliveryError('Missing authorized native non-closing PR-to-issue reference.');\n const allClosing = await readClosingReferenceIds(context, issueNumber, issue.node_id, repository.node_id, pr);\n const manualClosing = await readClosingReferenceIds(\n context,\n issueNumber,\n issue.node_id,\n repository.node_id,\n pr,\n true,\n );\n await verifyNonClosingCommits(context, pr);\n if (!pr.merged) {\n const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data;\n if (\n ref.ref !== `refs/heads/${pr.base.ref}` ||\n ref.object.type !== 'commit' ||\n !validSha(ref.object.sha) ||\n (!forReview && ref.object.sha !== pr.base.sha)\n )\n throw new DeliveryError('Non-closing default base has moved or is incomplete.');\n }\n const after = await openReferenceIssue(context, issueNumber);\n sameReferenceIssue(issue, after);\n sameReferencePr(pr, await getPr(context, pr.number));\n return { issue, closesTarget: closesTarget!, allClosing, manualClosing };\n}\n\n// Both strict verification and the explicit action consume the same complete graph.\n// Reading a closing edge here never supplies authority to remove it.\nasync function readClosingReferenceIds(\n context: DeliveryContext,\n issueNumber: number,\n issueId: string,\n repositoryId: string,\n pr: RemotePr,\n manual = false,\n) {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const ids = new Set<string>();\n for (let page = 0; page < 20; page++) {\n const result: ClosingIssuesQuery = await context.clients.graphql(\n `query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor${manual ? ',userLinkedOnly:true' : ''}){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,\n { ...context.repo, number: pr.number, cursor },\n );\n const connection = result.repository?.pullRequest?.closingIssuesReferences;\n if (\n result.repository?.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n result.repository.pullRequest?.id !== pr.node_id ||\n result.repository.pullRequest.number !== pr.number ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100\n )\n throw new DeliveryError('Incomplete or conflicting native closing-reference graph.');\n for (const issue of connection.nodes) {\n if (\n !issue ||\n issue.__typename !== 'Issue' ||\n issue.id !== issueId ||\n issue.number !== issueNumber ||\n issue.repository?.id !== repositoryId ||\n issue.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n ids.has(issue.id)\n )\n throw new DeliveryError(\n 'Non-closing PR has an unintended, duplicate or incomplete native closing association.',\n );\n ids.add(issue.id);\n }\n cursor = pageCursor(connection, cursors);\n if (cursor === null) return [...ids];\n }\n throw new DeliveryError('Native closing-reference graph exceeds the bounded readback window.');\n}\nasync function verifyNonClosingReference(\n context: DeliveryContext,\n issueNumber: number,\n pr: RemotePr,\n forReview = false,\n) {\n const graph = await readNonClosingReference(context, issueNumber, pr, forReview);\n if (graph.closesTarget || graph.allClosing.length || graph.manualClosing.length)\n throw new DeliveryError('Non-closing PR has a closing native PR reference/association.');\n return graph.issue;\n}\n\nfunction nativeId(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\nfunction validSha(value: unknown): value is string {\n return typeof value === 'string' && Sha.test(value);\n}\nfunction validBranch(value: unknown): asserts value is string {\n if (\n typeof value !== 'string' ||\n !Branch.test(value) ||\n value.startsWith('/') ||\n value.endsWith('/') ||\n value.endsWith('.lock')\n )\n throw new DeliveryError('Invalid GitHub branch name.');\n}\nasync function getPr(context: DeliveryContext, prNumber: number) {\n if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())\n throw new DeliveryError('Configured and selected GitHub repository identities disagree.');\n const pr = (await context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })).data;\n if (\n pr.number !== prNumber ||\n typeof pr.base.repo?.full_name !== 'string' ||\n typeof pr.head.repo?.full_name !== 'string' ||\n pr.base.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() ||\n pr.head.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() ||\n !validSha(pr.head.sha) ||\n !validSha(pr.base.sha) ||\n (pr.state !== 'open' && pr.state !== 'closed') ||\n typeof pr.merged !== 'boolean' ||\n typeof pr.draft !== 'boolean' ||\n (pr.merged && pr.state !== 'closed')\n )\n throw new DeliveryError('GitHub PR identity or exact head readback is invalid.');\n validBranch(pr.head.ref);\n validBranch(pr.base.ref);\n return pr;\n}\nasync function verifyPrIssueAssociation(\n context: DeliveryContext,\n prNumber: number,\n issueNumber: number,\n expectedPrId?: string,\n onlyIntended = false,\n expectedIssueId?: string,\n expectedRepositoryId?: string,\n options: { allowMissing?: boolean; missingMessage?: string } = {},\n): Promise<number> {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n let matches = 0;\n for (let page = 0; page < 20; page++) {\n const result: ClosingIssuesQuery = await context.clients.graphql<ClosingIssuesQuery>(\n 'query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: prNumber, cursor },\n );\n const connection = result.repository?.pullRequest?.closingIssuesReferences;\n if (\n typeof result.repository?.nameWithOwner !== 'string' ||\n result.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() ||\n result.repository?.pullRequest?.number !== prNumber ||\n (expectedPrId !== undefined && result.repository?.pullRequest?.id !== expectedPrId) ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100 ||\n typeof connection.pageInfo?.hasNextPage !== 'boolean' ||\n !(connection.pageInfo.endCursor === null || typeof connection.pageInfo.endCursor === 'string')\n )\n throw new DeliveryError('Incomplete or conflicting native GitHub PR issue association readback.');\n for (const issue of connection.nodes) {\n if (\n onlyIntended &&\n (!issue ||\n issue.__typename !== 'Issue' ||\n !nativeId(expectedIssueId) ||\n issue.id !== expectedIssueId ||\n !nativeId(expectedRepositoryId) ||\n issue.repository?.id !== expectedRepositoryId)\n )\n throw new DeliveryError(\n 'Incomplete or conflicting typed closing issue/repository identity before body transition.',\n );\n if (\n !issue ||\n !Number.isSafeInteger(issue.number) ||\n issue.number <= 0 ||\n typeof issue.repository?.nameWithOwner !== 'string' ||\n !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(issue.repository.nameWithOwner)\n )\n throw new DeliveryError('Incomplete native PR closing-issue identity.');\n if (\n issue.number === issueNumber &&\n issue.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase()\n )\n matches++;\n else if (onlyIntended)\n throw new DeliveryError('Existing PR has conflicting closing associations; body transition refused.');\n }\n if (!connection.pageInfo.hasNextPage) {\n if (matches !== 1 && !(matches === 0 && options.allowMissing))\n throw new DeliveryError(\n matches === 0 && options.missingMessage\n ? options.missingMessage\n : 'Native GitHub PR closing-issue association does not identify the intended issue.',\n );\n return matches;\n }\n const next = connection.pageInfo.endCursor;\n if (!next || cursors.has(next)) throw new DeliveryError('Native PR issue pagination did not advance.');\n cursors.add(next);\n cursor = next;\n }\n throw new DeliveryError('Native PR issue association exceeds the bounded readback window.');\n}\ninterface ClosingIssuesQuery {\n repository: {\n nameWithOwner: string;\n pullRequest: {\n id?: string;\n number: number;\n closingIssuesReferences: {\n nodes: Array<{\n __typename?: string;\n id?: string;\n number: number;\n repository: { id?: string; nameWithOwner: string };\n } | null>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n } | null;\n}\nasync function matchingPrs(context: DeliveryContext, branch: string, base?: string, state: 'all' | 'open' = 'all') {\n const matches: Awaited<ReturnType<typeof context.clients.rest.pulls.list>>['data'] = [];\n for (let page = 1; page <= 20; page++) {\n const batch = (\n await context.clients.rest.pulls.list({\n ...context.repo,\n head: `${context.repo.owner}:${branch}`,\n ...(base === undefined ? {} : { base }),\n state,\n page,\n per_page: 100,\n })\n ).data;\n if (!Array.isArray(batch) || batch.some((pr) => !pr || !Number.isSafeInteger(pr.number) || pr.number <= 0))\n throw new DeliveryError('Incomplete GitHub PR match readback.');\n matches.push(...batch);\n if (batch.length < 100) return matches;\n }\n throw new DeliveryError('GitHub PR match history exceeds the bounded readback window.');\n}\nasync function verifyIssuePr(\n context: DeliveryContext,\n issueNumber: number,\n prNumber: number,\n nonClosing = false,\n forReview = false,\n) {\n const pr = await getPr(context, prNumber);\n if (nonClosing) await verifyNonClosingReference(context, issueNumber, pr, forReview);\n else\n await verifyPrIssueAssociation(\n context,\n prNumber,\n issueNumber,\n undefined,\n false,\n undefined,\n undefined,\n forReview && !hasClosingLink(pr.body, issueNumber)\n ? {\n missingMessage: `Missing \\`Closes #${issueNumber}\\` in PR #${prNumber}. Restore it with issue_pr_create(${JSON.stringify({ repo: context.config.repository, issueNumber, head: pr.head.ref })}).`,\n }\n : {},\n );\n if (!pr.merged) {\n const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.head.ref}` })).data;\n if (ref.ref !== `refs/heads/${pr.head.ref}` || ref.object.type !== 'commit' || ref.object.sha !== pr.head.sha)\n throw new DeliveryError('Current remote PR head/ref readback is incomplete or has moved.');\n }\n return pr;\n}\n\nexport async function prInfo(\n context: DeliveryContext,\n input: { issueNumber?: number; prNumber?: number; nonClosing?: boolean },\n) {\n const nonClosing = nonClosingMode(input.nonClosing);\n if (nonClosing && (input.issueNumber === undefined || input.prNumber === undefined))\n throw new DeliveryError('Non-closing inspection requires explicit canonical issue and PR numbers.');\n let number = input.prNumber;\n if (number === undefined) {\n if (input.issueNumber === undefined) throw new DeliveryError('prNumber or issueNumber is required.');\n const branches = await linkedIssueBranches(context, input.issueNumber);\n if (branches.length !== 1)\n throw new DeliveryError(\n 'Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.',\n );\n const branch = branches[0]!.name;\n const matches = await matchingPrs(context, branch);\n if (matches.length !== 1)\n throw new DeliveryError('Select an explicit PR number when the remote issue branch has zero or multiple PRs.');\n number = matches[0]!.number;\n }\n const pr =\n input.issueNumber === undefined\n ? await getPr(context, number)\n : await verifyIssuePr(context, input.issueNumber, number, nonClosing);\n return {\n prNumber: pr.number,\n url: pr.html_url,\n state: pr.state,\n draft: pr.draft,\n headSha: pr.head.sha,\n headBranch: pr.head.ref,\n baseBranch: pr.base.ref,\n merged: pr.merged,\n };\n}\nexport async function listPrs(context: DeliveryContext, state: 'all' | 'closed' | 'open' = 'open') {\n const prs = await context.clients.rest.paginate(context.clients.rest.pulls.list, {\n ...context.repo,\n state,\n per_page: 100,\n });\n return {\n schemaVersion: 'ai-delivery.pr-list@1' as const,\n pullRequests: prs.map((pr) => ({\n number: pr.number,\n state: pr.state,\n draft: pr.draft ?? false,\n headSha: pr.head.sha,\n baseSha: pr.base.sha,\n url: pr.html_url,\n })),\n };\n}\n\n/** Enumerate configured requirements even when a check has never reported. */\nasync function readRequiredCheckNames(context: PrReadContext, base: string) {\n const sources = await branchRuleSources(context, base);\n const { confirmedUnprotected, confirmedRulesetOnly } = await corroborateClassicProtectionAbsence(\n context,\n base,\n sources,\n );\n const names = new Set<string>();\n const required = new Map<string, { name: string; appId: number | null }>();\n let complete = true;\n for (const [index, result] of sources.entries()) {\n if (index === 1 && (confirmedUnprotected || confirmedRulesetOnly)) continue;\n if (\n result.status !== 'fulfilled' ||\n result.value.status !== 200 ||\n !result.value.headers ||\n result.value.headers.link\n ) {\n complete = false;\n continue;\n }\n const data = result.value.data;\n const lists: unknown[] = [];\n if (index === 0) {\n if (!Array.isArray(data)) {\n complete = false;\n continue;\n }\n for (const rule of data) {\n if (typeof rule?.type !== 'string') complete = false;\n if (rule?.type === 'required_status_checks') lists.push(rule.parameters?.required_status_checks);\n }\n } else if (Array.isArray(data) || !data || typeof data !== 'object') complete = false;\n else if (data.required_status_checks === null) lists.push([]);\n else {\n const checks = data?.required_status_checks;\n if (Array.isArray(checks?.checks)) lists.push(checks.checks);\n if (Array.isArray(checks?.contexts))\n lists.push(\n checks.contexts\n .filter(\n (context: unknown) =>\n !Array.isArray(checks?.checks) ||\n !checks.checks.some((check: { context?: unknown } | null) => check?.context === context),\n )\n .map((context: unknown) => ({ context })),\n );\n if (!Array.isArray(checks?.checks) && !Array.isArray(checks?.contexts)) complete = false;\n }\n for (const list of lists) {\n const parsed = z\n .array(\n z.object({\n context: z.string().min(1),\n app_id: z.number().int().nullable().optional(),\n integration_id: z.number().int().nullable().optional(),\n }),\n )\n .safeParse(list);\n if (!parsed.success) complete = false;\n else\n for (const check of parsed.data) {\n names.add(check.context);\n const selected = index === 0 ? check.integration_id : check.app_id;\n if (selected !== undefined && selected !== null && selected !== -1 && selected <= 0) complete = false;\n const appId = selected === undefined || selected === null || selected === -1 ? null : selected;\n required.set(JSON.stringify([check.context, appId]), { name: check.context, appId });\n }\n }\n }\n return { names: [...names].sort(), complete, required: [...required.values()] };\n}\n\nexport async function queueChecks(context: DeliveryContext, base: string, sha: string) {\n return readRequiredCheckProof(context, base, sha, false);\n}\nasync function readRequiredCheckProof(context: PrReadContext, base: string, sha: string, allowEmpty: boolean) {\n const requirements = await readRequiredCheckNames(context, base);\n if (!requirements.complete || (!allowEmpty && requirements.required.length === 0))\n return { state: 'waiting' as const, reason: 'Required queue checks are absent or incompletely discovered.' };\n if (requirements.required.length === 0)\n return { state: 'passed' as const, reason: 'Native requirements are completely observed and empty.', proof: [] };\n const [runs, statuses] = await Promise.all([\n context.clients.rest.checks.listForRef({ ...context.repo, ref: sha, filter: 'latest', per_page: 100 }),\n context.clients.rest.repos.getCombinedStatusForRef({ ...context.repo, ref: sha, per_page: 100 }),\n ]);\n if (\n runs.status !== 200 ||\n statuses.status !== 200 ||\n !runs.headers ||\n !statuses.headers ||\n runs.headers?.link ||\n statuses.headers?.link ||\n runs.data.total_count !== runs.data.check_runs.length ||\n statuses.data.total_count !== statuses.data.statuses.length ||\n statuses.data.sha !== sha ||\n runs.data.check_runs.some((run) => run.head_sha !== sha)\n )\n return { state: 'waiting' as const, reason: 'Queue SHA check/status pagination or identity is incomplete.' };\n const proof: { name: string; appId: number | null; id: number }[] = [];\n for (const required of requirements.required) {\n const status = statuses.data.statuses.filter((s) => s.context === required.name).sort((a, b) => b.id - a.id)[0];\n let waiting: string | undefined;\n if (status) {\n if (required.appId !== null) waiting = `Queue status ${required.name} required App source cannot be established.`;\n else if (!Number.isSafeInteger(status.id) || status.id <= 0)\n waiting = `Queue status ${required.name} attempt is unknown.`;\n else if (status.state === 'failure' || status.state === 'error')\n return { state: 'failed' as const, reason: `Queue status ${required.name} is ${status.state}.` };\n else if (status.state !== 'success')\n waiting = `Queue status ${required.name} is ${status.state === 'pending' ? 'pending' : 'unknown'}.`;\n else proof.push({ ...required, id: status.id });\n }\n const candidates = runs.data.check_runs\n .filter((run) => run.name === required.name && (required.appId === null || run.app?.id === required.appId))\n .sort((a, b) => b.id - a.id);\n const run = candidates[0];\n if (run) {\n if (!Number.isSafeInteger(run.id) || run.id <= 0 || !run.app?.id)\n return { state: 'waiting' as const, reason: `Queue check ${required.name} producer/attempt is unknown.` };\n if (run.status !== 'completed')\n return { state: 'waiting' as const, reason: `Queue check ${required.name} is pending.` };\n if (\n run.conclusion !== 'success' &&\n !['failure', 'cancelled', 'timed_out', 'action_required', 'startup_failure', 'stale'].includes(\n run.conclusion ?? '',\n )\n )\n return {\n state: 'waiting' as const,\n reason: `Queue check ${required.name} conclusion is unknown or not successful.`,\n };\n if (run.conclusion !== 'success')\n return {\n state: 'failed' as const,\n reason: `Queue check ${required.name} concluded ${run.conclusion ?? 'unknown'}.`,\n };\n proof.push({ ...required, id: run.id });\n } else if (!status) waiting = `Queue check ${required.name} has not reported from its required source.`;\n if (waiting) return { state: 'waiting' as const, reason: waiting };\n }\n return { state: 'passed' as const, reason: 'Current required queue SHA checks passed.', proof };\n}\n\nexport interface PrBoardFacts {\n repository: { id: string; name: string };\n headRepository: { id: string; name: string };\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed';\n draft: boolean;\n nonClosing: boolean;\n headSha: string;\n baseSha: string;\n headRef: string;\n baseRef: string;\n currentBaseSha: string | null;\n mergeable: string | null;\n mergeStateStatus: string | null;\n review: RequiredReviewState;\n checks: {\n state: 'passed' | 'waiting' | 'failed';\n reason: string;\n complete: boolean;\n proof?: Array<{ name: string; appId: number | null; id: number }>;\n };\n closingLinks: {\n complete: boolean;\n issues: Array<{ id: string; number: number; repository: { id: string; name: string } }>;\n };\n stable: boolean;\n ready: boolean;\n reasons: string[];\n}\ninterface BoardNativePr {\n id: string;\n number: number;\n state: string;\n isDraft: boolean;\n headRefOid: string;\n baseRefOid: string;\n headRefName: string;\n baseRefName: string;\n baseRepository: { id: string; nameWithOwner: string };\n headRepository: { id: string; nameWithOwner: string };\n mergeable: string;\n mergeStateStatus: string;\n closingIssuesReferences: NonNullable<\n NonNullable<ClosingIssuesQuery['repository']>['pullRequest']\n >['closingIssuesReferences'];\n}\n\n/** Current native observations for display only; never a merge grant. Fork heads are readable. */\nexport async function readPrBoardFacts(context: PrReadContext, prNumber: number): Promise<PrBoardFacts> {\n const repository = `${context.repo.owner}/${context.repo.repo}`;\n const pr = (await context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })).data;\n const baseRepo = pr.base.repo;\n const headRepo = pr.head.repo;\n if (\n pr.number !== prNumber ||\n !nativeId(pr.node_id) ||\n pr.html_url?.toLowerCase() !== `https://github.com/${repository}/pull/${prNumber}`.toLowerCase() ||\n typeof pr.title !== 'string' ||\n (pr.body !== null && typeof pr.body !== 'string') ||\n (pr.state !== 'open' && pr.state !== 'closed') ||\n typeof pr.draft !== 'boolean' ||\n typeof pr.merged !== 'boolean' ||\n !baseRepo ||\n !headRepo ||\n !nativeId(baseRepo.node_id) ||\n !nativeId(headRepo.node_id) ||\n typeof baseRepo.full_name !== 'string' ||\n typeof headRepo.full_name !== 'string' ||\n baseRepo.full_name.toLowerCase() !== repository.toLowerCase() ||\n !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(headRepo.full_name) ||\n typeof pr.head.ref !== 'string' ||\n !pr.head.ref ||\n typeof pr.base.ref !== 'string' ||\n !pr.base.ref ||\n !validSha(pr.head.sha) ||\n !validSha(pr.base.sha)\n )\n throw new DeliveryError('Incomplete native PR identity for board display.');\n // Native refs are observed names, not delivery branch inputs. Retain their\n // exact bytes for the native comparisons and encoded API parameters below.\n const baseRepository = { id: baseRepo.node_id, name: baseRepo.full_name };\n const headRepository = { id: headRepo.node_id, name: headRepo.full_name };\n const closingLinks: PrBoardFacts['closingLinks'] = { complete: false, issues: [] };\n let native: BoardNativePr | null = null;\n try {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const issues = new Set<string>();\n const issueNumbers = new Set<string>();\n for (let page = 0; page < 20; page++) {\n const data: { repository: { id: string; nameWithOwner: string; pullRequest: BoardNativePr | null } | null } =\n await context.clients.graphql(\n 'query DeliveryBoardPr($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner pullRequest(number:$number){id number state isDraft headRefOid baseRefOid headRefName baseRefName baseRepository{id nameWithOwner} headRepository{id nameWithOwner} mergeable mergeStateStatus closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: prNumber, cursor },\n );\n const live = data.repository?.pullRequest;\n const links = live?.closingIssuesReferences;\n if (\n data.repository?.id !== baseRepository.id ||\n data.repository.nameWithOwner?.toLowerCase() !== repository.toLowerCase() ||\n live?.id !== pr.node_id ||\n live.number !== prNumber ||\n live.headRefOid !== pr.head.sha ||\n live.baseRefOid !== pr.base.sha ||\n live.headRefName !== pr.head.ref ||\n live.baseRefName !== pr.base.ref ||\n live.baseRepository?.id !== baseRepository.id ||\n live.baseRepository.nameWithOwner?.toLowerCase() !== baseRepository.name.toLowerCase() ||\n live.headRepository?.id !== headRepository.id ||\n live.headRepository.nameWithOwner?.toLowerCase() !== headRepository.name.toLowerCase() ||\n live.state !== (pr.merged ? 'MERGED' : pr.state.toUpperCase()) ||\n live.isDraft !== pr.draft ||\n !['MERGEABLE', 'CONFLICTING', 'UNKNOWN'].includes(live.mergeable) ||\n typeof live.mergeStateStatus !== 'string' ||\n (native !== null &&\n (native.mergeable !== live.mergeable || native.mergeStateStatus !== live.mergeStateStatus)) ||\n !links ||\n !Array.isArray(links.nodes) ||\n links.nodes.length > 100\n )\n throw new DeliveryError('Native PR board snapshot is incomplete or changed.');\n native = live;\n for (const issue of links.nodes) {\n if (\n issue?.__typename !== 'Issue' ||\n !nativeId(issue.id) ||\n !Number.isSafeInteger(issue.number) ||\n issue.number <= 0 ||\n !nativeId(issue.repository?.id) ||\n typeof issue.repository.nameWithOwner !== 'string' ||\n !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(issue.repository.nameWithOwner) ||\n issues.has(issue.id) ||\n issueNumbers.has(`${issue.repository.nameWithOwner.toLowerCase()}#${issue.number}`) ||\n (issue.repository.nameWithOwner.toLowerCase() === repository.toLowerCase() &&\n issue.repository.id !== baseRepository.id)\n )\n throw new DeliveryError('Native closing-issue board identity is incomplete.');\n issues.add(issue.id);\n issueNumbers.add(`${issue.repository.nameWithOwner.toLowerCase()}#${issue.number}`);\n closingLinks.issues.push({\n id: issue.id,\n number: issue.number,\n repository: { id: issue.repository.id, name: issue.repository.nameWithOwner },\n });\n }\n cursor = pageCursor(links, cursors);\n if (cursor === null) {\n closingLinks.complete = true;\n break;\n }\n }\n } catch {\n native = null;\n }\n const [decision, proof] = await Promise.allSettled([\n readRequiredReviewState(context, prNumber, pr.head.sha),\n readRequiredCheckProof(context, pr.base.ref, pr.head.sha, true),\n ]);\n const review: RequiredReviewState =\n decision.status === 'fulfilled'\n ? { ...decision.value, observed: decision.value.observed === true }\n : {\n observed: false,\n reviewDecision: null,\n status: 'unknown',\n submittedReviewAuthorCanPushToRepository: null,\n nextAction: 'Refresh exact-head native review evidence.',\n };\n const checks = {\n ...(proof.status === 'fulfilled'\n ? proof.value\n : { state: 'waiting' as const, reason: 'Native required-check evidence is unavailable.' }),\n complete: proof.status === 'fulfilled' && proof.value.state === 'passed',\n };\n const [current, reread] = await Promise.allSettled([\n context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` }),\n context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber }),\n ]);\n const ref = current.status === 'fulfilled' ? current.value.data : null;\n const currentBaseSha =\n ref?.ref === `refs/heads/${pr.base.ref}` && ref.object.type === 'commit' && validSha(ref.object.sha)\n ? ref.object.sha\n : null;\n const final = reread.status === 'fulfilled' ? reread.value.data : null;\n const stable =\n final !== null &&\n final.node_id === pr.node_id &&\n final.number === pr.number &&\n final.head.sha === pr.head.sha &&\n final.base.sha === pr.base.sha &&\n final.head.ref === pr.head.ref &&\n final.base.ref === pr.base.ref &&\n final.head.repo?.node_id === headRepository.id &&\n final.head.repo.full_name?.toLowerCase() === headRepository.name.toLowerCase() &&\n final.base.repo?.node_id === baseRepository.id &&\n final.base.repo.full_name?.toLowerCase() === baseRepository.name.toLowerCase() &&\n final.state === pr.state &&\n final.merged === pr.merged &&\n final.draft === pr.draft &&\n final.body === pr.body &&\n final.title === pr.title &&\n final.mergeable === pr.mergeable &&\n final.mergeable_state === pr.mergeable_state;\n const reference = /^References ([A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+)#[1-9]\\d*(?:\\r?\\n|$)/u.exec(pr.body ?? '');\n const nonClosing = reference?.[1]?.toLowerCase() === repository.toLowerCase();\n const reasons: string[] = [];\n if (pr.state !== 'open' || pr.merged) reasons.push('pr-closed');\n if (pr.draft) reasons.push('draft');\n if (nonClosing) reasons.push('non-closing');\n if (!native) reasons.push('native-eligibility-unknown');\n else if (\n native.mergeable !== 'MERGEABLE' ||\n native.mergeStateStatus !== 'CLEAN' ||\n pr.mergeable !== true ||\n pr.mergeable_state !== 'clean'\n )\n reasons.push('native-not-clean');\n if (!review.observed) reasons.push('review-unknown');\n else if (review.reviewDecision !== 'APPROVED' && review.reviewDecision !== null)\n reasons.push(review.reviewDecision === 'CHANGES_REQUESTED' ? 'changes-requested' : 'review-required');\n if (checks.state !== 'passed') reasons.push(checks.state === 'failed' ? 'checks-failed' : 'checks-unproven');\n if (!closingLinks.complete) reasons.push('closing-links-unknown');\n else if (\n !closingLinks.issues.some(\n (issue) =>\n issue.repository.id === baseRepository.id && issue.repository.name.toLowerCase() === repository.toLowerCase(),\n )\n )\n reasons.push('no-closing-issue');\n if (!stable) reasons.push('pr-drift-or-unavailable');\n if (currentBaseSha !== pr.base.sha) reasons.push('base-moved-or-unavailable');\n return {\n repository: baseRepository,\n headRepository,\n number: pr.number,\n url: pr.html_url,\n title: pr.title,\n state: pr.state,\n draft: pr.draft,\n nonClosing,\n headSha: pr.head.sha,\n baseSha: pr.base.sha,\n headRef: pr.head.ref,\n baseRef: pr.base.ref,\n currentBaseSha,\n mergeable: native?.mergeable ?? null,\n mergeStateStatus: native?.mergeStateStatus ?? null,\n review,\n checks,\n closingLinks,\n stable,\n ready: reasons.length === 0,\n reasons,\n };\n}\n\nexport async function prChecks(context: DeliveryContext, prNumber: number) {\n const pr = await getPr(context, prNumber);\n const requirements = await readRequiredCheckNames(context, pr.base.ref);\n const [checks, status, reviewState] = await Promise.all([\n context.clients.rest.checks.listForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),\n context.clients.rest.repos.getCombinedStatusForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),\n readRequiredReviewState(context, prNumber, pr.head.sha),\n ]);\n const headChecksComplete =\n checks.data.total_count === checks.data.check_runs.length &&\n status.data.total_count === status.data.statuses.length;\n return {\n schemaVersion: 'ai-delivery.pr-checks@1' as const,\n prNumber: pr.number,\n headSha: pr.head.sha,\n combinedStatus: status.data.state,\n mergeStateStatus: pr.mergeable_state ?? 'unknown',\n requiredCheckDiscovery: requirements.complete ? 'complete' : 'partial',\n headChecksComplete,\n requiredChecks: requirements.names.map((name) => {\n const states = [\n ...checks.data.check_runs\n .filter((check) => check.name === name)\n .map((check) => `check: ${check.status}/${check.conclusion ?? 'pending'}`),\n ...status.data.statuses.filter((check) => check.context === name).map((check) => `status: ${check.state}`),\n ];\n return { name, headState: states.join('; ') || (headChecksComplete ? 'not-reported' : 'unknown') };\n }),\n reviewState,\n checkRuns: checks.data.check_runs.map((check) => ({\n name: check.name,\n status: check.status,\n conclusion: check.conclusion,\n })),\n };\n}\n\nexport interface ReviewRoutePreflight {\n author: { actorLogin: string; authSource: GitHubClients['authSource']; credentialSource: string; identity: string };\n reviewer: {\n actorLogin: string;\n credentialSource: string;\n effectiveContentsPermission: NonNullable<GitHubClients['effectiveContentsPermission']> | 'unknown';\n identity: string;\n repositoryAccess: 'readable';\n };\n rules: { observedRequiredApprovals: number | null; visibility: 'complete' | 'partial' | 'unknown' };\n approvalEligibility: 'unknown' | 'insufficient-permission';\n nextAction: string;\n}\n\nfunction requiredApprovalCount(value: unknown): number | null {\n if (typeof value !== 'object' || value === null) return null;\n const count = (value as Record<string, unknown>).required_approving_review_count;\n return typeof count === 'number' && Number.isSafeInteger(count) && count >= 0 ? count : null;\n}\n\nfunction completeRulePage(response: { status: number; data: unknown; headers: { link?: unknown } }): boolean {\n return (\n response.status === 200 &&\n Array.isArray(response.data) &&\n response.headers !== undefined &&\n response.headers !== null &&\n (response.headers.link === undefined || response.headers.link === '')\n );\n}\n\n/** Absence is proved only by an empty successful first page with no continuation evidence. */\nfunction emptyRulePage(response: { status: number; data: unknown; headers: { link?: unknown } }): boolean {\n return completeRulePage(response) && Array.isArray(response.data) && response.data.length === 0;\n}\n\nfunction branchRuleSources(context: PrReadContext, base: string, control?: { signal: AbortSignal }) {\n return Promise.allSettled([\n context.clients.rest.request('GET /repos/{owner}/{repo}/rules/branches/{branch}', {\n ...context.repo,\n branch: base,\n ...(control === undefined ? {} : { request: { signal: control.signal } }),\n }),\n context.clients.rest.request('GET /repos/{owner}/{repo}/branches/{branch}/protection', {\n ...context.repo,\n branch: base,\n ...(control === undefined ? {} : { request: { signal: control.signal } }),\n }),\n ]);\n}\n\nasync function corroborateClassicProtectionAbsence(\n context: PrReadContext,\n base: string,\n [rulesetResult, protectionResult]: Awaited<ReturnType<typeof branchRuleSources>>,\n control?: { signal: AbortSignal; checkResources: () => Promise<void> },\n) {\n let confirmedUnprotected = false;\n let confirmedRulesetOnly = false;\n if (\n rulesetResult.status === 'fulfilled' &&\n completeRulePage(rulesetResult.value) &&\n protectionResult.status === 'rejected' &&\n githubClients.hasBranchProtectionAbsence(protectionResult.reason, context.clients, context.repo, base)\n ) {\n // A generic/permission 404 is never absence. Corroborate the named branch,\n // selected author's write access, and all repository/parent rulesets.\n const parameters = { ...context.repo, ...(control === undefined ? {} : { request: { signal: control.signal } }) };\n const [repository, branch, rulesets] = await Promise.allSettled([\n context.clients.rest.request('GET /repos/{owner}/{repo}', parameters),\n context.clients.rest.request('GET /repos/{owner}/{repo}/branches/{branch}', { ...parameters, branch: base }),\n context.clients.rest.request('GET /repos/{owner}/{repo}/rulesets', {\n ...parameters,\n includes_parents: true,\n per_page: 100,\n page: 1,\n }),\n ]);\n await control?.checkResources();\n control?.signal.throwIfAborted();\n if (repository.status === 'fulfilled' && branch.status === 'fulfilled' && rulesets.status === 'fulfilled') {\n const repoData = repository.value.data as {\n full_name?: string;\n permissions?: { push?: boolean; admin?: boolean };\n } | null;\n const branchData = branch.value.data as {\n name?: string;\n protected?: boolean;\n protection?: { enabled?: boolean };\n } | null;\n const corroborated =\n repository.value.status === 200 &&\n branch.value.status === 200 &&\n typeof repoData?.full_name === 'string' &&\n repoData.full_name.toLowerCase() === `${context.repo.owner}/${context.repo.repo}`.toLowerCase() &&\n (repoData.permissions?.push === true || repoData.permissions?.admin === true) &&\n branchData?.name === base;\n confirmedUnprotected =\n corroborated &&\n emptyRulePage(rulesetResult.value) &&\n branchData?.protected === false &&\n branchData.protection?.enabled === false &&\n emptyRulePage(rulesets.value);\n // The applicable-rules endpoint includes all active repository/parent\n // rules. A classic-protection 404 needs independent identity and active\n // ruleset readbacks, not just an observed approval count. The aggregate\n // protected flag and nested enabled summary need not be equal.\n confirmedRulesetOnly =\n corroborated &&\n branchData?.protected === true &&\n typeof branchData.protection?.enabled === 'boolean' &&\n completeRulePage(rulesets.value) &&\n rulesetResult.value.data.length > 0 &&\n rulesetResult.value.data.every((rule) => {\n if (\n typeof rule !== 'object' ||\n rule === null ||\n typeof rule.type !== 'string' ||\n !rule.type ||\n typeof rule.ruleset_id !== 'number' ||\n !Number.isSafeInteger(rule.ruleset_id) ||\n rule.ruleset_id <= 0 ||\n typeof rule.ruleset_source !== 'string' ||\n (rule.ruleset_source_type === 'Repository'\n ? rule.ruleset_source.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()\n : rule.ruleset_source_type !== 'Organization' ||\n rule.ruleset_source.toLowerCase() !== context.repo.owner.toLowerCase()) ||\n (rule.type === 'pull_request' && requiredApprovalCount(rule.parameters) === null)\n )\n return false;\n const matches = rulesets.value.data.filter((ruleset) => ruleset?.id === rule.ruleset_id);\n return (\n matches.length === 1 &&\n matches[0]?.source_type === rule.ruleset_source_type &&\n matches[0]?.source === rule.ruleset_source &&\n matches[0]?.enforcement === 'active'\n );\n });\n }\n }\n return { confirmedUnprotected, confirmedRulesetOnly };\n}\n\nasync function routeAuthor(\n context: DeliveryContext,\n purpose: 'development' | 'publication',\n check: () => Promise<void> = async () => {},\n signal?: AbortSignal,\n): Promise<ReviewRoutePreflight['author']> {\n const configuredAuthorSource = context.config.roles.author.authSource ?? 'app';\n const personalDevelopmentOverride =\n purpose === 'development' && configuredAuthorSource === 'app' && context.clients.authSource === 'personal';\n if (context.clients.authSource !== configuredAuthorSource && !personalDevelopmentOverride) {\n throw new DeliveryError(\n purpose === 'publication'\n ? 'PR publication requires the configured author credential; configure the personal author role for personal publication.'\n : 'Development access preflight requires the configured author credential or the explicit personal author override.',\n );\n }\n if (context.clients.role !== 'author' || !context.clients.authenticatedAuthor) {\n throw new DeliveryError('Delivery access preflight requires authenticated author identity readback.');\n }\n const author = await context.clients.authenticatedAuthor(signal);\n await check();\n if (!author.actorLogin || !author.credentialIdentity) {\n throw new DeliveryError('Author GitHub identity readback is incomplete.');\n }\n return {\n actorLogin: author.actorLogin,\n authSource: context.clients.authSource,\n credentialSource: context.clients.credentialSource ?? 'unreported',\n identity: personalDevelopmentOverride ? 'personal' : context.config.roles.author.identity,\n };\n}\n\n/** Check selected actors and rule evidence; publication also requires the configured author source. */\nexport async function preflightReviewRoute(\n context: DeliveryContext,\n base?: string,\n selectedReviewer?: GitHubClients,\n purpose: 'development' | 'publication' = 'publication',\n control?: { signal: AbortSignal; checkResources: () => Promise<void> },\n): Promise<ReviewRoutePreflight> {\n if (base === undefined) {\n try {\n base = (await context.clients.rest.repos.get({ ...context.repo })).data.default_branch;\n } catch {\n throw new DeliveryError('Author cannot read the selected GitHub repository; verify configured access.');\n }\n }\n const check = async (): Promise<void> => {\n await control?.checkResources();\n control?.signal.throwIfAborted();\n };\n await check();\n const author = await routeAuthor(context, purpose, check, control?.signal);\n const reviewer =\n selectedReviewer ??\n context.reviewerClients ??\n (await githubClients.createDeliveryGitHubClients({\n config: context.config,\n identity: context.config.roles.reviewer.identity,\n role: 'reviewer',\n selectedAuthor: context.clients,\n ...(control === undefined ? {} : { signal: control.signal }),\n }));\n await check();\n if (reviewer.role !== 'reviewer' || reviewer.authSource !== 'app' || !reviewer.appActorLogin) {\n throw new DeliveryError('Configured reviewer GitHub App identity is unavailable.');\n }\n const reviewerActor = await reviewer.appActorLogin(control?.signal);\n await check();\n if (!reviewerActor) throw new DeliveryError('Reviewer GitHub App actor lookup is incomplete.');\n if (author.actorLogin.toLowerCase() === reviewerActor.toLowerCase()) {\n throw new DeliveryError(\n 'Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.',\n );\n }\n try {\n const repository = (\n await reviewer.rest.repos.get({\n ...context.repo,\n ...(control === undefined ? {} : { request: { signal: control.signal } }),\n })\n ).data;\n await check();\n if (repository.full_name.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()) {\n throw new DeliveryError('Reviewer GitHub App repository readback disagrees with the selected checkout.');\n }\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError(\n 'Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.',\n );\n }\n const [rulesetResult, protectionResult] = await branchRuleSources(context, base, control);\n await check();\n const { confirmedUnprotected, confirmedRulesetOnly } = await corroborateClassicProtectionAbsence(\n context,\n base,\n [rulesetResult, protectionResult],\n control,\n );\n const counts: number[] = [];\n let countsKnown = rulesetResult.status === 'fulfilled' && completeRulePage(rulesetResult.value);\n if (rulesetResult.status === 'fulfilled' && Array.isArray(rulesetResult.value.data)) {\n for (const rule of rulesetResult.value.data) {\n if (typeof rule !== 'object' || rule === null || typeof rule.type !== 'string' || !rule.type) countsKnown = false;\n if (rule?.type === 'pull_request') {\n const count = requiredApprovalCount(rule.parameters);\n if (count === null) countsKnown = false;\n else counts.push(count);\n }\n }\n }\n if (protectionResult.status === 'fulfilled') {\n const protection = protectionResult.value.data as { required_pull_request_reviews?: unknown };\n const count =\n typeof protection === 'object' && protection !== null && !Array.isArray(protection)\n ? requiredApprovalCount(protection.required_pull_request_reviews)\n : null;\n if (protectionResult.value.status !== 200 || count === null) countsKnown = false;\n if (count !== null) counts.push(count);\n } else if (!confirmedUnprotected && !confirmedRulesetOnly) countsKnown = false;\n const rulesVisible =\n rulesetResult.status === 'fulfilled' &&\n Array.isArray(rulesetResult.value.data) &&\n (rulesetResult.value.headers?.link === undefined || rulesetResult.value.headers.link === '');\n const visible =\n Number(rulesVisible) +\n Number(protectionResult.status === 'fulfilled' || confirmedUnprotected || confirmedRulesetOnly);\n const visibility = visible === 2 ? 'complete' : visible === 1 ? 'partial' : 'unknown';\n // A positive observation is a conservative lower bound for permission checks.\n // Zero requires complete, valid requirement evidence from every source.\n const observedRequiredApprovals =\n counts.length > 0 && (countsKnown || counts.some((count) => count > 0))\n ? Math.max(...counts)\n : countsKnown && confirmedUnprotected\n ? 0\n : null;\n const insufficientPermission =\n observedRequiredApprovals !== null &&\n observedRequiredApprovals > 0 &&\n reviewer.effectiveContentsPermission === 'read';\n return {\n author,\n reviewer: {\n actorLogin: reviewerActor,\n credentialSource: reviewer.credentialSource ?? 'unreported',\n effectiveContentsPermission: reviewer.effectiveContentsPermission ?? 'unknown',\n identity: context.config.roles.reviewer.identity,\n repositoryAccess: 'readable',\n },\n rules: { observedRequiredApprovals, visibility },\n approvalEligibility: insufficientPermission ? 'insufficient-permission' : 'unknown',\n nextAction: insufficientPermission\n ? 'The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.'\n : visibility === 'complete' && observedRequiredApprovals === null\n ? 'No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.'\n : visibility === 'complete'\n ? 'Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.'\n : 'Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.',\n };\n}\n\nexport async function publishPr(\n context: DeliveryContext,\n input: {\n issueNumber: number;\n prNumber?: number;\n nonClosing?: boolean;\n reconcileNonClosingReference?: boolean;\n expectedHeadSha?: string;\n expectedBaseSha?: string;\n body?: string;\n title?: string;\n draft?: boolean;\n headBranch?: string;\n baseBranch?: string;\n dryRun?: boolean;\n },\n) {\n const nonClosing = nonClosingMode(input.nonClosing);\n const reconcileReference = nonClosingMode(input.reconcileNonClosingReference);\n if (reconcileReference) {\n if (\n context.clients.role !== 'author' ||\n context.clients.authSource !== (context.config.roles.author.authSource ?? 'app') ||\n !context.clients.authenticatedAuthor\n )\n throw new DeliveryError('Reference reconciliation requires the configured authenticated author role.');\n if (\n !nonClosing ||\n input.draft === false ||\n !validSha(input.expectedHeadSha) ||\n !validSha(input.expectedBaseSha) ||\n typeof input.body !== 'string' ||\n !input.body.trim()\n )\n throw new DeliveryError(\n 'Reference reconciliation requires nonClosing, DRAFT, explicit safe body and exact expected head/base SHAs.',\n );\n refuseClosingDirective(input.body);\n } else if (input.expectedHeadSha !== undefined || input.expectedBaseSha !== undefined)\n throw new DeliveryError('Expected head/base inputs require explicit reconcileNonClosingReference.');\n if (input.prNumber !== undefined && (!Number.isSafeInteger(input.prNumber) || input.prNumber <= 0))\n throw new DeliveryError('Existing PR selector must be a positive safe integer.');\n const issue = nonClosing\n ? await openReferenceIssue(context, input.issueNumber)\n : (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;\n if ('pull_request' in issue || issue.number !== input.issueNumber || issue.state !== 'open')\n throw new DeliveryError('PR creation requires the requested open GitHub issue.');\n const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;\n if (\n repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() ||\n context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()\n )\n throw new DeliveryError('Configured and selected GitHub repository identities disagree.');\n if (nonClosing && !nativeId(repository.node_id))\n throw new DeliveryError('Incomplete canonical non-closing repository node identity.');\n const base = input.baseBranch ?? repository.default_branch;\n if (base !== repository.default_branch)\n throw new DeliveryError('PR delivery requires the repository default branch for durable issue association.');\n validBranch(base);\n if (input.headBranch !== undefined) validBranch(input.headBranch);\n const explicit = input.prNumber === undefined ? undefined : await getPr(context, input.prNumber);\n const explicitPromotion = nonClosing && input.draft === false && input.headBranch !== undefined;\n const selectedMatches = explicitPromotion ? await matchingPrs(context, input.headBranch!, base) : undefined;\n const branch = explicit\n ? explicit.head.ref\n : nonClosing\n ? explicitPromotion && selectedMatches!.length > 0\n ? input.headBranch!\n : await issueBranch(context, input.issueNumber, input.headBranch)\n : (input.headBranch ?? (await issueBranch(context, input.issueNumber)));\n if (input.headBranch !== undefined && branch !== input.headBranch)\n throw new DeliveryError('Explicit PR and head selectors disagree.');\n validBranch(branch);\n const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n if (ref.ref !== `refs/heads/${branch}` || ref.object.type !== 'commit' || !validSha(ref.object.sha))\n throw new DeliveryError('Remote issue branch head/ref readback is invalid.');\n const matches = selectedMatches ?? (await matchingPrs(context, branch, base, nonClosing ? 'all' : 'open'));\n if (matches.length > 1 || (explicit && (matches.length !== 1 || matches[0]!.number !== explicit.number)))\n throw new DeliveryError('Remote issue branch has conflicting PR matches.');\n let pr = explicit ?? (matches[0] === undefined ? undefined : await getPr(context, matches[0].number));\n if (\n pr &&\n input.draft === false &&\n input.headBranch === undefined &&\n input.prNumber === undefined &&\n (await linkedIssueBranches(context, input.issueNumber)).filter((entry) => entry.name === branch).length !== 1\n )\n throw new DeliveryError('Select an explicit PR or head after GitHub-linked branch references disappear.');\n if (reconcileReference && pr && !explicit)\n throw new DeliveryError(\n 'Reference reconciliation of an existing match requires explicit --pr and caller-reconciled authority/attempt receipts.',\n );\n if (nonClosing && !pr && !reconcileReference)\n throw new DeliveryError(\n 'New linked-branch non-closing publication requires explicitly authorized --reconcile-non-closing-reference --expected-head SHA --expected-base SHA and --body-file PATH; bare --non-closing grants no removal authority.',\n );\n if (reconcileReference && ref.object.sha !== input.expectedHeadSha)\n throw new DeliveryError('Reference reconciliation expected head differs from the exact remote linked head.');\n const requestedBody =\n input.body ?? pr?.body ?? (nonClosing ? referenceLine(context, input.issueNumber) : closingBody(issue));\n if ((nonClosing || input.body !== undefined) && !requestedBody.trim())\n throw new DeliveryError('PR body must contain text.');\n const body = publicationBody(\n nonClosing ? nonClosingBody(context, input.issueNumber, requestedBody) : closingBody(issue, requestedBody),\n pr?.body,\n );\n const closingRepair = !nonClosing && pr !== undefined && !hasClosingLink(pr.body, input.issueNumber);\n const transition = nonClosing && pr !== undefined && pr.body !== body;\n // A PR that already references the issue changes only its body; a closing PR converts (#238).\n const referenceUpdate = transition && hasReferenceBody(context, input.issueNumber, pr?.body);\n if (reconcileReference && transition)\n throw new DeliveryError('Reference reconciliation refuses body transition; retain exact original intent.');\n if (transition && (input.prNumber === undefined || input.body === undefined))\n throw new DeliveryError('Non-closing body transition requires an explicit existing PR number and body.');\n if (\n pr &&\n (pr.head.sha !== ref.object.sha ||\n pr.head.ref !== branch ||\n pr.base.ref !== base ||\n pr.state !== 'open' ||\n pr.merged ||\n (!transition && input.body !== undefined && pr.body !== input.body && pr.body !== body) ||\n (input.title !== undefined && pr.title !== input.title))\n )\n throw new DeliveryError('Existing remote PR conflicts with the requested branch, intent or state.');\n // Opening a closing PR needs only the author; review submission checks the reviewer App.\n const reviewRoute = nonClosing\n ? await nonClosingRoute(context, base)\n : { author: await routeAuthor(context, 'publication') };\n if (pr && pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())\n throw new DeliveryError('Existing PR author differs from the configured authenticated author.');\n if (pr && (typeof pr.node_id !== 'string' || !pr.node_id))\n throw new DeliveryError('Existing PR publication identity is incomplete.');\n if (nonClosing) refuseClosingDirective(input.title ?? pr?.title ?? issue.title);\n const creationTitle = input.title ?? issue.title;\n let publicationBaseSha: string | undefined;\n const existing = pr;\n let pendingTransition = transition;\n let pendingClosingRepair = closingRepair;\n let expectedBody = pr?.body;\n const transitionDraft = pr?.draft;\n let promotionApplied = false;\n let removalState: 'not attempted' | 'acknowledged' | 'uncertain' = 'not attempted';\n const preserveIssue = async () => {\n if (nonClosing) sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));\n };\n const readReconciliation = async (selected: RemotePr) => {\n try {\n if (\n selected.state !== 'open' ||\n selected.draft !== true ||\n selected.merged ||\n selected.head.sha !== input.expectedHeadSha ||\n selected.base.sha !== input.expectedBaseSha ||\n selected.head.ref !== branch ||\n selected.base.ref !== base ||\n selected.body !== body ||\n selected.title !== (existing?.title ?? creationTitle) ||\n selected.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase()\n )\n throw new DeliveryError('Reference reconciliation DRAFT, exact head/base, message or author drifted.');\n const graph = await readNonClosingReference(context, input.issueNumber, selected);\n sameReferenceIssue(issue, graph.issue);\n const safe = !graph.closesTarget && !graph.allClosing.length && !graph.manualClosing.length;\n if (!safe && !(graph.closesTarget && graph.allClosing.length === 1 && graph.manualClosing.length === 1))\n throw new DeliveryError(\n 'Reference removal requires only the intended manual closing pair and closing cross-reference.',\n );\n const currentHead = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n if (\n currentHead.ref !== ref.ref ||\n currentHead.object.type !== 'commit' ||\n currentHead.object.sha !== input.expectedHeadSha\n )\n throw new DeliveryError('Reference reconciliation source head drifted.');\n sameReferencePr(selected, await getPr(context, selected.number));\n await preserveIssue();\n return !safe;\n } catch (error) {\n throw new DeliveryError(\n `PR #${selected.number}; reference removal ${removalState}. Reconcile read-only; do not retry without caller-established authority and attempt history. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n };\n const readExisting = async () => {\n const current =\n reconcileReference || pendingClosingRepair\n ? await getPr(context, existing!.number)\n : await verifyIssuePr(\n context,\n input.issueNumber,\n existing!.number,\n nonClosing && (!pendingTransition || referenceUpdate),\n );\n if (\n current.state !== 'open' ||\n current.merged ||\n current.node_id !== existing!.node_id ||\n current.head.sha !== ref.object.sha ||\n current.head.ref !== branch ||\n current.base.ref !== base ||\n current.base.sha !== existing!.base.sha ||\n current.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase() ||\n ((transition || closingRepair) && !promotionApplied && current.draft !== transitionDraft) ||\n current.body !== expectedBody ||\n current.title !== existing!.title\n )\n throw new DeliveryError('Existing PR publication head, identity, intent or author readback drifted.');\n if (reconcileReference) await readReconciliation(current);\n if (pendingClosingRepair) {\n await verifyPrIssueAssociation(\n context,\n current.number,\n input.issueNumber,\n current.node_id,\n true,\n issue.node_id,\n repository.node_id,\n { allowMissing: true },\n );\n const currentRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n if (currentRef.ref !== ref.ref || currentRef.object.type !== 'commit' || currentRef.object.sha !== ref.object.sha)\n throw new DeliveryError('Closing-link repair remote head drifted; reconcile read-only.');\n sameReferencePr(current, await getPr(context, current.number));\n }\n if (pendingTransition && !referenceUpdate) {\n await verifyPrIssueAssociation(\n context,\n current.number,\n input.issueNumber,\n current.node_id,\n true,\n issue.node_id,\n repository.node_id,\n );\n refuseClosingDirective(current.title);\n await verifyNonClosingCommits(context, current);\n const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;\n if (\n baseRef.ref !== `refs/heads/${base}` ||\n baseRef.object.type !== 'commit' ||\n baseRef.object.sha !== current.base.sha\n )\n throw new DeliveryError('Non-closing transition default base drifted.');\n sameReferencePr(current, await getPr(context, current.number));\n }\n await preserveIssue();\n return current;\n };\n const readNew = async () => {\n const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;\n if (baseRef.ref !== `refs/heads/${base}` || baseRef.object.type !== 'commit' || !validSha(baseRef.object.sha))\n throw new DeliveryError('Incomplete publication default base.');\n if (publicationBaseSha !== undefined && publicationBaseSha !== baseRef.object.sha)\n throw new DeliveryError('Publication default base drifted before creation.');\n publicationBaseSha = baseRef.object.sha;\n if (reconcileReference && publicationBaseSha !== input.expectedBaseSha)\n throw new DeliveryError('Reference reconciliation expected default base differs from the remote base.');\n if (nonClosing) await verifyUnpublishedCommits(context, baseRef.object.sha, ref.object.sha);\n const afterHead = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n const afterBase = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;\n if (\n afterHead.ref !== ref.ref ||\n afterHead.object.type !== 'commit' ||\n afterHead.object.sha !== ref.object.sha ||\n afterBase.ref !== baseRef.ref ||\n afterBase.object.type !== 'commit' ||\n afterBase.object.sha !== baseRef.object.sha\n )\n throw new DeliveryError('Non-closing publication head/base drifted.');\n await preserveIssue();\n };\n if (pr) pr = await readExisting();\n else await readNew();\n if (input.dryRun)\n return {\n dryRun: true,\n ...(pr === undefined ? { body } : {}),\n ...(pr === undefined ? {} : { prNumber: pr.number, draft: pr.draft }),\n ...(nonClosing\n ? {\n nonClosing: true,\n nonClosingVerified: pr !== undefined && !pendingTransition,\n body,\n bodyTransition: pendingTransition,\n }\n : {}),\n headSha: ref.object.sha,\n headBranch: branch,\n baseBranch: base,\n reviewRoute,\n ...(closingRepair ? { closingLinkAdded: false, body } : {}),\n ...(reconcileReference ? { referenceRemoval: 'pending', nonClosingVerified: false } : {}),\n };\n let created = false;\n const warnings: string[] = [];\n if (pr) {\n if (pendingClosingRepair) {\n pr = await readExisting();\n try {\n await context.clients.rest.pulls.update({ ...context.repo, pull_number: pr.number, body });\n } catch (error) {\n throw new DeliveryError(\n `PR #${pr.number} closing-link repair acknowledgement is uncertain; reconcile this PR read-only before retrying. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n pendingClosingRepair = false;\n expectedBody = body;\n pr = await readExisting();\n }\n if (pendingTransition) {\n pr = await readExisting();\n await context.clients.rest.pulls.update({ ...context.repo, pull_number: pr.number, body });\n pendingTransition = false;\n expectedBody = body;\n pr = await readExisting();\n }\n if (input.draft === false && pr.draft) {\n pr = await readExisting();\n if (pr.draft) {\n const promoted = await context.clients.graphql<{\n markPullRequestReadyForReview: { pullRequest: { id: string; isDraft: boolean } | null } | null;\n }>(\n 'mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}',\n { id: pr.node_id },\n );\n if (\n promoted?.markPullRequestReadyForReview?.pullRequest?.id !== pr.node_id ||\n promoted.markPullRequestReadyForReview.pullRequest.isDraft !== false\n )\n throw new DeliveryError('PR promotion mutation readback is incomplete or conflicting; reconcile this PR.');\n promotionApplied = true;\n }\n pr = await readExisting();\n if (pr.draft) throw new DeliveryError('PR promotion readback is still draft.');\n }\n } else {\n await readNew();\n let response;\n try {\n response = await context.clients.rest.pulls.create({\n ...context.repo,\n head: branch,\n base,\n title: creationTitle,\n body,\n draft: input.draft !== false,\n });\n } catch (error) {\n throw new DeliveryError(\n `PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n if (!Number.isSafeInteger(response.data.number) || response.data.number <= 0)\n throw new DeliveryError(\n 'PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.',\n );\n created = true;\n try {\n pr = await getPr(context, response.data.number);\n } catch (error) {\n throw new DeliveryError(\n `GitHub returned created PR #${response.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n }\n try {\n if (\n created &&\n (pr.body !== body ||\n pr.title !== creationTitle ||\n pr.draft !== (input.draft !== false) ||\n pr.state !== 'open' ||\n pr.merged ||\n pr.base.sha !== publicationBaseSha)\n )\n throw new DeliveryError(\n 'Created PR body, title, draft/open state or default base differs from publication intent.',\n );\n if (pr.head.sha !== ref.object.sha || pr.head.ref !== branch || pr.base.ref !== base)\n throw new DeliveryError('GitHub PR creation readback drifted.');\n if (pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())\n throw new DeliveryError('Published PR author differs from the configured authenticated author.');\n if (nonClosing) {\n if (reconcileReference && (await readReconciliation(pr))) {\n // The trusted caller owns the exact grant and prior-attempt history.\n // This invocation never retries this non-transactional native action.\n if (await readReconciliation(pr)) {\n removalState = 'uncertain';\n try {\n const removed = await context.clients.graphql<{\n removeCloseIssueReferences?: { issue?: { id: string } | null } | null;\n }>(\n 'mutation DeliveryRemoveClosingReference($issueId:ID!,$pullRequestIds:[ID!]!,$clientMutationId:String!){removeCloseIssueReferences(input:{issueId:$issueId,pullRequestIds:$pullRequestIds,clientMutationId:$clientMutationId}){issue{id}}}',\n { issueId: issue.node_id, pullRequestIds: [pr.node_id], clientMutationId: randomUUID() },\n );\n if (removed.removeCloseIssueReferences?.issue?.id !== issue.node_id)\n throw new DeliveryError('Incomplete reference-removal acknowledgement.');\n removalState = 'acknowledged';\n } catch (error) {\n throw new DeliveryError(\n `PR #${pr.number}; reference removal acknowledgement is uncertain. Reconcile read-only; no automatic retry or rollback. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n }\n }\n const verified = await verifyIssuePr(context, input.issueNumber, pr.number, true);\n sameReferencePr(pr, verified);\n pr = verified;\n await preserveIssue();\n } else if (\n // GitHub lists a new PR's closing link a few seconds after creation (aviaratech/ai#3780).\n (await verifyPrIssueAssociation(context, pr.number, input.issueNumber, undefined, false, undefined, undefined, {\n allowMissing: created,\n })) === 0\n )\n warnings.push(\n `GitHub has not yet listed PR #${pr.number} as closing #${input.issueNumber}; confirm with issue_pr_info.`,\n );\n if (created) {\n const final = await getPr(context, pr.number);\n sameReferencePr(pr, final);\n pr = final;\n }\n } catch (error) {\n if (!created && !reconcileReference) throw error;\n throw new DeliveryError(\n `GitHub ${created ? 'created' : 'selected'} PR #${pr.number} (${pr.html_url}) at ${pr.head.sha}; post-publication association/identity verification is unresolved.${reconcileReference ? ` Reference removal ${removalState}.` : ''} Reconcile this PR read-only; do not create again. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n return {\n prNumber: pr.number,\n url: pr.html_url,\n headSha: pr.head.sha,\n state: pr.draft ? 'draft' : pr.state,\n ...(closingRepair ? { closingLinkAdded: true } : {}),\n ...(nonClosing ? { nonClosing: true, nonClosingVerified: true } : {}),\n ...(reconcileReference ? { referenceRemoval: removalState } : {}),\n ...(warnings.length ? { warnings } : {}),\n };\n}\n\nexport async function submitFormalReview(\n context: DeliveryContext,\n input: { artifact: string; issueNumber: number; prNumber: number; dryRun?: boolean; nonClosing?: boolean },\n) {\n const nonClosing = nonClosingMode(input.nonClosing);\n const pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing, true);\n const issue = nonClosing ? await openReferenceIssue(context, input.issueNumber) : undefined;\n const result = await submitReview({\n context,\n artifact: parseReviewArtifact(input.artifact),\n issueNumber: input.issueNumber,\n prNumber: input.prNumber,\n ...(input.dryRun === undefined ? {} : { dryRun: input.dryRun }),\n });\n try {\n if (nonClosing) {\n sameReferencePr(pr, await verifyIssuePr(context, input.issueNumber, input.prNumber, true, true));\n sameReferenceIssue(issue!, await openReferenceIssue(context, input.issueNumber));\n }\n if ('dryRun' in result) return result;\n return {\n ...result,\n requiredReview: await readRequiredReviewState(context, input.prNumber, result.headSha, {\n id: result.githubReviewId,\n login: result.login,\n state: result.state,\n }),\n };\n } catch (error) {\n if ('dryRun' in result) throw error;\n throw new ReviewSubmissionError(\n error instanceof DeliveryError ? error.message : 'Post-submission status is unavailable.',\n {\n artifactId: result.artifact.artifactId,\n repository: result.repository,\n headSha: result.headSha,\n prNumber: result.prNumber,\n githubReviewId: result.githubReviewId,\n githubReviewUrl: result.githubReviewUrl,\n },\n );\n }\n}\nexport async function mergePr(\n context: DeliveryContext,\n input: {\n issueNumber: number;\n prNumber: number;\n strategy?: 'merge' | 'squash' | 'rebase';\n reviewedHeadSha?: string;\n dryRun?: boolean;\n nonClosing?: boolean;\n },\n queue?: { expectedBase: string; checkProof(): Promise<void>; beforeMutation(): Promise<void> },\n) {\n const nonClosing = nonClosingMode(input.nonClosing);\n if (nonClosing && input.strategy !== undefined && input.strategy !== 'squash')\n throw new DeliveryError('Non-closing merge requires squash with explicit safe messages.');\n if (\n context.clients.role !== 'author' ||\n context.clients.authSource !== (context.config.roles.author.authSource ?? 'app') ||\n !context.clients.authenticatedAuthor\n )\n throw new DeliveryError('Merge and finish require the configured authenticated author role.');\n const author = await context.clients.authenticatedAuthor();\n if (!author.actorLogin || !author.credentialIdentity)\n throw new DeliveryError('Author identity readback is incomplete.');\n let pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);\n const initialPr = pr;\n const issue = nonClosing ? await openReferenceIssue(context, input.issueNumber) : undefined;\n if (input.reviewedHeadSha !== undefined && input.reviewedHeadSha !== pr.head.sha)\n throw new DeliveryError('Requested reviewed head differs from the GitHub PR.');\n if (pr.merged && pr.state === 'closed' && validSha(pr.merge_commit_sha))\n return { mergeSha: pr.merge_commit_sha, headSha: pr.head.sha, reused: true };\n if (pr.state !== 'open' || pr.draft) throw new DeliveryError('GitHub PR must be open and ready for merge.');\n if (pr.user.login.toLowerCase() !== author.actorLogin.toLowerCase())\n throw new DeliveryError('Merge requires the configured PR author.');\n const squash =\n (input.strategy ?? 'squash') === 'squash'\n ? {\n commit_title: pr.title,\n commit_message: deliverySquashMessage(\n nonClosing\n ? `${referenceLine(context, input.issueNumber)}\\n\\nDelivered by PR #${pr.number}.`\n : pr.body || `Closes #${input.issueNumber}`,\n ),\n }\n : undefined;\n if (nonClosing) {\n refuseClosingDirective(squash!.commit_title);\n refuseClosingDirective(squash!.commit_message);\n }\n const reviewedHead = pr.head.sha;\n const blockers = await getNativeBlockerRelationships({\n graphql: context.clients.graphql,\n issueNumber: input.issueNumber,\n repo: context.repo,\n });\n if (blockers.blockers.some((value) => value.state === 'OPEN'))\n throw new DeliveryError('GitHub issue has unresolved native blockers.');\n pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);\n if (nonClosing) {\n sameReferencePr(initialPr, pr);\n sameReferenceIssue(issue!, await openReferenceIssue(context, input.issueNumber));\n refuseClosingDirective(squash!.commit_title);\n refuseClosingDirective(squash!.commit_message);\n }\n const decision = await readRequiredReviewState(context, input.prNumber, reviewedHead);\n pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);\n if (nonClosing) {\n sameReferencePr(initialPr, pr);\n sameReferenceIssue(issue!, await openReferenceIssue(context, input.issueNumber));\n }\n if (squash && (pr.title !== initialPr.title || pr.body !== initialPr.body))\n throw new DeliveryError('GitHub PR message changed; refresh squash delivery before merge.');\n if (pr.head.sha !== reviewedHead || pr.base.ref !== initialPr.base.ref || pr.base.sha !== initialPr.base.sha)\n throw new DeliveryError('GitHub head/base changed; refresh native merge eligibility.');\n if (\n pr.state !== 'open' ||\n pr.draft ||\n pr.mergeable !== true ||\n !['clean', 'has_hooks', 'unstable'].includes(pr.mergeable_state ?? '') ||\n !decision.observed ||\n (decision.reviewDecision !== 'APPROVED' && decision.reviewDecision !== null)\n ) {\n const requirements = await readRequiredCheckNames(context, pr.base.ref);\n throw new DeliveryError(\n `GitHub merge eligibility is ${pr.mergeable_state ?? 'unknown'}; review eligibility is ${decision.status}. Required checks: ${requirements.names.join(', ') || (requirements.complete ? 'none' : 'unknown')}; requirement discovery is ${requirements.complete ? 'complete' : 'partial'}. ${decision.nextAction}`,\n );\n }\n const currentBase = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data\n .object.sha;\n if (!validSha(currentBase) || currentBase !== pr.base.sha || (queue && currentBase !== queue.expectedBase))\n throw new DeliveryError('GitHub base moved; refresh native merge eligibility before merge.');\n if (input.dryRun)\n return {\n dryRun: true,\n headSha: reviewedHead,\n prNumber: pr.number,\n ...(nonClosing ? { nonClosing: true } : {}),\n ...squash,\n };\n if (queue) {\n await queue.checkProof();\n const finalBase = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data\n .object.sha;\n if (finalBase !== queue.expectedBase)\n throw new DeliveryError('GitHub base moved after queue proof; merge was not sent.');\n await queue.beforeMutation();\n }\n const result = (\n await context.clients.rest.pulls.merge({\n ...context.repo,\n pull_number: input.prNumber,\n sha: reviewedHead,\n merge_method: input.strategy ?? 'squash',\n ...squash,\n })\n ).data;\n if (!result.merged || !validSha(result.sha)) throw new DeliveryError('GitHub refused the reviewed-head merge.');\n const readback = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing);\n if (nonClosing) {\n sameReferencePr(initialPr, readback, true);\n sameReferenceIssue(issue!, await openReferenceIssue(context, input.issueNumber));\n }\n if (\n !readback.merged ||\n readback.state !== 'closed' ||\n readback.head.sha !== reviewedHead ||\n readback.merge_commit_sha !== result.sha\n )\n throw new DeliveryError('GitHub merged PR readback disagrees with the reviewed-head mutation.');\n return { mergeSha: result.sha, headSha: reviewedHead, reused: false };\n}\nexport async function finishIssue(\n context: DeliveryContext,\n input: {\n issueNumber: number;\n prNumber: number;\n strategy?: 'merge' | 'squash' | 'rebase';\n reviewedHeadSha?: string;\n dryRun?: boolean;\n nonClosing?: boolean;\n },\n) {\n if (nonClosingMode(input.nonClosing))\n throw new DeliveryError('Non-closing delivery cannot finish or close its retained issue.');\n const result = await mergePr(context, input);\n if (input.dryRun) return result;\n const pr = await verifyIssuePr(context, input.issueNumber, input.prNumber);\n if (!pr.merged || pr.state !== 'closed' || pr.merge_commit_sha !== result.mergeSha)\n throw new DeliveryError('Intended GitHub PR is not verifiably merged; issue remains open.');\n const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;\n if (issue.number !== input.issueNumber || 'pull_request' in issue)\n throw new DeliveryError('Finish target is not the intended GitHub issue.');\n if (issue.state !== 'closed')\n await context.clients.rest.issues.update({\n ...context.repo,\n issue_number: input.issueNumber,\n state: 'closed',\n state_reason: 'completed',\n });\n const readback = (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;\n if (readback.number !== input.issueNumber || readback.state !== 'closed')\n throw new DeliveryError('GitHub issue closure readback disagrees.');\n return {\n ...result,\n issueClosed: true,\n cleanup: await cleanupFinishedIssue(context, input.issueNumber, pr, result.headSha!, result.mergeSha!),\n };\n}\nasync function cleanupFinishedIssue(\n context: DeliveryContext,\n issueNumber: number,\n pr: Awaited<ReturnType<typeof verifyIssuePr>>,\n headSha: string,\n mergeSha: string,\n): Promise<{ status: 'absent' | 'removed' | 'retained'; reason?: string }> {\n if (!context.root || !existsSync(context.root))\n return { status: 'absent', reason: 'No local checkout selected; no registered source was removed.' };\n try {\n const root = primaryGitRoot(context.root);\n const repo = resolveRepoFromRemote(root, 'origin');\n if (`${repo.owner}/${repo.repo}`.toLowerCase() !== context.config.repository.toLowerCase())\n throw new DeliveryError('Local repository differs from the finished repository; preserve its source.');\n const matches = listWorktreesStrict(root).filter((row) => row.type === 'issue' && row.issueNumber === issueNumber);\n if (matches.length === 0)\n return { status: 'absent', reason: 'No registered issue worktree exists; host-owned source was not adopted.' };\n const row = getIssueWorktreeStrict(issueNumber, root);\n const authorIdentity = context.config.roles.author.identity;\n if (row.identity !== authorIdentity || (row.prNumber !== undefined && row.prNumber !== pr.number))\n throw new DeliveryError('Registered owner or PR differs from the finished delivery; preserve the source.');\n let attestation: MergeCleanupAttestation | undefined;\n const branchPresent = gitExitCode(root, 'show-ref', '--verify', '--quiet', `refs/heads/${row.branch}`) === 0;\n if (branchPresent && gitExitCode(root, 'merge-base', '--is-ancestor', row.branch, defaultBaseRef(root)) !== 0) {\n if (gitExitCode(root, 'cat-file', '-e', `${mergeSha}^{commit}`) !== 0)\n throw new DeliveryError(\n 'Merged source retention is unavailable locally; fetch the verified base before cleanup.',\n );\n const mergeTree = git(root, 'rev-parse', `${mergeSha}^{tree}`);\n if (mergeTree !== git(root, 'rev-parse', `${row.branch}^{tree}`))\n throw new DeliveryError('Merged tree does not retain the source tree; preserve its commits.');\n const base = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data;\n let remoteHeadSha: string | null;\n try {\n remoteHeadSha = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${row.branch}` })).data\n .object.sha;\n } catch (error) {\n if ((error as { status?: number }).status !== 404) throw error;\n remoteHeadSha = null;\n }\n attestation = {\n baseBranch: pr.base.ref,\n baseSha: pr.base.sha,\n headBranch: pr.head.ref,\n headSha,\n mergeSha,\n mergeTree,\n remoteBaseSha: base.object.sha,\n remoteHeadSha,\n strategy: 'squash',\n };\n }\n await reconcileCompletedIssueWorktreeDelivery({\n projectRoot: root,\n issueNumber,\n path: row.path,\n branch: row.branch,\n prNumber: pr.number,\n removeSource: (current) => {\n if (current.identity !== authorIdentity || current.createdAt !== row.createdAt)\n throw new DeliveryError('Registered source ownership changed; preserve the new owner before cleanup.');\n removeFinishedIssueSource(current, root, headSha, attestation);\n },\n });\n return { status: 'removed' };\n } catch (error) {\n return {\n status: 'retained',\n reason:\n error instanceof DeliveryError\n ? error.message\n : 'Cleanup could not prove safe source removal; preserve the worktree and inspect its retention.',\n };\n }\n}\nexport { startIssueBranch };\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,YAAY,mBAAmB;AAE/B,SAAS,qCAAqC;AAC9C,SAAS,aAAa,qBAAqB,wBAA8C;AACzF,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB,gBAAgB,aAAa,WAAW;AACjE,SAAS,6BAA6B;AACtC,SAAS,iCA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,aAAa,kBAAkB,QAAQ,cAAc,IAAI;AACnE,gBAAM,IAAI,cAAc,6EAA6E;AACvG,kCAA0B,SAAS,MAAM,SAAS,WAAW;AAAA,MAC/D;AAAA,IACF,CAAC;AACD,WAAO,EAAE,QAAQ,UAAU;AAAA,EAC7B,SAAS,OAAO;AACd,WAAO;AAAA,MACL,QAAQ;AAAA,MACR,QACE,iBAAiB,gBACb,MAAM,UACN;AAAA,IACR;AAAA,EACF;AACF;",
|
|
6
|
-
"names": ["context", "run"
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod';\nimport { randomUUID } from 'node:crypto';\nimport { DeliveryError } from './errors.js';\nimport * as githubClients from './github/client.js';\nimport type { GitHubClients } from './github/client.js';\nimport { issueBranch, linkedIssueBranches, startIssueBranch, type DeliveryContext } from './issue.js';\nimport {\n parseReviewArtifact,\n readRequiredReviewState,\n ReviewSubmissionError,\n submitReview,\n type RequiredReviewState,\n} from './review.js';\nimport { parseIssueBody } from './issueContract.js';\n\nconst Sha = /^[a-f0-9]{40}$/u;\nconst Branch = /^(?!.*(?:\\.\\.|@\\{|\\/\\/))[A-Za-z0-9._/-]+$/u;\n\nexport type PrReadContext = Pick<DeliveryContext, 'clients' | 'repo'>;\n\nconst DeliveryPrFooter = '\\n\\n<!-- ai-delivery:pr@1 -->';\nfunction activeMarkerPositions(text: string, pattern: RegExp): number[] | null {\n // A bounded context reader, not a Markdown renderer. Resolve blocks before inline\n // quoting; unsupported container/HTML interactions cannot prove a usage marker.\n const ignored: Array<[number, number]> = [];\n const uncertain: Array<[number, number]> = [];\n const inline: Array<[number, number]> = [];\n let paragraph: number | null = null;\n let fence: string | null = null;\n let comment = false;\n let htmlEnd: 'blank' | RegExp | null = null;\n let container = false;\n let quoted = false;\n let blank = true;\n const flush = (end: number) => {\n if (paragraph !== null) inline.push([paragraph, end]);\n paragraph = null;\n };\n for (const line of text.matchAll(/[^\\n]*(?:\\n|$)/gu)) {\n if (!line[0]) continue;\n const start = line.index;\n const end = start + line[0].length;\n const content = line[0].replace(/\\r?\\n$/u, '');\n if (comment) {\n const closing = content.indexOf('-->');\n ignored.push([start, closing < 0 ? end : start + closing + 3]);\n if (closing >= 0) comment = false;\n continue;\n }\n if (htmlEnd !== null) {\n if (htmlEnd === 'blank' && !content.trim()) htmlEnd = null;\n else {\n uncertain.push([start, end]);\n if (htmlEnd !== 'blank' && htmlEnd.test(content)) htmlEnd = null;\n continue;\n }\n }\n const edge = /^ {0,3}(`{3,}|~{3,})(.*)$/u.exec(content);\n if (fence !== null) {\n ignored.push([start, end]);\n if (edge && edge[1]![0] === fence[0] && edge[1]!.length >= fence.length && !edge[2]!.trim()) fence = null;\n continue;\n }\n if (!content.trim()) {\n flush(start);\n quoted = false;\n blank = true;\n continue;\n }\n if (/^ {0,3}>/u.test(content)) {\n flush(start);\n ignored.push([start, end]);\n quoted = true;\n blank = false;\n continue;\n }\n if (blank && /^\\S/u.test(content) && !/^[-+*\\d]/u.test(content)) container = false;\n const indented = /^(?: {4}| {0,3}\\t)/u.test(content);\n if (indented && paragraph === null) {\n (container || quoted ? uncertain : ignored).push([start, end]);\n continue;\n }\n if (edge && (edge[1]![0] !== '`' || !edge[2]!.includes('`'))) {\n flush(start);\n if (container || quoted) uncertain.push([start, text.length]);\n ignored.push([start, end]);\n fence = edge[1]!;\n } else if (/^ {0,3}<!--/u.test(content)) {\n flush(start);\n const opening = content.indexOf('<!--');\n const closing = content.indexOf('-->', opening + 4);\n ignored.push([start + opening + 4, closing < 0 ? end : start + closing + 3]);\n if (closing < 0) comment = true;\n } else if (/^ {0,3}<\\/?[A-Za-z!?]/u.test(content)) {\n flush(start);\n uncertain.push([start, end]);\n const closing = /^ {0,3}<\\?/u.test(content)\n ? /\\?>/u\n : /^ {0,3}<!\\[CDATA\\[/u.test(content)\n ? /\\]\\]>/u\n : /^ {0,3}<!/u.test(content)\n ? />/u\n : /^ {0,3}<(?:pre|script|style|textarea)(?:[ \\t>]|$)/iu.test(content)\n ? /<\\/(?:pre|script|style|textarea)>/iu\n : null;\n htmlEnd = closing === null ? 'blank' : closing.test(content) ? null : closing;\n } else if (\n /^ {0,3}(?:#{1,6}(?:[ \\t]|$)|(?:[-+*]|\\d+[.)])[ \\t])/u.test(content) ||\n /^ {0,3}(?:=+|-+)[ \\t]*$/u.test(content) ||\n /^ {0,3}(?:(?:\\*[ \\t]*){3,}|(?:_[ \\t]*){3,}|(?:-[ \\t]*){3,})$/u.test(content)\n ) {\n flush(start);\n inline.push([start, end]);\n container = /^ {0,3}(?:[-+*]|\\d+[.)])[ \\t]/u.test(content);\n } else {\n if (quoted || container) uncertain.push([start, end]);\n paragraph ??= start;\n }\n blank = false;\n }\n flush(text.length);\n for (const [start, end] of inline) {\n const unit = text.slice(start, end);\n const tokens = /\\\\[\\\\`<]|`+|<!--/gu;\n for (let token = tokens.exec(unit); token; token = tokens.exec(unit)) {\n if (token[0].startsWith('\\\\')) {\n ignored.push([start + token.index + 1, start + tokens.lastIndex]);\n } else if (token[0] === '<!--') {\n const closing = unit.indexOf('-->', tokens.lastIndex);\n if (closing < 0) uncertain.push([start + token.index, end]);\n else {\n ignored.push([start + tokens.lastIndex, start + closing + 3]);\n tokens.lastIndex = closing + 3;\n }\n } else {\n const ticks = /`+/gu;\n ticks.lastIndex = tokens.lastIndex;\n for (let closing = ticks.exec(unit); closing; closing = ticks.exec(unit)) {\n if (closing[0].length !== token[0].length) continue;\n ignored.push([start + token.index, start + ticks.lastIndex]);\n tokens.lastIndex = ticks.lastIndex;\n break;\n }\n }\n }\n }\n const candidates = [...text.matchAll(pattern)].map((match) => match.index);\n if (candidates.some((position) => uncertain.some(([start, end]) => position >= start && position < end))) return null;\n return candidates.filter((position) => !ignored.some(([start, end]) => position >= start && position < end));\n}\n/** A forgeable usage indicator, not publication or merge authority. */\nexport function hasDeliveryPrMarker(body: string): boolean {\n if (!body.endsWith(DeliveryPrFooter)) return false;\n const prefix = body.slice(0, -DeliveryPrFooter.length);\n const active = activeMarkerPositions(body, /<!--\\s*ai-delivery:pr@[^\\n]*?(?:-->|$)/gmu);\n return Boolean(prefix.trim()) && active?.length === 1 && active[0] === prefix.length + 2;\n}\nexport function hasDeliveryMergeTrailer(message: string): boolean {\n const trailer = /\\n\\nDelivered-by: ai-delivery\\n?$/u.exec(message);\n if (!trailer || !message.slice(0, trailer.index).trim()) return false;\n const active = activeMarkerPositions(message, /^Delivered-by: ai-delivery[ \\t]*$/gmu);\n return active?.length === 1 && active[0] === trailer.index + 2;\n}\n\nfunction publicationBody(body: string, previous: string | null | undefined): string {\n function marked(value: string): boolean {\n const active = activeMarkerPositions(value, /<!--\\s*ai-delivery:pr@[^\\n]*?(?:-->|$)/gmu);\n if (active === null || (active.length > 0 && !hasDeliveryPrMarker(value)))\n throw new DeliveryError('PR marker footer is malformed, misplaced or ambiguous; reconcile without repair.');\n return active.length === 1;\n }\n const previousMarked = typeof previous === 'string' && marked(previous);\n const requestedMarked = marked(body);\n if (previous !== undefined && !previousMarked) {\n if (requestedMarked) throw new DeliveryError('Historical unmarked PRs cannot receive a marker footer backfill.');\n return body;\n }\n if (requestedMarked) return body;\n const decorated = body + DeliveryPrFooter;\n if (!hasDeliveryPrMarker(decorated))\n throw new DeliveryError('PR marker footer would be ambiguous; retain the original body without repair.');\n return decorated;\n}\n\nfunction hasClosingLink(body: string | null, issueNumber: number) {\n const line = `Closes #${issueNumber}`;\n return body === line || body?.startsWith(`${line}\\n`) === true || body?.startsWith(`${line}\\r\\n`) === true;\n}\nfunction closingBody(issue: { number: number; title: string; body?: string | null }, requested?: string) {\n const line = `Closes #${issue.number}`;\n if (requested !== undefined)\n return requested.startsWith(`${line}\\n`) || requested === line ? requested : `${line}\\n\\n${requested}`;\n const { outcome, acceptanceCriteria } = parseIssueBody(issue.body ?? '', { title: issue.title }).issue;\n return [\n line,\n ...(outcome ? [`## Outcome\\n\\n${outcome}`] : []),\n ...(acceptanceCriteria.length\n ? [\n `## Acceptance criteria\\n\\n${acceptanceCriteria.map((ac) => `- [ ] ${ac.behavior}\\n Verified by: ${ac.verifiedBy}`).join('\\n')}`,\n ]\n : []),\n ].join('\\n\\n');\n}\n\n// Conservative refusals also cover Markdown decoration/escaped references.\n// This is a closure safety check, never authority for an issue association.\nfunction refuseClosingDirective(text: unknown): asserts text is string {\n if (typeof text !== 'string') throw new DeliveryError('Incomplete non-closing message readback.');\n const normalized = text.replace(/\\[[^\\]\\r\\n]*\\]\\(([^()\\s]+)\\)/gu, '$1').replace(/[*_~`\\\\<>[\\]]/gu, '');\n if (\n /(?<![\\p{L}\\p{N}_-])(?:close[sd]?|fix(?:es|ed)?|resolve[sd]?)(?:\\s*:\\s*|\\s+)(?:#[0-9]+|[A-Za-z0-9.-]+\\/[A-Za-z0-9.-]+#[0-9]+|https?:\\/\\/(?:www\\.)?github\\.com\\/[A-Za-z0-9.-]+\\/[A-Za-z0-9.-]+\\/(?:issues|pull)\\/[0-9]+)/iu.test(\n normalized,\n )\n )\n throw new DeliveryError('Non-closing delivery refuses closing directives in body, title or commit messages.');\n}\nfunction referenceLine(context: DeliveryContext, issueNumber: number) {\n return `References ${context.config.repository}#${issueNumber}`;\n}\nfunction nonClosingBody(context: DeliveryContext, issueNumber: number, requested: string) {\n refuseClosingDirective(requested);\n const line = referenceLine(context, issueNumber);\n const body = requested.startsWith(`${line}\\n`) || requested === line ? requested : `${line}\\n\\n${requested}`;\n verifyReferenceBody(context, issueNumber, body);\n return body;\n}\nfunction hasReferenceBody(context: DeliveryContext, issueNumber: number, body: unknown): boolean {\n try {\n verifyReferenceBody(context, issueNumber, body);\n return true;\n } catch {\n return false;\n }\n}\nfunction verifyReferenceBody(context: DeliveryContext, issueNumber: number, body: unknown): asserts body is string {\n refuseClosingDirective(body);\n const lines = body.split(/\\r?\\n/u);\n if (\n lines[0] !== referenceLine(context, issueNumber) ||\n lines.filter((line) => /^References\\s/iu.test(line)).length !== 1\n )\n throw new DeliveryError('Non-closing PR body must retain one leading canonical References line.');\n}\nfunction pageCursor(connection: { pageInfo?: { hasNextPage: boolean; endCursor: string | null } }, seen: Set<string>) {\n const info = connection.pageInfo;\n if (\n !info ||\n typeof info.hasNextPage !== 'boolean' ||\n !(info.endCursor === null || typeof info.endCursor === 'string')\n )\n throw new DeliveryError('Incomplete non-closing native pagination.');\n if (!info.hasNextPage) return null;\n if (!info.endCursor || seen.has(info.endCursor))\n throw new DeliveryError('Non-closing native pagination did not advance.');\n seen.add(info.endCursor);\n return info.endCursor;\n}\nasync function openReferenceIssue(context: DeliveryContext, issueNumber: number) {\n const issue = (await context.clients.rest.issues.get({ ...context.repo, issue_number: issueNumber })).data;\n if (\n issue.number !== issueNumber ||\n 'pull_request' in issue ||\n issue.state !== 'open' ||\n typeof issue.node_id !== 'string' ||\n !issue.node_id ||\n typeof issue.title !== 'string' ||\n typeof issue.body !== 'string' ||\n issue.html_url?.toLowerCase() !==\n `https://github.com/${context.config.repository}/issues/${issueNumber}`.toLowerCase()\n )\n throw new DeliveryError('Non-closing delivery requires the exact canonical OPEN issue and complete title/body.');\n return issue;\n}\ntype RemotePr = Awaited<ReturnType<typeof getPr>>;\nfunction sameReferencePr(before: RemotePr, after: RemotePr, expectedMerge = false) {\n if (\n expectedMerge\n ? before.state !== 'open' ||\n before.draft ||\n before.merged ||\n after.state !== 'closed' ||\n after.draft ||\n !after.merged\n : before.state !== after.state || before.draft !== after.draft || before.merged !== after.merged\n )\n throw new DeliveryError('Non-closing PR state/draft/merged readback drifted; reconcile read-only.');\n if (\n before.node_id !== after.node_id ||\n before.head.sha !== after.head.sha ||\n before.head.ref !== after.head.ref ||\n before.base.sha !== after.base.sha ||\n before.base.ref !== after.base.ref ||\n before.body !== after.body ||\n before.title !== after.title ||\n before.user.login.toLowerCase() !== after.user.login.toLowerCase()\n )\n throw new DeliveryError('Non-closing PR identity, reference, message or head/base drifted; reconcile read-only.');\n}\nfunction sameReferenceIssue(\n before: Awaited<ReturnType<typeof openReferenceIssue>>,\n after: Awaited<ReturnType<typeof openReferenceIssue>>,\n) {\n if (before.node_id !== after.node_id || before.title !== after.title || before.body !== after.body)\n throw new DeliveryError('Non-closing issue identity/title/criteria drifted; reconcile read-only.');\n}\nfunction nonClosingMode(value: unknown) {\n if (value !== undefined && typeof value !== 'boolean') throw new DeliveryError('nonClosing must be a boolean.');\n return value === true;\n}\nasync function nonClosingRoute(context: DeliveryContext, base: string) {\n const authorContext =\n context.clients.role === 'author'\n ? context\n : {\n ...context,\n clients: await githubClients.createDeliveryGitHubClients({\n config: context.config,\n ...(context.credentialEnvironment === undefined ? {} : { env: context.credentialEnvironment }),\n identity: context.config.roles.author.identity,\n role: 'author',\n }),\n reviewerClients: context.clients,\n };\n const route = await preflightReviewRoute(authorContext, base);\n if (route.rules.visibility !== 'complete' || route.approvalEligibility === 'insufficient-permission')\n throw new DeliveryError(\n 'Non-closing delivery requires complete native rule visibility and an independent reviewer route.',\n );\n return route;\n}\nasync function verifyNonClosingCommits(context: DeliveryContext, pr: RemotePr) {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const commits = new Map<string, string>();\n let total: number | undefined;\n for (let page = 0; page < 20; page++) {\n const data: {\n repository?: {\n nameWithOwner: string;\n pullRequest?: {\n id: string;\n number: number;\n headRefOid: string;\n baseRefOid: string;\n baseRefName: string;\n commits: {\n totalCount: number;\n nodes: Array<{\n commit: {\n oid: string;\n message: string;\n parents: {\n totalCount: number;\n nodes: Array<{ oid: string }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n };\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n };\n };\n } = await context.clients.graphql(\n 'query DeliveryNonClosingCommits($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number headRefOid baseRefOid baseRefName commits(first:100,after:$cursor){totalCount nodes{commit{oid message parents(first:100){totalCount nodes{oid} pageInfo{hasNextPage endCursor}}}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: pr.number, cursor },\n );\n const live = data.repository?.pullRequest;\n const connection = live?.commits;\n if (\n data.repository?.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n live?.id !== pr.node_id ||\n live.number !== pr.number ||\n live.headRefOid !== pr.head.sha ||\n live.baseRefOid !== pr.base.sha ||\n live.baseRefName !== pr.base.ref ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100 ||\n !Number.isSafeInteger(connection.totalCount) ||\n connection.totalCount < 1 ||\n connection.totalCount > 2000 ||\n (total !== undefined && total !== connection.totalCount)\n )\n throw new DeliveryError('Incomplete or moved introduced commit graph at the non-closing head/base.');\n total = connection.totalCount;\n for (const node of connection.nodes) {\n const commit = node?.commit;\n if (\n !commit ||\n !validSha(commit.oid) ||\n commits.has(commit.oid) ||\n !commit.parents ||\n !Array.isArray(commit.parents.nodes) ||\n commit.parents.nodes.length > 100 ||\n !Number.isSafeInteger(commit.parents.totalCount) ||\n commit.parents.totalCount < 1 ||\n commit.parents.totalCount !== commit.parents.nodes.length ||\n commit.parents.pageInfo?.hasNextPage !== false ||\n commit.parents.nodes.some((parent) => !validSha(parent?.oid))\n )\n throw new DeliveryError('Incomplete, duplicate or truncated introduced commit identity/parents.');\n refuseClosingDirective(commit.message);\n commits.set(commit.oid, commit.message);\n }\n cursor = pageCursor(connection, cursors);\n if (cursor === null) {\n if (commits.size !== total || !commits.has(pr.head.sha))\n throw new DeliveryError('Introduced commit count/head is incomplete.');\n return;\n }\n }\n throw new DeliveryError('Non-closing commit graph exceeds the bounded readback window.');\n}\nasync function verifyUnpublishedCommits(context: DeliveryContext, baseSha: string, headSha: string) {\n const commits = new Set<string>();\n let total: number | undefined;\n for (let page = 1; page <= 20; page++) {\n const comparison = (\n await context.clients.rest.repos.compareCommitsWithBasehead({\n ...context.repo,\n basehead: `${baseSha}...${headSha}`,\n per_page: 100,\n page,\n })\n ).data;\n if (\n comparison.base_commit?.sha !== baseSha ||\n !validSha(comparison.merge_base_commit?.sha) ||\n !['ahead', 'diverged'].includes(comparison.status) ||\n !Number.isSafeInteger(comparison.total_commits) ||\n comparison.total_commits < 1 ||\n comparison.total_commits > 2000 ||\n (total !== undefined && total !== comparison.total_commits) ||\n !Array.isArray(comparison.commits) ||\n comparison.commits.length > 100\n )\n throw new DeliveryError('Incomplete introduced commit range before non-closing publication.');\n total = comparison.total_commits;\n for (const commit of comparison.commits) {\n if (\n !validSha(commit.sha) ||\n commits.has(commit.sha) ||\n !Array.isArray(commit.parents) ||\n commit.parents.length < 1 ||\n commit.parents.length > 100 ||\n commit.parents.some((parent) => !validSha(parent.sha))\n )\n throw new DeliveryError('Incomplete or duplicate introduced commit identity.');\n refuseClosingDirective(commit.commit?.message);\n commits.add(commit.sha);\n }\n if (commits.size === total && commits.has(headSha)) return;\n if (comparison.commits.length < 100)\n throw new DeliveryError('Truncated introduced commit range before publication.');\n }\n throw new DeliveryError('Introduced commit range exceeds the bounded readback window.');\n}\nasync function readNonClosingReference(context: DeliveryContext, issueNumber: number, pr: RemotePr, forReview = false) {\n if (\n typeof pr.node_id !== 'string' ||\n !pr.node_id ||\n pr.html_url?.toLowerCase() !== `https://github.com/${context.config.repository}/pull/${pr.number}`.toLowerCase()\n )\n throw new DeliveryError('Incomplete non-closing PR node identity.');\n verifyReferenceBody(context, issueNumber, pr.body);\n refuseClosingDirective(pr.title);\n const issue = await openReferenceIssue(context, issueNumber);\n const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;\n if (\n repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() ||\n pr.base.ref !== repository.default_branch ||\n typeof repository.node_id !== 'string' ||\n !repository.node_id\n )\n throw new DeliveryError('Non-closing PR must target the canonical default repository/base.');\n const route = await nonClosingRoute(context, pr.base.ref);\n if (pr.user.login.toLowerCase() !== route.author.actorLogin.toLowerCase())\n throw new DeliveryError('Non-closing PR author differs from the configured author.');\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const events = new Map<string, string>();\n let matched = false;\n let closesTarget: boolean | undefined;\n for (let page = 0; page < 20; page++) {\n type Subject = {\n __typename: string;\n id: string;\n number: number;\n repository: { id: string; nameWithOwner: string };\n };\n const data: {\n repository?: {\n id: string;\n nameWithOwner: string;\n issue?: {\n id: string;\n number: number;\n state: string;\n timelineItems: {\n nodes: Array<{\n id: string;\n actor: { login: string } | null;\n isCrossRepository: boolean;\n willCloseTarget: boolean;\n source: Subject;\n target: Subject;\n }>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n };\n };\n } = await context.clients.graphql(\n 'query DeliveryNonClosingReferences($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner issue(number:$number){id number state timelineItems(first:100,after:$cursor,itemTypes:[CROSS_REFERENCED_EVENT]){nodes{... on CrossReferencedEvent{id actor{login} isCrossRepository willCloseTarget source{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}} target{__typename ... on Issue{id number repository{id nameWithOwner}} ... on PullRequest{id number repository{id nameWithOwner}}}}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: issueNumber, cursor },\n );\n const target = data.repository?.issue;\n const connection = target?.timelineItems;\n if (\n data.repository?.id !== repository.node_id ||\n data.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n target?.id !== issue.node_id ||\n target.number !== issueNumber ||\n target.state !== 'OPEN' ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100\n )\n throw new DeliveryError('Incomplete or conflicting native non-closing issue identity.');\n for (const event of connection.nodes) {\n const source = event?.source;\n const referenced = event?.target;\n if (\n !event ||\n !nativeId(event.id) ||\n !source ||\n !referenced ||\n !['Issue', 'PullRequest'].includes(source.__typename) ||\n !nativeId(source.id) ||\n !Number.isSafeInteger(source.number) ||\n source.number <= 0 ||\n !nativeId(source.repository?.id) ||\n typeof source.repository.nameWithOwner !== 'string' ||\n referenced.__typename !== 'Issue' ||\n referenced.id !== issue.node_id ||\n referenced.number !== issueNumber ||\n referenced.repository?.id !== repository.node_id ||\n referenced.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n typeof event.isCrossRepository !== 'boolean' ||\n typeof event.willCloseTarget !== 'boolean' ||\n !nativeId(event.actor?.login)\n )\n throw new DeliveryError('Incomplete native cross-reference event identity/actor.');\n const signature = JSON.stringify([\n source.__typename,\n source.id,\n source.number,\n source.repository.id,\n source.repository.nameWithOwner.toLowerCase(),\n referenced.id,\n referenced.number,\n referenced.repository.id,\n referenced.repository.nameWithOwner.toLowerCase(),\n event.actor.login.toLowerCase(),\n event.isCrossRepository,\n event.willCloseTarget,\n ]);\n if (events.has(event.id) && events.get(event.id) !== signature)\n throw new DeliveryError('Conflicting duplicate native reference event.');\n events.set(event.id, signature);\n if (\n source.id === pr.node_id ||\n (source.__typename === 'PullRequest' &&\n source.number === pr.number &&\n source.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase())\n ) {\n if (\n source.__typename !== 'PullRequest' ||\n source.id !== pr.node_id ||\n source.number !== pr.number ||\n source.repository.id !== repository.node_id ||\n source.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() ||\n event.isCrossRepository ||\n event.actor.login.toLowerCase() !== route.author.actorLogin.toLowerCase()\n )\n throw new DeliveryError('Conflicting, closing or unauthorized native PR reference.');\n if (closesTarget !== undefined && closesTarget !== event.willCloseTarget)\n throw new DeliveryError('Conflicting native PR closing-reference semantics.');\n closesTarget = event.willCloseTarget;\n matched = true;\n }\n }\n cursor = pageCursor(connection, cursors);\n if (cursor === null) break;\n if (page === 19) throw new DeliveryError('Native non-closing references exceed the bounded readback window.');\n }\n if (!matched) throw new DeliveryError('Missing authorized native non-closing PR-to-issue reference.');\n const allClosing = await readClosingReferenceIds(context, issueNumber, issue.node_id, repository.node_id, pr);\n const manualClosing = await readClosingReferenceIds(\n context,\n issueNumber,\n issue.node_id,\n repository.node_id,\n pr,\n true,\n );\n await verifyNonClosingCommits(context, pr);\n if (!pr.merged) {\n const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` })).data;\n if (\n ref.ref !== `refs/heads/${pr.base.ref}` ||\n ref.object.type !== 'commit' ||\n !validSha(ref.object.sha) ||\n (!forReview && ref.object.sha !== pr.base.sha)\n )\n throw new DeliveryError('Non-closing default base has moved or is incomplete.');\n }\n const after = await openReferenceIssue(context, issueNumber);\n sameReferenceIssue(issue, after);\n sameReferencePr(pr, await getPr(context, pr.number));\n return { issue, closesTarget: closesTarget!, allClosing, manualClosing };\n}\n\n// Both strict verification and the explicit action consume the same complete graph.\n// Reading a closing edge here never supplies authority to remove it.\nasync function readClosingReferenceIds(\n context: DeliveryContext,\n issueNumber: number,\n issueId: string,\n repositoryId: string,\n pr: RemotePr,\n manual = false,\n) {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const ids = new Set<string>();\n for (let page = 0; page < 20; page++) {\n const result: ClosingIssuesQuery = await context.clients.graphql(\n `query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor${manual ? ',userLinkedOnly:true' : ''}){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}`,\n { ...context.repo, number: pr.number, cursor },\n );\n const connection = result.repository?.pullRequest?.closingIssuesReferences;\n if (\n result.repository?.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n result.repository.pullRequest?.id !== pr.node_id ||\n result.repository.pullRequest.number !== pr.number ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100\n )\n throw new DeliveryError('Incomplete or conflicting native closing-reference graph.');\n for (const issue of connection.nodes) {\n if (\n !issue ||\n issue.__typename !== 'Issue' ||\n issue.id !== issueId ||\n issue.number !== issueNumber ||\n issue.repository?.id !== repositoryId ||\n issue.repository.nameWithOwner?.toLowerCase() !== context.config.repository.toLowerCase() ||\n ids.has(issue.id)\n )\n throw new DeliveryError(\n 'Non-closing PR has an unintended, duplicate or incomplete native closing association.',\n );\n ids.add(issue.id);\n }\n cursor = pageCursor(connection, cursors);\n if (cursor === null) return [...ids];\n }\n throw new DeliveryError('Native closing-reference graph exceeds the bounded readback window.');\n}\nasync function verifyNonClosingReference(\n context: DeliveryContext,\n issueNumber: number,\n pr: RemotePr,\n forReview = false,\n) {\n const graph = await readNonClosingReference(context, issueNumber, pr, forReview);\n if (graph.closesTarget || graph.allClosing.length || graph.manualClosing.length)\n throw new DeliveryError('Non-closing PR has a closing native PR reference/association.');\n return graph.issue;\n}\n\nfunction nativeId(value: unknown): value is string {\n return typeof value === 'string' && value.trim().length > 0;\n}\nfunction validSha(value: unknown): value is string {\n return typeof value === 'string' && Sha.test(value);\n}\nfunction validBranch(value: unknown): asserts value is string {\n if (\n typeof value !== 'string' ||\n !Branch.test(value) ||\n value.startsWith('/') ||\n value.endsWith('/') ||\n value.endsWith('.lock')\n )\n throw new DeliveryError('Invalid GitHub branch name.');\n}\nasync function getPr(context: DeliveryContext, prNumber: number) {\n if (context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase())\n throw new DeliveryError('Configured and selected GitHub repository identities disagree.');\n const pr = (await context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })).data;\n if (\n pr.number !== prNumber ||\n typeof pr.base.repo?.full_name !== 'string' ||\n typeof pr.head.repo?.full_name !== 'string' ||\n pr.base.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() ||\n pr.head.repo?.full_name.toLowerCase() !== context.config.repository.toLowerCase() ||\n !validSha(pr.head.sha) ||\n !validSha(pr.base.sha) ||\n (pr.state !== 'open' && pr.state !== 'closed') ||\n typeof pr.merged !== 'boolean' ||\n typeof pr.draft !== 'boolean' ||\n (pr.merged && pr.state !== 'closed')\n )\n throw new DeliveryError('GitHub PR identity or exact head readback is invalid.');\n validBranch(pr.head.ref);\n validBranch(pr.base.ref);\n return pr;\n}\nasync function verifyPrIssueAssociation(\n context: DeliveryContext,\n prNumber: number,\n issueNumber: number,\n expectedPrId?: string,\n onlyIntended = false,\n expectedIssueId?: string,\n expectedRepositoryId?: string,\n options: { allowMissing?: boolean; missingMessage?: string } = {},\n): Promise<number> {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n let matches = 0;\n for (let page = 0; page < 20; page++) {\n const result: ClosingIssuesQuery = await context.clients.graphql<ClosingIssuesQuery>(\n 'query DeliveryClosingIssues($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){nameWithOwner pullRequest(number:$number){id number closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: prNumber, cursor },\n );\n const connection = result.repository?.pullRequest?.closingIssuesReferences;\n if (\n typeof result.repository?.nameWithOwner !== 'string' ||\n result.repository.nameWithOwner.toLowerCase() !== context.config.repository.toLowerCase() ||\n result.repository?.pullRequest?.number !== prNumber ||\n (expectedPrId !== undefined && result.repository?.pullRequest?.id !== expectedPrId) ||\n !connection ||\n !Array.isArray(connection.nodes) ||\n connection.nodes.length > 100 ||\n typeof connection.pageInfo?.hasNextPage !== 'boolean' ||\n !(connection.pageInfo.endCursor === null || typeof connection.pageInfo.endCursor === 'string')\n )\n throw new DeliveryError('Incomplete or conflicting native GitHub PR issue association readback.');\n for (const issue of connection.nodes) {\n if (\n onlyIntended &&\n (!issue ||\n issue.__typename !== 'Issue' ||\n !nativeId(expectedIssueId) ||\n issue.id !== expectedIssueId ||\n !nativeId(expectedRepositoryId) ||\n issue.repository?.id !== expectedRepositoryId)\n )\n throw new DeliveryError(\n 'Incomplete or conflicting typed closing issue/repository identity before body transition.',\n );\n if (\n !issue ||\n !Number.isSafeInteger(issue.number) ||\n issue.number <= 0 ||\n typeof issue.repository?.nameWithOwner !== 'string' ||\n !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(issue.repository.nameWithOwner)\n )\n throw new DeliveryError('Incomplete native PR closing-issue identity.');\n if (\n issue.number === issueNumber &&\n issue.repository.nameWithOwner.toLowerCase() === context.config.repository.toLowerCase()\n )\n matches++;\n else if (onlyIntended)\n throw new DeliveryError('Existing PR has conflicting closing associations; body transition refused.');\n }\n if (!connection.pageInfo.hasNextPage) {\n if (matches !== 1 && !(matches === 0 && options.allowMissing))\n throw new DeliveryError(\n matches === 0 && options.missingMessage\n ? options.missingMessage\n : 'Native GitHub PR closing-issue association does not identify the intended issue.',\n );\n return matches;\n }\n const next = connection.pageInfo.endCursor;\n if (!next || cursors.has(next)) throw new DeliveryError('Native PR issue pagination did not advance.');\n cursors.add(next);\n cursor = next;\n }\n throw new DeliveryError('Native PR issue association exceeds the bounded readback window.');\n}\ninterface ClosingIssuesQuery {\n repository: {\n nameWithOwner: string;\n pullRequest: {\n id?: string;\n number: number;\n closingIssuesReferences: {\n nodes: Array<{\n __typename?: string;\n id?: string;\n number: number;\n repository: { id?: string; nameWithOwner: string };\n } | null>;\n pageInfo: { hasNextPage: boolean; endCursor: string | null };\n };\n } | null;\n } | null;\n}\nasync function matchingPrs(context: DeliveryContext, branch: string, base?: string, state: 'all' | 'open' = 'all') {\n const matches: Awaited<ReturnType<typeof context.clients.rest.pulls.list>>['data'] = [];\n for (let page = 1; page <= 20; page++) {\n const batch = (\n await context.clients.rest.pulls.list({\n ...context.repo,\n head: `${context.repo.owner}:${branch}`,\n ...(base === undefined ? {} : { base }),\n state,\n page,\n per_page: 100,\n })\n ).data;\n if (!Array.isArray(batch) || batch.some((pr) => !pr || !Number.isSafeInteger(pr.number) || pr.number <= 0))\n throw new DeliveryError('Incomplete GitHub PR match readback.');\n matches.push(...batch);\n if (batch.length < 100) return matches;\n }\n throw new DeliveryError('GitHub PR match history exceeds the bounded readback window.');\n}\nasync function verifyIssuePr(\n context: DeliveryContext,\n issueNumber: number,\n prNumber: number,\n nonClosing = false,\n forReview = false,\n) {\n const pr = await getPr(context, prNumber);\n if (nonClosing) await verifyNonClosingReference(context, issueNumber, pr, forReview);\n else\n await verifyPrIssueAssociation(\n context,\n prNumber,\n issueNumber,\n undefined,\n false,\n undefined,\n undefined,\n forReview && !hasClosingLink(pr.body, issueNumber)\n ? {\n missingMessage: `Missing \\`Closes #${issueNumber}\\` in PR #${prNumber}. Restore it with issue_pr_create(${JSON.stringify({ repo: context.config.repository, issueNumber, head: pr.head.ref })}).`,\n }\n : {},\n );\n if (!pr.merged) {\n const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.head.ref}` })).data;\n if (ref.ref !== `refs/heads/${pr.head.ref}` || ref.object.type !== 'commit' || ref.object.sha !== pr.head.sha)\n throw new DeliveryError('Current remote PR head/ref readback is incomplete or has moved.');\n }\n return pr;\n}\n\nexport async function prInfo(\n context: DeliveryContext,\n input: { issueNumber?: number; prNumber?: number; nonClosing?: boolean },\n) {\n const nonClosing = nonClosingMode(input.nonClosing);\n if (nonClosing && (input.issueNumber === undefined || input.prNumber === undefined))\n throw new DeliveryError('Non-closing inspection requires explicit canonical issue and PR numbers.');\n let number = input.prNumber;\n if (number === undefined) {\n if (input.issueNumber === undefined) throw new DeliveryError('prNumber or issueNumber is required.');\n const branches = await linkedIssueBranches(context, input.issueNumber);\n if (branches.length !== 1)\n throw new DeliveryError(\n 'Issue-only PR inspection requires one GitHub-linked issue branch. After publication, supply the exact issue and PR numbers (CLI --issue and --pr) to verify the native PR closing-issue association.',\n );\n const branch = branches[0]!.name;\n const matches = await matchingPrs(context, branch);\n if (matches.length !== 1)\n throw new DeliveryError('Select an explicit PR number when the remote issue branch has zero or multiple PRs.');\n number = matches[0]!.number;\n }\n const pr =\n input.issueNumber === undefined\n ? await getPr(context, number)\n : await verifyIssuePr(context, input.issueNumber, number, nonClosing);\n return {\n prNumber: pr.number,\n url: pr.html_url,\n state: pr.state,\n draft: pr.draft,\n headSha: pr.head.sha,\n headBranch: pr.head.ref,\n baseBranch: pr.base.ref,\n merged: pr.merged,\n };\n}\nexport async function listPrs(context: DeliveryContext, state: 'all' | 'closed' | 'open' = 'open') {\n const prs = await context.clients.rest.paginate(context.clients.rest.pulls.list, {\n ...context.repo,\n state,\n per_page: 100,\n });\n return {\n schemaVersion: 'ai-delivery.pr-list@1' as const,\n pullRequests: prs.map((pr) => ({\n number: pr.number,\n state: pr.state,\n draft: pr.draft ?? false,\n headSha: pr.head.sha,\n baseSha: pr.base.sha,\n url: pr.html_url,\n })),\n };\n}\n\n/** Enumerate configured requirements even when a check has never reported. */\nasync function readRequiredCheckNames(context: PrReadContext, base: string) {\n const sources = await branchRuleSources(context, base);\n const { confirmedUnprotected, confirmedRulesetOnly } = await corroborateClassicProtectionAbsence(\n context,\n base,\n sources,\n );\n const names = new Set<string>();\n const required = new Map<string, { name: string; appId: number | null }>();\n let complete = true;\n for (const [index, result] of sources.entries()) {\n if (index === 1 && (confirmedUnprotected || confirmedRulesetOnly)) continue;\n if (\n result.status !== 'fulfilled' ||\n result.value.status !== 200 ||\n !result.value.headers ||\n result.value.headers.link\n ) {\n complete = false;\n continue;\n }\n const data = result.value.data;\n const lists: unknown[] = [];\n if (index === 0) {\n if (!Array.isArray(data)) {\n complete = false;\n continue;\n }\n for (const rule of data) {\n if (typeof rule?.type !== 'string') complete = false;\n if (rule?.type === 'required_status_checks') lists.push(rule.parameters?.required_status_checks);\n }\n } else if (Array.isArray(data) || !data || typeof data !== 'object') complete = false;\n else if (data.required_status_checks === null) lists.push([]);\n else {\n const checks = data?.required_status_checks;\n if (Array.isArray(checks?.checks)) lists.push(checks.checks);\n if (Array.isArray(checks?.contexts))\n lists.push(\n checks.contexts\n .filter(\n (context: unknown) =>\n !Array.isArray(checks?.checks) ||\n !checks.checks.some((check: { context?: unknown } | null) => check?.context === context),\n )\n .map((context: unknown) => ({ context })),\n );\n if (!Array.isArray(checks?.checks) && !Array.isArray(checks?.contexts)) complete = false;\n }\n for (const list of lists) {\n const parsed = z\n .array(\n z.object({\n context: z.string().min(1),\n app_id: z.number().int().nullable().optional(),\n integration_id: z.number().int().nullable().optional(),\n }),\n )\n .safeParse(list);\n if (!parsed.success) complete = false;\n else\n for (const check of parsed.data) {\n names.add(check.context);\n const selected = index === 0 ? check.integration_id : check.app_id;\n if (selected !== undefined && selected !== null && selected !== -1 && selected <= 0) complete = false;\n const appId = selected === undefined || selected === null || selected === -1 ? null : selected;\n required.set(JSON.stringify([check.context, appId]), { name: check.context, appId });\n }\n }\n }\n return { names: [...names].sort(), complete, required: [...required.values()] };\n}\n\nexport async function queueChecks(context: DeliveryContext, base: string, sha: string) {\n return readRequiredCheckProof(context, base, sha, false);\n}\nasync function readRequiredCheckProof(context: PrReadContext, base: string, sha: string, allowEmpty: boolean) {\n const requirements = await readRequiredCheckNames(context, base);\n if (!requirements.complete || (!allowEmpty && requirements.required.length === 0))\n return { state: 'waiting' as const, reason: 'Required queue checks are absent or incompletely discovered.' };\n if (requirements.required.length === 0)\n return { state: 'passed' as const, reason: 'Native requirements are completely observed and empty.', proof: [] };\n const [runs, statuses] = await Promise.all([\n context.clients.rest.checks.listForRef({ ...context.repo, ref: sha, filter: 'latest', per_page: 100 }),\n context.clients.rest.repos.getCombinedStatusForRef({ ...context.repo, ref: sha, per_page: 100 }),\n ]);\n if (\n runs.status !== 200 ||\n statuses.status !== 200 ||\n !runs.headers ||\n !statuses.headers ||\n runs.headers?.link ||\n statuses.headers?.link ||\n runs.data.total_count !== runs.data.check_runs.length ||\n statuses.data.total_count !== statuses.data.statuses.length ||\n statuses.data.sha !== sha ||\n runs.data.check_runs.some((run) => run.head_sha !== sha)\n )\n return { state: 'waiting' as const, reason: 'Queue SHA check/status pagination or identity is incomplete.' };\n const proof: { name: string; appId: number | null; id: number }[] = [];\n for (const required of requirements.required) {\n const status = statuses.data.statuses.filter((s) => s.context === required.name).sort((a, b) => b.id - a.id)[0];\n let waiting: string | undefined;\n if (status) {\n if (required.appId !== null) waiting = `Queue status ${required.name} required App source cannot be established.`;\n else if (!Number.isSafeInteger(status.id) || status.id <= 0)\n waiting = `Queue status ${required.name} attempt is unknown.`;\n else if (status.state === 'failure' || status.state === 'error')\n return { state: 'failed' as const, reason: `Queue status ${required.name} is ${status.state}.` };\n else if (status.state !== 'success')\n waiting = `Queue status ${required.name} is ${status.state === 'pending' ? 'pending' : 'unknown'}.`;\n else proof.push({ ...required, id: status.id });\n }\n const candidates = runs.data.check_runs\n .filter((run) => run.name === required.name && (required.appId === null || run.app?.id === required.appId))\n .sort((a, b) => b.id - a.id);\n const run = candidates[0];\n if (run) {\n if (!Number.isSafeInteger(run.id) || run.id <= 0 || !run.app?.id)\n return { state: 'waiting' as const, reason: `Queue check ${required.name} producer/attempt is unknown.` };\n if (run.status !== 'completed')\n return { state: 'waiting' as const, reason: `Queue check ${required.name} is pending.` };\n if (\n run.conclusion !== 'success' &&\n !['failure', 'cancelled', 'timed_out', 'action_required', 'startup_failure', 'stale'].includes(\n run.conclusion ?? '',\n )\n )\n return {\n state: 'waiting' as const,\n reason: `Queue check ${required.name} conclusion is unknown or not successful.`,\n };\n if (run.conclusion !== 'success')\n return {\n state: 'failed' as const,\n reason: `Queue check ${required.name} concluded ${run.conclusion ?? 'unknown'}.`,\n };\n proof.push({ ...required, id: run.id });\n } else if (!status) waiting = `Queue check ${required.name} has not reported from its required source.`;\n if (waiting) return { state: 'waiting' as const, reason: waiting };\n }\n return { state: 'passed' as const, reason: 'Current required queue SHA checks passed.', proof };\n}\n\nexport interface PrBoardFacts {\n repository: { id: string; name: string };\n headRepository: { id: string; name: string };\n number: number;\n url: string;\n title: string;\n state: 'open' | 'closed';\n draft: boolean;\n nonClosing: boolean;\n headSha: string;\n baseSha: string;\n headRef: string;\n baseRef: string;\n currentBaseSha: string | null;\n mergeable: string | null;\n mergeStateStatus: string | null;\n review: RequiredReviewState;\n checks: {\n state: 'passed' | 'waiting' | 'failed';\n reason: string;\n complete: boolean;\n proof?: Array<{ name: string; appId: number | null; id: number }>;\n };\n closingLinks: {\n complete: boolean;\n issues: Array<{ id: string; number: number; repository: { id: string; name: string } }>;\n };\n stable: boolean;\n ready: boolean;\n reasons: string[];\n}\ninterface BoardNativePr {\n id: string;\n number: number;\n state: string;\n isDraft: boolean;\n headRefOid: string;\n baseRefOid: string;\n headRefName: string;\n baseRefName: string;\n baseRepository: { id: string; nameWithOwner: string };\n headRepository: { id: string; nameWithOwner: string };\n mergeable: string;\n mergeStateStatus: string;\n closingIssuesReferences: NonNullable<\n NonNullable<ClosingIssuesQuery['repository']>['pullRequest']\n >['closingIssuesReferences'];\n}\n\n/** Current native observations for display only; never a merge grant. Fork heads are readable. */\nexport async function readPrBoardFacts(context: PrReadContext, prNumber: number): Promise<PrBoardFacts> {\n const repository = `${context.repo.owner}/${context.repo.repo}`;\n const pr = (await context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber })).data;\n const baseRepo = pr.base.repo;\n const headRepo = pr.head.repo;\n if (\n pr.number !== prNumber ||\n !nativeId(pr.node_id) ||\n pr.html_url?.toLowerCase() !== `https://github.com/${repository}/pull/${prNumber}`.toLowerCase() ||\n typeof pr.title !== 'string' ||\n (pr.body !== null && typeof pr.body !== 'string') ||\n (pr.state !== 'open' && pr.state !== 'closed') ||\n typeof pr.draft !== 'boolean' ||\n typeof pr.merged !== 'boolean' ||\n !baseRepo ||\n !headRepo ||\n !nativeId(baseRepo.node_id) ||\n !nativeId(headRepo.node_id) ||\n typeof baseRepo.full_name !== 'string' ||\n typeof headRepo.full_name !== 'string' ||\n baseRepo.full_name.toLowerCase() !== repository.toLowerCase() ||\n !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(headRepo.full_name) ||\n typeof pr.head.ref !== 'string' ||\n !pr.head.ref ||\n typeof pr.base.ref !== 'string' ||\n !pr.base.ref ||\n !validSha(pr.head.sha) ||\n !validSha(pr.base.sha)\n )\n throw new DeliveryError('Incomplete native PR identity for board display.');\n // Native refs are observed names, not delivery branch inputs. Retain their\n // exact bytes for the native comparisons and encoded API parameters below.\n const baseRepository = { id: baseRepo.node_id, name: baseRepo.full_name };\n const headRepository = { id: headRepo.node_id, name: headRepo.full_name };\n const closingLinks: PrBoardFacts['closingLinks'] = { complete: false, issues: [] };\n let native: BoardNativePr | null = null;\n try {\n let cursor: string | null = null;\n const cursors = new Set<string>();\n const issues = new Set<string>();\n const issueNumbers = new Set<string>();\n for (let page = 0; page < 20; page++) {\n const data: { repository: { id: string; nameWithOwner: string; pullRequest: BoardNativePr | null } | null } =\n await context.clients.graphql(\n 'query DeliveryBoardPr($owner:String!,$repo:String!,$number:Int!,$cursor:String){repository(owner:$owner,name:$repo){id nameWithOwner pullRequest(number:$number){id number state isDraft headRefOid baseRefOid headRefName baseRefName baseRepository{id nameWithOwner} headRepository{id nameWithOwner} mergeable mergeStateStatus closingIssuesReferences(first:100,after:$cursor){nodes{__typename id number repository{id nameWithOwner}} pageInfo{hasNextPage endCursor}}}}}',\n { ...context.repo, number: prNumber, cursor },\n );\n const live = data.repository?.pullRequest;\n const links = live?.closingIssuesReferences;\n if (\n data.repository?.id !== baseRepository.id ||\n data.repository.nameWithOwner?.toLowerCase() !== repository.toLowerCase() ||\n live?.id !== pr.node_id ||\n live.number !== prNumber ||\n live.headRefOid !== pr.head.sha ||\n live.baseRefOid !== pr.base.sha ||\n live.headRefName !== pr.head.ref ||\n live.baseRefName !== pr.base.ref ||\n live.baseRepository?.id !== baseRepository.id ||\n live.baseRepository.nameWithOwner?.toLowerCase() !== baseRepository.name.toLowerCase() ||\n live.headRepository?.id !== headRepository.id ||\n live.headRepository.nameWithOwner?.toLowerCase() !== headRepository.name.toLowerCase() ||\n live.state !== (pr.merged ? 'MERGED' : pr.state.toUpperCase()) ||\n live.isDraft !== pr.draft ||\n !['MERGEABLE', 'CONFLICTING', 'UNKNOWN'].includes(live.mergeable) ||\n typeof live.mergeStateStatus !== 'string' ||\n (native !== null &&\n (native.mergeable !== live.mergeable || native.mergeStateStatus !== live.mergeStateStatus)) ||\n !links ||\n !Array.isArray(links.nodes) ||\n links.nodes.length > 100\n )\n throw new DeliveryError('Native PR board snapshot is incomplete or changed.');\n native = live;\n for (const issue of links.nodes) {\n if (\n issue?.__typename !== 'Issue' ||\n !nativeId(issue.id) ||\n !Number.isSafeInteger(issue.number) ||\n issue.number <= 0 ||\n !nativeId(issue.repository?.id) ||\n typeof issue.repository.nameWithOwner !== 'string' ||\n !/^[A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+$/u.test(issue.repository.nameWithOwner) ||\n issues.has(issue.id) ||\n issueNumbers.has(`${issue.repository.nameWithOwner.toLowerCase()}#${issue.number}`) ||\n (issue.repository.nameWithOwner.toLowerCase() === repository.toLowerCase() &&\n issue.repository.id !== baseRepository.id)\n )\n throw new DeliveryError('Native closing-issue board identity is incomplete.');\n issues.add(issue.id);\n issueNumbers.add(`${issue.repository.nameWithOwner.toLowerCase()}#${issue.number}`);\n closingLinks.issues.push({\n id: issue.id,\n number: issue.number,\n repository: { id: issue.repository.id, name: issue.repository.nameWithOwner },\n });\n }\n cursor = pageCursor(links, cursors);\n if (cursor === null) {\n closingLinks.complete = true;\n break;\n }\n }\n } catch {\n native = null;\n }\n const [decision, proof] = await Promise.allSettled([\n readRequiredReviewState(context, prNumber, pr.head.sha),\n readRequiredCheckProof(context, pr.base.ref, pr.head.sha, true),\n ]);\n const review: RequiredReviewState =\n decision.status === 'fulfilled'\n ? { ...decision.value, observed: decision.value.observed === true }\n : {\n observed: false,\n reviewDecision: null,\n status: 'unknown',\n submittedReviewAuthorCanPushToRepository: null,\n nextAction: 'Refresh exact-head native review evidence.',\n };\n const checks = {\n ...(proof.status === 'fulfilled'\n ? proof.value\n : { state: 'waiting' as const, reason: 'Native required-check evidence is unavailable.' }),\n complete: proof.status === 'fulfilled' && proof.value.state === 'passed',\n };\n const [current, reread] = await Promise.allSettled([\n context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${pr.base.ref}` }),\n context.clients.rest.pulls.get({ ...context.repo, pull_number: prNumber }),\n ]);\n const ref = current.status === 'fulfilled' ? current.value.data : null;\n const currentBaseSha =\n ref?.ref === `refs/heads/${pr.base.ref}` && ref.object.type === 'commit' && validSha(ref.object.sha)\n ? ref.object.sha\n : null;\n const final = reread.status === 'fulfilled' ? reread.value.data : null;\n const stable =\n final !== null &&\n final.node_id === pr.node_id &&\n final.number === pr.number &&\n final.head.sha === pr.head.sha &&\n final.base.sha === pr.base.sha &&\n final.head.ref === pr.head.ref &&\n final.base.ref === pr.base.ref &&\n final.head.repo?.node_id === headRepository.id &&\n final.head.repo.full_name?.toLowerCase() === headRepository.name.toLowerCase() &&\n final.base.repo?.node_id === baseRepository.id &&\n final.base.repo.full_name?.toLowerCase() === baseRepository.name.toLowerCase() &&\n final.state === pr.state &&\n final.merged === pr.merged &&\n final.draft === pr.draft &&\n final.body === pr.body &&\n final.title === pr.title &&\n final.mergeable === pr.mergeable &&\n final.mergeable_state === pr.mergeable_state;\n const reference = /^References ([A-Za-z0-9_.-]+\\/[A-Za-z0-9_.-]+)#[1-9]\\d*(?:\\r?\\n|$)/u.exec(pr.body ?? '');\n const nonClosing = reference?.[1]?.toLowerCase() === repository.toLowerCase();\n const reasons: string[] = [];\n if (pr.state !== 'open' || pr.merged) reasons.push('pr-closed');\n if (pr.draft) reasons.push('draft');\n if (nonClosing) reasons.push('non-closing');\n if (!native) reasons.push('native-eligibility-unknown');\n else if (\n native.mergeable !== 'MERGEABLE' ||\n native.mergeStateStatus !== 'CLEAN' ||\n pr.mergeable !== true ||\n pr.mergeable_state !== 'clean'\n )\n reasons.push('native-not-clean');\n if (!review.observed) reasons.push('review-unknown');\n else if (review.reviewDecision !== 'APPROVED' && review.reviewDecision !== null)\n reasons.push(review.reviewDecision === 'CHANGES_REQUESTED' ? 'changes-requested' : 'review-required');\n if (checks.state !== 'passed') reasons.push(checks.state === 'failed' ? 'checks-failed' : 'checks-unproven');\n if (!closingLinks.complete) reasons.push('closing-links-unknown');\n else if (\n !closingLinks.issues.some(\n (issue) =>\n issue.repository.id === baseRepository.id && issue.repository.name.toLowerCase() === repository.toLowerCase(),\n )\n )\n reasons.push('no-closing-issue');\n if (!stable) reasons.push('pr-drift-or-unavailable');\n if (currentBaseSha !== pr.base.sha) reasons.push('base-moved-or-unavailable');\n return {\n repository: baseRepository,\n headRepository,\n number: pr.number,\n url: pr.html_url,\n title: pr.title,\n state: pr.state,\n draft: pr.draft,\n nonClosing,\n headSha: pr.head.sha,\n baseSha: pr.base.sha,\n headRef: pr.head.ref,\n baseRef: pr.base.ref,\n currentBaseSha,\n mergeable: native?.mergeable ?? null,\n mergeStateStatus: native?.mergeStateStatus ?? null,\n review,\n checks,\n closingLinks,\n stable,\n ready: reasons.length === 0,\n reasons,\n };\n}\n\nexport async function prChecks(context: DeliveryContext, prNumber: number) {\n const pr = await getPr(context, prNumber);\n const requirements = await readRequiredCheckNames(context, pr.base.ref);\n const [checks, status, reviewState] = await Promise.all([\n context.clients.rest.checks.listForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),\n context.clients.rest.repos.getCombinedStatusForRef({ ...context.repo, ref: pr.head.sha, per_page: 100 }),\n readRequiredReviewState(context, prNumber, pr.head.sha),\n ]);\n const headChecksComplete =\n checks.data.total_count === checks.data.check_runs.length &&\n status.data.total_count === status.data.statuses.length;\n return {\n schemaVersion: 'ai-delivery.pr-checks@1' as const,\n prNumber: pr.number,\n headSha: pr.head.sha,\n combinedStatus: status.data.state,\n mergeStateStatus: pr.mergeable_state ?? 'unknown',\n requiredCheckDiscovery: requirements.complete ? 'complete' : 'partial',\n headChecksComplete,\n requiredChecks: requirements.names.map((name) => {\n const states = [\n ...checks.data.check_runs\n .filter((check) => check.name === name)\n .map((check) => `check: ${check.status}/${check.conclusion ?? 'pending'}`),\n ...status.data.statuses.filter((check) => check.context === name).map((check) => `status: ${check.state}`),\n ];\n return { name, headState: states.join('; ') || (headChecksComplete ? 'not-reported' : 'unknown') };\n }),\n reviewState,\n checkRuns: checks.data.check_runs.map((check) => ({\n name: check.name,\n status: check.status,\n conclusion: check.conclusion,\n })),\n };\n}\n\nexport interface ReviewRoutePreflight {\n author: { actorLogin: string; authSource: GitHubClients['authSource']; credentialSource: string; identity: string };\n reviewer: {\n actorLogin: string;\n credentialSource: string;\n effectiveContentsPermission: NonNullable<GitHubClients['effectiveContentsPermission']> | 'unknown';\n identity: string;\n repositoryAccess: 'readable';\n };\n rules: { observedRequiredApprovals: number | null; visibility: 'complete' | 'partial' | 'unknown' };\n approvalEligibility: 'unknown' | 'insufficient-permission';\n nextAction: string;\n}\n\nfunction requiredApprovalCount(value: unknown): number | null {\n if (typeof value !== 'object' || value === null) return null;\n const count = (value as Record<string, unknown>).required_approving_review_count;\n return typeof count === 'number' && Number.isSafeInteger(count) && count >= 0 ? count : null;\n}\n\nfunction completeRulePage(response: { status: number; data: unknown; headers: { link?: unknown } }): boolean {\n return (\n response.status === 200 &&\n Array.isArray(response.data) &&\n response.headers !== undefined &&\n response.headers !== null &&\n (response.headers.link === undefined || response.headers.link === '')\n );\n}\n\n/** Absence is proved only by an empty successful first page with no continuation evidence. */\nfunction emptyRulePage(response: { status: number; data: unknown; headers: { link?: unknown } }): boolean {\n return completeRulePage(response) && Array.isArray(response.data) && response.data.length === 0;\n}\n\nfunction branchRuleSources(context: PrReadContext, base: string, control?: { signal: AbortSignal }) {\n return Promise.allSettled([\n context.clients.rest.request('GET /repos/{owner}/{repo}/rules/branches/{branch}', {\n ...context.repo,\n branch: base,\n ...(control === undefined ? {} : { request: { signal: control.signal } }),\n }),\n context.clients.rest.request('GET /repos/{owner}/{repo}/branches/{branch}/protection', {\n ...context.repo,\n branch: base,\n ...(control === undefined ? {} : { request: { signal: control.signal } }),\n }),\n ]);\n}\n\nasync function corroborateClassicProtectionAbsence(\n context: PrReadContext,\n base: string,\n [rulesetResult, protectionResult]: Awaited<ReturnType<typeof branchRuleSources>>,\n control?: { signal: AbortSignal; checkResources: () => Promise<void> },\n) {\n let confirmedUnprotected = false;\n let confirmedRulesetOnly = false;\n if (\n rulesetResult.status === 'fulfilled' &&\n completeRulePage(rulesetResult.value) &&\n protectionResult.status === 'rejected' &&\n githubClients.hasBranchProtectionAbsence(protectionResult.reason, context.clients, context.repo, base)\n ) {\n // A generic/permission 404 is never absence. Corroborate the named branch,\n // selected author's write access, and all repository/parent rulesets.\n const parameters = { ...context.repo, ...(control === undefined ? {} : { request: { signal: control.signal } }) };\n const [repository, branch, rulesets] = await Promise.allSettled([\n context.clients.rest.request('GET /repos/{owner}/{repo}', parameters),\n context.clients.rest.request('GET /repos/{owner}/{repo}/branches/{branch}', { ...parameters, branch: base }),\n context.clients.rest.request('GET /repos/{owner}/{repo}/rulesets', {\n ...parameters,\n includes_parents: true,\n per_page: 100,\n page: 1,\n }),\n ]);\n await control?.checkResources();\n control?.signal.throwIfAborted();\n if (repository.status === 'fulfilled' && branch.status === 'fulfilled' && rulesets.status === 'fulfilled') {\n const repoData = repository.value.data as {\n full_name?: string;\n permissions?: { push?: boolean; admin?: boolean };\n } | null;\n const branchData = branch.value.data as {\n name?: string;\n protected?: boolean;\n protection?: { enabled?: boolean };\n } | null;\n const corroborated =\n repository.value.status === 200 &&\n branch.value.status === 200 &&\n typeof repoData?.full_name === 'string' &&\n repoData.full_name.toLowerCase() === `${context.repo.owner}/${context.repo.repo}`.toLowerCase() &&\n (repoData.permissions?.push === true || repoData.permissions?.admin === true) &&\n branchData?.name === base;\n confirmedUnprotected =\n corroborated &&\n emptyRulePage(rulesetResult.value) &&\n branchData?.protected === false &&\n branchData.protection?.enabled === false &&\n emptyRulePage(rulesets.value);\n // The applicable-rules endpoint includes all active repository/parent\n // rules. A classic-protection 404 needs independent identity and active\n // ruleset readbacks, not just an observed approval count. The aggregate\n // protected flag and nested enabled summary need not be equal.\n confirmedRulesetOnly =\n corroborated &&\n branchData?.protected === true &&\n typeof branchData.protection?.enabled === 'boolean' &&\n completeRulePage(rulesets.value) &&\n rulesetResult.value.data.length > 0 &&\n rulesetResult.value.data.every((rule) => {\n if (\n typeof rule !== 'object' ||\n rule === null ||\n typeof rule.type !== 'string' ||\n !rule.type ||\n typeof rule.ruleset_id !== 'number' ||\n !Number.isSafeInteger(rule.ruleset_id) ||\n rule.ruleset_id <= 0 ||\n typeof rule.ruleset_source !== 'string' ||\n (rule.ruleset_source_type === 'Repository'\n ? rule.ruleset_source.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()\n : rule.ruleset_source_type !== 'Organization' ||\n rule.ruleset_source.toLowerCase() !== context.repo.owner.toLowerCase()) ||\n (rule.type === 'pull_request' && requiredApprovalCount(rule.parameters) === null)\n )\n return false;\n const matches = rulesets.value.data.filter((ruleset) => ruleset?.id === rule.ruleset_id);\n return (\n matches.length === 1 &&\n matches[0]?.source_type === rule.ruleset_source_type &&\n matches[0]?.source === rule.ruleset_source &&\n matches[0]?.enforcement === 'active'\n );\n });\n }\n }\n return { confirmedUnprotected, confirmedRulesetOnly };\n}\n\nasync function routeAuthor(\n context: DeliveryContext,\n purpose: 'development' | 'publication',\n check: () => Promise<void> = async () => {},\n signal?: AbortSignal,\n): Promise<ReviewRoutePreflight['author']> {\n const configuredAuthorSource = context.config.roles.author.authSource ?? 'app';\n const personalDevelopmentOverride =\n purpose === 'development' && configuredAuthorSource === 'app' && context.clients.authSource === 'personal';\n if (context.clients.authSource !== configuredAuthorSource && !personalDevelopmentOverride) {\n throw new DeliveryError(\n purpose === 'publication'\n ? 'PR publication requires the configured author credential; configure the personal author role for personal publication.'\n : 'Development access preflight requires the configured author credential or the explicit personal author override.',\n );\n }\n if (context.clients.role !== 'author' || !context.clients.authenticatedAuthor) {\n throw new DeliveryError('Delivery access preflight requires authenticated author identity readback.');\n }\n const author = await context.clients.authenticatedAuthor(signal);\n await check();\n if (!author.actorLogin || !author.credentialIdentity) {\n throw new DeliveryError('Author GitHub identity readback is incomplete.');\n }\n return {\n actorLogin: author.actorLogin,\n authSource: context.clients.authSource,\n credentialSource: context.clients.credentialSource ?? 'unreported',\n identity: personalDevelopmentOverride ? 'personal' : context.config.roles.author.identity,\n };\n}\n\n/** Check selected actors and rule evidence; publication also requires the configured author source. */\nexport async function preflightReviewRoute(\n context: DeliveryContext,\n base?: string,\n selectedReviewer?: GitHubClients,\n purpose: 'development' | 'publication' = 'publication',\n control?: { signal: AbortSignal; checkResources: () => Promise<void> },\n): Promise<ReviewRoutePreflight> {\n if (base === undefined) {\n try {\n base = (await context.clients.rest.repos.get({ ...context.repo })).data.default_branch;\n } catch {\n throw new DeliveryError('Author cannot read the selected GitHub repository; verify configured access.');\n }\n }\n const check = async (): Promise<void> => {\n await control?.checkResources();\n control?.signal.throwIfAborted();\n };\n await check();\n const author = await routeAuthor(context, purpose, check, control?.signal);\n const reviewer =\n selectedReviewer ??\n context.reviewerClients ??\n (await githubClients.createDeliveryGitHubClients({\n config: context.config,\n identity: context.config.roles.reviewer.identity,\n role: 'reviewer',\n selectedAuthor: context.clients,\n ...(control === undefined ? {} : { signal: control.signal }),\n }));\n await check();\n if (reviewer.role !== 'reviewer' || reviewer.authSource !== 'app' || !reviewer.appActorLogin) {\n throw new DeliveryError('Configured reviewer GitHub App identity is unavailable.');\n }\n const reviewerActor = await reviewer.appActorLogin(control?.signal);\n await check();\n if (!reviewerActor) throw new DeliveryError('Reviewer GitHub App actor lookup is incomplete.');\n if (author.actorLogin.toLowerCase() === reviewerActor.toLowerCase()) {\n throw new DeliveryError(\n 'Author and reviewer resolve to the same GitHub actor; select distinct configured credentials.',\n );\n }\n try {\n const repository = (\n await reviewer.rest.repos.get({\n ...context.repo,\n ...(control === undefined ? {} : { request: { signal: control.signal } }),\n })\n ).data;\n await check();\n if (repository.full_name.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()) {\n throw new DeliveryError('Reviewer GitHub App repository readback disagrees with the selected checkout.');\n }\n } catch (error) {\n if (error instanceof DeliveryError) throw error;\n throw new DeliveryError(\n 'Reviewer GitHub App cannot read the selected repository; verify its installation and repository access.',\n );\n }\n const [rulesetResult, protectionResult] = await branchRuleSources(context, base, control);\n await check();\n const { confirmedUnprotected, confirmedRulesetOnly } = await corroborateClassicProtectionAbsence(\n context,\n base,\n [rulesetResult, protectionResult],\n control,\n );\n const counts: number[] = [];\n let countsKnown = rulesetResult.status === 'fulfilled' && completeRulePage(rulesetResult.value);\n if (rulesetResult.status === 'fulfilled' && Array.isArray(rulesetResult.value.data)) {\n for (const rule of rulesetResult.value.data) {\n if (typeof rule !== 'object' || rule === null || typeof rule.type !== 'string' || !rule.type) countsKnown = false;\n if (rule?.type === 'pull_request') {\n const count = requiredApprovalCount(rule.parameters);\n if (count === null) countsKnown = false;\n else counts.push(count);\n }\n }\n }\n if (protectionResult.status === 'fulfilled') {\n const protection = protectionResult.value.data as { required_pull_request_reviews?: unknown };\n const count =\n typeof protection === 'object' && protection !== null && !Array.isArray(protection)\n ? requiredApprovalCount(protection.required_pull_request_reviews)\n : null;\n if (protectionResult.value.status !== 200 || count === null) countsKnown = false;\n if (count !== null) counts.push(count);\n } else if (!confirmedUnprotected && !confirmedRulesetOnly) countsKnown = false;\n const rulesVisible =\n rulesetResult.status === 'fulfilled' &&\n Array.isArray(rulesetResult.value.data) &&\n (rulesetResult.value.headers?.link === undefined || rulesetResult.value.headers.link === '');\n const visible =\n Number(rulesVisible) +\n Number(protectionResult.status === 'fulfilled' || confirmedUnprotected || confirmedRulesetOnly);\n const visibility = visible === 2 ? 'complete' : visible === 1 ? 'partial' : 'unknown';\n // A positive observation is a conservative lower bound for permission checks.\n // Zero requires complete, valid requirement evidence from every source.\n const observedRequiredApprovals =\n counts.length > 0 && (countsKnown || counts.some((count) => count > 0))\n ? Math.max(...counts)\n : countsKnown && confirmedUnprotected\n ? 0\n : null;\n const insufficientPermission =\n observedRequiredApprovals !== null &&\n observedRequiredApprovals > 0 &&\n reviewer.effectiveContentsPermission === 'read';\n return {\n author,\n reviewer: {\n actorLogin: reviewerActor,\n credentialSource: reviewer.credentialSource ?? 'unreported',\n effectiveContentsPermission: reviewer.effectiveContentsPermission ?? 'unknown',\n identity: context.config.roles.reviewer.identity,\n repositoryAccess: 'readable',\n },\n rules: { observedRequiredApprovals, visibility },\n approvalEligibility: insufficientPermission ? 'insufficient-permission' : 'unknown',\n nextAction: insufficientPermission\n ? 'The reviewer App token has Contents: read, but the visible rule requires approval from a reviewer with repository write access. To use the App for required approval, grant Contents: write, accept the installation permission change, and obtain a fresh token before publication.'\n : visibility === 'complete' && observedRequiredApprovals === null\n ? 'No required approving review was observed in the visible rules. Confirm the live PR review decision after exact-head submission.'\n : visibility === 'complete'\n ? 'Confirm whether the reviewer approval counts after exact-head submission; installation scopes do not prove required-review eligibility.'\n : 'Inspect the active branch review rule with an authorized repository view and confirm whether the reviewer approval counts after exact-head submission.',\n };\n}\n\nexport async function publishPr(\n context: DeliveryContext,\n input: {\n issueNumber: number;\n prNumber?: number;\n nonClosing?: boolean;\n reconcileNonClosingReference?: boolean;\n expectedHeadSha?: string;\n expectedBaseSha?: string;\n body?: string;\n title?: string;\n draft?: boolean;\n headBranch?: string;\n baseBranch?: string;\n dryRun?: boolean;\n },\n) {\n const nonClosing = nonClosingMode(input.nonClosing);\n const reconcileReference = nonClosingMode(input.reconcileNonClosingReference);\n if (reconcileReference) {\n if (\n context.clients.role !== 'author' ||\n context.clients.authSource !== (context.config.roles.author.authSource ?? 'app') ||\n !context.clients.authenticatedAuthor\n )\n throw new DeliveryError('Reference reconciliation requires the configured authenticated author role.');\n if (\n !nonClosing ||\n input.draft === false ||\n !validSha(input.expectedHeadSha) ||\n !validSha(input.expectedBaseSha) ||\n typeof input.body !== 'string' ||\n !input.body.trim()\n )\n throw new DeliveryError(\n 'Reference reconciliation requires nonClosing, DRAFT, explicit safe body and exact expected head/base SHAs.',\n );\n refuseClosingDirective(input.body);\n } else if (input.expectedHeadSha !== undefined || input.expectedBaseSha !== undefined)\n throw new DeliveryError('Expected head/base inputs require explicit reconcileNonClosingReference.');\n if (input.prNumber !== undefined && (!Number.isSafeInteger(input.prNumber) || input.prNumber <= 0))\n throw new DeliveryError('Existing PR selector must be a positive safe integer.');\n const issue = nonClosing\n ? await openReferenceIssue(context, input.issueNumber)\n : (await context.clients.rest.issues.get({ ...context.repo, issue_number: input.issueNumber })).data;\n if ('pull_request' in issue || issue.number !== input.issueNumber || issue.state !== 'open')\n throw new DeliveryError('PR creation requires the requested open GitHub issue.');\n const repository = (await context.clients.rest.repos.get({ ...context.repo })).data;\n if (\n repository.full_name?.toLowerCase() !== context.config.repository.toLowerCase() ||\n context.config.repository.toLowerCase() !== `${context.repo.owner}/${context.repo.repo}`.toLowerCase()\n )\n throw new DeliveryError('Configured and selected GitHub repository identities disagree.');\n if (nonClosing && !nativeId(repository.node_id))\n throw new DeliveryError('Incomplete canonical non-closing repository node identity.');\n const base = input.baseBranch ?? repository.default_branch;\n if (base !== repository.default_branch)\n throw new DeliveryError('PR delivery requires the repository default branch for durable issue association.');\n validBranch(base);\n if (input.headBranch !== undefined) validBranch(input.headBranch);\n const explicit = input.prNumber === undefined ? undefined : await getPr(context, input.prNumber);\n const explicitPromotion = nonClosing && input.draft === false && input.headBranch !== undefined;\n const selectedMatches = explicitPromotion ? await matchingPrs(context, input.headBranch!, base) : undefined;\n const branch = explicit\n ? explicit.head.ref\n : nonClosing\n ? explicitPromotion && selectedMatches!.length > 0\n ? input.headBranch!\n : await issueBranch(context, input.issueNumber, input.headBranch)\n : (input.headBranch ?? (await issueBranch(context, input.issueNumber)));\n if (input.headBranch !== undefined && branch !== input.headBranch)\n throw new DeliveryError('Explicit PR and head selectors disagree.');\n validBranch(branch);\n const ref = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n if (ref.ref !== `refs/heads/${branch}` || ref.object.type !== 'commit' || !validSha(ref.object.sha))\n throw new DeliveryError('Remote issue branch head/ref readback is invalid.');\n const matches = selectedMatches ?? (await matchingPrs(context, branch, base, nonClosing ? 'all' : 'open'));\n if (matches.length > 1 || (explicit && (matches.length !== 1 || matches[0]!.number !== explicit.number)))\n throw new DeliveryError('Remote issue branch has conflicting PR matches.');\n let pr = explicit ?? (matches[0] === undefined ? undefined : await getPr(context, matches[0].number));\n if (\n pr &&\n input.draft === false &&\n input.headBranch === undefined &&\n input.prNumber === undefined &&\n (await linkedIssueBranches(context, input.issueNumber)).filter((entry) => entry.name === branch).length !== 1\n )\n throw new DeliveryError('Select an explicit PR or head after GitHub-linked branch references disappear.');\n if (reconcileReference && pr && !explicit)\n throw new DeliveryError(\n 'Reference reconciliation of an existing match requires explicit --pr and caller-reconciled authority/attempt receipts.',\n );\n if (nonClosing && !pr && !reconcileReference)\n throw new DeliveryError(\n 'New linked-branch non-closing publication requires explicitly authorized --reconcile-non-closing-reference --expected-head SHA --expected-base SHA and --body-file PATH; bare --non-closing grants no removal authority.',\n );\n if (reconcileReference && ref.object.sha !== input.expectedHeadSha)\n throw new DeliveryError('Reference reconciliation expected head differs from the exact remote linked head.');\n const requestedBody =\n input.body ?? pr?.body ?? (nonClosing ? referenceLine(context, input.issueNumber) : closingBody(issue));\n if ((nonClosing || input.body !== undefined) && !requestedBody.trim())\n throw new DeliveryError('PR body must contain text.');\n const body = publicationBody(\n nonClosing ? nonClosingBody(context, input.issueNumber, requestedBody) : closingBody(issue, requestedBody),\n pr?.body,\n );\n const closingRepair = !nonClosing && pr !== undefined && !hasClosingLink(pr.body, input.issueNumber);\n const transition = nonClosing && pr !== undefined && pr.body !== body;\n // A PR that already references the issue changes only its body; a closing PR converts (#238).\n const referenceUpdate = transition && hasReferenceBody(context, input.issueNumber, pr?.body);\n if (reconcileReference && transition)\n throw new DeliveryError('Reference reconciliation refuses body transition; retain exact original intent.');\n if (transition && (input.prNumber === undefined || input.body === undefined))\n throw new DeliveryError('Non-closing body transition requires an explicit existing PR number and body.');\n if (\n pr &&\n (pr.head.sha !== ref.object.sha ||\n pr.head.ref !== branch ||\n pr.base.ref !== base ||\n pr.state !== 'open' ||\n pr.merged ||\n (!transition && input.body !== undefined && pr.body !== input.body && pr.body !== body) ||\n (input.title !== undefined && pr.title !== input.title))\n )\n throw new DeliveryError('Existing remote PR conflicts with the requested branch, intent or state.');\n // Opening a closing PR needs only the author; review submission checks the reviewer App.\n const reviewRoute = nonClosing\n ? await nonClosingRoute(context, base)\n : { author: await routeAuthor(context, 'publication') };\n if (pr && pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())\n throw new DeliveryError('Existing PR author differs from the configured authenticated author.');\n if (pr && (typeof pr.node_id !== 'string' || !pr.node_id))\n throw new DeliveryError('Existing PR publication identity is incomplete.');\n if (nonClosing) refuseClosingDirective(input.title ?? pr?.title ?? issue.title);\n const creationTitle = input.title ?? issue.title;\n let publicationBaseSha: string | undefined;\n const existing = pr;\n let pendingTransition = transition;\n let pendingClosingRepair = closingRepair;\n let expectedBody = pr?.body;\n const transitionDraft = pr?.draft;\n let promotionApplied = false;\n let removalState: 'not attempted' | 'acknowledged' | 'uncertain' = 'not attempted';\n const preserveIssue = async () => {\n if (nonClosing) sameReferenceIssue(issue, await openReferenceIssue(context, input.issueNumber));\n };\n const readReconciliation = async (selected: RemotePr) => {\n try {\n if (\n selected.state !== 'open' ||\n selected.draft !== true ||\n selected.merged ||\n selected.head.sha !== input.expectedHeadSha ||\n selected.base.sha !== input.expectedBaseSha ||\n selected.head.ref !== branch ||\n selected.base.ref !== base ||\n selected.body !== body ||\n selected.title !== (existing?.title ?? creationTitle) ||\n selected.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase()\n )\n throw new DeliveryError('Reference reconciliation DRAFT, exact head/base, message or author drifted.');\n const graph = await readNonClosingReference(context, input.issueNumber, selected);\n sameReferenceIssue(issue, graph.issue);\n const safe = !graph.closesTarget && !graph.allClosing.length && !graph.manualClosing.length;\n if (!safe && !(graph.closesTarget && graph.allClosing.length === 1 && graph.manualClosing.length === 1))\n throw new DeliveryError(\n 'Reference removal requires only the intended manual closing pair and closing cross-reference.',\n );\n const currentHead = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n if (\n currentHead.ref !== ref.ref ||\n currentHead.object.type !== 'commit' ||\n currentHead.object.sha !== input.expectedHeadSha\n )\n throw new DeliveryError('Reference reconciliation source head drifted.');\n sameReferencePr(selected, await getPr(context, selected.number));\n await preserveIssue();\n return !safe;\n } catch (error) {\n throw new DeliveryError(\n `PR #${selected.number}; reference removal ${removalState}. Reconcile read-only; do not retry without caller-established authority and attempt history. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n };\n const readExisting = async () => {\n const current =\n reconcileReference || pendingClosingRepair\n ? await getPr(context, existing!.number)\n : await verifyIssuePr(\n context,\n input.issueNumber,\n existing!.number,\n nonClosing && (!pendingTransition || referenceUpdate),\n );\n if (\n current.state !== 'open' ||\n current.merged ||\n current.node_id !== existing!.node_id ||\n current.head.sha !== ref.object.sha ||\n current.head.ref !== branch ||\n current.base.ref !== base ||\n current.base.sha !== existing!.base.sha ||\n current.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase() ||\n ((transition || closingRepair) && !promotionApplied && current.draft !== transitionDraft) ||\n current.body !== expectedBody ||\n current.title !== existing!.title\n )\n throw new DeliveryError('Existing PR publication head, identity, intent or author readback drifted.');\n if (reconcileReference) await readReconciliation(current);\n if (pendingClosingRepair) {\n await verifyPrIssueAssociation(\n context,\n current.number,\n input.issueNumber,\n current.node_id,\n true,\n issue.node_id,\n repository.node_id,\n { allowMissing: true },\n );\n const currentRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n if (currentRef.ref !== ref.ref || currentRef.object.type !== 'commit' || currentRef.object.sha !== ref.object.sha)\n throw new DeliveryError('Closing-link repair remote head drifted; reconcile read-only.');\n sameReferencePr(current, await getPr(context, current.number));\n }\n if (pendingTransition && !referenceUpdate) {\n await verifyPrIssueAssociation(\n context,\n current.number,\n input.issueNumber,\n current.node_id,\n true,\n issue.node_id,\n repository.node_id,\n );\n refuseClosingDirective(current.title);\n await verifyNonClosingCommits(context, current);\n const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;\n if (\n baseRef.ref !== `refs/heads/${base}` ||\n baseRef.object.type !== 'commit' ||\n baseRef.object.sha !== current.base.sha\n )\n throw new DeliveryError('Non-closing transition default base drifted.');\n sameReferencePr(current, await getPr(context, current.number));\n }\n await preserveIssue();\n return current;\n };\n const readNew = async () => {\n const baseRef = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;\n if (baseRef.ref !== `refs/heads/${base}` || baseRef.object.type !== 'commit' || !validSha(baseRef.object.sha))\n throw new DeliveryError('Incomplete publication default base.');\n if (publicationBaseSha !== undefined && publicationBaseSha !== baseRef.object.sha)\n throw new DeliveryError('Publication default base drifted before creation.');\n publicationBaseSha = baseRef.object.sha;\n if (reconcileReference && publicationBaseSha !== input.expectedBaseSha)\n throw new DeliveryError('Reference reconciliation expected default base differs from the remote base.');\n if (nonClosing) await verifyUnpublishedCommits(context, baseRef.object.sha, ref.object.sha);\n const afterHead = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${branch}` })).data;\n const afterBase = (await context.clients.rest.git.getRef({ ...context.repo, ref: `heads/${base}` })).data;\n if (\n afterHead.ref !== ref.ref ||\n afterHead.object.type !== 'commit' ||\n afterHead.object.sha !== ref.object.sha ||\n afterBase.ref !== baseRef.ref ||\n afterBase.object.type !== 'commit' ||\n afterBase.object.sha !== baseRef.object.sha\n )\n throw new DeliveryError('Non-closing publication head/base drifted.');\n await preserveIssue();\n };\n if (pr) pr = await readExisting();\n else await readNew();\n if (input.dryRun)\n return {\n dryRun: true,\n ...(pr === undefined ? { body } : {}),\n ...(pr === undefined ? {} : { prNumber: pr.number, draft: pr.draft }),\n ...(nonClosing\n ? {\n nonClosing: true,\n nonClosingVerified: pr !== undefined && !pendingTransition,\n body,\n bodyTransition: pendingTransition,\n }\n : {}),\n headSha: ref.object.sha,\n headBranch: branch,\n baseBranch: base,\n reviewRoute,\n ...(closingRepair ? { closingLinkAdded: false, body } : {}),\n ...(reconcileReference ? { referenceRemoval: 'pending', nonClosingVerified: false } : {}),\n };\n let created = false;\n const warnings: string[] = [];\n if (pr) {\n if (pendingClosingRepair) {\n pr = await readExisting();\n try {\n await context.clients.rest.pulls.update({ ...context.repo, pull_number: pr.number, body });\n } catch (error) {\n throw new DeliveryError(\n `PR #${pr.number} closing-link repair acknowledgement is uncertain; reconcile this PR read-only before retrying. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n pendingClosingRepair = false;\n expectedBody = body;\n pr = await readExisting();\n }\n if (pendingTransition) {\n pr = await readExisting();\n await context.clients.rest.pulls.update({ ...context.repo, pull_number: pr.number, body });\n pendingTransition = false;\n expectedBody = body;\n pr = await readExisting();\n }\n if (input.draft === false && pr.draft) {\n pr = await readExisting();\n if (pr.draft) {\n const promoted = await context.clients.graphql<{\n markPullRequestReadyForReview: { pullRequest: { id: string; isDraft: boolean } | null } | null;\n }>(\n 'mutation DeliveryReadyPr($id:ID!){markPullRequestReadyForReview(input:{pullRequestId:$id}){pullRequest{id isDraft}}}',\n { id: pr.node_id },\n );\n if (\n promoted?.markPullRequestReadyForReview?.pullRequest?.id !== pr.node_id ||\n promoted.markPullRequestReadyForReview.pullRequest.isDraft !== false\n )\n throw new DeliveryError('PR promotion mutation readback is incomplete or conflicting; reconcile this PR.');\n promotionApplied = true;\n }\n pr = await readExisting();\n if (pr.draft) throw new DeliveryError('PR promotion readback is still draft.');\n }\n } else {\n await readNew();\n let response;\n try {\n response = await context.clients.rest.pulls.create({\n ...context.repo,\n head: branch,\n base,\n title: creationTitle,\n body,\n draft: input.draft !== false,\n });\n } catch (error) {\n throw new DeliveryError(\n `PR creation acknowledgement is uncertain; reconcile the remote head read-only before any new mutation. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n if (!Number.isSafeInteger(response.data.number) || response.data.number <= 0)\n throw new DeliveryError(\n 'PR creation acknowledgement lacks a valid PR identity; reconcile the remote head read-only, do not create again.',\n );\n created = true;\n try {\n pr = await getPr(context, response.data.number);\n } catch (error) {\n throw new DeliveryError(\n `GitHub returned created PR #${response.data.number}; identity readback is unresolved. Reconcile read-only; do not create again. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n }\n try {\n if (\n created &&\n (pr.body !== body ||\n pr.title !== creationTitle ||\n pr.draft !== (input.draft !== false) ||\n pr.state !== 'open' ||\n pr.merged ||\n pr.base.sha !== publicationBaseSha)\n )\n throw new DeliveryError(\n 'Created PR body, title, draft/open state or default base differs from publication intent.',\n );\n if (pr.head.sha !== ref.object.sha || pr.head.ref !== branch || pr.base.ref !== base)\n throw new DeliveryError('GitHub PR creation readback drifted.');\n if (pr.user.login.toLowerCase() !== reviewRoute.author.actorLogin.toLowerCase())\n throw new DeliveryError('Published PR author differs from the configured authenticated author.');\n if (nonClosing) {\n if (reconcileReference && (await readReconciliation(pr))) {\n // The trusted caller owns the exact grant and prior-attempt history.\n // This invocation never retries this non-transactional native action.\n if (await readReconciliation(pr)) {\n removalState = 'uncertain';\n try {\n const removed = await context.clients.graphql<{\n removeCloseIssueReferences?: { issue?: { id: string } | null } | null;\n }>(\n 'mutation DeliveryRemoveClosingReference($issueId:ID!,$pullRequestIds:[ID!]!,$clientMutationId:String!){removeCloseIssueReferences(input:{issueId:$issueId,pullRequestIds:$pullRequestIds,clientMutationId:$clientMutationId}){issue{id}}}',\n { issueId: issue.node_id, pullRequestIds: [pr.node_id], clientMutationId: randomUUID() },\n );\n if (removed.removeCloseIssueReferences?.issue?.id !== issue.node_id)\n throw new DeliveryError('Incomplete reference-removal acknowledgement.');\n removalState = 'acknowledged';\n } catch (error) {\n throw new DeliveryError(\n `PR #${pr.number}; reference removal acknowledgement is uncertain. Reconcile read-only; no automatic retry or rollback. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n }\n }\n const verified = await verifyIssuePr(context, input.issueNumber, pr.number, true);\n sameReferencePr(pr, verified);\n pr = verified;\n await preserveIssue();\n } else if (\n // GitHub lists a new PR's closing link a few seconds after creation (aviaratech/ai#3780).\n (await verifyPrIssueAssociation(context, pr.number, input.issueNumber, undefined, false, undefined, undefined, {\n allowMissing: created,\n })) === 0\n )\n warnings.push(\n `GitHub has not yet listed PR #${pr.number} as closing #${input.issueNumber}; confirm with issue_pr_info.`,\n );\n if (created) {\n const final = await getPr(context, pr.number);\n sameReferencePr(pr, final);\n pr = final;\n }\n } catch (error) {\n if (!created && !reconcileReference) throw error;\n throw new DeliveryError(\n `GitHub ${created ? 'created' : 'selected'} PR #${pr.number} (${pr.html_url}) at ${pr.head.sha}; post-publication association/identity verification is unresolved.${reconcileReference ? ` Reference removal ${removalState}.` : ''} Reconcile this PR read-only; do not create again. ${error instanceof Error ? error.message : 'Unknown failure'}`,\n );\n }\n return {\n prNumber: pr.number,\n url: pr.html_url,\n headSha: pr.head.sha,\n state: pr.draft ? 'draft' : pr.state,\n ...(closingRepair ? { closingLinkAdded: true } : {}),\n ...(nonClosing ? { nonClosing: true, nonClosingVerified: true } : {}),\n ...(reconcileReference ? { referenceRemoval: removalState } : {}),\n ...(warnings.length ? { warnings } : {}),\n };\n}\n\nexport async function submitFormalReview(\n context: DeliveryContext,\n input: { artifact: string; issueNumber: number; prNumber: number; dryRun?: boolean; nonClosing?: boolean },\n) {\n const nonClosing = nonClosingMode(input.nonClosing);\n const pr = await verifyIssuePr(context, input.issueNumber, input.prNumber, nonClosing, true);\n const issue = nonClosing ? await openReferenceIssue(context, input.issueNumber) : undefined;\n const result = await submitReview({\n context,\n artifact: parseReviewArtifact(input.artifact),\n issueNumber: input.issueNumber,\n prNumber: input.prNumber,\n ...(input.dryRun === undefined ? {} : { dryRun: input.dryRun }),\n });\n try {\n if (nonClosing) {\n sameReferencePr(pr, await verifyIssuePr(context, input.issueNumber, input.prNumber, true, true));\n sameReferenceIssue(issue!, await openReferenceIssue(context, input.issueNumber));\n }\n if ('dryRun' in result) return result;\n return {\n ...result,\n requiredReview: await readRequiredReviewState(context, input.prNumber, result.headSha, {\n id: result.githubReviewId,\n login: result.login,\n state: result.state,\n }),\n };\n } catch (error) {\n if ('dryRun' in result) throw error;\n throw new ReviewSubmissionError(\n error instanceof DeliveryError ? error.message : 'Post-submission status is unavailable.',\n {\n artifactId: result.artifact.artifactId,\n repository: result.repository,\n headSha: result.headSha,\n prNumber: result.prNumber,\n githubReviewId: result.githubReviewId,\n githubReviewUrl: result.githubReviewUrl,\n },\n );\n }\n}\nexport { startIssueBranch };\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAC3B,SAAS,qBAAqB;AAC9B,YAAY,mBAAmB;AAE/B,SAAS,aAAa,qBAAqB,wBAA8C;AACzF;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,sBAAsB;AAE/B,MAAM,MAAM;AACZ,MAAM,SAAS;AAIf,MAAM,mBAAmB;AACzB,SAAS,sBAAsB,MAAc,SAAkC;AAG7E,QAAM,UAAmC,CAAC;AAC1C,QAAM,YAAqC,CAAC;AAC5C,QAAM,SAAkC,CAAC;AACzC,MAAI,YAA2B;AAC/B,MAAI,QAAuB;AAC3B,MAAI,UAAU;AACd,MAAI,UAAmC;AACvC,MAAI,YAAY;AAChB,MAAI,SAAS;AACb,MAAI,QAAQ;AACZ,QAAM,QAAQ,CAAC,QAAgB;AAC7B,QAAI,cAAc,KAAM,QAAO,KAAK,CAAC,WAAW,GAAG,CAAC;AACpD,gBAAY;AAAA,EACd;AACA,aAAW,QAAQ,KAAK,SAAS,kBAAkB,GAAG;AACpD,QAAI,CAAC,KAAK,CAAC,EAAG;AACd,UAAM,QAAQ,KAAK;AACnB,UAAM,MAAM,QAAQ,KAAK,CAAC,EAAE;AAC5B,UAAM,UAAU,KAAK,CAAC,EAAE,QAAQ,WAAW,EAAE;AAC7C,QAAI,SAAS;AACX,YAAM,UAAU,QAAQ,QAAQ,KAAK;AACrC,cAAQ,KAAK,CAAC,OAAO,UAAU,IAAI,MAAM,QAAQ,UAAU,CAAC,CAAC;AAC7D,UAAI,WAAW,EAAG,WAAU;AAC5B;A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