All files / src/output dedup.ts

72.31% Statements 209/289
63.13% Branches 125/198
77.5% Functions 31/40
71.95% Lines 195/271

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                                                                                                                                                                    128x 128x               62x               6x 6x 2x     4x 4x 4x     4x       4x                             6x 6x 1x       5x     5x 5x 5x   6x   6x             5x 5x 3x 3x 3x     2x 2x                       8x                 6x   9x                             35x 35x 6x 6x       29x 29x 7x 11x 11x 7x       22x 22x 7x 11x 11x 7x       15x 15x 8x 12x 12x 8x       7x 7x 1x   6x   10x                                   17x     17x         17x 5x       12x 12x 1x 1x 1x 1x   1x         11x 17x 4x 3x 3x 3x   3x         8x 8x 4x 3x 3x 3x   3x         5x 5x 4x   3x 3x 3x 3x 3x   3x         2x   2x                                                                 5x                                                                             1x     1x 1x   1x 1x             1x 1x         1x   1x   1x 1x       1x 1x 1x       1x 1x   1x                                 1x 1x     1x                                 5x                                                                                                                                                                                                   5x                                                                                                                                                                                                   10x 1x     9x                                 5x                       5x                   7x 7x 12x 12x 12x 4x   8x       7x   7x 8x     4x       4x 4x 4x   4x 4x 4x 4x   4x 2x   2x 2x     4x     7x                                 9x 2x       7x 7x   7x 14x 14x 14x 14x   14x 12x 12x     7x   7x 2x       7x     7x 7x                                                                                                                                                   8x 3x       5x 5x 5x 6x 6x 6x 3x         5x 5x   5x 7x 7x 7x 7x   7x         7x 2x 2x 2x 2x 2x 1x 1x         7x 4x             3x       5x 3x       5x 5x                                                      
import { createHash } from 'node:crypto';
import type { Octokit } from '@octokit/rest';
import { z } from 'zod';
import type { Finding, UsageStats } from '../types/index.js';
import { findingLine } from '../types/index.js';
import { getRuntime } from '../sdk/runtimes/index.js';
import { applyMergeGroups, canUseRuntimeAuth } from '../sdk/extract.js';
import type { AuxiliaryCallOptions } from '../sdk/extract.js';
import {
  buildJsonOutputSection,
  formatIndexedFindingsForPrompt,
  joinPromptSections,
} from '../sdk/prompt-sections.js';
 
/**
 * Parsed marker data from a Warden comment.
 */
export interface WardenMarker {
  path: string;
  line: number;
  contentHash: string;
}
 
/**
 * Existing comment from GitHub (either Warden or external).
 */
export interface ExistingComment {
  id: number;
  path: string;
  line: number;
  title: string;
  description: string;
  /** Stable Warden finding ID from the attribution footer or legacy title prefix */
  findingId?: string;
  contentHash: string;
  /** GraphQL node ID for the review thread (used to resolve stale comments) */
  threadId?: string;
  /** Whether the thread has been resolved (resolved comments are used for dedup but not stale detection) */
  isResolved?: boolean;
  /** Whether this is a Warden-generated comment */
  isWarden?: boolean;
  /** Skills that have already detected this issue (for Warden comments) */
  skills?: string[];
  /** The raw comment body (needed for updating Warden comments) */
  body?: string;
  /** GraphQL node ID for the comment (needed for adding reactions) */
  commentNodeId?: string;
}
 
/**
 * Type of action to take for a duplicate finding.
 */
export type DuplicateActionType = 'update_warden' | 'react_external';
 
/**
 * Action to take for a duplicate finding.
 */
export interface DuplicateAction {
  type: DuplicateActionType;
  finding: Finding;
  existingComment: ExistingComment;
  /** Whether this was a hash match or semantic match */
  matchType: 'hash' | 'semantic';
}
 
/**
 * Result of deduplication with actions for duplicates.
 */
export interface DeduplicateResult {
  /** Findings that are not duplicates - should be posted */
  newFindings: Finding[];
  /** Actions to take for duplicate findings */
  duplicateActions: DuplicateAction[];
  /** Usage from semantic dedup LLM call, if invoked */
  dedupUsage?: UsageStats;
}
 
/**
 * Generate a short content hash from title and description.
 * Used for exact-match deduplication.
 */
export function generateContentHash(title: string, description: string): string {
  const content = `${title}\n${description}`;
  return createHash('sha256').update(content).digest('hex').slice(0, 8);
}
 
