Coverage analysis

From FerroxLabs/murage · View interactive version

Coverage analysis is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level coverage analysis implementation: clean-code and best-practices decision frameworks, production-ready patterns, and concrete templates for coverage analysis workflows. Use when the user asks about coverage analysis, coverage analysis configuration, or testing best practices for c

How to use this skill

Skill file

Coverage Analysis

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Establish the Current Coverage Baseline

Before making any recommendations, understand where the codebase currently stands.

2. Select the Right Coverage Metric for the Context

Different metrics reveal different risks. Choose the primary metric based on what the code does.

3. Define Threshold Strategy by Module Risk Tier

A single global threshold is almost always wrong. Define thresholds by risk tier.

4. Configure the Coverage Tool Correctly

Misconfigured tools produce misleading numbers. Each tool has critical configuration decisions.

Jest (JavaScript/TypeScript):

pytest-cov (Python):

JaCoCo (Java/Kotlin):

Istanbul/nyc (JavaScript legacy):

5. Implement Coverage Ratcheting to Prevent Regression

Ratcheting prevents coverage regression without requiring perfection immediately.

6. Interpret Coverage Reports to Find Meaningful Gaps

Raw percentages are not actionable. Teach users to read the report critically.

7. Configure Coverage Exclusions Correctly

Bad exclusion policies create false confidence. Good ones reduce noise.

8. Integrate Coverage into the Development Workflow

Coverage must be part of the regular development loop, not just a CI artifact.


Output Format

When responding to a coverage analysis request, structure the output as follows:

## Coverage Analysis: [Project/Module Name]

### Current State Assessment
| Metric           | Current % | Target % | Gap   | Priority |
|------------------|-----------|----------|-------|----------|
| Line Coverage    |           |          |       |          |
| Branch Coverage  |           |          |       |          |
| Function Coverage|           |          |       |          |
| Statement Coverage|          |          |       |          |

### Module Risk Tier Classification
| Module/Directory | Risk Tier | Line Target | Branch Target | Rationale          |
|-----------------|-----------|-------------|---------------|--------------------|
|                 | Tier 1    | 95%         | 90%           |                    |
|                 | Tier 2    | 85%         | 80%           |                    |
|                 | Tier 3    | 60%         | N/A           |                    |
|                 | Excluded  | --          | --            |                    |

### Top Coverage Gaps (Priority Order)
1. [File/Module] -- [Metric]: [Current%] -- [Risk]: [Why this matters] -- [Action]: [Specific tests needed]
2. ...

### Tool Configuration
[Language/framework-specific configuration snippet]

