All files / src/cli terminal.ts

88.23% Statements 120/136
84.7% Branches 72/85
100% Functions 10/10
87.96% Lines 117/133

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                                        5x                               8x 8x 8x 8x 8x 1x   1x   6x                         11x 11x 11x     11x     11x 8x 8x     8x       11x 8x 8x 8x 1x 7x 6x           11x 2x 2x 2x 3x 3x         11x 11x     11x         11x 1x 1x       11x 1x 1x 1x 3x 1x 2x 1x 1x 1x       1x     11x             18x 18x     18x 18x 8x   18x 18x     18x     18x 1x       18x         18x 1x 2x 2x   1x       18x     18x 2x 2x 2x 8x       18x             12x 12x   12x           12x       12x                 12x 12x   12x 1x 1x     11x 11x 11x 11x 11x   11x           12x   12x               29x 29x 29x         29x                 29x     29x     29x 3x   29x 3x   29x 4x     29x 18x 18x     29x                 41x     41x           41x   12x 12x 12x       29x 29x 29x       41x                   9x 3x            
import { readFileSync } from 'node:fs';
import chalk from 'chalk';
import type { SkillReport, Finding, Severity, SeverityThreshold, ConfidenceThreshold } from '../types/index.js';
import { filterFindings } from '../types/index.js';
import {
  formatSeverityBadge,
  formatSeverityPlain,
  formatConfidenceBadge,
  formatFindingCounts,
  formatFindingCountsPlain,
  formatDuration,
  formatElapsed,
  formatLocation,
  countBySeverity,
  pluralize,
} from './output/index.js';
import { Verbosity } from './output/verbosity.js';
import { BoxRenderer } from './output/box.js';
import type { OutputMode } from './output/tty.js';
 
const SEVERITY_COLORS: Record<Severity, typeof chalk.red> = {
  high: chalk.red,
  medium: chalk.yellow,
  low: chalk.green,
};
 
type FileLineResult =
  | { status: 'ok'; line: string }
  | { status: 'file_unavailable' }
  | { status: 'line_not_found' };
 
/**
 * Read a specific line from a file.
 * Returns a result indicating success, file unavailable, or line not found.
 */
function readFileLine(filePath: string, lineNumber: number): FileLineResult {
  try {
    const content = readFileSync(filePath, 'utf-8');
    const lines = content.split('\n');
    const line = lines[lineNumber - 1];
    if (lineNumber > 0 && lineNumber <= lines.length && line !== undefined) {
      return { status: 'ok', line };
    }
    return { status: 'line_not_found' };
  } catch {
    return { status: 'file_unavailable' };
  }
}
 
interface RenderOptions {
  suppressFixDiffs?: boolean;
  verbosity?: Verbosity;
}
 
/**
 * Format a finding for TTY display.
 */