/**
 * Generate the marker HTML comment to embed in comment body.
 * Format: <!-- warden:v1:{path}:{line}:{contentHash} -->
 */
export function generateMarker(path: string, line: number, contentHash: string): string {
  return `<!-- warden:v1:${path}:${line}:${contentHash} -->`;
}
 
/**
 * Parse a Warden marker from a comment body.
 * Returns null if no valid marker is found.
 */
export function parseMarker(body: string): WardenMarker | null {
  const match = body.match(/<!-- warden:v1:([^:]+):(\d+):([a-f0-9]+) -->/);
  if (!match || match.length < 4) {
    return null;
  }
 
  const path = match[1];
  const lineStr = match[2];
  const contentHash = match[3];
 
  // Validate that all capture groups exist (defensive, should always be true when regex matches)
  Iif (!path || !lineStr || !contentHash) {
    return null;
  }
 
  return {
    path,
    line: parseInt(lineStr, 10),
    contentHash,
  };
}
 
/**
 * Parse title and description from a Warden comment body.
 * Expected format: **:emoji: Title**\n\nDescription or **Title**\n\nDescription
 * Strips legacy [ID] prefix from titles for backward compat.
 */
export function parseWardenComment(body: string): { title: string; description: string } | null {
  // Match the title pattern: **:emoji: Title** or **Title**
  // Use non-greedy match to handle titles containing asterisks
  const titleMatch = body.match(/\*\*(?::[a-z_]+:\s*)?(.+?)\*\*/);
  if (!titleMatch || !titleMatch[1]) {
    return null;
  }
 
  // Strip legacy [ID] prefix (e.g., "[2K5-29B] Title" → "Title")
  const title = titleMatch[1].replace(/^\[[A-Z0-9-]+\]\s*/, '').trim();
 
  // Get the description - everything after the title until the first ---
  const titleEnd = body.indexOf('**', body.indexOf('**') + 2) + 2;
  const separatorIndex = body.indexOf('---');
  const descEnd = separatorIndex > -1 ? separatorIndex : body.length;
 
  const description = body.slice(titleEnd, descEnd).trim();
 
  return { title, description };
}
 
/**
 * Parse the finding ID from a Warden comment's attribution or legacy title.
 */
export function parseWardenFindingId(body: string): string | undefined {
  const attributionMatch = body.match(/(?:<sub>)?Identified by Warden (?!via\s)([^<\n\r]*)(?:<\/sub>|$)/m);
  if (attributionMatch?.[1]) {
    const idMatch = attributionMatch[1].match(/·\s*(?:`([^`]+)`|([^`\n\r]+))/);
    const id = (idMatch?.[1] ?? idMatch?.[2])?.trim();
    Eif (id) return id;
  }
 
  const titleMatch = body.match(/\*\*(?::[a-z_]+:\s*)?\[([^\]]+)\]\s*.+?\*\*/);
  return titleMatch?.[1]?.trim() || undefined;
}
 
/**
 * Check if a comment body is a Warden-generated comment.
 * Supports current muted format (<sub>Identified by Warden skill</sub>), and
 * legacy formats: backtick (Identified by Warden `skill`), bracket
 * (<sub>Identified by Warden [skill]</sub>), via
 * (<sub>Identified by Warden via `skill`</sub>), old
 * (<sub>warden: skill</sub>).
 */
export function isWardenComment(body: string): boolean {
  return (
    body.includes('<sub>Identified by Warden ') ||
    body.includes('Identified by Warden `') ||
    body.includes('<sub>warden:') ||
    body.includes('<!-- warden:v1:')
  );
}
 
function parsePlainSkillList(value: string): string[] {
  return value
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean);
}
 
/**
 * Parse skill names from a Warden comment's attribution line.
 * Supports five formats:
 * - Current: "<sub>Identified by Warden skill1, skill2 · id</sub>"
 * - Legacy backtick: "Identified by Warden `skill1`, `skill2` · id"
 * - Legacy bracket: "<sub>Identified by Warden [skill1], [skill2] · id</sub>"
 * - Legacy via: "<sub>Identified by Warden via `skill1`, `skill2` · severity</sub>"
 * - Legacy old: "<sub>warden: skill1, skill2</sub>"
 */