### Threshold Configuration (CI Gate)
[Exact configuration for the project's CI tool]

### Ratchet Plan
- Current enforced threshold: [N%]
- Proposed immediate threshold: [current - 2%] (no regression gate)
- 30-day target: [N%]
- 90-day target: [N%]
- Milestone to lock in: [condition for ratcheting up]

### Exclusion Policy
| Pattern | Reason | Review Date |
|---------|--------|-------------|
|         |        |             |

### Recommended Next Actions (Ordered by Impact)
1. ...
2. ...
3. ...

Rules

  1. Never cite an aggregate coverage percentage without specifying the metric type. "80% coverage" is meaningless -- it must be "80% branch coverage" or "80% line coverage". These can differ by 20-30 percentage points on the same codebase and imply completely different levels of test completeness.
  1. Never recommend a single global threshold for a heterogeneous codebase. Authentication code and configuration bootstrap code do not have the same risk profile. A global 70% requirement under-protects the former and over-burdens the latter. Always tier thresholds by module risk.
  1. 100% coverage is not the goal and should not be stated as such. Chasing 100% line coverage leads to trivial tests written to execute lines rather than verify behavior. The goal is meaningful coverage of risk-bearing code paths. State this clearly when a user asks "how do I get to 100%."
  1. Never recommend coverage in isolation without acknowledging its limits. Coverage tells you which lines ran, not whether they were tested correctly. Always note that coverage is a floor metric -- it identifies untested code but cannot identify poorly tested code. Pair with mutation testing recommendations for higher assurance needs.
  1. Always configure collectCoverageFrom (or equivalent) explicitly. The default behavior of Jest (and similar tools) only measures files imported during the test run, which gives artificially inflated percentages by ignoring completely untested files. This is the single most common source of false confidence in coverage reports.
  1. Never suppress coverage annotations without requiring an explanatory comment. /* istanbul ignore next */ without explanation is a code smell. Treat unannotated suppressions like unannotated @SuppressWarnings or # type: ignore -- they must be justified.
  1. Branch coverage thresholds must be lower than line coverage thresholds by at least 5-10 points when configuring CI gates. Branch coverage is structurally harder to achieve and a branch threshold equal to line threshold will produce constant false failures. Typical calibration: line 85%, branch 75% for Tier 2 code.
  1. Ratcheting thresholds must be stored in source control, not in CI environment variables or CI GUI settings. Coverage thresholds that live outside the repository can be silently changed without code review. They must be committed alongside the code they govern.
  1. Uncovered catch blocks, error handlers, and authorization rejection paths must be explicitly called out as higher priority than uncovered utility code. When reviewing a coverage report, do not present gaps alphabetically -- present them by risk tier.
  1. When introducing coverage tooling to an existing codebase for the first time, set the initial CI threshold at current coverage minus 2%, not at a desired future target. Failing a build on day one because coverage is at 34% when the target is 80% provides no useful signal and destroys team trust in the tool. The ratchet starts from reality, not aspiration.

Edge Cases

Legacy Codebase with Near-Zero Coverage

When a codebase has 5-20% coverage and has never had gates enforced:

Generated Code Inflating or Deflating Coverage

Generated code (GraphQL resolvers, Protobuf classes, ORM models, OpenAPI client stubs, Lombok-annotated classes) creates two problems:

Microservices or Monorepo with Per-Service Coverage Requirements

In a monorepo with multiple services, a single global threshold hides per-service gaps:

Test Suite Runs Slowly with Coverage Enabled

Coverage instrumentation adds 20-50% overhead to test execution time in most environments. This is not a tool bug -- it is the cost of instrumenting every line.

Coverage Paradox: High Percentage, Low Confidence

This is the most dangerous edge case -- a codebase reporting 85% coverage but with poor tests that only execute code without asserting behavior:

Coverage Tools and TypeScript/Transpiled Code

TypeScript, Babel-transpiled JavaScript, and source-mapped languages create a coverage accuracy problem:

CI Coverage Reporting Flakiness

Coverage percentages sometimes fluctuate 1-3% between identical test runs due to test execution order, async timing, or conditional code paths that depend on timing:


Example

Input: "We have a Node.js/TypeScript Express API with Jest. The coverage report says 72% but our senior engineer thinks the number is misleading. We keep getting production bugs in our payment processing module. How should we approach coverage analysis?"

Output:

Coverage Analysis: Node.js/TypeScript Express API

Diagnosing Why the 72% Number Is Misleading

Your senior engineer is likely correct. The most common sources of false confidence in Jest coverage reports are:

  1. Missing collectCoverageFrom -- Without this setting, Jest only measures files that were imported during tests. Completely untested files are invisible to the report, inflating the percentage. Verify by checking your jest.config.ts:
// jest.config.ts
export default {
  collectCoverageFrom: [
    "src/**/*.ts",
    "!src/**/*.d.ts",
    "!src/**/*.test.ts",
    "!src/**/*.spec.ts",
    "!src/generated/**",
    "!src/migrations/**",
    "!src/index.ts",       // Express bootstrap -- exclude
  ],
  coverageProvider: "v8",  // More accurate branch coverage for modern TS
  coverageReporters: ["text", "text-summary", "lcov", "json-summary"],
};

If you were not using collectCoverageFrom, re-run with this config. Your actual coverage number will likely drop -- this is revealing reality, not regression.

  1. Line vs. branch coverage -- "72% coverage" almost certainly means line coverage. Check whether you have branch coverage configured and what that number is. A file can have 95% line coverage and 40% branch coverage if error paths and conditional branches are untested.

Current State Assessment (After Correcting Configuration)

Run jest --coverage with the corrected config and fill in this table:

| Metric | Current % | Target % | Gap | Priority |

|-------------------|-----------|----------|------|----------|

| Line Coverage | ~72% (reported) | TBD after config fix | -- | Medium |

| Branch Coverage | Unknown -- check report | 80% (Tier 2), 90% (Tier 1) | -- | High |

| Function Coverage | Unknown | 90% | -- | High |

| Statement Coverage| ~72% | (use branch instead) | -- | Low |


Module Risk Tier Classification

| Module/Directory | Risk Tier | Line Target | Branch Target | Rationale |

|-----------------------------|-----------|-------------|---------------|----------------------------------------|

| src/payments/ | Tier 1 | 95% | 90% | Financial transactions, data integrity |

| src/auth/ | Tier 1 | 95% | 90% | Authentication, authorization |

| src/orders/ | Tier 2 | 85% | 80% | Core business logic |

| src/users/ | Tier 2 | 85% | 80% | User data management |

| src/routes/ | Tier 2 | 80% | 75% | Request handling, validation |

| src/middleware/ | Tier 3 | 65% | 60% | Logging, error formatting |

| src/config/ | Tier 3 | 50% | N/A | Env-var loading, DI setup |

| src/generated/ | Excluded | -- | -- | Auto-generated GraphQL/OpenAPI types |

| src/migrations/ | Excluded | -- | -- | Database migrations |


Immediate Action: Inspect the Payments Module

Open the HTML coverage report in coverage/lcov-report/index.html. Navigate to src/payments/. Look for the following specific patterns:

High-priority uncovered scenarios to find:

```typescript

if (amount > 0 && amount <= MAX_TRANSACTION_LIMIT) {

// process payment

} else {

// reject -- is this branch tested?

}

```

The else path rejecting invalid amounts is a critical security and correctness path.


Corrected Jest Configuration

// jest.config.ts
import type { Config } from "jest";

const config: Config = {
  preset: "ts-jest",
  testEnvironment: "node",
  collectCoverageFrom: [
    "src/**/*.ts",
    "!src/**/*.d.ts",
    "!src/**/*.{test,spec}.ts",
    "!src/generated/**",
    "!src/migrations/**",
    "!src/index.ts",
  ],
  coverageProvider: "v8",
  coverageReporters: ["text", "lcov", "json-summary"],
  coverageThreshold: {
    // Global minimum -- ratchet, not aspirational target
    global: {
      lines: 70,         // Set to current - 2%
      branches: 60,      // Branch coverage will be lower than line -- this is normal
      functions: 75,
    },
    // Tier 1: payments -- strict
    "./src/payments/**/*.ts": {
      lines: 90,
      branches: 85,
      functions: 90,
    },
    // Tier 1: auth -- strict
    "./src/auth/**/*.ts": {
      lines: 90,
      branches: 85,
      functions: 90,
    },
    // Tier 2: orders
    "./src/orders/**/*.ts": {
      lines: 80,
      branches: 75,
      functions: 85,
    },
  },
};

export default config;

Top Coverage Gaps (Priority Order)

  1. src/payments/PaymentProcessor.ts -- Branch Coverage: likely < 50% -- Risk: payment gateway error paths completely untested -- Action: Add test cases for network timeout, declined card (response code 402), fraud block (response code 403), malformed gateway response, and idempotency key collision.
  1. src/payments/RefundService.ts -- Catch blocks uncovered -- Risk: partial refund failures may be silently swallowed -- Action: Inject a mock gateway that throws GatewayTimeoutError and InsufficientFundsError and assert correct HTTP response codes and error logging.
  1. src/auth/TokenValidator.ts -- Else branch on permission check -- Risk: authorization bypass if the rejection path has a bug -- Action: Test expired tokens, malformed JWTs, insufficient-scope tokens, and revoked tokens as explicit test cases.
  1. src/orders/PricingEngine.ts -- Ternary expressions uncovered on false path -- Risk: promotional pricing or discount logic errors -- Action: Test with no active promotions, expired promotions, stacked discounts, and zero-value orders.

Ratchet Plan


Exclusion Policy

| Pattern | Reason | Review Date |

|--------------------------|-------------------------------------|-------------|

| src/generated/** | Auto-generated from OpenAPI spec | Each spec update |

| src/migrations/** | Knex migration files, not runtime | Quarterly |

| src/index.ts | Express bootstrap, no logic | Quarterly |

| src/config/env.ts | Reads process.env, no branching logic | 90 days |

All suppression annotations in source code (/* c8 ignore next */) must include an inline comment explaining why:

/* c8 ignore next -- exhaustive switch on PaymentStatus enum, default is unreachable by type construction */
default:
  throw new UnreachableError(status);

Recommended Next Actions (Ordered by Impact)

  1. Add collectCoverageFrom to Jest config immediately and re-run coverage. Establish the real baseline number before doing anything else.
  2. Open the branch coverage HTML report for src/payments/ and catalog every uncovered catch block and else branch. This is the direct cause of production bugs.
  3. Write payment gateway error scenario tests this sprint -- network failure, declined card, timeout, partial charge. Each is a test case, not a category.
  4. Set the no-regression CI gate at current branch coverage - 2% to stop the hole from getting bigger while the team fills it.
  5. Configure diff coverage enforcement in CI so all new code in PRs must have 80% branch coverage -- prevent new debt accumulation in parallel with paying down old debt.
  6. Install Coverage Gutters extension in VS Code (or equivalent IDE coverage runner) so engineers see uncovered lines while writing code, not after pushing.
  7. Schedule a 30-day coverage review to ratchet thresholds upward based on actual progress, not on aspirational targets set today.
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.