All files / src/sdk analyze.ts

82.49% Statements 245/297
66.81% Branches 147/220
76.92% Functions 30/39
82.45% Lines 235/285

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 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976                                                                                                    7x 5x 5x   2x       8x       7x               2x                               7x 6x 7x                                             6x           6x   6x 5x       1x               1x         1x                                   13x 13x     13x 11x 11x     13x 13x 9x   4x     13x                           14x   14x                     14x   14x 14x     14x 14x 14x 14x     14x     14x         14x             14x   14x 16x 16x         16x                         16x 16x 16x 16x                                     8x       8x                           8x 8x     8x   8x   2x     2x 2x           2x       2x         2x 2x 2x 2x     2x                     6x 16x     6x 6x 6x                             6x     6x             16x 1x             6x 6x   6x                       8x   8x 1x 1x                       7x               7x                     7x             7x 8x 5x       2x 2x   8x           8x     8x               8x 8x                                   7x     14x 5x       5x                   5x 5x   5x 5x 5x 5x 2x   3x                                 16x 16x 16x             14x                                   9x                     9x 9x 9x 9x 9x 9x 9x   9x 15x   14x 14x   15x                       15x 15x 14x             14x 7x 7x               7x 1x 1x                   14x 15x 15x                                 15x   15x 15x 15x         9x 9x 9x   9x                                 9x 5x     4x 4x 4x     4x 4x 4x 4x   4x                     6x                     6x 6x 5x 5x 5x   1x 1x                     6x 6x   6x       6x           6x 1x                 1x     1x     5x 5x 5x     5x 5x     5x 5x         5x 5x 5x                           5x   5x   5x     9x     9x                                                                   5x   5x   5x         5x 5x 5x 5x       6x     6x   5x 5x   5x     5x     5x   5x                         5x 5x 5x 5x 5x 5x 5x 2x   5x                       5x 5x 6x     5x 2x 1x   1x             1x   1x   1x                       4x                             4x 4x     4x     4x   4x               4x               4x 6x     4x 1x   4x     4x 1x   4x 4x 1x   4x    
import type { SkillDefinition } from '../config/schema.js';
import type { ErrorCode, Finding, RetryConfig } from '../types/index.js';
import { getHunkLineRange, type HunkWithContext } from '../diff/index.js';
import { Sentry, emitExtractionMetrics, emitRetryMetric, emitSkillMetrics } from '../sentry.js';
import { SkillRunnerError, WardenAuthenticationError, isRetryableError, isAuthenticationError, isAuthenticationErrorMessage, isSubprocessError, classifyError, mapExtractionErrorCode, sanitizeErrorMessage } from './errors.js';
import type { CircuitBreakerReason } from './circuit-breaker.js';
import { DEFAULT_RETRY_CONFIG, calculateRetryDelay, sleep } from './retry.js';
import { aggregateUsage, emptyUsage, estimateTokens, aggregateAuxiliaryUsage } from './usage.js';
import { buildHunkSystemPrompt, buildHunkUserPrompt, type PRPromptContext } from './prompt.js';
import { extractFindingsJson, extractFindingsWithLLM, validateFindings } from './extract.js';
import { postProcessFindings } from './post-process.js';
import { buildFileReports } from './report-files.js';
import { getRuntime, getRuntimeProviderOptions } from './runtimes/index.js';
import type { SkillRunResult } from './runtimes/index.js';
import {
  LARGE_PROMPT_THRESHOLD_CHARS,
  DEFAULT_FILE_CONCURRENCY,
  type AuxiliaryUsageEntry,
  type HunkAnalysisResult,
  type HunkAnalysisCallbacks,
  type SkillRunnerOptions,
  type PreparedFile,
  type FileAnalysisCallbacks,
  type FileAnalysisResult,
  type ChunkAnalysisResult,
} from './types.js';
import { prepareFiles } from './prepare.js';
import type { EventContext, SkillReport, UsageStats, HunkFailure } from '../types/index.js';
import { runPool } from '../utils/index.js';
 
/** Result from parsing hunk output */
interface ParseHunkOutputResult {
  findings: Finding[];
  /** Whether extraction failed (both regex and LLM fallback) */
  extractionFailed: boolean;
  /** Which extraction method succeeded */
  extractionMethod: 'regex' | 'llm' | 'none';
  /** Error message if extraction failed */
  extractionError?: string;
  /** Preview of the output that failed to parse */
  extractionPreview?: string;
  /** Usage from LLM extraction fallback, if invoked */
  extractionUsage?: UsageStats;
}
 
function notifyHunkFailed(
  callbacks: HunkAnalysisCallbacks | undefined,
  lineRange: string,
  message: string,
): void {
  if (callbacks) {
    callbacks.onHunkFailed?.(lineRange, message);
    return;
  }
  console.error(`Hunk analysis failed for ${lineRange}.`);
}
 