export function parseWardenSkills(body: string): string[] {
  // Try current muted format: <sub>Identified by Warden skill1, skill2 · id</sub>
  const plainSubMatch = body.match(/<sub>Identified by Warden (?!via\s)([^`[\]<]+?)(?:\s*·|<\/sub>)/);
  if (plainSubMatch?.[1]) {
    const skills = parsePlainSkillList(plainSubMatch[1]);
    Eif (skills.length > 0) return skills;
  }
 
  // Try legacy backtick format (no "via"): Identified by Warden `skill1`, `skill2` · id
  const backtickMatch = body.match(/Identified by Warden ((?:`[^`]+`(?:, )?)+)/);
  if (backtickMatch?.[1]) {
    const skills = [...backtickMatch[1].matchAll(/`([^`]+)`/g)]
      .map((m) => m[1])
      .filter((s): s is string => s !== undefined);
    Eif (skills.length > 0) return skills;
  }
 
  // Try legacy bracket format: <sub>Identified by Warden [skill1], [skill2] · id</sub>
  const bracketMatch = body.match(/<sub>Identified by Warden ((?:\[[^\]]+\](?:, )?)+)/);
  if (bracketMatch?.[1]) {
    const skills = [...bracketMatch[1].matchAll(/\[([^\]]+)\]/g)]
      .map((m) => m[1])
      .filter((s): s is string => s !== undefined);
    Eif (skills.length > 0) return skills;
  }
 
  // Try legacy via format: <sub>Identified by Warden via `skill1`, `skill2` · severity</sub>
  const viaMatch = body.match(/<sub>Identified by Warden via ([^·<]+)/);
  if (viaMatch?.[1]) {
    const skills = [...viaMatch[1].matchAll(/`([^`]+)`/g)]
      .map((m) => m[1])
      .filter((s): s is string => s !== undefined);
    Eif (skills.length > 0) return skills;
  }
 
  // Fall back to legacy old format: <sub>warden: skill1, skill2</sub>
  const oldMatch = body.match(/<sub>warden:\s*([^<]+)<\/sub>/);
  if (!oldMatch?.[1]) {
    return [];
  }
  return oldMatch[1]
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean);
}
 
/**
 * Update a Warden comment body to add a new skill to the attribution.
 * Current format: Changes "<sub>Identified by Warden skill1 · id</sub>"
 *                 to "<sub>Identified by Warden skill1, skill2 · id</sub>"
 * Legacy backtick: Changes "Identified by Warden `skill1` · id"
 *                  to "Identified by Warden `skill1`, `skill2` · id"
 * Legacy bracket: Changes "<sub>Identified by Warden [skill1] · id</sub>"
 *                 to "<sub>Identified by Warden [skill1], [skill2] · id</sub>"
 * Legacy via: Changes "<sub>Identified by Warden via `skill1` · severity</sub>"
 *             to "<sub>Identified by Warden via `skill1`, `skill2` · severity</sub>"
 * Legacy old: Changes "<sub>warden: skill1</sub>" to "<sub>warden: skill1, skill2</sub>"
 * Returns null if skill is already listed or if no attribution tag exists.
 */
