skill-coverage-audit

nyldn/claude-octopus

Трассировка кода в диффах, сопоставление с тестами, автогенерация недостающего покрытия — перед PR

Звёзды4 465
Авторnyldn
Установок83

Установка

SKILL.md

Test Coverage Audit

Overview

Trace every codepath in a diff, map each path against existing tests, visualize coverage gaps, and auto-generate tests for uncovered paths.

Core principle: Trace codepaths in changed files -> Map against existing tests -> Score coverage quality -> Generate tests for gaps -> Report before/after counts.


Caps and Limits

These hard limits prevent runaway analysis:

  • 30 code paths max per audit. If a diff yields more than 30, prioritize by complexity and risk (error paths, security-sensitive branches, public API surfaces first).
  • 20 tests generated max per audit. Focus on highest-impact gaps first.
  • 2-minute per-test exploration cap. If understanding a single test path takes longer than 2 minutes, mark it as "needs manual review" and move on.

Phase 1: Codepath Tracing

Step 1: Identify Changed Files

Determine the diff scope. Use the most relevant source:

# PR diff
git diff --name-only main...HEAD

# Staged changes
git diff --name-only --cached

# Last commit
git diff --name-only HEAD~1..HEAD

Filter to source code files only (exclude configs, docs, generated files).

Step 2: Trace Data Flow Through Every Branch

For each changed file, you MUST trace:

  1. Conditionals -- Every if/else, switch/case, ternary, and pattern match. Each branch is a separate codepath.
  2. Error paths -- Every catch, throw, error return, validation failure, and early return with error. WHY: Error paths are the most common source of untested bugs.
  3. Function calls -- Every function invoked from changed code. Trace one level deep into callees to identify integration boundaries.
  4. Loop boundaries -- Empty collection, single item, and multi-item paths through loops.
  5. Guard clauses -- Every early return, null check, and permission gate.

Step 3: Build the Codepath Inventory

Produce a structured inventory:

## Codepath Inventory: [filename]

| # | Path Description | Type | Risk |
|---|-----------------|------|------|
| 1 | validateUser() happy path | conditional | low |
| 2 | validateUser() missing email | error | medium |
| 3 | validateUser() invalid format | error | medium |
| 4 | processOrder() empty cart guard | guard | high |
| 5 | processOrder() payment timeout | error | high |
| 6 | processOrder() success | conditional | low |

Type categories: conditional, error, guard, loop-boundary, integration, async

Risk assessment: high = user-facing failure or data loss, medium = degraded behavior, low = cosmetic or logging


Phase 2: Test Mapping and Quality Scoring

Step 1: Search for Existing Tests

For each file in the diff, search the test directory for related tests:

# Find test files that reference the changed file or its exports
# Search by filename pattern
find tests/ -name "*[changed_file_stem]*" -type f

# Search by import/require of the changed module
grep -rl "import.*from.*[module_name]" tests/
grep -rl "require.*[module_name]" tests/

# Search by function name references
grep -rl "[function_name]" tests/

Step 2: Score Test Quality

For each codepath, assess existing test coverage with this rubric:

RatingMeaningCriteria
★★★Behavior + edge cases testedTests assert behavior AND cover boundary conditions, error cases, and edge inputs
★★Happy path testedTests cover the success path but miss error branches or edge cases
★Smoke test onlyTest exists but only checks the function runs without error (no meaningful assertions)
☆No test foundNo test references this codepath at all

Step 3: Produce Coverage Map

Map each codepath to its test coverage:

## Coverage Map: [filename]

| # | Codepath | Test File | Rating | Notes |
|---|----------|-----------|--------|-------|
| 1 | validateUser() happy path | test-user.sh:42 | ★★★ | Asserts valid + invalid inputs |
| 2 | validateUser() missing email | test-user.sh:58 | ★★ | Tests missing, not malformed |
| 3 | validateUser() invalid format | -- | ☆ | No test for format validation |
| 4 | processOrder() empty cart guard | -- | ☆ | Guard clause untested |
| 5 | processOrder() payment timeout | test-orders.sh:30 | ★ | Checks no crash, no assertions |
| 6 | processOrder() success | test-orders.sh:15 | ★★★ | Full integration test |

Phase 3: Coverage Diagram

After completing the map, produce an ASCII coverage summary. This is the primary output artifact.

COVERAGE: 5/12 paths tested (42%)
  Code paths: 3/5 (60%)
  User flows: 2/7 (29%)
GAPS: 7 paths need tests

Break down by category:

BY TYPE:
  conditional:  3/4 tested (75%)  ████████░░
  error:        1/5 tested (20%)  ██░░░░░░░░
  guard:        0/2 tested  (0%)  ░░░░░░░░░░
  integration:  1/1 tested (100%) ██████████

BY RISK:
  high:    1/3 tested (33%)  ███░░░░░░░
  medium:  2/5 tested (40%)  ████░░░░░░
  low:     2/4 tested (50%)  █████░░░░░

Use full block for covered and light shade for uncovered. 10-character bar. Always show exact fractions and percentages.