function formatFindingTTY(finding: Finding, options?: RenderOptions): string[] {
  const lines: string[] = [];
  const badge = formatSeverityBadge(finding.severity);
  const color = SEVERITY_COLORS[finding.severity];
 
  // Title line with severity badge
  lines.push(`${badge} ${color(finding.title)}`);
 
  // Location with elapsed time
  if (finding.location) {
    const locParts = [chalk.dim(`${finding.location.path}:${finding.location.startLine}`)];
    Iif (finding.elapsedMs !== undefined) {
      locParts.push(chalk.dim(formatElapsed(finding.elapsedMs)));
    }
    lines.push(`  ${locParts.join('  ')}`);
  }
 
  // Code snippet
  if (finding.location?.startLine) {
    const result = readFileLine(finding.location.path, finding.location.startLine);
    const lineNum = chalk.dim(`${finding.location.startLine} │`);
    if (result.status === 'ok') {
      lines.push(`  ${lineNum} ${result.line.trimStart()}`);
    } else if (result.status === 'file_unavailable') {
      lines.push(`  ${lineNum} ${chalk.dim.italic('(file unavailable)')}`);
    }
    // For 'line_not_found', we silently skip - the line may not exist in this version
  }
 
  // Additional locations
  if (finding.additionalLocations?.length) {
    const count = finding.additionalLocations.length;
    lines.push(`  ${chalk.dim(`+${count} more ${pluralize(count, 'location')}:`)}`);
    for (const loc of finding.additionalLocations) {
      const range = loc.endLine ? `${loc.startLine}-${loc.endLine}` : `${loc.startLine}`;
      lines.push(`    ${chalk.dim(`${loc.path}:${range}`)}`);
    }
  }
 
  // Blank line, then description
  lines.push('');
  lines.push(`  ${chalk.dim(finding.description)}`);
 
  // Verification (what the agent checked)
  Iif (finding.verification) {
    lines.push(`  ${chalk.dim.italic(finding.verification)}`);
  }
 
  // Confidence level
  if (finding.confidence) {
    lines.push('');
    lines.push(`  ${formatConfidenceBadge(finding.confidence)}`);
  }
 
  // Suggested fix diff if available (suppress when step-through will show it)
  if (finding.suggestedFix?.diff && !options?.suppressFixDiffs) {
    lines.push('');
    lines.push(chalk.dim('  Suggested fix:'));
    const diffLines = finding.suggestedFix.diff.split('\n').map((line) => {
      if (line.startsWith('+') && !line.startsWith('+++')) {
        return chalk.green(`  ${line}`);
      } else if (line.startsWith('-') && !line.startsWith('---')) {
        return chalk.red(`  ${line}`);
      E} else if (line.startsWith('@@')) {
        return chalk.cyan(`  ${line}`);
      }
      return `  ${line}`;
    });
    lines.push(...diffLines);
  }
 
  return lines;
}
 
/**
 * Format a finding for CI (non-TTY) display.
 */
function formatFindingCI(finding: Finding): string[] {
  const lines: string[] = [];
  const badge = formatSeverityPlain(finding.severity);
 
  // Title line with location (including endLine range) and elapsed time
  const titleParts = [badge];
  if (finding.location) {
    titleParts.push(formatLocation(finding.location.path, finding.location.startLine, finding.location.endLine));
  }
  titleParts.push('-', finding.title);
  Iif (finding.elapsedMs !== undefined) {
    titleParts.push(`(${formatElapsed(finding.elapsedMs)})`);
  }
  lines.push(titleParts.join(' '));
 
  // Confidence
  if (finding.confidence) {
    lines.push(`  confidence: ${finding.confidence}`);
  }
 
  // Verification
  Iif (finding.verification) {
    lines.push(`  verification: ${finding.verification}`);
  }
 
  // Additional locations
  if (finding.additionalLocations?.length) {
    const locs = finding.additionalLocations.map((loc) => {
      const range = loc.endLine ? `${loc.startLine}-${loc.endLine}` : `${loc.startLine}`;
      return `${loc.path}:${range}`;
    });
    lines.push(`  also at: ${locs.join(', ')}`);
  }
 
  // Description
  lines.push(`  ${finding.description}`);
 
  // Suggested fix diff (plain text, no color)
  if (finding.suggestedFix?.diff) {
    lines.push('');
    lines.push('  Suggested fix:');
    for (const line of finding.suggestedFix.diff.split('\n')) {
      lines.push(`  ${line}`);
    }
  }
 
  return lines;
}
 
/**
 * Render a skill report as a box (TTY mode).
 */
