All files / src/action/workflow pr-workflow.ts

86% Statements 252/293
78.06% Branches 121/155
91.89% Functions 34/37
85.61% Lines 238/278

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                                                                                                                                                                                                33x 33x   33x                                                                                                           36x 36x   1x 1x     35x 35x 35x 35x     35x 35x         35x   35x 35x 6x   35x 4x   35x 35x     35x   35x 35x               35x       36x 36x 36x 36x   36x 25x 25x 28x   25x   7x     32x   3x         1x 1x   2x                       28x       28x 28x   28x                 28x             28x                           25x         25x     25x 25x         25x 25x           25x   25x 4x     25x                         25x 28x 25x 1x   24x   25x 25x 25x     25x     27x                             27x                               24x 24x 24x 24x 24x           24x 24x 6x 6x 6x                     24x 24x 24x 24x   24x 27x 26x     26x                         26x 26x       26x 26x 26x 1x 1x 1x         24x                                                         27x 27x 27x 27x 27x 10x   27x 27x           27x           8x 8x 8x 8x 7x     8x                             8x         8x 1x 1x 1x     1x       2x 1x 1x 1x 1x             2x 2x 2x 2x     2x             2x   6x 6x 6x           27x 10x 10x 10x   10x       10x   10x 5x 5x 5x 5x   5x 5x 5x 5x 5x       5x       5x           17x         27x 27x 10x     27x                                               23x 26x 2x 2x   26x 23x             1x 1x             1x               23x 23x     23x 23x 23x           23x 23x 23x 23x   23x                   23x 1x     22x                               7x         7x 7x                     7x 7x 2x     5x 1x     4x     4x     4x 4x 7x     7x 3x 3x 1x 1x             1x                                     36x     36x   36x     33x 1x 1x 1x 1x 1x 1x 1x             1x     32x 32x     32x 32x   32x       32x 32x             32x   32x 32x         32x 7x           6x 6x 6x 6x 6x     25x   25x     25x           25x     24x   24x     24x 24x   24x 26x 24x   24x     23x           23x       23x             23x                  
/**
 * PR Workflow
 *
 * Handles pull_request and push events.
 */
 
import { readFileSync } from 'node:fs';
import type { Octokit } from '@octokit/rest';
import { Sentry, logger, emitStaleResolutionMetric, setRepositoryScope, emitRunMetric } from '../../sentry.js';
import {
  buildSkillRootsByName,
  loadLayeredWardenConfig,
  resolveLayeredSkillConfigs,
  ConfigLoadError,
  emptyToUndefined,
} from '../../config/loader.js';
import type {
  LayeredSkillRootsByName,
  LoadedLayeredConfig,
  ResolvedTrigger,
} from '../../config/loader.js';
import { buildEventContext } from '../../event/context.js';
import { matchTrigger, shouldFail, countFindingsAtOrAbove } from '../../triggers/matcher.js';
import { fetchExistingComments } from '../../output/dedup.js';
import type { ExistingComment } from '../../output/dedup.js';
import { buildAnalyzedScope, findStaleComments, resolveStaleComments } from '../../output/stale.js';
import { filterFindings } from '../../types/index.js';
import type { EventContext, SkillReport, Finding } from '../../types/index.js';
import { runPool, Semaphore } from '../../utils/index.js';
import { evaluateFixAttempts, postThreadReply } from '../fix-evaluation/index.js';
import type { FixEvaluation } from '../fix-evaluation/index.js';
import { logAction, warnAction } from '../../cli/output/tty.js';
import { formatCost, formatTokens, formatDuration } from '../../cli/output/formatters.js';
import { findBotReviewState } from '../review-state.js';
import type { BotReviewInfo } from '../review-state.js';
import type { ActionInputs } from '../inputs.js';
import { executeTrigger } from '../triggers/executor.js';
import type { TriggerResult } from '../triggers/executor.js';
import { postTriggerReview } from '../review/poster.js';
import { shouldResolveStaleComments } from '../review/coordination.js';
import type { RuntimeName } from '../../sdk/runtimes/index.js';
import { canUseRuntimeAuth } from '../../sdk/extract.js';
import { ProviderFailureCircuitBreaker } from '../../sdk/circuit-breaker.js';
import {
  createCoreCheck,
  updateCoreCheck,
  buildCoreSummaryData,
  determineCoreConclusion,
} from '../checks/manager.js';
import {
  setOutput,
  setFailed,
  ensureClaudeAuth,
  logGroup,
  logGroupEnd,
  findClaudeCodeExecutable,
  handleTriggerErrors,
  collectTriggerErrors,
  computeWorkflowOutputs,
  setWorkflowOutputs,
  getAuthenticatedBotLogin,
  writeFindingsOutput,
} from './base.js';
 
