Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | 15x 15x 15x 15x 15x 15x 12x 12x 15x 1x 1x 1x 3x 3x 3x 36x 36x 36x 36x 36x 1x 35x 35x 36x 19x 16x 16x 16x 16x 1x 1x 1x 1x 1x 16x 5x 5x 5x 5x 4x 5x 4x 3x 16x 4x 4x 1x 4x 1x 4x 16x 36x 36x 36x 14x 14x 14x 14x 3x 2x 1x 1x 1x 12x 10x 10x 10x 12x 2x 2x 2x | /**
* Review Poster
*
* Handles posting GitHub PR reviews with deduplication.
* Extracted from main.ts to isolate the complex review posting state machine.
*/
import type { Octokit } from '@octokit/rest';
import type { EventContext, Finding } from '../../types/index.js';
import { filterFindings } from '../../types/index.js';
import { shouldFail } from '../../triggers/matcher.js';
import type { RenderResult } from '../../output/types.js';
import { renderSkillReport, renderFindingsBody } from '../../output/renderer.js';
import {
deduplicateFindings,
processDuplicateActions,
findingToExistingComment,
consolidateBatchFindings,
} from '../../output/dedup.js';
import type { ExistingComment, DeduplicateResult } from '../../output/dedup.js';
import { mergeAuxiliaryUsage } from '../../sdk/usage.js';
import { canUseRuntimeAuth } from '../../sdk/extract.js';
import type { RuntimeName } from '../../sdk/runtimes/index.js';
import type { TriggerResult } from '../triggers/executor.js';
import { logAction, warnAction } from '../../cli/output/tty.js';
// -----------------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------------
/**
* Context for posting a review for a single trigger.
*/
export interface ReviewPostingContext {
result: TriggerResult;
existingComments: ExistingComment[];
apiKey: string;
runtime?: RuntimeName;
model?: string;
maxRetries?: number;
}
/**
* Result from posting a review.
*/
export interface ReviewPostResult {
/** Whether a review was posted */
posted: boolean;
/** New comments that were posted (for cross-trigger deduplication) */
newComments: ExistingComment[];
/** Existing Warden comment IDs matched by current findings */
activeWardenCommentIds: Set<number>;
/** Whether this trigger should cause the action to fail */
shouldFail: boolean;
/** Reason for failure, if any */
failureReason?: string;
}
/**
* Dependencies for the review poster.
*/
export interface ReviewPosterDeps {
octokit: Octokit;
context: EventContext;
}
// -----------------------------------------------------------------------------
// GitHub Review Posting
// -----------------------------------------------------------------------------
/**
* Post a PR review to GitHub.
*/
async function postReviewToGitHub(
octokit: Octokit,
context: EventContext,
result: RenderResult
): Promise<void> {
Iif (!context.pullRequest) {
return;
}
// Only post PR reviews with inline comments - skip standalone summary comments
// as they add noise without providing actionable inline feedback
Iif (!result.review) {
return;
}
const { owner, name: repo } = context.repository;
const pullNumber = context.pullRequest.number;
const commitId = context.pullRequest.headSha;
const reviewComments = result.review.comments
.filter((c): c is typeof c & { path: string; line: number } => Boolean(c.path && c.line))
.map((c) => ({
path: c.path,
line: c.line,
side: c.side ?? ('RIGHT' as const),
body: c.body,
start_line: c.start_line,
start_side: c.start_line ? c.start_side ?? ('RIGHT' as const) : undefined,
}));
await octokit.pulls.createReview({
owner,
repo,
pull_number: pullNumber,
commit_id: commitId,
event: result.review.event,
body: result.review.body,
comments: reviewComments,
});
}
/**
* Move inline comments into the review body as markdown.
* Used as a fallback when GitHub rejects inline comments (e.g. lines outside the diff).
*/
function moveCommentsToBody(renderResult: RenderResult, findings: Finding[], skill: string): RenderResult {
Iif (!renderResult.review) {
return renderResult;
}
const body = renderFindingsBody(findings, skill);
return {
...renderResult,
review: {
...renderResult.review,
body,
comments: [],
},
};
}
/**
* Check if an error is a GitHub 422 "line could not be resolved" error.
*/
function isLineResolutionError(error: unknown): boolean {
Iif (!(error instanceof Error)) return false;
const msg = error.message.toLowerCase();
return msg.includes('pull_request_review_thread.line') ||
msg.includes('line must be part of the diff') ||
msg.includes('line could not be resolved');
}
// -----------------------------------------------------------------------------
// Main Review Posting Logic
// -----------------------------------------------------------------------------
/**
* Post a review for a single trigger result.
*
* Handles:
* - Filtering findings by reportOn threshold
* - Deduplicating against existing comments
* - Processing duplicate actions (reactions, updates)
* - Posting the final review
*/
export async function postTriggerReview(
ctx: ReviewPostingContext,
deps: ReviewPosterDeps
): Promise<ReviewPostResult> {
const { result, existingComments, apiKey } = ctx;
const { octokit, context } = deps;
const newComments: ExistingComment[] = [];
const activeWardenCommentIds = new Set<number>();
if (!result.report) {
return { posted: false, newComments, activeWardenCommentIds, shouldFail: false };
}
// Filter findings by reportOn threshold and confidence
const filteredFindings = filterFindings(result.report.findings, result.reportOn, result.minConfidence);
const reportOnSuccess = result.reportOnSuccess ?? false;
// Skip if nothing to post
if (!result.renderResult || (filteredFindings.length === 0 && !reportOnSuccess)) {
return { posted: false, newComments, activeWardenCommentIds, shouldFail: false };
}
try {
// Cross-location merging already happened in runSkillTask().
// Consolidate findings within this batch (intra-batch dedup).
let findingsToPost = filteredFindings;
const canUseAuxiliaryRuntime = canUseRuntimeAuth({ apiKey, runtime: ctx.runtime });
if (findingsToPost.length > 1) {
const consolidateResult = await consolidateBatchFindings(findingsToPost, {
apiKey,
runtime: ctx.runtime,
model: ctx.model,
hashOnly: !canUseAuxiliaryRuntime,
maxRetries: ctx.maxRetries,
agentName: result.report.skill,
});
findingsToPost = consolidateResult.findings;
Iif (consolidateResult.usage) {
const consolidateAux = { consolidate: consolidateResult.usage };
result.report.auxiliaryUsage = mergeAuxiliaryUsage(result.report.auxiliaryUsage, consolidateAux);
}
Eif (consolidateResult.removedCount > 0) {
logAction(
`Consolidated ${consolidateResult.removedCount} duplicate findings within batch for ${result.triggerName}`
);
}
}
// Deduplicate findings against existing comments
let dedupResult: DeduplicateResult | undefined;
if (existingComments.length > 0 && findingsToPost.length > 0) {
dedupResult = await deduplicateFindings(findingsToPost, existingComments, {
apiKey,
runtime: ctx.runtime,
model: ctx.model,
currentSkill: result.report.skill,
maxRetries: ctx.maxRetries,
});
findingsToPost = dedupResult.newFindings;
// Merge dedup usage into the report's auxiliary usage
Iif (dedupResult.dedupUsage) {
const dedupAux = { dedup: dedupResult.dedupUsage };
result.report.auxiliaryUsage = mergeAuxiliaryUsage(result.report.auxiliaryUsage, dedupAux);
}
if (dedupResult.duplicateActions.length > 0) {
logAction(
`Found ${dedupResult.duplicateActions.length} duplicate findings for ${result.triggerName}`
);
}
for (const action of dedupResult.duplicateActions) {
if (action.existingComment.isWarden && action.existingComment.id > 0) {
activeWardenCommentIds.add(action.existingComment.id);
}
}
}
// Process duplicate actions (update Warden comments, add reactions)
if (dedupResult?.duplicateActions.length) {
const actionCounts = await processDuplicateActions(
octokit,
context.repository.owner,
context.repository.name,
dedupResult.duplicateActions,
result.report.skill
);
if (actionCounts.updated > 0) {
logAction(`Updated ${actionCounts.updated} existing Warden comments with skill attribution`);
}
if (actionCounts.reacted > 0) {
logAction(`Added reactions to ${actionCounts.reacted} existing external comments`);
}
Iif (actionCounts.failed > 0) {
warnAction(`Failed to process ${actionCounts.failed} duplicate actions`);
}
}
// Check if failOn threshold is met (even if all findings deduplicated, we still need REQUEST_CHANGES)
// Filter by confidence first so low-confidence findings don't trigger REQUEST_CHANGES
const useRequestChanges = result.requestChanges ?? false;
const reportForFail = { ...result.report, findings: filterFindings(result.report.findings, undefined, result.minConfidence) };
const needsRequestChanges = useRequestChanges && result.failOn && shouldFail(reportForFail, result.failOn);
// Only post if we have non-duplicate findings, reportOnSuccess, or REQUEST_CHANGES needed
if (findingsToPost.length > 0 || reportOnSuccess || needsRequestChanges) {
// Re-render with deduplicated findings if any were removed
const renderResultToPost =
findingsToPost.length !== filteredFindings.length
? renderSkillReport(
{ ...result.report, findings: findingsToPost },
{
maxFindings: result.maxFindings,
reportOn: result.reportOn,
minConfidence: result.minConfidence,
failOn: result.failOn,
requestChanges: result.requestChanges,
checkRunUrl: result.checkRunUrl,
totalFindings: result.report.findings.length,
// Pass original findings for failOn evaluation (not affected by dedup)
allFindings: result.report.findings,
}
)
: result.renderResult;
// Apply maxFindings limit consistently for both the fallback body and dedup tracking
const postedFindings = result.maxFindings
? findingsToPost.slice(0, result.maxFindings)
: findingsToPost;
try {
await postReviewToGitHub(octokit, context, renderResultToPost);
} catch (error) {
if (!isLineResolutionError(error)) {
throw error;
}
warnAction(`Inline comments failed for ${result.triggerName}, posting findings in review body`);
const fallback = moveCommentsToBody(renderResultToPost, postedFindings, result.report.skill);
await postReviewToGitHub(octokit, context, fallback);
}
for (const finding of postedFindings) {
const comment = findingToExistingComment(finding, result.report.skill);
Eif (comment) {
newComments.push(comment);
}
}
return { posted: true, newComments, activeWardenCommentIds, shouldFail: false };
}
return { posted: false, newComments, activeWardenCommentIds, shouldFail: false };
} catch (error) {
warnAction(`Failed to post review for ${result.triggerName}: ${error}`);
return { posted: false, newComments, activeWardenCommentIds, shouldFail: false };
}
}
|