diff --git a/test/pr-review-advisor.test.ts b/test/pr-review-advisor.test.ts index a59ab3007c2..0729910bf50 100644 --- a/test/pr-review-advisor.test.ts +++ b/test/pr-review-advisor.test.ts @@ -1035,29 +1035,33 @@ diff --git a/test/example.test.ts b/test/example.test.ts expect(detailed).toContain("## Source-of-truth review"); expect(detailed).toContain("trusted-code boundary"); expect(comment).toContain("
"); - expect(comment).toContain( - "Review findings by urgency: 1 required fix, 0 items to resolve/justify, 0 in-scope improvements", - ); + expect(comment).toContain("### Action checklist"); + expect(comment).toContain("### Findings index"); + expect(comment).toContain("| `PRA-1` | Required | workflow |"); expect(comment).toContain("Test follow-ups to resolve or justify"); - expect(comment).toContain("- **Mocked behavioral coverage** — comment builder test."); + expect(comment).toContain("- `PRA-T1` **Mocked behavioral coverage** — comment builder test."); expect(comment).not.toContain("\\*\\*Mocked behavioral coverage\\*\\*"); expect(comment).toContain("comment builder test"); expect(comment).toContain(""); - expect(comment).toContain("**Review posture:** Resolve findings before merge"); + expect(comment).toContain("## PR Review Advisor — Changes requested"); + expect(comment).toContain("**Merge posture:** Do not merge yet"); + expect(comment).toContain("**Primary next action:** Fix `PRA-1`: trusted-code boundary"); expect(comment).toContain("### 🚨 Required before merge"); - expect(comment).toContain("### ⚠️ Resolve or justify before merge"); - expect(comment).toContain("### 💡 In-scope improvements"); + expect(comment).toContain("#### `PRA-1` Required — trusted-code boundary"); expect(comment).toContain( - "Impact: A PR-controlled workflow could run advisor code with repository secrets.", + "- **Impact:** A PR-controlled workflow could run advisor code with repository secrets.", ); expect(comment).toContain( - "Verification hint: Inspect the workflow checkout and advisor script path.", + "- **Verification:** Inspect the workflow checkout and advisor script path.", ); expect(comment).toContain( - "Missing regression test: Keep the workflow trusted-code boundary test.", + "- **Missing regression test:** Keep the workflow trusted-code boundary test.", ); expect(comment).toContain( - "Expected follow-up: Fix before merge or get explicit maintainer override.", + "- **Expected follow-up:** Fix before merge or get explicit maintainer override.", + ); + expect(comment).toContain( + "- **Done when:** The required change is committed and verification passes: Inspect the workflow checkout and advisor script path.", ); expect(comment).toContain( "Treat suggestions as current-PR improvements when they touch changed code", @@ -1074,7 +1078,7 @@ diff --git a/test/example.test.ts b/test/example.test.ts expect(summary).not.toContain("## Review completeness"); expect(summary).not.toContain("Human maintainer review required"); expect(comment).toContain( - "1 required fix, 0 items to resolve/justify, 0 in-scope improvements", + "**Open items:** 1 required · 0 warnings · 0 suggestions · 1 test follow-up", ); expect(comment).toContain("**Top item:** trusted-code boundary"); expect(summary).not.toContain("Base: `origin/main`"); @@ -1100,9 +1104,9 @@ diff --git a/test/example.test.ts b/test/example.test.ts result: followUpResult, }); expect(followUp).toContain( - "**Since last review:** 1 prior item resolved, 1 still applies, 1 new item found", + "**Since last review:** 1 prior item resolved · 1 still applies · 1 new item found", ); - expect(followUp).toContain("Review findings by urgency:"); + expect(followUp).toContain("### Action checklist"); expect(followUp).toContain("Since last review details"); }); @@ -1146,6 +1150,37 @@ diff --git a/test/example.test.ts b/test/example.test.ts expect(comment).toContain("Safety boundary: Keep input validation and timezone test coverage."); }); + it("prioritizes warning findings ahead of test follow-ups", () => { + const result = normalizeReviewResult( + validResult({ + findings: [ + { + severity: "warning", + category: "correctness", + file: "src/lib/example.ts", + line: 12, + title: "Resolve the warning first", + description: "Warnings should remain ahead of test follow-ups in scan-first sections.", + recommendation: + "Resolve or justify this warning before working through test follow-ups.", + }, + ], + }), + metadata(), + ); + + const comment = buildComment({ summary: renderSummary(result), result }); + const warningChecklist = "- [ ] `PRA-1` Resolve or justify: Resolve the warning first"; + const testChecklist = "- [ ] `PRA-T1` Add or justify test follow-up"; + + expect(comment).toContain( + "**Primary next action:** Resolve or justify `PRA-1`: Resolve the warning first.", + ); + expect(comment).toContain(warningChecklist); + expect(comment).toContain(testChecklist); + expect(comment.indexOf(warningChecklist)).toBeLessThan(comment.indexOf(testChecklist)); + }); + it("renders suggestion findings as in-scope current-review work", () => { const result = normalizeReviewResult( validResult({ @@ -1176,8 +1211,12 @@ diff --git a/test/example.test.ts b/test/example.test.ts ); expect(comment).toContain("### 💡 In-scope improvements"); expect(comment).toContain( - "Expected follow-up: Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.", + "- [ ] `PRA-1` In-scope improvement: Simplify changed branch in src/lib/example.ts:12", ); + expect(comment).toContain( + "- **Expected follow-up:** Prefer a current-PR fix when local to changed code; defer only with rationale or linked follow-up.", + ); + expect(comment).not.toContain("Optional: Simplify changed branch"); expect(comment).not.toContain("nice ideas"); }); @@ -1194,13 +1233,59 @@ diff --git a/test/example.test.ts b/test/example.test.ts ); const comment = buildComment({ summary: renderSummary(result), result }); - expect(comment).toContain("- **Mocked behavioral coverage** — probe"); + expect(comment).toContain("- `PRA-T1` **Mocked behavioral coverage** — probe"); expect(comment).toContain("probe \\*\\*bold\\*\\* \\[link\\]\\(https://bad.invalid\\)."); expect(comment).toContain("</details> and @team"); expect(comment).not.toContain("- \\*\\*Mocked behavioral coverage\\*\\*"); expect(comment).not.toContain("check
"); }); + it("keeps hostile file locations inside checklist and table fields", () => { + const result = normalizeReviewResult( + validResult({ + findings: [ + { + severity: "blocker", + category: "correctness", + file: "src/a|b.ts", + line: 7, + title: "Pipe in path", + description: "Location should not add a table cell.", + }, + { + severity: "warning", + category: "correctness", + file: "src/a\nb.ts", + line: 8, + title: "Newline in path", + description: "Location should stay on one rendered line.", + }, + { + severity: "suggestion", + category: "correctness", + file: "src/a`b.ts", + line: 9, + title: "Backtick in path", + description: "Location should not break a Markdown code span.", + }, + ], + }), + metadata(), + ); + const comment = buildComment({ summary: renderSummary(result), result }); + const indexRows = comment.split("\n").filter((line) => /^\| `PRA-/.test(line)); + + expect(indexRows).toHaveLength(3); + expect(indexRows[0]).toContain("src/a|b.ts:7"); + expect(indexRows[1]).toContain("src/a b.ts:8"); + expect(indexRows[2]).toContain("src/a`b.ts:9"); + for (const row of indexRows) expect(row.match(/\|/g)).toHaveLength(6); + expect(comment).toContain("- [ ] `PRA-1` Fix: Pipe in path in src/a|b.ts:7"); + expect(comment).toContain("- **Location:** src/a b.ts:8"); + expect(comment).not.toContain("src/a\nb.ts"); + expect(comment).not.toContain("`src/a`b.ts:9`"); + }); + it("escapes advisor finding text before rendering sticky comments", () => { const result = normalizeReviewResult( validResult({ @@ -1231,7 +1316,7 @@ diff --git a/test/example.test.ts b/test/example.test.ts expect(comment).toContain( "</details> @team \\*\\*boom\\*\\* \\[x\\]\\(https://bad.invalid\\)", ); - expect(comment).toContain("src/<bad>\\(1\\).ts:7"); + expect(comment).toContain("src/<bad>(1).ts:7"); expect(comment).toContain("first ### injected <script>"); expect(comment).toContain("ping @here & fix \\_now\\_"); expect(comment).toContain("\\`code\\` <tag>"); diff --git a/tools/pr-review-advisor/comment.mts b/tools/pr-review-advisor/comment.mts index 3ccf9e4d24f..9baf7539c3f 100755 --- a/tools/pr-review-advisor/comment.mts +++ b/tools/pr-review-advisor/comment.mts @@ -69,11 +69,23 @@ type CommentMetadata = { commentId?: string; }; +type Finding = NonNullable[number]; + +type FindingRecord = { + id: string; + finding: Finding; +}; + type TestingFollowup = { label: string; text: string; }; +type TestingFollowupRecord = { + id: string; + followup: TestingFollowup; +}; + if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { main().catch((error: unknown) => { console.error(error instanceof Error ? error.message : String(error)); @@ -151,33 +163,55 @@ export function buildComment({ marker?: string; metadata?: CommentMetadata; }): string { - const blockerCount = - result?.findings?.filter((finding) => finding.severity === "blocker").length ?? 0; - const warningCount = - result?.findings?.filter((finding) => finding.severity === "warning").length ?? 0; - const suggestionCount = - result?.findings?.filter((finding) => finding.severity === "suggestion").length ?? 0; - const secondary = buildSecondarySummary(result); - const findingsDetails = renderFindingsDetails(result); - const simplificationDetails = renderSimplificationDetails(result); - const testingFollowupsDetails = renderTestingFollowupsDetails(result); - const previousReviewDetails = renderPreviousReviewDetails(result); + const findingRecords = collectFindingRecords(result); + const testingFollowups = collectTestingFollowupRecords(result); + const blockerCount = findingRecords.filter( + (record) => record.finding.severity === "blocker", + ).length; + const warningCount = findingRecords.filter( + (record) => record.finding.severity === "warning", + ).length; + const suggestionCount = findingRecords.filter( + (record) => record.finding.severity === "suggestion", + ).length; + const secondary = buildSecondarySummary(result, findingRecords); + const actionChecklist = renderActionChecklist(findingRecords, testingFollowups); + const findingsIndex = renderFindingsIndex(findingRecords); + const findingsDetails = renderFindingsDetails(findingRecords); + const simplificationDetails = renderSimplificationDetails(findingRecords); + const testingFollowupsDetails = renderTestingFollowupsDetails(testingFollowups); + const previousReviewDetails = renderPreviousReviewDetails(result, findingRecords); const details = runUrl ? `\n[Workflow run details](${runUrl})` : ""; const hiddenMetadata = renderHiddenMetadata(result, metadata); const posture = reviewPosture(result?.summary?.recommendation); + const headline = reviewHeadline(result?.summary?.recommendation); return `${marker || MARKER} -${hiddenMetadata}## PR Review Advisor +${hiddenMetadata}## PR Review Advisor — ${headline} -**Review posture:** ${posture} -**Action expectation:** Address required items before merge. Resolve or explicitly justify warnings. Treat suggestions as current-PR improvements when they touch changed code; defer only with maintainer rationale or a linked follow-up. -**Findings:** ${countLabel(blockerCount, "required fix", "required fixes")}, ${countLabel(warningCount, "item to resolve/justify", "items to resolve/justify")}, ${countLabel(suggestionCount, "in-scope improvement", "in-scope improvements")} -${secondary}${findingsDetails}${simplificationDetails}${testingFollowupsDetails}${previousReviewDetails}${details} +**Merge posture:** ${posture} +**Primary next action:** ${primaryNextAction(findingRecords, testingFollowups)} +**Open items:** ${compactCount(blockerCount, "required", "required")} · ${compactCount(warningCount, "warning")} · ${compactCount(suggestionCount, "suggestion")} · ${compactCount(testingFollowups.length, "test follow-up")} +${secondary}${actionChecklist}${findingsIndex}${findingsDetails}${simplificationDetails}${testingFollowupsDetails}${previousReviewDetails}${details} -This is an automated, non-binding review; it still expects maintainers and agents to respond to each finding. A human maintainer must make the final merge decision. +This is an automated, non-binding review; it still expects maintainers and agents to respond to each required or warning item. Treat suggestions as current-PR improvements when they touch changed code; defer only with maintainer rationale or a linked follow-up. A human maintainer must make the final merge decision. `; } +function collectFindingRecords(result?: ReviewAdvisorResult): FindingRecord[] { + return (result?.findings || []).map((finding, index) => ({ + id: `PRA-${index + 1}`, + finding, + })); +} + +function collectTestingFollowupRecords(result?: ReviewAdvisorResult): TestingFollowupRecord[] { + return collectTestingFollowups(result).map((followup, index) => ({ + id: `PRA-T${index + 1}`, + followup, + })); +} + function renderHiddenMetadata(result?: ReviewAdvisorResult, metadata?: CommentMetadata): string { const fields = [ result?.headSha ? `head_sha: ${safeMetadataValue(result.headSha)}` : undefined, @@ -198,9 +232,18 @@ function safeMetadataValue(value: string): string { .slice(0, 120); } +function reviewHeadline(recommendation?: string): string { + if (recommendation === "merge_as_is") return "No blocking findings"; + if (recommendation === "merge_after_fixes") return "Changes requested"; + if (recommendation === "needs_rework" || recommendation === "blocked") return "Blocked"; + if (recommendation === "superseded") return "Superseded"; + if (recommendation === "info_only") return "Informational"; + return "Review ready"; +} + function reviewPosture(recommendation?: string): string { if (recommendation === "merge_as_is") return "No blocking advisor findings"; - if (recommendation === "merge_after_fixes") return "Resolve findings before merge"; + if (recommendation === "merge_after_fixes") return "Do not merge yet"; if (recommendation === "needs_rework" || recommendation === "blocked") { return "Do not merge until addressed"; } @@ -209,76 +252,148 @@ function reviewPosture(recommendation?: string): string { return "Review findings and decide before merge"; } -function buildSecondarySummary(result?: ReviewAdvisorResult): string { +function primaryNextAction( + records: FindingRecord[], + testingFollowups: TestingFollowupRecord[], +): string { + const blocker = records.find((record) => record.finding.severity === "blocker"); + if (blocker) { + const testText = + testingFollowups.length > 0 ? `; then add or justify \`${testingFollowups[0]?.id}\`` : ""; + return `Fix \`${blocker.id}\`: ${escapeCommentText(findingTitle(blocker.finding))}${testText}.`; + } + const warning = records.find((record) => record.finding.severity === "warning"); + if (warning) { + return `Resolve or justify \`${warning.id}\`: ${escapeCommentText(findingTitle(warning.finding))}.`; + } + if (testingFollowups.length > 0) { + return `Add or justify \`${testingFollowups[0]?.id || "PRA-T1"}\` and any related test follow-ups.`; + } + const suggestion = records.find((record) => record.finding.severity === "suggestion"); + if (suggestion) { + return `Consider \`${suggestion.id}\`: ${escapeCommentText(findingTitle(suggestion.finding))}.`; + } + return "No advisor follow-up required beyond maintainer review."; +} + +function buildSecondarySummary( + result?: ReviewAdvisorResult, + records: FindingRecord[] = [], +): string { const sinceLastReview = result?.summary?.sinceLastReview; if (sinceLastReview) { - return `**Since last review:** ${countLabel(sinceLastReview.resolved, "prior item")} resolved, ${countLabel(sinceLastReview.stillApplies, "still applies", "still apply")}, ${countLabel(sinceLastReview.newItems, "new item")} found\n`; + return `**Since last review:** ${countLabel(sinceLastReview.resolved, "prior item")} resolved · ${countLabel(sinceLastReview.stillApplies, "still applies", "still apply")} · ${countLabel(sinceLastReview.newItems, "new item")} found\n`; } - const topItem = result?.summary?.topItem || topFindingTitle(result); + const topItem = result?.summary?.topItem || topFindingTitle(records); return topItem ? `**Top item:** ${escapeCommentText(topItem)}\n` : ""; } -function topFindingTitle(result?: ReviewAdvisorResult): string | undefined { +function topFindingTitle(records: FindingRecord[]): string | undefined { return ( - result?.findings?.find((finding) => finding.severity === "blocker")?.title || - result?.findings?.find((finding) => finding.severity === "warning")?.title || - result?.findings?.find((finding) => finding.severity === "suggestion")?.title + records.find((record) => record.finding.severity === "blocker")?.finding.title || + records.find((record) => record.finding.severity === "warning")?.finding.title || + records.find((record) => record.finding.severity === "suggestion")?.finding.title ); } -function renderFindingsDetails(result?: ReviewAdvisorResult): string { - if (!result?.findings?.length) return ""; - const blockerFindings = result.findings.filter((finding) => finding.severity === "blocker"); - const warningFindings = result.findings.filter((finding) => finding.severity === "warning"); - const suggestionFindings = result.findings.filter((finding) => finding.severity === "suggestion"); - const sections = [ - { - summary: "🚨 Required before merge", - guidance: - "Address these before merging unless a maintainer explicitly overrides the advisor with rationale.", - findings: blockerFindings, - }, - { - summary: "⚠️ Resolve or justify before merge", - guidance: - "Investigate these in the current review; either fix them, explain why they are not applicable, or document the accepted risk.", - findings: warningFindings, - }, - { - summary: "💡 In-scope improvements", - guidance: - "These are lower-risk, not throwaway. Prefer fixing them in this PR when they are local to changed code; defer only with rationale or a linked follow-up.", - findings: suggestionFindings, - }, - ]; - const lines: string[] = [ +function renderActionChecklist( + records: FindingRecord[], + testingFollowups: TestingFollowupRecord[], +): string { + if (records.length === 0 && testingFollowups.length === 0) return ""; + const lines = ["", "### Action checklist", ""]; + for (const record of records.filter((item) => item.finding.severity === "blocker").slice(0, 10)) { + lines.push(formatChecklistFinding(record, "Fix")); + } + for (const record of records.filter((item) => item.finding.severity === "warning").slice(0, 10)) { + lines.push(formatChecklistFinding(record, "Resolve or justify")); + } + for (const followup of testingFollowups.slice(0, 8)) + lines.push(formatChecklistFollowup(followup)); + for (const record of records + .filter((item) => item.finding.severity === "suggestion") + .slice(0, 10)) { + lines.push(formatChecklistFinding(record, "In-scope improvement")); + } + return `${lines.join("\n")}\n`; +} + +function formatChecklistFinding(record: FindingRecord, action: string): string { + const location = formatInlineLocation(record.finding); + const locationText = location ? ` in ${location}` : ""; + return `- [ ] \`${record.id}\` ${action}: ${escapeCommentText(findingTitle(record.finding))}${locationText}`; +} + +function formatChecklistFollowup(record: TestingFollowupRecord): string { + return `- [ ] \`${record.id}\` Add or justify test follow-up: ${escapeCommentText(record.followup.label)}`; +} + +function renderFindingsIndex(records: FindingRecord[]): string { + if (records.length === 0) return ""; + const lines = [ "", - "
", - `Review findings by urgency: ${countLabel(blockerFindings.length, "required fix", "required fixes")}, ${countLabel(warningFindings.length, "item to resolve/justify", "items to resolve/justify")}, ${countLabel(suggestionFindings.length, "in-scope improvement", "in-scope improvements")}`, + "### Findings index", "", + "| ID | Severity | Category | Location | Required action |", + "|---|---|---|---|---|", ]; + for (const record of records.slice(0, 20)) { + const finding = record.finding; + lines.push( + `| \`${record.id}\` | ${severityLabel(finding.severity)} | ${escapeCommentText(finding.category || "uncategorized")} | ${formatTableLocation(finding)} | ${escapeCommentText(finding.recommendation || findingTitle(finding))} |`, + ); + } + return `${lines.join("\n")}\n`; +} - for (const section of sections) { - lines.push(`### ${section.summary}`); - lines.push(`_${section.guidance}_`); - if (section.findings.length === 0) { - lines.push("- _None._"); - } else { - for (const finding of section.findings.slice(0, 20)) { - lines.push(formatFinding(finding)); - } - } - lines.push(""); +function renderFindingsDetails(records: FindingRecord[]): string { + if (records.length === 0) return ""; + const blockerFindings = records.filter((record) => record.finding.severity === "blocker"); + const warningFindings = records.filter((record) => record.finding.severity === "warning"); + const suggestionFindings = records.filter((record) => record.finding.severity === "suggestion"); + const lines: string[] = []; + if (blockerFindings.length > 0) { + lines.push("", "### 🚨 Required before merge"); + lines.push( + "_Address these before merging unless a maintainer explicitly overrides the advisor with rationale._", + "", + ); + for (const record of blockerFindings.slice(0, 20)) lines.push(formatFinding(record), ""); + } + if (warningFindings.length === 0 && suggestionFindings.length === 0) + return `${lines.join("\n")}\n`; + lines.push( + "
", + `Review findings by urgency: ${countLabel(blockerFindings.length, "required fix", "required fixes")}, ${countLabel(warningFindings.length, "item to resolve/justify", "items to resolve/justify")}, ${countLabel(suggestionFindings.length, "in-scope improvement", "in-scope improvements")}`, + "", + ); + lines.push("### ⚠️ Resolve or justify before merge"); + lines.push( + "_Investigate these in the current review; either fix them, explain why they are not applicable, or document the accepted risk._", + ); + if (warningFindings.length === 0) { + lines.push("- _None._"); + } else { + for (const record of warningFindings.slice(0, 20)) lines.push(formatFinding(record)); + } + lines.push("", "### 💡 In-scope improvements"); + lines.push( + "_These are lower-risk, not throwaway. Prefer fixing them in this PR when they are local to changed code; defer only with rationale or a linked follow-up._", + ); + if (suggestionFindings.length === 0) { + lines.push("- _None._"); + } else { + for (const record of suggestionFindings.slice(0, 20)) lines.push(formatFinding(record)); } - lines.push("
", ""); + lines.push("", "
", ""); return `${lines.join("\n")}\n`; } -function renderSimplificationDetails(result?: ReviewAdvisorResult): string { - const findings = result?.findings?.filter((finding) => finding.simplification) || []; +function renderSimplificationDetails(records: FindingRecord[]): string { + const findings = records.filter((record) => record.finding.simplification); if (findings.length === 0) return ""; - const netLines = findings.reduce((total, finding) => { - const value = finding.simplification?.estimatedNetLines; + const netLines = findings.reduce((total, record) => { + const value = record.finding.simplification?.estimatedNetLines; return typeof value === "number" && Number.isFinite(value) ? total + value : total; }, 0); const netLabel = netLines < 0 ? `, net ${netLines} lines possible` : ""; @@ -289,12 +404,12 @@ function renderSimplificationDetails(result?: ReviewAdvisorResult): string { "", "_These are safe simplification checks only. Do not remove validation, security controls, data-loss prevention, or required tests._", ]; - for (const finding of findings.slice(0, 12)) { - const item = finding.simplification; + for (const record of findings.slice(0, 12)) { + const item = record.finding.simplification; if (!item) continue; - const location = formatFindingLocation(finding); + const location = formatFindingLocation(record.finding); lines.push( - `- **${escapeCommentText(item.tag || "shrink")}**${location}: ${escapeCommentText(item.cut || finding.title || "Review simplification")}`, + `- \`${record.id}\` **${escapeCommentText(item.tag || "shrink")}**${location}: ${escapeCommentText(item.cut || record.finding.title || "Review simplification")}`, ); lines.push( ` - Replacement: ${escapeCommentText(item.replacement || "Use the simpler existing path.")}`, @@ -310,9 +425,8 @@ function renderSimplificationDetails(result?: ReviewAdvisorResult): string { return `${lines.join("\n")}\n`; } -function renderTestingFollowupsDetails(result?: ReviewAdvisorResult): string { - const followups = collectTestingFollowups(result); - if (followups.length === 0) return ""; +function renderTestingFollowupsDetails(records: TestingFollowupRecord[]): string { + if (records.length === 0) return ""; const lines: string[] = [ "", "
", @@ -320,7 +434,7 @@ function renderTestingFollowupsDetails(result?: ReviewAdvisorResult): string { "", "_If these cover changed behavior, prefer adding them in this PR; otherwise state why existing coverage is enough or link the follow-up._", ]; - for (const followup of followups) lines.push(formatTestingFollowup(followup)); + for (const record of records) lines.push(formatTestingFollowup(record)); lines.push("", "
", ""); return `${lines.join("\n")}\n`; } @@ -364,8 +478,8 @@ function collectTestingFollowups(result?: ReviewAdvisorResult): TestingFollowup[ return uniqueTestingFollowups(followups).slice(0, 8); } -function formatTestingFollowup(followup: TestingFollowup): string { - return `- **${escapeCommentText(followup.label)}** — ${escapeCommentText(followup.text)}`; +function formatTestingFollowup(record: TestingFollowupRecord): string { + return `- \`${record.id}\` **${escapeCommentText(record.followup.label)}** — ${escapeCommentText(record.followup.text)}`; } function uniqueTestingFollowups(followups: TestingFollowup[]): TestingFollowup[] { @@ -386,37 +500,65 @@ function testDepthLabel(verdict: string): string { return "Test coverage"; } -function renderPreviousReviewDetails(result?: ReviewAdvisorResult): string { +function renderPreviousReviewDetails( + result: ReviewAdvisorResult | undefined, + records: FindingRecord[], +): string { const sinceLastReview = result?.summary?.sinceLastReview; - if (!sinceLastReview || !result?.findings?.length) return ""; + if (!sinceLastReview || records.length === 0) return ""; const lines: string[] = ["
", "Since last review details", ""]; lines.push("Current findings, using the urgency labels above:"); - for (const finding of result.findings.slice(0, 20)) lines.push(formatFinding(finding)); + for (const record of records.slice(0, 20)) lines.push(formatFinding(record)); lines.push("", "
", ""); return `${lines.join("\n")}\n`; } -function formatFinding(finding: NonNullable[number]): string { - const title = escapeCommentText(finding.title || "Review finding"); - const location = formatFindingLocation(finding); - const description = finding.description ? `: ${escapeCommentText(finding.description)}` : ""; - const lines = [`- **${title}**${location}${description}`]; - if (finding.impact) lines.push(` - Impact: ${escapeCommentText(finding.impact)}`); +function formatFinding(record: FindingRecord): string { + const finding = record.finding; + const title = escapeCommentText(findingTitle(finding)); + const lines = [`#### \`${record.id}\` ${severityLabel(finding.severity)} — ${title}`]; + lines.push(`- **Location:** ${formatInlineLocation(finding) || "not file-specific"}`); + lines.push(`- **Category:** ${escapeCommentText(finding.category || "uncategorized")}`); + if (finding.description) lines.push(`- **Problem:** ${escapeCommentText(finding.description)}`); + if (finding.impact) lines.push(`- **Impact:** ${escapeCommentText(finding.impact)}`); if (finding.recommendation) { - lines.push(` - Recommendation: ${escapeCommentText(finding.recommendation)}`); + lines.push( + `- **${actionFieldLabel(finding.severity)}:** ${escapeCommentText(finding.recommendation)}`, + ); } const expectedFollowUp = findingExpectedFollowUp(finding.severity); - if (expectedFollowUp) lines.push(` - Expected follow-up: ${expectedFollowUp}`); + if (expectedFollowUp) lines.push(`- **Expected follow-up:** ${expectedFollowUp}`); if (finding.verificationHint) { - lines.push(` - Verification hint: ${escapeCommentText(finding.verificationHint)}`); + lines.push(`- **Verification:** ${escapeCommentText(finding.verificationHint)}`); } if (finding.missingRegressionTest) { - lines.push(` - Missing regression test: ${escapeCommentText(finding.missingRegressionTest)}`); + lines.push( + `- **Missing regression test:** ${escapeCommentText(finding.missingRegressionTest)}`, + ); } - if (finding.evidence) lines.push(` - Evidence: ${escapeCommentText(finding.evidence)}`); + lines.push(`- **Done when:** ${doneWhenForFinding(finding)}`); + if (finding.evidence) lines.push(`- **Evidence:** ${escapeCommentText(finding.evidence)}`); return lines.join("\n"); } +function findingTitle(finding: Finding): string { + return finding.title || "Review finding"; +} + +function severityLabel(severity?: string): string { + if (severity === "blocker") return "Required"; + if (severity === "warning") return "Resolve/justify"; + if (severity === "suggestion") return "Improvement"; + return "Review"; +} + +function actionFieldLabel(severity?: string): string { + if (severity === "blocker") return "Required action"; + if (severity === "warning") return "Recommended action"; + if (severity === "suggestion") return "Suggested action"; + return "Recommendation"; +} + function findingExpectedFollowUp(severity?: string): string { if (severity === "blocker") return "Fix before merge or get explicit maintainer override."; if (severity === "warning") return "Resolve in this PR or explain why the risk is acceptable."; @@ -426,14 +568,58 @@ function findingExpectedFollowUp(severity?: string): string { return "Review and decide whether this PR should act on it."; } -function formatFindingLocation( - finding: NonNullable[number], -): string { +function doneWhenForFinding(finding: Finding): string { + if (finding.severity === "blocker") { + const verification = finding.verificationHint + ? `and verification passes: ${stripTerminalPunctuation(finding.verificationHint)}` + : "and the fix is covered by relevant test or review evidence"; + return escapeCommentText(`The required change is committed ${verification}.`); + } + if (finding.severity === "warning") { + const verification = finding.verificationHint + ? ` Verification: ${stripTerminalPunctuation(finding.verificationHint)}.` + : ""; + return escapeCommentText(`The risk is fixed or explicitly justified in the PR.${verification}`); + } + if (finding.severity === "suggestion") { + return escapeCommentText( + "The local improvement is applied, or the PR notes why it should be deferred.", + ); + } + return escapeCommentText("The PR records the maintainer decision for this item."); +} + +function stripTerminalPunctuation(value: string): string { + return value.trim().replace(/[.!?]+$/g, ""); +} + +function formatFindingLocation(finding: Finding): string { if (!finding.file) return ""; const line = Number.isInteger(finding.line) && Number(finding.line) > 0 ? `:${finding.line}` : ""; return ` (${escapeCommentText(finding.file)}${line})`; } +function formatInlineLocation(finding: Finding): string { + if (!finding.file) return ""; + const line = Number.isInteger(finding.line) && Number(finding.line) > 0 ? `:${finding.line}` : ""; + return `${escapeLocationHtml(`${finding.file}${line}`)}`; +} + +function formatTableLocation(finding: Finding): string { + return formatInlineLocation(finding) || "—"; +} + +function escapeLocationHtml(value: string): string { + return value + .replace(/\s+/g, " ") + .trim() + .replaceAll("&", "&") + .replaceAll("<", "<") + .replaceAll(">", ">") + .replaceAll("|", "|") + .replaceAll("@", "@"); +} + function escapeCommentText(value: string): string { return value .replace(/\s+/g, " ") @@ -449,3 +635,7 @@ function countLabel(count: unknown, singular: string, plural = `${singular}s`): const numeric = typeof count === "number" && Number.isFinite(count) ? count : 0; return `${numeric} ${numeric === 1 ? singular : plural}`; } + +function compactCount(count: number, singular: string, plural = `${singular}s`): string { + return `${count} ${count === 1 ? singular : plural}`; +}