// -----------------------------------------------------------------------------
// Phase Result Types
// -----------------------------------------------------------------------------
 
interface InitResult {
  context: EventContext;
  runnerConcurrency?: number;
  auxiliaryOptions: AuxiliaryWorkflowOptions;
  matchedTriggers: ResolvedTrigger[];
}
 
interface GitHubSetupResult {
  coreCheckId?: number;
  previousReviewInfo: BotReviewInfo | null;
}
 
interface ReviewPhaseResult {
  reports: SkillReport[];
  fetchedComments: ExistingComment[];
  existingComments: ExistingComment[];
  activeWardenCommentIds: Set<number>;
  shouldFailAction: boolean;
  failureReasons: string[];
}
 
interface AuxiliaryWorkflowOptions {
  runtime?: RuntimeName;
  model?: string;
  maxRetries?: number;
}
 
function resolveWorkflowAuxiliaryOptions(layered: LoadedLayeredConfig): AuxiliaryWorkflowOptions {
  const baseDefaults = layered.baseConfig?.defaults;
  const repoDefaults = layered.repoConfig?.defaults ?? layered.config.defaults;
 
  return {
    // These workflow-scoped auxiliary calls are not tied to an individual
    // trigger, so the org base config remains the enforced baseline and the
    // repo layer only fills fields the base omits.
    runtime: baseDefaults?.runtime ?? repoDefaults?.runtime ?? 'pi',
    model:
      emptyToUndefined(baseDefaults?.auxiliary?.model) ??
      emptyToUndefined(repoDefaults?.auxiliary?.model),
    maxRetries:
      baseDefaults?.auxiliary?.maxRetries ??
      baseDefaults?.auxiliaryMaxRetries ??
      repoDefaults?.auxiliary?.maxRetries ??
      repoDefaults?.auxiliaryMaxRetries,
  };
}
 
// -----------------------------------------------------------------------------
// Fix Evaluation Logging
// -----------------------------------------------------------------------------
 
function logFixEvaluation(ev: FixEvaluation, index: number, total: number): void {
  const totalTokens = ev.usage.inputTokens + ev.usage.outputTokens;
  const costStr = ev.usage.costUSD > 0 ? `, ${formatCost(ev.usage.costUSD)}` : '';
  const idPrefix = ev.findingId ? `${ev.findingId} ` : '';
  const verdict = ev.verdict;
 
  const line = `  [${index + 1}/${total}] ${idPrefix}${ev.path}:${ev.line} → ${verdict} (${formatDuration(ev.durationMs)}, ${formatTokens(totalTokens)} tok${costStr})`;
 
  if (ev.usedFallback) {
    warnAction(line);
  } else {
    logAction(line);
  }
 
  if (ev.verdict === 'attempted_failed' && ev.reasoning) {
    logAction(`        reason: "${ev.reasoning}"`);
  }
}
 
// -----------------------------------------------------------------------------
// Phase Functions
// -----------------------------------------------------------------------------
 
/**
 * Parse event payload, build context, load config, match triggers.
 */
