diff --git a/packages/engine/src/chat-job.test.ts b/packages/engine/src/chat-job.test.ts index 4400c4a..27a671b 100644 --- a/packages/engine/src/chat-job.test.ts +++ b/packages/engine/src/chat-job.test.ts @@ -6,7 +6,9 @@ import { MockLanguageModelV4 } from 'ai/test'; import type { EngineContext } from './context'; import { git } from './git'; import { replyMarker, runChatJob, upTo } from './chat-job'; +import { formatSummaryComment, SUMMARY_MARKER } from './format'; import type { ChatJob } from './jobs'; +import { summaryMarkerFor } from './scope'; import { MemoryGitHub, MemoryResultsSink } from './testing'; // The chat job end to end against a local git remote, the in-memory GitHub and a scripted @@ -145,6 +147,117 @@ function seedFinding(github: MemoryGitHub, results: MemoryResultsSink) { return rootId; } +/** + * A completed review that only commented, because its one finding, a minor bug, was open: what + * the summary of appwrite-labs/infrastructure#1157 looked like before the reply that dismissed it. + */ +function seedWithheldApproval( + github: MemoryGitHub, + results: MemoryResultsSink, + options: { approvesWhenSettled: boolean } +) { + results.queue({ + id: 'review0', + status: 'completed', + headSha, + summary: 'Divides.', + verdict: 'comment', + tier: 'A', + tierReason: 'Limited by an open minor finding: Division by zero', + completedAt: '2026-10-01T00:00:00.000Z' + }); + const rootId = '500'; + github.reviewComments.push( + { + id: rootId, + author: 'hansi[bot]', + isBot: true, + body: '**Division by zero**', + path: 'src/math.ts', + line: 2 + }, + { + id: '501', + inReplyToId: rootId, + author: 'octocat', + isBot: false, + body: 'Intended: callers check b first.' + } + ); + const finding = { + path: 'src/math.ts', + startLine: 2, + endLine: 2, + severity: 'minor' as const, + category: 'bug' as const, + title: 'Division by zero', + body: '`b` can be 0.' + }; + results.findings.push({ + ...finding, + id: 'finding1', + reviewId: 'review0', + suggestion: null, + status: 'posted', + dropReason: null, + providerCommentId: rootId, + createdAt: '2026-10-01T00:00:00.000Z' + }); + const summary = formatSummaryComment({ + repository: 'https://github.com/acme/math/blob', + headSha, + summary: 'Divides.', + tier: 'A', + tierReason: 'Limited by an open minor finding: Division by zero', + verdict: 'comment', + posted: [finding], + resolved: [], + stillOpen: [], + dropped: [], + walkthrough: [], + approvalWithheld: 'Not approving while a bug finding is open: Division by zero', + approvesWhenSettled: options.approvesWhenSettled, + mention: '@hansi' + }); + github.issueComments.push({ + id: '400', + author: 'hansi[bot]', + isBot: true, + body: summary.replace(SUMMARY_MARKER, summaryMarkerFor(repository.repositoryId)) + }); + return rootId; +} + +/** The author's reply on that finding, which the model accepts as intended. */ +async function dismissByReply(context: EngineContext) { + await runChatJob( + { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '501', + kind: 'review', + rootCommentId: '500', + author: 'octocat', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#discussion_r501' + }, + unmentioned: true + }, + context, + first + ); +} + +const dismissing = () => + new MockLanguageModelV4({ + doGenerate: [ + toolCalls(['mark_finding', { status: 'dismissed', reason: 'Intended policy' }]), + text('Intended, dismissed.') + ] + }); + describe('runChatJob', () => { test('a reply on a finding can remember a rule and dismiss the finding', async () => { const model = new MockLanguageModelV4({ @@ -201,6 +314,156 @@ describe('runChatJob', () => { expect(results.chatUsage[0]?.usage.map((u) => u.role)).toEqual(['chat']); }); + test('dismissing the finding that held approval back approves the reviewed head', async () => { + const { github, results, context } = setup([dismissing()]); + seedWithheldApproval(github, results, { approvesWhenSettled: true }); + + await dismissByReply(context); + + expect(results.findings[0]?.status).toBe('dismissed'); + const summary = github.summary() ?? ''; + expect(summary).toContain('✅ Approved'); + expect(summary).not.toContain('Not approving'); + expect(summary).not.toContain('Division by zero'); + expect(results.review('review0')?.tier).toBe('S'); + expect(github.reviews.map((r) => [r.event, r.commitId])).toEqual([['APPROVE', headSha]]); + expect(github.reviews[0]?.body).toContain('Looks good to merge.'); + expect(github.checkRuns.map((r) => [r.name, r.headSha, r.conclusion, r.title])).toEqual([ + ['Hansi', headSha, 'success', 'Tier S: Ready to merge'] + ]); + }); + + test('a later settlement keeps the approval without approving again', async () => { + const { github, results, context } = setup([dismissing(), dismissing()]); + seedWithheldApproval(github, results, { approvesWhenSettled: true }); + // A documentation note does not hold approval back, but its thread can still settle. + github.reviewComments.push( + { + id: '510', + author: 'hansi[bot]', + isBot: true, + body: '**Document divide**', + path: 'src/math.ts', + line: 1 + }, + { id: '511', inReplyToId: '510', author: 'octocat', isBot: false, body: 'Not needed.' } + ); + results.findings.push({ + ...results.findings[0]!, + id: 'finding2', + severity: 'minor', + category: 'documentation', + title: 'Document divide', + providerCommentId: '510' + }); + + await dismissByReply(context); + context.models.review.model = dismissing(); + await runChatJob( + { + type: 'chat', + repository, + pullNumber: 7, + comment: { + id: '511', + kind: 'review', + rootCommentId: '510', + author: 'octocat', + authorAssociation: 'MEMBER', + url: 'https://github.test/pull/7#discussion_r511' + }, + unmentioned: true + }, + context, + first + ); + + expect(results.findings.map((f) => f.status)).toEqual(['dismissed', 'dismissed']); + expect(github.summary()).toContain('✅ Approved'); + expect(github.reviews.map((r) => r.event)).toEqual(['APPROVE']); + // The check run follows the grade: the open note held it at A, then nothing is open. + expect(github.checkRuns.map((r) => [r.conclusion, r.title])).toEqual([ + ['success', 'Tier A: Mergeable after minor fixes'], + ['success', 'Tier S: Ready to merge'] + ]); + }); + + test('an approval GitHub refused is not claimed in the summary', async () => { + const { github, results, context } = setup([dismissing()]); + seedWithheldApproval(github, results, { approvesWhenSettled: true }); + github.createReview = async () => { + throw new Error('GitHub is down'); + }; + + await dismissByReply(context); + + expect(results.findings[0]?.status).toBe('dismissed'); + expect(github.summary()).toContain('💬 Commented'); + expect(github.checkRuns.map((r) => r.conclusion)).toEqual(['neutral']); + }); + + test('a findings list cut at its limit leaves the standing as it is', async () => { + const { github, results, context } = setup([dismissing()]); + seedWithheldApproval(github, results, { approvesWhenSettled: true }); + const settled = { + ...results.findings[0]!, + status: 'resolved' as const, + providerCommentId: null + }; + for (let i = 0; i < 199; i++) results.findings.push({ ...settled, id: `old${i}` }); + const before = github.summary(); + + await dismissByReply(context); + + expect(results.findings[0]?.status).toBe('dismissed'); + expect(github.summary()).toBe(before); + expect(results.review('review0')?.tier).toBe('A'); + expect(github.reviews).toEqual([]); + expect(github.checkRuns).toEqual([]); + }); + + test('an approved summary without the settlement mark is not taken as an approval', async () => { + const { github, results, context } = setup([dismissing()]); + seedWithheldApproval(github, results, { approvesWhenSettled: false }); + // A review's final summary is written before its GitHub review is posted. + const summary = github.issueComments[0]!; + summary.body = summary.body.replace('💬 Commented', '✅ Approved'); + + await dismissByReply(context); + + expect(github.summary()).toContain('💬 Commented'); + expect(github.reviews).toEqual([]); + }); + + test('a review that could not have approved anyway only refreshes its summary', async () => { + const { github, results, context } = setup([dismissing()]); + seedWithheldApproval(github, results, { approvesWhenSettled: false }); + + await dismissByReply(context); + + const summary = github.summary() ?? ''; + expect(summary).toContain('💬 Commented'); + expect(summary).not.toContain('Division by zero'); + expect(github.reviews).toEqual([]); + // The grade still moves, so the check run stops showing the dismissed finding's tier. + expect(github.checkRuns.map((r) => [r.conclusion, r.title])).toEqual([ + ['neutral', 'Tier S: Ready to merge'] + ]); + }); + + test('a push since the review keeps the approval for the review of the new commits', async () => { + const { github, results, context } = setup([dismissing()]); + seedWithheldApproval(github, results, { approvesWhenSettled: true }); + // The chat job reads the head first; the settlement then sees a newer one. + github.nextHeads.push(headSha, 'f'.repeat(40)); + + await dismissByReply(context); + + expect(github.summary()).toContain('💬 Commented'); + expect(github.reviews).toEqual([]); + expect(github.checkRuns).toEqual([]); + }); + test("a thread on another project's finding is left to that project", async () => { const { github, results, context } = setup(); const rootId = seedFinding(github, results); diff --git a/packages/engine/src/chat-job.ts b/packages/engine/src/chat-job.ts index 517d777..36eb967 100644 --- a/packages/engine/src/chat-job.ts +++ b/packages/engine/src/chat-job.ts @@ -1,4 +1,4 @@ -import { changeRequestSeverity, parseRepoConfig, REPO_CONFIG_FILE } from './config'; +import { parseRepoConfig, REPO_CONFIG_FILE } from './config'; import { runChat, type ThreadMessage } from './chat'; import { chatFinding, @@ -229,7 +229,7 @@ export async function runChatJob( .resolveReviewThreads(job.pullNumber, [comment.rootCommentId]) .catch((error: unknown) => log.warn('could not resolve thread', { err: error })); } - // Keep the PR summary's open-finding list and tier in sync with the dismissal. + // Keep the summary, grade, check run and approval in sync with the settled finding. await refreshSummaryAfterSettlement({ results, connection, @@ -237,7 +237,7 @@ export async function runChatJob( repository, consoleUrl: job.repository.consoleUrl, images: statusImagesOrigin(job.repository), - blockingSeverity: changeRequestSeverity(config), + config, log }).catch((error: unknown) => log.warn('could not refresh summary after settlement', { err: error }) diff --git a/packages/engine/src/core.test.ts b/packages/engine/src/core.test.ts index 1a5647d..f754c60 100644 --- a/packages/engine/src/core.test.ts +++ b/packages/engine/src/core.test.ts @@ -1307,6 +1307,8 @@ ${upstream}`; expect(posted.approvalWithheld).toBe( 'Not approving while a bug finding is open: Include nested rows in the purge' ); + // Only the finding holds approval back: settling it in its thread may approve. + expect(posted.approvesWhenSettled).toBe(true); const earlier = await runReview({ repoDir, @@ -1446,11 +1448,13 @@ ${upstream}`; if (trusted.status !== 'completed') throw new Error('expected a completed review'); expect(trusted.verdict).toBe('approve'); expect(trusted.approvalWithheld).toBeNull(); + expect(trusted.approvesWhenSettled).toBe(true); const outsider = await review({ withholdApproval: 'Outside contributor.' }); if (outsider.status !== 'completed') throw new Error('expected a completed review'); expect(outsider.verdict).toBe('comment'); expect(outsider.approvalWithheld).toBe('Outside contributor.'); + expect(outsider.approvesWhenSettled).toBe(false); // A second file that does not fit in the prompt: the review is incomplete. const bigger = `${diff}diff --git a/src/big.ts b/src/big.ts @@ -1464,6 +1468,7 @@ ${upstream}`; if (truncated.status !== 'completed') throw new Error('expected a completed review'); expect(truncated.verdict).toBe('comment'); expect(truncated.approvalWithheld).toContain('too large'); + expect(truncated.approvesWhenSettled).toBe(false); expect(truncated.filesTooLargeForPrompt).toEqual({ omitted: 1, total: 2 }); expect(trusted.filesTooLargeForPrompt).toBeNull(); diff --git a/packages/engine/src/format.ts b/packages/engine/src/format.ts index a63d658..5d1f814 100644 --- a/packages/engine/src/format.ts +++ b/packages/engine/src/format.ts @@ -19,6 +19,21 @@ export const SUMMARY_MARKER = ``; */ export const STALE_HEAD_NOTE_MARK = ``; +/** + * Hidden marker on a summary whose review held approval back only for its open findings: the + * whole diff was seen and the author may be approved. Settling those findings in their threads + * then approves without another review. Without it (a partial diff, an outside contributor, or a + * summary written before the marker existed), settling never approves. + */ +export const APPROVES_WHEN_SETTLED_MARK = ``; + +/** + * Hidden marker written once GitHub took the approval a settlement posted. The stored review + * keeps its own verdict, so later settlements read this to keep the approval, and to not post it + * again. + */ +export const APPROVED_ON_SETTLEMENT_MARK = ``; + const severityIcon: Record = { critical: '🔴', major: '🟠', @@ -471,6 +486,10 @@ export interface SummaryInput { * change this pull request's code. */ scope?: string; + /** Only open findings keep Hansi from approving. See `APPROVES_WHEN_SETTLED_MARK`. */ + approvesWhenSettled?: boolean; + /** A settlement approved this head. See `APPROVED_ON_SETTLEMENT_MARK`. */ + approvedOnSettlement?: boolean; detailsUrl?: string; /** The bot's handle, e.g. `@hansi-codes`. */ mention: string; @@ -696,6 +715,8 @@ export function formatSummaryComment(input: SummaryInput): string { ? `Reviewed the commits since ${input.incrementalFrom.slice(0, 7)}` : `Reviewed ${input.headSha.slice(0, 7)}`; parts.push(`
\n\n${reviewed}`, interactionTip(input.mention)); + if (input.approvesWhenSettled) parts.push(APPROVES_WHEN_SETTLED_MARK); + if (input.approvedOnSettlement) parts.push(APPROVED_ON_SETTLEMENT_MARK); return parts.join('\n\n'); } diff --git a/packages/engine/src/review-job.ts b/packages/engine/src/review-job.ts index 2598bea..03645c0 100644 --- a/packages/engine/src/review-job.ts +++ b/packages/engine/src/review-job.ts @@ -61,6 +61,8 @@ import { sameHeadSkipSummary } from './same-head'; import { + CHECK_NAME, + checkConclusions, lastCompleted, modelUsage, reviewDetailsUrl, @@ -81,8 +83,7 @@ import type { ReviewEvent as TraceStep } from './tools'; // Appwrite. It follows hansi.codes' worker step for step; Appwrite's Reviews API stands in for // hansi.codes' database. -/** The check run the review reports on the commit. */ -export const CHECK_NAME = 'Hansi'; +export { CHECK_NAME } from './shared'; type Outcome = { status: 'skipped'; summary: string; headSha?: string } | { status: 'completed' }; @@ -92,13 +93,6 @@ const reviewEvents = { comment: 'COMMENT' } as const satisfies Record; -/** The check run follows the verdict, so teams can require it for merging. */ -const checkConclusions = { - approve: 'success', - request_changes: 'failure', - comment: 'neutral' -} as const; - /** The trigger as hansi.codes names it, for the decisions that depend on it. */ function triggerOf(job: ReviewJob): string { return job.trigger.kind; @@ -548,6 +542,7 @@ async function executeReview( approvalWithheld: result.approvalWithheld, filesTooLargeForPrompt: result.filesTooLargeForPrompt, staleHead: decision.note, + approvesWhenSettled: result.approvesWhenSettled, incrementalFrom, detailsUrl, mention, diff --git a/packages/engine/src/review.ts b/packages/engine/src/review.ts index 5652281..1b902df 100644 --- a/packages/engine/src/review.ts +++ b/packages/engine/src/review.ts @@ -184,6 +184,11 @@ export type ReviewResult = latestChanges: string | null; /** Why Hansi did not approve although it found nothing blocking. */ approvalWithheld: string | null; + /** + * Only open findings keep Hansi from approving: once they settle, it may approve this + * head without another review. False when it could not have approved with none open. + */ + approvesWhenSettled: boolean; /** * Reviewable changed files that did not fit in the prompt, out of how many were * considered. Null when every reviewable file was included. @@ -626,14 +631,17 @@ export async function runReview(input: ReviewInput): Promise { stillOpen: [], config }) !== 'approve'; + // What holds approval back whatever happens to the open findings. + const withheldRegardless = + input.withholdApproval ?? + (truncated + ? 'Part of the diff was too large to review, so Hansi did not approve.' + : unplacedDefects + ? 'Hansi found problems with this deletion that it could not comment on inline, so it did not approve.' + : null); const approvalWithheld = verdict === 'approve' - ? (input.withholdApproval ?? - (truncated - ? 'Part of the diff was too large to review, so Hansi did not approve.' - : unplacedDefects - ? 'Hansi found problems with this deletion that it could not comment on inline, so it did not approve.' - : null)) + ? withheldRegardless : openDefectApprovalReason([...posted, ...stillOpen], config); if (verdict === 'approve' && approvalWithheld) verdict = 'comment'; const presented = presentReview({ @@ -675,6 +683,7 @@ export async function runReview(input: ReviewInput): Promise { ), latestChanges: input.incrementalFrom ? (submitted.latest_changes ?? null) : null, approvalWithheld, + approvesWhenSettled: config.reviews.approve && withheldRegardless === null, filesTooLargeForPrompt: shown.length < included.length ? { omitted: included.length - shown.length, total: included.length } diff --git a/packages/engine/src/shared.ts b/packages/engine/src/shared.ts index 4654778..ea44237 100644 --- a/packages/engine/src/shared.ts +++ b/packages/engine/src/shared.ts @@ -10,6 +10,16 @@ import type { ModelUsage, ReviewRecord } from './results'; // What the review and chat jobs share: the work directory, links into the Console, the bot's // change requests, and model usage. +/** The check run the review reports on the commit. */ +export const CHECK_NAME = 'Hansi'; + +/** The check run follows the verdict, so teams can require it for merging. */ +export const checkConclusions = { + approve: 'success', + request_changes: 'failure', + comment: 'neutral' +} as const; + /** The latest completed review of a pull request, by when it finished. */ export function lastCompleted(reviews: readonly ReviewRecord[]): ReviewRecord | undefined { return reviews diff --git a/packages/engine/src/summary.test.ts b/packages/engine/src/summary.test.ts index 79254d3..10187b1 100644 --- a/packages/engine/src/summary.test.ts +++ b/packages/engine/src/summary.test.ts @@ -154,6 +154,31 @@ describe('summaryExtrasFromBody', () => { expect(rebuilt).toContain('@stranger does not have write access.'); }); + test('keeps the approves-when-settled mark through a rebuild', () => { + const body = formatSummaryComment( + summaryAfterSettlement({ + ...base, + verdict: 'comment', + findings: [], + approvesWhenSettled: true + }) + ); + expect(summaryExtrasFromBody(body).approvesWhenSettled).toBe(true); + const rebuilt = formatSummaryComment( + summaryAfterSettlement({ + ...base, + verdict: 'comment', + findings: [], + ...summaryExtrasFromBody(body) + }) + ); + expect(summaryExtrasFromBody(rebuilt).approvesWhenSettled).toBe(true); + const without = formatSummaryComment( + summaryAfterSettlement({ ...base, verdict: 'comment', findings: [] }) + ); + expect(summaryExtrasFromBody(without).approvesWhenSettled).toBeUndefined(); + }); + test('returns nulls when those sections are absent', () => { expect( summaryExtrasFromBody(formatSummaryComment(summaryAfterSettlement({ ...base, findings: [] }))) diff --git a/packages/engine/src/summary.ts b/packages/engine/src/summary.ts index 2ecd7f6..5b87406 100644 --- a/packages/engine/src/summary.ts +++ b/packages/engine/src/summary.ts @@ -1,8 +1,18 @@ -import { severityAtLeast, type Severity, type Verdict } from './config'; +import { + changeRequestSeverity, + severityAtLeast, + type RepoConfig, + type Severity, + type Verdict +} from './config'; import type { Log } from './context'; import type { Finding } from './findings'; import { + absolutizeLinks, + APPROVED_ON_SETTLEMENT_MARK, + APPROVES_WHEN_SETTLED_MARK, filesTooLargeFromBody, + formatReviewBody, formatSummaryComment, latestChangesFromBody, STALE_HEAD_NOTE_MARK, @@ -12,9 +22,21 @@ import { import type { GitHubConnection } from './github'; import { statusBlockOf, withStatusBlock } from './progress'; import type { FindingRecord, PullRef, ResultsSink } from './results'; -import { lastCompleted, reviewDetailsUrl, withdrawChangeRequests } from './shared'; +import { + CHECK_NAME, + checkConclusions, + lastCompleted, + reviewDetailsUrl, + withdrawChangeRequests +} from './shared'; import { CHANGE_REQUEST_DISMISSAL } from './submit-review'; -import { standingFromOpenFindings } from './tier'; +import { standingFromOpenFindings, tierMeaning } from './tier'; +import { + decideVerdict, + OPEN_DEFECT_NOTE, + openDefectApprovalReason, + type VerdictFinding +} from './verdict'; type FindingRow = { reviewId: string; @@ -40,6 +62,10 @@ export type SummaryExtras = { filesTooLargeForPrompt?: { omitted: number; total: number } | null; /** Footer sentence written when a merge did not change the pull request. */ scope?: string; + /** Only open findings kept the review from approving. */ + approvesWhenSettled?: boolean; + /** A settlement already approved this head. */ + approvedOnSettlement?: boolean; }; /** @@ -62,7 +88,9 @@ export function summaryExtrasFromBody(body: string): SummaryExtras { filesTooLargeForPrompt: filesTooLargeFromBody(body), staleHead: staleLine ? staleLine.slice(stalePrefix.length) : null, ...(incrementalFrom ? { incrementalFrom } : {}), - ...(scope ? { scope } : {}) + ...(scope ? { scope } : {}), + ...(body.includes(APPROVES_WHEN_SETTLED_MARK) ? { approvesWhenSettled: true } : {}), + ...(body.includes(APPROVED_ON_SETTLEMENT_MARK) ? { approvedOnSettlement: true } : {}) }; } @@ -71,7 +99,12 @@ export function summaryFindings(findings: readonly FindingRecord[]): FindingRow[ return findings.filter((f) => f.status !== 'dismissed').slice(0, 200); } -/** Rebuilds the summary comment after a finding is resolved or dismissed in a thread. */ +/** + * Rebuilds the summary comment after a finding is resolved or dismissed in a thread, and brings + * Hansi's standing on the pull request in line with the findings still open: the grade, the + * change request, the check run and, where the review held it back only for its findings, the + * approval. + */ export async function refreshSummaryAfterSettlement(input: { results: ResultsSink; connection: GitHubConnection; @@ -81,50 +114,114 @@ export async function refreshSummaryAfterSettlement(input: { consoleUrl?: string; /** The Console's origin, where the status images are served. Absent: the status is text. */ images?: string; - /** - * Findings at or above this severity keep a change request standing - * (`reviews.requestChanges`); null when the repository never requests changes. - */ - blockingSeverity: Severity | null; + /** The base branch's settings: what blocks the pull request, and whether Hansi approves. */ + config: RepoConfig; log: Log; }): Promise { - const { results, connection, pull } = input; + const { results, connection, pull, config } = input; const { github, app } = connection; const mention = `@${app.slug}`; + const blockingSeverity = changeRequestSeverity(config); const last = lastCompleted(await results.listReviews(pull)); if (!last?.summary || !last.verdict) return; - const rows = summaryFindings(await results.listFindings(pull, { limit: 200 })); - const blockingOpen = hasBlockingOpen(rows, input.blockingSeverity); - // A change request stands while a blocking finding is open; after that the latest verdict - // becomes a comment. A conversation is not a review of the code, so it never approves. - const verdict = - last.verdict === 'request_changes' && !blockingOpen ? 'comment' : (last.verdict as Verdict); + const listed = await results.listFindings(pull, { limit: FINDINGS_LIMIT }); + // The list stops at the limit, so a full one may leave open findings out. The grade, the + // change request and the approval would all rest on it: leave everything as it is. + if (listed.length >= FINDINGS_LIMIT) { + input.log.warn('too many findings to refresh the standing after settlement', { + limit: FINDINGS_LIMIT + }); + return; + } + const rows = summaryFindings(listed); + const open: VerdictFinding[] = rows + .filter((f) => f.status === 'posted') + .map((f) => ({ severity: f.severity as Severity, category: f.category, title: f.title })); + const blockingOpen = hasBlockingOpen(rows, blockingSeverity); const existing = await github.getMarkedComment(pull.pullNumber, SUMMARY_MARKER); const extras = existing ? summaryExtrasFromBody(existing.body) : {}; + const status = existing && statusBlockOf(existing.body); + // An earlier settlement may have approved already; the stored review keeps its own verdict. + const reviewed: Verdict = extras.approvedOnSettlement ? 'approve' : (last.verdict as Verdict); + // A note that names an open defect follows the findings; any other note stays as written. + const withheld = extras.approvalWithheld?.startsWith(OPEN_DEFECT_NOTE) + ? openDefectApprovalReason(open, config) + : extras.approvalWithheld; - const summaryInput = summaryAfterSettlement({ - repository: input.repository, - headSha: last.headSha, - summary: last.summary, - verdict, - walkthrough: last.walkthrough ?? [], - latestReviewId: last.id, - findings: rows, - detailsUrl: reviewDetailsUrl(input.consoleUrl, pull.projectId, last.id), - mention, - images: input.images, - ...extras - }); + // A change request stands while a blocking finding is open; after that it becomes a comment. + const settled: Verdict = reviewed === 'request_changes' && !blockingOpen ? 'comment' : reviewed; + // The review held approval back only for findings that are now settled: approve, as a review + // of the same head would. Never while a review is running, which decides for itself, and never + // over newer commits, which nobody reviewed. + const reviewedHead = async () => + sameSha((await github.getPullRequest(pull.pullNumber)).headSha, last.headSha); + const current = status ? false : await reviewedHead(); + const approves = + current && + settled !== 'approve' && + !!extras.approvesWhenSettled && + !extras.staleHead && + decideVerdict({ posted: open, stillOpen: [], config }) === 'approve'; + const detailsUrl = reviewDetailsUrl(input.consoleUrl, pull.projectId, last.id); + const build = (verdict: Verdict) => + summaryAfterSettlement({ + repository: input.repository, + headSha: last.headSha, + summary: last.summary, + verdict, + walkthrough: last.walkthrough ?? [], + latestReviewId: last.id, + findings: rows, + detailsUrl, + mention, + images: input.images, + ...extras, + approvalWithheld: verdict === 'approve' ? null : withheld, + // Approve here comes from the stored review, an earlier settlement, or GitHub taking + // this one's approval. + approvedOnSettlement: verdict === 'approve' && last.verdict !== 'approve' + }); // A review running right now keeps its status line above the rebuilt summary. - await github.upsertMarkedComment( - pull.pullNumber, - SUMMARY_MARKER, - withStatusBlock(formatSummaryComment(summaryInput), existing && statusBlockOf(existing.body)) - ); + const write = (summaryInput: SummaryInput) => + github.upsertMarkedComment( + pull.pullNumber, + SUMMARY_MARKER, + withStatusBlock(formatSummaryComment(summaryInput), status) + ); + + // Approve first, so the summary never claims an approval GitHub does not have. Confirm the + // head right before: a push since the first read takes the approval back. + let verdict: Verdict = settled; + const tier = build('approve').tier; + if (approves && (await reviewedHead())) { + verdict = await github + .createReview({ + pullNumber: pull.pullNumber, + commitId: last.headSha, + body: formatReviewBody({ + tier, + verdict: 'approve', + blocking: 0, + comments: 0, + summaryUrl: existing?.url + }), + comments: [], + event: 'APPROVE' + }) + .then( + (): Verdict => 'approve', + (error: unknown) => { + input.log.warn('could not approve after settlement', { err: error }); + return settled; + } + ); + } + const summaryInput = build(verdict); + await write(summaryInput); await results.updateGrade( { projectId: pull.projectId, reviewId: last.id }, { tier: summaryInput.tier, tierReason: summaryInput.tierReason } @@ -134,6 +231,31 @@ export async function refreshSummaryAfterSettlement(input: { if (!blockingOpen) { await withdrawChangeRequests(connection, pull.pullNumber, CHANGE_REQUEST_DISMISSAL, input.log); } + // The check run follows the new standing, so a required check stops holding the merge back. + if (current && (verdict !== reviewed || summaryInput.tier !== last.tier)) { + const checkRunId = await github.startCheckRun({ + headSha: last.headSha, + name: CHECK_NAME, + detailsUrl, + ownAppId: app.id + }); + await github.completeCheckRun(checkRunId, { + conclusion: checkConclusions[verdict], + title: `Tier ${summaryInput.tier}: ${tierMeaning[summaryInput.tier]}`, + summary: absolutizeLinks( + [summaryInput.tierReason, last.summary].filter(Boolean).join('\n\n'), + input.repository, + last.headSha + ) + }); + } +} + +/** How many findings a settlement reads. */ +const FINDINGS_LIMIT = 200; + +function sameSha(a: string, b: string): boolean { + return a.toLowerCase() === b.toLowerCase(); } /** Whether a finding at or above the blocking severity is still open on the pull request. */ @@ -218,6 +340,8 @@ export function summaryAfterSettlement( staleHead: input.staleHead, incrementalFrom: input.incrementalFrom, scope: input.scope, + approvesWhenSettled: input.approvesWhenSettled, + approvedOnSettlement: input.approvedOnSettlement, detailsUrl: input.detailsUrl, mention: input.mention, images: input.images diff --git a/packages/engine/src/verdict.ts b/packages/engine/src/verdict.ts index d98ae01..b716c7d 100644 --- a/packages/engine/src/verdict.ts +++ b/packages/engine/src/verdict.ts @@ -83,7 +83,8 @@ export function openDefectApprovalReason( const defect = findings.filter(isDefectFinding).sort(compareSeverity)[0]; if (!defect) return null; const title = defect.title?.trim(); - return title - ? `Not approving while a bug finding is open: ${title}` - : 'Not approving while a bug finding is open.'; + return title ? `${OPEN_DEFECT_NOTE}: ${title}` : `${OPEN_DEFECT_NOTE}.`; } + +/** How `openDefectApprovalReason` starts: the note names a finding, and follows the findings. */ +export const OPEN_DEFECT_NOTE = 'Not approving while a bug finding is open';