export function updateWardenCommentBody(body: string, newSkill: string): string | null {
  const existingSkills = parseWardenSkills(body);
 
  // If no existing attribution tag exists, we can't update it
  Iif (existingSkills.length === 0) {
    return null;
  }
 
  // Don't update if skill already listed
  if (existingSkills.includes(newSkill)) {
    return null;
  }
 
  // Check if it's the current muted format: <sub>Identified by Warden skill · id</sub>
  const plainSubFormatMatch = body.match(/<sub>Identified by Warden (?!via\s)[^`[\]<]+<\/sub>/);
  if (plainSubFormatMatch) {
    const allSkills = [...existingSkills, newSkill].join(', ');
    const subTagMatch = body.match(/<sub>Identified by Warden (?!via\s)([^<]*?)(\s*·[^<]*)?<\/sub>/);
    const suffix = subTagMatch?.[2] || '';
    return body.replace(
      /<sub>Identified by Warden (?!via\s)[^<]+<\/sub>/,
      () => `<sub>Identified by Warden ${allSkills}${suffix}</sub>`
    );
  }
 
  // Check if it's the legacy backtick format (no <sub>, no "via"): Identified by Warden `skill` · id
  const backtickFormatMatch = body.match(/Identified by Warden `[^`]+`/) && !body.includes('<sub>Identified by Warden');
  if (backtickFormatMatch) {
    const existingSkillsFormatted = existingSkills.map((s) => `\`${s}\``).join(', ');
    const lineMatch = body.match(/Identified by Warden ((?:`[^`]+`(?:, )?)+)(.*)/);
    const suffix = lineMatch?.[2] || '';
    return body.replace(
      /Identified by Warden (?:`[^`]+`(?:, )?)+.*/,
      () => `Identified by Warden ${existingSkillsFormatted}, \`${newSkill}\`${suffix}`
    );
  }
 
  // Check if it's the legacy bracket format: <sub>Identified by Warden [skill] · id</sub>
  const bracketFormatMatch = body.match(/<sub>Identified by Warden \[[^\]]+\]/);
  if (bracketFormatMatch) {
    const existingSkillsFormatted = existingSkills.map((s) => `[${s}]`).join(', ');
    const subTagMatch = body.match(/<sub>Identified by Warden ((?:\[[^\]]+\](?:, )?)+)(.*?)<\/sub>/);
    const suffix = subTagMatch?.[2] || '';
    return body.replace(
      /<sub>Identified by Warden [^<]+<\/sub>/,
      () => `<sub>Identified by Warden ${existingSkillsFormatted}, [${newSkill}]${suffix}</sub>`
    );
  }
 
  // Check if it's the legacy via format
  const viaFormatMatch = body.match(/<sub>Identified by Warden via `[^`]+`/);
  if (viaFormatMatch) {
    const existingSkillsFormatted = existingSkills.map((s) => `\`${s}\``).join(', ');
    // Extract the suffix (metadata) starting from the · separator, not from the skill list
    const subTagMatch = body.match(/<sub>Identified by Warden via ([^<]+)<\/sub>/);
    const fullContent = subTagMatch?.[1] || '';
    const separatorIndex = fullContent.indexOf(' · ');
    const suffix = separatorIndex >= 0 ? fullContent.slice(separatorIndex) : '';
    return body.replace(
      /<sub>Identified by Warden via [^<]+<\/sub>/,
      () => `<sub>Identified by Warden via ${existingSkillsFormatted}, \`${newSkill}\`${suffix}</sub>`
    );
  }
 
  // Legacy old format: <sub>warden: skill1, skill2</sub>
  const allSkills = [...existingSkills, newSkill].join(', ');
  // Use a replacer function to avoid special $ character interpretation in skill names
  return body.replace(/<sub>warden:\s*[^<]+<\/sub>/, () => `<sub>warden: ${allSkills}</sub>`);
}
 
/** GraphQL response structure for review threads */
interface ReviewThreadNode {
  id: string;
  isResolved: boolean;
  comments: {
    nodes: {
      id: string; // GraphQL node ID (for reactions)
      databaseId: number;
      body: string;
      path: string;
      line: number | null;
      originalLine: number | null;
    }[];
  };
}
 
interface ReviewThreadsResponse {
  repository?: {
    pullRequest?: {
      reviewThreads: {
        pageInfo: {
          hasNextPage: boolean;
          endCursor: string | null;
        };
        nodes: ReviewThreadNode[];
      };
    } | null;
  } | null;
}
 
const REVIEW_THREADS_QUERY = `
  query($owner: String!, $repo: String!, $prNumber: Int!, $cursor: String) {
    repository(owner: $owner, name: $repo) {
      pullRequest(number: $prNumber) {
        reviewThreads(first: 100, after: $cursor) {
          pageInfo {
            hasNextPage
            endCursor
          }
          nodes {
            id
            isResolved
            comments(first: 1) {
              nodes {
                id
                databaseId
                body
                path
                line
                originalLine
              }
            }
          }
        }
      }
    }
  }
`;
 
/**
 * Fetch all existing review comments for a PR (both Warden and external).
 * Uses GraphQL to get thread IDs for stale comment resolution and node IDs for reactions.
 */