async function initializeWorkflow(
  octokit: Octokit,
  inputs: ActionInputs,
  eventName: string,
  eventPath: string,
  repoPath: string
): Promise<InitResult | null> {
  let eventPayload: unknown;
  try {
    eventPayload = JSON.parse(readFileSync(eventPath, 'utf-8'));
  } catch (error) {
    Sentry.captureException(error, { tags: { operation: 'read_event_payload' } });
    setFailed(`Failed to read event payload: ${error}`);
  }
 
  logGroup('Building event context');
  console.log(`Event: ${eventName}`);
  console.log(`Workspace: ${repoPath}`);
  logGroupEnd();
 
  let context: EventContext;
  try {
    context = await buildEventContext(eventName, eventPayload, repoPath, octokit);
  } catch (error) {
    Sentry.captureException(error, { tags: { operation: 'build_event_context' } });
    setFailed(`Failed to build event context: ${error}`);
  }
  setRepositoryScope(context.repository.fullName);
 
  logGroup('Loading configuration');
  if (inputs.baseConfigPath) {
    console.log(`Base config path: ${inputs.baseConfigPath}`);
  }
  if (inputs.baseSkillRoot) {
    console.log(`Base skill root: ${inputs.baseSkillRoot}`);
  }
  console.log(`Repo config path: ${inputs.configPath}`);
  logGroupEnd();
 
  let runnerConcurrency: number | undefined;
  let auxiliaryOptions: AuxiliaryWorkflowOptions = { runtime: 'pi' };
  let skillRootsByName: LayeredSkillRootsByName | undefined;
  try {
    const layered = loadLayeredWardenConfig(repoPath, {
      baseConfigPath: inputs.baseConfigPath,
      configPath: inputs.configPath,
      onWarning: (message) => console.log(`::warning::${message}`),
    });
    // The org base config is an enforced baseline. Repo config extends the run
    // with additional repo-local triggers, but does not override these
    // action-level settings for the global workflow.
    runnerConcurrency =
      layered.baseConfig?.runner?.concurrency ??
      layered.repoConfig?.runner?.concurrency ??
      layered.config.runner?.concurrency;
    auxiliaryOptions = resolveWorkflowAuxiliaryOptions(layered);
    skillRootsByName = buildSkillRootsByName(repoPath, layered, inputs.baseSkillRoot);
    const resolvedTriggers = resolveLayeredSkillConfigs(layered, undefined, skillRootsByName);
    const matchedTriggers = resolvedTriggers.filter((t) => matchTrigger(t, context, 'github'));
 
    if (matchedTriggers.length > 0) {
      logGroup('Matched triggers');
      for (const trigger of matchedTriggers) {
        console.log(`- ${trigger.name}: ${trigger.skill}`);
      }
      logGroupEnd();
    } else {
      console.log('No triggers matched for this event');
    }
 
    return { context, runnerConcurrency, auxiliaryOptions, matchedTriggers };
  } catch (error) {
    if (
      error instanceof ConfigLoadError &&
      error.message.includes('not found') &&
      !inputs.baseConfigPath
    ) {
      console.log('::warning::No warden.toml found. Skipping analysis.');
      return null;
    }
    throw error;
  }
}
 
/**
 * Fetch the bot's previous review state on a PR.
 * Returns null if the bot has no actionable reviews or identity cannot be determined.
 */
async function fetchPreviousReviewInfo(
  octokit: Octokit,
  context: EventContext
): Promise<BotReviewInfo | null> {
  Iif (!context.pullRequest) {
    return null;
  }
 
  try {
    const botLogin = await getAuthenticatedBotLogin(octokit);
 
    Iif (!botLogin) {
      logAction(
        'Skipping dismiss flow: cannot identify bot (using PAT or GITHUB_TOKEN instead of GitHub App)'
      );
      return null;
    }
 
    // Note: No pagination. PRs with 100+ reviews are rare; if Warden's review
    // is beyond page 1, user can manually dismiss. Not worth the complexity.
    const { data: reviews } = await octokit.pulls.listReviews({
      owner: context.repository.owner,
      repo: context.repository.name,
      pull_number: context.pullRequest.number,
      per_page: 100,
    });
 
    return findBotReviewState(reviews, botLogin);
  } catch (error) {
    warnAction(`Failed to fetch previous review info: ${error}`);
    return null;
  }
}
 
/**
 * Create core check and fetch previous review info. PR-only.
 */
async function setupGitHubState(
  octokit: Octokit,
  context: EventContext
): Promise<GitHubSetupResult> {
  Iif (!context.pullRequest) {
    return { previousReviewInfo: null };
  }
 
  let coreCheckId: number | undefined;
  let previousReviewInfo: BotReviewInfo | null = null;
 
  // Create core warden check
  try {
    const coreCheck = await createCoreCheck(octokit, {
      owner: context.repository.owner,
      repo: context.repository.name,
      headSha: context.pullRequest.headSha,
    });
    coreCheckId = coreCheck.checkRunId;
    logAction(`Created core check: ${coreCheck.url}`);
  } catch (error) {
    Sentry.captureException(error, { tags: { operation: 'create_core_check' } });
    warnAction(`Failed to create core check: ${error}`);
  }
 
  previousReviewInfo = await fetchPreviousReviewInfo(octokit, context);
 
  if (previousReviewInfo) {
    logAction(`Previous Warden review state: ${previousReviewInfo.state}`);
  }
 
  return { coreCheckId, previousReviewInfo };
}
 