function isAbortRequested(error: unknown, abortController?: AbortController): boolean {
  return (abortController?.signal.aborted ?? false) || classifyError(error).code === 'aborted';
}
 
function isCircuitBreakerCode(code: ErrorCode | undefined): code is CircuitBreakerReason['code'] {
  return code === 'auth_failed' || code === 'provider_unavailable' || code === 'invalid_model_selector';
}
 
function hunkFailureFromCircuit(
  reason: CircuitBreakerReason,
  usage: UsageStats[],
  attempts: number,
): HunkAnalysisResult {
  return {
    findings: [],
    usage: aggregateUsage(usage),
    failed: true,
    extractionFailed: false,
    failureCode: reason.code,
    failureMessage: reason.message,
    attempts,
  };
}
 
function recordCircuitFailure(
  options: SkillRunnerOptions,
  code: ErrorCode,
  message: string,
): CircuitBreakerReason | undefined {
  if (!isCircuitBreakerCode(code)) return undefined;
  options.circuitBreaker?.recordFailure(code, message);
  return options.circuitBreaker?.reason;
}
 
function allHunksFailedGuidance(runtime: SkillRunnerOptions['runtime'] | undefined): string {
  if ((runtime ?? 'pi') === 'pi') {
    return 'Verify Pi has credentials for the selected provider/model, or choose a configured Pi model.';
  }
 
  return "Verify WARDEN_ANTHROPIC_API_KEY is set correctly, or run 'claude login' when using the Claude runtime without an API key.";
}
 
/**
 * Parse findings from a hunk analysis result.
 * Uses a two-tier extraction strategy:
 * 1. Regex-based extraction (fast, handles well-formed output)
 * 2. LLM fallback using haiku (handles malformed output gracefully)
 */
async function parseHunkOutput(
  result: SkillRunResult,
  filename: string,
  skillName: string,
  options: SkillRunnerOptions
): Promise<ParseHunkOutputResult> {
  Iif (result.status !== 'success') {
    // SDK error - not an extraction failure, just no findings
    return { findings: [], extractionFailed: false, extractionMethod: 'none' };
  }
 
  // Tier 1: Try regex-based extraction first (fast)
  const extracted = extractFindingsJson(result.text);
 
  if (extracted.success) {
    return { findings: validateFindings(extracted.findings, filename), extractionFailed: false, extractionMethod: 'regex' };
  }
 
  // Tier 2: Try LLM fallback for malformed output
  const fallback = await extractFindingsWithLLM(result.text, {
    apiKey: options.apiKey,
    runtime: options.runtime,
    model: options.auxiliaryModel,
    maxRetries: options.auxiliaryMaxRetries,
    agentName: skillName,
  });
 
  Iif (fallback.success) {
    return { findings: validateFindings(fallback.findings, filename), extractionFailed: false, extractionMethod: 'llm', extractionUsage: fallback.usage };
  }
 
  // Both tiers failed - return extraction failure info
  return {
    findings: [],
    extractionFailed: true,
    extractionMethod: 'none',
    extractionError: fallback.error,
    extractionPreview: fallback.preview,
    extractionUsage: fallback.usage,
  };
}
 
/**
 * Filter findings whose startLine falls outside the hunk line range.
 * Findings without a location are kept (general findings).
 */
export function filterOutOfRangeFindings(
  findings: Finding[],
  hunkRange: { start: number; end: number }
): { filtered: Finding[]; dropped: Finding[] } {
  const filtered: Finding[] = [];
  const dropped: Finding[] = [];
 
  function isWithinHunk(finding: Finding): boolean {
    if (!finding.location) return true;
    const { startLine } = finding.location;
    return startLine >= hunkRange.start && startLine <= hunkRange.end;
  }
 
  for (const finding of findings) {
    if (isWithinHunk(finding)) {
      filtered.push(finding);
    } else {
      dropped.push(finding);
    }
  }
  return { filtered, dropped };
}
 
/**
 * Analyze a single hunk with retry logic for transient failures.
 */