export async function fetchExistingComments(
  octokit: Octokit,
  owner: string,
  repo: string,
  prNumber: number
): Promise<ExistingComment[]> {
  const comments: ExistingComment[] = [];
 
  // Use GraphQL to get thread IDs along with comment data
  let cursor: string | null = null;
  let hasNextPage = true;
 
  while (hasNextPage) {
    const response: ReviewThreadsResponse = await octokit.graphql(REVIEW_THREADS_QUERY, {
      owner,
      repo,
      prNumber,
      cursor,
    });
 
    const pullRequest = response.repository?.pullRequest;
    Iif (!pullRequest) {
      // PR doesn't exist or was deleted
      return comments;
    }
 
    const threads = pullRequest.reviewThreads;
 
    for (const thread of threads.nodes) {
      // Get the first comment in the thread
      const firstComment = thread.comments.nodes[0];
      Iif (!firstComment) {
        continue;
      }
 
      const isWarden = isWardenComment(firstComment.body);
      const marker = isWarden ? parseMarker(firstComment.body) : null;
      const parsed = parseWardenComment(firstComment.body);
 
      // For Warden comments, we need parsed title/description
      // For external comments, we extract what we can or use body as description
      const title = parsed?.title ?? '';
      const description = parsed?.description ?? firstComment.body.slice(0, 500);
 
      comments.push({
        id: firstComment.databaseId,
        path: marker?.path ?? firstComment.path,
        line: marker?.line ?? firstComment.line ?? firstComment.originalLine ?? 0,
        title,
        description,
        findingId: isWarden ? parseWardenFindingId(firstComment.body) : undefined,
        contentHash: marker?.contentHash ?? generateContentHash(title, description),
        threadId: thread.id,
        isResolved: thread.isResolved,
        isWarden,
        skills: isWarden ? parseWardenSkills(firstComment.body) : undefined,
        body: firstComment.body,
        commentNodeId: firstComment.id,
      });
    }
 
    hasNextPage = threads.pageInfo.hasNextPage;
    cursor = threads.pageInfo.endCursor;
  }
 
  return comments;
}
 
/**
 * @deprecated Use fetchExistingComments instead
 */
export async function fetchExistingWardenComments(
  octokit: Octokit,
  owner: string,
  repo: string,
  prNumber: number
): Promise<ExistingComment[]> {
  const allComments = await fetchExistingComments(octokit, owner, repo, prNumber);
  return allComments.filter((c) => c.isWarden);
}
 
/** Schema for validating LLM deduplication response with matched indices */
const DuplicateMatchesSchema = z.array(
  z.object({
    findingIndex: z.number().int(),
    existingIndex: z.number().int(),
  })
);
 
/**
 * Result from semantic dedup LLM call.
 */
interface SemanticDuplicateResult {
  matches: Map<string, ExistingComment>;
  usage?: UsageStats;
}
 
/**
 * Use LLM to identify which findings are semantic duplicates of existing comments.
 * Returns a Map of finding ID to matched ExistingComment, plus usage stats.
 */
async function findSemanticDuplicates(
  findings: Finding[],
  existingComments: ExistingComment[],
  apiKey: string | undefined,
  options: Pick<DeduplicateOptions, 'runtime' | 'model' | 'maxRetries' | 'currentSkill'> = {}
): Promise<SemanticDuplicateResult> {
  if (findings.length === 0 || existingComments.length === 0) {
    return { matches: new Map() };
  }
 
  const existingList = existingComments
    .map((c, i) => `${i + 1}. [${c.path}:${c.line}] "${c.title}" - ${c.description}`)
    .join('\n');
 
  const findingsList = formatIndexedFindingsForPrompt(findings);
 
  const prompt = joinPromptSections([
    `<task>
Compare these code review findings and identify duplicates.
</task>`,
    `<existing_comments>
${existingList}
</existing_comments>`,
    `<new_findings>
${findingsList}
</new_findings>`,
    `<deduplication_rules>
Return a JSON array of objects identifying which findings are DUPLICATES of which existing comments.
Only mark as duplicate if they describe the SAME issue at the SAME location (within a few lines).
Different issues at the same location are NOT duplicates.
</deduplication_rules>`,
    buildJsonOutputSection(`[{"findingIndex": 1, "existingIndex": 2}]
where findingIndex is the 1-based index of the new finding and existingIndex is the 1-based index of the matching existing comment.
Return [] if none are duplicates.`),
  ]);
 
  const result = await getRuntime(options.runtime ?? 'claude').runAuxiliary({
    task: 'deduplication',
    agentName: options.currentSkill,
    apiKey,
    prompt,
    schema: DuplicateMatchesSchema,
    model: options.model,
    maxTokens: 512,
    maxRetries: options.maxRetries,
  });
 
  if (!result.success) {
    console.warn(`LLM deduplication failed, falling back to hash-only: ${result.error}`);
    return { matches: new Map(), usage: result.usage };
  }
 
  const matches = new Map<string, ExistingComment>();
  for (const match of result.data) {
    const finding = findings[match.findingIndex - 1];
    const existing = existingComments[match.existingIndex - 1];
    if (finding && existing) {
      matches.set(finding.id, existing);
    }
  }
 
  return { matches, usage: result.usage };
}
 