/**
 * Run all matched triggers in parallel batches.
 */
async function executeAllTriggers(
  matchedTriggers: ResolvedTrigger[],
  octokit: Octokit,
  context: EventContext,
  runnerConcurrency: number | undefined,
  inputs: ActionInputs
): Promise<TriggerResult[]> {
  const concurrency = runnerConcurrency ?? inputs.parallel;
  const usesClaudeRuntime = matchedTriggers.some((trigger) => (trigger.runtime ?? 'pi') === 'claude');
  if (usesClaudeRuntime) {
    ensureClaudeAuth(inputs);
  }
  const claudePath = usesClaudeRuntime ? await findClaudeCodeExecutable() : undefined;
 
  const semaphore = new Semaphore(concurrency);
  const abortController = new AbortController();
  const circuitBreaker = new ProviderFailureCircuitBreaker({ abortController });
 
  // Limit trigger dispatch too; the semaphore only gates work after a trigger starts.
  return runPool(
    matchedTriggers,
    concurrency,
    (trigger) =>
      executeTrigger(trigger, {
        octokit,
        context,
        anthropicApiKey: inputs.anthropicApiKey,
        claudePath,
        globalFailOn: inputs.failOn,
        globalReportOn: inputs.reportOn,
        globalMaxFindings: inputs.maxFindings,
        globalRequestChanges: inputs.requestChanges,
        globalFailCheck: inputs.failCheck,
        semaphore,
        abortController,
        circuitBreaker,
      }),
    { shouldAbort: () => abortController.signal.aborted },
  );
}
 
/**
 * Fetch existing comments, post reviews with cross-trigger dedup, accumulate failure state.
 */
async function postReviewsAndTrackFailures(
  octokit: Octokit,
  context: EventContext,
  results: TriggerResult[],
  inputs: ActionInputs,
  auxiliaryOptions: AuxiliaryWorkflowOptions
): Promise<ReviewPhaseResult> {
  // Fetch existing comments for deduplication (only for PRs)
  // Keep original list separate for stale detection (modified list includes newly posted comments)
  let fetchedComments: ExistingComment[] = [];
  let existingComments: ExistingComment[] = [];
  Eif (context.pullRequest) {
    try {
      fetchedComments = await fetchExistingComments(
        octokit,
        context.repository.owner,
        context.repository.name,
        context.pullRequest.number
      );
      existingComments = [...fetchedComments];
      if (fetchedComments.length > 0) {
        const wardenCount = fetchedComments.filter((c) => c.isWarden).length;
        const externalCount = fetchedComments.length - wardenCount;
        logAction(
          `Found ${fetchedComments.length} existing comments for deduplication (${wardenCount} Warden, ${externalCount} external)`
        );
      }
    } catch (error) {
      Sentry.captureException(error, { tags: { operation: 'fetch_existing_comments' } });
      warnAction(`Failed to fetch existing comments for deduplication: ${error}`);
    }
  }
 
  // Post reviews to GitHub (sequentially to avoid rate limits)
  const reports: SkillReport[] = [];
  const activeWardenCommentIds = new Set<number>();
  let shouldFailAction = false;
  const failureReasons: string[] = [];
 
  for (const result of results) {
    if (result.report) {
      reports.push(result.report);
 
      // Post review
      const postResult = await postTriggerReview(
        {
          result,
          existingComments,
          apiKey: inputs.anthropicApiKey,
          runtime: auxiliaryOptions.runtime,
          model: auxiliaryOptions.model,
          maxRetries: auxiliaryOptions.maxRetries,
        },
        { octokit, context }
      );
 
      // Add newly posted comments to existing comments for cross-trigger deduplication
      existingComments.push(...postResult.newComments);
      postResult.activeWardenCommentIds.forEach((id) => activeWardenCommentIds.add(id));
 
      // Check if we should fail based on this trigger's config
      // Filter by confidence first so low-confidence findings don't cause failure
      const failCheck = result.failCheck ?? false;
      const reportForFail = { ...result.report, findings: filterFindings(result.report.findings, undefined, result.minConfidence) };
      if (failCheck && result.failOn && shouldFail(reportForFail, result.failOn)) {
        shouldFailAction = true;
        const count = countFindingsAtOrAbove(reportForFail, result.failOn);
        failureReasons.push(`${result.triggerName}: Found ${count} ${result.failOn}+ severity issues`);
      }
    }
  }
 
  return {
    reports,
    fetchedComments,
    existingComments,
    activeWardenCommentIds,
    shouldFailAction,
    failureReasons,
  };
}
 
