All files / src/triggers matcher.ts

95.19% Statements 99/104
87.67% Branches 64/73
100% Functions 24/24
96.73% Lines 89/92

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            23x     23x       7x         9x             2912x 2912x   790x 790x 790x     2122x   2122x 31087x 31087x 31087x   31087x       31087x 110x 110x 110x     30977x 34x 34x 34x     30943x 2049x 2049x     28894x 1x 1x     28893x     2122x     2122x 8x 8x 8x       2122x 2122x               2912x                     52x     52x 3x     49x 13x 16x   13x 10x       39x 1x 1x   1x 1x       38x                     48x     48x 43x       5x 1x     4x   4x 3x 14x       4x 2x 8x       4x                                               55x 8x 4x       51x 2x 1x       50x 48x     45x     45x 1x         49x 1x 1x           52x 55x               15x 15x 15x               6x 6x 12x             40x   49x        
import type { ResolvedTrigger } from '../config/loader.js';
import type { TriggerType } from '../config/schema.js';
import { SEVERITY_ORDER } from '../types/index.js';
import type { EventContext, Severity, SeverityThreshold, SkillReport } from '../types/index.js';
 
/** Maximum number of patterns to cache (LRU eviction when exceeded) */
const GLOB_CACHE_MAX_SIZE = 1000;
 
/** Cache for compiled glob patterns with LRU eviction */
const globCache = new Map<string, RegExp>();
 
/** Clear the glob cache (useful for testing) */
export function clearGlobCache(): void {
  globCache.clear();
}
 
/** Get current cache size (useful for testing) */
export function getGlobCacheSize(): number {
  return globCache.size;
}
 
/**
 * Convert a glob pattern to a regex (cached with LRU eviction).
 */
function globToRegex(pattern: string): RegExp {
  const cached = globCache.get(pattern);
  if (cached) {
    // Move to end for LRU ordering (delete and re-add)
    globCache.delete(pattern);
    globCache.set(pattern, cached);
    return cached;
  }
 
  let regexPattern = '';
 
  for (let index = 0; index < pattern.length; index++) {
    const char = pattern[index];
    const nextChar = pattern[index + 1];
    const nextNextChar = pattern[index + 2];
 
    Iif (char === undefined) {
      break;
    }
 
    if (char === '*' && nextChar === '*' && nextNextChar === '/') {
      regexPattern += '(?:.*/)?';
      index += 2;
      continue;
    }
 
    if (char === '*' && nextChar === '*') {
      regexPattern += '.*';
      index += 1;
      continue;
    }
 
    if (char === '*') {
      regexPattern += '[^/]*';
      continue;
    }
 
    if (char === '?') {
      regexPattern += '[^/]';
      continue;
    }
 
    regexPattern += char.replace(/[.+^${}()|[\]\\]/g, '\\$&');
  }
 
  const regex = new RegExp(`^${regexPattern}$`);
 
  // Evict oldest entry if cache is full
  if (globCache.size >= GLOB_CACHE_MAX_SIZE) {
    const oldestKey = globCache.keys().next().value;
    Eif (oldestKey !== undefined) {
      globCache.delete(oldestKey);
    }
  }
 
  globCache.set(pattern, regex);
  return regex;
}
 
/**
 * Match a glob pattern against a file path.
 * Supports ** for recursive matching and * for single directory matching.
 */
export function matchGlob(pattern: string, path: string): boolean {
  return globToRegex(pattern).test(path);
}
 
/**
 * Check if a file list matches the path filters.
 * Returns true if paths match (or no filters), false if all files are excluded.
 */
function matchPathFilters(
  filters: { paths?: string[]; ignorePaths?: string[] },
  filenames: string[] | undefined
): boolean {
  const { paths: pathPatterns, ignorePaths: ignorePatterns } = filters;
 
  // Fail trigger match when path filters are defined but filenames unavailable
  if ((pathPatterns || ignorePatterns) && (!filenames || filenames.length === 0)) {
    return false;
  }
 
  if (pathPatterns && filenames) {
    const hasMatch = filenames.some((file) =>
      pathPatterns.some((pattern) => matchGlob(pattern, file))
    );
    if (!hasMatch) {
      return false;
    }
  }
 
  if (ignorePatterns && filenames) {
    const allIgnored = filenames.every((file) =>
      ignorePatterns.some((pattern) => matchGlob(pattern, file))
    );
    Eif (allIgnored) {
      return false;
    }
  }
 
  return true;
}
 