/**
 * Options for deduplication.
 */
export interface DeduplicateOptions extends AuxiliaryCallOptions {
  /** Skip LLM deduplication and only use exact hash matching */
  hashOnly?: boolean;
  /** Current skill name (for updating Warden comment attribution) */
  currentSkill?: string;
}
 
export interface ConsolidateOptions extends AuxiliaryCallOptions {
  /** Skip LLM consolidation and only use exact hash matching */
  hashOnly?: boolean;
}
 
const ADD_REACTION_MUTATION = `
  mutation($subjectId: ID!, $content: ReactionContent!) {
    addReaction(input: { subjectId: $subjectId, content: $content }) {
      reaction {
        content
      }
    }
  }
`;
 
/**
 * Update an existing Warden PR review comment via REST API.
 */
export async function updateWardenComment(
  octokit: Octokit,
  owner: string,
  repo: string,
  commentId: number,
  newBody: string
): Promise<void> {
  await octokit.pulls.updateReviewComment({
    owner,
    repo,
    comment_id: commentId,
    body: newBody,
  });
}
 
/**
 * Add a reaction to an existing PR review comment.
 * Uses GraphQL to handle review comments.
 */
export async function addReactionToComment(
  octokit: Octokit,
  commentNodeId: string,
  reaction: 'THUMBS_UP' | 'EYES' = 'EYES'
): Promise<void> {
  await octokit.graphql(ADD_REACTION_MUTATION, {
    subjectId: commentNodeId,
    content: reaction,
  });
}
 
/**
 * Process duplicate actions - update Warden comments and add reactions.
 * Returns counts of actions taken for logging.
 */
export async function processDuplicateActions(
  octokit: Octokit,
  owner: string,
  repo: string,
  actions: DuplicateAction[],
  currentSkill: string
): Promise<{ updated: number; reacted: number; skipped: number; failed: number }> {
  let updated = 0;
  let reacted = 0;
  let skipped = 0;
  let failed = 0;
 
  for (const action of actions) {
    try {
      if (action.type === 'update_warden') {
        if (!action.existingComment.body) {
          skipped++;
          continue;
        }
        const newBody = updateWardenCommentBody(action.existingComment.body, currentSkill);
        // Only update if body actually changed (skill wasn't already listed)
        if (newBody) {
          await updateWardenComment(octokit, owner, repo, action.existingComment.id, newBody);
          // Update in-memory body so subsequent triggers see the updated content
          action.existingComment.body = newBody;
          updated++;
        } else {
          skipped++;
        }
      } else if (action.type === 'react_external') {
        if (!action.existingComment.commentNodeId) {
          skipped++;
          continue;
        }
        await addReactionToComment(octokit, action.existingComment.commentNodeId);
        reacted++;
      }
    } catch (error) {
      console.warn(`Failed to process duplicate action for ${action.finding.title}: ${error}`);
      failed++;
    }
  }
 
  return { updated, reacted, skipped, failed };
}
 
/**
 * Convert a Finding to an ExistingComment for cross-trigger deduplication.
 * Returns null if the finding has no location.
 */
export function findingToExistingComment(finding: Finding, skill?: string): ExistingComment | null {
  if (!finding.location) {
    return null;
  }
 
  return {
    id: -1, // Newly posted comments don't have IDs yet
    path: finding.location.path,
    line: finding.location.endLine ?? finding.location.startLine,
    title: finding.title,
    description: finding.description,
    findingId: finding.id,
    contentHash: generateContentHash(finding.title, finding.description),
    isWarden: true,
    skills: skill ? [skill] : [],
  };
}
 
// -----------------------------------------------------------------------------
// Intra-batch consolidation
// -----------------------------------------------------------------------------
 
const PROXIMITY_THRESHOLD = 5;
 
/**
 * Result from consolidating findings within a single batch.
 */
export interface ConsolidateResult {
  findings: Finding[];
  removedCount: number;
  usage?: UsageStats;
}
 
/** Schema for LLM consolidation response: groups of finding indices that share a root cause. */
const ConsolidationGroupsSchema = z.array(
  z.array(z.number().int())
);
 
/**
 * Group findings by file path, then identify clusters where findings are within
 * PROXIMITY_THRESHOLD lines of each other. Returns only clusters with 2+ findings.
 */