async function analyzeHunk(
  skill: SkillDefinition,
  hunkCtx: HunkWithContext,
  repoPath: string,
  options: SkillRunnerOptions,
  callbacks?: HunkAnalysisCallbacks,
  prContext?: PRPromptContext
): Promise<HunkAnalysisResult> {
  const lineRange = callbacks?.lineRange ?? formatHunkLineRange(hunkCtx);
 
  return Sentry.startSpan(
    {
      op: 'skill.analyze_hunk',
      name: `analyze hunk ${hunkCtx.filename}:${lineRange}`,
      attributes: {
        'gen_ai.agent.name': skill.name,
        'code.file.path': hunkCtx.filename,
        'warden.hunk.line_range': lineRange,
      },
    },
    async (span) => {
      const { abortController, retry } = options;
 
      const systemPrompt = buildHunkSystemPrompt(skill);
      const userPrompt = buildHunkUserPrompt(skill, hunkCtx, prContext);
 
      // Report prompt size information
      const systemChars = systemPrompt.length;
      const userChars = userPrompt.length;
      const totalChars = systemChars + userChars;
      const estimatedTokensCount = estimateTokens(totalChars);
 
      // Always call onPromptSize if provided (for debug mode)
      callbacks?.onPromptSize?.(callbacks.lineRange, systemChars, userChars, totalChars, estimatedTokensCount);
 
      // Warn about large prompts
      Iif (totalChars > LARGE_PROMPT_THRESHOLD_CHARS) {
        callbacks?.onLargePrompt?.(callbacks.lineRange, totalChars, estimatedTokensCount);
      }
 
      // Merge retry config with defaults
      const retryConfig: Required<RetryConfig> = {
        ...DEFAULT_RETRY_CONFIG,
        ...retry,
      };
 
      let lastError: unknown;
      // Track accumulated usage across retry attempts for accurate cost reporting
      const accumulatedUsage: UsageStats[] = [];
 
      for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
        const circuitReason = options.circuitBreaker?.reason;
        Iif (circuitReason) {
          return hunkFailureFromCircuit(circuitReason, accumulatedUsage, attempt);
        }
 
        // Check for abort before each attempt
        Iif (abortController?.signal.aborted) {
          callbacks?.onHunkFailed?.(callbacks.lineRange, 'Analysis aborted');
          return {
            findings: [],
            usage: aggregateUsage(accumulatedUsage),
            failed: true,
            extractionFailed: false,
            failureCode: 'aborted',
            failureMessage: 'Analysis aborted',
            attempts: attempt,
          };
        }
 
        try {
          const runtimeName = options.runtime ?? 'pi';
          const runtime = getRuntime(runtimeName);
          const { result: resultMessage, authError } = await runtime.runSkill({
            apiKey: options.apiKey,
            systemPrompt,
            userPrompt,
            repoPath,
            skillName: skill.name,
            tools: skill.tools,
            options: {
              maxTurns: options.maxTurns,
              model: options.model,
              abortController: options.abortController,
            },
            providerOptions: getRuntimeProviderOptions(runtimeName, {
              pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable,
            }),
          });
 
          // Check for authentication errors from auth_status messages
          // auth_status errors are always auth-related - throw immediately
          Iif (authError) {
            throw new WardenAuthenticationError(authError);
          }
 
          Iif (!resultMessage) {
            notifyHunkFailed(callbacks, callbacks?.lineRange ?? lineRange, 'SDK returned no result');
            return {
              findings: [],
              usage: aggregateUsage(accumulatedUsage),
              failed: true,
              extractionFailed: false,
              failureCode: 'sdk_error',
              failureMessage: 'SDK returned no result',
              attempts: attempt + 1,
            };
          }
 
          // Extract usage from the result, regardless of success/error status
          const usage = resultMessage.usage;
          accumulatedUsage.push(usage);
 
          // Check if the SDK returned an error result (e.g., max turns, budget exceeded)
          const isError = resultMessage.status !== 'success';
 
          if (isError) {
            // Extract error messages from SDK result
            const errorMessages = resultMessage.errors;
 
            // Check if any error indicates authentication failure
            for (const err of errorMessages) {
              Iif (isAuthenticationErrorMessage(err)) {
                throw new WardenAuthenticationError();
              }
            }
 
            // SDK error - log and return failure with error details
            const errorSummary = errorMessages.length > 0
              ? sanitizeErrorMessage(errorMessages.join('; '))
              : `Runtime error: ${resultMessage.status}`;
            const failureCode =
              resultMessage.status === 'turn_limit'
                ? 'max_turns'
                : resultMessage.status === 'provider_error'
                  ? 'provider_unavailable'
                  : 'sdk_error';
            const failureMessage = `Runtime execution failed: ${errorSummary}`;
            const openReason = recordCircuitFailure(options, failureCode, failureMessage);
            notifyHunkFailed(callbacks, callbacks?.lineRange ?? lineRange, failureMessage);
            Iif (openReason) {
              return hunkFailureFromCircuit(openReason, accumulatedUsage, attempt + 1);
            }
            return {
              findings: [],
              usage: aggregateUsage(accumulatedUsage),
              failed: true,
              extractionFailed: false,
              failureCode,
              failureMessage,
              attempts: attempt + 1,
            };
          }
 
          options.circuitBreaker?.recordSuccess();
          const parseResult = await parseHunkOutput(resultMessage, hunkCtx.filename, skill.name, options);
 
          // Filter findings outside hunk line range (defense-in-depth)
          const hunkRange = getHunkLineRange(hunkCtx.hunk);
          const { filtered: filteredFindings, dropped } = filterOutOfRangeFindings(parseResult.findings, hunkRange);
          Iif (dropped.length > 0) {
            Sentry.addBreadcrumb({
              category: 'finding.out_of_range',
              message: `Dropped ${dropped.length} finding(s) outside hunk range ${hunkRange.start}-${hunkRange.end}`,
              level: 'warning',
              data: {
                skill: skill.name,
                filename: hunkCtx.filename,
                hunkRange,
                droppedLines: dropped.map((f) => f.location?.startLine),
              },
            });
          }
 
          // Emit extraction metrics
          emitExtractionMetrics(skill.name, parseResult.extractionMethod, filteredFindings.length);
 
          // Notify about extraction result (debug mode)
          callbacks?.onExtractionResult?.(
            callbacks.lineRange,
            filteredFindings.length,
            parseResult.extractionMethod
          );
 
          // Notify about extraction failure if callback provided
          if (parseResult.extractionFailed) {
            callbacks?.onExtractionFailure?.(
              callbacks.lineRange,
              parseResult.extractionError ?? 'unknown_error',
              parseResult.extractionPreview ?? ''
            );
          }
 
          span.setAttribute('warden.hunk.failed', false);
          span.setAttribute('warden.finding.count', filteredFindings.length);
 
          return {
            findings: filteredFindings,
            usage: aggregateUsage(accumulatedUsage),
            failed: false,
            extractionFailed: parseResult.extractionFailed,
            extractionError: parseResult.extractionError,
            extractionPreview: parseResult.extractionPreview,
            auxiliaryUsage: parseResult.extractionUsage
              ? [{ agent: 'extraction', usage: parseResult.extractionUsage }]
              : undefined,
          };
        } catch (error) {
          lastError = error;
 
          if (isAbortRequested(error, abortController)) {
            callbacks?.onHunkFailed?.(callbacks.lineRange, 'Analysis aborted');
            return {
              findings: [],
              usage: aggregateUsage(accumulatedUsage),
              failed: true,
              extractionFailed: false,
              failureCode: 'aborted',
              failureMessage: 'Analysis aborted',
              attempts: attempt + 1,
            };
          }
 
          // Re-throw authentication errors (they shouldn't be retried)
          Iif (error instanceof WardenAuthenticationError) {
            const message = sanitizeErrorMessage(error.message);
            options.circuitBreaker?.recordFailure('auth_failed', message);
            throw error;
          }
 
          // Subprocess IPC failures (EPIPE, ECONNRESET, etc.) indicate the Claude CLI
          // can't communicate — surface as an auth error with actionable guidance
          Iif (isSubprocessError(error)) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            options.circuitBreaker?.recordFailure('auth_failed', sanitizeErrorMessage(errorMessage));
            throw new WardenAuthenticationError(
              `Claude Code subprocess failed (${errorMessage}).\n` +
              `This usually means the claude CLI cannot run in this environment.`,
              { cause: error }
            );
          }
 
          // Authentication errors should surface immediately with helpful guidance
          Iif (isAuthenticationError(error)) {
            const errorMessage = error instanceof Error ? error.message : String(error);
            options.circuitBreaker?.recordFailure('auth_failed', sanitizeErrorMessage(errorMessage));
            throw new WardenAuthenticationError(undefined, { cause: error });
          }
 
          // Don't retry if not a retryable error or we've exhausted retries
          const shouldRetry = isRetryableError(error) && attempt < retryConfig.maxRetries;
          if (!shouldRetry) {
            break;
          }
 
          // Calculate delay and wait before retry
          const delayMs = calculateRetryDelay(attempt, retryConfig);
          const errorMessage = sanitizeErrorMessage(error instanceof Error ? error.message : String(error));
 
          Sentry.addBreadcrumb({
            category: 'retry',
            message: `Retrying hunk analysis`,
            data: { attempt: attempt + 1, error: errorMessage, delayMs },
            level: 'warning',
          });
          emitRetryMetric(skill.name, attempt + 1);
 
          // Notify about retry in verbose mode
          callbacks?.onRetry?.(
            callbacks.lineRange,
            attempt + 1,
            retryConfig.maxRetries,
            errorMessage,
            delayMs
          );
 
          try {
            await sleep(delayMs, abortController?.signal);
          } catch {
            // Aborted during sleep
            callbacks?.onHunkFailed?.(callbacks.lineRange, 'Analysis aborted during retry delay');
            return {
              findings: [],
              usage: aggregateUsage(accumulatedUsage),
              failed: true,
              extractionFailed: false,
              failureCode: 'aborted',
              failureMessage: 'Analysis aborted during retry delay',
              attempts: attempt + 1,
            };
          }
        }
      }
 
      // All attempts failed - return failure with any accumulated usage
      const finalError = sanitizeErrorMessage(lastError instanceof Error ? lastError.message : String(lastError));
 
      // Log the final error
      if (lastError) {
        notifyHunkFailed(callbacks, callbacks?.lineRange ?? lineRange, `All retry attempts failed: ${finalError}`);
      }
 
      // Also notify via callback if verbose
      Iif (options.verbose) {
        callbacks?.onRetry?.(
          callbacks.lineRange,
          retryConfig.maxRetries + 1,
          retryConfig.maxRetries,
          `Final failure: ${finalError}`,
          0
        );
      }
 
      span.setAttribute('warden.hunk.failed', true);
      span.setAttribute('warden.finding.count', 0);
 
      const { code: retryCode, message } = classifyError(lastError);
      const retryMsg = sanitizeErrorMessage(message);
      const openReason = recordCircuitFailure(options, retryCode, retryMsg);
      if (openReason) {
        return hunkFailureFromCircuit(openReason, accumulatedUsage, retryConfig.maxRetries + 1);
      }
      return {
        findings: [],
        usage: aggregateUsage(accumulatedUsage),
        failed: true,
        extractionFailed: false,
        failureCode: retryCode,
        failureMessage: `All retry attempts failed: ${retryMsg}`,
        attempts: retryConfig.maxRetries + 1,
      };
    },
  );
}
 
