Test Coverage Gap Analysis
Systematic, multi-phase approach to finding and filling test coverage gaps. The core idea: audit what is missing before writing a single test, then fill gaps in priority order.
When to Use
- Before claiming "done" — verify the feature is actually tested, not just implemented
- Inheriting an unknown codebase — understand what is tested and what is not before making changes
- After a refactoring — confirm tests still cover the paths that matter
- Below target coverage — systematic gap-filling is faster than writing tests at random
- After a production incident — find the test that should have caught the bug
Principle Reference
This playbook applies Principle 7: Make gaps visible before filling them and Principle 5: Structure the output, not just the prompt.
Overview
The workflow has five phases. Each phase produces a structured artifact that feeds the next.
Phase 1: Coverage Audit
→ Coverage matrix (file × coverage %)
│
Phase 2: Edge Case Enumeration
→ Untested cases table (case × category × priority)
│
Phase 3: Gap Prioritization
→ Prioritized gap list (P1–P4)
│
Phase 4: Systematic Gap Filling
→ New tests, re-measured coverage
│
Phase 5: Regression Check
→ Full suite green, no fragile testsDo Not Skip Phase 1
Writing tests without a coverage audit is like fixing bugs without a bug report. You will write tests for code that is already covered and miss code that is not.
Phase 1: Coverage Audit
Run the existing test suite with coverage instrumentation and produce a structured matrix.
Step 1: Collect Metrics
bash
# JavaScript / TypeScript
npx jest --coverage --coverageReporters=text
# PHP
php artisan test --coverage
# or: XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-text
# Rust
cargo tarpaulin --out stdout
# Go
go test -coverprofile=coverage.out ./...
go tool cover -func=coverage.out
# Python
pytest --cov=src --cov-report=term-missingStep 2: Produce the Coverage Matrix
Structure the results as a ranked table, worst-covered areas first:
markdown
| File / Area | Line Coverage | Status |
| ---------------------------------- | ------------- | ---------------------- |
| Text/Loaders/Textract/ (subsystem) | 4.61% | No tests on most files |
| Extraction/Builtins/Contacts.php | 0% | No tests |
| Extraction/Builtins/Simple.php | 0% | No tests |
| Engine.php | 57.5% | Partial |
| Text/TextContent.php | 50% | Partial |
| Parser/TokenParser.php | 89% | Good |
| Config/Settings.php | 95% | Excellent |Step 3: Rank by Impact
Not all coverage gaps are equal. Rank by:
- Business criticality — code that handles money, auth, or user data
- Change frequency — files that change often and break often
- Complexity — high cyclomatic complexity with low coverage is the most dangerous combination
- Dependency count — code that many other modules depend on
Phase 2: Edge Case Enumeration
Launch an explore agent to read the source code and enumerate specific untested cases. The agent does not write tests — it produces a list.
Categories to Enumerate
| Category | What to Look For |
|---|---|
| Happy path | Is the basic success case tested? |
| Error handling | What happens when inputs are invalid, services are down, files are missing? |
| Boundary values | Empty strings, zero, negative numbers, max int, single-element arrays |
| State transitions | Object goes from state A to B — is every valid transition tested? Every invalid one? |
| Concurrency | Parallel access, race conditions, lock contention |
Output Format
The agent should produce a table:
markdown
| # | Category | File | Untested Case | Priority |
| --- | -------------- | --------------------- | ----------------------------------------------- | -------- |
| 1 | Error handling | Engine.php:process() | File not found throws, but catch block untested | P1 |
| 2 | Boundary | Parser.php:parse() | Empty input string | P2 |
| 3 | State | Order.php:cancel() | Cancel after partial refund | P2 |
| 4 | Concurrency | Cache.php:get() | Concurrent read during write | P3 |
| 5 | Happy path | Report.php:generate() | Basic generation with default params | P4 |Explore Agent Prompt
Use a dedicated explore agent for this phase. It should read source files, not run tests. Its only output is the enumerated list. See Example Prompts below.
Phase 3: Gap Prioritization
Combine the coverage matrix (Phase 1) and edge case list (Phase 2) into a single prioritized gap list.
Priority Levels
| Priority | Category | Rationale |
|---|---|---|
| P1 | Error handling paths | Untested error handling is a leading source of production incidents. Code that silently swallows errors, returns wrong status codes, or corrupts state on failure. |
| P2 | State transitions + boundaries | Off-by-one errors, invalid state transitions, and boundary values cause subtle bugs that are hard to diagnose in production. |
| P3 | Integration tests | Interactions between modules — API endpoints calling services calling databases. Unit tests pass but the integration fails. |
| P4 | Config/environment variations | Different feature flags, environment variables, locale settings. Important but rarely the source of critical bugs. |
Prioritization Criteria
For each gap, ask:
- What is the blast radius if this breaks in production? (Users affected, data at risk)
- How likely is this path to be exercised? (Every request vs. rare edge case)
- How hard is this to test? (Easy unit test vs. complex integration setup)
High blast radius + high likelihood + easy to test = P1. Low blast radius + rare + hard to test = P4.
Phase 4: Systematic Gap Filling
Write tests in priority order. Re-run coverage after each batch to track progress.
Workflow
- Pick the highest-priority gap batch (e.g., all P1 error handling gaps)
- Write tests for that batch
- Run the suite — all tests must pass
- Re-measure coverage
- Record the delta: "P1 batch: coverage 53% → 62%"
- Move to the next priority level
Rules
- One batch at a time. Do not mix P1 and P3 tests in the same pass.
- Re-measure after each batch. This catches the case where your new tests overlap with existing coverage instead of filling actual gaps.
- Target a specific metric. "Reach 80% line coverage" is better than "write more tests."
- Tests must be meaningful. A test that asserts
true === truecounts toward coverage but catches nothing. Every test should be able to fail if the code is wrong.
Avoid Coverage Theater
Coverage percentage is a proxy, not a goal. A codebase at 90% coverage with assertions like expect(result).toBeDefined() is worse than 70% coverage with real assertions. Every test should answer: "What bug would this catch if it failed?"
Next Step
After filling test gaps, use the Code Review Loops Playbook to review the gap-filling tests for quality and correctness.
Phase 5: Regression Check
After filling gaps, run the full suite and verify quality.
Checklist
- [ ] Full test suite passes (not just the new tests)
- [ ] No fragile tests — tests that pass/fail depending on execution order, timing, or environment
- [ ] Test isolation — each test can run independently, no shared mutable state between tests
- [ ] No unnecessary mocking — if you mocked something that could run for real in tests, remove the mock
- [ ] Coverage target met or delta documented
Fragile Test Detection
bash
# Run tests in random order (Jest)
npx jest --randomize
# Run tests multiple times (any framework)
for i in {1..5}; do npm test || echo "FAILED on run $i"; done
# Run a single test file in isolation
npx jest path/to/suspect.test.tsReal Examples
Example 1: PHP Extractor — 53% Coverage Audit
A coverage audit of a PHP text extraction library revealed:
Overall: 53.39% (331/620 lines)
Worst areas:
- Text/Loaders/Textract/ (entire subsystem): 4.61%
- Extraction/Builtins/Contacts.php: 0%
- Extraction/Builtins/Simple.php: 0%
- ContactDto.php: 0%
- Engine.php: 57.5%The audit immediately showed that the Textract subsystem (the integration with AWS Textract) had almost no tests. This was a P1 gap because it handled document parsing for production workflows.
Example 2: Blade Parser — 31 Untested Edge Cases
An explore agent read the source code of a Dart Blade template parser and enumerated 31 untested edge cases across 5 categories. The cases were prioritized by likelihood in real Blade components. Writing tests for the highest-priority cases found and fixed an actual bug: an unclosed comment at EOF caused the parser to hang.
TIP
The explore agent found a real bug that the existing tests missed — not because there were no tests, but because the tests did not cover the specific edge case (comment never closed before end of file). Gap analysis finds these.
Example 3: Rust Editor — 73% to 80%+
A Rust Lisp editor had 73.12% patch coverage against an 80% target. The audit identified the biggest gaps:
- vfs.rs: 57% — no unit tests
- home.rs: 0% — completely untested
- import_tracer.rs: 83% — edge cases untested
- io.rs: 57% — VFS interception paths never exercised
- system.rs: 25% — sys/sema-home untestedKey insight: the VFS used thread_local!, so every test needed std::thread::spawn for isolation. Systematic gap filling in priority order brought coverage above 80%.
Example 4: Multi-Agent Coverage Audit
For a larger project with 30% overall coverage, three explore agents were dispatched in parallel:
- Agent 1: Audited the API layer (controllers, middleware, routes)
- Agent 2: Audited the domain layer (services, models, business rules)
- Agent 3: Audited the infrastructure layer (database, external APIs, file I/O)
Each agent produced an independent coverage matrix. The matrices were merged, deduplicated, and prioritized. This parallel approach completed the audit in roughly one-third the time of a sequential pass.
Example Prompts
Launch a Coverage Audit Agent
Run the test suite with coverage enabled and produce a coverage matrix.
1. Run: [test command with coverage]
2. Parse the output into a table:
| File / Area | Line Coverage | Status |
3. Rank worst-covered areas first
4. For each area below 60%, note:
- Is this business-critical code?
- How often does this file change? (check git log)
- What is the cyclomatic complexity?
5. Produce a prioritized list of areas to test first.
Output the coverage matrix and the prioritized list.Launch an Edge Case Exploration Agent
Read the source files in [directory] and enumerate untested edge cases.
Do NOT write tests. Only produce a list.
For each function/method, identify cases that are NOT tested:
- Error handling: what exceptions can be thrown? Are catch blocks tested?
- Boundary values: empty inputs, zero, negative, max values
- State transitions: what states can the object be in? Are all transitions covered?
- Null/undefined: what happens with missing or null inputs?
- Concurrency: is this called from multiple threads? Is that tested?
Output format:
| # | Category | File:Function | Untested Case | Priority (P1-P4) |
Prioritize by: P1 = error handling, P2 = boundaries/state,
P3 = integration, P4 = config/environment.Launch a Gap-Filling Agent
Write tests to fill these specific gaps (from the gap analysis):
[paste prioritized gap list]
Rules:
1. Write tests in priority order (P1 first)
2. Every test must have meaningful assertions — no "it doesn't throw" tests
3. After writing each batch, run the suite and report:
- All tests pass? (yes/no)
- Coverage before → after
4. Stop after each priority level so I can review before continuing.Launch a Regression Check
Run the full test suite and check for fragile tests.
1. Run all tests once. Report pass/fail count.
2. Run tests in random order (if framework supports it).
3. Run tests 3 times. Report any that fail intermittently.
4. For any fragile tests found:
- Identify the cause (shared state, timing, external dependency)
- Suggest a fix
Report the final coverage number and any fragile test findings.Verification Checklist
Before declaring test coverage work complete:
- [ ] Coverage matrix produced with all files ranked
- [ ] Edge cases enumerated with categories and priorities
- [ ] Gaps filled in priority order (P1 first)
- [ ] Coverage re-measured after each batch
- [ ] Full suite passes (not just new tests)
- [ ] No fragile tests detected
- [ ] Coverage target met or gap documented with rationale
Superpowers Skill Mapping
| Skill | Role in This Playbook |
|---|---|
test-driven-development | Writing tests that target specific gaps with meaningful assertions |
verification-before-completion | Using coverage analysis to prove the work is actually done, not just "it works on my machine" |