Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(health): coverage findings carry a prompt to add tests and the rule that silences them (#4335)

Raghav Chamadiya7e28e9f91bff
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 0c859238e..2e2f48257 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -177,7 +177,10 @@ those two, `MEDIUM` otherwise. `coverage_gap` covers thin-but-present coverage,
`untested_complexity` reads the CRAP score: complexity weighted by the share of
the function a report measured as run, or by its reach tier when no report covers
it. A tier never becomes a percentage, and only measured findings are listed by
-default. The graph check
+default. A `coverage_gap` finding, and an `untested_complexity` finding on measured
+coverage or a direct test, carries `actions`: a prompt to add tests (or to split
+the function at complexity 30 and above) naming the nearest test file to extend,
+and the `.repowise/health-rules.json` rule that silences it for that file. The graph check
matters because a filename convention misses tests in both directions
([examples](../architecture/test-intelligence.md#why-a-graph-signal)).
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 85852a45d..d8cc1fd07 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -385,7 +385,7 @@ Items are ordered by value first, then tier. History markers (churn, ownership,
| `top_findings` / `findings`, `test_findings` | Production and test findings; their totals sum to the whole open set |
| metric row | `score` (defect dimension and headline), `maintainability_score`, `performance_score`, `weighted_deficit` = (8 - score) x NLOC, `is_test`, `has_test_file`, `primary_biomarker`, `total_deduction`, `structure_deduction` and `history_deduction` (the score is 10 minus both, before the 1.0 floor; history reads 0.0 under `counts="code_shape"`), `history: "short"` only when the file has fewer than 5 recorded commits (new, split out, or renamed without follow), where most history markers cannot fire yet, and `withheld_deduction` when part of it comes from a withheld finding type |
-`weighted_deficit` and the gap fields share one unit, score points x NLOC; they compare only with each other. `primary_biomarker` prefers a discrete finding over the continuous `coverage_gradient`. Each finding carries a `dimension`; `advisory` findings (`assertion_free_test`, `mock_saturated_test`, `hidden_coupling`, `brain_method`, `untested_complexity`) never deduct and appear only with `include=["advisory"]`.
+`weighted_deficit` and the gap fields share one unit, score points x NLOC; they compare only with each other. `primary_biomarker` prefers a discrete finding over the continuous `coverage_gradient`. A finding's `details.actions` (an agent prompt and the rule that silences it) appear only on the single-finding view, `finding_id=...`. Each finding carries a `dimension`; `advisory` findings (`assertion_free_test`, `mock_saturated_test`, `hidden_coupling`, `brain_method`, `untested_complexity`) never deduct and appear only with `include=["advisory"]`.
Provisional finding types appear only with `include=["unverified"]`, each marked `verification: "unverified"`. A withheld type never lists but still lowers the score it was counted in, so a file row reports it as `withheld_deduction` and `_meta.withheld` names the type, its count and why it is held back. Targeted mode is never split into production and test.
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
index 88495480a..ac8a19658 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/base.py
@@ -138,6 +138,11 @@ class FileContext:
# Start line of each function a test reaches on the call graph, to the call
# hops of the nearest such test (1: a test calls it). Empty without a graph.
function_test_hops: dict[int, int] = field(default_factory=dict)
+ # The same functions' nearest test file, and the file's own: the nearest
+ # test any of its functions has, else a test file named for it. ``None``
+ # when nothing names one.
+ function_test_files: dict[int, str] = field(default_factory=dict)
+ file_test: str | None = None
@property
def is_test_material(self) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py
index 22751aad9..d0e7a6167 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/coverage_gap.py
@@ -13,6 +13,7 @@ does nothing — the absence-of-coverage case is the
from __future__ import annotations
+from ..coverage_actions import coverage_actions
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -56,6 +57,7 @@ class CoverageGapDetector:
else:
severity = Severity.LOW
+ reason = f"{uncovered}/{total} lines uncovered ({cov:.0f}% line coverage)"
return [
BiomarkerResult(
biomarker_type=self.name,
@@ -68,8 +70,16 @@ class CoverageGapDetector:
"branch_coverage_pct": ctx.branch_coverage_pct,
"uncovered_lines": uncovered,
"total_coverable_lines": total,
+ # Measured by construction: the report is what fired it.
+ "actions": coverage_actions(
+ self.name,
+ ctx.file_path,
+ function=None,
+ target_test=ctx.file_test,
+ evidence=reason,
+ ),
},
- reason=(f"{uncovered}/{total} lines uncovered ({cov:.0f}% line coverage)"),
+ reason=reason,
)
]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/untested_complexity.py b/packages/core/src/repowise/core/analysis/health/biomarkers/untested_complexity.py
index f8bb37025..79d1d6598 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/untested_complexity.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/untested_complexity.py
@@ -13,6 +13,7 @@ refactor rather than tests. Test files are exempt.
from __future__ import annotations
from ..complexity.dispatch import judged_ccn
+from ..coverage_actions import coverage_actions
from ..crap import CRAP_THRESHOLD, coverage_tier, function_coverage, function_crap
from ..models import Severity
from .base import BiomarkerResult, FileContext
@@ -86,6 +87,18 @@ class UntestedComplexityDetector:
reason = f"{fn.name} has CRAP {result.crap:.0f} (complexity {ccn}, {covered})"
if refactor:
reason += "; full coverage would not bring it under 30, so simplify it"
+ # ``actions`` carries the step ``action`` names, with its prompt.
+ # Only on evidence of what runs: a measurement, or a test that calls
+ # it. A graph that found no test is not a reason to act.
+ if is_measured or tier == "direct":
+ details["actions"] = coverage_actions(
+ self.name,
+ ctx.file_path,
+ function=fn.name,
+ target_test=ctx.function_test_files.get(fn.start_line) or ctx.file_test,
+ evidence=f"CRAP {result.crap:.0f} at complexity {ccn}, {covered}",
+ refactor=refactor,
+ )
out.append(
BiomarkerResult(
biomarker_type=self.name,
diff --git a/packages/core/src/repowise/core/analysis/health/coverage_actions.py b/packages/core/src/repowise/core/analysis/health/coverage_actions.py
new file mode 100644
index 000000000..463b9a91e
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/coverage_actions.py
@@ -0,0 +1,123 @@
+"""The actions a coverage finding carries: which test to extend, and how to silence it.
+
+Pure functions over paths and names. An action is raised only on evidence that
+says what tests run: a measured coverage report, or a test that calls the
+function directly. A graph that found no test reaching the code is never the
+reason, since its recall is partial.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from collections.abc import Collection, Mapping
+from pathlib import PurePosixPath
+from typing import Any
+
+from ...test_paths import names_test_for, paired_test_names
+from ..execution_graph import file_of_symbol
+
+#: The user-authored file that turns a marker off for a path (``health/config.py``).
+HEALTH_RULES_FILE = ".repowise/health-rules.json"
+
+_CONSTRAINTS = (
+ "Read the source and at least one nearby test first, and follow the project's "
+ "test framework, fixtures and naming.",
+ "Cover the untested branches with behaviour-named tests; do not pad coverage "
+ "with trivial cases.",
+ "Mock external IO, never the code under test. If a test exposes a real bug, "
+ "keep it failing and say so rather than fixing it silently.",
+)
+
+
+def paired_test_index(test_files: Collection[str]) -> dict[str, list[str]]:
+ """Test files by file name, built once so a pairing lookup stays a dict hit."""
+ index: dict[str, list[str]] = {}
+ for path in sorted(test_files):
+ index.setdefault(PurePosixPath(path).name, []).append(path)
+ return index
+
+
+def nearest_test_file(
+ rel_path: str,
+ selector: str | None = None,
+ paired: Mapping[str, list[str]] | None = None,
+) -> str | None:
+ """The test file to extend for *rel_path*, ``None`` when nothing names one.
+
+ *selector* is the nearest test that runs the code (``function_test_map``);
+ its file wins. Otherwise a test file named for *rel_path* (``test_x.py``,
+ ``x.test.ts``), its own language first.
+ """
+ if selector:
+ return file_of_symbol(selector)
+ named = [
+ test
+ for name in paired_test_names(rel_path)
+ for test in (paired or {}).get(name, ())
+ if names_test_for(test, rel_path)
+ ]
+ # A test in the file's own language first: ``router.test.ts`` is not ``router.py``'s.
+ suffix = PurePosixPath(rel_path).suffix
+ return min(named, key=lambda t: (PurePosixPath(t).suffix != suffix, t), default=None)
+
+
+def _literal_glob(rel_path: str) -> str:
+ """*rel_path* as a gitignore pattern matching only itself: anchored at the
+ root, so ``setup.py`` is not every ``setup.py``, and ``[id]`` is literal."""
+ return "/" + re.sub(r"([\\\[\]*?! #])", r"\\\1", rel_path)
+
+
+def suppress_how(biomarker: str, rel_path: str) -> str:
+ """The ``health-rules.json`` rule that turns *biomarker* off for this file."""
+ rule = {"rules": [{"path": _literal_glob(rel_path), "disabled_biomarkers": [biomarker]}]}
+ return f"{HEALTH_RULES_FILE}: {json.dumps(rule)}"
+
+
+def add_tests_prompt(
+ biomarker: str, rel_path: str, function: str | None, target_test: str | None, evidence: str
+) -> str:
+ """An agent prompt to test the code a coverage finding names."""
+ # Deferred: the fix_first package imports the biomarkers, which import this.
+ from .fix_first.text import FINDING_TITLE, PROBLEM
+
+ where = f"`{function}` in `{rel_path}`" if function else f"`{rel_path}`"
+ title = FINDING_TITLE.get(biomarker, "Add tests for {where}").format(where=where)
+ problem = PROBLEM.get(biomarker, "has little test coverage")
+ target = (
+ f"Extend `{target_test}`."
+ if target_test
+ else "Add a test beside the project's existing tests for this code."
+ )
+ lines = [f"{title}.", "", f"{where} {problem}: {evidence}.", target, "", "Constraints:"]
+ lines += [f"- {c}" for c in _CONSTRAINTS]
+ return "\n".join(lines)
+
+
+def coverage_actions(
+ biomarker: str,
+ rel_path: str,
+ *,
+ function: str | None,
+ target_test: str | None,
+ evidence: str,
+ refactor: bool = False,
+) -> list[dict[str, Any]]:
+ """``add-tests`` (or ``refactor`` when tests alone cannot clear it), then ``suppress``."""
+ first: dict[str, Any]
+ if refactor:
+ where = f"`{function}` in `{rel_path}`" if function else f"`{rel_path}`"
+ first = {
+ "kind": "refactor",
+ "prompt": (
+ f"Split {where} into smaller functions: {evidence}, and its complexity "
+ "keeps it above the bar even at full coverage. Then test the parts."
+ ),
+ }
+ else:
+ first = {
+ "kind": "add-tests",
+ **({"target_test": target_test} if target_test else {}),
+ "prompt": add_tests_prompt(biomarker, rel_path, function, target_test, evidence),
+ }
+ return [first, {"kind": "suppress", "how": suppress_how(biomarker, rel_path)}]
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index fea963a6a..b3dea17fb 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -46,6 +46,7 @@ from ..graph_view import ImportEdgeView
from .asserts.lexicon import AssertVocabulary
from .asserts.oracle_reach import collect_cross_file_oracles
from .complexity import FileComplexity, FunctionComplexity, walk_file
+from .coverage_actions import paired_test_index
from .crossfn_perf import CrossFunctionPerfStage
from .dataflow import FileDataflowCache
from .duplication import ClonePair, DuplicationReport
@@ -972,6 +973,7 @@ class HealthAnalyzer:
methods_by_file=build_methods_by_file(self.graph),
dataflow_cache=dataflow_cache,
function_tests=function_tests,
+ paired_test_files=paired_test_index(self.test_index.all_test_files()),
)
def _evaluate_all(
diff --git a/packages/core/src/repowise/core/analysis/health/file_evaluator.py b/packages/core/src/repowise/core/analysis/health/file_evaluator.py
index 39508f14f..b3b353c1a 100644
--- a/packages/core/src/repowise/core/analysis/health/file_evaluator.py
+++ b/packages/core/src/repowise/core/analysis/health/file_evaluator.py
@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Any
from ...ingestion.git_indexer.function_blame import BlameIndex
from ...ingestion.package_roots import module_for as _module_for
+from ..execution_graph import file_of_symbol
from ..graph_view import HasEdge
from ..test_reach.type_only import is_type_only, may_be_type_only
from .asserts.lexicon import AssertVocabulary
@@ -16,6 +17,7 @@ from .biomarkers.base import BiomarkerResult
from .biomarkers.function_hotspot import refresh_replayed
from .complexity import FileComplexity, FunctionComplexity
from .complexity.languages import has_health_dialect
+from .coverage_actions import nearest_test_file
from .dataflow import FileDataflowCache
from .duplication import ClonePair, DuplicationReport
from .finding_identity import SYMBOL_INDEX_KEY, SYMBOL_KEY, SYMBOL_LINE_KEY
@@ -28,7 +30,7 @@ from .scoring import attach_impacts, file_score_fields, remap_severities, score_
from .source_reader import SourceReader
if TYPE_CHECKING:
- from ..function_test_map import FunctionTests
+ from ..function_test_map import FunctionTests, MappedTest
from .engine import HealthAnalyzer
#: Function facts a finding inside the function carries in its details.
@@ -224,6 +226,8 @@ class FileEvaluator:
methods_by_file: dict[str, tuple[str, ...]] | None = None
dataflow_cache: FileDataflowCache | None = None
function_tests: FunctionTests | None = None
+ #: Test files by file name (``coverage_actions.paired_test_index``).
+ paired_test_files: dict[str, list[str]] | None = None
def evaluate(
self, pf: Any, fcx: FileComplexity
@@ -306,23 +310,39 @@ class FileEvaluator:
perf_hits=fcx.perf_hits,
io_boundary_names=set(fcx.io_boundary_names),
cross_file_oracle_lines=frozenset(getattr(fcx, "cross_file_oracles", ())),
- function_test_hops=self._function_test_hops(pf, fcx),
+ **self._nearest_tests(pf, fcx),
)
- def _function_test_hops(self, pf: Any, fcx: FileComplexity) -> dict[int, int]:
- """Each function's start line to the hops of the nearest test that reaches it."""
- if not self.function_tests or pf.file_info.is_test:
+ def _nearest_tests(self, pf: Any, fcx: FileComplexity) -> dict[str, Any]:
+ """Each function's nearest test (hops and file), and the file's own test."""
+ if pf.file_info.is_test:
+ return {}
+ path = pf.file_info.path
+ nearest = self._function_tests(path, fcx)
+ hops = {line: test.hops for line, test in nearest.items()}
+ files = {line: file_of_symbol(test.selector) for line, test in nearest.items()}
+ closest = min(nearest.values(), key=lambda t: t.hops, default=None)
+ return {
+ "function_test_hops": hops,
+ "function_test_files": files,
+ "file_test": nearest_test_file(
+ path, closest.selector if closest else None, self.paired_test_files
+ ),
+ }
+
+ def _function_tests(self, path: str, fcx: FileComplexity) -> dict[int, MappedTest]:
+ """Each function's start line to the nearest test that reaches it."""
+ if not self.function_tests:
return {}
index = self.analyzer._execution_graph()
if index is None:
return {}
- path = pf.file_info.path
- out: dict[int, int] = {}
+ out: dict[int, MappedTest] = {}
for fc in fcx.functions:
symbol = index.resolve_function(path, fc.start_line, func_end=fc.end_line)
tests = self.function_tests.get(symbol) if symbol is not None else None
if tests:
- out[fc.start_line] = tests[0].hops
+ out[fc.start_line] = tests[0]
return out
def _findings(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/details.py b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
index 7dec43f08..d99e338f8 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/details.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/details.py
@@ -104,7 +104,10 @@ async def _finding_detail_response(
"finding_id": finding_id,
"finding": (
_serialize_finding(
- match, reference_repository, await _lower_priority(session, repository.id, match)
+ match,
+ reference_repository,
+ await _lower_priority(session, repository.id, match),
+ with_actions=True,
)
if match
else None
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py
index a0e809ce5..4116cb493 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py
@@ -100,12 +100,20 @@ def _legacy_health_finding_id(f: Any, repository: str) -> str:
def _serialize_finding(
- f: HealthFinding, repository: str = "default", lower_priority: str | None = None
+ f: HealthFinding,
+ repository: str = "default",
+ lower_priority: str | None = None,
+ *,
+ with_actions: bool = False,
) -> dict[str, Any]:
+ """One finding as a row. ``details.actions`` (prompts, a suppress rule) ride
+ only on the single-finding view, so a list keeps its size."""
try:
details = json.loads(f.details_json) if f.details_json else {}
except Exception:
details = {}
+ if not with_actions and isinstance(details, dict):
+ details.pop("actions", None)
dimension = getattr(f, "dimension", None) or "defect"
rank = (
{"perf_rank": _perf_rank(f.biomarker_type, details)} if dimension == "performance" else {}
diff --git a/packages/ui/__tests__/health/finding-actions.test.tsx b/packages/ui/__tests__/health/finding-actions.test.tsx
new file mode 100644
index 000000000..582772224
--- /dev/null
+++ b/packages/ui/__tests__/health/finding-actions.test.tsx
@@ -0,0 +1,23 @@
+import { describe, it, expect } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { FindingActions } from "../../src/health/finding-actions.js";
+import { AGENT_PROMPT_LABEL } from "../../src/health/ai-prompt-action.js";
+
+const ACTIONS = [
+ { kind: "add-tests", target_test: "tests/test_router.py", prompt: "Add tests for `src/router.py`." },
+ { kind: "suppress", how: '.repowise/health-rules.json: {"rules": []}' },
+];
+
+describe("FindingActions", () => {
+ it("leads with the copy-prompt, then the test to extend and the suppress rule", () => {
+ render(<FindingActions details={{ actions: ACTIONS }} filePath="src/router.py" />);
+ expect(screen.getByRole("button", { name: AGENT_PROMPT_LABEL })).toBeInTheDocument();
+ expect(screen.getByText("tests/test_router.py")).toBeInTheDocument();
+ expect(screen.getByText(/health-rules\.json/)).toBeInTheDocument();
+ });
+
+ it("renders nothing for a finding with no actions", () => {
+ const { container } = render(<FindingActions details={{ crap: 40 }} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/ui/src/health/file-drawer/issues.tsx b/packages/ui/src/health/file-drawer/issues.tsx
index c2f504ea9..3a24a5e7d 100644
--- a/packages/ui/src/health/file-drawer/issues.tsx
+++ b/packages/ui/src/health/file-drawer/issues.tsx
@@ -23,6 +23,7 @@ import {
isHistoryBiomarker,
} from "../biomarker-glossary";
import { BiomarkerDetails } from "../biomarker-details";
+import { FindingActions } from "../finding-actions";
import { plainIssue } from "../plain-language";
import { SeverityMark } from "../severity-mark";
import { VerificationTag } from "../verification-tag";
@@ -75,6 +76,7 @@ export function FindingDetail({
{suggestion}
</p>
) : null}
+ <FindingActions details={f.details} />
</>
);
}
diff --git a/packages/ui/src/health/finding-actions.tsx b/packages/ui/src/health/finding-actions.tsx
new file mode 100644
index 000000000..347057e8c
--- /dev/null
+++ b/packages/ui/src/health/finding-actions.tsx
@@ -0,0 +1,75 @@
+"use client";
+
+import { AiPromptButton } from "./ai-prompt-button";
+import { AGENT_PROMPT_LABEL, useAiPromptAction } from "./ai-prompt-action";
+
+/** One entry of a finding's `details.actions`, as the health engine writes it. */
+interface FindingAction {
+ kind: string;
+ prompt?: string;
+ target_test?: string;
+ how?: string;
+}
+
+const PROMPT_TITLE: Record<string, string> = {
+ "add-tests": "Add tests",
+ refactor: "Simplify, then test",
+};
+
+function readActions(details: Record<string, unknown> | null | undefined): FindingAction[] {
+ const raw = details?.actions;
+ if (!Array.isArray(raw)) return [];
+ return raw.filter(
+ (a): a is FindingAction =>
+ typeof a === "object" && a !== null && typeof (a as FindingAction).kind === "string",
+ );
+}
+
+/**
+ * A finding's own actions: the copy-prompt first (the primary way to act on
+ * it), then the test to extend and the rule that would silence it. Renders
+ * nothing for a finding that carries no actions.
+ */
+export function FindingActions({
+ details,
+ filePath,
+}: {
+ details: Record<string, unknown> | null | undefined;
+ filePath?: string | null;
+}) {
+ const { openPrompt, promptModal } = useAiPromptAction();
+ const actions = readActions(details);
+ const lead = actions.find((a) => typeof a.prompt === "string" && a.prompt.length > 0);
+ const suppress = actions.find((a) => a.kind === "suppress" && a.how);
+ if (!lead && !suppress) return null;
+ return (
+ <div className="flex flex-col gap-1.5 text-xs text-[var(--color-text-secondary)]">
+ {lead ? (
+ <div className="flex flex-wrap items-center gap-2">
+ <AiPromptButton
+ label={AGENT_PROMPT_LABEL}
+ onClick={() =>
+ openPrompt({
+ title: PROMPT_TITLE[lead.kind] ?? "Act on this finding",
+ filePath: filePath ?? null,
+ getPrompt: () => lead.prompt ?? "",
+ })
+ }
+ />
+ {lead.target_test ? (
+ <span>
+ Extend <code className="font-mono">{lead.target_test}</code>
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+ {suppress ? (
+ <p>
+ <span className="font-medium text-[var(--color-text-primary)]">To silence it: </span>
+ <code className="font-mono break-all">{suppress.how}</code>
+ </p>
+ ) : null}
+ {promptModal}
+ </div>
+ );
+}
diff --git a/tests/unit/health/test_coverage_actions.py b/tests/unit/health/test_coverage_actions.py
new file mode 100644
index 000000000..e8b2ea813
--- /dev/null
+++ b/tests/unit/health/test_coverage_actions.py
@@ -0,0 +1,189 @@
+"""The actions a coverage finding carries: the test to extend, the prompt, the suppress rule.
+
+Raised only from a measured report or a test that calls the function, never
+because the graph found no test.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers import FileContext
+from repowise.core.analysis.health.biomarkers.coverage_gap import BIOMARKER as COVERAGE_GAP
+from repowise.core.analysis.health.biomarkers.untested_complexity import BIOMARKER as CRAP
+from repowise.core.analysis.health.complexity.models import FunctionComplexity
+from repowise.core.analysis.health.config import HealthConfig
+from repowise.core.analysis.health.coverage_actions import (
+ coverage_actions,
+ nearest_test_file,
+ paired_test_index,
+ suppress_how,
+)
+
+_TESTS = paired_test_index(
+ ["tests/test_router.py", "tests/test_router_golden.py", "web/router.test.ts", "tests/test_other.py"]
+)
+
+
+# --------------------------------------------------------------------------
+# The test to extend
+# --------------------------------------------------------------------------
+
+
+def test_the_nearest_mapped_test_wins() -> None:
+ selector = "tests/integration/test_flow.py::test_routes"
+ assert nearest_test_file("src/router.py", selector, _TESTS) == "tests/integration/test_flow.py"
+
+
+def test_a_js_selector_is_the_test_file_itself() -> None:
+ assert nearest_test_file("web/router.ts", "web/router.test.ts", _TESTS) == "web/router.test.ts"
+
+
+def test_without_a_mapped_test_a_test_named_for_the_file() -> None:
+ assert nearest_test_file("src/router.py", None, _TESTS) == "tests/test_router.py"
+ assert nearest_test_file("web/router.ts", None, _TESTS) == "web/router.test.ts"
+
+
+def test_nothing_named_for_it_names_nothing() -> None:
+ assert nearest_test_file("src/billing.py", None, _TESTS) is None
+
+
+# --------------------------------------------------------------------------
+# The suppress rule is the real one
+# --------------------------------------------------------------------------
+
+
+ "path",
+ ["src/legacy/foo.py", "packages/web/src/app/repos/[id]/tests/page.tsx", "setup.py", "a b.py"],
+)
+def test_the_suppress_rule_silences_exactly_that_file(path: str) -> None:
+ how = suppress_how("coverage_gap", path)
+ file, _, rule = how.partition(": ")
+ assert file == ".repowise/health-rules.json"
+ cfg = HealthConfig.from_json(rule)
+ # A root file stays anchored: ``pkg/setup.py`` is another file.
+ disabled = cfg.per_file_disabled([path, "src/legacy/bar.py", "pkg/setup.py"])
+ assert disabled == {path: {"coverage_gap"}}
+
+
+# --------------------------------------------------------------------------
+# Action shapes
+# --------------------------------------------------------------------------
+
+
+def test_add_tests_then_suppress() -> None:
+ actions = coverage_actions(
+ "coverage_gap", "src/router.py", function=None, target_test="tests/test_router.py",
+ evidence="40/90 lines uncovered (56% line coverage)",
+ )
+ assert [a["kind"] for a in actions] == ["add-tests", "suppress"]
+ add = actions[0]
+ assert add["target_test"] == "tests/test_router.py"
+ assert "Extend `tests/test_router.py`" in add["prompt"]
+ assert "Add tests for `src/router.py`" in add["prompt"]
+ assert "40/90 lines uncovered" in add["prompt"]
+
+
+def test_no_target_omits_the_key_and_says_where_to_add() -> None:
+ add = coverage_actions(
+ "coverage_gap", "src/billing.py", function=None, target_test=None, evidence="x"
+ )[0]
+ assert "target_test" not in add
+ assert "Add a test beside" in add["prompt"]
+
+
+def test_refactor_replaces_add_tests() -> None:
+ actions = coverage_actions(
+ "untested_complexity", "src/router.py", function="route", target_test="tests/test_router.py",
+ evidence="CRAP 30", refactor=True,
+ )
+ assert [a["kind"] for a in actions] == ["refactor", "suppress"]
+ assert "`route` in `src/router.py`" in actions[0]["prompt"]
+
+
+# --------------------------------------------------------------------------
+# The biomarkers carry them only on evidence
+# --------------------------------------------------------------------------
+
+
+def _fn(start: int, end: int, ccn: int) -> FunctionComplexity:
+ return FunctionComplexity(
+ name="route", start_line=start, end_line=end, ccn=ccn, max_nesting=1, cognitive=ccn,
+ nloc=end - start,
+ )
+
+
+def _ctx(**kw) -> FileContext:
+ base = {
+ "file_path": "src/router.py",
+ "language": "python",
+ "nloc": 200,
+ "has_test_file": False,
+ "module": None,
+ "is_test": False,
+ }
+ base.update(kw)
+ return FileContext(**base)
+
+
+def test_a_coverage_gap_names_the_file_test() -> None:
+ ctx = _ctx(line_coverage_pct=20.0, total_coverable_lines=100, file_test="tests/test_router.py")
+ (finding,) = COVERAGE_GAP.detect(ctx)
+ assert [a["kind"] for a in finding.details["actions"]] == ["add-tests", "suppress"]
+ assert finding.details["actions"][0]["target_test"] == "tests/test_router.py"
+
+
+def test_measured_crap_carries_actions_with_the_function_test() -> None:
+ lines = set(range(1, 21))
+ ctx = _ctx(
+ all_functions=(_fn(1, 20, 7),),
+ line_coverage_pct=0.0,
+ coverable_lines=lines,
+ total_coverable_lines=20,
+ function_test_files={1: "tests/test_route_paths.py"},
+ file_test="tests/test_router.py",
+ )
+ (finding,) = CRAP.detect(ctx)
+ assert finding.details["actions"][0]["target_test"] == "tests/test_route_paths.py"
+
+
+def test_a_directly_tested_function_carries_actions() -> None:
+ ctx = _ctx(all_functions=(_fn(1, 60, 40),), function_test_hops={1: 1})
+ (finding,) = CRAP.detect(ctx)
+ assert finding.details["coverage_tier"] == "direct"
+ assert [a["kind"] for a in finding.details["actions"]] == ["refactor", "suppress"]
+
+
[email protected](("hops", "reached"), [(None, False), (None, True), (2, False)])
+def test_no_action_when_only_the_graph_speaks(hops, reached) -> None:
+ """``none`` means the graph found nothing; ``reached`` is reach, not a test run."""
+ ctx = _ctx(
+ all_functions=(_fn(1, 40, 12),),
+ reached_by_tests=reached,
+ function_test_hops={1: hops} if hops else {},
+ file_test="tests/test_router.py",
+ )
+ (finding,) = CRAP.detect(ctx)
+ assert finding.details["coverage_basis"] == "estimated"
+ assert "actions" not in finding.details
+
+
+# --------------------------------------------------------------------------
+# Engine wiring: the nearest test reaches the finding
+# --------------------------------------------------------------------------
+
+
[email protected]("calls", [True, False])
+def test_the_engine_names_the_test_to_extend(tmp_path, calls: bool) -> None:
+ """Through the function test map when a test calls it, else by name."""
+ from repowise.core.analysis.health import HealthAnalyzer
+ from repowise.core.analysis.health.coverage.model import coverage_map_entry, file_coverage
+ from tests.unit.health.test_untested_complexity import _graph, _tree
+
+ entry = coverage_map_entry(file_coverage("src/router.py", (), range(1, 25)), "lcov")
+ report = HealthAnalyzer(
+ _graph(calls=calls), parsed_files=_tree(tmp_path), coverage_map={"src/router.py": entry}
+ ).analyze()
+ (finding,) = [f for f in report.findings if f.biomarker_type == "untested_complexity"]
+ assert finding.details["actions"][0]["target_test"] == "tests/test_router.py"
diff --git a/tests/unit/server/mcp/test_health_untested_complexity.py b/tests/unit/server/mcp/test_health_untested_complexity.py
index 0abb21edc..a227982fa 100644
--- a/tests/unit/server/mcp/test_health_untested_complexity.py
+++ b/tests/unit/server/mcp/test_health_untested_complexity.py
@@ -24,7 +24,14 @@ def _row(repo_id: str, name: str, basis: str, crap: float) -> HealthFinding:
line_start=10,
line_end=40,
details_json=json.dumps(
- {"crap": crap, "ccn": 8, "coverage_basis": basis, "action": "add_tests", **cov}
+ {
+ "crap": crap,
+ "ccn": 8,
+ "coverage_basis": basis,
+ "action": "add_tests",
+ **cov,
+ "actions": [{"kind": "add-tests", "prompt": f"Test {name}."}],
+ }
),
reason=f"{name} has CRAP {crap:.0f}",
dimension="advisory",
@@ -96,3 +103,15 @@ async def test_held_estimates_are_counted_not_listed(setup_mcp, crap_rows):
gated = (await get_health(targets=["src/auth/service.py"], include=["advisory"]))["_meta"]["gated"]
assert gated["health"]["estimated"] == 1
assert gated["opt_in"] == {"include": ["unverified"]}
+
+
+async def test_actions_ride_only_on_the_single_finding_view(setup_mcp, crap_rows):
+ from repowise.server.mcp_server import get_health
+
+ listed = await get_health(targets=["src/auth/service.py"], include=["advisory"])
+ rows = [f for f in listed["findings"] if f["biomarker_type"] == "untested_complexity"]
+ assert rows and all("actions" not in f["details"] for f in rows)
+
+ detail = await get_health(finding_id=rows[0]["id"])
+ assert detail["finding"]["details"]["actions"][0]["kind"] == "add-tests"