/**
 * Format a hunk's line range as a display string (e.g. "10-20" or "10").
 */
function formatHunkLineRange(hunk: HunkWithContext): string {
  const start = hunk.hunk.newStart;
  const end = start + hunk.hunk.newCount - 1;
  return start === end ? `${start}` : `${start}-${end}`;
}
 
/**
 * Attach elapsed time to findings if skill start time is available.
 */
function attachElapsedTime(findings: Finding[], skillStartTime: number | undefined): void {
  Eif (skillStartTime === undefined) return;
  const elapsedMs = Date.now() - skillStartTime;
  for (const finding of findings) {
    finding.elapsedMs = elapsedMs;
  }
}
 
/**
 * Analyze a single prepared file's hunks.
 */
export async function analyzeFile(
  skill: SkillDefinition,
  file: PreparedFile,
  repoPath: string,
  options: SkillRunnerOptions = {},
  callbacks?: FileAnalysisCallbacks,
  prContext?: PRPromptContext
): Promise<FileAnalysisResult> {
  return Sentry.startSpan(
    {
      op: 'skill.analyze_file',
      name: `analyze file ${file.filename}`,
      attributes: {
        'gen_ai.agent.name': skill.name,
        'code.file.path': file.filename,
        'warden.hunk.count': file.hunks.length,
      },
    },
    async (span) => {
      const { abortController } = options;
      const fileFindings: Finding[] = [];
      const fileUsage: UsageStats[] = [];
      const fileAuxiliaryUsage: AuxiliaryUsageEntry[] = [];
      const hunkFailures: HunkFailure[] = [];
      let failedHunks = 0;
      let failedExtractions = 0;
 
      for (const [hunkIndex, hunk] of file.hunks.entries()) {
        if (abortController?.signal.aborted) break;
 
        const lineRange = formatHunkLineRange(hunk);
        callbacks?.onHunkStart?.(hunkIndex + 1, file.hunks.length, lineRange);
 
        const hunkCallbacks: HunkAnalysisCallbacks | undefined = callbacks
          ? {
              lineRange,
              onLargePrompt: callbacks.onLargePrompt,
              onPromptSize: callbacks.onPromptSize,
              onRetry: callbacks.onRetry,
              onExtractionFailure: callbacks.onExtractionFailure,
              onExtractionResult: callbacks.onExtractionResult,
              onHunkFailed: callbacks.onHunkFailed,
            }
          : undefined;
 
        const hunkStartTime = Date.now();
        const result = await analyzeHunk(skill, hunk, repoPath, options, hunkCallbacks, prContext);
        const hunkDurationMs = Date.now() - hunkStartTime;
 
        // `failed` and `extractionFailed` are conceptually mutually exclusive:
        // if analysis failed (no output produced), there's nothing to extract.
        // Use else-if so a future change that violates this invariant doesn't
        // silently double-count (one hunk → two hunkFailures entries +
        // failedHunks AND failedExtractions both incremented).
        if (result.failed && result.failureCode !== 'aborted') {
          failedHunks++;
          hunkFailures.push({
            type: 'analysis',
            filename: file.filename,
            lineRange,
            code: result.failureCode ?? 'unknown',
            message: result.failureMessage ?? 'unknown error',
            ...(result.attempts !== undefined ? { attempts: result.attempts } : {}),
          });
        } else if (result.extractionFailed) {
          failedExtractions++;
          hunkFailures.push({
            type: 'extraction',
            filename: file.filename,
            lineRange,
            code: mapExtractionErrorCode(result.extractionError),
            message: result.extractionError ?? 'unknown extraction error',
            ...(result.extractionPreview !== undefined ? { preview: result.extractionPreview } : {}),
          });
        }
 
        attachElapsedTime(result.findings, callbacks?.skillStartTime);
        callbacks?.onHunkComplete?.(hunkIndex + 1, result.findings, result.usage);
        const chunkResult: ChunkAnalysisResult = {
          filename: file.filename,
          model: options.model,
          index: hunkIndex + 1,
          total: file.hunks.length,
          lineRange,
          findings: result.findings,
          usage: result.usage,
          durationMs: hunkDurationMs,
          failed: result.failed && result.failureCode !== 'aborted',
          extractionFailed: result.extractionFailed,
          failureCode: result.failureCode,
          failureMessage: result.failureMessage,
          extractionError: result.extractionError,
          extractionPreview: result.extractionPreview,
          auxiliaryUsage: result.auxiliaryUsage,
        };
        callbacks?.onChunkComplete?.(chunkResult);
 
        fileFindings.push(...result.findings);
        fileUsage.push(result.usage);
        Iif (result.auxiliaryUsage) {
          fileAuxiliaryUsage.push(...result.auxiliaryUsage);
        }
      }
 
      span.setAttribute('warden.finding.count', fileFindings.length);
      span.setAttribute('warden.hunk.failed_count', failedHunks);
      span.setAttribute('warden.extraction.failed_count', failedExtractions);
 
      return {
        filename: file.filename,
        findings: fileFindings,
        usage: aggregateUsage(fileUsage),
        failedHunks,
        failedExtractions,
        hunkFailures,
        auxiliaryUsage: fileAuxiliaryUsage.length > 0 ? fileAuxiliaryUsage : undefined,
      };
    },
  );
}
 