Phase 4: Auto-Generate Tests

Step 1: Detect Project Test Conventions

Before generating any tests, you MUST detect the project's testing patterns:

**Detected Test Conventions:**
- Framework: [jest/vitest/pytest/bash/go test/etc.]
- Location: [tests/ | __tests__/ | src/**/*.test.* | etc.]
- Naming: [test-*.sh | *.test.ts | *_test.go | etc.]
- Style: [BDD describe/it | xUnit | TAP | custom]
- Helpers: [test-utils.ts | conftest.py | helpers/ | etc.]
- Assertion library: [built-in | chai | assert | etc.]

Step 2: Generate Tests for Uncovered Paths

For each no-test and smoke-only codepath, generate a test that:

  1. Follows project naming conventions -- same directory structure, same file naming pattern
  2. Uses existing test helpers -- import from the same test utilities the project already uses
  3. Tests behavior, not implementation -- assert observable outcomes, not internal state
  4. Covers the specific gap -- targets the exact branch or error path identified in Phase 1
  5. Includes edge cases -- aim for full coverage on each generated test

Step 3: Present Generated Tests

For each generated test, show:

### Generated: test for [codepath description]
**Covers:** Codepath #N from [filename]
**Raises coverage:** from no-test to full coverage

[test code block]

Step 4: Report Before/After

After generating all tests, show the coverage change:

BEFORE: 5/12 paths tested (42%)
AFTER:  11/12 paths tested (92%)
  New tests generated: 6
  Remaining gaps: 1 (manual review needed)

Integration with Other Skills

With flow-deliver / skill-code-review

Coverage audit runs as a complement to code review. When invoked during deliver phase:

  1. Code review assesses quality and correctness
  2. Coverage audit assesses test completeness
  3. Both feed into the ship/no-ship decision

With skill-tdd

If coverage audit finds gaps in new code, recommend the user adopt TDD for the next iteration. Coverage audit fixes existing gaps; TDD prevents future ones.

With skill-verification-gate

After generating tests, use skill-verification-gate to run the test suite and confirm the new tests pass.


Red Flags -- Do Not Do This

ActionWhy It Is Wrong
Count lines instead of pathsLine coverage misses branch coverage entirely
Generate tests without checking conventionsTests that do not match project style will be rejected
Test implementation detailsBrittle tests that break on refactoring
Skip error pathsError paths are where most bugs live
Exceed the 30-path capAnalysis becomes unfocused and slow
Generate more than 20 testsDiminishing returns; focus on highest impact
Spend more than 2 min on one pathMark as needs-manual-review and move on

Quick Reference

1. TRACE   -> Identify all codepaths in the diff (max 30)
2. MAP     -> Find existing tests for each path
3. SCORE   -> Rate coverage quality (no-test / smoke / happy-path / full)
4. DIAGRAM -> ASCII coverage visualization
5. GENERATE -> Auto-create tests for gaps (max 20)
6. REPORT  -> Before/after test counts

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: skill-coverage-audit](https://darkplay.ru/ai/skills/nyldn-claude-octopus-skill-coverage-audit)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

mattpocock-skillsmattpocock · Агентские навыки Matt Pocock для настоящей инженерии: разбор задач, потоки спецификаций и…
41 комп.
superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
16 комп.
eccaffaan-m · Нативный для harness операторский слой ECC: 67 агентов, 278 навыков, 94 шима устаревших…
441 комп.
andrej-karpathy-skillsmultica-ai · Правила поведения для снижения типичных ошибок LLM при программировании: думай перед…
1 комп.
A11y Architectaffaan-m · Архитектор доступности, специализирующийся на соответствии WCAG 2.2 для веба и нативных…
225 587 ★
Agent Evaluatoraffaan-m · Оценивает результат агента по рубрике качества из 5 критериев (точность, полнота…
225 587 ★
Network Architectaffaan-m · Проектирует корпоративные и распределённые сети с маршрутизацией и автоматизацией.
225 587 ★
Opensource Forkeraffaan-m · Форкает проект для open-source: чистит секреты, ссылки и историю git.
225 587 ★
Opensource Packageraffaan-m · Готовит open-source упаковку: CLAUDE.md, README, LICENSE, CONTRIBUTING и шаблоны.
225 587 ★
Opensource Sanitizeraffaan-m · Проверяет open-source форк на утечки секретов, PII и опасные файлы перед релизом.
225 587 ★

Лучшие ИИ-инструменты для программирования

ИИ для программирования

Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные

GenAPIGenapi
По запросу
5.0
Notepad++ AINotepad-plus-plus
По запросу
4.9
GitHub CopilotGitHub
По подписке
4.9
Creatium MaxCremax
По запросу
4.8
Emacs AIGnu
По запросу
4.8
KiteKite
По запросу
4.8
Amazon Q DeveloperAmazon
По запросу
4.8
VECTA
Есть бесплатный тариф
4.8
SoftPractice
Есть бесплатный тариф
4.8
VibeForge
Есть бесплатный тариф
4.7

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8