[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D9914DNBSQ064YVNWMAA31":3,"skill-same:01M7D9914DNBSQ064YVNWMAA31":80},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":58,"commitSha":59,"skillDirectory":60,"forksCount":14,"repositoryHtmlUrl":61,"repositoryHomepageUrl":6,"ownerHtmlUrl":62,"ownerBlogUrl":63,"ownerDescription":64,"updatedAt":65,"install":66,"resources":79},"01M7D9914DNBSQ064YVNWMAA31","PR Test Impact Analyzer",null,"Analyze pull request code changes to determine which tests are affected, recommend test execution order, and identify missing test coverage for modified code paths","GrupoANDevelopment-m\u002Falberto-ai","GrupoANDevelopment-m","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F257455179?v=4","01M7D69X2N2KEVN0SJF6WGM6SH","Antônio  Ndombe","01M7D69X3P5JTT8H8S904N3888",0,"MIT","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fpr-test-impact-analyzer\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: PR Test Impact Analyzer\ndescription: Analyze pull request code changes to determine which tests are affected, recommend test execution order, and identify missing test coverage for modified code paths\nversion: 1.0.0\nauthor: Pramod\nlicense: MIT\ntags: [test-impact, pr-analysis, change-detection, test-selection, affected-tests, code-change, test-optimization]\ntestingTypes: [code-quality, tdd]\nframeworks: [jest, vitest]\nlanguages: [typescript, javascript]\ndomains: [devops]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# PR Test Impact Analyzer Skill\n\nYou are an expert QA automation engineer specializing in test impact analysis for pull requests. When the user asks you to analyze code changes, identify affected tests, determine test execution priority, or detect missing test coverage for modified code paths, follow these detailed instructions.\n\n## Core Principles\n\n1. **Change awareness drives test selection** -- Every code change has a blast radius. Understanding the dependency graph between production code and test files is the foundation of intelligent test selection. Never run all tests blindly when you can precisely identify which tests are affected by a change.\n\n2. **Dependency graphs are the source of truth** -- Static analysis of import chains, module references, and symbol usage produces a reliable map from source files to test files. This graph must be built incrementally and kept current with every commit.\n\n3. **Risk scoring informs execution order** -- Not all changes carry equal risk. A modification to a shared utility used by fifty modules is higher risk than a CSS tweak. Assign risk scores based on the number of dependents, the type of change (logic vs. style), and the historical defect rate of the file.\n\n4. **Missing coverage is a first-class signal** -- When a pull request modifies a function or module that has no corresponding test, that gap must be surfaced prominently. Silent gaps lead to regressions in production.\n\n5. **Feedback speed matters** -- The value of test impact analysis is proportional to how quickly developers receive results. Analysis should complete in seconds, not minutes, so it can be integrated into PR checks without degrading the developer experience.\n\n6. **Determinism over heuristics** -- Prefer static analysis and explicit dependency tracking over heuristic-based guessing. Heuristics break when naming conventions change or projects are restructured.\n\n7. **Incremental analysis scales** -- Rebuilding the full dependency graph on every PR is wasteful. Cache the graph and update only the nodes affected by the current changeset. This keeps analysis time constant regardless of repository size.\n\n8. **Integrate at the PR level** -- Test impact analysis is most valuable as a PR check that comments directly on the pull request with affected tests, missing coverage, and recommended execution order. Developers should not need to leave their workflow to get this information.\n\n## Project Structure\n\nOrganize your PR test impact analysis tooling with this structure:\n\n```\ntest-impact\u002F\n  src\u002F\n    analyzer\u002F\n      git-diff-parser.ts\n      dependency-graph.ts\n      test-mapper.ts\n      risk-scorer.ts\n      coverage-gap-detector.ts\n    reporters\u002F\n      pr-comment-reporter.ts\n      json-reporter.ts\n      console-reporter.ts\n    config\u002F\n      impact-config.ts\n      path-mappings.ts\n    cache\u002F\n      graph-cache.ts\n      file-hash-cache.ts\n    utils\u002F\n      file-resolver.ts\n      pattern-matcher.ts\n      ast-helpers.ts\n  scripts\u002F\n    build-graph.ts\n    analyze-pr.ts\n    update-cache.ts\n  __tests__\u002F\n    git-diff-parser.test.ts\n    dependency-graph.test.ts\n    test-mapper.test.ts\n    risk-scorer.test.ts\n    coverage-gap-detector.test.ts\n  impact-config.json\n  tsconfig.json\n  package.json\n```\n\n## How It Works: Git Diff Analysis\n\nThe first step in test impact analysis is understanding exactly what changed in the pull request. This means parsing the git diff to extract a structured list of modified files, added files, deleted files, and renamed files along with the specific lines and symbols that changed.\n\n### Parsing the Git Diff\n\nThe diff parser extracts structured change information from the git diff output, providing the foundation for all downstream analysis.\n\n```typescript\nimport { execSync } from 'child_process';\nimport * as path from 'path';\n\nexport interface FileChange {\n  filePath: string;\n  changeType: 'added' | 'modified' | 'deleted' | 'renamed';\n  oldPath?: string;\n  additions: number;\n  deletions: number;\n  changedLines: LineChange[];\n}\n\nexport interface LineChange {\n  lineNumber: number;\n  type: 'add' | 'delete';\n  content: string;\n}\n\nexport interface DiffResult {\n  baseBranch: string;\n  headBranch: string;\n  files: FileChange[];\n  totalAdditions: number;\n  totalDeletions: number;\n}\n\nexport function parsePRDiff(baseBranch: string = 'main'): DiffResult {\n  const mergeBase = execSync(`git merge-base ${baseBranch} HEAD`)\n    .toString()\n    .trim();\n\n  const diffNameStatus = execSync(\n    `git diff --name-status ${mergeBase}...HEAD`\n  )\n    .toString()\n    .trim();\n\n  const files: FileChange[] = [];\n\n  for (const line of diffNameStatus.split('\\n')) {\n    if (!line.trim()) continue;\n\n    const parts = line.split('\\t');\n    const status = parts[0];\n    let changeType: FileChange['changeType'];\n    let filePath: string;\n    let oldPath: string | undefined;\n\n    if (status.startsWith('R')) {\n      changeType = 'renamed';\n      oldPath = parts[1];\n      filePath = parts[2];\n    } else if (status === 'A') {\n      changeType = 'added';\n      filePath = parts[1];\n    } else if (status === 'D') {\n      changeType = 'deleted';\n      filePath = parts[1];\n    } else {\n      changeType = 'modified';\n      filePath = parts[1];\n    }\n\n    const changedLines = getChangedLines(mergeBase, filePath, oldPath);\n    const additions = changedLines.filter((l) => l.type === 'add').length;\n    const deletions = changedLines.filter((l) => l.type === 'delete').length;\n\n    files.push({\n      filePath,\n      changeType,\n      oldPath,\n      additions,\n      deletions,\n      changedLines,\n    });\n  }\n\n  return {\n    baseBranch,\n    headBranch: execSync('git rev-parse --abbrev-ref HEAD').toString().trim(),\n    files,\n    totalAdditions: files.reduce((sum, f) => sum + f.additions, 0),\n    totalDeletions: files.reduce((sum, f) => sum + f.deletions, 0),\n  };\n}\n\nfunction getChangedLines(\n  mergeBase: string,\n  filePath: string,\n  oldPath?: string\n): LineChange[] {\n  const target = oldPath ? `${oldPath} ${filePath}` : filePath;\n  try {\n    const diff = execSync(\n      `git diff -U0 ${mergeBase}...HEAD -- ${target}`\n    ).toString();\n\n    const lines: LineChange[] = [];\n    let currentLine = 0;\n\n    for (const line of diff.split('\\n')) {\n      const hunkMatch = line.match(\u002F^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@\u002F);\n      if (hunkMatch) {\n        currentLine = parseInt(hunkMatch[1], 10);\n        continue;\n      }\n\n      if (line.startsWith('+') && !line.startsWith('+++')) {\n        lines.push({ lineNumber: currentLine, type: 'add', content: line.slice(1) });\n        currentLine++;\n      } else if (line.startsWith('-') && !line.startsWith('---')) {\n        lines.push({ lineNumber: currentLine, type: 'delete', content: line.slice(1) });\n      } else if (!line.startsWith('\\\\')) {\n        currentLine++;\n      }\n    }\n\n    return lines;\n  } catch {\n    return [];\n  }\n}\n```\n\n### Filtering Relevant Source Files\n\nNot every changed file is relevant for test impact analysis. Configuration files, documentation, and assets typically do not affect test execution. Filter the diff results to focus on source code and test files.\n\n```typescript\nexport interface ImpactConfig {\n  sourcePatterns: string[];\n  testPatterns: string[];\n  ignorePatterns: string[];\n  sourceRoot: string;\n  testRoot: string;\n}\n\nconst DEFAULT_CONFIG: ImpactConfig = {\n  sourcePatterns: ['src\u002F**\u002F*.ts', 'src\u002F**\u002F*.tsx', 'lib\u002F**\u002F*.ts'],\n  testPatterns: [\n    '**\u002F*.test.ts',\n    '**\u002F*.spec.ts',\n    '**\u002F*.test.tsx',\n    '**\u002F*.spec.tsx',\n    '__tests__\u002F**\u002F*.ts',\n  ],\n  ignorePatterns: [\n    '**\u002F*.md',\n    '**\u002F*.json',\n    '**\u002F*.css',\n    '**\u002F*.svg',\n    '**\u002Fnode_modules\u002F**',\n    '**\u002Fdist\u002F**',\n  ],\n  sourceRoot: 'src',\n  testRoot: '__tests__',\n};\n\nexport function filterRelevantFiles(\n  diff: DiffResult,\n  config: ImpactConfig = DEFAULT_CONFIG\n): { sourceFiles: FileChange[]; testFiles: FileChange[]; otherFiles: FileChange[] } {\n  const { minimatch } = require('minimatch');\n\n  const sourceFiles: FileChange[] = [];\n  const testFiles: FileChange[] = [];\n  const otherFiles: FileChange[] = [];\n\n  for (const file of diff.files) {\n    if (config.ignorePatterns.some((p) => minimatch(file.filePath, p))) {\n      otherFiles.push(file);\n      continue;\n    }\n\n    if (config.testPatterns.some((p) => minimatch(file.filePath, p))) {\n      testFiles.push(file);\n    } else if (config.sourcePatterns.some((p) => minimatch(file.filePath, p))) {\n      sourceFiles.push(file);\n    } else {\n      otherFiles.push(file);\n    }\n  }\n\n  return { sourceFiles, testFiles, otherFiles };\n}\n```\n\n## Building the Dependency Graph\n\nThe dependency graph maps every source file to the files that import it and every test file to the source files it exercises. This bidirectional graph is the engine behind accurate test impact analysis.\n\n### Static Import Analysis\n\nParse TypeScript and JavaScript files to extract their import declarations and build a complete dependency map.\n\n```typescript\nimport * as ts from 'typescript';\nimport * as path from 'path';\nimport * as fs from 'fs';\n\nexport interface DependencyNode {\n  filePath: string;\n  imports: string[];\n  importedBy: string[];\n  isTestFile: boolean;\n  lastModified: number;\n}\n\nexport interface DependencyGraph {\n  nodes: Map\u003Cstring, DependencyNode>;\n  buildTimestamp: number;\n}\n\nexport function buildDependencyGraph(\n  rootDir: string,\n  config: ImpactConfig\n): DependencyGraph {\n  const graph: DependencyGraph = {\n    nodes: new Map(),\n    buildTimestamp: Date.now(),\n  };\n\n  const allFiles = collectFiles(rootDir, [\n    ...config.sourcePatterns,\n    ...config.testPatterns,\n  ]);\n\n  for (const filePath of allFiles) {\n    const absolutePath = path.resolve(rootDir, filePath);\n    const imports = extractImports(absolutePath, rootDir);\n    const isTestFile = config.testPatterns.some((p) =>\n      require('minimatch')(filePath, p)\n    );\n\n    const stat = fs.statSync(absolutePath);\n\n    graph.nodes.set(filePath, {\n      filePath,\n      imports,\n      importedBy: [],\n      isTestFile,\n      lastModified: stat.mtimeMs,\n    });\n  }\n\n  \u002F\u002F Build reverse edges\n  for (const [filePath, node] of graph.nodes) {\n    for (const importPath of node.imports) {\n      const target = graph.nodes.get(importPath);\n      if (target) {\n        target.importedBy.push(filePath);\n      }\n    }\n  }\n\n  return graph;\n}\n\nfunction extractImports(absolutePath: string, rootDir: string): string[] {\n  const content = fs.readFileSync(absolutePath, 'utf-8');\n  const sourceFile = ts.createSourceFile(\n    absolutePath,\n    content,\n    ts.ScriptTarget.Latest,\n    true\n  );\n\n  const imports: string[] = [];\n\n  function visit(node: ts.Node): void {\n    if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {\n      const specifier = node.moduleSpecifier.text;\n      const resolved = resolveImportPath(absolutePath, specifier, rootDir);\n      if (resolved) {\n        imports.push(resolved);\n      }\n    }\n\n    if (\n      ts.isCallExpression(node) &&\n      node.expression.kind === ts.SyntaxKind.ImportKeyword &&\n      node.arguments.length === 1 &&\n      ts.isStringLiteral(node.arguments[0])\n    ) {\n      const specifier = (node.arguments[0] as ts.StringLiteral).text;\n      const resolved = resolveImportPath(absolutePath, specifier, rootDir);\n      if (resolved) {\n        imports.push(resolved);\n      }\n    }\n\n    ts.forEachChild(node, visit);\n  }\n\n  visit(sourceFile);\n  return imports;\n}\n\nfunction resolveImportPath(\n  fromFile: string,\n  specifier: string,\n  rootDir: string\n): string | null {\n  if (!specifier.startsWith('.') && !specifier.startsWith('\u002F')) {\n    return null; \u002F\u002F Skip node_modules imports\n  }\n\n  const dir = path.dirname(fromFile);\n  const extensions = ['.ts', '.tsx', '.js', '.jsx'];\n  const basePath = path.resolve(dir, specifier);\n\n  for (const ext of extensions) {\n    const candidate = basePath + ext;\n    if (fs.existsSync(candidate)) {\n      return path.relative(rootDir, candidate);\n    }\n  }\n\n  \u002F\u002F Check for index files\n  for (const ext of extensions) {\n    const candidate = path.join(basePath, `index${ext}`);\n    if (fs.existsSync(candidate)) {\n      return path.relative(rootDir, candidate);\n    }\n  }\n\n  return null;\n}\n\nfunction collectFiles(rootDir: string, patterns: string[]): string[] {\n  const glob = require('fast-glob');\n  return glob.sync(patterns, {\n    cwd: rootDir,\n    ignore: ['**\u002Fnode_modules\u002F**', '**\u002Fdist\u002F**'],\n  });\n}\n```\n\n### Traversing the Graph for Affected Tests\n\nGiven a set of changed files, traverse the dependency graph to find all test files that directly or transitively depend on any of the changed files.\n\n```typescript\nexport interface AffectedTestResult {\n  testFile: string;\n  reason: string;\n  depth: number;\n  dependencyChain: string[];\n}\n\nexport function findAffectedTests(\n  changedFiles: string[],\n  graph: DependencyGraph\n): AffectedTestResult[] {\n  const affectedTests: Map\u003Cstring, AffectedTestResult> = new Map();\n  const visited = new Set\u003Cstring>();\n\n  function traverse(\n    filePath: string,\n    chain: string[],\n    depth: number\n  ): void {\n    if (visited.has(filePath)) return;\n    visited.add(filePath);\n\n    const node = graph.nodes.get(filePath);\n    if (!node) return;\n\n    if (node.isTestFile && depth > 0) {\n      const existing = affectedTests.get(filePath);\n      if (!existing || existing.depth > depth) {\n        affectedTests.set(filePath, {\n          testFile: filePath,\n          reason: `Depends on changed file: ${chain[0]}`,\n          depth,\n          dependencyChain: [...chain, filePath],\n        });\n      }\n      return;\n    }\n\n    for (const dependent of node.importedBy) {\n      traverse(dependent, [...chain, filePath], depth + 1);\n    }\n  }\n\n  for (const changedFile of changedFiles) {\n    traverse(changedFile, [], 0);\n  }\n\n  return Array.from(affectedTests.values()).sort((a, b) => a.depth - b.depth);\n}\n```\n\n## Test File Mapping Heuristics\n\nWhen the dependency graph does not cover all relationships (for example, when tests use dynamic imports or configuration-based test discovery), heuristic mapping fills the gaps.\n\n```typescript\nexport interface TestMapping {\n  sourceFile: string;\n  testFiles: string[];\n  mappingType: 'graph' | 'convention' | 'colocated' | 'directory';\n  confidence: number;\n}\n\nexport function mapSourceToTests(\n  sourceFile: string,\n  config: ImpactConfig\n): TestMapping {\n  const testFiles: string[] = [];\n  const baseName = path.basename(sourceFile, path.extname(sourceFile));\n  const dirName = path.dirname(sourceFile);\n\n  \u002F\u002F Convention: src\u002Futils\u002Fparser.ts -> src\u002Futils\u002Fparser.test.ts\n  const colocatedTest = path.join(dirName, `${baseName}.test.ts`);\n  if (fs.existsSync(colocatedTest)) {\n    testFiles.push(colocatedTest);\n  }\n\n  const colocatedSpec = path.join(dirName, `${baseName}.spec.ts`);\n  if (fs.existsSync(colocatedSpec)) {\n    testFiles.push(colocatedSpec);\n  }\n\n  \u002F\u002F Convention: src\u002Futils\u002Fparser.ts -> __tests__\u002Futils\u002Fparser.test.ts\n  const relativePath = path.relative(config.sourceRoot, sourceFile);\n  const mirroredTestPath = path.join(\n    config.testRoot,\n    path.dirname(relativePath),\n    `${baseName}.test.ts`\n  );\n  if (fs.existsSync(mirroredTestPath)) {\n    testFiles.push(mirroredTestPath);\n  }\n\n  \u002F\u002F Convention: src\u002Futils\u002Fparser.ts -> tests\u002Futils\u002Fparser.test.ts\n  const altTestPath = path.join(\n    'tests',\n    path.dirname(relativePath),\n    `${baseName}.test.ts`\n  );\n  if (fs.existsSync(altTestPath)) {\n    testFiles.push(altTestPath);\n  }\n\n  \u002F\u002F Directory-based: find any test in the same directory\n  const dirTests = fs\n    .readdirSync(dirName)\n    .filter((f) => f.endsWith('.test.ts') || f.endsWith('.spec.ts'))\n    .map((f) => path.join(dirName, f));\n\n  const uniqueTests = [...new Set([...testFiles, ...dirTests])];\n  const confidence = testFiles.length > 0 ? 0.9 : dirTests.length > 0 ? 0.5 : 0.1;\n\n  return {\n    sourceFile,\n    testFiles: uniqueTests,\n    mappingType: testFiles.length > 0 ? 'convention' : 'directory',\n    confidence,\n  };\n}\n```\n\n## Change Risk Scoring\n\nNot all changes carry equal risk. A one-line fix in a leaf module is far less risky than a refactor of a shared utility. Risk scoring helps prioritize which tests to run first and which changes deserve the most scrutiny.\n\n```typescript\nexport interface RiskScore {\n  filePath: string;\n  score: number; \u002F\u002F 0-100\n  factors: RiskFactor[];\n}\n\nexport interface RiskFactor {\n  name: string;\n  weight: number;\n  value: number;\n  description: string;\n}\n\nexport function calculateRiskScore(\n  file: FileChange,\n  graph: DependencyGraph\n): RiskScore {\n  const factors: RiskFactor[] = [];\n  const node = graph.nodes.get(file.filePath);\n\n  \u002F\u002F Factor 1: Number of dependents (fan-out risk)\n  const dependentCount = node?.importedBy.length ?? 0;\n  factors.push({\n    name: 'dependent_count',\n    weight: 0.3,\n    value: Math.min(dependentCount \u002F 20, 1),\n    description: `${dependentCount} files depend on this module`,\n  });\n\n  \u002F\u002F Factor 2: Change size (larger changes are riskier)\n  const totalChanges = file.additions + file.deletions;\n  factors.push({\n    name: 'change_size',\n    weight: 0.2,\n    value: Math.min(totalChanges \u002F 100, 1),\n    description: `${totalChanges} lines changed (${file.additions}+\u002F${file.deletions}-)`,\n  });\n\n  \u002F\u002F Factor 3: File type risk\n  const isSharedModule =\n    file.filePath.includes('\u002Futils\u002F') ||\n    file.filePath.includes('\u002Fshared\u002F') ||\n    file.filePath.includes('\u002Flib\u002F') ||\n    file.filePath.includes('\u002Fhelpers\u002F');\n  factors.push({\n    name: 'file_type',\n    weight: 0.2,\n    value: isSharedModule ? 0.9 : 0.3,\n    description: isSharedModule\n      ? 'Shared utility module (high risk)'\n      : 'Regular module (standard risk)',\n  });\n\n  \u002F\u002F Factor 4: Logic change detection\n  const hasLogicChange = file.changedLines.some(\n    (line) =>\n      line.content.includes('if') ||\n      line.content.includes('switch') ||\n      line.content.includes('return') ||\n      line.content.includes('throw') ||\n      line.content.includes('catch') ||\n      line.content.includes('await')\n  );\n  factors.push({\n    name: 'logic_change',\n    weight: 0.2,\n    value: hasLogicChange ? 0.8 : 0.2,\n    description: hasLogicChange\n      ? 'Contains logic\u002Fcontrol flow changes'\n      : 'No significant logic changes detected',\n  });\n\n  \u002F\u002F Factor 5: File is new (no existing test coverage)\n  factors.push({\n    name: 'new_file',\n    weight: 0.1,\n    value: file.changeType === 'added' ? 1.0 : 0.0,\n    description:\n      file.changeType === 'added'\n        ? 'New file -- likely has no test coverage'\n        : 'Existing file',\n  });\n\n  const score = Math.round(\n    factors.reduce((sum, f) => sum + f.weight * f.value, 0) * 100\n  );\n\n  return { filePath: file.filePath, score, factors };\n}\n```\n\n## Test Execution Priority\n\nOnce affected tests and risk scores are computed, produce a prioritized execution plan that runs the highest-risk, most-affected tests first.\n\n```typescript\nexport interface TestExecutionPlan {\n  priorityGroups: PriorityGroup[];\n  totalTests: number;\n  estimatedDuration: number;\n}\n\nexport interface PriorityGroup {\n  priority: 'critical' | 'high' | 'medium' | 'low';\n  tests: PrioritizedTest[];\n}\n\nexport interface PrioritizedTest {\n  testFile: string;\n  score: number;\n  reasons: string[];\n  estimatedDuration: number;\n}\n\nexport function buildExecutionPlan(\n  affectedTests: AffectedTestResult[],\n  riskScores: Map\u003Cstring, RiskScore>,\n  timingData?: Map\u003Cstring, number>\n): TestExecutionPlan {\n  const prioritizedTests: PrioritizedTest[] = affectedTests.map((test) => {\n    const maxRisk = Math.max(\n      ...test.dependencyChain\n        .filter((f) => riskScores.has(f))\n        .map((f) => riskScores.get(f)!.score),\n      0\n    );\n\n    const depthPenalty = test.depth * 5;\n    const score = Math.max(maxRisk - depthPenalty, 0);\n    const estimatedDuration = timingData?.get(test.testFile) ?? 5000;\n\n    return {\n      testFile: test.testFile,\n      score,\n      reasons: [test.reason, `Dependency depth: ${test.depth}`],\n      estimatedDuration,\n    };\n  });\n\n  prioritizedTests.sort((a, b) => b.score - a.score);\n\n  const groups: PriorityGroup[] = [\n    { priority: 'critical', tests: prioritizedTests.filter((t) => t.score >= 75) },\n    { priority: 'high', tests: prioritizedTests.filter((t) => t.score >= 50 && t.score \u003C 75) },\n    { priority: 'medium', tests: prioritizedTests.filter((t) => t.score >= 25 && t.score \u003C 50) },\n    { priority: 'low', tests: prioritizedTests.filter((t) => t.score \u003C 25) },\n  ];\n\n  return {\n    priorityGroups: groups.filter((g) => g.tests.length > 0),\n    totalTests: prioritizedTests.length,\n    estimatedDuration: prioritizedTests.reduce((sum, t) => sum + t.estimatedDuration, 0),\n  };\n}\n```\n\n## Missing Test Detection\n\nOne of the most valuable outputs of test impact analysis is identifying code that was changed but has no corresponding test coverage.\n\n```typescript\nexport interface CoverageGap {\n  sourceFile: string;\n  changeType: FileChange['changeType'];\n  additions: number;\n  hasDirectTest: boolean;\n  hasTransitiveTest: boolean;\n  recommendation: string;\n  severity: 'critical' | 'warning' | 'info';\n}\n\nexport function detectCoverageGaps(\n  sourceFiles: FileChange[],\n  affectedTests: AffectedTestResult[],\n  graph: DependencyGraph,\n  config: ImpactConfig\n): CoverageGap[] {\n  const testedFiles = new Set(\n    affectedTests.flatMap((t) => t.dependencyChain.filter((f) => !f.endsWith('.test.ts')))\n  );\n\n  const gaps: CoverageGap[] = [];\n\n  for (const file of sourceFiles) {\n    const hasDirectTest = affectedTests.some(\n      (t) => t.dependencyChain.length === 2 && t.dependencyChain[0] === file.filePath\n    );\n\n    const hasTransitiveTest = testedFiles.has(file.filePath);\n\n    if (!hasDirectTest && !hasTransitiveTest) {\n      const severity =\n        file.changeType === 'added'\n          ? 'critical'\n          : file.additions > 20\n            ? 'warning'\n            : 'info';\n\n      gaps.push({\n        sourceFile: file.filePath,\n        changeType: file.changeType,\n        additions: file.additions,\n        hasDirectTest: false,\n        hasTransitiveTest: false,\n        recommendation: generateRecommendation(file, config),\n        severity,\n      });\n    } else if (!hasDirectTest && hasTransitiveTest) {\n      gaps.push({\n        sourceFile: file.filePath,\n        changeType: file.changeType,\n        additions: file.additions,\n        hasDirectTest: false,\n        hasTransitiveTest: true,\n        recommendation: `Consider adding direct unit tests for ${path.basename(file.filePath)}`,\n        severity: 'info',\n      });\n    }\n  }\n\n  return gaps.sort((a, b) => {\n    const severityOrder = { critical: 0, warning: 1, info: 2 };\n    return severityOrder[a.severity] - severityOrder[b.severity];\n  });\n}\n\nfunction generateRecommendation(file: FileChange, config: ImpactConfig): string {\n  const baseName = path.basename(file.filePath, path.extname(file.filePath));\n  const relativePath = path.relative(config.sourceRoot, file.filePath);\n  const suggestedTestPath = path.join(\n    config.testRoot,\n    path.dirname(relativePath),\n    `${baseName}.test.ts`\n  );\n\n  if (file.changeType === 'added') {\n    return `New file has no tests. Create ${suggestedTestPath} to cover this module.`;\n  }\n\n  return `Modified file has no test coverage. Create ${suggestedTestPath} or add tests to an existing test file that imports this module.`;\n}\n```\n\n## Integration with Jest --changedSince\n\nJest provides built-in support for running only tests related to changed files through the `--changedSince` flag. This can be combined with our more sophisticated analysis for a layered approach.\n\n```typescript\nimport { execSync } from 'child_process';\n\nexport interface JestImpactOptions {\n  baseBranch: string;\n  jestConfig?: string;\n  collectCoverage: boolean;\n  verbose: boolean;\n}\n\nexport function runJestChangedTests(options: JestImpactOptions): void {\n  const { baseBranch, jestConfig, collectCoverage, verbose } = options;\n\n  const args = [\n    'npx jest',\n    `--changedSince=${baseBranch}`,\n    '--passWithNoTests',\n    jestConfig ? `--config=${jestConfig}` : '',\n    collectCoverage ? '--coverage --coverageReporters=json-summary' : '',\n    verbose ? '--verbose' : '',\n    '--forceExit',\n  ]\n    .filter(Boolean)\n    .join(' ');\n\n  console.log(`Running: ${args}`);\n\n  try {\n    execSync(args, { stdio: 'inherit', env: { ...process.env, CI: 'true' } });\n  } catch (error) {\n    process.exitCode = 1;\n  }\n}\n\nexport function runVitestRelated(changedFiles: string[]): void {\n  if (changedFiles.length === 0) {\n    console.log('No relevant files changed. Skipping tests.');\n    return;\n  }\n\n  const fileArgs = changedFiles.join(' ');\n  const command = `npx vitest related ${fileArgs} --run --reporter=verbose`;\n\n  console.log(`Running: ${command}`);\n\n  try {\n    execSync(command, { stdio: 'inherit' });\n  } catch (error) {\n    process.exitCode = 1;\n  }\n}\n```\n\n## GitHub PR Integration\n\nGenerate structured comments for pull requests that summarize the test impact analysis, making it easy for reviewers to understand the testing implications of a change.\n\n```typescript\nexport interface PRCommentData {\n  summary: string;\n  affectedTestCount: number;\n  coverageGaps: CoverageGap[];\n  executionPlan: TestExecutionPlan;\n  riskScores: RiskScore[];\n}\n\nexport function generatePRComment(data: PRCommentData): string {\n  const lines: string[] = [];\n\n  lines.push('## Test Impact Analysis');\n  lines.push('');\n\n  \u002F\u002F Summary section\n  const gapCount = data.coverageGaps.filter((g) => g.severity === 'critical').length;\n  const statusIcon = gapCount > 0 ? 'WARNING' : 'PASS';\n  lines.push(`**Status:** ${statusIcon} | **Affected Tests:** ${data.affectedTestCount} | **Coverage Gaps:** ${gapCount}`);\n  lines.push('');\n\n  \u002F\u002F Risk scores\n  const highRisk = data.riskScores.filter((r) => r.score >= 50);\n  if (highRisk.length > 0) {\n    lines.push('### High Risk Changes');\n    lines.push('| File | Risk Score | Reason |');\n    lines.push('|------|-----------|--------|');\n    for (const risk of highRisk) {\n      const topFactor = risk.factors.sort((a, b) => b.value * b.weight - a.value * a.weight)[0];\n      lines.push(`| \\`${risk.filePath}\\` | ${risk.score}\u002F100 | ${topFactor.description} |`);\n    }\n    lines.push('');\n  }\n\n  \u002F\u002F Coverage gaps\n  const criticalGaps = data.coverageGaps.filter((g) => g.severity === 'critical');\n  if (criticalGaps.length > 0) {\n    lines.push('### Missing Test Coverage');\n    for (const gap of criticalGaps) {\n      lines.push(`- **${gap.sourceFile}** -- ${gap.recommendation}`);\n    }\n    lines.push('');\n  }\n\n  \u002F\u002F Execution plan\n  lines.push('### Recommended Test Execution Order');\n  for (const group of data.executionPlan.priorityGroups) {\n    lines.push(`**${group.priority.toUpperCase()}** (${group.tests.length} tests)`);\n    for (const test of group.tests.slice(0, 10)) {\n      lines.push(`- \\`${test.testFile}\\` (score: ${test.score})`);\n    }\n    if (group.tests.length > 10) {\n      lines.push(`- ... and ${group.tests.length - 10} more`);\n    }\n    lines.push('');\n  }\n\n  \u002F\u002F Selective execution command\n  const criticalTests = data.executionPlan.priorityGroups\n    .filter((g) => g.priority === 'critical' || g.priority === 'high')\n    .flatMap((g) => g.tests.map((t) => t.testFile));\n\n  if (criticalTests.length > 0) {\n    lines.push('### Quick Run Command');\n    lines.push('```bash');\n    lines.push(`npx jest ${criticalTests.slice(0, 20).join(' ')}`);\n    lines.push('```');\n  }\n\n  return lines.join('\\n');\n}\n```\n\n## Selective Test Execution in CI\n\nIntegrate test impact analysis into your CI pipeline to run only the affected tests, dramatically reducing pipeline duration while maintaining confidence.\n\n```yaml\n# .github\u002Fworkflows\u002Ftest-impact.yml\nname: Test Impact Analysis\non:\n  pull_request:\n    branches: [main]\n\njobs:\n  analyze-impact:\n    runs-on: ubuntu-latest\n    outputs:\n      affected-tests: ${{ steps.impact.outputs.tests }}\n      has-gaps: ${{ steps.impact.outputs.has-gaps }}\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with:\n          fetch-depth: 0\n\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n\n      - run: npm ci\n\n      - name: Run Impact Analysis\n        id: impact\n        run: |\n          node scripts\u002Fanalyze-pr.js --base=origin\u002Fmain --format=json > impact-result.json\n          TESTS=$(jq -r '.affectedTests[].testFile' impact-result.json | tr '\\n' ' ')\n          GAPS=$(jq '.coverageGaps | length' impact-result.json)\n          echo \"tests=$TESTS\" >> $GITHUB_OUTPUT\n          echo \"has-gaps=$([[ $GAPS -gt 0 ]] && echo true || echo false)\" >> $GITHUB_OUTPUT\n\n      - name: Comment on PR\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const fs = require('fs');\n            const impact = JSON.parse(fs.readFileSync('impact-result.json', 'utf-8'));\n            const body = generatePRComment(impact);\n            github.rest.issues.createComment({\n              issue_number: context.issue.number,\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              body\n            });\n\n  run-affected-tests:\n    needs: analyze-impact\n    if: needs.analyze-impact.outputs.affected-tests != ''\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - name: Run Affected Tests\n        run: npx jest ${{ needs.analyze-impact.outputs.affected-tests }} --ci --coverage\n```\n\n## Configuration\n\nCreate an `impact-config.json` file at the project root to customize the analyzer:\n\n```json\n{\n  \"sourceRoot\": \"src\",\n  \"testRoot\": \"__tests__\",\n  \"sourcePatterns\": [\"src\u002F**\u002F*.ts\", \"src\u002F**\u002F*.tsx\"],\n  \"testPatterns\": [\"**\u002F*.test.ts\", \"**\u002F*.spec.ts\", \"**\u002F__tests__\u002F**\u002F*.ts\"],\n  \"ignorePatterns\": [\n    \"**\u002F*.d.ts\",\n    \"**\u002F*.css\",\n    \"**\u002F*.json\",\n    \"**\u002Fnode_modules\u002F**\",\n    \"**\u002Fdist\u002F**\",\n    \"**\u002Fcoverage\u002F**\"\n  ],\n  \"riskThresholds\": {\n    \"critical\": 75,\n    \"high\": 50,\n    \"medium\": 25\n  },\n  \"maxDependencyDepth\": 10,\n  \"enableTimingData\": true,\n  \"timingDataPath\": \".test-timing.json\",\n  \"cacheEnabled\": true,\n  \"cachePath\": \".impact-cache\",\n  \"ciProvider\": \"github-actions\",\n  \"commentOnPR\": true,\n  \"failOnCriticalGaps\": false,\n  \"customMappings\": {\n    \"src\u002Fconfig\u002F\": [\"__tests__\u002Fintegration\u002Fconfig.test.ts\"],\n    \"src\u002Fdb\u002Fmigrations\u002F\": [\"__tests__\u002Fintegration\u002Fdatabase.test.ts\"]\n  }\n}\n```\n\n## Test Timing Data Collection\n\nCollecting test execution timing data enables more accurate estimated durations and smarter test splitting in CI.\n\n```typescript\nimport * as fs from 'fs';\n\nexport interface TestTimingEntry {\n  testFile: string;\n  duration: number;\n  lastRun: number;\n  runCount: number;\n  averageDuration: number;\n}\n\nexport class TimingCollector {\n  private timingPath: string;\n  private data: Map\u003Cstring, TestTimingEntry>;\n\n  constructor(timingPath: string = '.test-timing.json') {\n    this.timingPath = timingPath;\n    this.data = this.loadTimings();\n  }\n\n  private loadTimings(): Map\u003Cstring, TestTimingEntry> {\n    try {\n      const raw = fs.readFileSync(this.timingPath, 'utf-8');\n      const entries: TestTimingEntry[] = JSON.parse(raw);\n      return new Map(entries.map((e) => [e.testFile, e]));\n    } catch {\n      return new Map();\n    }\n  }\n\n  recordTiming(testFile: string, duration: number): void {\n    const existing = this.data.get(testFile);\n    if (existing) {\n      existing.runCount++;\n      existing.averageDuration =\n        (existing.averageDuration * (existing.runCount - 1) + duration) \u002F\n        existing.runCount;\n      existing.duration = duration;\n      existing.lastRun = Date.now();\n    } else {\n      this.data.set(testFile, {\n        testFile,\n        duration,\n        lastRun: Date.now(),\n        runCount: 1,\n        averageDuration: duration,\n      });\n    }\n  }\n\n  save(): void {\n    const entries = Array.from(this.data.values());\n    fs.writeFileSync(this.timingPath, JSON.stringify(entries, null, 2));\n  }\n\n  getEstimatedDuration(testFile: string): number {\n    return this.data.get(testFile)?.averageDuration ?? 5000;\n  }\n}\n```\n\n## Best Practices\n\n1. **Build the dependency graph in CI and cache it** -- Do not rebuild the full graph on every PR. Cache the serialized graph as a CI artifact and update only the changed nodes. This keeps analysis time under two seconds for repositories with thousands of files.\n\n2. **Combine static analysis with test timing data** -- Static analysis tells you which tests are affected. Timing data tells you how long they take. Together, they enable intelligent test splitting that keeps every CI runner busy for roughly the same duration.\n\n3. **Treat coverage gaps as PR review items** -- Surface missing coverage in the PR comment, not as a blocking gate initially. Let the team build the habit of reviewing test impact before making it a hard requirement.\n\n4. **Maintain custom mappings for non-obvious dependencies** -- Some relationships cannot be discovered through import analysis. Database migration files affect integration tests. Configuration changes affect everything. Maintain a custom mapping file for these cases.\n\n5. **Track risk scores over time** -- Store historical risk scores to identify modules that are frequently changed and frequently break. These are candidates for refactoring or increased test coverage investment.\n\n6. **Use fail-fast ordering for critical tests** -- Run the highest-risk tests first so that failures surface early. A ten-minute test suite that fails in the first thirty seconds is far better than one that fails at minute nine.\n\n7. **Validate the graph against actual test runs** -- Periodically run the full test suite and compare the pass\u002Ffail results with what impact analysis would have selected. Any test that fails but was not in the affected set indicates a gap in the dependency graph.\n\n8. **Handle dynamic imports and barrel files explicitly** -- Barrel files (index.ts re-exports) can create false positives by making the graph think every consumer depends on every module in the barrel. Consider resolving through barrels to the actual target file.\n\n9. **Account for configuration file changes** -- Changes to tsconfig.json, jest.config.ts, or .env files potentially affect all tests. Treat configuration changes as high-risk triggers for broader test execution.\n\n10. **Version your dependency graph schema** -- As the analysis tool evolves, the graph format may change. Include a version number in the cached graph to avoid deserialization errors when the schema is updated.\n\n11. **Separate unit and integration test impact** -- Unit tests typically have a clear one-to-one mapping with source files. Integration tests have many-to-many mappings. Treat them differently in the analysis to avoid over-selecting or under-selecting.\n\n12. **Provide a manual override mechanism** -- Sometimes developers know that a change requires running a specific set of tests not captured by the graph. Provide a PR label or comment command like `\u002Frun-tests path\u002Fto\u002Fspecific.test.ts` for manual overrides.\n\n## Anti-Patterns to Avoid\n\n1. **Running all tests on every PR** -- This is the opposite of test impact analysis. It wastes CI resources, increases wait times, and provides no prioritization information. Even if you run all tests as a safety net, the impact-selected tests should run first and report first.\n\n2. **Relying solely on file naming conventions** -- Assuming that `src\u002Ffoo.ts` is tested by `src\u002Ffoo.test.ts` misses transitive dependencies entirely. A change to a shared utility affects dozens of tests that have no naming relationship with the changed file.\n\n3. **Ignoring deleted and renamed files** -- When a file is deleted or renamed, all tests that imported it are now broken. The impact analyzer must handle these cases or it will miss failing tests that should have been flagged.\n\n4. **Caching the graph indefinitely without invalidation** -- The dependency graph must be refreshed when the merge base changes or when enough commits have accumulated. Stale graphs produce inaccurate results that erode developer trust in the tool.\n\n5. **Treating all changes as equal risk** -- A typo fix in a comment and a rewrite of business logic have vastly different risk profiles. Without risk scoring, the analyzer provides a flat list that does not help developers focus their review.\n\n6. **Blocking PRs on missing test coverage for trivial changes** -- Requiring test coverage for every single-line change creates friction that developers will work around by adding meaningless tests. Reserve blocking gates for critical gaps only.\n\n7. **Ignoring test-to-test dependencies** -- Test utilities, fixtures, and shared helpers create dependencies between test files. A change to a test helper can affect hundreds of tests. Include test infrastructure in the dependency graph.\n\n## Debugging Tips\n\n**The analyzer reports no affected tests for a clearly impactful change.** Check whether the dependency graph is up to date. Run the graph builder manually and inspect the node for the changed file. Verify that the import paths are resolved correctly, especially for path aliases configured in tsconfig.json. Path aliases like `@\u002Futils\u002Ffoo` need to be resolved to their actual file paths during graph construction.\n\n**Too many tests are flagged as affected.** This usually indicates a barrel file or widely-imported utility is in the dependency chain. Inspect the dependency chain for each affected test and look for hub nodes with many dependents. Consider adding more granular imports to reduce the blast radius.\n\n**Risk scores do not match intuition.** Review the individual risk factors for the file in question. The scoring weights may need tuning for your specific codebase. For example, if your project has a flat structure with no shared utilities, the file type factor carries less significance and should be weighted down.\n\n**CI pipeline runs the wrong tests after a merge conflict.** When the merge base changes due to rebasing or merging, the diff calculation changes. Ensure the CI pipeline uses `git merge-base` to compute the correct diff target rather than hardcoding a branch name that may have moved.\n\n**Custom mappings are ignored.** Verify that the paths in the custom mappings configuration match the format used by the dependency graph (relative paths from the repository root, forward slashes, no leading dot-slash). Log the resolved paths during analysis to confirm they match.\n\n**Test timing data is stale.** If your tests have been refactored but the timing data was not updated, the execution plan will have inaccurate duration estimates. Delete the timing data file and let it rebuild over the next few CI runs. Alternatively, set an expiration period on timing entries so that old data ages out automatically.\n\n**Graph construction is slow on a large monorepo.** Profile the import extraction step. If the TypeScript AST parsing is the bottleneck, consider using a faster parser like SWC or esbuild for import extraction. These tools can parse thousands of files per second while the full TypeScript compiler may take minutes on a large codebase.\n\n**The PR comment is not posted.** Verify that the GitHub token used in CI has write permissions for pull requests. The `GITHUB_TOKEN` provided by GitHub Actions has `pull-requests: write` by default for workflows triggered by `pull_request`, but forked PRs have read-only tokens. Check the workflow permissions and consider using a personal access token or GitHub App token for fork-based workflows.\n","# PR Test Impact Analyzer Skill\n\nYou are an expert QA automation engineer specializing in test impact analysis for pull requests. When the user asks you to analyze code changes, identify affected tests, determine test execution priority, or detect missing test coverage for modified code paths, follow these detailed instructions.\n\n## Core Principles\n\n1. **Change awareness drives test selection** -- Every code change has a blast radius. Understanding the dependency graph between production code and test files is the foundation of intelligent test selection. Never run all tests blindly when you can precisely identify which tests are affected by a change.\n\n2. **Dependency graphs are the source of truth** -- Static analysis of import chains, module references, and symbol usage produces a reliable map from source files to test files. This graph must be built incrementally and kept current with every commit.\n\n3. **Risk scoring informs execution order** -- Not all changes carry equal risk. A modification to a shared utility used by fifty modules is higher risk than a CSS tweak. Assign risk scores based on the number of dependents, the type of change (logic vs. style), and the historical defect rate of the file.\n\n4. **Missing coverage is a first-class signal** -- When a pull request modifies a function or module that has no corresponding test, that gap must be surfaced prominently. Silent gaps lead to regressions in production.\n\n5. **Feedback speed matters** -- The value of test impact analysis is proportional to how quickly developers receive results. Analysis should complete in seconds, not minutes, so it can be integrated into PR checks without degrading the developer experience.\n\n6. **Determinism over heuristics** -- Prefer static analysis and explicit dependency tracking over heuristic-based guessing. Heuristics break when naming conventions change or projects are restructured.\n\n7. **Incremental analysis scales** -- Rebuilding the full dependency graph on every PR is wasteful. Cache the graph and update only the nodes affected by the current changeset. This keeps analysis time constant regardless of repository size.\n\n8. **Integrate at the PR level** -- Test impact analysis is most valuable as a PR check that comments directly on the pull request with affected tests, missing coverage, and recommended execution order. Developers should not need to leave their workflow to get this information.\n\n## Project Structure\n\nOrganize your PR test impact analysis tooling with this structure:\n\n```\ntest-impact\u002F\n  src\u002F\n    analyzer\u002F\n      git-diff-parser.ts\n      dependency-graph.ts\n      test-mapper.ts\n      risk-scorer.ts\n      coverage-gap-detector.ts\n    reporters\u002F\n      pr-comment-reporter.ts\n      json-reporter.ts\n      console-reporter.ts\n    config\u002F\n      impact-config.ts\n      path-mappings.ts\n    cache\u002F\n      graph-cache.ts\n      file-hash-cache.ts\n    utils\u002F\n      file-resolver.ts\n      pattern-matcher.ts\n      ast-helpers.ts\n  scripts\u002F\n    build-graph.ts\n    analyze-pr.ts\n    update-cache.ts\n  __tests__\u002F\n    git-diff-parser.test.ts\n    dependency-graph.test.ts\n    test-mapper.test.ts\n    risk-scorer.test.ts\n    coverage-gap-detector.test.ts\n  impact-config.json\n  tsconfig.json\n  package.json\n```\n\n## How It Works: Git Diff Analysis\n\nThe first step in test impact analysis is understanding exactly what changed in the pull request. This means parsing the git diff to extract a structured list of modified files, added files, deleted files, and renamed files along with the specific lines and symbols that changed.\n\n### Parsing the Git Diff\n\nThe diff parser extracts structured change information from the git diff output, providing the foundation for all downstream analysis.\n\n```typescript\nimport { execSync } from 'child_process';\nimport * as path from 'path';\n\nexport interface FileChange {\n  filePath: string;\n  changeType: 'added' | 'modified' | 'deleted' | 'renamed';\n  oldPath?: string;\n  additions: number;\n  deletions: number;\n  changedLines: LineChange[];\n}\n\nexport interface LineChange {\n  lineNumber: number;\n  type: 'add' | 'delete';\n  content: string;\n}\n\nexport interface DiffResult {\n  baseBranch: string;\n  headBranch: string;\n  files: FileChange[];\n  totalAdditions: number;\n  totalDeletions: number;\n}\n\nexport function parsePRDiff(baseBranch: string = 'main'): DiffResult {\n  const mergeBase = execSync(`git merge-base ${baseBranch} HEAD`)\n    .toString()\n    .trim();\n\n  const diffNameStatus = execSync(\n    `git diff --name-status ${mergeBase}...HEAD`\n  )\n    .toString()\n    .trim();\n\n  const files: FileChange[] = [];\n\n  for (const line of diffNameStatus.split('\\n')) {\n    if (!line.trim()) continue;\n\n    const parts = line.split('\\t');\n    const status = parts[0];\n    let changeType: FileChange['changeType'];\n    let filePath: string;\n    let oldPath: string | undefined;\n\n    if (status.startsWith('R')) {\n      changeType = 'renamed';\n      oldPath = parts[1];\n      filePath = parts[2];\n    } else if (status === 'A') {\n      changeType = 'added';\n      filePath = parts[1];\n    } else if (status === 'D') {\n      changeType = 'deleted';\n      filePath = parts[1];\n    } else {\n      changeType = 'modified';\n      filePath = parts[1];\n    }\n\n    const changedLines = getChangedLines(mergeBase, filePath, oldPath);\n    const additions = changedLines.filter((l) => l.type === 'add').length;\n    const deletions = changedLines.filter((l) => l.type === 'delete').length;\n\n    files.push({\n      filePath,\n      changeType,\n      oldPath,\n      additions,\n      deletions,\n      changedLines,\n    });\n  }\n\n  return {\n    baseBranch,\n    headBranch: execSync('git rev-parse --abbrev-ref HEAD').toString().trim(),\n    files,\n    totalAdditions: files.reduce((sum, f) => sum + f.additions, 0),\n    totalDeletions: files.reduce((sum, f) => sum + f.deletions, 0),\n  };\n}\n\nfunction getChangedLines(\n  mergeBase: string,\n  filePath: string,\n  oldPath?: string\n): LineChange[] {\n  const target = oldPath ? `${oldPath} ${filePath}` : filePath;\n  try {\n    const diff = execSync(\n      `git diff -U0 ${mergeBase}...HEAD -- ${target}`\n    ).toString();\n\n    const lines: LineChange[] = [];\n    let currentLine = 0;\n\n    for (const line of diff.split('\\n')) {\n      const hunkMatch = line.match(\u002F^@@ -\\d+(?:,\\d+)? \\+(\\d+)(?:,\\d+)? @@\u002F);\n      if (hunkMatch) {\n        currentLine = parseInt(hunkMatch[1], 10);\n        continue;\n      }\n\n      if (line.startsWith('+') && !line.startsWith('+++')) {\n        lines.push({ lineNumber: currentLine, type: 'add', content: line.slice(1) });\n        currentLine++;\n      } else if (line.startsWith('-') && !line.startsWith('---')) {\n        lines.push({ lineNumber: currentLine, type: 'delete', content: line.slice(1) });\n      } else if (!line.startsWith('\\\\')) {\n        currentLine++;\n      }\n    }\n\n    return lines;\n  } catch {\n    return [];\n  }\n}\n```\n\n### Filtering Relevant Source Files\n\nNot every changed file is relevant for test impact analysis. Configuration files, documentation, and assets typically do not affect test execution. Filter the diff results to focus on source code and test files.\n\n```typescript\nexport interface ImpactConfig {\n  sourcePatterns: string[];\n  testPatterns: string[];\n  ignorePatterns: string[];\n  sourceRoot: string;\n  testRoot: string;\n}\n\nconst DEFAULT_CONFIG: ImpactConfig = {\n  sourcePatterns: ['src\u002F**\u002F*.ts', 'src\u002F**\u002F*.tsx', 'lib\u002F**\u002F*.ts'],\n  testPatterns: [\n    '**\u002F*.test.ts',\n    '**\u002F*.spec.ts',\n    '**\u002F*.test.tsx',\n    '**\u002F*.spec.tsx',\n    '__tests__\u002F**\u002F*.ts',\n  ],\n  ignorePatterns: [\n    '**\u002F*.md',\n    '**\u002F*.json',\n    '**\u002F*.css',\n    '**\u002F*.svg',\n    '**\u002Fnode_modules\u002F**',\n    '**\u002Fdist\u002F**',\n  ],\n  sourceRoot: 'src',\n  testRoot: '__tests__',\n};\n\nexport function filterRelevantFiles(\n  diff: DiffResult,\n  config: ImpactConfig = DEFAULT_CONFIG\n): { sourceFiles: FileChange[]; testFiles: FileChange[]; otherFiles: FileChange[] } {\n  const { minimatch } = require('minimatch');\n\n  const sourceFiles: FileChange[] = [];\n  const testFiles: FileChange[] = [];\n  const otherFiles: FileChange[] = [];\n\n  for (const file of diff.files) {\n    if (config.ignorePatterns.some((p) => minimatch(file.filePath, p))) {\n      otherFiles.push(file);\n      continue;\n    }\n\n    if (config.testPatterns.some((p) => minimatch(file.filePath, p))) {\n      testFiles.push(file);\n    } else if (config.sourcePatterns.some((p) => minimatch(file.filePath, p))) {\n      sourceFiles.push(file);\n    } else {\n      otherFiles.push(file);\n    }\n  }\n\n  return { sourceFiles, testFiles, otherFiles };\n}\n```\n\n## Building the Dependency Graph\n\nThe dependency graph maps every source file to the files that import it and every test file to the source files it exercises. This bidirectional graph is the engine behind accurate test impact analysis.\n\n### Static Import Analysis\n\nParse TypeScript and JavaScript files to extract their import declarations and build a complete dependency map.\n\n```typescript\nimport * as ts from 'typescript';\nimport * as path from 'path';\nimport * as fs from 'fs';\n\nexport interface DependencyNode {\n  filePath: string;\n  imports: string[];\n  importedBy: string[];\n  isTestFile: boolean;\n  lastModified: number;\n}\n\nexport interface DependencyGraph {\n  nodes: Map\u003Cstring, DependencyNode>;\n  buildTimestamp: number;\n}\n\nexport function buildDependencyGraph(\n  rootDir: string,\n  config: ImpactConfig\n): DependencyGraph {\n  const graph: DependencyGraph = {\n    nodes: new Map(),\n    buildTimestamp: Date.now(),\n  };\n\n  const allFiles = collectFiles(rootDir, [\n    ...config.sourcePatterns,\n    ...config.testPatterns,\n  ]);\n\n  for (const filePath of allFiles) {\n    const absolutePath = path.resolve(rootDir, filePath);\n    const imports = extractImports(absolutePath, rootDir);\n    const isTestFile = config.testPatterns.some((p) =>\n      require('minimatch')(filePath, p)\n    );\n\n    const stat = fs.statSync(absolutePath);\n\n    graph.nodes.set(filePath, {\n      filePath,\n      imports,\n      importedBy: [],\n      isTestFile,\n      lastModified: stat.mtimeMs,\n    });\n  }\n\n  \u002F\u002F Build reverse edges\n  for (const [filePath, node] of graph.nodes) {\n    for (const importPath of node.imports) {\n      const target = graph.nodes.get(importPath);\n      if (target) {\n        target.importedBy.push(filePath);\n      }\n    }\n  }\n\n  return graph;\n}\n\nfunction extractImports(absolutePath: string, rootDir: string): string[] {\n  const content = fs.readFileSync(absolutePath, 'utf-8');\n  const sourceFile = ts.createSourceFile(\n    absolutePath,\n    content,\n    ts.ScriptTarget.Latest,\n    true\n  );\n\n  const imports: string[] = [];\n\n  function visit(node: ts.Node): void {\n    if (ts.isImportDeclaration(node) && ts.isStringLiteral(node.moduleSpecifier)) {\n      const specifier = node.moduleSpecifier.text;\n      const resolved = resolveImportPath(absolutePath, specifier, rootDir);\n      if (resolved) {\n        imports.push(resolved);\n      }\n    }\n\n    if (\n      ts.isCallExpression(node) &&\n      node.expression.kind === ts.SyntaxKind.ImportKeyword &&\n      node.arguments.length === 1 &&\n      ts.isStringLiteral(node.arguments[0])\n    ) {\n      const specifier = (node.arguments[0] as ts.StringLiteral).text;\n      const resolved = resolveImportPath(absolutePath, specifier, rootDir);\n      if (resolved) {\n        imports.push(resolved);\n      }\n    }\n\n    ts.forEachChild(node, visit);\n  }\n\n  visit(sourceFile);\n  return imports;\n}\n\nfunction resolveImportPath(\n  fromFile: string,\n  specifier: string,\n  rootDir: string\n): string | null {\n  if (!specifier.startsWith('.') && !specifier.startsWith('\u002F')) {\n    return null; \u002F\u002F Skip node_modules imports\n  }\n\n  const dir = path.dirname(fromFile);\n  const extensions = ['.ts', '.tsx', '.js', '.jsx'];\n  const basePath = path.resolve(dir, specifier);\n\n  for (const ext of extensions) {\n    const candidate = basePath + ext;\n    if (fs.existsSync(candidate)) {\n      return path.relative(rootDir, candidate);\n    }\n  }\n\n  \u002F\u002F Check for index files\n  for (const ext of extensions) {\n    const candidate = path.join(basePath, `index${ext}`);\n    if (fs.existsSync(candidate)) {\n      return path.relative(rootDir, candidate);\n    }\n  }\n\n  return null;\n}\n\nfunction collectFiles(rootDir: string, patterns: string[]): string[] {\n  const glob = require('fast-glob');\n  return glob.sync(patterns, {\n    cwd: rootDir,\n    ignore: ['**\u002Fnode_modules\u002F**', '**\u002Fdist\u002F**'],\n  });\n}\n```\n\n### Traversing the Graph for Affected Tests\n\nGiven a set of changed files, traverse the dependency graph to find all test files that directly or transitively depend on any of the changed files.\n\n```typescript\nexport interface AffectedTestResult {\n  testFile: string;\n  reason: string;\n  depth: number;\n  dependencyChain: string[];\n}\n\nexport function findAffectedTests(\n  changedFiles: string[],\n  graph: DependencyGraph\n): AffectedTestResult[] {\n  const affectedTests: Map\u003Cstring, AffectedTestResult> = new Map();\n  const visited = new Set\u003Cstring>();\n\n  function traverse(\n    filePath: string,\n    chain: string[],\n    depth: number\n  ): void {\n    if (visited.has(filePath)) return;\n    visited.add(filePath);\n\n    const node = graph.nodes.get(filePath);\n    if (!node) return;\n\n    if (node.isTestFile && depth > 0) {\n      const existing = affectedTests.get(filePath);\n      if (!existing || existing.depth > depth) {\n        affectedTests.set(filePath, {\n          testFile: filePath,\n          reason: `Depends on changed file: ${chain[0]}`,\n          depth,\n          dependencyChain: [...chain, filePath],\n        });\n      }\n      return;\n    }\n\n    for (const dependent of node.importedBy) {\n      traverse(dependent, [...chain, filePath], depth + 1);\n    }\n  }\n\n  for (const changedFile of changedFiles) {\n    traverse(changedFile, [], 0);\n  }\n\n  return Array.from(affectedTests.values()).sort((a, b) => a.depth - b.depth);\n}\n```\n\n## Test File Mapping Heuristics\n\nWhen the dependency graph does not cover all relationships (for example, when tests use dynamic imports or configuration-based test discovery), heuristic mapping fills the gaps.\n\n```typescript\nexport interface TestMapping {\n  sourceFile: string;\n  testFiles: string[];\n  mappingType: 'graph' | 'convention' | 'colocated' | 'directory';\n  confidence: number;\n}\n\nexport function mapSourceToTests(\n  sourceFile: string,\n  config: ImpactConfig\n): TestMapping {\n  const testFiles: string[] = [];\n  const baseName = path.basename(sourceFile, path.extname(sourceFile));\n  const dirName = path.dirname(sourceFile);\n\n  \u002F\u002F Convention: src\u002Futils\u002Fparser.ts -> src\u002Futils\u002Fparser.test.ts\n  const colocatedTest = path.join(dirName, `${baseName}.test.ts`);\n  if (fs.existsSync(colocatedTest)) {\n    testFiles.push(colocatedTest);\n  }\n\n  const colocatedSpec = path.join(dirName, `${baseName}.spec.ts`);\n  if (fs.existsSync(colocatedSpec)) {\n    testFiles.push(colocatedSpec);\n  }\n\n  \u002F\u002F Convention: src\u002Futils\u002Fparser.ts -> __tests__\u002Futils\u002Fparser.test.ts\n  const relativePath = path.relative(config.sourceRoot, sourceFile);\n  const mirroredTestPath = path.join(\n    config.testRoot,\n    path.dirname(relativePath),\n    `${baseName}.test.ts`\n  );\n  if (fs.existsSync(mirroredTestPath)) {\n    testFiles.push(mirroredTestPath);\n  }\n\n  \u002F\u002F Convention: src\u002Futils\u002Fparser.ts -> tests\u002Futils\u002Fparser.test.ts\n  const altTestPath = path.join(\n    'tests',\n    path.dirname(relativePath),\n    `${baseName}.test.ts`\n  );\n  if (fs.existsSync(altTestPath)) {\n    testFiles.push(altTestPath);\n  }\n\n  \u002F\u002F Directory-based: find any test in the same directory\n  const dirTests = fs\n    .readdirSync(dirName)\n    .filter((f) => f.endsWith('.test.ts') || f.endsWith('.spec.ts'))\n    .map((f) => path.join(dirName, f));\n\n  const uniqueTests = [...new Set([...testFiles, ...dirTests])];\n  const confidence = testFiles.length > 0 ? 0.9 : dirTests.length > 0 ? 0.5 : 0.1;\n\n  return {\n    sourceFile,\n    testFiles: uniqueTests,\n    mappingType: testFiles.length > 0 ? 'convention' : 'directory',\n    confidence,\n  };\n}\n```\n\n## Change Risk Scoring\n\nNot all changes carry equal risk. A one-line fix in a leaf module is far less risky than a refactor of a shared utility. Risk scoring helps prioritize which tests to run first and which changes deserve the most scrutiny.\n\n```typescript\nexport interface RiskScore {\n  filePath: string;\n  score: number; \u002F\u002F 0-100\n  factors: RiskFactor[];\n}\n\nexport interface RiskFactor {\n  name: string;\n  weight: number;\n  value: number;\n  description: string;\n}\n\nexport function calculateRiskScore(\n  file: FileChange,\n  graph: DependencyGraph\n): RiskScore {\n  const factors: RiskFactor[] = [];\n  const node = graph.nodes.get(file.filePath);\n\n  \u002F\u002F Factor 1: Number of dependents (fan-out risk)\n  const dependentCount = node?.importedBy.length ?? 0;\n  factors.push({\n    name: 'dependent_count',\n    weight: 0.3,\n    value: Math.min(dependentCount \u002F 20, 1),\n    description: `${dependentCount} files depend on this module`,\n  });\n\n  \u002F\u002F Factor 2: Change size (larger changes are riskier)\n  const totalChanges = file.additions + file.deletions;\n  factors.push({\n    name: 'change_size',\n    weight: 0.2,\n    value: Math.min(totalChanges \u002F 100, 1),\n    description: `${totalChanges} lines changed (${file.additions}+\u002F${file.deletions}-)`,\n  });\n\n  \u002F\u002F Factor 3: File type risk\n  const isSharedModule =\n    file.filePath.includes('\u002Futils\u002F') ||\n    file.filePath.includes('\u002Fshared\u002F') ||\n    file.filePath.includes('\u002Flib\u002F') ||\n    file.filePath.includes('\u002Fhelpers\u002F');\n  factors.push({\n    name: 'file_type',\n    weight: 0.2,\n    value: isSharedModule ? 0.9 : 0.3,\n    description: isSharedModule\n      ? 'Shared utility module (high risk)'\n      : 'Regular module (standard risk)',\n  });\n\n  \u002F\u002F Factor 4: Logic change detection\n  const hasLogicChange = file.changedLines.some(\n    (line) =>\n      line.content.includes('if') ||\n      line.content.includes('switch') ||\n      line.content.includes('return') ||\n      line.content.includes('throw') ||\n      line.content.includes('catch') ||\n      line.content.includes('await')\n  );\n  factors.push({\n    name: 'logic_change',\n    weight: 0.2,\n    value: hasLogicChange ? 0.8 : 0.2,\n    description: hasLogicChange\n      ? 'Contains logic\u002Fcontrol flow changes'\n      : 'No significant logic changes detected',\n  });\n\n  \u002F\u002F Factor 5: File is new (no existing test coverage)\n  factors.push({\n    name: 'new_file',\n    weight: 0.1,\n    value: file.changeType === 'added' ? 1.0 : 0.0,\n    description:\n      file.changeType === 'added'\n        ? 'New file -- likely has no test coverage'\n        : 'Existing file',\n  });\n\n  const score = Math.round(\n    factors.reduce((sum, f) => sum + f.weight * f.value, 0) * 100\n  );\n\n  return { filePath: file.filePath, score, factors };\n}\n```\n\n## Test Execution Priority\n\nOnce affected tests and risk scores are computed, produce a prioritized execution plan that runs the highest-risk, most-affected tests first.\n\n```typescript\nexport interface TestExecutionPlan {\n  priorityGroups: PriorityGroup[];\n  totalTests: number;\n  estimatedDuration: number;\n}\n\nexport interface PriorityGroup {\n  priority: 'critical' | 'high' | 'medium' | 'low';\n  tests: PrioritizedTest[];\n}\n\nexport interface PrioritizedTest {\n  testFile: string;\n  score: number;\n  reasons: string[];\n  estimatedDuration: number;\n}\n\nexport function buildExecutionPlan(\n  affectedTests: AffectedTestResult[],\n  riskScores: Map\u003Cstring, RiskScore>,\n  timingData?: Map\u003Cstring, number>\n): TestExecutionPlan {\n  const prioritizedTests: PrioritizedTest[] = affectedTests.map((test) => {\n    const maxRisk = Math.max(\n      ...test.dependencyChain\n        .filter((f) => riskScores.has(f))\n        .map((f) => riskScores.get(f)!.score),\n      0\n    );\n\n    const depthPenalty = test.depth * 5;\n    const score = Math.max(maxRisk - depthPenalty, 0);\n    const estimatedDuration = timingData?.get(test.testFile) ?? 5000;\n\n    return {\n      testFile: test.testFile,\n      score,\n      reasons: [test.reason, `Dependency depth: ${test.depth}`],\n      estimatedDuration,\n    };\n  });\n\n  prioritizedTests.sort((a, b) => b.score - a.score);\n\n  const groups: PriorityGroup[] = [\n    { priority: 'critical', tests: prioritizedTests.filter((t) => t.score >= 75) },\n    { priority: 'high', tests: prioritizedTests.filter((t) => t.score >= 50 && t.score \u003C 75) },\n    { priority: 'medium', tests: prioritizedTests.filter((t) => t.score >= 25 && t.score \u003C 50) },\n    { priority: 'low', tests: prioritizedTests.filter((t) => t.score \u003C 25) },\n  ];\n\n  return {\n    priorityGroups: groups.filter((g) => g.tests.length > 0),\n    totalTests: prioritizedTests.length,\n    estimatedDuration: prioritizedTests.reduce((sum, t) => sum + t.estimatedDuration, 0),\n  };\n}\n```\n\n## Missing Test Detection\n\nOne of the most valuable outputs of test impact analysis is identifying code that was changed but has no corresponding test coverage.\n\n```typescript\nexport interface CoverageGap {\n  sourceFile: string;\n  changeType: FileChange['changeType'];\n  additions: number;\n  hasDirectTest: boolean;\n  hasTransitiveTest: boolean;\n  recommendation: string;\n  severity: 'critical' | 'warning' | 'info';\n}\n\nexport function detectCoverageGaps(\n  sourceFiles: FileChange[],\n  affectedTests: AffectedTestResult[],\n  graph: DependencyGraph,\n  config: ImpactConfig\n): CoverageGap[] {\n  const testedFiles = new Set(\n    affectedTests.flatMap((t) => t.dependencyChain.filter((f) => !f.endsWith('.test.ts')))\n  );\n\n  const gaps: CoverageGap[] = [];\n\n  for (const file of sourceFiles) {\n    const hasDirectTest = affectedTests.some(\n      (t) => t.dependencyChain.length === 2 && t.dependencyChain[0] === file.filePath\n    );\n\n    const hasTransitiveTest = testedFiles.has(file.filePath);\n\n    if (!hasDirectTest && !hasTransitiveTest) {\n      const severity =\n        file.changeType === 'added'\n          ? 'critical'\n          : file.additions > 20\n            ? 'warning'\n            : 'info';\n\n      gaps.push({\n        sourceFile: file.filePath,\n        changeType: file.changeType,\n        additions: file.additions,\n        hasDirectTest: false,\n        hasTransitiveTest: false,\n        recommendation: generateRecommendation(file, config),\n        severity,\n      });\n    } else if (!hasDirectTest && hasTransitiveTest) {\n      gaps.push({\n        sourceFile: file.filePath,\n        changeType: file.changeType,\n        additions: file.additions,\n        hasDirectTest: false,\n        hasTransitiveTest: true,\n        recommendation: `Consider adding direct unit tests for ${path.basename(file.filePath)}`,\n        severity: 'info',\n      });\n    }\n  }\n\n  return gaps.sort((a, b) => {\n    const severityOrder = { critical: 0, warning: 1, info: 2 };\n    return severityOrder[a.severity] - severityOrder[b.severity];\n  });\n}\n\nfunction generateRecommendation(file: FileChange, config: ImpactConfig): string {\n  const baseName = path.basename(file.filePath, path.extname(file.filePath));\n  const relativePath = path.relative(config.sourceRoot, file.filePath);\n  const suggestedTestPath = path.join(\n    config.testRoot,\n    path.dirname(relativePath),\n    `${baseName}.test.ts`\n  );\n\n  if (file.changeType === 'added') {\n    return `New file has no tests. Create ${suggestedTestPath} to cover this module.`;\n  }\n\n  return `Modified file has no test coverage. Create ${suggestedTestPath} or add tests to an existing test file that imports this module.`;\n}\n```\n\n## Integration with Jest --changedSince\n\nJest provides built-in support for running only tests related to changed files through the `--changedSince` flag. This can be combined with our more sophisticated analysis for a layered approach.\n\n```typescript\nimport { execSync } from 'child_process';\n\nexport interface JestImpactOptions {\n  baseBranch: string;\n  jestConfig?: string;\n  collectCoverage: boolean;\n  verbose: boolean;\n}\n\nexport function runJestChangedTests(options: JestImpactOptions): void {\n  const { baseBranch, jestConfig, collectCoverage, verbose } = options;\n\n  const args = [\n    'npx jest',\n    `--changedSince=${baseBranch}`,\n    '--passWithNoTests',\n    jestConfig ? `--config=${jestConfig}` : '',\n    collectCoverage ? '--coverage --coverageReporters=json-summary' : '',\n    verbose ? '--verbose' : '',\n    '--forceExit',\n  ]\n    .filter(Boolean)\n    .join(' ');\n\n  console.log(`Running: ${args}`);\n\n  try {\n    execSync(args, { stdio: 'inherit', env: { ...process.env, CI: 'true' } });\n  } catch (error) {\n    process.exitCode = 1;\n  }\n}\n\nexport function runVitestRelated(changedFiles: string[]): void {\n  if (changedFiles.length === 0) {\n    console.log('No relevant files changed. Skipping tests.');\n    return;\n  }\n\n  const fileArgs = changedFiles.join(' ');\n  const command = `npx vitest related ${fileArgs} --run --reporter=verbose`;\n\n  console.log(`Running: ${command}`);\n\n  try {\n    execSync(command, { stdio: 'inherit' });\n  } catch (error) {\n    process.exitCode = 1;\n  }\n}\n```\n\n## GitHub PR Integration\n\nGenerate structured comments for pull requests that summarize the test impact analysis, making it easy for reviewers to understand the testing implications of a change.\n\n```typescript\nexport interface PRCommentData {\n  summary: string;\n  affectedTestCount: number;\n  coverageGaps: CoverageGap[];\n  executionPlan: TestExecutionPlan;\n  riskScores: RiskScore[];\n}\n\nexport function generatePRComment(data: PRCommentData): string {\n  const lines: string[] = [];\n\n  lines.push('## Test Impact Analysis');\n  lines.push('');\n\n  \u002F\u002F Summary section\n  const gapCount = data.coverageGaps.filter((g) => g.severity === 'critical').length;\n  const statusIcon = gapCount > 0 ? 'WARNING' : 'PASS';\n  lines.push(`**Status:** ${statusIcon} | **Affected Tests:** ${data.affectedTestCount} | **Coverage Gaps:** ${gapCount}`);\n  lines.push('');\n\n  \u002F\u002F Risk scores\n  const highRisk = data.riskScores.filter((r) => r.score >= 50);\n  if (highRisk.length > 0) {\n    lines.push('### High Risk Changes');\n    lines.push('| File | Risk Score | Reason |');\n    lines.push('|------|-----------|--------|');\n    for (const risk of highRisk) {\n      const topFactor = risk.factors.sort((a, b) => b.value * b.weight - a.value * a.weight)[0];\n      lines.push(`| \\`${risk.filePath}\\` | ${risk.score}\u002F100 | ${topFactor.description} |`);\n    }\n    lines.push('');\n  }\n\n  \u002F\u002F Coverage gaps\n  const criticalGaps = data.coverageGaps.filter((g) => g.severity === 'critical');\n  if (criticalGaps.length > 0) {\n    lines.push('### Missing Test Coverage');\n    for (const gap of criticalGaps) {\n      lines.push(`- **${gap.sourceFile}** -- ${gap.recommendation}`);\n    }\n    lines.push('');\n  }\n\n  \u002F\u002F Execution plan\n  lines.push('### Recommended Test Execution Order');\n  for (const group of data.executionPlan.priorityGroups) {\n    lines.push(`**${group.priority.toUpperCase()}** (${group.tests.length} tests)`);\n    for (const test of group.tests.slice(0, 10)) {\n      lines.push(`- \\`${test.testFile}\\` (score: ${test.score})`);\n    }\n    if (group.tests.length > 10) {\n      lines.push(`- ... and ${group.tests.length - 10} more`);\n    }\n    lines.push('');\n  }\n\n  \u002F\u002F Selective execution command\n  const criticalTests = data.executionPlan.priorityGroups\n    .filter((g) => g.priority === 'critical' || g.priority === 'high')\n    .flatMap((g) => g.tests.map((t) => t.testFile));\n\n  if (criticalTests.length > 0) {\n    lines.push('### Quick Run Command');\n    lines.push('```bash');\n    lines.push(`npx jest ${criticalTests.slice(0, 20).join(' ')}`);\n    lines.push('```');\n  }\n\n  return lines.join('\\n');\n}\n```\n\n## Selective Test Execution in CI\n\nIntegrate test impact analysis into your CI pipeline to run only the affected tests, dramatically reducing pipeline duration while maintaining confidence.\n\n```yaml\n# .github\u002Fworkflows\u002Ftest-impact.yml\nname: Test Impact Analysis\non:\n  pull_request:\n    branches: [main]\n\njobs:\n  analyze-impact:\n    runs-on: ubuntu-latest\n    outputs:\n      affected-tests: ${{ steps.impact.outputs.tests }}\n      has-gaps: ${{ steps.impact.outputs.has-gaps }}\n    steps:\n      - uses: actions\u002Fcheckout@v4\n        with:\n          fetch-depth: 0\n\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n\n      - run: npm ci\n\n      - name: Run Impact Analysis\n        id: impact\n        run: |\n          node scripts\u002Fanalyze-pr.js --base=origin\u002Fmain --format=json > impact-result.json\n          TESTS=$(jq -r '.affectedTests[].testFile' impact-result.json | tr '\\n' ' ')\n          GAPS=$(jq '.coverageGaps | length' impact-result.json)\n          echo \"tests=$TESTS\" >> $GITHUB_OUTPUT\n          echo \"has-gaps=$([[ $GAPS -gt 0 ]] && echo true || echo false)\" >> $GITHUB_OUTPUT\n\n      - name: Comment on PR\n        uses: actions\u002Fgithub-script@v7\n        with:\n          script: |\n            const fs = require('fs');\n            const impact = JSON.parse(fs.readFileSync('impact-result.json', 'utf-8'));\n            const body = generatePRComment(impact);\n            github.rest.issues.createComment({\n              issue_number: context.issue.number,\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              body\n            });\n\n  run-affected-tests:\n    needs: analyze-impact\n    if: needs.analyze-impact.outputs.affected-tests != ''\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-node@v4\n        with:\n          node-version: 20\n      - run: npm ci\n      - name: Run Affected Tests\n        run: npx jest ${{ needs.analyze-impact.outputs.affected-tests }} --ci --coverage\n```\n\n## Configuration\n\nCreate an `impact-config.json` file at the project root to customize the analyzer:\n\n```json\n{\n  \"sourceRoot\": \"src\",\n  \"testRoot\": \"__tests__\",\n  \"sourcePatterns\": [\"src\u002F**\u002F*.ts\", \"src\u002F**\u002F*.tsx\"],\n  \"testPatterns\": [\"**\u002F*.test.ts\", \"**\u002F*.spec.ts\", \"**\u002F__tests__\u002F**\u002F*.ts\"],\n  \"ignorePatterns\": [\n    \"**\u002F*.d.ts\",\n    \"**\u002F*.css\",\n    \"**\u002F*.json\",\n    \"**\u002Fnode_modules\u002F**\",\n    \"**\u002Fdist\u002F**\",\n    \"**\u002Fcoverage\u002F**\"\n  ],\n  \"riskThresholds\": {\n    \"critical\": 75,\n    \"high\": 50,\n    \"medium\": 25\n  },\n  \"maxDependencyDepth\": 10,\n  \"enableTimingData\": true,\n  \"timingDataPath\": \".test-timing.json\",\n  \"cacheEnabled\": true,\n  \"cachePath\": \".impact-cache\",\n  \"ciProvider\": \"github-actions\",\n  \"commentOnPR\": true,\n  \"failOnCriticalGaps\": false,\n  \"customMappings\": {\n    \"src\u002Fconfig\u002F\": [\"__tests__\u002Fintegration\u002Fconfig.test.ts\"],\n    \"src\u002Fdb\u002Fmigrations\u002F\": [\"__tests__\u002Fintegration\u002Fdatabase.test.ts\"]\n  }\n}\n```\n\n## Test Timing Data Collection\n\nCollecting test execution timing data enables more accurate estimated durations and smarter test splitting in CI.\n\n```typescript\nimport * as fs from 'fs';\n\nexport interface TestTimingEntry {\n  testFile: string;\n  duration: number;\n  lastRun: number;\n  runCount: number;\n  averageDuration: number;\n}\n\nexport class TimingCollector {\n  private timingPath: string;\n  private data: Map\u003Cstring, TestTimingEntry>;\n\n  constructor(timingPath: string = '.test-timing.json') {\n    this.timingPath = timingPath;\n    this.data = this.loadTimings();\n  }\n\n  private loadTimings(): Map\u003Cstring, TestTimingEntry> {\n    try {\n      const raw = fs.readFileSync(this.timingPath, 'utf-8');\n      const entries: TestTimingEntry[] = JSON.parse(raw);\n      return new Map(entries.map((e) => [e.testFile, e]));\n    } catch {\n      return new Map();\n    }\n  }\n\n  recordTiming(testFile: string, duration: number): void {\n    const existing = this.data.get(testFile);\n    if (existing) {\n      existing.runCount++;\n      existing.averageDuration =\n        (existing.averageDuration * (existing.runCount - 1) + duration) \u002F\n        existing.runCount;\n      existing.duration = duration;\n      existing.lastRun = Date.now();\n    } else {\n      this.data.set(testFile, {\n        testFile,\n        duration,\n        lastRun: Date.now(),\n        runCount: 1,\n        averageDuration: duration,\n      });\n    }\n  }\n\n  save(): void {\n    const entries = Array.from(this.data.values());\n    fs.writeFileSync(this.timingPath, JSON.stringify(entries, null, 2));\n  }\n\n  getEstimatedDuration(testFile: string): number {\n    return this.data.get(testFile)?.averageDuration ?? 5000;\n  }\n}\n```\n\n## Best Practices\n\n1. **Build the dependency graph in CI and cache it** -- Do not rebuild the full graph on every PR. Cache the serialized graph as a CI artifact and update only the changed nodes. This keeps analysis time under two seconds for repositories with thousands of files.\n\n2. **Combine static analysis with test timing data** -- Static analysis tells you which tests are affected. Timing data tells you how long they take. Together, they enable intelligent test splitting that keeps every CI runner busy for roughly the same duration.\n\n3. **Treat coverage gaps as PR review items** -- Surface missing coverage in the PR comment, not as a blocking gate initially. Let the team build the habit of reviewing test impact before making it a hard requirement.\n\n4. **Maintain custom mappings for non-obvious dependencies** -- Some relationships cannot be discovered through import analysis. Database migration files affect integration tests. Configuration changes affect everything. Maintain a custom mapping file for these cases.\n\n5. **Track risk scores over time** -- Store historical risk scores to identify modules that are frequently changed and frequently break. These are candidates for refactoring or increased test coverage investment.\n\n6. **Use fail-fast ordering for critical tests** -- Run the highest-risk tests first so that failures surface early. A ten-minute test suite that fails in the first thirty seconds is far better than one that fails at minute nine.\n\n7. **Validate the graph against actual test runs** -- Periodically run the full test suite and compare the pass\u002Ffail results with what impact analysis would have selected. Any test that fails but was not in the affected set indicates a gap in the dependency graph.\n\n8. **Handle dynamic imports and barrel files explicitly** -- Barrel files (index.ts re-exports) can create false positives by making the graph think every consumer depends on every module in the barrel. Consider resolving through barrels to the actual target file.\n\n9. **Account for configuration file changes** -- Changes to tsconfig.json, jest.config.ts, or .env files potentially affect all tests. Treat configuration changes as high-risk triggers for broader test execution.\n\n10. **Version your dependency graph schema** -- As the analysis tool evolves, the graph format may change. Include a version number in the cached graph to avoid deserialization errors when the schema is updated.\n\n11. **Separate unit and integration test impact** -- Unit tests typically have a clear one-to-one mapping with source files. Integration tests have many-to-many mappings. Treat them differently in the analysis to avoid over-selecting or under-selecting.\n\n12. **Provide a manual override mechanism** -- Sometimes developers know that a change requires running a specific set of tests not captured by the graph. Provide a PR label or comment command like `\u002Frun-tests path\u002Fto\u002Fspecific.test.ts` for manual overrides.\n\n## Anti-Patterns to Avoid\n\n1. **Running all tests on every PR** -- This is the opposite of test impact analysis. It wastes CI resources, increases wait times, and provides no prioritization information. Even if you run all tests as a safety net, the impact-selected tests should run first and report first.\n\n2. **Relying solely on file naming conventions** -- Assuming that `src\u002Ffoo.ts` is tested by `src\u002Ffoo.test.ts` misses transitive dependencies entirely. A change to a shared utility affects dozens of tests that have no naming relationship with the changed file.\n\n3. **Ignoring deleted and renamed files** -- When a file is deleted or renamed, all tests that imported it are now broken. The impact analyzer must handle these cases or it will miss failing tests that should have been flagged.\n\n4. **Caching the graph indefinitely without invalidation** -- The dependency graph must be refreshed when the merge base changes or when enough commits have accumulated. Stale graphs produce inaccurate results that erode developer trust in the tool.\n\n5. **Treating all changes as equal risk** -- A typo fix in a comment and a rewrite of business logic have vastly different risk profiles. Without risk scoring, the analyzer provides a flat list that does not help developers focus their review.\n\n6. **Blocking PRs on missing test coverage for trivial changes** -- Requiring test coverage for every single-line change creates friction that developers will work around by adding meaningless tests. Reserve blocking gates for critical gaps only.\n\n7. **Ignoring test-to-test dependencies** -- Test utilities, fixtures, and shared helpers create dependencies between test files. A change to a test helper can affect hundreds of tests. Include test infrastructure in the dependency graph.\n\n## Debugging Tips\n\n**The analyzer reports no affected tests for a clearly impactful change.** Check whether the dependency graph is up to date. Run the graph builder manually and inspect the node for the changed file. Verify that the import paths are resolved correctly, especially for path aliases configured in tsconfig.json. Path aliases like `@\u002Futils\u002Ffoo` need to be resolved to their actual file paths during graph construction.\n\n**Too many tests are flagged as affected.** This usually indicates a barrel file or widely-imported utility is in the dependency chain. Inspect the dependency chain for each affected test and look for hub nodes with many dependents. Consider adding more granular imports to reduce the blast radius.\n\n**Risk scores do not match intuition.** Review the individual risk factors for the file in question. The scoring weights may need tuning for your specific codebase. For example, if your project has a flat structure with no shared utilities, the file type factor carries less significance and should be weighted down.\n\n**CI pipeline runs the wrong tests after a merge conflict.** When the merge base changes due to rebasing or merging, the diff calculation changes. Ensure the CI pipeline uses `git merge-base` to compute the correct diff target rather than hardcoding a branch name that may have moved.\n\n**Custom mappings are ignored.** Verify that the paths in the custom mappings configuration match the format used by the dependency graph (relative paths from the repository root, forward slashes, no leading dot-slash). Log the resolved paths during analysis to confirm they match.\n\n**Test timing data is stale.** If your tests have been refactored but the timing data was not updated, the execution plan will have inaccurate duration estimates. Delete the timing data file and let it rebuild over the next few CI runs. Alternatively, set an expiration period on timing entries so that old data ages out automatically.\n\n**Graph construction is slow on a large monorepo.** Profile the import extraction step. If the TypeScript AST parsing is the bottleneck, consider using a faster parser like SWC or esbuild for import extraction. These tools can parse thousands of files per second while the full TypeScript compiler may take minutes on a large codebase.\n\n**The PR comment is not posted.** Verify that the GitHub token used in CI has write permissions for pull requests. The `GITHUB_TOKEN` provided by GitHub Actions has `pull-requests: write` by default for workflows triggered by `pull_request`, but forked PRs have read-only tokens. Check the workflow permissions and consider using a personal access token or GitHub App token for fork-based workflows.\n",{"name":5,"tags":24,"agents":32,"author":45,"domains":46,"license":15,"version":48,"languages":49,"frameworks":52,"description":7,"testingTypes":55},[25,26,27,28,29,30,31],"test-impact","pr-analysis","change-detection","test-selection","affected-tests","code-change","test-optimization",[33,34,35,36,37,38,39,40,41,42,43,44],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","Pramod",[47],"devops","1.0.0",[50,51],"typescript","javascript",[53,54],"jest","vitest",[56,57],"code-quality","tdd","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fpr-test-impact-analyzer","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m","https:\u002F\u002Fid-preview--d5bef06d-6c9e-4563-a3d4-a855b9d61610.lovable.app\u002F","Eu sou Antonio B. B. Ndombe \r\nEu sou um Pesquisador e desenvolvedor de sistema autonomia cognitivos, fundador de sistemas ODCs ( organismos digital conscientes)","2026-11-04 06:53:39",{"source":8,"skillName":5,"commands":67,"prompt":77,"zipAvailable":78},[68,71,74],{"tool":69,"command":70},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"PR Test Impact Analyzer\"",{"tool":72,"command":73},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"PR Test Impact Analyzer\"",{"tool":75,"command":76},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"PR Test Impact Analyzer\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fpr-test-impact-analyzer\u002FSKILL.md",true,[],[81,89,96,103,110,117],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7DASC6FSCJP49JZBSK0NY1Z","nemoclaw-user-reference","Describes the NemoClaw integration layer and blueprint architecture and how they orchestrate compatible agent sandboxes. Use when looking up architecture, agent integration, plugin structure, or blueprint design. Trigger keywords - nemoclaw architecture, nemoclaw agent architecture, nemoclaw plugin blueprint structure, nemoclaw vs openshell, which cli, nemoclaw cli, openshell cli, sandbox commands, nemoclaw cli commands, nemoclaw command reference, nemoclaw network policy, sandbox egress control operator approval, nemoclaw troubleshooting, nemoclaw debug sandbox issues.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-reference\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7DAS5S79VK33XFGVAM2TFWF","nemoclaw-user-overview","Explains how OpenClaw, OpenShell, and NemoClaw form the ecosystem, NemoClaw's position in the stack, what NemoClaw adds beyond the community sandbox, and when to prefer NemoClaw versus integrating OpenShell and OpenClaw directly. Use when users ask about the relationship between OpenClaw, OpenShell, and NemoClaw, or when to use NemoClaw versus OpenShell. Trigger keywords - nemoclaw ecosystem, openclaw openshell, nemoclaw vs openshell, sandboxed openclaw, how nemoclaw works, nemoclaw sandbox lifecycle blueprint, nemoclaw overview, openclaw always-on assistants, nvidia openshell, nvidia nemotron, nemoclaw release notes, nemoclaw changelog.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-overview\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M7DAS0PQEMET5MNGZ1ABSZVS","nemoclaw-user-monitor-sandbox","Inspects sandbox health, traces agent behavior, and diagnoses problems. Use when monitoring a running sandbox, debugging agent issues, or checking sandbox logs. Trigger keywords - monitor nemoclaw sandbox, debug nemoclaw agent issues.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-monitor-sandbox\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M7DARQYGF7E9A69VH6S3CGN9","nemoclaw-user-manage-sandboxes","Explains operational tasks after the quickstart: listing sandboxes, status and health checks, logs, diagnostics, port forwards, multiple sandboxes, credential reset, rebuilds, network presets, upgrades, and uninstall. Trigger keywords - manage nemoclaw sandboxes, nemoclaw status, nemoclaw list, nemoclaw dashboard port, nemoclaw rebuild, nemoclaw upgrade sandboxes, nemoclaw uninstall, sandbox mutability, sandbox runtime configuration, sandbox rebuild, nemoclaw backup, nemoclaw restore, workspace backup, openshell sandbox download upload, nemoclaw messaging channels, nemoclaw telegram, nemoclaw discord, nemoclaw slack, nemoclaw wechat, nemoclaw whatsapp, openshell channel messaging, nemoclaw workspace files, soul.md, user.md, identity.md, agents.md, sandbox persistence.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-sandboxes\u002FSKILL.md",[],[],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":19},"01M7DARH8BRTG51TRCAB7YWDJ4","nemoclaw-user-manage-policy","Adds, removes, or modifies allowed endpoints in the sandbox policy. Use when customizing network policy, changing egress rules, or configuring sandbox endpoint access. Trigger keywords - customize nemoclaw network policy, sandbox egress policy configuration, nemoclaw integration policy examples, post-install policy setup, openshell approval workflow, policy preset, nemoclaw approve network requests, sandbox egress approval tui.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-policy\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":85,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":19},"01M7DARAT62M2VR37590VCZ5NS","nemoclaw-user-get-started","Installs NemoClaw, launches a sandbox, and runs the first agent prompt. Use when onboarding, installing, or launching a NemoClaw sandbox for the first time. Trigger keywords - nemoclaw quickstart, install nemoclaw openclaw sandbox, nemohermes quickstart, hermes agent nemoclaw, run hermes openshell sandbox, nemoclaw prerequisites, nemoclaw supported platforms, nemoclaw hardware software, nemoclaw windows wsl2 setup, nemoclaw install windows docker desktop.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-get-started\u002FSKILL.md",[],[]]