/**
 * Generate a summary of findings.
 */
export function generateSummary(skillName: string, findings: Finding[]): string {
  if (findings.length === 0) {
    return `${skillName}: No issues found`;
  }
 
  const counts: Record<string, number> = {};
  for (const f of findings) {
    counts[f.severity] = (counts[f.severity] ?? 0) + 1;
  }
 
  const parts: string[] = [];
  if (counts['high']) parts.push(`${counts['high']} high`);
  if (counts['medium']) parts.push(`${counts['medium']} medium`);
  Iif (counts['low']) parts.push(`${counts['low']} low`);
 
  return `${skillName}: Found ${findings.length} issue${findings.length === 1 ? '' : 's'} (${parts.join(', ')})`;
}
 
/**
 * Run a skill on a PR, analyzing each hunk separately.
 */
export async function runSkill(
  skill: SkillDefinition,
  context: EventContext,
  options: SkillRunnerOptions = {}
): Promise<SkillReport> {
  return Sentry.startSpan(
    {
      op: 'skill.run',
      name: `run ${skill.name}`,
      attributes: {
        'gen_ai.agent.name': skill.name,
        ...(options.telemetryTriggerName ? { 'warden.trigger.name': options.telemetryTriggerName } : {}),
        'warden.file.count': context.pullRequest?.files.length ?? 0,
      },
    },
    async (span) => {
      try {
        const report = await runSkillAnalysis(skill, context, options);
        span.setAttribute('warden.finding.count', report.findings.length);
        emitSkillMetrics(report);
        return report;
      } catch (error) {
        span.setAttribute('warden.finding.count', 0);
        throw error;
      }
    },
  );
}
 
