From 2c4766bb927dca10973de1fb46d1a18b262ce348 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:47:14 +0000 Subject: [PATCH 1/3] fix(engine): approve once the findings that held approval back are settled A reply that dismissed or resolved a finding rebuilt the summary, but kept the review's verdict and its "Not approving while a bug finding is open" note, and left the check run on the old tier. A pull request whose only open finding was talked away stayed at "Commented" until the next push. The review now marks its summary when only open findings kept it from approving: the whole diff was seen, the author may be approved and reviews.approve is on. Settling the last such finding in its thread then approves the reviewed head, drops the note, and posts a check run with the new tier and conclusion. It never approves while a review is running, over a newer head, or from a summary without the mark (a partial diff, an outside contributor, or one written before this change). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F3M7tu37atmEwQALkjzmjx Co-authored-by: Torsten Dittmann <1759475+TorstenDittmann@users.noreply.github.com> --- packages/engine/src/chat-job.test.ts | 161 ++++++++++++++++++++++++++ packages/engine/src/chat-job.ts | 6 +- packages/engine/src/core.test.ts | 5 + packages/engine/src/format.ts | 11 ++ packages/engine/src/review-job.ts | 13 +-- packages/engine/src/review.ts | 21 +++- packages/engine/src/shared.ts | 10 ++ packages/engine/src/summary.test.ts | 25 ++++ packages/engine/src/summary.ts | 167 +++++++++++++++++++++------ packages/engine/src/verdict.ts | 7 +- 10 files changed, 371 insertions(+), 55 deletions(-) diff --git a/packages/engine/src/chat-job.test.ts b/packages/engine/src/chat-job.test.ts index 4400c4a..c9a560b 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,54 @@ 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 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..73dfda3 100644 --- a/packages/engine/src/format.ts +++ b/packages/engine/src/format.ts @@ -19,6 +19,14 @@ 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 = ``; + const severityIcon: Record = { critical: '🔴', major: '🟠', @@ -471,6 +479,8 @@ 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; detailsUrl?: string; /** The bot's handle, e.g. `@hansi-codes`. */ mention: string; @@ -696,6 +706,7 @@ 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); 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..68dba79 100644 --- a/packages/engine/src/summary.ts +++ b/packages/engine/src/summary.ts @@ -1,8 +1,17 @@ -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, + APPROVES_WHEN_SETTLED_MARK, filesTooLargeFromBody, + formatReviewBody, formatSummaryComment, latestChangesFromBody, STALE_HEAD_NOTE_MARK, @@ -12,9 +21,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 +61,8 @@ 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; }; /** @@ -62,7 +85,8 @@ 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 } : {}) }; } @@ -71,7 +95,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,59 +110,128 @@ 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 reviewed = last.verdict as Verdict; 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 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); + // 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 + }); // 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) + ); + + let verdict: Verdict = approves ? 'approve' : settled; + let summaryInput = build(verdict); + const summary = await write(summaryInput); + // Confirm the head again right before approving: a push during the summary write takes the + // approval back, and the summary with it. + if (approves && !(await reviewedHead())) { + verdict = settled; + summaryInput = build(verdict); + await write(summaryInput); + } await results.updateGrade( { projectId: pull.projectId, reviewId: last.id }, { tier: summaryInput.tier, tierReason: summaryInput.tierReason } ); + if (verdict === 'approve' && approves) { + await github.createReview({ + pullNumber: pull.pullNumber, + commitId: last.headSha, + body: formatReviewBody({ + tier: summaryInput.tier, + verdict, + blocking: 0, + comments: 0, + summaryUrl: summary.url + }), + comments: [], + event: 'APPROVE' + }); + } // No blocking finding is left: withdraw any change request, including one an earlier review // left in place. Dismissing finds nothing to do when there is none. 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 + ) + }); + } +} + +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 +316,7 @@ export function summaryAfterSettlement( staleHead: input.staleHead, incrementalFrom: input.incrementalFrom, scope: input.scope, + approvesWhenSettled: input.approvesWhenSettled, 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'; From c5d1d7922660a88578b65c7af9d82131377384a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:52:09 +0000 Subject: [PATCH 2/3] fix(engine): approve once per settlement, after GitHub took it, on a whole list - A settlement that already approved shows it in the summary, which a later settlement now reads, so it neither approves again nor reverts the summary to the stored "Commented" verdict. - The approval is submitted before the summary is written, and a refused one leaves the summary on the settled verdict. - A findings list cut at its limit may leave open findings out, so it never approves. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F3M7tu37atmEwQALkjzmjx Co-authored-by: Torsten Dittmann <1759475+TorstenDittmann@users.noreply.github.com> --- packages/engine/src/chat-job.test.ts | 85 ++++++++++++++++++++++++++++ packages/engine/src/format.test.ts | 8 +++ packages/engine/src/format.ts | 13 +++++ packages/engine/src/summary.ts | 68 +++++++++++++--------- 4 files changed, 148 insertions(+), 26 deletions(-) diff --git a/packages/engine/src/chat-job.test.ts b/packages/engine/src/chat-job.test.ts index c9a560b..0146afd 100644 --- a/packages/engine/src/chat-job.test.ts +++ b/packages/engine/src/chat-job.test.ts @@ -333,6 +333,91 @@ describe('runChatJob', () => { ]); }); + 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 never approves', 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}` }); + + 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 }); diff --git a/packages/engine/src/format.test.ts b/packages/engine/src/format.test.ts index 197236f..c37046a 100644 --- a/packages/engine/src/format.test.ts +++ b/packages/engine/src/format.test.ts @@ -12,6 +12,7 @@ import { latestChangesFromBody, statusCell, SUMMARY_MARKER, + summaryVerdictFromBody, type SummaryInput } from './format'; @@ -215,6 +216,13 @@ describe('formatSummaryComment', () => { }); }); +test('summaryVerdictFromBody reads the head row, with or without a details link', () => { + expect(summaryVerdictFromBody(formatSummaryComment(base))).toBe('request_changes'); + const plain = formatSummaryComment({ ...base, verdict: 'approve', detailsUrl: undefined }); + expect(summaryVerdictFromBody(plain)).toBe('approve'); + expect(summaryVerdictFromBody(SUMMARY_MARKER)).toBeNull(); +}); + describe('statusCell', () => { test('is the label alone without images, as for providers that cannot show them', () => { expect(statusCell('building', 'Reviewing 2 files')).toBe('_Reviewing 2 files_'); diff --git a/packages/engine/src/format.ts b/packages/engine/src/format.ts index 73dfda3..7348ff2 100644 --- a/packages/engine/src/format.ts +++ b/packages/engine/src/format.ts @@ -540,6 +540,19 @@ export function latestChangesFromBody(body: string): string | null { return body.match(/\*\*Latest changes:\*\* ([\s\S]*?)\n\n\| Verdict \|/)?.[1] ?? null; } +/** The verdict a summary comment's head row shows, or null when it shows none. */ +export function summaryVerdictFromBody(body: string): Verdict | null { + for (const line of body.split('\n')) { + if (!line.startsWith('| `')) continue; + const cells = (line.endsWith(' |') ? line.slice(0, -2) : line).split(' | '); + const found = (Object.keys(verdictText) as Verdict[]).find((verdict) => + cells.includes(verdictText[verdict]) + ); + if (found) return found; + } + return null; +} + /** The summary comment Hansi keeps up to date on every pull request. */ export function formatSummaryComment(input: SummaryInput): string { const permalink = { repository: input.repository, headSha: input.headSha }; diff --git a/packages/engine/src/summary.ts b/packages/engine/src/summary.ts index 68dba79..9ca18b5 100644 --- a/packages/engine/src/summary.ts +++ b/packages/engine/src/summary.ts @@ -14,6 +14,7 @@ import { formatReviewBody, formatSummaryComment, latestChangesFromBody, + summaryVerdictFromBody, STALE_HEAD_NOTE_MARK, SUMMARY_MARKER, type SummaryInput @@ -121,9 +122,11 @@ export async function refreshSummaryAfterSettlement(input: { const last = lastCompleted(await results.listReviews(pull)); if (!last?.summary || !last.verdict) return; - const reviewed = last.verdict as Verdict; - const rows = summaryFindings(await results.listFindings(pull, { limit: 200 })); + const listed = await results.listFindings(pull, { limit: FINDINGS_LIMIT }); + // The list stops at the limit, so a full one may leave open findings out: never approve on it. + const complete = listed.length < FINDINGS_LIMIT; + 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 })); @@ -132,6 +135,11 @@ export async function refreshSummaryAfterSettlement(input: { 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 = + existing && summaryVerdictFromBody(existing.body) === 'approve' + ? '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) @@ -147,6 +155,7 @@ export async function refreshSummaryAfterSettlement(input: { const current = status ? false : await reviewedHead(); const approves = current && + complete && settled !== 'approve' && !!extras.approvesWhenSettled && !extras.staleHead && @@ -176,35 +185,39 @@ export async function refreshSummaryAfterSettlement(input: { withStatusBlock(formatSummaryComment(summaryInput), status) ); - let verdict: Verdict = approves ? 'approve' : settled; - let summaryInput = build(verdict); - const summary = await write(summaryInput); - // Confirm the head again right before approving: a push during the summary write takes the - // approval back, and the summary with it. - if (approves && !(await reviewedHead())) { - verdict = settled; - summaryInput = build(verdict); - await write(summaryInput); + // 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 } ); - if (verdict === 'approve' && approves) { - await github.createReview({ - pullNumber: pull.pullNumber, - commitId: last.headSha, - body: formatReviewBody({ - tier: summaryInput.tier, - verdict, - blocking: 0, - comments: 0, - summaryUrl: summary.url - }), - comments: [], - event: 'APPROVE' - }); - } // No blocking finding is left: withdraw any change request, including one an earlier review // left in place. Dismissing finds nothing to do when there is none. if (!blockingOpen) { @@ -230,6 +243,9 @@ export async function refreshSummaryAfterSettlement(input: { } } +/** How many findings a settlement reads. */ +const FINDINGS_LIMIT = 200; + function sameSha(a: string, b: string): boolean { return a.toLowerCase() === b.toLowerCase(); } From e631b5922aa6905957c84f2e95a3e65701ef850c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 12:56:20 +0000 Subject: [PATCH 3/3] fix(engine): mark a settlement's approval, and leave a cut findings list alone - A settlement that GitHub took an approval from writes its own hidden mark. Later settlements read that instead of the summary's verdict column, which a review job writes before its own GitHub review is posted. - A findings list at its limit may leave open blockers out, so the settlement no longer rebuilds the grade, the summary or the change request from it, not only the approval. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01F3M7tu37atmEwQALkjzmjx Co-authored-by: Torsten Dittmann <1759475+TorstenDittmann@users.noreply.github.com> --- packages/engine/src/chat-job.test.ts | 19 +++++++++++++++++- packages/engine/src/format.test.ts | 8 -------- packages/engine/src/format.ts | 23 ++++++++++------------ packages/engine/src/summary.ts | 29 ++++++++++++++++++---------- 4 files changed, 47 insertions(+), 32 deletions(-) diff --git a/packages/engine/src/chat-job.test.ts b/packages/engine/src/chat-job.test.ts index 0146afd..27a671b 100644 --- a/packages/engine/src/chat-job.test.ts +++ b/packages/engine/src/chat-job.test.ts @@ -402,7 +402,7 @@ describe('runChatJob', () => { expect(github.checkRuns.map((r) => r.conclusion)).toEqual(['neutral']); }); - test('a findings list cut at its limit never approves', async () => { + 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 = { @@ -411,6 +411,23 @@ describe('runChatJob', () => { 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); diff --git a/packages/engine/src/format.test.ts b/packages/engine/src/format.test.ts index c37046a..197236f 100644 --- a/packages/engine/src/format.test.ts +++ b/packages/engine/src/format.test.ts @@ -12,7 +12,6 @@ import { latestChangesFromBody, statusCell, SUMMARY_MARKER, - summaryVerdictFromBody, type SummaryInput } from './format'; @@ -216,13 +215,6 @@ describe('formatSummaryComment', () => { }); }); -test('summaryVerdictFromBody reads the head row, with or without a details link', () => { - expect(summaryVerdictFromBody(formatSummaryComment(base))).toBe('request_changes'); - const plain = formatSummaryComment({ ...base, verdict: 'approve', detailsUrl: undefined }); - expect(summaryVerdictFromBody(plain)).toBe('approve'); - expect(summaryVerdictFromBody(SUMMARY_MARKER)).toBeNull(); -}); - describe('statusCell', () => { test('is the label alone without images, as for providers that cannot show them', () => { expect(statusCell('building', 'Reviewing 2 files')).toBe('_Reviewing 2 files_'); diff --git a/packages/engine/src/format.ts b/packages/engine/src/format.ts index 7348ff2..5d1f814 100644 --- a/packages/engine/src/format.ts +++ b/packages/engine/src/format.ts @@ -27,6 +27,13 @@ export const STALE_HEAD_NOTE_MARK = ``; */ 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: '🟠', @@ -481,6 +488,8 @@ export interface SummaryInput { 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; @@ -540,19 +549,6 @@ export function latestChangesFromBody(body: string): string | null { return body.match(/\*\*Latest changes:\*\* ([\s\S]*?)\n\n\| Verdict \|/)?.[1] ?? null; } -/** The verdict a summary comment's head row shows, or null when it shows none. */ -export function summaryVerdictFromBody(body: string): Verdict | null { - for (const line of body.split('\n')) { - if (!line.startsWith('| `')) continue; - const cells = (line.endsWith(' |') ? line.slice(0, -2) : line).split(' | '); - const found = (Object.keys(verdictText) as Verdict[]).find((verdict) => - cells.includes(verdictText[verdict]) - ); - if (found) return found; - } - return null; -} - /** The summary comment Hansi keeps up to date on every pull request. */ export function formatSummaryComment(input: SummaryInput): string { const permalink = { repository: input.repository, headSha: input.headSha }; @@ -720,6 +716,7 @@ export function formatSummaryComment(input: SummaryInput): string { : `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/summary.ts b/packages/engine/src/summary.ts index 9ca18b5..5b87406 100644 --- a/packages/engine/src/summary.ts +++ b/packages/engine/src/summary.ts @@ -9,12 +9,12 @@ import type { Log } from './context'; import type { Finding } from './findings'; import { absolutizeLinks, + APPROVED_ON_SETTLEMENT_MARK, APPROVES_WHEN_SETTLED_MARK, filesTooLargeFromBody, formatReviewBody, formatSummaryComment, latestChangesFromBody, - summaryVerdictFromBody, STALE_HEAD_NOTE_MARK, SUMMARY_MARKER, type SummaryInput @@ -64,6 +64,8 @@ export type SummaryExtras = { scope?: string; /** Only open findings kept the review from approving. */ approvesWhenSettled?: boolean; + /** A settlement already approved this head. */ + approvedOnSettlement?: boolean; }; /** @@ -87,7 +89,8 @@ export function summaryExtrasFromBody(body: string): SummaryExtras { staleHead: staleLine ? staleLine.slice(stalePrefix.length) : null, ...(incrementalFrom ? { incrementalFrom } : {}), ...(scope ? { scope } : {}), - ...(body.includes(APPROVES_WHEN_SETTLED_MARK) ? { approvesWhenSettled: true } : {}) + ...(body.includes(APPROVES_WHEN_SETTLED_MARK) ? { approvesWhenSettled: true } : {}), + ...(body.includes(APPROVED_ON_SETTLEMENT_MARK) ? { approvedOnSettlement: true } : {}) }; } @@ -124,8 +127,14 @@ export async function refreshSummaryAfterSettlement(input: { if (!last?.summary || !last.verdict) return; const listed = await results.listFindings(pull, { limit: FINDINGS_LIMIT }); - // The list stops at the limit, so a full one may leave open findings out: never approve on it. - const complete = listed.length < 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') @@ -136,10 +145,7 @@ export async function refreshSummaryAfterSettlement(input: { 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 = - existing && summaryVerdictFromBody(existing.body) === 'approve' - ? 'approve' - : (last.verdict as 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) @@ -155,7 +161,6 @@ export async function refreshSummaryAfterSettlement(input: { const current = status ? false : await reviewedHead(); const approves = current && - complete && settled !== 'approve' && !!extras.approvesWhenSettled && !extras.staleHead && @@ -175,7 +180,10 @@ export async function refreshSummaryAfterSettlement(input: { mention, images: input.images, ...extras, - approvalWithheld: verdict === 'approve' ? null : withheld + 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. const write = (summaryInput: SummaryInput) => @@ -333,6 +341,7 @@ export function summaryAfterSettlement( incrementalFrom: input.incrementalFrom, scope: input.scope, approvesWhenSettled: input.approvesWhenSettled, + approvedOnSettlement: input.approvedOnSettlement, detailsUrl: input.detailsUrl, mention: input.mention, images: input.images