/**
 * Evaluate fix attempts on unresolved comments and resolve stale comments.
 *
 * Returns whether all Warden comments are resolved after evaluation.
 */
async function evaluateFixesAndResolveStale(
  octokit: Octokit,
  context: EventContext,
  fetchedComments: ExistingComment[],
  allFindings: Finding[],
  activeWardenCommentIds: ReadonlySet<number>,
  canResolveStale: boolean,
  anthropicApiKey: string,
  auxiliaryOptions: AuxiliaryWorkflowOptions
): Promise<{
  allResolved: boolean;
  autoResolvedByFixEvaluation: number;
  autoResolvedByStaleCheck: number;
}> {
  const wardenComments = fetchedComments.filter((c) => c.isWarden);
  const commentsResolvedByFixEval = new Set<number>();
  const commentsEvaluatedByFixEval = new Set<number>();
  const commentsResolvedByStale = new Set<number>();
  const commentsForFixEvaluation = wardenComments.filter(
    (c) => !activeWardenCommentIds.has(c.id)
  );
  const fixEvaluationRuntime = auxiliaryOptions.runtime ?? 'pi';
  const canUseFixEvaluationRuntime = canUseRuntimeAuth({
    apiKey: anthropicApiKey,
    runtime: fixEvaluationRuntime,
  });
 
  // Evaluate follow-up commit fix attempts
  if (
    context.pullRequest &&
    commentsForFixEvaluation.length > 0 &&
    canResolveStale &&
    canUseFixEvaluationRuntime
  ) {
    try {
      logGroup('Fix evaluation');
      const unresolvedCount = commentsForFixEvaluation.filter((c) => !c.isResolved && c.threadId).length;
      if (unresolvedCount > 0) {
        logAction(`Fix evaluation: evaluating ${unresolvedCount} unresolved comments`);
      }
 
      const fixEvaluation = await evaluateFixAttempts(
        octokit,
        commentsForFixEvaluation,
        {
          owner: context.repository.owner,
          repo: context.repository.name,
          baseSha: context.pullRequest.baseSha,
          headSha: context.pullRequest.headSha,
        },
        allFindings,
        anthropicApiKey,
        { ...auxiliaryOptions, runtime: fixEvaluationRuntime }
      );
 
      // Log per-evaluation details
      fixEvaluation.evaluations.forEach((ev, i) =>
        logFixEvaluation(ev, i, fixEvaluation.evaluations.length)
      );
 
      // Resolve successful fixes
      if (fixEvaluation.toResolve.length > 0) {
        const { resolvedCount, resolvedIds } = await resolveStaleComments(octokit, fixEvaluation.toResolve);
        Eif (resolvedCount > 0) {
          logAction(`Resolved ${resolvedCount} comments via fix evaluation`);
        }
        // Track only actually resolved comments for allResolved check
        resolvedIds.forEach((id) => commentsResolvedByFixEval.add(id));
      }
 
      // Post replies for failed fixes and track them so stale pass doesn't override
      for (const reply of fixEvaluation.toReply) {
        commentsEvaluatedByFixEval.add(reply.comment.id);
        Eif (reply.comment.threadId) {
          try {
            await postThreadReply(octokit, reply.comment.threadId, reply.replyBody);
          } catch (error) {
            Sentry.captureException(error, { tags: { operation: 'post_thread_reply' } });
          }
        }
      }
 
      Eif (fixEvaluation.evaluated > 0) {
        const totalTokens = fixEvaluation.usage.inputTokens + fixEvaluation.usage.outputTokens;
        let usageStr = '';
        Iif (totalTokens > 0) {
          usageStr = `, ${formatTokens(totalTokens)} tok, ${formatCost(fixEvaluation.usage.costUSD)}`;
        }
        logAction(
          `Fix evaluation: ${fixEvaluation.toResolve.length} resolved, ` +
            `${fixEvaluation.toReply.length} need attention, ` +
            `${fixEvaluation.skipped} skipped` +
            usageStr
        );
      }
      logGroupEnd();
    } catch (error) {
      Sentry.captureException(error, { tags: { operation: 'evaluate_fix_attempts' } });
      warnAction(`Failed to evaluate fix attempts: ${error}`);
      logGroupEnd();
    }
  }
 
  // Resolve stale Warden comments (comments that no longer have matching findings)
  // Exclude comments already handled by fix evaluation (resolved or flagged as needing attention)
  if (context.pullRequest && wardenComments.length > 0 && canResolveStale) {
    try {
      const scope = buildAnalyzedScope(context.pullRequest.files);
      const commentsForStaleCheck = wardenComments.filter(
        (c) =>
          !activeWardenCommentIds.has(c.id) &&
          !commentsResolvedByFixEval.has(c.id) &&
          !commentsEvaluatedByFixEval.has(c.id)
      );
      const staleComments = findStaleComments(commentsForStaleCheck, allFindings, scope);
 
      if (staleComments.length > 0) {
        const { resolvedCount, resolvedIds } = await resolveStaleComments(octokit, staleComments);
        Eif (resolvedCount > 0) {
          logAction(`Resolved ${resolvedCount} stale Warden comments`);
          emitStaleResolutionMetric(resolvedCount);
          // Emit per-skill breakdown (only count actually resolved comments)
          const bySkill = new Map<string, number>();
          for (const c of staleComments) {
            Iif (!resolvedIds.has(c.id)) continue;
            const skill = c.skills?.[0];
            Iif (skill) {
              bySkill.set(skill, (bySkill.get(skill) ?? 0) + 1);
            }
          }
          for (const [skill, count] of bySkill) {
            emitStaleResolutionMetric(count, skill);
          }
        }
        resolvedIds.forEach((id) => commentsResolvedByStale.add(id));
      }
    } catch (error) {
      Sentry.captureException(error, { tags: { operation: 'resolve_stale_comments' } });
      warnAction(`Failed to resolve stale comments: ${error}`);
    }
  I} else if (!canResolveStale && wardenComments.length > 0) {
    logAction('Skipping stale comment resolution due to trigger failures');
  }
 
  // Determine if all unresolved Warden comments were resolved during this run
  const unresolvedBefore = wardenComments.filter((c) => !c.isResolved);
  const allResolved = unresolvedBefore.every(
    (c) => commentsResolvedByFixEval.has(c.id) || commentsResolvedByStale.has(c.id)
  );
 
  return {
    allResolved,
    autoResolvedByFixEvaluation: commentsResolvedByFixEval.size,
    autoResolvedByStaleCheck: commentsResolvedByStale.size,
  };
}
 
