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 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 | 2x 125x 18x 4x 103x 36x 36x 126x 36x 109x 36x 36x 36x 88x 87x 88x 18x 36x 35x 36x 63x 39x 24x 7x 17x 17x 17x 17x 27x 27x 26x 26x 26x 26x 26x 26x 26x 1x 1x 25x 25x 24x 24x 24x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 48x 48x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 50x 50x 1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 18x 8x 8x 26x 26x 2x 24x 24x 24x 24x 8x 8x 16x 27x 24x 24x 24x 24x 1x 1x 1x 1x 1x 1x 23x 23x 26x 24x 24x 24x 25x 25x 28x 13x 25x | import type { Octokit } from '@octokit/rest';
import { SEVERITY_ORDER, filterFindings } from '../types/index.js';
import type { Severity, SeverityThreshold, ConfidenceThreshold, Finding, SkillReport, UsageStats, AuxiliaryUsageMap } from '../types/index.js';
import { formatDuration, formatCost, formatTokens, totalUsageCost } from '../cli/output/formatters.js';
import { escapeHtml } from '../utils/index.js';
/**
* GitHub Check annotation for inline code comments.
*/
export interface CheckAnnotation {
path: string;
start_line: number;
end_line: number;
annotation_level: 'failure' | 'warning' | 'notice';
message: string;
title?: string;
}
/**
* Possible conclusions for a GitHub Check run.
*/
export type CheckConclusion = 'success' | 'failure' | 'neutral' | 'cancelled';
/**
* Options for creating/updating checks.
*/
export interface CheckOptions {
owner: string;
repo: string;
headSha: string;
}
/**
* Options for updating a skill check.
*/
export interface UpdateSkillCheckOptions extends CheckOptions {
failOn?: SeverityThreshold;
/** Only include findings at or above this severity level in annotations */
reportOn?: SeverityThreshold;
/** Only include findings at or above this confidence level in annotations */
minConfidence?: ConfidenceThreshold;
/** Whether to fail the check run when findings exceed failOn. Default: false */
failCheck?: boolean;
}
/**
* Summary data for the core warden check.
*/
export interface CoreCheckSummaryData {
totalSkills: number;
totalFindings: number;
findingsBySeverity: Record<Severity, number>;
totalDurationMs?: number;
totalUsage?: UsageStats;
/** All findings from all skills */
findings: Finding[];
/** Aggregate auxiliary usage from all skills */
totalAuxiliaryUsage?: AuxiliaryUsageMap;
skillResults: {
name: string;
findingCount: number;
conclusion: CheckConclusion;
durationMs?: number;
usage?: UsageStats;
auxiliaryUsage?: AuxiliaryUsageMap;
}[];
}
/**
* Result from creating a check run.
*/
export interface CreateCheckResult {
checkRunId: number;
url: string;
}
/**
* Maximum number of annotations per API call (GitHub limit).
*/
const MAX_ANNOTATIONS_PER_REQUEST = 50;
/**
* Map severity levels to GitHub annotation levels.
* high -> failure, medium -> warning, low -> notice
*/
export function severityToAnnotationLevel(
severity: Severity
): CheckAnnotation['annotation_level'] {
switch (severity) {
case 'high':
return 'failure';
case 'medium':
return 'warning';
case 'low':
return 'notice';
}
}
/**
* Convert findings to GitHub Check annotations.
* Only findings with locations can be converted to annotations.
* Returns at most MAX_ANNOTATIONS_PER_REQUEST annotations.
* If reportOn is specified, only include findings at or above that severity.
*/
export function findingsToAnnotations(findings: Finding[], reportOn?: SeverityThreshold, minConfidence?: ConfidenceThreshold): CheckAnnotation[] {
// Filter by reportOn threshold and confidence if specified
const filtered = filterFindings(findings, reportOn, minConfidence);
// Filter to findings with location using type predicate
const withLocation = filtered.filter(
(f): f is Finding & { location: NonNullable<Finding['location']> } => Boolean(f.location)
);
// Sort by severity (most severe first)
const sorted = [...withLocation].sort(
(a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]
);
// Limit to max annotations
const limited = sorted.slice(0, MAX_ANNOTATIONS_PER_REQUEST);
const annotations: CheckAnnotation[] = [];
for (const finding of limited) {
if (annotations.length >= MAX_ANNOTATIONS_PER_REQUEST) break;
// Primary location annotation
annotations.push({
path: finding.location.path,
start_line: finding.location.startLine,
end_line: finding.location.endLine ?? finding.location.startLine,
annotation_level: severityToAnnotationLevel(finding.severity),
message: escapeHtml(finding.description),
title: escapeHtml(finding.title),
});
// Additional location annotations
if (finding.additionalLocations) {
for (const loc of finding.additionalLocations) {
if (annotations.length >= MAX_ANNOTATIONS_PER_REQUEST) break;
annotations.push({
path: loc.path,
start_line: loc.startLine,
end_line: loc.endLine ?? loc.startLine,
annotation_level: severityToAnnotationLevel(finding.severity),
message: escapeHtml(finding.description),
title: `[${finding.id}] ${escapeHtml(finding.title)} (additional location)`,
});
}
}
}
return annotations;
}
/**
* Determine the check conclusion based on findings and failOn threshold.
* - No findings: success
* - Findings, none >= failOn: neutral
* - Findings >= failOn threshold: failure
*/
export function determineConclusion(
findings: Finding[],
failOn?: SeverityThreshold,
failCheck?: boolean,
): CheckConclusion {
if (findings.length === 0) {
return 'success';
}
if (!failOn || failOn === 'off') {
// No failure threshold or disabled, findings exist but don't cause failure
return 'neutral';
}
const failOnOrder = SEVERITY_ORDER[failOn];
const hasFailingSeverity = findings.some(
(f) => SEVERITY_ORDER[f.severity] <= failOnOrder
);
return hasFailingSeverity && failCheck ? 'failure' : 'neutral';
}
/**
* Create a check run for a skill.
* The check is created with status: in_progress.
*/
export async function createSkillCheck(
octokit: Octokit,
skillName: string,
options: CheckOptions
): Promise<CreateCheckResult> {
const { data } = await octokit.checks.create({
owner: options.owner,
repo: options.repo,
name: `warden: ${skillName}`,
head_sha: options.headSha,
status: 'in_progress',
started_at: new Date().toISOString(),
});
return {
checkRunId: data.id,
url: data.html_url ?? '',
};
}
/**
* Update a skill check with results.
* Completes the check with conclusion, summary, and annotations.
*/
export async function updateSkillCheck(
octokit: Octokit,
checkRunId: number,
report: SkillReport,
options: UpdateSkillCheckOptions
): Promise<void> {
// Conclusion is based on confidence-filtered findings (consistent with CLI path)
const filteredForConclusion = filterFindings(report.findings, undefined, options.minConfidence);
const conclusion = determineConclusion(filteredForConclusion, options.failOn, options.failCheck);
// Annotations are filtered by reportOn threshold and confidence
const annotations = findingsToAnnotations(report.findings, options.reportOn, options.minConfidence);
const summary = buildSkillSummary(report);
const filteredCount = filteredForConclusion.length;
const title = filteredCount === 0
? 'No issues'
: `${filteredCount} issue${filteredCount === 1 ? '' : 's'}`;
await octokit.checks.update({
owner: options.owner,
repo: options.repo,
check_run_id: checkRunId,
status: 'completed',
conclusion,
completed_at: new Date().toISOString(),
output: {
title,
summary,
annotations,
},
});
}
/**
* Mark a skill check as failed due to execution error.
*/
export async function failSkillCheck(
octokit: Octokit,
checkRunId: number,
error: unknown,
options: CheckOptions
): Promise<void> {
const errorMessage = error instanceof Error ? error.message : String(error);
await octokit.checks.update({
owner: options.owner,
repo: options.repo,
check_run_id: checkRunId,
status: 'completed',
conclusion: 'failure',
completed_at: new Date().toISOString(),
output: {
title: 'Skill execution failed',
summary: `Error: ${errorMessage}`,
},
});
}
/**
* Create the core warden check run.
* The check is created with status: in_progress.
*/
export async function createCoreCheck(
octokit: Octokit,
options: CheckOptions
): Promise<CreateCheckResult> {
const { data } = await octokit.checks.create({
owner: options.owner,
repo: options.repo,
name: 'warden',
head_sha: options.headSha,
status: 'in_progress',
started_at: new Date().toISOString(),
});
return {
checkRunId: data.id,
url: data.html_url ?? '',
};
}
/**
* Update the core warden check with overall summary.
*/
export async function updateCoreCheck(
octokit: Octokit,
checkRunId: number,
summaryData: CoreCheckSummaryData,
conclusion: CheckConclusion,
options: Omit<CheckOptions, 'headSha'>
): Promise<void> {
const summary = buildCoreSummary(summaryData);
const title = summaryData.totalFindings === 0
? 'No issues'
: `${summaryData.totalFindings} issue${summaryData.totalFindings === 1 ? '' : 's'}`;
await octokit.checks.update({
owner: options.owner,
repo: options.repo,
check_run_id: checkRunId,
status: 'completed',
conclusion,
completed_at: new Date().toISOString(),
output: {
title,
summary,
},
});
}
/**
* Format a file location as a markdown code span.
*/
function formatLocation(location: { path: string; startLine: number; endLine?: number }): string {
const { path, startLine, endLine } = location;
const lineRange = endLine && endLine !== startLine ? `${startLine}-${endLine}` : `${startLine}`;
return `\`${path}:${lineRange}\``;
}
/**
* Render findings grouped by severity as collapsible markdown sections.
*/
function renderFindingsSections(findings: Finding[]): string[] {
const lines: string[] = [];
const findingsBySeverity = new Map<Severity, Finding[]>();
for (const finding of findings) {
const existing = findingsBySeverity.get(finding.severity) ?? [];
existing.push(finding);
findingsBySeverity.set(finding.severity, existing);
}
const severityOrder: Severity[] = ['high', 'medium', 'low'];
for (const severity of severityOrder) {
const group = findingsBySeverity.get(severity);
if (!group?.length) continue;
const label = severity.charAt(0).toUpperCase() + severity.slice(1);
lines.push(`### ${label}`, '');
for (const finding of group) {
const location = finding.location ? ` - ${formatLocation(finding.location)}` : '';
lines.push('<details>');
lines.push(`<summary><strong>${escapeHtml(finding.title)}</strong>${location}</summary>`, '');
lines.push(escapeHtml(finding.description), '');
Iif (finding.additionalLocations?.length) {
lines.push('Also found at:');
for (const loc of finding.additionalLocations) {
lines.push(`- ${formatLocation(loc)}`);
}
lines.push('');
}
lines.push('</details>', '');
}
}
return lines;
}
/**
* Render a stats footer line (duration, tokens, cost).
*/
function renderStatsFooter(
durationMs: number | undefined,
usage: UsageStats | undefined,
auxiliaryUsage: AuxiliaryUsageMap | undefined
): string[] {
const cost = totalUsageCost(usage, auxiliaryUsage);
if (durationMs === undefined && !usage && cost === undefined) return [];
const parts: string[] = [];
Eif (durationMs !== undefined) {
parts.push(`⏱ ${formatDuration(durationMs)}`);
}
Eif (usage) {
parts.push(`${formatTokens(usage.inputTokens)} in / ${formatTokens(usage.outputTokens)} out`);
}
Eif (cost !== undefined) {
parts.push(`${formatCost(cost)}`);
}
return ['---', `<sub>${parts.join(' · ')}</sub>`];
}
/**
* Build the summary markdown for a skill check.
*/
function buildSkillSummary(report: SkillReport): string {
const lines: string[] = [escapeHtml(report.summary), ''];
if (report.findings.length === 0) {
lines.push('No issues found.');
} else {
const sortedFindings = [...report.findings].sort(
(a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]
);
lines.push(...renderFindingsSections(sortedFindings));
}
lines.push(...renderStatsFooter(report.durationMs, report.usage, report.auxiliaryUsage));
return lines.join('\n');
}
/** Maximum findings to show in the summary */
const MAX_SUMMARY_FINDINGS = 10;
/**
* Build the summary markdown for the core warden check.
*/
function buildCoreSummary(data: CoreCheckSummaryData): string {
const lines: string[] = [];
// Sort findings by severity and take top N
const sortedFindings = [...data.findings].sort(
(a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity]
);
const topFindings = sortedFindings.slice(0, MAX_SUMMARY_FINDINGS);
if (topFindings.length > 0) {
lines.push(...renderFindingsSections(topFindings));
Iif (data.totalFindings > topFindings.length) {
const remaining = data.totalFindings - topFindings.length;
lines.push(`*...and ${remaining} more*`, '');
}
} else {
lines.push('No issues found.', '');
}
// Skills table in collapsible section
const hasSkillStats = data.skillResults.some((s) => s.durationMs !== undefined || s.usage || s.auxiliaryUsage);
const skillPlural = data.totalSkills === 1 ? '' : 's';
lines.push('<details>');
lines.push(`<summary>${data.totalSkills} skill${skillPlural} analyzed</summary>`, '');
if (hasSkillStats) {
lines.push(
'| Skill | Findings | Duration | Cost |',
'|-------|----------|----------|------|'
);
for (const skill of data.skillResults) {
const duration = skill.durationMs !== undefined ? formatDuration(skill.durationMs) : '-';
const costUSD = totalUsageCost(skill.usage, skill.auxiliaryUsage);
const cost = costUSD !== undefined ? formatCost(costUSD) : '-';
lines.push(`| ${skill.name} | ${skill.findingCount} | ${duration} | ${cost} |`);
}
} else {
lines.push(
'| Skill | Findings |',
'|-------|----------|'
);
for (const skill of data.skillResults) {
lines.push(`| ${skill.name} | ${skill.findingCount} |`);
}
}
lines.push('', '</details>', '');
lines.push(...renderStatsFooter(data.totalDurationMs, data.totalUsage, data.totalAuxiliaryUsage));
return lines.join('\n');
}
/**
* Aggregate severity counts from multiple reports.
*/
export function aggregateSeverityCounts(
reports: SkillReport[]
): Record<Severity, number> {
const counts: Record<Severity, number> = {
high: 0,
medium: 0,
low: 0,
};
for (const report of reports) {
for (const finding of report.findings) {
counts[finding.severity]++;
}
}
return counts;
}
|