function renderSkillBoxTTY(report: SkillReport, mode: OutputMode, options?: RenderOptions): string[] {
  const counts = countBySeverity(report.findings);
  const durationStr = report.durationMs !== undefined ? formatDuration(report.durationMs) : undefined;
 
  const box = new BoxRenderer({
    title: report.skill,
    badge: durationStr,
    mode,
  });
 
  box.header();
 
  // Errored runs render as failures, not "No issues found" — the skill
  // never finished, so a finding count is the wrong frame.
  Iif (report.error) {
    box.content(chalk.red(`FAILED (${report.error.code})`));
    box.blank();
    box.content(report.error.message);
    box.footer();
    return box.render();
  }
 
  // Finding counts summary line
  const countStr = formatFindingCounts(counts);
  box.content(countStr);
 
  if (report.findings.length === 0) {
    box.blank();
    box.content(chalk.green('No issues found.'));
  } else {
    // Render each finding
    for (const [index, finding] of report.findings.entries()) {
      box.divider();
      box.blank();
      const findingLines = formatFindingTTY(finding, options);
      box.content(findingLines);
      // Only add blank after finding if not the last one
      Iif (index < report.findings.length - 1) {
        box.blank();
      }
    }
  }
 
  box.footer();
 
  return box.render();
}
 
/**
 * Render a skill report for CI (non-TTY) mode.
 * See specs/reporters.md "Plain" findings report section.
 */
function renderSkillCI(report: SkillReport, verbosity: Verbosity = Verbosity.Normal): string[] {
  const lines: string[] = [];
  const counts = countBySeverity(report.findings);
  const durationStr = report.durationMs !== undefined ? ` (${formatDuration(report.durationMs)})` : '';
 
  // For errored runs, lead with the failure rather than a misleading
  // "No issues found" line — the skill never finished, so a finding count
  // is the wrong frame.
  Iif (report.error) {
    lines.push(`${report.skill}${durationStr} - FAILED (${report.error.code})`);
    lines.push(`  ${report.error.message}`);
    if (report.failedHunks) {
      lines.push(`  ${report.failedHunks} ${pluralize(report.failedHunks, 'chunk')} failed to analyze`);
    }
    return lines;
  }
 
  const summary = formatFindingCountsPlain(counts);
 
  // Header: skill (duration) - summary
  lines.push(`${report.skill}${durationStr} - ${summary}`);
 
  // Per-skill warnings for operational issues
  if (report.failedHunks) {
    lines.push(`  WARN: ${report.failedHunks} ${pluralize(report.failedHunks, 'chunk')} failed to analyze`);
  }
  if (report.failedExtractions) {
    lines.push(`  WARN: ${report.failedExtractions} finding ${pluralize(report.failedExtractions, 'extraction')} failed`);
  }
  if ((report.failedHunks || report.failedExtractions) && verbosity < Verbosity.Verbose) {
    lines.push('  Use -v for failure details');
  }
 
  for (const [index, finding] of report.findings.entries()) {
    if (index > 0) lines.push('');
    lines.push(...formatFindingCI(finding));
  }
 
  return lines;
}
 
/**
 * Render skill reports for terminal output.
 * @param reports - The skill reports to render
 * @param mode - Output mode (TTY vs non-TTY)
 */
export function renderTerminalReport(reports: SkillReport[], mode?: OutputMode, options?: RenderOptions): string {
  const lines: string[] = [];
 
  // Default to TTY mode if not specified (for backwards compatibility)
  const outputMode: OutputMode = mode ?? {
    isTTY: true,
    supportsColor: true,
    columns: 80,
  };
 
  if (outputMode.isTTY) {
    // TTY mode: use boxes
    for (const report of reports) {
      lines.push(...renderSkillBoxTTY(report, outputMode, options));
      lines.push('');
    }
  } else {
    // CI mode: plain text
    for (const report of reports) {
      lines.push(...renderSkillCI(report, options?.verbosity));
      lines.push('');
    }
  }
 
  return lines.join('\n');
}
 
/**
 * Filter reports to only include findings at or above the given severity threshold
 * and confidence threshold.
 * Returns new report objects with filtered findings; does not mutate the originals.
 * If reportOn is 'off', returns reports with empty findings.
 */
export function filterReports(reports: SkillReport[], reportOn?: SeverityThreshold, minConfidence?: ConfidenceThreshold): SkillReport[] {
  if (!reportOn && !minConfidence) return reports;
  return reports.map((report) => ({
    ...report,
    findings: filterFindings(report.findings, reportOn, minConfidence),
  }));
}