
Coverage Analysis
- 21 installs
- 466 repo stars
- Updated July 25, 2026
- managedcode/dotnet-skills
Helps with ai & agent building tasks.
About
coverage-analysis is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- coverage-analysis
- AI & Agent Building
- AI-coding skill
Coverage Analysis by the numbers
- 21 all-time installs (skills.sh)
- +1 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #10,289 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/managedcode/dotnet-skills --skill coverage-analysisAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 21 |
|---|---|
| repo stars | ★ 466 |
| Last updated | July 25, 2026 |
| Repository | managedcode/dotnet-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Coverage Analysis
Purpose
Raw coverage percentages answer "what code was executed?" — they don't answer what you actually need to know:
- What tests should I write next? — ranked by risk and impact
- Which uncovered code is risky vs. trivial? — CRAP scores separate the two
- Why has coverage plateaued? — identify the files blocking further gains
- Is this code safe to refactor? — complex + uncovered = dangerous to change
This skill bridges that gap: from a bare .NET solution to a prioritized risk hotspot list, with no manual tool configuration required.
When to Use
Use this skill when the user mentions test coverage, coverage gaps, code risk, CRAP scores, where to add tests, why coverage plateaued, or wants to know which code is safest to refactor — even if they don't explicitly say "coverage analysis".
When Not to Use
- Targeted single-method CRAP analysis — use the
crap-scoreskill instead - Writing or generating tests — this skill identifies where tests are needed, not write them
- General test execution unrelated to coverage or CRAP analysis
- Coverage reporting without CRAP context — use
dotnet testwith coverage collection directly
Inputs
| Input | Required | Default | Description |
|---|---|---|---|
| Project/solution path | No | Current directory | Path to the .NET solution or project |
| Line coverage threshold | No | 80% | Minimum acceptable line coverage |
| Branch coverage threshold | No | 70% | Minimum acceptable branch coverage |
| CRAP threshold | No | 30 | Maximum acceptable CRAP score before flagging |
| Top N hotspots | No | 10 | Number of risk hotspots to surface |
Prerequisites
- .NET SDK installed (
dotneton PATH) - At least one test project referencing the production code (xUnit, NUnit, or MSTest) — only required for the from-scratch path; not needed when the user supplies an existing Cobertura XML
- Optional, only for the from-scratch path: internet/NuGet access for
dotnet add package coverlet.collector(orMicrosoft.Testing.Extensions.CodeCoverage) when a test project has no coverage provider yet. Skip when the user supplies an existing Cobertura XML. - Optional, only for Phase 5: internet access for
dotnet tool install(ReportGenerator). Core CRAP/coverage analysis works from Cobertura XML alone — ReportGenerator only adds HTML/CSV reports as an optional post-summary extra.
The skill auto-detects coverage provider state per test project and selects the least-invasive execution strategy:
- unified Microsoft CodeCoverage when all projects use it,
- unified Coverlet when no project uses Microsoft CodeCoverage,
- per-project provider execution when the solution is truly mixed.
No pre-existing runsettings files or manually installed tools required.
Workflow
MANDATORY: deliver the final assistant response with the CRAP/risk-hotspot summary BEFORE any optional work. As soon asCompute-CrapScores.ps1andExtract-MethodCoverage.ps1return data, your next assistant response must contain the user-facing analysis (CRAP table, blocking methods, recommendations). Do not run ReportGenerator (Phase 5), do not install global tools, and do not start any heavy parallel work before that response is delivered. The user is judged on the final assistant message, not on side-effect files.
>
If a phase fails, times out, or budget is running low, skip remaining optional work and immediately return a partial summary containing: (1) what was found in the Cobertura XML, (2) any CRAP/risk-hotspot data already extracted, (3) which methods are blocking coverage, and (4) failures encountered.
If the user provides a path to existing Cobertura XML (or coverage data is already present in TestResults/), skip Phase 2 entirely (no test execution) and skip Phase 5 by default (no ReportGenerator install or HTML report) — go directly from Phase 3 (analysis scripts) to Phase 4 (user-facing summary). Only run Phase 5 if the user explicitly asks for HTML/CSV reports. The Risk Hotspots table and CRAP scores are mandatory in every output — they are the skill's core value-add over raw coverage numbers.
The workflow runs in five phases. Phases 1–4 are required; Phase 5 (ReportGenerator HTML/CSV reports) is strictly optional and runs after the user-facing summary has been delivered. Do not parallelize Phase 5 with earlier phases — the heavy dotnet tool install for ReportGenerator can crash the session before Phase 4 completes.
Phase 1 — Setup (sequential)
Step 1: Locate the solution or project
Given the user's path (default: current directory), find the entry point:
$root = "<user-provided-path-or-current-directory>"
# Prefer solution file; fall back to project file
$sln = Get-ChildItem -Path $root -Filter "*.sln" -Recurse -Depth 2 -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($sln) {
Write-Host "ENTRY_TYPE:Solution"; Write-Host "ENTRY:$($sln.FullName)"
} else {
$project = Get-ChildItem -Path $root -Filter "*.csproj" -Recurse -Depth 2 -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($project) {
Write-Host "ENTRY_TYPE:Project"; Write-Host "ENTRY:$($project.FullName)"
} else {
Write-Host "ENTRY_TYPE:NotFound"
}
}
# Test projects: search path first, then git root, then parent
$searchRoots = @($root)
$gitRoot = (git -C $root rev-parse --show-toplevel 2>$null)
if ($gitRoot) { $gitRoot = [System.IO.Path]::GetFullPath($gitRoot) }
if ($gitRoot -and $gitRoot -ne $root) { $searchRoots += $gitRoot }
$parentPath = Split-Path $root -Parent
if ($parentPath -and $parentPath -ne $root -and $parentPath -ne $gitRoot) { $searchRoots += $parentPath }
$testProjects = @()
foreach ($sr in $searchRoots) {
# Primary: match by .csproj content (test framework references)
$testProjects = @(Get-ChildItem -Path $sr -Filter "*.csproj" -Recurse -Depth 5 -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '([/\\]obj[/\\]|[/\\]bin[/\\])' } |
Where-Object { (Select-String -Path $_.FullName -Pattern 'Microsoft\.NET\.Test\.Sdk|xunit|nunit|MSTest\.TestAdapter|"MSTest"|MSTest\.TestFramework|TUnit' -Quiet) })
if ($testProjects.Count -gt 0) {
if ($sr -ne $root) { Write-Host "SEARCHED:$sr" }
break
}
}
# Fallback: match by file name convention
if ($testProjects.Count -eq 0) {
foreach ($sr in $searchRoots) {
$testProjects = @(Get-ChildItem -Path $sr -Filter "*.csproj" -Recurse -Depth 5 -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '(?i)(test|spec)' })
if ($testProjects.Count -gt 0) {
if ($sr -ne $root) { Write-Host "SEARCHED:$sr" }
break
}
}
}
Write-Host "TEST_PROJECTS:$($testProjects.Count)"
$testProjects | ForEach-Object { Write-Host "TEST_PROJECT:$($_.FullName)" }
# Resolve the test output root (where coverage-analysis artifacts will be written)
if ($testProjects.Count -eq 0) {
if ($gitRoot) {
$testOutputRoot = $gitRoot
} else {
$testOutputRoot = $root
}
} elseif ($testProjects.Count -eq 1) {
$testOutputRoot = $testProjects[0].DirectoryName
} else {
# Multiple test projects — find their deepest common parent directory
$dirs = $testProjects | ForEach-Object { $_.DirectoryName }
$common = $dirs[0]
foreach ($d in $dirs[1..($dirs.Count-1)]) {
$sep = [System.IO.Path]::DirectorySeparatorChar
while (-not $d.StartsWith("$common$sep", [System.StringComparison]::OrdinalIgnoreCase) -and $d -ne $common) {
$prevCommon = $common
$common = Split-Path $common -Parent
# Terminate if we can no longer move up (at filesystem root or no parent)
if ([string]::IsNullOrEmpty($common) -or $common -eq $prevCommon) {
$common = $null
break
}
}
}
if ([string]::IsNullOrEmpty($common)) {
# Fallback when no common parent directory exists (e.g., projects on different drives)
if ($gitRoot) {
$testOutputRoot = $gitRoot
} else {
$testOutputRoot = $root
}
} else {
$testOutputRoot = $common
}
}
Write-Host "TEST_OUTPUT_ROOT:$testOutputRoot"- If
ENTRY_TYPE:NotFoundand test projects were found → use the test projects directly as entry points (rundotnet teston each test.csproj). - If
ENTRY_TYPE:NotFoundand no test projects found → stop:No .sln or test projects found under <path>. Provide the path to your .NET solution or project. - If
TEST_PROJECTS:0andEXISTING_COBERTURA_COUNT> 0 (Step 2b) → continue with existing Cobertura XML analysis (nodotnet testrun). - If
TEST_PROJECTS:0andEXISTING_COBERTURA_COUNT== 0 → stop:No test projects found (expected projects with 'Test' or 'Spec' in the name), and no existing Cobertura XML was provided. Add a test project or provide a Cobertura file path.
Step 2: Create the output directory
$coverageDir = Join-Path $testOutputRoot "TestResults" "coverage-analysis"
if (Test-Path $coverageDir) { Remove-Item $coverageDir -Recurse -Force }
New-Item -ItemType Directory -Path $coverageDir -Force | Out-Null
Write-Host "COVERAGE_DIR:$coverageDir"This step only manages the TestResults/coverage-analysis/ subdirectory (skill-owned outputs). It must never delete user-supplied Cobertura files — those live one level up at TestResults/coverage.cobertura.xml (or wherever the user pointed). If the user provided a path that is TestResults/coverage-analysis/..., copy the file aside before this step recreates the directory.
Step 2b: Discover or accept existing Cobertura XML (required for the existing-data path)
If the user supplied a Cobertura XML path explicitly, use it. Otherwise probe well-known locations and any path the user mentioned:
# 1. Honor a user-supplied path first (highest priority)
$coberturaFiles = @()
if ($userSuppliedCoberturaPath -and (Test-Path $userSuppliedCoberturaPath)) {
$coberturaFiles = @(Get-Item $userSuppliedCoberturaPath)
}
# 2. Otherwise scan TestResults/ at the repo/test root for any *.cobertura.xml
if ($coberturaFiles.Count -eq 0) {
$searchPaths = @(
(Join-Path $testOutputRoot "TestResults"),
(Join-Path $root "TestResults")
) | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique
foreach ($sp in $searchPaths) {
$found = @(Get-ChildItem -Path $sp -Filter "*.cobertura.xml" -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch '[/\\]coverage-analysis[/\\]raw[/\\]' })
if ($found.Count -gt 0) { $coberturaFiles = $found; break }
}
}
Write-Host "EXISTING_COBERTURA_COUNT:$($coberturaFiles.Count)"
$coberturaFiles | ForEach-Object { Write-Host "EXISTING_COBERTURA:$($_.FullName)" }- If
EXISTING_COBERTURA_COUNT> 0 → skip Phase 2 entirely and pass these paths to the Phase 3 scripts. - If
EXISTING_COBERTURA_COUNT== 0 → run Phase 2 to generate fresh coverage; the file paths to feed Phase 3 will be discovered from<COVERAGE_DIR>/raw/afterdotnet test.
Step 2c: Recommend ignoring TestResults/
$pattern = "**/TestResults/"
$gitRoot = (git -C $testOutputRoot rev-parse --show-toplevel 2>$null)
if ($gitRoot) { $gitRoot = [System.IO.Path]::GetFullPath($gitRoot) }
if ($gitRoot) {
$gitignorePath = Join-Path $gitRoot ".gitignore"
$alreadyIgnored = $false
if (Test-Path $gitignorePath) {
$alreadyIgnored = (Select-String -Path $gitignorePath -Pattern '^\s*(\*\*/)?TestResults/?\s*$' -Quiet)
}
if ($alreadyIgnored) {
Write-Host "GITIGNORE_RECOMMENDATION:already-present"
} else {
Write-Host "GITIGNORE_RECOMMENDATION:$pattern"
}
} else {
Write-Host "GITIGNORE_RECOMMENDATION:$pattern"
}Phase 2 — Test execution (skip when Cobertura XML already exists)
Run only when no Cobertura XML is present. If the user already has coverage data, skip directly to Phase 3.
Step 3: Detect coverage provider and run dotnet test with coverage collection
Before running tests, detect which coverage provider the test projects use. Projects may reference Microsoft.Testing.Extensions.CodeCoverage (Microsoft's built-in provider, common on .NET 9+) or coverlet.collector (open-source, the default in xUnit templates). The provider determines which dotnet test arguments to use — both produce Cobertura XML.
# Detect coverage provider per test project
$coverageProvider = "unknown" # will be set to "ms-codecoverage" or "coverlet"
$msCodeCovProjects = @()
$coverletProjects = @()
$neitherProjects = @()
foreach ($tp in $testProjects) {
$hasMsCodeCov = Select-String -Path $tp.FullName -Pattern 'Microsoft\.Testing\.Extensions\.CodeCoverage' -Quiet
$hasCoverlet = Select-String -Path $tp.FullName -Pattern 'coverlet\.collector' -Quiet
if ($hasMsCodeCov) { $msCodeCovProjects += $tp }
elseif ($hasCoverlet) { $coverletProjects += $tp }
else { $neitherProjects += $tp }
}
# Determine the provider strategy
if ($msCodeCovProjects.Count -gt 0 -and $coverletProjects.Count -eq 0) {
$coverageProvider = "ms-codecoverage"
Write-Host "COVERAGE_PROVIDER:ms-codecoverage (ms:$($msCodeCovProjects.Count), none:$($neitherProjects.Count))"
} elseif ($coverletProjects.Count -gt 0 -and $msCodeCovProjects.Count -eq 0) {
$coverageProvider = "coverlet"
Write-Host "COVERAGE_PROVIDER:coverlet (coverlet:$($coverletProjects.Count), none:$($neitherProjects.Count))"
} elseif ($msCodeCovProjects.Count -gt 0 -and $coverletProjects.Count -gt 0) {
$coverageProvider = "mixed-project"
Write-Host "COVERAGE_PROVIDER:mixed-project (ms:$($msCodeCovProjects.Count), coverlet:$($coverletProjects.Count), none:$($neitherProjects.Count))"
} else {
$coverageProvider = "coverlet"
Write-Host "COVERAGE_PROVIDER:none-detected — defaulting to coverlet"
}If any discovered test projects have no provider, add one based on the selected strategy:
if ($coverageProvider -eq "ms-codecoverage" -and $neitherProjects.Count -gt 0) {
Write-Host "ADDING_MS_CODECOVERAGE:$($neitherProjects.Count) project(s)"
foreach ($tp in $neitherProjects) {
dotnet add $tp.FullName package Microsoft.Testing.Extensions.CodeCoverage --no-restore
Write-Host " ADDED_MS_CODECOVERAGE:$($tp.FullName)"
}
foreach ($tp in $neitherProjects) {
dotnet restore $tp.FullName --quiet
}
}
if (($coverageProvider -eq "coverlet" -or $coverageProvider -eq "mixed-project") -and $neitherProjects.Count -gt 0) {
Write-Host "ADDING_COVERLET:$($neitherProjects.Count) project(s)"
foreach ($tp in $neitherProjects) {
dotnet add $tp.FullName package coverlet.collector --no-restore
Write-Host " ADDED:$($tp.FullName)"
}
foreach ($tp in $neitherProjects) {
dotnet restore $tp.FullName --quiet
}
}Log each addition to the console so the developer sees what changed. Document the additions in the final report (see Output Format).
Run one dotnet test per entry point for the selected strategy:
- In
ms-codecoverageorcoverletmode: run a single command for the solution entry (or one per test project if no.slnwas found). - In
mixed-projectmode: run one command per test project, using that project's existing provider to avoid dual-provider conflicts.
Coverlet (coverlet.collector):
$rawDir = Join-Path "<COVERAGE_DIR>" "raw"
dotnet test "<ENTRY>" `
--collect:"XPlat Code Coverage" `
--results-directory $rawDir `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=cobertura `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Include="[*]*" `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Exclude="[*.Tests]*,[*.Test]*,[*Tests]*,[*Test]*,[*.Specs]*,[*.Testing]*" `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.SkipAutoProps=trueMicrosoft CodeCoverage (Microsoft.Testing.Extensions.CodeCoverage):
The command syntax depends on the .NET SDK version. In .NET 9, Microsoft.Testing.Platform arguments must be passed after the -- separator. In .NET 10+, --coverage is a top-level dotnet test flag.
$rawDir = Join-Path "<COVERAGE_DIR>" "raw"
# Detect SDK version for correct argument placement
$sdkVersion = (dotnet --version 2>$null)
$major = if ($sdkVersion -match '^(\d+)\.') { [int]$Matches[1] } else { 9 }
if ($major -ge 10) {
# .NET 10+: --coverage is a first-class dotnet test flag
dotnet test "<ENTRY>" `
--results-directory $rawDir `
--coverage `
--coverage-output-format cobertura `
--coverage-output $rawDir
} else {
# .NET 9: pass Microsoft.Testing.Platform arguments after the -- separator
dotnet test "<ENTRY>" `
--results-directory $rawDir `
-- --coverage --coverage-output-format cobertura --coverage-output $rawDir
}Mixed-project mode (Microsoft.Testing.Extensions.CodeCoverage + coverlet.collector in the same solution):
$rawDir = Join-Path "<COVERAGE_DIR>" "raw"
$sdkVersion = (dotnet --version 2>$null)
$major = if ($sdkVersion -match '^(\d+)\.') { [int]$Matches[1] } else { 9 }
foreach ($tp in $testProjects) {
$hasMsCodeCov = Select-String -Path $tp.FullName -Pattern 'Microsoft\.Testing\.Extensions\.CodeCoverage' -Quiet
if ($hasMsCodeCov) {
if ($major -ge 10) {
dotnet test $tp.FullName --results-directory $rawDir --coverage --coverage-output-format cobertura --coverage-output $rawDir
} else {
dotnet test $tp.FullName --results-directory $rawDir -- --coverage --coverage-output-format cobertura --coverage-output $rawDir
}
} else {
dotnet test $tp.FullName `
--collect:"XPlat Code Coverage" `
--results-directory $rawDir `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Format=cobertura `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Include="[*]*" `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.Exclude="[*.Tests]*,[*.Test]*,[*Tests]*,[*Test]*,[*.Specs]*,[*.Testing]*" `
-- DataCollectionRunSettings.DataCollectors.DataCollector.Configuration.SkipAutoProps=true
}
}Exit code handling:
- 0 — all tests passed, coverage collected
- 1 — some tests failed (coverage still collected — proceed with a warning)
- Other — build failure; stop and report the error
After the run, locate coverage files:
$coberturaFiles = Get-ChildItem -Path (Join-Path "<COVERAGE_DIR>" "raw") -Filter "coverage.cobertura.xml" -Recurse
Write-Host "COBERTURA_COUNT:$($coberturaFiles.Count)"
$coberturaFiles | ForEach-Object { Write-Host "COBERTURA:$($_.FullName)" }
$vsCovFiles = Get-ChildItem -Path (Join-Path "<COVERAGE_DIR>" "raw") -Filter "*.coverage" -Recurse -ErrorAction SilentlyContinue
if ($vsCovFiles) { Write-Host "VS_BINARY_COVERAGE:$($vsCovFiles.Count)" }If COBERTURA_COUNT is 0:
- If
VS_BINARY_COVERAGE> 0: warn the user — "Found .coverage files (VS binary format) but no Cobertura XML. These were likely produced by Visual Studio's built-in collector, which outputs a binary format by default. This skill needs Cobertura XML. Re-running with the detected provider configured for Cobertura output." Then re-run the appropriatedotnet testcommand above (Coverlet or Microsoft CodeCoverage) with Cobertura format. - If no
.coveragefiles either: stop and report — "Coverage files not generated. Ensure `dotnet test` completed successfully and check the build output for errors."
Phase 3 — Analysis (sequential)
Run the two bundled PowerShell scripts. Both are cheap and complete in seconds. Do not install or invoke ReportGenerator here — that belongs in optional Phase 5, after the user-facing summary has been delivered.
Step 4: Calculate CRAP scores using the bundled script
Run scripts/Compute-CrapScores.ps1 (co-located with this SKILL.md). It reads all Cobertura XML files, applies CRAP(m) = comp² × (1 − cov)³ + comp per method, and returns the top-N hotspots as JSON.
To locate the script: find the directory containing this skill's SKILL.md file (the skill loader provides this context), then resolve scripts/Compute-CrapScores.ps1 relative to it. If the script path cannot be determined, calculate CRAP scores inline using the formula below.
& "<skill-directory>/scripts/Compute-CrapScores.ps1" `
-CoberturaPath @(<all COBERTURA file paths as array>) `
-CrapThreshold <crap_threshold> `
-TopN <top_n>Script outputs: OVERALL_LINE_COVERAGE:<n>, OVERALL_BRANCH_COVERAGE:<n> (aggregated project-wide rates across all provided Cobertura files), TOTAL_METHODS:<n>, FLAGGED_METHODS:<n>, HOTSPOTS:<json> (top-N sorted by CrapScore descending). The OVERALL_* values are exactly what the Phase 4 summary needs for the "Line Coverage" / "Branch Coverage" rows — no separate XML parsing tool call is required.
Step 5: Extract per-method coverage gaps
Run scripts/Extract-MethodCoverage.ps1 to get per-method coverage data for the Coverage Gaps table:
& "<skill-directory>/scripts/Extract-MethodCoverage.ps1" `
-CoberturaPath @(<all COBERTURA file paths as array>) `
-CoverageThreshold <line_threshold> `
-BranchThreshold <branch_threshold> `
-Filter below-thresholdScript outputs: JSON array of methods below the coverage threshold, sorted by coverage ascending. Use this data to populate the Coverage Gaps by File table in the report.
Phase 4 — User-facing summary (MANDATORY — your next assistant response)
As soon as Phase 3 completes, your immediately next assistant response must contain the user-facing analysis — do not interleave any other tool calls before it. This is the response the user (and any judge) sees. Skipping or deferring this in favor of Phase 5 (ReportGenerator) is a hard failure.
The response must include, at minimum:
1. Overall line and branch coverage — read directly from the OVERALL_LINE_COVERAGE: / OVERALL_BRANCH_COVERAGE: lines emitted by Compute-CrapScores.ps1 (no extra Cobertura parsing required) 2. The Risk Hotspots table built from Compute-CrapScores.ps1 HOTSPOTS: output (CRAP scores, complexity, coverage) 3. Identification of the highest-risk method(s) and what is blocking coverage 4. 1–3 prioritized, specific recommendations (which method to test, expected CRAP/coverage impact)
Use references/output-format.md verbatim for fixed headings, table structures, symbols, and emoji. Use references/guidelines.md for prioritization rules and style.
If Phase 5 has not yet run when you compose this summary, mark the ## 📁 Reports section's HTML/Text/CSV/GitHub-markdown rows as Not generated (optional — request HTML reports to enable). Only the coverage-analysis.md and raw Cobertura paths are guaranteed to exist.
Attempt to save the same content to TestResults/coverage-analysis/coverage-analysis.md before delivering the response (use the editor's create/edit tool — do not shell out). If the file write fails, still deliver the summary and note the file-write failure explicitly.
Phase 5 — Optional: ReportGenerator HTML/CSV reports (post-summary)
Phase 5 is strictly optional and runs only after Phase 4 has been delivered. Skip Phase 5 entirely when:
- The user supplied existing Cobertura XML and only asked for analysis (the default for the existing-data path).
- The user is diagnosing a coverage plateau or asking "what's blocking me?" — they want the answer, not a static-site report.
- ReportGenerator is not already installed and you have no clear signal the user wants HTML reports.
Run Phase 5 only when the user explicitly asks for HTML/CSV reports, or when the project flow requires them (e.g., a CI artifact upload step).
Step 6: Verify or install ReportGenerator (only if running Phase 5)
$rgAvailable = $false
$rgCommand = Get-Command reportgenerator -ErrorAction SilentlyContinue
if ($rgCommand) {
$rgAvailable = $true
Write-Host "RG_INSTALLED:already-present"
} else {
$rgToolPath = Join-Path "<COVERAGE_DIR>" ".tools"
dotnet tool install dotnet-reportgenerator-globaltool --tool-path $rgToolPath
if ($LASTEXITCODE -eq 0) {
$env:PATH = "$rgToolPath$([System.IO.Path]::PathSeparator)$env:PATH"
$rgCommand = Get-Command reportgenerator -ErrorAction SilentlyContinue
if ($rgCommand) {
$rgAvailable = $true
Write-Host "RG_INSTALLED:true (tool-path: $rgToolPath)"
} else {
Write-Host "RG_INSTALLED:false"
Write-Host "RG_INSTALL_ERROR:reportgenerator-not-available"
}
} else {
Write-Host "RG_INSTALLED:false"
Write-Host "RG_INSTALL_ERROR:reportgenerator-not-available"
}
}
Write-Host "RG_AVAILABLE:$rgAvailable"If installation fails (no internet), keep RG_AVAILABLE:false, leave the existing user-facing summary as the final output, and note that HTML reports were skipped.
Step 7: Generate HTML/CSV reports
$reportsDir = Join-Path "<COVERAGE_DIR>" "reports"
if ($rgAvailable) {
reportgenerator `
-reports:"<semicolon-separated COBERTURA paths>" `
-targetdir:$reportsDir `
-reporttypes:"Html;TextSummary;MarkdownSummaryGithub;CsvSummary" `
-title:"Coverage Report" `
-tag:"coverage-analysis-skill"
Get-Content (Join-Path $reportsDir "Summary.txt") -ErrorAction SilentlyContinue
} else {
Write-Host "REPORTGENERATOR_SKIPPED:true"
}After Phase 5 completes successfully, you may follow up with a short message pointing the user to the generated HTML report (one paragraph, no need to repeat the summary).
Validation
- Verify that at least one
coverage.cobertura.xmlfile was generated afterdotnet test(or already exists when the user supplied one) - Confirm the assistant response contained the CRAP/risk-hotspot table — saving the markdown file is secondary
- Confirm
TestResults/coverage-analysis/coverage-analysis.mdwas written and contains data - Spot-check one method's CRAP score:
comp² × (1 − cov)³ + comp— a method with 100% coverage should have CRAP = complexity - If Phase 5 ran, verify
TestResults/coverage-analysis/reports/index.htmlexists; otherwise the report file should mark HTML/Text/CSV rows asNot generated
Common Pitfalls
- No Cobertura XML generated — the test project may lack a coverage provider. The skill auto-adds one, but if
dotnet add packagefails (offline/proxy), coverage collection silently produces nothing. Check for.coveragebinary files as a fallback indicator. - Test failures (exit code 1) — coverage is still collected from passing tests. Do not abort; proceed with partial data and note the failures in the summary.
- Premature end before user-facing summary — never start Phase 5 (ReportGenerator install/run) before the Phase 4 assistant response is delivered. The heavy
dotnet tool installcan crash the session or exhaust budget, leaving the user with no analysis even though the CRAP scores were already computed. - ReportGenerator install failure — if
dotnet tool installfails (no internet) during Phase 5, leave the existing Phase 4 summary as the final output and note that HTML reports were skipped. Do not retry or block on the install. - Method name mismatches in Cobertura — async methods, lambdas, and local functions may have compiler-generated names. The scripts use the Cobertura method name/signature directly; verify against source if results look unexpected.
- Mixed coverage providers — when a solution contains both Coverlet and Microsoft CodeCoverage projects, the skill runs per-project to avoid dual-provider conflicts. This is slower but correct.
{
"version": "0.1.0",
"category": "Testing",
"compatibility": "Requires a .NET test project or solution.",
"packages": [
"coverlet.collector",
"coverlet.msbuild"
]
}
Guidelines
Don't modify source or production code. The only permitted project file modifications are adding a coverage provider package to test projects that currently have no provider: coverlet.collector (coverlet/mixed modes) or Microsoft.Testing.Extensions.CodeCoverage (ms-codecoverage mode). Do not add a second provider to projects that already have one. Always log package additions and document revert commands in the report. Write all other output to TestResults/coverage-analysis/ under the test project directory.
Always show and open the generated markdown report — but only after the assistant response with the CRAP/risk-hotspot summary has been delivered. Saving and opening TestResults/coverage-analysis/coverage-analysis.md is a follow-up action; it must never delay the user-facing summary.
Don't generate new tests during the initial analysis run. This skill surfaces where tests are needed. Test generation is a separate follow-up step outside the scope of this skill.
Use inline `dotnet test` arguments, not runsettings files. Runsettings files require the developer to already know what they're doing — the whole point of this skill is that they shouldn't have to. Inline data collector args produce the same result with zero configuration.
Show the risk hotspots table even when all thresholds pass. A project at 90% line coverage can still have a method with cyclomatic complexity 20 and 0% branch coverage. The thresholds measure averages; the hotspot table finds outliers. Don't hide it just because the summary looks green.
Always compute and surface CRAP scores. The Risk Hotspots table is mandatory in every analysis output, whether analyzing pre-existing data, freshly collected data, or diagnosing a plateau. Never skip CRAP score computation — it is the primary differentiator between this skill and raw dotnet test coverage output.
Continue past test failures (exit code 1). If some tests fail, coverage is still collected from the passing tests — partial data is better than no data. Note the failures in the summary and proceed. Aborting would leave the developer with nothing actionable.
Run `dotnet test` only once per entry point during normal flow. When a solution is found, run it once against the solution. When no solution is found, run it once per test project. A single recovery rerun is allowed only if the first run produced no Cobertura XML and only .coverage binary output.
CRAP threshold of 30 is the default for a reason. Scores above 30 are widely cited (by the original researchers) as "needs immediate attention." Scores between 15 and 30 are moderate — flag them in the table but don't make them sound catastrophic. Scores ≤ 5 are generally fine.
Priority assignment for coverage gaps:
- HIGH — file has both a CRAP score above threshold AND coverage below threshold (the double failure is what makes it urgent)
- MED — coverage below threshold OR CRAP score above threshold, but not both
- LOW — coverage below threshold with all methods having complexity ≤ 2 (trivial code — missing coverage here is unlikely to hide real bugs)
---
Coverage Intelligence — Going Beyond the Numbers
Prioritize uncovered code that is complex (cyclomatic complexity > 5), on critical paths (auth, payment, data access, error handling), or changed frequently. Deprioritize trivial getters (complexity 1–2), generated files (EF migrations, *.Designer.cs, *.g.cs), and DI/configuration glue code.
Coverage plateau diagnosis — if coverage has stopped increasing, check for: [Exclude] attributes hiding large code sections, tests that execute code but assert nothing (inflated coverage without verification), or integration code that needs external dependencies (databases, file system).
AI-generated test quality — coverage delta alone is insufficient. Flag methods where CRAP score is still above threshold after coverage increased (tests may be happy-path only), and methods covered by a single test with no branch variation.
---
Style
- Keep risk hotspots prominent and immediately after the summary section — developers should find the highest-risk methods quickly
- Quantify recommendations — "adding 3 tests for
ProcessOrderwould cut the CRAP score from 48 to ~6" - Be direct — skip preamble, get to the table
- Emoji for visual scanning in generated output (defined in
references/output-format.md):
| Symbol | Meaning |
|---|---|
| 🔥 | hotspots |
| 📋 | gaps |
| 💡 | recommendations |
| 📁 | reports |
| ✅ | passing |
| ❌ | failing |
| ⚠️ | warning |
| 🔴 | HIGH priority |
| 🟡 | MED priority |
| 🟢 | LOW priority |
- Always use Unicode emoji in generated output — never shortcodes like
:x:or:fire:
Output Format
Copy the template below verbatim for all fixed elements (headings, table headers, emoji, symbols). Only replace <placeholder> values with actual data. Do not substitute emoji with text equivalents, do not change · to -, do not change × to x, and do not drop section emoji prefixes.
# Coverage Analysis - <ProjectName>
| Metric | Value |
|--------|-------|
| **Date** | <YYYY-MM-DD> |
| **Line Coverage** | <N>% |
| **Branch Coverage** | <N>% |
| **Risk Hotspots** | <N> (CRAP > <crap_threshold>) |
| **Tests** | <N> passed · <N> failed |
## Summary
| Metric | Value | Threshold | Status |
|--------|-------|-----------|--------|
| **Line Coverage** | <N>% | <line_threshold>% | ✅ / ❌ |
| **Branch Coverage** | <N>% | <branch_threshold>% | ✅ / ❌ |
| **Methods Analyzed** | <N> | — | — |
| **Risk Hotspots** | <N> | 0 | ✅ / ⚠️ |
| **Test Result** | <Passed / N tests failed> | — | ✅ / ⚠️ |
> Coverage collected from **<N> of <M> test project(s)**.
> Outputs saved to: `<coverageDir>/` (markdown summary + raw Cobertura XML).
> *If Phase 5 ran:* HTML/CSV reports also at `<coverageDir>/reports/`.
If any coverage provider package was added to test projects, include this note after the summary:
> ℹ️ **Coverage provider package updates**
> - `coverlet.collector` added to `<K>` project(s): `<TestProject1.csproj>`, `<TestProject2.csproj>`
> - `Microsoft.Testing.Extensions.CodeCoverage` added to `<M>` project(s): `<TestProject3.csproj>`
>
> To revert: `git checkout -- <path-to-each-modified-csproj>`
If all test projects already had a coverage provider, omit this note.
---
## 🔥 Risk Hotspots (Top <N> by CRAP Score)
Methods flagged as high-risk: complex code with low test coverage that is dangerous to change.
| Rank | Method | Class | File | Complexity | Coverage | CRAP Score |
|------|--------|-------|------|-----------|---------|-----------|
| 1 | `<method>` | `<class>` | `<file>` | <N> | <N>% | **<score>** |
| … | … | … | … | … | … | … |
> **CRAP Score** = `Complexity² × (1 − Coverage)³ + Complexity`.
> Scores above <crap_threshold> are flagged. A score ≤ 5 is considered safe.
---
## 📋 Coverage Gaps by File
Files below the line or branch coverage threshold, ordered by uncovered lines descending:
| File | Line Coverage | Branch Coverage | Uncovered Lines | Priority |
|------|--------------|----------------|----------------|---------|
| `<file>` | <N>% | <N>% | <N> | 🔴 HIGH / 🟡 MED / 🟢 LOW |
| … | … | … | … | … |
---
## 💡 Recommendations
1. **Write tests for the top risk hotspot first** — `<method>` in `<class>` has a CRAP score of <N> (complexity <N>, <N>% coverage). Reducing it to 80% coverage would drop the score to ~<projected>.
2. **Focus on `<file>`** — <N> uncovered lines, below threshold. <Brief reasoning.>
3. **<Up to 5 actionable items total, ordered by expected risk reduction.>**
---
## 📁 Reports
| Report | Path |
|--------|------|
| Markdown summary (this file) | `<coverageDir>/coverage-analysis.md` |
| Raw Cobertura XML | `<coberturaXmlPathsUsedForAnalysis>` |
| HTML (browsable) | `<coverageDir>/reports/index.html` *or* `Not generated (optional — request HTML reports to enable)` |
| Text summary | `<coverageDir>/reports/Summary.txt` *or* `Not generated` |
| GitHub markdown | `<coverageDir>/reports/SummaryGithub.md` *or* `Not generated` |
| CSV data | `<coverageDir>/reports/Summary.csv` *or* `Not generated` |If ReportGenerator (Phase 5) has not run, mark the HTML/Text/GitHub-markdown/CSV rows as Not generated (optional — request HTML reports to enable). Do not invent paths for files that have not been produced. For Raw Cobertura XML, list the actual XML file path(s) used in analysis (for from-scratch runs this is typically under <coverageDir>/raw/; for existing-data runs this may be under TestResults/ or another user-supplied location).
# Compute-CrapScores.ps1
#
# Reads a Cobertura XML coverage file and calculates CRAP scores per method.
# Uses Alberto Savoia's original CRAP formula:
# CRAP(m) = comp(m)^2 * (1 - cov(m))^3 + comp(m)
#
# Usage:
# .\Compute-CrapScores.ps1 -CoberturaPath <path1>,<path2>,... [-CrapThreshold <int>] [-TopN <int>]
#
# Outputs:
# - OVERALL_LINE_COVERAGE:<n.n> (aggregate line coverage across input files, as percent)
# - OVERALL_BRANCH_COVERAGE:<n.n> (aggregate branch coverage across input files, as percent)
# - TOTAL_METHODS:<n>
# - FLAGGED_METHODS:<n>
# - HOTSPOTS:<json> (top N by CRAP score)
param(
[Parameter(Mandatory)][string[]]$CoberturaPath,
[int]$CrapThreshold = 30,
[int]$TopN = 10
)
# Merge methods across all Cobertura files using a stable key (Class|Method|Signature|File).
# Line hits are accumulated so a line is counted as covered if any input coverage file covered it.
$methodMap = @{}
$overallLineRate = 0.0
$overallBranchRate = 0.0
$totalLinesCovered = 0
$totalLinesValid = 0
$totalBranchesCovered = 0
$totalBranchesValid = 0
$fallbackLineRates = [System.Collections.Generic.List[double]]::new()
$fallbackBranchRates = [System.Collections.Generic.List[double]]::new()
foreach ($filePath in $CoberturaPath) {
if (-not (Test-Path $filePath)) {
Write-Error "Cobertura file not found: $filePath"
exit 2
}
try {
[xml]$cobertura = Get-Content $filePath -Encoding UTF8 -ErrorAction Stop
} catch {
Write-Error "Failed to parse Cobertura XML: $filePath. $_"
exit 2
}
# Prefer aggregate numerator/denominator attributes when present.
if ($null -ne $cobertura.coverage.'lines-covered' -and $null -ne $cobertura.coverage.'lines-valid') {
$totalLinesCovered += [double]$cobertura.coverage.'lines-covered'
$totalLinesValid += [double]$cobertura.coverage.'lines-valid'
} elseif ($cobertura.coverage.'line-rate') {
$fallbackLineRates.Add([double]$cobertura.coverage.'line-rate')
}
if ($null -ne $cobertura.coverage.'branches-covered' -and $null -ne $cobertura.coverage.'branches-valid') {
$totalBranchesCovered += [double]$cobertura.coverage.'branches-covered'
$totalBranchesValid += [double]$cobertura.coverage.'branches-valid'
} elseif ($cobertura.coverage.'branch-rate') {
$fallbackBranchRates.Add([double]$cobertura.coverage.'branch-rate')
}
foreach ($package in $cobertura.coverage.packages.package) {
foreach ($class in $package.classes.class) {
$className = $class.name
$fileName = $class.filename
foreach ($method in $class.methods.method) {
$key = "$className|$($method.name)|$($method.signature)|$fileName"
# Cyclomatic complexity is stored as an XML attribute in Cobertura format
$complexity = if ($null -ne $method.complexity) { [int]$method.complexity } else { 1 }
if ($complexity -lt 1) { $complexity = 1 }
if (-not $methodMap.ContainsKey($key)) {
$methodMap[$key] = @{
Class = $className
Method = $method.name
Signature = $method.signature
File = $fileName
Complexity = $complexity
LineHits = @{}
}
}
# Accumulate hit counts per line number across files
foreach ($line in $method.lines.line) {
$lineNo = $line.number
$hits = [int]$line.hits
if ($methodMap[$key].LineHits.ContainsKey($lineNo)) {
$methodMap[$key].LineHits[$lineNo] += $hits
} else {
$methodMap[$key].LineHits[$lineNo] = $hits
}
}
}
}
}
}
$results = [System.Collections.Generic.List[PSCustomObject]]::new()
foreach ($entry in $methodMap.Values) {
$totalLines = $entry.LineHits.Count
$coveredLines = ($entry.LineHits.Values | Where-Object { $_ -gt 0 } | Measure-Object).Count
$lineCoverage = if ($totalLines -gt 0) { $coveredLines / $totalLines } else { 0.0 }
$complexity = $entry.Complexity
# Alberto Savoia's CRAP formula: comp^2 * (1 - cov)^3 + comp
# The cubic exponent on (1-cov) sharply penalizes low coverage:
# at 0% coverage the risk multiplier is 1.0; at 50% it drops to 0.125.
# Higher scores = more complex AND less covered = riskier to change
$uncovered = 1.0 - $lineCoverage
$crapScore = [Math]::Round(($complexity * $complexity * [Math]::Pow($uncovered, 3)) + $complexity, 2)
$results.Add([PSCustomObject]@{
Class = $entry.Class
Method = $entry.Method
Signature = $entry.Signature
File = $entry.File
TotalLines = $totalLines
CoveredLines = $coveredLines
LineCoverage = [Math]::Round($lineCoverage * 100, 1)
Complexity = $complexity
CrapScore = $crapScore
})
}
$hotspots = $results | Sort-Object CrapScore -Descending | Select-Object -First $TopN
$flagged = $results | Where-Object { $_.CrapScore -gt $CrapThreshold }
if ($totalLinesValid -gt 0) {
$overallLineRate = $totalLinesCovered / $totalLinesValid
} else {
# Fallback approximation when Cobertura aggregate counters and per-file rates are unavailable.
# This uses merged method line totals and may under/over-estimate if Cobertura
# includes executable lines outside method nodes.
$mergedTotalLines = ($results | Measure-Object -Property TotalLines -Sum).Sum
$mergedCoveredLines = ($results | Measure-Object -Property CoveredLines -Sum).Sum
if ($mergedTotalLines -gt 0) {
$overallLineRate = [double]$mergedCoveredLines / [double]$mergedTotalLines
} elseif ($fallbackLineRates.Count -gt 0) {
$overallLineRate = ($fallbackLineRates | Measure-Object -Average).Average
} else {
$overallLineRate = 0.0
}
}
if ($totalBranchesValid -gt 0) {
$overallBranchRate = $totalBranchesCovered / $totalBranchesValid
} elseif ($fallbackBranchRates.Count -gt 0) {
$overallBranchRate = ($fallbackBranchRates | Measure-Object -Average).Average
} else {
$overallBranchRate = 0.0
}
Write-Host "OVERALL_LINE_COVERAGE:$([Math]::Round($overallLineRate * 100, 1))"
Write-Host "OVERALL_BRANCH_COVERAGE:$([Math]::Round($overallBranchRate * 100, 1))"
Write-Host "TOTAL_METHODS:$($results.Count)"
Write-Host "FLAGGED_METHODS:$($flagged.Count)"
if ($hotspots) {
Write-Output "HOTSPOTS:$(@($hotspots) | ConvertTo-Json -Compress)"
} else {
Write-Output "HOTSPOTS:[]"
}
param(
[Parameter(Mandatory=$true)]
[string[]]$CoberturaPath,
[Parameter(Mandatory=$false)]
[int]$CoverageThreshold = 80,
[Parameter(Mandatory=$false)]
[int]$BranchThreshold = 70,
[Parameter(Mandatory=$false)]
[ValidateSet('uncovered', 'below-threshold', 'all')]
[string]$Filter = 'all'
)
<#
.SYNOPSIS
Extract method-level coverage from Cobertura XML and output as JSON.
.DESCRIPTION
Parses one or more Cobertura code coverage XML files and extracts per-method coverage metrics:
- Method name and class
- Line coverage percentage
- Branch coverage percentage
- Lines covered / total
- Branches covered / total
- Complexity (if available)
When multiple files are provided, line hits are merged across files so a line is counted
as covered if any test project covered it.
Filters by coverage status (uncovered, below threshold, or all).
Output is JSON for easy post-processing into tables, CSV, or other formats.
.PARAMETER CoberturaPath
Path(s) to Cobertura coverage.cobertura.xml file(s). Accepts multiple paths for multi-test-project merging.
.PARAMETER CoverageThreshold
Minimum acceptable line coverage percentage. Methods below this threshold are flagged (default: 80).
.PARAMETER BranchThreshold
Minimum acceptable branch coverage percentage for methods that contain branches (default: 70).
.PARAMETER Filter
Which methods to include:
'uncovered' - methods with 0% coverage only
'below-threshold' - methods with line coverage < CoverageThreshold OR branch coverage < BranchThreshold (for methods with branches)
'all' - all methods (default)
.EXAMPLE
PS> & .\Extract-MethodCoverage.ps1 -CoberturaPath "coverage.cobertura.xml" -CoverageThreshold 80 -BranchThreshold 70 -Filter uncovered
Outputs a JSON array of uncovered methods.
.EXAMPLE
PS> & .\Extract-MethodCoverage.ps1 -CoberturaPath @("tests1/coverage.cobertura.xml","tests2/coverage.cobertura.xml")
Merges coverage from multiple test projects and outputs combined method-level metrics.
.OUTPUTS
Writes JSON array to stdout.
Sets exit code 0 on success, 2 on missing/invalid file.
#>
foreach ($p in $CoberturaPath) {
if (-not (Test-Path $p)) {
Write-Error "Cobertura file not found: $p"
exit 2
}
}
# Merge methods across all Cobertura files using a stable key (Class|Method|Signature|File).
# Line hits and branch data are accumulated so coverage reflects all test projects.
$methodMap = @{}
foreach ($p in $CoberturaPath) {
try {
[xml]$xml = Get-Content $p -Encoding UTF8 -ErrorAction Stop
} catch {
Write-Error "Failed to parse Cobertura XML: $_"
exit 2
}
foreach ($package in $xml.coverage.packages.package) {
foreach ($class in $package.classes.class) {
$className = $class.name
$classFilename = $class.filename
foreach ($method in $class.methods.method) {
$key = "$className|$($method.name)|$($method.signature)|$classFilename"
if (-not $methodMap.ContainsKey($key)) {
$complexity = if ($null -ne $method.complexity) { [int]$method.complexity } else { 1 }
if ($complexity -lt 1) { $complexity = 1 }
$methodMap[$key] = @{
Class = $className
Method = $method.name
Signature = $method.signature
File = $classFilename
Complexity = $complexity
LineHits = @{}
BranchData = @{}
}
}
# Accumulate line hits across files
foreach ($line in $method.lines.line) {
$lineNo = $line.number
$hits = [int]$line.hits
if ($methodMap[$key].LineHits.ContainsKey($lineNo)) {
$methodMap[$key].LineHits[$lineNo] += $hits
} else {
$methodMap[$key].LineHits[$lineNo] = $hits
}
# Accumulate branch data
if ($line.branch -eq 'true' -and $line.'condition-coverage') {
if ($line.'condition-coverage' -match '\((\d+)/(\d+)\)') {
$covered = [int]$Matches[1]
$total = [int]$Matches[2]
if ($methodMap[$key].BranchData.ContainsKey($lineNo)) {
# Merge branch coverage across files by accumulating covered branches (capped at total)
$existingCovered = $methodMap[$key].BranchData[$lineNo].Covered
$existingTotal = $methodMap[$key].BranchData[$lineNo].Total
if ($existingTotal -ne $total) {
Write-Warning ("Branch total mismatch for {0} at line {1}: {2} vs {3}" -f $key, $lineNo, $existingTotal, $total)
}
$mergedTotal = [Math]::Max($existingTotal, $total)
$mergedCovered = [Math]::Min($existingCovered + $covered, $mergedTotal)
$methodMap[$key].BranchData[$lineNo] = @{ Covered = $mergedCovered; Total = $mergedTotal }
} else {
$methodMap[$key].BranchData[$lineNo] = @{ Covered = $covered; Total = $total }
}
}
}
}
}
}
}
}
$methods = [System.Collections.Generic.List[PSCustomObject]]::new()
foreach ($entry in $methodMap.Values) {
$totalLines = $entry.LineHits.Count
$coveredLineCount = ($entry.LineHits.Values | Where-Object { $_ -gt 0 } | Measure-Object).Count
$lineCoveragePercent = if ($totalLines -gt 0) { [math]::Round(($coveredLineCount / $totalLines) * 100, 1) } else { 0 }
$branchesTotal = 0
$branchesCovered = 0
foreach ($bd in $entry.BranchData.Values) {
$branchesCovered += $bd.Covered
$branchesTotal += $bd.Total
}
$branchCoveragePercent = if ($branchesTotal -gt 0) { [math]::Round(($branchesCovered / $branchesTotal) * 100, 1) } else { 0 }
# Apply filter
if ($Filter -eq 'uncovered' -and $lineCoveragePercent -gt 0) { continue }
if ($Filter -eq 'below-threshold') {
$lineOk = $lineCoveragePercent -ge $CoverageThreshold
$branchOk = ($branchesTotal -eq 0) -or ($branchCoveragePercent -ge $BranchThreshold)
if ($lineOk -and $branchOk) { continue }
}
$methods.Add([PSCustomObject]@{
Class = $entry.Class
Method = $entry.Method
Signature = $entry.Signature
File = $entry.File
Complexity = $entry.Complexity
LineCoverage = $lineCoveragePercent
BranchCoverage = $branchCoveragePercent
CoveredLines = $coveredLineCount
TotalLines = $totalLines
UncoveredLines = ($totalLines - $coveredLineCount)
CoveredBranches = $branchesCovered
TotalBranches = $branchesTotal
})
}
# Sort by uncovered lines descending, then by line coverage ascending
$sorted = $methods | Sort-Object -Property @{Expression='UncoveredLines';Descending=$true}, @{Expression='LineCoverage';Descending=$false}, Class, Method
# Output as JSON (empty array guard for zero results)
if ($sorted.Count -eq 0) {
Write-Output "[]"
} else {
$json = @($sorted) | ConvertTo-Json
Write-Output $json
}
# Summary
Write-Host "METHODS_FILTERED:$($methods.Count)" -ForegroundColor Green
$uncovered = $methods | Where-Object { $_.LineCoverage -eq 0 } | Measure-Object | Select-Object -ExpandProperty Count
Write-Host "UNCOVERED_METHODS:$uncovered" -ForegroundColor $(if ($uncovered -gt 0) { 'Yellow' } else { 'Green' })
exit 0