/**
 * Return a copy of the context with only files matching the path filters.
 * If no filters are set, returns the original context unchanged (no copy).
 */
export function filterContextByPaths(
  context: EventContext,
  filters: { paths?: string[]; ignorePaths?: string[] }
): EventContext {
  const { paths: pathPatterns, ignorePaths: ignorePatterns } = filters;
 
  // No filters — return original reference
  if (!pathPatterns && !ignorePatterns) {
    return context;
  }
 
  // No PR context — nothing to filter
  if (!context.pullRequest) {
    return context;
  }
 
  let files = context.pullRequest.files;
 
  if (pathPatterns) {
    files = files.filter((f) =>
      pathPatterns.some((pattern) => matchGlob(pattern, f.filename))
    );
  }
 
  if (ignorePatterns) {
    files = files.filter(
      (f) => !ignorePatterns.some((pattern) => matchGlob(pattern, f.filename))
    );
  }
 
  return {
    ...context,
    pullRequest: {
      ...context.pullRequest,
      files,
    },
  };
}
 
/**
 * Check if a trigger matches the given event context and environment.
 *
 * Trigger types:
 * - '*' (wildcard): matches all environments, skips event/action checks
 * - 'local': matches only when environment is 'local' (local-only skills)
 * - 'pull_request': matches in 'github' (with event/action checks) and 'local' (path filters only)
 * - 'schedule': matches when event is schedule
 */
export function matchTrigger(
  trigger: ResolvedTrigger,
  context: EventContext,
  environment?: TriggerType | 'github'
): boolean {
  // Wildcard triggers match everywhere, only check path filters
  if (trigger.type === '*') {
    const filenames = context.pullRequest?.files.map((f) => f.filename);
    return matchPathFilters(trigger.filters, filenames);
  }
 
  // Type-based matching with early returns
  if (trigger.type === 'local') {
    if (environment !== 'local') {
      return false;
    }
  }
 
  if (trigger.type === 'pull_request') {
    if (environment === 'local') {
      // Local mode runs all skills — skip event/action checks, fall through to path filters
    } else {
      Iif (context.eventType !== 'pull_request') {
        return false;
      }
      if (!trigger.actions?.includes(context.action)) {
        return false;
      }
    }
  }
 
  if (trigger.type === 'schedule') {
    Eif (context.eventType !== 'schedule') {
      return false;
    }
    return (context.pullRequest?.files.length ?? 0) > 0;
  }
 
  // Apply path filters
  const filenames = context.pullRequest?.files.map((f) => f.filename);
  return matchPathFilters(trigger.filters, filenames);
}
 
/**
 * Check if a report has any findings at or above the given severity threshold.
 * Returns false if failOn is 'off' (disabled).
 */
export function shouldFail(report: SkillReport, failOn: SeverityThreshold): boolean {
  Iif (failOn === 'off') return false;
  const threshold = SEVERITY_ORDER[failOn];
  return report.findings.some((f) => SEVERITY_ORDER[f.severity] <= threshold);
}
 
/**
 * Count findings at or above the given severity threshold.
 * Returns 0 if failOn is 'off' (disabled).
 */
export function countFindingsAtOrAbove(report: SkillReport, failOn: SeverityThreshold): number {
  Iif (failOn === 'off') return 0;
  const threshold = SEVERITY_ORDER[failOn];
  return report.findings.filter((f) => SEVERITY_ORDER[f.severity] <= threshold).length;
}
 
/**
 * Count findings of a specific severity across multiple reports.
 */
export function countSeverity(reports: SkillReport[], severity: Severity): number {
  return reports.reduce(
    (count, report) =>
      count + report.findings.filter((f) => f.severity === severity).length,
    0
  );
}