/**
 * Dismiss review, set outputs, update core check, fail action.
 */
async function finalizeWorkflow(
  octokit: Octokit,
  context: EventContext,
  previousReviewInfo: BotReviewInfo | null,
  coreCheckId: number | undefined,
  results: TriggerResult[],
  reports: SkillReport[],
  shouldFailAction: boolean,
  failureReasons: string[],
  canResolveStale: boolean
): Promise<void> {
  // Dismiss previous CHANGES_REQUESTED if all blocking issues are resolved.
  // Requires: all triggers succeeded, current run would not request changes,
  // and at least one trigger has an active failOn (prevents accidental dismiss when config changes).
  const wouldRequestChanges = results.some((r) => {
    if (!r.failOn || r.failOn === 'off' || !(r.requestChanges ?? false) || !r.report) return false;
    const filtered = { ...r.report, findings: filterFindings(r.report.findings, undefined, r.minConfidence) };
    return shouldFail(filtered, r.failOn);
  });
  const hasActiveFailOn = results.some((r) => r.failOn && r.failOn !== 'off');
  if (
    context.pullRequest &&
    previousReviewInfo?.state === 'CHANGES_REQUESTED' &&
    canResolveStale &&
    !wouldRequestChanges &&
    hasActiveFailOn
  ) {
    try {
      await octokit.pulls.dismissReview({
        owner: context.repository.owner,
        repo: context.repository.name,
        pull_number: context.pullRequest.number,
        review_id: previousReviewInfo.reviewId,
        message: 'All previously reported issues have been resolved.',
      });
      logAction('Dismissed previous CHANGES_REQUESTED review');
    } catch (error) {
      Sentry.captureException(error, { tags: { operation: 'dismiss_review' } });
      warnAction(`Failed to dismiss previous review: ${error}`);
    }
  }
 
  // Set outputs
  const outputs = computeWorkflowOutputs(reports);
  setWorkflowOutputs(outputs);
 
  // Write structured findings to file for external export (GCS, S3, etc.)
  try {
    const findingsPath = writeFindingsOutput(reports, context);
    logAction(`Findings written to ${findingsPath}`);
  } catch (error) {
    warnAction(`Failed to write findings output: ${error}`);
  }
 
  // Update core check with overall summary
  Eif (coreCheckId && context.pullRequest) {
    try {
      const summaryData = buildCoreSummaryData(results, reports);
      const coreConclusion = determineCoreConclusion(shouldFailAction, outputs.findingsCount);
 
      await updateCoreCheck(octokit, coreCheckId, summaryData, coreConclusion, {
        owner: context.repository.owner,
        repo: context.repository.name,
      });
    } catch (error) {
      Sentry.captureException(error, { tags: { operation: 'update_core_check' } });
      warnAction(`Failed to update core check: ${error}`);
    }
  }
 
  if (shouldFailAction) {
    setFailed(failureReasons.join('; '));
  }
 
  logAction(`Analysis complete: ${outputs.findingsCount} total findings`);
}
 