function findProximityClusters(findings: Finding[]): Finding[][] {
  // Group by file path
  const byPath = new Map<string, Finding[]>();
  for (const f of findings) {
    const path = f.location?.path ?? '';
    const existing = byPath.get(path);
    if (existing) {
      existing.push(f);
    } else {
      byPath.set(path, [f]);
    }
  }
 
  const clusters: Finding[][] = [];
 
  for (const group of byPath.values()) {
    if (group.length < 2) continue;
 
    // Sort by line number
    const sorted = [...group].sort((a, b) => findingLine(a) - findingLine(b));
 
    // Single-linkage clustering: consecutive findings within PROXIMITY_THRESHOLD
    // lines of each other are grouped together.
    const first = sorted[0];
    Iif (!first) continue;
    let current: Finding[] = [first];
 
    for (let i = 1; i < sorted.length; i++) {
      const prev = sorted[i - 1];
      const curr = sorted[i];
      Iif (!prev || !curr) continue;
 
      if (findingLine(curr) - findingLine(prev) <= PROXIMITY_THRESHOLD) {
        current.push(curr);
      } else {
        Iif (current.length >= 2) clusters.push(current);
        current = [curr];
      }
    }
    if (current.length >= 2) clusters.push(current);
  }
 
  return clusters;
}
 
/**
 * Consolidate findings within a single batch to remove duplicates that describe
 * the same root cause. Three-phase approach:
 *
 * 1. Hash dedup: remove exact duplicates (same path:line:contentHash)
 * 2. Proximity grouping: identify clusters of findings within 5 lines of each other
 * 3. LLM consolidation: ask the auxiliary runtime to group findings by root cause (only when proximity matches exist)
 *
 * For each group, keeps the highest-severity finding.
 */
export async function consolidateBatchFindings(
  findings: Finding[],
  options: ConsolidateOptions = {}
): Promise<ConsolidateResult> {
  if (findings.length <= 1) {
    return { findings, removedCount: 0 };
  }
 
  // Phase 1: Hash dedup within batch
  const seen = new Set<string>();
  const hashDeduped: Finding[] = [];
 
  for (const f of findings) {
    const hash = generateContentHash(f.title, f.description);
    const line = findingLine(f);
    const path = f.location?.path ?? '';
    const key = `${path}:${line}:${hash}`;
 
    if (seen.has(key)) continue;
    seen.add(key);
    hashDeduped.push(f);
  }
 
  const hashRemovedCount = findings.length - hashDeduped.length;
 
  if (hashRemovedCount > 0) {
    console.log(`Consolidate: ${hashRemovedCount} exact duplicate findings removed within batch`);
  }
 
  // Phase 2: Proximity grouping
  const clusters = findProximityClusters(hashDeduped);
 
  // If no proximity clusters, hash-only mode, or no runtime auth, return hash-deduped results.
  Eif (clusters.length === 0 || options.hashOnly || !canUseRuntimeAuth(options)) {
    return { findings: hashDeduped, removedCount: hashRemovedCount };
  }
 
  // Phase 3: LLM consolidation for proximity clusters
  // Only send clustered findings to the LLM (deduplicated across clusters)
  const clusteredList = [...new Set(clusters.flat())];
  const findingsList = formatIndexedFindingsForPrompt(clusteredList, {
    includeSeverity: true,
  });
 
  const prompt = joinPromptSections([
    `<task>
Group findings that describe the SAME root cause or bug.
</task>`,
    `<findings>
${findingsList}
</findings>`,
    `<deduplication_rules>
Return a JSON array of arrays, where each inner array contains the 1-based indices of findings that describe the same root cause.
Only group findings that are truly about the same underlying issue. Findings about different issues should NOT be grouped even if they're nearby.
Singletons (findings with no duplicates) should not appear in any group.
</deduplication_rules>`,
    buildJsonOutputSection('Return the JSON array. Return [] if no findings share a root cause.'),
  ]);
 
  const result = await getRuntime(options.runtime ?? 'claude').runAuxiliary({
    task: 'deduplication',
    agentName: options.agentName,
    apiKey: options.apiKey,
    prompt,
    schema: ConsolidationGroupsSchema,
    model: options.model,
    maxTokens: 512,
    maxRetries: options.maxRetries,
  });
 
  if (!result.success) {
    console.warn(`LLM batch consolidation failed, keeping all findings: ${result.error}`);
    return { findings: hashDeduped, removedCount: hashRemovedCount, usage: result.usage };
  }
 
  const { absorbed, replacements } = applyMergeGroups(clusteredList, result.data);
 
  if (absorbed.size === 0) {
    return { findings: hashDeduped, removedCount: hashRemovedCount, usage: result.usage };
  }
 
  const consolidated = hashDeduped
    .filter((f) => !absorbed.has(f))
    .map((f) => replacements.get(f) ?? f);
  const totalRemoved = hashRemovedCount + absorbed.size;
 
  console.log(`Consolidate: ${absorbed.size} findings merged by LLM (same root cause)`);
 
  return { findings: consolidated, removedCount: totalRemoved, usage: result.usage };
}
 