async function runSkillAnalysis(
  skill: SkillDefinition,
  context: EventContext,
  options: SkillRunnerOptions = {}
): Promise<SkillReport> {
  const { parallel = true, callbacks, abortController } = options;
  const startTime = Date.now();
 
  Iif (!context.pullRequest) {
    throw new SkillRunnerError('Pull request context required for skill execution');
  }
 
  const { files: fileHunks, skippedFiles } = prepareFiles(context, {
    contextLines: options.contextLines,
    // Note: chunking config should come from the caller (e.g., from warden.toml defaults)
    // For now, we use built-in defaults. The caller can pass explicit chunking config.
  });
 
  if (fileHunks.length === 0) {
    const report: SkillReport = {
      skill: skill.name,
      summary: 'No code changes to analyze',
      findings: [],
      usage: emptyUsage(),
      durationMs: Date.now() - startTime,
      model: options.model,
      runtime: options.runtime ?? 'pi',
    };
    Iif (skippedFiles.length > 0) {
      report.skippedFiles = skippedFiles;
    }
    return report;
  }
 
  const totalFiles = fileHunks.length;
  const totalHunks = fileHunks.reduce((sum, file) => sum + file.hunks.length, 0);
  const allFindings: Finding[] = [];
 
  // Track all usage stats for aggregation
  const allUsage: UsageStats[] = [];
  const allAuxiliaryUsage: AuxiliaryUsageEntry[] = [];
 
  // Track failed hunks across all files
  let totalFailedHunks = 0;
  let totalFailedExtractions = 0;
 
  // Build PR context for inclusion in prompts (helps LLM understand the full scope of changes)
  // For non-PR contexts (CLI file/diff mode), skip the "Other Files" list to avoid
  // bloating every hunk prompt with thousands of filenames.
  const isPullRequest = context.pullRequest.number !== 0;
  const prContext: PRPromptContext = {
    changedFiles: isPullRequest ? context.pullRequest.files.map((f) => f.filename) : [],
    title: context.pullRequest.title,
    body: context.pullRequest.body,
    maxContextFiles: options.maxContextFiles,
  };
 
  /**
   * Process all hunks for a single file sequentially.
   * Wraps analyzeFile with progress callbacks.
   */
  async function processFile(
    fileHunkEntry: PreparedFile,
    fileIndex: number
  ): Promise<FileAnalysisResult> {
    const { filename } = fileHunkEntry;
 
    callbacks?.onFileStart?.(filename, fileIndex, totalFiles);
 
    const fileCallbacks: FileAnalysisCallbacks = {
      skillStartTime: callbacks?.skillStartTime,
      onHunkStart: (hunkNum, totalHunks, lineRange) => {
        callbacks?.onHunkStart?.(filename, hunkNum, totalHunks, lineRange);
      },
      onHunkComplete: (hunkNum, findings, usage) => {
        callbacks?.onHunkComplete?.(filename, hunkNum, findings, usage);
      },
      onLargePrompt: callbacks?.onLargePrompt
        ? (lineRange, chars, estTokens) => {
            callbacks.onLargePrompt?.(filename, lineRange, chars, estTokens);
          }
        : undefined,
      onPromptSize: callbacks?.onPromptSize
        ? (lineRange, systemChars, userChars, totalCharsVal, estTokens) => {
            callbacks.onPromptSize?.(filename, lineRange, systemChars, userChars, totalCharsVal, estTokens);
          }
        : undefined,
      onRetry: callbacks?.onRetry
        ? (lineRange, attemptNum, maxRetries, error, delayMs) => {
            callbacks.onRetry?.(filename, lineRange, attemptNum, maxRetries, error, delayMs);
          }
        : undefined,
      onExtractionFailure: callbacks?.onExtractionFailure
        ? (lineRange, error, preview) => {
            callbacks.onExtractionFailure?.(filename, lineRange, error, preview);
          }
        : undefined,
      onExtractionResult: callbacks?.onExtractionResult
        ? (lineRange, findingsCount, method) => {
            callbacks.onExtractionResult?.(filename, lineRange, findingsCount, method);
          }
        : undefined,
      onHunkFailed: callbacks?.onHunkFailed
        ? (lineRange, error) => {
            callbacks.onHunkFailed?.(filename, lineRange, error);
          }
        : undefined,
    };
 
    const result = await analyzeFile(skill, fileHunkEntry, context.repoPath, options, fileCallbacks, prContext);
 
    callbacks?.onFileComplete?.(filename, fileIndex, totalFiles);
 
    return result;
  }
 
  /** Process a file with timing, returning a self-contained result. */
  async function processFileWithTiming(fileHunkEntry: PreparedFile, fileIndex: number) {
    const fileStart = Date.now();
    const result = await processFile(fileHunkEntry, fileIndex);
    const durationMs = Date.now() - fileStart;
    return { filename: fileHunkEntry.filename, result, durationMs };
  }
 
  // Collect results in input order (Promise.all preserves order)
  const fileResults: { filename: string; result: FileAnalysisResult; durationMs: number }[] = [];
 
  // Process files - parallel or sequential based on options
  if (parallel) {
    // Process files with sliding-window concurrency pool
    const fileConcurrency = options.concurrency ?? DEFAULT_FILE_CONCURRENCY;
    const batchDelayMs = options.batchDelayMs ?? 0;
 
    fileResults.push(...await runPool(fileHunks, fileConcurrency,
      async (fileHunkEntry, index) => {
        // Rate-limit: delay items beyond the first concurrent wave
        Iif (index >= fileConcurrency && batchDelayMs > 0) {
          await new Promise((resolve) => setTimeout(resolve, batchDelayMs));
        }
        return processFileWithTiming(fileHunkEntry, index);
      },
      { shouldAbort: () => abortController?.signal.aborted ?? false }
    ));
  } else E{
    // Process files sequentially
    for (const [fileIndex, fileHunkEntry] of fileHunks.entries()) {
      // Check for abort before starting new file
      if (abortController?.signal.aborted) break;
 
      fileResults.push(await processFileWithTiming(fileHunkEntry, fileIndex));
    }
  }
 
  // Accumulate results from ordered fileResults
  const allHunkFailures: HunkFailure[] = [];
  for (const fr of fileResults) {
    allFindings.push(...fr.result.findings);
    allUsage.push(fr.result.usage);
    totalFailedHunks += fr.result.failedHunks;
    totalFailedExtractions += fr.result.failedExtractions;
    if (fr.result.hunkFailures.length > 0) {
      allHunkFailures.push(...fr.result.hunkFailures);
    }
    Iif (fr.result.auxiliaryUsage) {
      allAuxiliaryUsage.push(...fr.result.auxiliaryUsage);
    }
  }
 
  // All hunks failed — typically a systemic problem (auth, subprocess, etc).
  // Throw so direct SDK consumers (evals, scheduled workflows) keep their
  // prior exception-based contract. The CLI path (tasks.ts) has its own
  // all-hunks-fail detection that emits a structured JSONL record instead.
  // Count both analysis and extraction failures: each hunk contributes to
  // at most one (analyzeFile makes them mutually exclusive), and an
  // extraction-only failure scenario would otherwise slip through silently.
  const totalAttemptFailures = totalFailedHunks + totalFailedExtractions;
  const circuitReason = options.circuitBreaker?.reason;
  Iif (circuitReason && totalAttemptFailures > 0 && allFindings.length === 0) {
    throw new SkillRunnerError(circuitReason.message, { code: circuitReason.code });
  }
  if (totalAttemptFailures > 0 && totalAttemptFailures === totalHunks && allFindings.length === 0) {
    const analysisFailures = allHunkFailures.filter((failure) => failure.type === 'analysis');
    Iif (
      analysisFailures.length > 0
      && analysisFailures.every((failure) => failure.code === 'invalid_model_selector')
    ) {
      throw new SkillRunnerError(
        analysisFailures[0]?.message ?? 'Invalid Pi model selector.',
        { code: 'invalid_model_selector' },
      );
    }
    Eif (
      analysisFailures.length > 0
      && analysisFailures.every((failure) => failure.code === 'provider_unavailable')
    ) {
      throw new SkillRunnerError(
        `Provider unavailable: all ${totalHunks} chunk${totalHunks === 1 ? '' : 's'} failed to analyze. Warden stopped early.`,
        { code: 'provider_unavailable' },
      );
    }
    throw new SkillRunnerError(
      `All ${totalHunks} chunk${totalHunks === 1 ? '' : 's'} failed to analyze. ` +
      `This usually indicates an authentication problem. ${allHunksFailedGuidance(options.runtime)}`,
      { code: 'all_hunks_failed' },
    );
  }
 
  const processed = await postProcessFindings(allFindings, {
    skill,
    repoPath: context.repoPath,
    apiKey: options.apiKey,
    runtime: options.runtime,
    auxiliaryModel: options.auxiliaryModel,
    synthesisModel: options.synthesisModel,
    auxiliaryMaxRetries: options.auxiliaryMaxRetries,
    verifyFindings: options.verifyFindings,
    maxTurns: options.maxTurns,
    abortController: options.abortController,
    pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable,
    prContext,
    onFindingProcessing: options.callbacks?.onFindingProcessing,
  });
  const finalFindings = processed.findings;
  allAuxiliaryUsage.push(...processed.auxiliaryUsage);
 
  // Generate summary
  const summary = generateSummary(skill.name, finalFindings);
 
  // Aggregate usage across all hunks
  const totalUsage = aggregateUsage(allUsage);
 
  const report: SkillReport = {
    skill: skill.name,
    summary,
    findings: finalFindings,
    usage: totalUsage,
    durationMs: Date.now() - startTime,
    model: options.model,
    files: buildFileReports(
      fileResults.map((fr) => ({
        filename: fr.filename,
        durationMs: fr.durationMs,
        usage: fr.result.usage,
      })),
      finalFindings,
    ),
  };
  report.runtime = options.runtime ?? 'pi';
  Iif (skippedFiles.length > 0) {
    report.skippedFiles = skippedFiles;
  }
  if (totalFailedHunks > 0) {
    report.failedHunks = totalFailedHunks;
  }
  Iif (totalFailedExtractions > 0) {
    report.failedExtractions = totalFailedExtractions;
  }
  if (allHunkFailures.length > 0) {
    report.hunkFailures = allHunkFailures;
  }
  const auxUsage = aggregateAuxiliaryUsage(allAuxiliaryUsage);
  if (auxUsage) {
    report.auxiliaryUsage = auxUsage;
  }
  return report;
}