/**
 * Clean up orphaned Warden comments when no triggers matched.
 *
 * Runs fix evaluation and stale resolution on existing comments so that
 * comments from earlier pushes get resolved even when the current push
 * only touches files outside all skills' paths filters.
 */
async function cleanupOrphanedComments(
  octokit: Octokit,
  context: EventContext,
  inputs: ActionInputs,
  auxiliaryOptions: AuxiliaryWorkflowOptions
): Promise<void> {
  Iif (!context.pullRequest) {
    return;
  }
 
  let existingComments: ExistingComment[];
  try {
    existingComments = await fetchExistingComments(
      octokit,
      context.repository.owner,
      context.repository.name,
      context.pullRequest.number
    );
  } catch (error) {
    warnAction(`Failed to fetch existing comments for cleanup: ${error}`);
    return;
  }
 
  const wardenComments = existingComments.filter((c) => c.isWarden);
  if (wardenComments.length === 0) {
    return;
  }
 
  if ((auxiliaryOptions.runtime ?? 'pi') === 'claude') {
    ensureClaudeAuth(inputs);
  }
 
  logAction(`No triggers matched, but found ${wardenComments.length} existing Warden comments. Running cleanup.`);
 
  const { allResolved, autoResolvedByFixEvaluation, autoResolvedByStaleCheck } =
    await evaluateFixesAndResolveStale(
      octokit, context, existingComments, [], new Set(), true, inputs.anthropicApiKey, auxiliaryOptions
    );
  const activeSpan = Sentry.getActiveSpan();
  activeSpan?.setAttribute('warden.feedback.auto_resolve.fix_eval_count', autoResolvedByFixEvaluation);
  activeSpan?.setAttribute('warden.feedback.auto_resolve.stale_count', autoResolvedByStaleCheck);
 
  // Dismiss CHANGES_REQUESTED only if every unresolved comment was resolved
  if (allResolved) {
    const previousReviewInfo = await fetchPreviousReviewInfo(octokit, context);
    if (previousReviewInfo?.state === 'CHANGES_REQUESTED') {
      try {
        await octokit.pulls.dismissReview({
          owner: context.repository.owner,
          repo: context.repository.name,
          pull_number: context.pullRequest.number,
          review_id: previousReviewInfo.reviewId,
          message: 'All previously reported issues have been resolved.',
        });
        logAction('Dismissed previous CHANGES_REQUESTED review');
      } catch (error) {
        warnAction(`Failed to dismiss previous review: ${error}`);
      }
    }
  }
}
 
// -----------------------------------------------------------------------------
// Main PR Workflow
// -----------------------------------------------------------------------------
 