/**
 * Deduplicate findings against existing comments.
 * Returns non-duplicate findings and actions to take for duplicates.
 *
 * Deduplication is two-pass:
 * 1. Exact content hash match - instant match
 * 2. LLM semantic comparison for remaining findings (if API key provided)
 *
 * For duplicates:
 * - If matching a Warden comment: action to update attribution with new skill
 * - If matching an external comment: action to add reaction
 */
export async function deduplicateFindings(
  findings: Finding[],
  existingComments: ExistingComment[],
  options: DeduplicateOptions = {}
): Promise<DeduplicateResult> {
  if (findings.length === 0 || existingComments.length === 0) {
    return { newFindings: findings, duplicateActions: [] };
  }
 
  // Build maps of existing comments by location+hash for fast lookup
  const existingByKey = new Map<string, ExistingComment>();
  const wardenByKey = new Map<string, ExistingComment>();
  for (const c of existingComments) {
    const key = `${c.path}:${c.line}:${c.contentHash}`;
    existingByKey.set(key, c);
    if (c.isWarden) {
      wardenByKey.set(key, c);
    }
  }
 
  // First pass: find exact matches (same content at same location)
  const hashDedupedFindings: Finding[] = [];
  const duplicateActions: DuplicateAction[] = [];
 
  for (const finding of findings) {
    const hash = generateContentHash(finding.title, finding.description);
    const line = finding.location?.endLine ?? finding.location?.startLine ?? 0;
    const path = finding.location?.path ?? '';
    const key = `${path}:${line}:${hash}`;
 
    let matchingComment = existingByKey.get(key);
 
    // If no primary location match, check additional locations against our own comments.
    // This handles winner-flip scenarios where a merged finding's primary location changed
    // between runs but an additional location matches a previous Warden comment.
    if (!matchingComment && finding.additionalLocations) {
      for (const loc of finding.additionalLocations) {
        const addlLine = loc.endLine ?? loc.startLine;
        const addlKey = `${loc.path}:${addlLine}:${hash}`;
        const wardenMatch = wardenByKey.get(addlKey);
        if (wardenMatch) {
          matchingComment = wardenMatch;
          break;
        }
      }
    }
 
    if (matchingComment) {
      duplicateActions.push({
        type: matchingComment.isWarden ? 'update_warden' : 'react_external',
        finding,
        existingComment: matchingComment,
        matchType: 'hash',
      });
    } else {
      hashDedupedFindings.push(finding);
    }
  }
 
  if (duplicateActions.length > 0) {
    console.log(`Dedup: ${duplicateActions.length} findings matched by content hash`);
  }
 
  // If hash-only mode, no runtime auth, or no remaining findings, stop here.
  Eif (options.hashOnly || !canUseRuntimeAuth(options) || hashDedupedFindings.length === 0) {
    return { newFindings: hashDedupedFindings, duplicateActions };
  }
 
  // Second pass: LLM semantic comparison for remaining findings
  const semanticResult = await findSemanticDuplicates(hashDedupedFindings, existingComments, options.apiKey, options);
 
  if (semanticResult.matches.size > 0) {
    console.log(`Dedup: ${semanticResult.matches.size} findings identified as semantic duplicates by LLM`);
  }
 
  const newFindings: Finding[] = [];
  for (const finding of hashDedupedFindings) {
    const matchingComment = semanticResult.matches.get(finding.id);
    if (matchingComment) {
      duplicateActions.push({
        type: matchingComment.isWarden ? 'update_warden' : 'react_external',
        finding,
        existingComment: matchingComment,
        matchType: 'semantic',
      });
    } else {
      newFindings.push(finding);
    }
  }
 
  return { newFindings, duplicateActions, dedupUsage: semanticResult.usage };
}