export async function runPRWorkflow(
  octokit: Octokit,
  inputs: ActionInputs,
  eventName: string,
  eventPath: string,
  repoPath: string
): Promise<void> {
  return Sentry.startSpan(
    { op: 'workflow.run', name: 'review pull_request' },
    async (span) => {
      const initResult = await Sentry.startSpan(
        { op: 'workflow.init', name: 'initialize workflow' },
        () => initializeWorkflow(octokit, inputs, eventName, eventPath, repoPath),
      );
 
      if (!initResult) {
        setOutput('findings-count', 0);
        setOutput('high-count', 0);
        setOutput('summary', 'No warden.toml found');
        try {
          const fullName = process.env['GITHUB_REPOSITORY'] ?? '';
          const [o = '', n = ''] = fullName.split('/');
          writeFindingsOutput([], {
            eventType: 'pull_request',
            action: '',
            repository: { owner: o, name: n, fullName, defaultBranch: '' },
            repoPath,
          });
        } catch { /* non-fatal */ }
        return;
      }
 
      const { context, runnerConcurrency, auxiliaryOptions, matchedTriggers } = initResult;
      span.setAttribute('warden.trigger.count', matchedTriggers.length);
 
      // Set Sentry context after building event context
      Eif (context.pullRequest) {
        Sentry.setUser({ username: context.pullRequest.author });
      }
      Sentry.setContext('repository', {
        owner: context.repository.owner,
        name: context.repository.name,
      });
      Eif (context.pullRequest) {
        Sentry.setContext('pull_request', {
          number: context.pullRequest.number,
          baseBranch: context.pullRequest.baseBranch,
          headBranch: context.pullRequest.headBranch,
        });
      }
 
      emitRunMetric();
 
      const traceId = span.spanContext().traceId;
      logger.info('Workflow initialized', {
        'warden.trigger.count': matchedTriggers.length,
        'trace.id': traceId,
      });
 
      if (matchedTriggers.length === 0) {
        await cleanupOrphanedComments(
          octokit,
          context,
          inputs,
          auxiliaryOptions
        );
        setOutput('findings-count', 0);
        setOutput('high-count', 0);
        setOutput('summary', 'No triggers matched');
        try { writeFindingsOutput([], context); } catch { /* non-fatal */ }
        return;
      }
 
      const { coreCheckId, previousReviewInfo } = await Sentry.startSpan(
        { op: 'workflow.setup', name: 'setup github state' },
        () => setupGitHubState(octokit, context),
      );
 
      const results = await Sentry.startSpan(
        {
          op: 'workflow.execute',
          name: 'execute triggers',
          attributes: { 'warden.trigger.count': matchedTriggers.length },
        },
        () => executeAllTriggers(matchedTriggers, octokit, context, runnerConcurrency, inputs),
      );
 
      const reviewPhase = await Sentry.startSpan(
        { op: 'workflow.review', name: 'post reviews' },
        () => postReviewsAndTrackFailures(octokit, context, results, inputs, auxiliaryOptions),
      );
 
      const triggerErrors = collectTriggerErrors(results);
      handleTriggerErrors(triggerErrors, matchedTriggers.length);
 
      const canResolveStale = shouldResolveStaleComments(results);
      const allFindings = reviewPhase.reports.flatMap((r) => r.findings);
      span.setAttribute('warden.finding.count', allFindings.length);
 
      await Sentry.startSpan(
        { op: 'workflow.resolve', name: 'resolve stale comments' },
        async (resolveSpan) => {
          const resolutionResult = await evaluateFixesAndResolveStale(
            octokit, context, reviewPhase.fetchedComments,
            allFindings, reviewPhase.activeWardenCommentIds,
            canResolveStale, inputs.anthropicApiKey,
            auxiliaryOptions,
          );
          resolveSpan.setAttribute(
            'warden.feedback.auto_resolve.fix_eval_count',
            resolutionResult.autoResolvedByFixEvaluation
          );
          resolveSpan.setAttribute(
            'warden.feedback.auto_resolve.stale_count',
            resolutionResult.autoResolvedByStaleCheck
          );
        },
      );
 
      await finalizeWorkflow(
        octokit, context, previousReviewInfo, coreCheckId,
        results, reviewPhase.reports,
        reviewPhase.shouldFailAction, reviewPhase.failureReasons,
        canResolveStale,
      );
    },
  );
}