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(findings): add a finding-type registry that decides what surfaces show (#2687)

Swati Ahuja27cf27ace7e7
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 661d84db7..b32d6d8dc 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -1047,6 +1047,14 @@ never silently: the response carries `truncated: true`, the `*_total` /
`_meta.omitted` names refs that restore the dropped rows. Re-requesting one
block with `only` also recovers it.
+**Finding types must earn their place.** `core/analysis/finding_registry.py`
+records each finding type as `validated`, `provisional` or `hidden`. Hidden
+types never appear in `get_health`, `get_dead_code`, overview, priorities or
+wiki prompts (the analyzers still run). Provisional types appear only when asked
+for — `include=["unverified"]` here, `kind=` on `get_dead_code` — and each row
+carries `verification: "unverified"`. `get_dead_code` reports what it held back
+in `summary.withheld_types`.
+
**Test material is bucketed, not hidden.** Every metric row carries `is_test`
(distinct from `has_test_file`: "is this file a test" vs "is this file tested").
In dashboard mode the ranked finding lists are split — `top_findings` /
@@ -1055,9 +1063,12 @@ In dashboard mode the ranked finding lists are split — `top_findings` /
a test asks a different question from defect risk in the code it covers, and at
the default limit a quarter of the headline list was describing the test suite.
Targeted mode is never split: you named the files, so you get their findings.
-KPIs, `worst_files` and `high_leverage_files` deliberately still include test
-files — excluding them would move the repo's headline score, which is a scoring
-change, not a display one.
+The ranked file lists split the same way: `worst_files` and
+`high_leverage_files` (and the `directive` built from them) are production files,
+and `test_worst_files` ranks the test files. `kpis.worst_performer_path` is the
+worst production file and `kpis.worst_test_path` the worst test file. The KPI
+averages still include test files — excluding them would move the repo's
+headline score, which is a scoring change, not a display one.
**Leverage, not just lowness.** `average_health` is NLOC-weighted (the number the
badge and dashboard surface), so a few large low-scoring files hold it down. To
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
index f711153fd..ad3f448dc 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/summary.py
@@ -51,7 +51,8 @@ def _render_performance_section(report: Any, lang_by_path: dict[str, str]) -> No
cov_line += f"; {coverage.skipped_files} skipped in unsupported languages ({langs})"
console.print(cov_line)
console.print(
- "[dim]Scope: I/O-in-loop / N+1, resource/regex/defer-in-loop, blocking-in-async. "
+ "[dim]Scope: I/O-in-loop (N+1 on database calls), resource/regex/defer-in-loop, "
+ "blocking-in-async. "
"Not covered: algorithmic blowups, GC pressure, ORM lazy-load N+1.[/dim]"
)
diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.py
index e998001c9..aba2dbe3b 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -14,6 +14,7 @@ from collections import OrderedDict
from dataclasses import dataclass
from ...test_paths import is_test_related_path
+from ..finding_registry import excluded_types
from ..health import HEALTH_ANALYZER_VERSION, HealthFindingData
from ..health.perf.causal import PERFORMANCE_MODEL_VERSION
from ..health.scoring import ADVISORY_DIMENSION, is_advisory
@@ -272,18 +273,23 @@ class ChangeHealthDeltaService:
# file cannot contribute a one-sided "introduced" or "resolved".
# Advisory markers deduct nothing, so adding one is not a regression
# and removing one is not a fix. Dropped from BOTH sides before
- # matching, so every counter derived from the match agrees.
+ # matching, so every counter derived from the match agrees. Types the
+ # finding-type registry withholds go the same way, for the same reason.
+ withheld = excluded_types()
base_findings = [
f
for f in base_run.findings
if rename.get(f.file_path, f.file_path) in subject
and not is_advisory(f.biomarker_type)
and not _is_test_perf(f)
+ and f.biomarker_type not in withheld
]
head_findings = [
f
for f in head_run.findings_for(subject)
- if not is_advisory(f.biomarker_type) and not _is_test_perf(f)
+ if not is_advisory(f.biomarker_type)
+ and not _is_test_perf(f)
+ and f.biomarker_type not in withheld
]
match = matcher.match(base_findings, head_findings)
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index c5aaafc13..767068d86 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -870,7 +870,7 @@ class DeadCodeAnalyzer:
whitelist = set(cfg.get("whitelist", []))
if cfg.get("detect_unreachable_files", True):
- findings.extend(self._detect_unreachable_files(dynamic_patterns, whitelist))
+ findings.extend(self._detect_unreachable_files(whitelist))
if on_step:
on_step("unreachable_files")
@@ -936,7 +936,6 @@ class DeadCodeAnalyzer:
def _detect_unreachable_files(
self,
- dynamic_patterns: tuple[str, ...],
whitelist: set[str],
) -> list[DeadCodeFindingData]:
"""Detect files nothing can reach that are not tests, fixtures, or config."""
@@ -969,7 +968,7 @@ class DeadCodeAnalyzer:
if is_file_reachable(str(node), self.graph, rescues):
continue
- finding = self._make_unreachable_finding(str(node), node_data, dynamic_patterns)
+ finding = self._make_unreachable_finding(str(node), node_data)
if finding:
findings.append(finding)
@@ -1067,7 +1066,6 @@ class DeadCodeAnalyzer:
self,
node: str,
node_data: dict,
- dynamic_patterns: tuple[str, ...],
) -> DeadCodeFindingData | None:
"""Create an unreachable file finding with confidence scoring."""
git_meta = self.git_meta_map.get(node)
@@ -1116,9 +1114,9 @@ class DeadCodeAnalyzer:
if risk_factors:
confidence = min(confidence, RISK_CAP_CONFIDENCE)
- safe = confidence >= SAFE_CONFIDENCE_THRESHOLD
- if safe and self._matches_dynamic_patterns(node, dynamic_patterns):
- safe = False
+ # A whole file is a review candidate, never deletion-ready: see
+ # ``REVIEW_ONLY_KINDS``. Confidence still ranks it.
+ safe = False
evidence = ["in_degree=0 (no files import this)"]
if no_git_signal:
@@ -1941,10 +1939,6 @@ class DeadCodeAnalyzer:
return False
- def _matches_dynamic_patterns(self, path: str, patterns: tuple[str, ...]) -> bool:
- name = Path(path).stem
- return any(fnmatch.fnmatch(name, pattern) for pattern in patterns)
-
def _name_matches_dynamic(self, name: str, patterns: tuple[str, ...]) -> bool:
return any(fnmatch.fnmatch(name, pattern) for pattern in patterns)
diff --git a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
index cb669c6d7..2f1994469 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
@@ -52,6 +52,12 @@ NO_GIT_SIGNAL_CONFIDENCE: float = 0.5
# reads as deletion-ready.
RISK_CAP_CONFIDENCE: float = 0.4
+# Finding kinds that are never deletion-ready, whatever their confidence. A
+# whole file with no importers was measured well below the deletion-ready bar
+# (files read by build scripts, manifests and runtime loaders by path), so it
+# is a review candidate until path mentions and entry-shape evidence exist.
+REVIEW_ONLY_KINDS: frozenset[str] = frozenset({"unreachable_file"})
+
# Filename-stem tokens → risk-factor tag. Matched against the basename split on
# ``. _ -`` so ``environment.db.js`` yields {environment, db, js} → environment
# + database. Deliberately curated: broad identifiers (app, main, index, core,
@@ -198,6 +204,7 @@ def effective_safe_to_delete(
confidence: float,
file_path: str,
stored_safe: bool = True,
+ kind: str | None = None,
) -> bool:
"""Re-derive whether a finding is genuinely deletion-ready.
@@ -206,9 +213,10 @@ def effective_safe_to_delete(
- never True when ``stored_safe`` is already False,
- never True below :data:`SAFE_CONFIDENCE_THRESHOLD`,
- - never True when the path carries any runtime-load risk factor.
+ - never True when the path carries any runtime-load risk factor,
+ - never True for a :data:`REVIEW_ONLY_KINDS` finding.
"""
- if not stored_safe:
+ if not stored_safe or kind in REVIEW_ONLY_KINDS:
return False
if confidence < SAFE_CONFIDENCE_THRESHOLD:
return False
diff --git a/packages/core/src/repowise/core/analysis/finding_registry.py b/packages/core/src/repowise/core/analysis/finding_registry.py
new file mode 100644
index 000000000..1ac343a4b
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/finding_registry.py
@@ -0,0 +1,136 @@
+"""Which finding types a surface may show, and on what evidence.
+
+One switch per finding type — a dead-code ``kind`` or a health
+``biomarker_type``; the two families share no names — so a type that has not
+earned its place can be taken off every surface at once, without deleting the
+analyzer that produces it. Visibility only: analyzers still run, rows are still
+persisted and scored, and the raw CLI analysis still reports them.
+
+- ``validated``: shown everywhere. A type absent from :data:`REGISTRY` is
+ validated — it shipped before measurement existed and stays on until a
+ measurement says otherwise.
+- ``provisional``: shown only when a caller asks for it by name (or opts into
+ unverified types), and then labelled :data:`UNVERIFIED_LABEL`.
+- ``hidden``: never shown on a default surface (overview, priorities, MCP,
+ REST lists, wiki prompts). Surfaces may report how many were held back.
+
+A type moves back to ``validated`` only when its measured precision clears the
+family floor; the measurement fields record the evidence either way.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass
+from typing import Literal
+
+FindingStatus = Literal["validated", "provisional", "hidden"]
+
+#: The label a provisional finding carries wherever it is shown.
+UNVERIFIED_LABEL = "unverified"
+
+
+@dataclass(frozen=True)
+class FindingTypeStatus:
+ status: FindingStatus
+ #: Measured precision and its Wilson 95% lower bound, or ``None`` when the
+ #: type has not been measured.
+ precision: float | None = None
+ ci_low: float | None = None
+ #: What the measurement ran on, in words (no repository names).
+ corpus: str | None = None
+ #: ISO date of the measurement.
+ measured_on: str | None = None
+ #: One line saying why the type is not ``validated``.
+ reason: str | None = None
+
+
+_VALIDATED = FindingTypeStatus("validated")
+
+_LABELLED = "hand-labelled findings from one TS/Python monorepo"
+
+REGISTRY: dict[str, FindingTypeStatus] = {
+ "unused_internal": FindingTypeStatus(
+ "hidden",
+ precision=0.005,
+ corpus=f"{_LABELLED}, 1,511 in all",
+ measured_on="2026-09-29",
+ reason=(
+ "Private-symbol findings were almost all false: TS/JS/Python emit no "
+ "'reads' edges, so same-file uses are invisible to the graph."
+ ),
+ ),
+ "duplicated_assertion_block": FindingTypeStatus(
+ "hidden",
+ corpus=f"{_LABELLED}, 1,168 in all",
+ measured_on="2026-09-29",
+ reason="Clones are matched on token shape only, so unrelated assertions pair up.",
+ ),
+ # The failing subset is clones over import blocks and data literals. A
+ # ClonePair carries only line spans, not the token kinds that would tell
+ # that subset apart, so the whole type is hidden until clone detection
+ # drops those windows itself (upgrade path: filter in the tokenizer, then
+ # re-measure and flip this back).
+ "dry_violation": FindingTypeStatus(
+ "hidden",
+ corpus=_LABELLED,
+ measured_on="2026-09-29",
+ reason="Flags duplicated import blocks and data literals as design duplication.",
+ ),
+}
+
+
+def status_of(finding_type: str) -> FindingTypeStatus:
+ return REGISTRY.get(finding_type, _VALIDATED)
+
+
+def excluded_types(
+ *, requested: Iterable[str] = (), include_provisional: bool = False
+) -> frozenset[str]:
+ """Types a surface must leave out: every hidden type, plus each provisional
+ type the caller neither named in *requested* nor opted into."""
+ named = set(requested)
+ return frozenset(
+ name
+ for name, entry in REGISTRY.items()
+ if entry.status == "hidden"
+ or (entry.status == "provisional" and not include_provisional and name not in named)
+ )
+
+
+def is_shown(
+ finding_type: str, *, requested: Iterable[str] = (), include_provisional: bool = False
+) -> bool:
+ return finding_type not in excluded_types(
+ requested=requested, include_provisional=include_provisional
+ )
+
+
+def verification_label(finding_type: str) -> str | None:
+ """:data:`UNVERIFIED_LABEL` for a provisional type, else ``None``."""
+ return UNVERIFIED_LABEL if status_of(finding_type).status == "provisional" else None
+
+
+def withheld_summary(counts: Mapping[str, int], excluded: Iterable[str]) -> dict[str, dict]:
+ """``{type: {count, status, reason}}`` for each excluded type that has rows,
+ so a surface can say what it held back instead of silently shrinking."""
+ out: dict[str, dict] = {}
+ for name in sorted(set(excluded)):
+ count = counts.get(name, 0)
+ if count:
+ entry = status_of(name)
+ out[name] = {"count": count, "status": entry.status, "reason": entry.reason}
+ return out
+
+
+__all__ = [
+ "REGISTRY",
+ "UNVERIFIED_LABEL",
+ "FindingStatus",
+ "FindingTypeStatus",
+ "excluded_types",
+ "is_shown",
+ "status_of",
+ "verification_label",
+ "withheld_summary",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py b/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py
index 155931483..12c2dac09 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/io_in_loop.py
@@ -49,6 +49,12 @@ _BOUNDARY_PHRASING: dict[str, str] = {
}
+def _shape(boundary_kind: str) -> str:
+ """ "N+1" names a query per row, so it needs a database boundary; any other
+ boundary is only an I/O call inside a loop."""
+ return "N+1 query" if boundary_kind == "db" else "I/O call inside a loop"
+
+
class IoInLoopDetector:
name = _KIND
category = "performance"
@@ -74,7 +80,7 @@ class IoInLoopDetector:
"cross_function": False,
**hit.loop_facts(),
},
- reason=f"{phrasing} runs once per loop iteration (N+1 / IO-in-loop)",
+ reason=f"{phrasing} runs once per loop iteration ({_shape(hit.detail)})",
)
)
return out
@@ -100,7 +106,7 @@ class IoInLoopDetector:
},
reason=(
f"{phrasing} is reached once per loop iteration through "
- f"{chain} (cross-function N+1)"
+ f"{chain} (cross-function {_shape(hit.detail)})"
),
)
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
index 5cfc1aa58..9932b8308 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/primitive_obsession.py
@@ -1,4 +1,4 @@
-"""Primitive Obsession — long parameter lists of unstructured values.
+"""Long parameter list (key ``primitive_obsession``) — wide signatures of raw values.
A proxy for the OOP smell: when a function signature carries 5+ raw
parameters, the call sites usually pass strings/ints/bools that *should*
@@ -42,6 +42,10 @@ class PrimitiveObsessionDetector:
return []
out: list[BiomarkerResult] = []
for fn in ctx.all_functions:
+ # A test case's parameters are fixtures the runner injects, not a
+ # signature anyone calls.
+ if fn.is_test_case:
+ continue
threshold = _PARAM_THRESHOLD
if fn.name in _CTOR_NAMES:
threshold += _CTOR_GRACE
@@ -64,7 +68,7 @@ class PrimitiveObsessionDetector:
details={
"param_count": fn.param_count,
},
- reason=f"{fn.name} takes {fn.param_count} parameters",
+ reason=f"long parameter list: {fn.name} takes {fn.param_count} parameters",
)
)
return out
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/serial_await_in_loop.py b/packages/core/src/repowise/core/analysis/health/biomarkers/serial_await_in_loop.py
index 3efa0e122..5d1367845 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/serial_await_in_loop.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/serial_await_in_loop.py
@@ -4,7 +4,8 @@
when they could often be fanned out (``asyncio.gather`` / ``Promise.all`` /
``Task.WhenAll``). This is the *missed-concurrency* sibling of ``io_in_loop``: a
different remediation (parallelize) from batching, so it rides as a separate,
-advisory signal alongside the N+1 finding rather than replacing it.
+advisory signal. When ``io_in_loop`` already fires on the same line this marker
+stays silent, so one call is never reported twice.
Advisory by design: static analysis cannot prove the iterations are independent
(a loop may genuinely need the awaited result before the next iteration), so the
@@ -34,8 +35,11 @@ class SerialAwaitInLoopDetector:
def detect(self, ctx: FileContext) -> list[BiomarkerResult]:
out: list[BiomarkerResult] = []
+ # The same awaited call on the same line is already an ``io_in_loop``
+ # finding; reporting it twice counts one problem as two.
+ io_lines = {(h.function, h.line) for h in ctx.perf_hits if h.kind == "io_in_loop"}
for hit in ctx.perf_hits:
- if hit.kind != _KIND:
+ if hit.kind != _KIND or (hit.function, hit.line) in io_lines:
continue
phrasing = _BOUNDARY_PHRASING.get(hit.detail, "an awaited I/O call")
if hit.promoted:
diff --git a/packages/core/src/repowise/core/analysis/health/ranking.py b/packages/core/src/repowise/core/analysis/health/ranking.py
index a73aaf35f..3160883a3 100644
--- a/packages/core/src/repowise/core/analysis/health/ranking.py
+++ b/packages/core/src/repowise/core/analysis/health/ranking.py
@@ -16,7 +16,7 @@ from __future__ import annotations
from collections.abc import Iterable, Mapping, Sequence
from typing import Any
-from .rows import field
+from .rows import field, split_tests
from .scoring import SCORE_MAX
__all__ = [
@@ -75,10 +75,15 @@ def sort_metrics_worst_first(rows: Sequence[Any], deductions: Mapping[str, float
def worst_metric(rows: Iterable[Any], deductions: Mapping[str, float]) -> Any | None:
- """The single worst row under the same key, or ``None`` for no rows.
+ """The single worst production row under the same key, or ``None`` for no rows.
- Identical to ``sort_metrics_worst_first(rows, deductions)[0]`` without
- sorting the tail. Sharing the key is what keeps a repo's headline "worst
- performer" from naming a different file than the worst-files list under it.
+ Identical to ``sort_metrics_worst_first(rows, deductions)[0]`` over the
+ production rows without sorting the tail. Sharing the key is what keeps a
+ repo's headline "worst performer" from naming a different file than the
+ worst-files list under it. Test files are ranked separately, so a test only
+ answers when there is no production row at all.
"""
- return min(rows, key=lambda row: worst_first_key(row, deductions), default=None)
+ production, tests = split_tests(rows)
+ return min(
+ production or tests, key=lambda row: worst_first_key(row, deductions), default=None
+ )
diff --git a/packages/core/src/repowise/core/analysis/health/rows.py b/packages/core/src/repowise/core/analysis/health/rows.py
index 68e57e60b..3e7f28b4c 100644
--- a/packages/core/src/repowise/core/analysis/health/rows.py
+++ b/packages/core/src/repowise/core/analysis/health/rows.py
@@ -8,7 +8,7 @@ these adapters so no consumer has to know which.
from __future__ import annotations
import json
-from collections.abc import Mapping
+from collections.abc import Iterable, Mapping
from typing import Any
@@ -51,4 +51,17 @@ def json_field(row: Any, name: str, default: Any) -> Any:
return default if value is None else value
-__all__ = ["detail_map", "field", "json_field"]
+def split_tests(rows: Iterable[Any]) -> tuple[list[Any], list[Any]]:
+ """Partition per-file rows into ``(production, tests)`` by their ``is_test``.
+
+ Ranked "worst file" answers name production files and report tests apart;
+ a surface falls back to the tests only when there is no production row.
+ """
+ production: list[Any] = []
+ tests: list[Any] = []
+ for row in rows:
+ (tests if field(row, "is_test", False) else production).append(row)
+ return production, tests
+
+
+__all__ = ["detail_map", "field", "json_field", "split_tests"]
diff --git a/packages/core/src/repowise/core/analysis/health/scoring.py b/packages/core/src/repowise/core/analysis/health/scoring.py
index e2698e801..13d2ba175 100644
--- a/packages/core/src/repowise/core/analysis/health/scoring.py
+++ b/packages/core/src/repowise/core/analysis/health/scoring.py
@@ -24,7 +24,7 @@ from dataclasses import replace
from typing import TYPE_CHECKING, Any
from .models import HealthFileMetricData, HealthFindingData, Severity
-from .rows import field
+from .rows import field, split_tests
if TYPE_CHECKING:
# Annotation-only, and deliberately not imported at runtime: the biomarker
@@ -882,7 +882,8 @@ def compute_kpis(
- ``hotspot_health``: NLOC-weighted average over files in *hotspot_paths*.
- ``average_health``: NLOC-weighted average over all files.
- - ``worst_performer``: lowest-scoring file + score.
+ - ``worst_performer``: lowest-scoring production file + score, and
+ ``worst_test_performer`` the same over test files, reported separately.
- ``maintainability_average`` / ``maintainability_hotspot``: the same two
NLOC-weighted averages over the per-file ``maintainability_score``, so the
maintainability pillar surfaces a repo headline alongside the defect one.
@@ -903,6 +904,8 @@ def compute_kpis(
"average_health": 10.0,
"worst_performer_path": None,
"worst_performer_score": None,
+ "worst_test_path": None,
+ "worst_test_score": None,
"file_count": 0,
"maintainability_average": None,
"maintainability_hotspot": None,
@@ -917,12 +920,14 @@ def compute_kpis(
}
hotspots = [m for m in metrics if field(m, "file_path") in hotspot_paths]
- worst = min(metrics, key=_row_score)
+ production, tests = split_tests(metrics)
+ # Production first; a test file names the worst only in a tests-only repo.
+ worst = min(production or metrics, key=_row_score)
+ worst_test = min(tests, key=_row_score) if tests else None
maint_avg = nloc_weighted_attr(metrics, "maintainability_score")
maint_hotspot = nloc_weighted_attr(hotspots, "maintainability_score")
perf_avg = nloc_weighted_attr(metrics, "performance_score")
perf_hotspot = nloc_weighted_attr(hotspots, "performance_score")
- production = [m for m in metrics if not field(m, "is_test", False)]
splits = {
f"{half}_{scope}": nloc_weighted_attr(rows, f"{half}_deduction")
for half in ("structure", "history")
@@ -939,6 +944,8 @@ def compute_kpis(
"average_health": round(nloc_weighted_score(metrics), 2),
"worst_performer_path": field(worst, "file_path"),
"worst_performer_score": round(_row_score(worst), 2),
+ "worst_test_path": field(worst_test, "file_path") if worst_test is not None else None,
+ "worst_test_score": round(_row_score(worst_test), 2) if worst_test is not None else None,
"file_count": len(metrics),
"maintainability_average": round(maint_avg, 2) if maint_avg is not None else None,
"maintainability_hotspot": round(maint_hotspot, 2) if maint_hotspot is not None else None,
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index 784fb11dc..d7b22199a 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -15,8 +15,10 @@ from pathlib import Path
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.grading import BAND_LABEL, band_for
from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
+from repowise.core.analysis.health.rows import split_tests
from repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_score
from repowise.core.analysis.health.trends import DECLINE_LOOKBACK, hotspot_trend
from repowise.core.entry_candidacy import conventional_entry_stems
@@ -375,7 +377,11 @@ class EditorFileDataFetcher:
# zero-total-weight fallback to a plain mean. The empty case cannot
# reach it — ``metric_rows`` is checked above.
avg = nloc_weighted_score(metric_rows)
- worst = min(metric_rows, key=lambda m: m.score)
+ # The worst file and the critical list name production files: a test
+ # is not the file an agent should be told to handle with care.
+ production, tests = split_tests(metric_rows)
+ test_paths = {m.file_path for m in tests}
+ worst = min(production or tests, key=lambda m: m.score)
# Hotspot-flagged paths, and the hotspot KPI over them. Both come from
# the shared owners now; this file used to re-derive the same weighted
@@ -435,6 +441,7 @@ class EditorFileDataFetcher:
.where(
HealthFinding.repository_id == self._repo_id,
HealthFinding.status == "open",
+ HealthFinding.biomarker_type.not_in(excluded_types()),
)
.order_by(HealthFinding.health_impact.desc())
)
@@ -455,6 +462,8 @@ class EditorFileDataFetcher:
for f in all_findings:
if len(critical) >= 5:
break
+ if f.file_path in test_paths:
+ continue
if f.biomarker_type == "brain_method" or (
f.severity == "critical" and f.file_path in hotspot_paths
):
diff --git a/packages/core/src/repowise/core/generation/page_generator/helpers.py b/packages/core/src/repowise/core/generation/page_generator/helpers.py
index f40ad912a..de2b70ade 100644
--- a/packages/core/src/repowise/core/generation/page_generator/helpers.py
+++ b/packages/core/src/repowise/core/generation/page_generator/helpers.py
@@ -15,7 +15,9 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
+from repowise.core.analysis.dead_code.risk_factors import effective_safe_to_delete
from repowise.core.analysis.decisions.scope import binds_to_paths
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
from repowise.core.ingestion.models import ParsedFile
@@ -228,10 +230,16 @@ def _select_clone_representatives(
def build_dead_code_map(dead_code_report: Any | None) -> dict[str, list[dict]]:
- """Index dead-code findings by file path for per-page lookup."""
+ """Index dead-code findings by file path for per-page lookup.
+
+ Kinds the finding-type registry withholds never reach a page prompt.
+ """
dead_code_by_file: dict[str, list[dict]] = {}
+ withheld = excluded_types()
if dead_code_report is not None and getattr(dead_code_report, "findings", None):
for f in dead_code_report.findings:
+ if str(f.kind) in withheld:
+ continue
dead_code_by_file.setdefault(f.file_path, []).append(
{
"symbol_name": f.symbol_name,
@@ -239,7 +247,9 @@ def build_dead_code_map(dead_code_report: Any | None) -> dict[str, list[dict]]:
"kind": str(f.kind),
"reason": f.reason,
"confidence": f.confidence,
- "safe_to_delete": f.safe_to_delete,
+ "safe_to_delete": effective_safe_to_delete(
+ f.confidence, f.file_path, f.safe_to_delete, str(f.kind)
+ ),
}
)
return dead_code_by_file
diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2
index a3eba654b..0768d3120 100644
--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2
@@ -47,7 +47,7 @@ Machine-readable scope: `{{ data.index_scope | tojson }}`
{% if data.code_health %}
### Code health
-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band %} ({{ data.code_health.band }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static I/O-in-loop / N+1 finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
+Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band %} ({{ data.code_health.band }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
{% if data.code_health.critical_biomarkers %}
Critical files:
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index eee5854a8..ab826143c 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -47,7 +47,7 @@ Machine-readable scope: `{{ data.index_scope | tojson }}`
{% if data.code_health %}
### Code health
-Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band %} ({{ data.code_health.band }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static I/O-in-loop / N+1 finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
+Three co-equal signals: code health {{ data.code_health.average_health }}/10 avg{% if data.code_health.band %} ({{ data.code_health.band }}){% endif %}, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static performance finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
{% if data.code_health.critical_biomarkers %}
Critical files:
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
index 45be747d1..9a04006c8 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
@@ -31,6 +31,8 @@ from repowise.core.analysis.actions.facts import (
SecretFacts,
)
from repowise.core.analysis.actions.rules.hygiene import PUBLIC_ENV_KIND, SECRET_KINDS
+from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category
from repowise.core.author_identity import author_identity_key
@@ -180,6 +182,7 @@ async def _files(session: AsyncSession, repo_id: str, since: datetime | None) ->
HealthFinding.repository_id == repo_id,
HealthFinding.status == "open",
HealthFinding.file_path.in_(lead_paths),
+ HealthFinding.biomarker_type.not_in(excluded_types()),
)
)
).all()
@@ -258,6 +261,7 @@ async def _recent(
for f, subject, at in rows
if not (files.get(f.file_path) and files[f.file_path].is_test)
and biomarker_category(f.biomarker_type) != HISTORY_CATEGORY
+ and f.biomarker_type not in excluded_types()
]
if not candidates:
return {"recent_findings": ()}
@@ -450,6 +454,7 @@ async def _dead(session: AsyncSession, repo_id: str, files: dict[str, FileFacts]
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
DeadCodeFinding.safe_to_delete.is_(True),
+ DeadCodeFinding.kind.not_in(excluded_types() | REVIEW_ONLY_KINDS),
)
)
).all()
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
index a674cbbf8..e8dc10c88 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
@@ -13,6 +13,7 @@ from repowise.core.analysis.dead_code.risk_factors import (
SAFE_CONFIDENCE_THRESHOLD,
effective_safe_to_delete,
)
+from repowise.core.analysis.finding_registry import excluded_types
from ...models import DeadCodeFinding, _new_uuid
from .._shared import _BATCH_SIZE, _finding_file_path
@@ -196,9 +197,13 @@ async def get_dead_code_findings(
status: str = "open",
safe_to_delete: bool | None = None,
limit: int | None = None,
+ include_withheld: bool = False,
) -> list[DeadCodeFinding]:
"""Return dead code findings filtered by kind, confidence, and status.
+ Kinds the finding-type registry withholds are left out unless
+ ``include_withheld``; naming a provisional ``kind`` is an explicit request.
+
``safe_to_delete`` and ``limit`` exist so a caller that wants a short
preview does not have to load every open finding in the repository and
then throw most of them away in Python. Overview does exactly that for a
@@ -211,6 +216,8 @@ async def get_dead_code_findings(
)
if kind is not None:
q = q.where(DeadCodeFinding.kind == kind)
+ if not include_withheld:
+ q = q.where(DeadCodeFinding.kind.not_in(excluded_types(requested=[kind] if kind else ())))
if safe_to_delete is not None:
q = q.where(DeadCodeFinding.safe_to_delete.is_(safe_to_delete))
q = q.order_by(DeadCodeFinding.confidence.desc())
@@ -243,6 +250,7 @@ async def get_dead_code_summary(session: AsyncSession, repository_id: str) -> di
select(DeadCodeFinding).where(
DeadCodeFinding.repository_id == repository_id,
DeadCodeFinding.status == "open",
+ DeadCodeFinding.kind.not_in(excluded_types()),
)
)
findings = list(result.scalars().all())
@@ -269,7 +277,7 @@ async def get_dead_code_summary(session: AsyncSession, repository_id: str) -> di
deletable_lines = sum(
f.lines or 0
for f in findings
- if effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete)
+ if effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete, f.kind)
)
return {
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
index d5492122f..ea4bc2aa5 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py
@@ -14,6 +14,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
if TYPE_CHECKING:
from ....analysis.health.perf.coverage import PerfCoverage
+from ....analysis.finding_registry import excluded_types
from ....analysis.health.finding_identity import finding_public_id
from ....analysis.health.governance import GOVERNANCE_BIOMARKERS
@@ -387,9 +388,15 @@ async def get_health_findings(
dimension: str | None = None,
exclude_dimensions: tuple[str, ...] | None = None,
status: str = "open",
+ include_withheld: bool = False,
) -> list[HealthFinding]:
"""Findings for one repository, ordered by health impact.
+ Finding types the registry withholds (``finding_registry``) are left out,
+ so every surface built on this read shows only what has earned a place; a
+ provisional type named in ``biomarker_type`` is an explicit request and is
+ returned. ``include_withheld`` is for analysis that must see every row.
+
``exclude_dimensions`` is how a general queue keeps a dimension out of a
ranking it does not share units with. It is ignored when ``dimension``
names one explicitly, so asking for a dimension always returns it.
@@ -413,13 +420,14 @@ async def get_health_findings(
HealthFinding.dimension.not_in(list(exclude_dimensions)),
)
)
- if biomarker_type is not None:
- # Accept a comma-separated list so a caller can pull several biomarker
- # types in one request (e.g. the function-level + coupling panels).
- # A single value with no comma still matches exactly (``IN`` of one).
- types = [t.strip() for t in biomarker_type.split(",") if t.strip()]
- if types:
- q = q.where(HealthFinding.biomarker_type.in_(types))
+ # Accept a comma-separated list so a caller can pull several biomarker
+ # types in one request (e.g. the function-level + coupling panels).
+ # A single value with no comma still matches exactly (``IN`` of one).
+ types = [t.strip() for t in (biomarker_type or "").split(",") if t.strip()]
+ if types:
+ q = q.where(HealthFinding.biomarker_type.in_(types))
+ if not include_withheld:
+ q = q.where(HealthFinding.biomarker_type.not_in(excluded_types(requested=types)))
if file_path is not None:
q = q.where(HealthFinding.file_path == file_path)
if dimension is not None:
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index dff882847..05f5059e9 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -1133,7 +1133,7 @@ async def refresh_unchanged_history(
return 0
findings_by_path: dict[str, list[Any]] = {}
- for finding in await get_health_findings(session, repo_id):
+ for finding in await get_health_findings(session, repo_id, include_withheld=True):
findings_by_path.setdefault(finding.file_path, []).append(finding)
cfg = HealthConfig.load(repo_path)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index 49c9e7a5a..4053acf76 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -27,6 +27,7 @@ from repowise.core.analysis.doc_drift.serialize import (
collapse_reference_sites,
documents_with_drift,
)
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.signals import file_signals
from repowise.core.ingestion.models import (
FILE_DEPENDENCY_EDGE_TYPES,
@@ -695,6 +696,7 @@ async def _resolve_health(
HealthFinding.repository_id == repo_id,
HealthFinding.file_path == file_path,
HealthFinding.status == "open",
+ HealthFinding.biomarker_type.not_in(excluded_types()),
)
.order_by(HealthFinding.health_impact.desc())
.limit(2)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index 17f93672e..17487630c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -12,9 +12,15 @@ from sqlalchemy import select
from repowise.core.analysis.dead_code.models import DeadCodeKind
from repowise.core.analysis.dead_code.risk_factors import (
RISK_CAP_CONFIDENCE,
+ SAFE_CONFIDENCE_THRESHOLD,
effective_safe_to_delete,
path_risk_factors,
)
+from repowise.core.analysis.finding_registry import (
+ excluded_types,
+ verification_label,
+ withheld_summary,
+)
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
DeadCodeFinding,
@@ -48,6 +54,17 @@ class _FindingFilters:
directory: str | None
owner: str | None
excluded_kinds: set[str] = field(default_factory=set)
+ # Kinds the finding-type registry keeps off this surface. Applied before
+ # anything is counted, so no total describes a finding the caller cannot see.
+ withheld_kinds: frozenset[str] = frozenset()
+
+ def split_withheld(self, findings: list) -> tuple[list, dict[str, dict]]:
+ """``(shown rows, {withheld kind: count/status/reason})``."""
+ counts: dict[str, int] = {}
+ for f in findings:
+ counts[f.kind] = counts.get(f.kind, 0) + 1
+ shown = [f for f in findings if f.kind not in self.withheld_kinds]
+ return shown, withheld_summary(counts, self.withheld_kinds)
def _compute_excluded_kinds(
@@ -105,6 +122,7 @@ async def _get_dead_code_all_repos(
total_deletable = 0
total_safe = 0
merged_by_kind: dict[str, int] = {}
+ merged_withheld: dict[str, dict] = {}
for ctx in contexts:
async with get_session(ctx.session_factory) as session:
@@ -118,6 +136,10 @@ async def _get_dead_code_all_repos(
repo_findings = filter_rows_by_attr(
list(all_result.scalars().all()), "file_path", _get_exclude_spec(ctx.path)
)
+ repo_findings, repo_withheld = filters.split_withheld(repo_findings)
+ for name, entry in repo_withheld.items():
+ merged = merged_withheld.setdefault(name, {**entry, "count": 0})
+ merged["count"] += entry["count"]
git_meta_map = await _load_git_meta_map(session, repository.id, repo_findings)
@@ -145,6 +167,8 @@ async def _get_dead_code_all_repos(
"safe_to_delete_count": total_safe,
"by_kind": merged_by_kind,
}
+ if merged_withheld:
+ summary["withheld_types"] = merged_withheld
tiers = _build_tiers_from_dicts(merged_findings, limit, tier)
@@ -164,11 +188,14 @@ async def _get_dead_code_all_repos(
# The bands this tool tiers by, in one place: the tier descriptions quote them
# and ``min_confidence="high"`` resolves to them, so the vocabulary the response
-# is organised by and the one it accepts cannot drift apart (#1496). Deliberately
-# this tool's own numbers — the web and CLI tier at 0.7/0.4
-# (``DEAD_CODE_CONFIDENCE`` in packages/types/src/dead-code.ts); reconciling the
-# two changes output and is not this change.
-_TIER_FLOORS: dict[str, float] = {"high": 0.8, "medium": 0.5, "low": 0.0}
+# is organised by and the one it accepts cannot drift apart (#1496). The engine's
+# own thresholds, so this tool, the web and the CLI (``DEAD_CODE_CONFIDENCE`` in
+# packages/types/src/dead-code.ts) put a finding in the same tier.
+_TIER_FLOORS: dict[str, float] = {
+ "high": SAFE_CONFIDENCE_THRESHOLD,
+ "medium": RISK_CAP_CONFIDENCE,
+ "low": 0.0,
+}
# The four kinds the analyzer writes, taken from the enum it writes them with
# rather than re-listed here, so a fifth kind never reads as a caller's typo.
@@ -219,15 +246,17 @@ async def _load_git_meta_map(session: Any, repository_id: Any, findings: list) -
_TIER_DESC_HIGH = (
- "High confidence (>=0.8): No references found in the codebase. "
- "Strong cleanup candidates — review (especially runtime-loaded files) before deleting."
+ f"High confidence (>={SAFE_CONFIDENCE_THRESHOLD}): No references found in the codebase. "
+ "Strong cleanup candidates — review (especially whole files and runtime-loaded files) "
+ "before deleting."
)
_TIER_DESC_MEDIUM = (
- "Medium confidence (0.5-0.8): Likely unused but may have indirect references. "
- "Review before deleting."
+ f"Medium confidence ({RISK_CAP_CONFIDENCE}-{SAFE_CONFIDENCE_THRESHOLD}): Likely unused "
+ "but may have indirect references. Review before deleting."
)
_TIER_DESC_LOW = (
- "Low confidence (<0.5): Potentially used via dynamic imports or reflection. Investigate first."
+ f"Low confidence (<{RISK_CAP_CONFIDENCE}): Potentially used via dynamic imports or "
+ "reflection. Investigate first."
)
@@ -281,10 +310,10 @@ async def get_dead_code(
An unrecognised value is dropped and named in ignored_arguments,
never applied as a filter that matches nothing.
min_confidence: floor, default 0.4 (0.7 = cleanup-ready only). Also
- accepts a tier name: "high" (0.8) | "medium" (0.5) | "low" (0.0).
+ accepts a tier name: "high" | "medium" | "low".
safe_only: deletion-ready findings only (no runtime-load risk).
limit: max findings per tier (clamped to 25).
- tier: "high" (>=0.8) | "medium" | "low".
+ tier: "high" | "medium" | "low", banded as min_confidence.
directory: path-prefix filter.
owner: primary-owner filter.
group_by: "directory" | "owner" rollup.
@@ -322,6 +351,11 @@ async def get_dead_code(
include_internals=include_internals,
include_zombie_packages=include_zombie_packages,
),
+ # Naming a kind, or ``include_internals`` for ``unused_internal``, is the
+ # explicit request a provisional kind needs; a hidden kind stays out.
+ withheld_kinds=excluded_types(
+ requested=[k for k in (kind, "unused_internal" if include_internals else None) if k]
+ ),
)
def _maybe_limit_note(target: dict[str, Any]) -> None:
@@ -370,7 +404,7 @@ async def get_dead_code(
DeadCodeFinding.status == "open",
)
all_result = await session.execute(all_query)
- all_findings = list(all_result.scalars().all())
+ all_findings, withheld = filters.split_withheld(list(all_result.scalars().all()))
# Phase 4: load git metadata for "last meaningful change" enrichment
git_meta_map = await _load_git_meta_map(session, repository.id, all_findings)
@@ -430,6 +464,8 @@ async def get_dead_code(
"safe_to_delete_count": sum(1 for f in all_findings if _effective_safe(f)),
"by_kind": by_kind,
}
+ if withheld:
+ summary["withheld_types"] = withheld
# Cross-repo confidence adjustment (Phase 3)
_adjust_dead_code_cross_repo(tiers, ctx.alias)
@@ -521,7 +557,7 @@ def _effective_safe(f: Any) -> bool:
files (and findings written before risk factors existed) never read as
safe-to-delete.
"""
- return effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete)
+ return effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete, f.kind)
def _dead_code_finding_id(f: Any, repository: str) -> str:
@@ -570,6 +606,9 @@ def _serialize_finding(
# findings. last_commit_at above is the staleness signal.
"age_days": f.age_days,
}
+ label = verification_label(f.kind)
+ if label:
+ result["verification"] = label
# Phase 4: add last meaningful change date
if git_meta_map:
gm = git_meta_map.get(f.file_path)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
index c0b7af852..b6cd7796c 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py
@@ -71,10 +71,14 @@ def build_dashboard(
"distribution": health_distribution(all_metrics),
# Where the gap to the target concentrates: a short list of files.
"gap_analysis": gap,
+ # Production files only: a test is never the worst file to work on.
+ # Test files rank in their own list, as findings do.
"worst_files": pager.bound([_metric_row(data, m) for m in data.metric_rows], "worst_files"),
- # Ranked file lists keep test files in place and mark them; dropping
- # them would change which files are "worst". Only finding lists split.
"worst_files_total": len(data.metric_rows),
+ "test_worst_files": pager.bound(
+ [_metric_row(data, m) for m in data.test_metric_rows], "test_worst_files"
+ ),
+ "test_worst_files_total": len(data.test_metric_rows),
"high_leverage_files": pager.bound(_high_leverage_rows(data, gap), "high_leverage_files"),
"high_leverage_files_total": len(data.by_leverage),
"top_findings": pager.bound(
@@ -147,6 +151,7 @@ def _defer_to_secondary_rankings(
repo = req.repo
totals = {
"worst_files": len(data.metric_rows),
+ "test_worst_files": len(data.test_metric_rows),
"top_findings": data.findings.findings_total,
"test_findings": data.findings.test_findings_total,
"modules": modules_total,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py b/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
index 8cdfab4f6..dafba1249 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/findings.py
@@ -55,10 +55,11 @@ class FindingSets:
test_findings_total: int = 0
-def _open_findings(repository: Any) -> tuple[Any, Any]:
+def _open_findings(repository: Any, req: HealthRequest) -> tuple[Any, ...]:
return (
HealthFinding.repository_id == repository.id,
HealthFinding.status == "open",
+ HealthFinding.biomarker_type.not_in(req.withheld_types),
)
@@ -71,7 +72,7 @@ async def load_targeted_findings(
(
await session.execute(
select(HealthFinding)
- .where(*_open_findings(repository))
+ .where(*_open_findings(repository, req))
.where(HealthFinding.file_path.in_(pop.effective_targets))
.order_by(HealthFinding.health_impact.desc())
)
@@ -167,7 +168,7 @@ async def _read_lite_findings(session: Any, repository: Any, req: HealthRequest)
(
await session.execute(
select(*lite_cols)
- .where(*_open_findings(repository))
+ .where(*_open_findings(repository, req))
.order_by(HealthFinding.health_impact.desc())
)
).all()
@@ -206,7 +207,7 @@ async def read_accuracy_rows(
(
await session.execute(
select(HealthFinding)
- .where(*_open_findings(repository))
+ .where(*_open_findings(repository, req))
.where(HealthFinding.biomarker_type == "prior_defect")
)
)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
index 95a0d8c43..252285366 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py
@@ -92,6 +92,9 @@ class HealthData:
snapshots: list[Any] = field(default_factory=list)
plan_biomarkers_by_path: dict[str, set[str]] = field(default_factory=dict)
plan_count_by_path: dict[str, int] = field(default_factory=dict)
+ # Dashboard only: the worst-first test files, ranked apart from
+ # ``metric_rows`` so a test never heads the production worklist.
+ test_metric_rows: list[HealthFileMetric] = field(default_factory=list)
async def load_health_data(
@@ -113,8 +116,12 @@ async def load_health_data(
# input order, so every block must see the same order as ``worst_files``.
pop.all_metrics = sort_metrics_worst_first(pop.all_metrics, deductions)
targets = set(pop.effective_targets)
+ # Targeted mode keeps what was named. The dashboard's ranked lists are
+ # production files; tests get their own list.
metric_rows = (
- [m for m in pop.all_metrics if m.file_path in targets] if pop.scoped else pop.all_metrics
+ [m for m in pop.all_metrics if m.file_path in targets]
+ if pop.scoped
+ else [m for m in pop.all_metrics if not _is_test(m, test_paths)]
)
data = HealthData(
repository=repository,
@@ -128,6 +135,9 @@ async def load_health_data(
performance=_PerformanceBlocks(),
by_leverage=[],
leads={},
+ test_metric_rows=(
+ [] if pop.scoped else [m for m in pop.all_metrics if _is_test(m, test_paths)]
+ ),
)
data.hotspot_paths = await _read_hotspot_paths(session, repository, pop, req)
data.perf_coverage, data.perf_findings_count = await _read_perf_headline(
@@ -149,13 +159,20 @@ async def load_health_data(
)
data.churn_points = await _read_churn_points(session, repository, pop, req)
data.snapshots = await _read_snapshots(session, repository, pop, req)
- data.by_leverage, data.leads = _rank_leverage_and_leads(pop, metric_rows, findings, req)
+ data.by_leverage, data.leads = _rank_leverage_and_leads(
+ pop, metric_rows, findings, req, data.test_metric_rows
+ )
data.plan_biomarkers_by_path, data.plan_count_by_path = await _read_directive_plans(
session, repository, pop, req, data.by_leverage
)
return data
+def _is_test(m: HealthFileMetric, test_paths: set[str]) -> bool:
+ """Test material by the metric's own flag or the graph's, whichever is read."""
+ return bool(m.is_test) or m.file_path in test_paths
+
+
async def _read_test_paths(
session: Any, repository: Any, pop: Population, req: HealthRequest
) -> set[str]:
@@ -378,6 +395,7 @@ def _rank_leverage_and_leads(
metric_rows: list[HealthFileMetric],
findings: FindingSets,
req: HealthRequest,
+ test_metric_rows: list[HealthFileMetric],
) -> tuple[list[HealthFileMetric], dict[str, dict[str, Any]]]:
"""Dominant-cause lead per file, and the leverage ranking it is printed beside.
@@ -392,11 +410,12 @@ def _rank_leverage_and_leads(
# Ranked by NLOC-weighted deficit, not raw score: a big mid-band file
# moves the average more than a tiny at-risk one.
by_leverage = sorted(
- (m for m in pop.all_metrics if m.score < TARGET_SCORE),
+ (m for m in metric_rows if m.score < TARGET_SCORE),
key=lambda m: max(TARGET_SCORE - m.score, 0.0) * max(m.nloc, 1),
reverse=True,
)
printed = {m.file_path for m in metric_rows[: req.limit]}
+ printed |= {m.file_path for m in test_metric_rows[: req.limit]}
printed |= {m.file_path for m in by_leverage[: req.limit]}
# The directive's candidates, unconditionally: its leads must not depend
# on ``limit``, or ``limit=0`` would make it assert wrong claims.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/paging.py b/packages/server/src/repowise/server/mcp_server/tool_health/paging.py
index cae7a6e54..14cc5a411 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/paging.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/paging.py
@@ -20,6 +20,7 @@ _PAGED_COLLECTIONS = frozenset(
"findings",
"trends",
"worst_files",
+ "test_worst_files",
"high_leverage_files",
"top_findings",
"test_findings",
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/request.py b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
index dd3983a1c..f82690e82 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/request.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/request.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.scoring import ALL_DIMENSIONS
from repowise.server.services.refactoring_health import CANONICAL_VIEWS as _REFACTORING_VIEWS
from repowise.server.services.refactoring_health import DEFAULT_VIEW as _REFACTORING_VIEW_DEFAULT
@@ -34,6 +35,8 @@ _KNOWN_INCLUDES = frozenset(
"defect",
"maintainability",
"advisory",
+ # Opts into provisional finding types, each labelled "unverified".
+ "unverified",
}
)
@@ -73,6 +76,7 @@ class HealthRequest:
raw_targets: list[str] = field(init=False)
module_targets: list[str] = field(init=False)
file_targets: list[str] = field(init=False)
+ withheld_types: frozenset[str] = field(init=False)
def __post_init__(self) -> None:
# ``0`` means totals and no rows, as on the REST coverage route.
@@ -87,6 +91,9 @@ class HealthRequest:
# Resolved before the reads, so the filter decides which rows are
# eligible for the impact cap rather than filtering an already-capped list.
self.dimension_filter = self.include_set & set(ALL_DIMENSIONS)
+ # Finding types the registry keeps off this surface, dropped at the read
+ # so no list, lead or total counts one.
+ self.withheld_types = excluded_types(include_provisional="unverified" in self.include_set)
# Performance findings carry zero impact, so an impact-ranked list
# leaves them out unless asked for; the performance blocks rank them.
self.ranked_dimensions = self.dimension_filter or _RANKED_DIMENSIONS_DEFAULT
@@ -144,6 +151,7 @@ class HealthRequest:
self.wants_findings
or self.wants_test_findings
or self.wants("worst_files")
+ or self.wants("test_worst_files")
or self.wants("high_leverage_files")
or self.wants("metrics")
or ("refactoring" in self.include_set and self.wants("suggestion_legend"))
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 8e543cff0..63a74c1e8 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
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from typing import Any
+from repowise.core.analysis.finding_registry import verification_label
from repowise.core.analysis.health.finding_identity import finding_public_id
from repowise.core.analysis.health.grading import TARGET_SCORE
from repowise.core.analysis.health.perf.opportunity_rank import observation_rank
@@ -107,6 +108,7 @@ def _serialize_finding(f: HealthFinding, repository: str = "default") -> dict[st
rank = (
{"perf_rank": _perf_rank(f.biomarker_type, details)} if dimension == "performance" else {}
)
+ label = verification_label(f.biomarker_type)
return {
"id": _health_finding_id(f, repository),
"repository": repository,
@@ -124,6 +126,8 @@ def _serialize_finding(f: HealthFinding, repository: str = "default") -> dict[st
"dimension": dimension,
# Performance rows only: a zero elsewhere would read as measured.
**rank,
+ # Provisional types only, and only when the caller opted into them.
+ **({"verification": label} if label else {}),
}
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/summary.py b/packages/server/src/repowise/server/mcp_server/tool_health/summary.py
index 9bcaf9611..639403beb 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/summary.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/summary.py
@@ -7,6 +7,7 @@ from typing import Any
from repowise.core.analysis.health.grading import TARGET_SCORE, band_for
from repowise.core.analysis.health.models import primary_finding, split_by_origin
from repowise.core.analysis.health.perf.coverage import PerfCoverage
+from repowise.core.analysis.health.rows import split_tests
from repowise.core.analysis.health.scoring import (
hotspot_health,
nloc_weighted_attr,
@@ -249,6 +250,8 @@ def _compute_kpis(
"hotspot_health": None,
"worst_performer_path": None,
"worst_performer_score": None,
+ "worst_test_path": None,
+ "worst_test_score": None,
"maintainability_average": None,
"performance_average": None,
"structure_average": None,
@@ -257,7 +260,10 @@ def _compute_kpis(
}
total_nloc = sum(max(m.nloc, 1) for m in metrics)
avg = sum(m.score * max(m.nloc, 1) for m in metrics) / total_nloc
- worst = min(metrics, key=lambda r: r.score)
+ # Production first; test files are ranked apart and named on their own.
+ production, tests = split_tests(metrics)
+ worst = min(production or metrics, key=lambda r: r.score)
+ worst_test = min(tests, key=lambda r: r.score) if tests else None
return {
"file_count": len(metrics),
"average_health": round(avg, 2),
@@ -269,6 +275,8 @@ def _compute_kpis(
"band": band_for(round(avg, 2)),
"worst_performer_path": worst.file_path,
"worst_performer_score": round(worst.score, 2),
+ "worst_test_path": worst_test.file_path if worst_test else None,
+ "worst_test_score": round(worst_test.score, 2) if worst_test else None,
# ``None`` until the pillar is measured.
"maintainability_average": _avg(metrics, "maintainability_score"),
"performance_average": _avg(metrics, "performance_score"),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
index 916c687be..8f73e3452 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py
@@ -252,6 +252,7 @@ def _finish(
"trends": mode_totals.trends,
"modules": mode_totals.modules,
"worst_files": len(data.metric_rows),
+ "test_worst_files": len(data.test_metric_rows),
"high_leverage_files": len(data.by_leverage),
"top_findings": findings.findings_total,
"test_findings": findings.test_findings_total,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
index 4ec2762fa..526486304 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py
@@ -6,6 +6,7 @@ from typing import Any
from sqlalchemy import select
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.persistence.database import get_session
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
@@ -355,6 +356,7 @@ async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:
HealthFinding.repository_id == repo_id,
HealthFinding.file_path.in_(target_paths),
HealthFinding.status == "open",
+ HealthFinding.biomarker_type.not_in(excluded_types()),
)
.order_by(HealthFinding.health_impact.desc())
)
diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.py
index c003ea39e..dec36260a 100644
--- a/packages/server/src/repowise/server/routers/code_health/serializers.py
+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import json
from typing import Any
+from repowise.core.analysis.finding_registry import verification_label
from repowise.core.analysis.health.aggregation import (
primary_and_magnitude,
primary_and_magnitude_by_file,
@@ -35,6 +36,8 @@ def _finding_to_dict(f: Any) -> dict:
# so the UI can filter findings per dimension. Defaults to defect for
# rows that predate the split.
"dimension": getattr(f, "dimension", None) or "defect",
+ # "unverified" for a provisional type a caller asked for by name.
+ "verification": verification_label(f.biomarker_type),
}
diff --git a/packages/server/src/repowise/server/routers/dead_code.py b/packages/server/src/repowise/server/routers/dead_code.py
index a5a16dce4..02f53ccce 100644
--- a/packages/server/src/repowise/server/routers/dead_code.py
+++ b/packages/server/src/repowise/server/routers/dead_code.py
@@ -49,7 +49,7 @@ async def list_dead_code(
findings = [
f
for f in findings
- if effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete)
+ if effective_safe_to_delete(f.confidence, f.file_path, f.safe_to_delete, f.kind)
]
return [DeadCodeFindingResponse.from_orm(f) for f in findings[:limit]]
diff --git a/packages/server/src/repowise/server/routers/files.py b/packages/server/src/repowise/server/routers/files.py
index 848ce8e4f..cbeb51726 100644
--- a/packages/server/src/repowise/server/routers/files.py
+++ b/packages/server/src/repowise/server/routers/files.py
@@ -18,6 +18,8 @@ from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.dead_code.risk_factors import effective_safe_to_delete
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.aggregation import NLOC_NULL_REASON
from repowise.core.analysis.health.signals import file_signals
from repowise.core.analysis.health.trends import file_trend
@@ -451,6 +453,7 @@ async def file_detail(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.file_path == file_path,
DeadCodeFinding.status == "open",
+ DeadCodeFinding.kind.not_in(excluded_types()),
)
)
)
@@ -465,7 +468,9 @@ async def file_detail(
"confidence": f.confidence,
"reason": f.reason,
"lines": f.lines,
- "safe_to_delete": f.safe_to_delete,
+ "safe_to_delete": effective_safe_to_delete(
+ f.confidence, f.file_path, f.safe_to_delete, f.kind
+ ),
}
for f in dead_rows
]
diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.py
index c4f779d31..c5ef618ac 100644
--- a/packages/server/src/repowise/server/schemas/code_health.py
+++ b/packages/server/src/repowise/server/schemas/code_health.py
@@ -30,6 +30,8 @@ class HealthFindingResponse(BaseModel):
#: defect | maintainability | performance. Rows predating the split read
#: as ``defect``.
dimension: str = "defect"
+ #: ``"unverified"`` for a provisional finding type, else ``None``.
+ verification: str | None = None
class HealthFindingWithSymbolResponse(HealthFindingResponse):
diff --git a/packages/server/src/repowise/server/schemas/code_quality.py b/packages/server/src/repowise/server/schemas/code_quality.py
index 79a1f142d..48c5580ae 100644
--- a/packages/server/src/repowise/server/schemas/code_quality.py
+++ b/packages/server/src/repowise/server/schemas/code_quality.py
@@ -11,6 +11,7 @@ from repowise.core.analysis.dead_code.risk_factors import (
effective_safe_to_delete,
path_risk_factors,
)
+from repowise.core.analysis.finding_registry import verification_label
class DeadCodeFindingResponse(BaseModel):
@@ -45,6 +46,8 @@ class DeadCodeFindingResponse(BaseModel):
# ladder (0 commits is what earns the high tiers), so surfacing it is what
# makes a low confidence score legible: the file is still being worked on.
commit_count_90d: int
+ # ``"unverified"`` for a provisional kind a caller asked for by name.
+ verification: str | None = None
@classmethod
def from_orm(cls, obj: object) -> DeadCodeFindingResponse:
@@ -68,7 +71,12 @@ class DeadCodeFindingResponse(BaseModel):
lines=obj.lines, # type: ignore[attr-defined]
start_line=obj.start_line, # type: ignore[attr-defined]
end_line=obj.end_line, # type: ignore[attr-defined]
- safe_to_delete=effective_safe_to_delete(confidence, file_path, stored_safe),
+ safe_to_delete=effective_safe_to_delete(
+ confidence,
+ file_path,
+ stored_safe,
+ obj.kind, # type: ignore[attr-defined]
+ ),
risk_factors=list(path_risk_factors(file_path)),
evidence=evidence,
primary_owner=obj.primary_owner, # type: ignore[attr-defined]
@@ -76,6 +84,7 @@ class DeadCodeFindingResponse(BaseModel):
note=obj.note, # type: ignore[attr-defined]
last_commit_at=obj.last_commit_at, # type: ignore[attr-defined]
commit_count_90d=obj.commit_count_90d, # type: ignore[attr-defined]
+ verification=verification_label(obj.kind), # type: ignore[attr-defined]
)
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index d6fe63503..dd8a388c3 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -23,6 +23,8 @@ from repowise.core.analysis.attention import (
severity_of_file_score,
silo_source,
)
+from repowise.core.analysis.dead_code.risk_factors import REVIEW_ONLY_KINDS
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category
from repowise.core.persistence.models import (
DeadCodeFinding,
@@ -79,6 +81,7 @@ async def _health_items(session: AsyncSession, repo_id: str) -> tuple[list[dict]
HealthFinding.repository_id == repo_id,
HealthFinding.status == "open",
HealthFinding.file_path.not_in(_test_paths(repo_id)),
+ HealthFinding.biomarker_type.not_in(excluded_types()),
)
rows = (
await session.execute(
@@ -336,6 +339,7 @@ async def _dead_code_items(session: AsyncSession, repo_id: str) -> tuple[list[di
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
DeadCodeFinding.safe_to_delete.is_(True),
+ DeadCodeFinding.kind.not_in(REVIEW_ONLY_KINDS),
DeadCodeFinding.file_path.not_in(_test_paths(repo_id)),
)
.order_by(DeadCodeFinding.confidence.desc())
@@ -351,6 +355,7 @@ async def _dead_code_items(session: AsyncSession, repo_id: str) -> tuple[list[di
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.status == "open",
DeadCodeFinding.safe_to_delete.is_(True),
+ DeadCodeFinding.kind.not_in(REVIEW_ONLY_KINDS),
DeadCodeFinding.file_path.not_in(_test_paths(repo_id)),
)
)
diff --git a/packages/server/src/repowise/server/services/module_health.py b/packages/server/src/repowise/server/services/module_health.py
index 90673af22..cfd2828c9 100644
--- a/packages/server/src/repowise/server/services/module_health.py
+++ b/packages/server/src/repowise/server/services/module_health.py
@@ -17,6 +17,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis import module_health as _fold
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.health.aggregation import module_label
from repowise.core.analysis.module_health import (
ModuleAccumulator,
@@ -62,7 +63,8 @@ async def aggregate_modules(session: AsyncSession, repo_id: str) -> dict[str, Mo
dead_rows = (
await session.execute(
select(DeadCodeFinding.file_path, DeadCodeFinding.lines).where(
- DeadCodeFinding.repository_id == repo_id
+ DeadCodeFinding.repository_id == repo_id,
+ DeadCodeFinding.kind.not_in(excluded_types()),
)
)
).all()
@@ -147,6 +149,7 @@ async def build_single_file_health(
).where(
DeadCodeFinding.repository_id == repo_id,
DeadCodeFinding.file_path == file_path,
+ DeadCodeFinding.kind.not_in(excluded_types()),
)
)
).one()
diff --git a/packages/server/src/repowise/server/services/owner_profile.py b/packages/server/src/repowise/server/services/owner_profile.py
index 1dafc48b9..940e2701e 100644
--- a/packages/server/src/repowise/server/services/owner_profile.py
+++ b/packages/server/src/repowise/server/services/owner_profile.py
@@ -11,6 +11,7 @@ from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis import owners as _fold
+from repowise.core.analysis.finding_registry import excluded_types
from repowise.core.analysis.owners import (
OwnerAccumulator,
module_share,
@@ -47,7 +48,10 @@ async def aggregate_owners(
DeadCodeFinding.primary_owner,
DeadCodeFinding.file_path,
DeadCodeFinding.lines,
- ).where(DeadCodeFinding.repository_id == repo_id)
+ ).where(
+ DeadCodeFinding.repository_id == repo_id,
+ DeadCodeFinding.kind.not_in(excluded_types()),
+ )
)
).all()
commit_rows = (
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 6c5469b41..15ece9401 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -860,6 +860,7 @@ export interface DeadCodeFindingResponse {
note: string | null;
last_commit_at: string | null;
commit_count_90d: number;
+ verification?: string | null;
}
export interface DeadCodeGraphNodeResponse {
@@ -1748,6 +1749,7 @@ export interface HealthFindingResponse {
details?: Record<string, unknown>;
status: string;
dimension?: string;
+ verification?: string | null;
}
/**
@@ -1769,6 +1771,7 @@ export interface HealthFindingWithSymbolResponse {
details?: Record<string, unknown>;
status: string;
dimension?: string;
+ verification?: string | null;
symbol_id?: string | null;
}
diff --git a/packages/ui/src/health/biomarker-details.tsx b/packages/ui/src/health/biomarker-details.tsx
index 81e15d0e0..9f781fb81 100644
--- a/packages/ui/src/health/biomarker-details.tsx
+++ b/packages/ui/src/health/biomarker-details.tsx
@@ -211,7 +211,11 @@ export function BiomarkerDetails({
<div>
<span className="font-medium text-[var(--color-text-secondary)]">{label}</span>
{" boundary"}
- {crossFn ? " · cross-function N+1" : " · in loop body"}
+ {crossFn
+ ? kind === "db"
+ ? " · cross-function N+1"
+ : " · cross-function, in loop"
+ : " · in loop body"}
</div>
) : null}
{path.length > 1 ? (
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index d49fb41f2..33ca023da 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -89,10 +89,10 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
"A function with too many non-comment lines of code. Even simple logic gets hard to hold in your head past a point.",
},
primitive_obsession: {
- label: "Primitive obsession",
+ label: "Long parameter list",
category: "size_and_complexity",
description:
- "Many primitive parameters where a domain object would carry the same data. Calls become positional and easy to mismatch.",
+ "A function that takes many parameters, where a value object would often carry the same data. Calls become positional and easy to mismatch. Test cases are skipped: their parameters are injected fixtures.",
},
dry_violation: {
label: "DRY violation",
@@ -248,7 +248,7 @@ export const BIOMARKER_GLOSSARY: Record<string, BiomarkerInfo> = {
label: "I/O in loop",
category: "performance",
description:
- "A database call, network request, filesystem read, or subprocess spawn that runs once per loop iteration — the classic N+1. Detected across function boundaries via the call graph, resolved to a classified I/O boundary. A static performance RISK (high precision, low recall), not measured runtime.",
+ "A database call, network request, filesystem read, or subprocess spawn that runs once per loop iteration. On a database boundary this is the classic N+1 query; elsewhere it is an I/O call inside a loop. Detected across function boundaries via the call graph, resolved to a classified I/O boundary. A static performance RISK (high precision, low recall), not measured runtime.",
},
string_concat_in_loop: {
label: "String concat in loop",
diff --git a/tests/unit/analysis/test_file_reachability.py b/tests/unit/analysis/test_file_reachability.py
index 7426af087..cab8dd3ed 100644
--- a/tests/unit/analysis/test_file_reachability.py
+++ b/tests/unit/analysis/test_file_reachability.py
@@ -221,22 +221,20 @@ def test_analyzer_flags_a_file_whose_only_in_edge_is_co_change():
read a raw ``in_degree``, so a doc committed alongside a file counted as
that file's importer and silenced the finding."""
from repowise.core.analysis.dead_code import DeadCodeAnalyzer
- from repowise.core.analysis.dead_code.constants import _DEFAULT_DYNAMIC_PATTERNS
g = _graph(
{"src/orphan.py": {}, "docs/notes.md": {"language": "markdown"}},
[("docs/notes.md", "src/orphan.py", "co_changes")],
)
- findings = DeadCodeAnalyzer(g)._detect_unreachable_files(_DEFAULT_DYNAMIC_PATTERNS, set())
+ findings = DeadCodeAnalyzer(g)._detect_unreachable_files(set())
assert "src/orphan.py" in {f.file_path for f in findings}
def test_analyzer_flags_a_file_that_only_imports_itself():
from repowise.core.analysis.dead_code import DeadCodeAnalyzer
- from repowise.core.analysis.dead_code.constants import _DEFAULT_DYNAMIC_PATTERNS
g = _graph({"src/orphan.py": {}}, [("src/orphan.py", "src/orphan.py", "imports")])
- findings = DeadCodeAnalyzer(g)._detect_unreachable_files(_DEFAULT_DYNAMIC_PATTERNS, set())
+ findings = DeadCodeAnalyzer(g)._detect_unreachable_files(set())
assert "src/orphan.py" in {f.file_path for f in findings}
@@ -270,7 +268,6 @@ def test_the_predicate_is_the_only_thing_deciding_reachability():
``_is_synthetic_node`` and ``_is_fixture_path`` are not represented.
"""
from repowise.core.analysis.dead_code import DeadCodeAnalyzer
- from repowise.core.analysis.dead_code.constants import _DEFAULT_DYNAMIC_PATTERNS
g = _graph(
{
@@ -294,7 +291,7 @@ def test_the_predicate_is_the_only_thing_deciding_reachability():
rescues = analyzer._reachability_rescues(whitelist)
flagged = {
f.file_path
- for f in analyzer._detect_unreachable_files(_DEFAULT_DYNAMIC_PATTERNS, whitelist)
+ for f in analyzer._detect_unreachable_files(whitelist)
}
unreachable = {n for n in g.nodes() if not is_file_reachable(str(n), g, rescues)}
diff --git a/tests/unit/dead_code/test_no_git_signal.py b/tests/unit/dead_code/test_no_git_signal.py
index 1e34d8422..3265a1d1f 100644
--- a/tests/unit/dead_code/test_no_git_signal.py
+++ b/tests/unit/dead_code/test_no_git_signal.py
@@ -66,4 +66,5 @@ def test_a_row_with_no_recent_commits_keeps_its_rung() -> None:
}
)
assert finding.confidence == pytest.approx(1.0)
- assert finding.safe_to_delete
+ # A whole file is review-only whatever its rung (REVIEW_ONLY_KINDS).
+ assert not finding.safe_to_delete
diff --git a/tests/unit/dead_code/test_risk_factors.py b/tests/unit/dead_code/test_risk_factors.py
index df31d0284..0531cfc0d 100644
--- a/tests/unit/dead_code/test_risk_factors.py
+++ b/tests/unit/dead_code/test_risk_factors.py
@@ -143,9 +143,11 @@ def test_analyzer_caps_risk_file_even_when_old() -> None:
assert set(risky.risk_factors) == {"database", "environment"}
assert any("review before deleting" in e for e in risky.evidence)
- # The ordinary file with identical git age is still confidently safe.
+ # The ordinary file with identical git age keeps its confidence; as a whole
+ # file it is a review candidate, never deletion-ready (REVIEW_ONLY_KINDS).
ordinary = by_path["src/old_module.js"]
- assert ordinary.safe_to_delete is True
+ assert ordinary.confidence > RISK_CAP_CONFIDENCE
+ assert ordinary.safe_to_delete is False
assert ordinary.risk_factors == []
@@ -197,7 +199,7 @@ def test_analyzer_caps_untouched_service_worker() -> None:
# demoted to a review candidate but still surfaces.
assert sw.confidence == RISK_CAP_CONFIDENCE
- assert by_path["src/old_module.js"].safe_to_delete is True
+ assert by_path["src/old_module.js"].confidence > RISK_CAP_CONFIDENCE
def test_effective_safe_downgrades_persisted_service_worker() -> None:
diff --git a/tests/unit/dead_code/test_whitelist_safety.py b/tests/unit/dead_code/test_whitelist_safety.py
index e23fad5f4..a8ebbe204 100644
--- a/tests/unit/dead_code/test_whitelist_safety.py
+++ b/tests/unit/dead_code/test_whitelist_safety.py
@@ -95,8 +95,10 @@ def test_safe_to_delete_conservative():
)
by_path = {f.file_path: f for f in report.findings}
- # High confidence + no dynamic pattern -> safe
- assert by_path["pkg/old_unused.py"].safe_to_delete is True
+ # High confidence + no dynamic pattern -> still a review candidate: a whole
+ # file is never deletion-ready (REVIEW_ONLY_KINDS).
+ assert by_path["pkg/old_unused.py"].confidence >= 0.9
+ assert by_path["pkg/old_unused.py"].safe_to_delete is False
# High confidence but matches *Handler -> not safe
assert by_path["pkg/RequestHandler.py"].safe_to_delete is False
# Low confidence (0.4) -> not safe
@@ -168,10 +170,7 @@ def test_report_deletable_lines_sum():
safe_findings = [f for f in report.findings if f.safe_to_delete]
expected_lines = sum(f.lines for f in safe_findings)
assert report.deletable_lines == expected_lines
- # Verify that the safe findings include the two stale files
- safe_paths = {f.file_path for f in safe_findings}
- assert "pkg/dead1.py" in safe_paths
- assert "pkg/dead2.py" in safe_paths
- assert "pkg/alive.py" not in safe_paths
- # Verify the actual sum
- assert report.deletable_lines == 100 + 200
+ # Whole files are review-only (REVIEW_ONLY_KINDS), so none is counted as
+ # deletable, however stale.
+ assert safe_findings == []
+ assert report.deletable_lines == 0
diff --git a/tests/unit/generation/test_editor_file_base.py b/tests/unit/generation/test_editor_file_base.py
index 2dd92ae6c..f8fc4dd5f 100644
--- a/tests/unit/generation/test_editor_file_base.py
+++ b/tests/unit/generation/test_editor_file_base.py
@@ -164,7 +164,8 @@ def test_render_surfaces_performance_when_present(gen):
result = gen.render(data)
# Leads with the finding COUNT; the bounded [9,10] average and coverage %
# are deliberately not rendered (nothing an agent can act on there).
- assert "performance risk 7 open static I/O-in-loop / N+1 findings" in result
+ assert "performance risk 7 open static performance findings" in result
+ assert "N+1" not in result
def test_render_omits_performance_when_unmeasured(gen):
diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.py
index 062f3b2e1..120201cf2 100644
--- a/tests/unit/generation/test_editor_file_fetcher.py
+++ b/tests/unit/generation/test_editor_file_fetcher.py
@@ -604,3 +604,39 @@ async def test_code_health_trend_is_read_from_the_snapshots(session, repo, tmp_p
data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
assert data.code_health.hotspot_trend == "declining"
+
+
+async def test_code_health_names_production_files_only(session, repo, tmp_path):
+ """The worst file and the critical list are a worklist: tests stay out."""
+ from repowise.core.persistence.crud import save_health_findings
+ from repowise.core.persistence.models import HealthFileMetric
+
+ session.add(
+ HealthFileMetric(
+ repository_id=repo.id, file_path="tests/test_a.py", score=1.0, nloc=10, is_test=True
+ )
+ )
+ await _add_metric(session, repo.id, "src/a.py", 4.0)
+ await save_health_findings(
+ session,
+ repo.id,
+ [
+ {
+ "file_path": path,
+ "biomarker_type": "brain_method",
+ "severity": "high",
+ "function_name": "f",
+ "line_start": 1,
+ "line_end": 9,
+ "details": {},
+ "health_impact": 2.0,
+ "reason": "brain method",
+ }
+ for path in ("tests/test_a.py", "src/a.py")
+ ],
+ )
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert data.code_health.worst_path == "src/a.py"
+ assert [b["path"] for b in data.code_health.critical_biomarkers] == ["src/a.py"]
diff --git a/tests/unit/health/test_failing_types_demoted.py b/tests/unit/health/test_failing_types_demoted.py
new file mode 100644
index 000000000..692a20086
--- /dev/null
+++ b/tests/unit/health/test_failing_types_demoted.py
@@ -0,0 +1,138 @@
+"""Finding types taken off default surfaces, and how the rest is worded.
+
+- ``unused_internal``, ``duplicated_assertion_block`` and ``dry_violation`` are
+ hidden in the finding-type registry.
+- "N+1" is said only on a database boundary.
+- ``serial_await_in_loop`` stays silent on a line ``io_in_loop`` reports.
+- The long-parameter-list marker skips test cases.
+- A whole unreachable file is never deletion-ready.
+- The worst file is a production file; the worst test is reported apart.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.analysis.dead_code.risk_factors import (
+ RISK_CAP_CONFIDENCE,
+ SAFE_CONFIDENCE_THRESHOLD,
+ effective_safe_to_delete,
+)
+from repowise.core.analysis.finding_registry import excluded_types, status_of
+from repowise.core.analysis.health.biomarkers.base import FileContext
+from repowise.core.analysis.health.biomarkers.io_in_loop import IoInLoopDetector
+from repowise.core.analysis.health.biomarkers.primitive_obsession import (
+ PrimitiveObsessionDetector,
+)
+from repowise.core.analysis.health.biomarkers.serial_await_in_loop import (
+ SerialAwaitInLoopDetector,
+)
+from repowise.core.analysis.health.complexity import FunctionComplexity, PerfHit
+from repowise.core.analysis.health.ranking import worst_metric
+from repowise.core.analysis.health.scoring import compute_kpis
+
+
+def _ctx(*, perf_hits=(), fns=()) -> FileContext:
+ return FileContext(
+ file_path="src/example.py",
+ language="python",
+ nloc=max(sum(f.nloc for f in fns), 100),
+ has_test_file=False,
+ module=None,
+ all_functions=tuple(fns),
+ perf_hits=list(perf_hits),
+ )
+
+
+def test_failing_types_are_hidden():
+ for name in ("unused_internal", "duplicated_assertion_block", "dry_violation"):
+ assert status_of(name).status == "hidden"
+ assert name in excluded_types(requested=[name], include_provisional=True)
+ # The rest of each family stays on.
+ for name in ("unused_export", "unreachable_file", "io_in_loop", "complex_method"):
+ assert name not in excluded_types()
+
+
+def test_n_plus_one_only_with_a_database_boundary():
+ hits = [
+ PerfHit(kind="io_in_loop", line=3, function="f", detail="db"),
+ PerfHit(kind="io_in_loop", line=5, function="f", detail="network"),
+ PerfHit(kind="io_in_loop", line=7, function="f", detail="filesystem"),
+ PerfHit(
+ kind="io_in_loop", line=9, function="f", detail="network", path=("a.py::f", "b.py::g")
+ ),
+ PerfHit(kind="io_in_loop", line=11, function="f", detail="db", path=("a.py::f", "b.py::q")),
+ ]
+ by_line = {r.line_start: r for r in IoInLoopDetector().detect(_ctx(perf_hits=hits))}
+ for line, result in by_line.items():
+ has_db = result.details["boundary_kind"] == "db"
+ assert ("N+1" in result.reason) is has_db, (line, result.reason)
+ if not has_db:
+ assert "I/O call inside a loop" in result.reason
+ assert "cross-function N+1" in by_line[11].reason
+ assert "cross-function I/O call inside a loop" in by_line[9].reason
+
+
+def test_serial_await_suppressed_where_io_in_loop_fires():
+ hits = [
+ PerfHit(kind="io_in_loop", line=4, function="f", detail="network"),
+ PerfHit(kind="serial_await_in_loop", line=4, function="f", detail="network"),
+ PerfHit(kind="serial_await_in_loop", line=8, function="f", detail="network"),
+ ]
+ out = SerialAwaitInLoopDetector().detect(_ctx(perf_hits=hits))
+ assert [r.line_start for r in out] == [8]
+
+
+def test_long_parameter_list_skips_test_cases_and_says_what_it_is():
+ wide = FunctionComplexity(
+ "build", 1, 20, ccn=1, max_nesting=0, cognitive=0, nloc=14, param_count=7
+ )
+ test_case = FunctionComplexity(
+ "test_build",
+ 30,
+ 50,
+ ccn=1,
+ max_nesting=0,
+ cognitive=0,
+ nloc=14,
+ param_count=7,
+ is_test_case=True,
+ )
+ filler = FunctionComplexity(
+ "filler", 60, 130, ccn=1, max_nesting=0, cognitive=0, nloc=70, param_count=0
+ )
+ out = PrimitiveObsessionDetector().detect(_ctx(fns=[wide, test_case, filler]))
+ assert [r.function_name for r in out] == ["build"]
+ assert out[0].reason.startswith("long parameter list")
+
+
+def test_unreachable_file_is_never_deletion_ready():
+ assert not effective_safe_to_delete(1.0, "src/old.py", True, "unreachable_file")
+ assert effective_safe_to_delete(1.0, "src/old.py", True, "unused_export")
+
+
+def test_mcp_dead_code_tiers_are_the_engine_thresholds():
+ from repowise.server.mcp_server.tool_dead_code import _TIER_FLOORS
+
+ assert _TIER_FLOORS["high"] == SAFE_CONFIDENCE_THRESHOLD
+ assert _TIER_FLOORS["medium"] == RISK_CAP_CONFIDENCE
+
+
+def _metric(path: str, score: float, *, is_test: bool) -> SimpleNamespace:
+ return SimpleNamespace(file_path=path, score=score, nloc=10, is_test=is_test)
+
+
+def test_worst_file_is_production_and_tests_report_apart():
+ rows = [
+ _metric("tests/test_a.py", 1.0, is_test=True),
+ _metric("src/a.py", 3.0, is_test=False),
+ _metric("src/b.py", 6.0, is_test=False),
+ ]
+ assert worst_metric(rows, {}).file_path == "src/a.py"
+ kpis = compute_kpis(rows, set())
+ assert kpis["worst_performer_path"] == "src/a.py"
+ assert kpis["worst_test_path"] == "tests/test_a.py"
+ assert kpis["worst_test_score"] == 1.0
+ # A tests-only repo still names a worst file.
+ only_tests = [_metric("tests/test_a.py", 2.0, is_test=True)]
+ assert worst_metric(only_tests, {}).file_path == "tests/test_a.py"
diff --git a/tests/unit/server/golden/attention_build.json b/tests/unit/server/golden/attention_build.json
index 2a3747e16..2f6f6dd7d 100644
--- a/tests/unit/server/golden/attention_build.json
+++ b/tests/unit/server/golden/attention_build.json
@@ -172,25 +172,15 @@
"target_id": "src/tiny.py",
"subtype": "long_method",
"weight": 0.4
- },
- {
- "id": "dead-dead2",
- "type": "dead_code",
- "title": "src/orphan.py",
- "description": "Unreachable symbol (40 lines)",
- "severity": "low",
- "target_id": "src/orphan.py",
- "subtype": "unreachable_file",
- "weight": 0.7
}
],
- "total": 20,
+ "total": 19,
"by_source": {
"health_finding": 4,
"security_finding": 3,
"refactoring": 2,
"doc_drift": 2,
- "dead_code": 2,
+ "dead_code": 1,
"decisions": 5,
"knowledge_silo": 2
},
@@ -281,7 +271,7 @@
},
{
"key": "dead_code",
- "total": 2,
+ "total": 1,
"severity": "low",
"detail": "",
"lead": {
diff --git a/tests/unit/server/mcp/test_argument_validation.py b/tests/unit/server/mcp/test_argument_validation.py
index f39190fa8..5bb4a2c43 100644
--- a/tests/unit/server/mcp/test_argument_validation.py
+++ b/tests/unit/server/mcp/test_argument_validation.py
@@ -59,7 +59,8 @@ class TestDeadCodeMinConfidence:
@pytest.mark.asyncio
@pytest.mark.parametrize(
("value", "expected"),
- [("high", 1), ("medium", 3), ("low", 3)],
+ # Engine bands (0.7 / 0.4): dc1 0.9 and dc2 0.7 are high, dc3 0.5 medium.
+ [("high", 2), ("medium", 3), ("low", 3)],
)
async def test_tier_names_resolve_to_their_own_bands(self, setup_mcp, value, expected):
# The response is organised by these words and each tier description
diff --git a/tests/unit/server/mcp/test_budget.py b/tests/unit/server/mcp/test_budget.py
index fcef98d06..e0768327b 100644
--- a/tests/unit/server/mcp/test_budget.py
+++ b/tests/unit/server/mcp/test_budget.py
@@ -545,15 +545,15 @@ async def test_get_dead_code_truncation_is_expandable(setup_mcp, repo_root: Path
from repowise.server.mcp_server import get_dead_code
mcp_mod._repo_path = str(repo_root)
- # Fixture has two medium-tier findings; limit=1 drops one of them.
+ # Fixture has two high-tier findings (0.9, 0.7); limit=1 drops the second.
result = await get_dead_code(limit=1)
- assert result["tiers"]["medium"]["truncated"] is True
+ assert result["tiers"]["high"]["truncated"] is True
omitted = result["_meta"]["omitted"]
assert omitted["refs"]
stored = "\n".join(_store_get(repo_root, r) or "" for r in omitted["refs"])
- assert "OldModel" in stored # the dropped medium finding
- assert "medium-tier findings beyond limit=1" in stored
+ assert "deprecated_login" in stored # the dropped high finding
+ assert "high-tier findings beyond limit=1" in stored
rec = _store_record(repo_root, omitted["refs"][0])
assert rec["source"] == "mcp:get_dead_code"
diff --git a/tests/unit/server/mcp/test_dead_code.py b/tests/unit/server/mcp/test_dead_code.py
index bfe4411d9..79903d955 100644
--- a/tests/unit/server/mcp/test_dead_code.py
+++ b/tests/unit/server/mcp/test_dead_code.py
@@ -15,17 +15,20 @@ async def test_get_dead_code(setup_mcp):
result = await get_dead_code()
assert result["summary"]["total_findings"] == 3
- assert result["summary"]["safe_to_delete_count"] == 2
+ # dc1 is stored safe but is a whole file, so it reads as review-only.
+ assert result["summary"]["safe_to_delete_count"] == 1
- # Tiered structure: dc1 (0.9) in high, dc2 (0.7) + dc3 (0.5) in medium
+ # Engine bands (0.7 / 0.4): dc1 (0.9) + dc2 (0.7) high, dc3 (0.5) medium
tiers = result["tiers"]
- assert tiers["high"]["count"] == 1
- assert tiers["medium"]["count"] == 2
+ assert tiers["high"]["count"] == 2
+ assert tiers["medium"]["count"] == 1
assert tiers["low"]["count"] == 0
# High tier findings sorted by confidence desc
high_findings = tiers["high"]["findings"]
- assert high_findings[0]["confidence"] >= 0.8
+ assert high_findings[0]["confidence"] >= high_findings[1]["confidence"] >= 0.7
+ assert high_findings[0]["kind"] == "unreachable_file"
+ assert high_findings[0]["safe_to_delete"] is False
# Impact estimate present
assert result["impact"]["total_lines_reclaimable"] > 0
@@ -68,7 +71,7 @@ async def test_get_dead_code_tier_filter(setup_mcp):
assert "high" in result["tiers"]
assert "medium" not in result["tiers"]
assert "low" not in result["tiers"]
- assert result["tiers"]["high"]["count"] == 1
+ assert result["tiers"]["high"]["count"] == 2
@pytest.mark.asyncio
diff --git a/tests/unit/server/mcp/test_failing_types_surfaces.py b/tests/unit/server/mcp/test_failing_types_surfaces.py
new file mode 100644
index 000000000..7c6b3ffde
--- /dev/null
+++ b/tests/unit/server/mcp/test_failing_types_surfaces.py
@@ -0,0 +1,131 @@
+"""Default MCP output for the finding types the registry hides or demotes.
+
+Hidden types (``dry_violation``, ``unused_internal``) never appear; a test file never heads
+the worst or leverage lists but is ranked in ``test_worst_files``; perf text
+says "N+1" only with database evidence.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.models import HealthFileMetric
+
+
+async def failing_types_data(session, health_data):
+ from repowise.core.persistence.crud import save_health_findings
+
+ rid = health_data
+ session.add(
+ HealthFileMetric(
+ repository_id=rid,
+ file_path="tests/test_service.py",
+ score=1.0,
+ max_ccn=30,
+ max_nesting=6,
+ nloc=400,
+ has_test_file=False,
+ module="tests",
+ is_test=True,
+ )
+ )
+ await save_health_findings(
+ session,
+ rid,
+ [
+ {
+ "file_path": "src/auth/service.py",
+ "biomarker_type": "dry_violation",
+ "severity": "high",
+ "function_name": None,
+ "line_start": 1,
+ "line_end": 30,
+ "details": {"duplication_pct": 40.0},
+ "health_impact": 9.0,
+ "reason": "40% of file duplicated",
+ },
+ {
+ "file_path": "src/auth/service.py",
+ "biomarker_type": "io_in_loop",
+ "severity": "medium",
+ "function_name": "notify",
+ "line_start": 90,
+ "line_end": 90,
+ "details": {"boundary_kind": "network", "cross_function": False},
+ "health_impact": 0.0,
+ "reason": "a network call runs once per loop iteration (I/O call inside a loop)",
+ "dimension": "performance",
+ },
+ ],
+ )
+ await session.commit()
+ return rid
+
+
+async def test_hidden_type_absent_from_default_health_output(setup_mcp, failing_types_data):
+ from repowise.server.mcp_server import get_health
+
+ dashboard = await get_health(only=["top_findings", "test_findings"], limit=50)
+ assert "dry_violation" not in {f["biomarker_type"] for f in dashboard["top_findings"]}
+ targeted = await get_health(targets=["src/auth/service.py"], include=["unverified"])
+ assert "dry_violation" not in {f["biomarker_type"] for f in targeted["findings"]}
+
+
+async def test_unused_internal_absent_from_default_dead_code_output(setup_mcp, session, populated_db):
+ from repowise.core.persistence.models import DeadCodeFinding
+ from repowise.server.mcp_server import get_dead_code
+
+ session.add(
+ DeadCodeFinding(
+ id="dc_internal",
+ repository_id=populated_db,
+ kind="unused_internal",
+ file_path="src/auth/service.py",
+ symbol_name="_helper",
+ symbol_kind="function",
+ confidence=0.65,
+ reason="Private symbol with no callers",
+ lines=5,
+ safe_to_delete=False,
+ status="open",
+ )
+ )
+ await session.commit()
+
+ result = await get_dead_code(min_confidence=0.0)
+ kinds = [f["kind"] for tier in result["tiers"].values() for f in tier["findings"]]
+ assert "unused_internal" not in kinds
+ assert result["summary"]["withheld_types"]["unused_internal"]["count"] == 1
+ # Naming the kind does not bring it back.
+ named = await get_dead_code(kind="unused_internal", min_confidence=0.0)
+ assert [f for tier in named["tiers"].values() for f in tier["findings"]] == []
+
+
+async def test_test_files_ranked_apart_from_production(setup_mcp, failing_types_data):
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(
+ only=["worst_files", "test_worst_files", "high_leverage_files", "kpis"], limit=50
+ )
+ worst = [r["file_path"] for r in result["worst_files"]]
+ assert worst and "tests/test_service.py" not in worst
+ assert "tests/test_service.py" not in [r["file_path"] for r in result["high_leverage_files"]]
+ assert [r["file_path"] for r in result["test_worst_files"]] == ["tests/test_service.py"]
+ assert result["kpis"]["worst_performer_path"] == "src/auth/service.py"
+ assert result["kpis"]["worst_test_path"] == "tests/test_service.py"
+
+
+async def test_perf_text_has_no_n_plus_one_without_db(setup_mcp, failing_types_data):
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(include=["performance"], only=["top_findings"], limit=50)
+ perf = [f for f in result["top_findings"] if f["dimension"] == "performance"]
+ assert perf
+ for f in perf:
+ if f["details"].get("boundary_kind") != "db":
+ assert "N+1" not in f["reason"]
diff --git a/tests/unit/server/mcp/test_finding_registry_visibility.py b/tests/unit/server/mcp/test_finding_registry_visibility.py
new file mode 100644
index 000000000..3f249f37e
--- /dev/null
+++ b/tests/unit/server/mcp/test_finding_registry_visibility.py
@@ -0,0 +1,138 @@
+"""The finding-type registry decides what default surfaces show.
+
+A hidden type never reaches default MCP output; a provisional type appears
+only when asked for by name (or via ``include=["unverified"]``), and then
+carries ``verification: "unverified"``.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis import finding_registry
+from repowise.core.analysis.finding_registry import (
+ UNVERIFIED_LABEL,
+ FindingTypeStatus,
+ excluded_types,
+ status_of,
+ verification_label,
+ withheld_summary,
+)
+
+
+def _set(monkeypatch, name: str, status: str) -> None:
+ monkeypatch.setitem(finding_registry.REGISTRY, name, FindingTypeStatus(status, reason="test"))
+
+
+def _dead_kinds(result: dict) -> list[str]:
+ return [f["kind"] for tier in result["tiers"].values() for f in tier["findings"]]
+
+
+def test_unlisted_type_is_validated():
+ assert status_of("no_such_type_anywhere").status == "validated"
+ assert verification_label("no_such_type_anywhere") is None
+
+
+def test_excluded_types_hidden_always_provisional_unless_requested(monkeypatch):
+ _set(monkeypatch, "t_hidden", "hidden")
+ _set(monkeypatch, "t_prov", "provisional")
+ assert {"t_hidden", "t_prov"} <= excluded_types()
+ assert "t_prov" not in excluded_types(requested=["t_prov"])
+ assert "t_prov" not in excluded_types(include_provisional=True)
+ # Naming a hidden type is not enough to show it.
+ assert "t_hidden" in excluded_types(requested=["t_hidden"], include_provisional=True)
+ assert verification_label("t_prov") == UNVERIFIED_LABEL
+
+
+def test_withheld_summary_reports_only_types_with_rows(monkeypatch):
+ _set(monkeypatch, "t_hidden", "hidden")
+ out = withheld_summary({"t_hidden": 4, "other": 2}, {"t_hidden", "t_empty"})
+ assert out == {"t_hidden": {"count": 4, "status": "hidden", "reason": "test"}}
+
+
+async def test_hidden_dead_code_kind_never_in_default_output(setup_mcp, monkeypatch):
+ from repowise.server.mcp_server import get_dead_code
+
+ _set(monkeypatch, "unused_export", "hidden")
+ result = await get_dead_code(min_confidence=0.0)
+ assert "unused_export" not in _dead_kinds(result)
+ assert result["summary"]["total_findings"] == 1
+ assert "unused_export" not in result["summary"]["by_kind"]
+ assert result["summary"]["withheld_types"]["unused_export"]["count"] == 2
+
+ # Asking for it by name does not bring a hidden kind back.
+ named = await get_dead_code(kind="unused_export", min_confidence=0.0)
+ assert _dead_kinds(named) == []
+
+
+async def test_provisional_dead_code_kind_only_when_named_and_labelled(setup_mcp, monkeypatch):
+ from repowise.server.mcp_server import get_dead_code
+
+ _set(monkeypatch, "unused_export", "provisional")
+ default = await get_dead_code(min_confidence=0.0)
+ assert "unused_export" not in _dead_kinds(default)
+
+ named = await get_dead_code(kind="unused_export", min_confidence=0.0)
+ rows = [f for tier in named["tiers"].values() for f in tier["findings"]]
+ assert len(rows) == 2
+ assert all(f["verification"] == UNVERIFIED_LABEL for f in rows)
+ # A validated kind carries no label.
+ files = await get_dead_code(kind="unreachable_file", min_confidence=0.0)
+ assert all(
+ "verification" not in f for tier in files["tiers"].values() for f in tier["findings"]
+ )
+
+
+async def test_hidden_health_type_never_in_default_output(setup_mcp, health_data, monkeypatch):
+ from repowise.server.mcp_server import get_health
+
+ _set(monkeypatch, "complex_method", "hidden")
+ dashboard = await get_health(only=["top_findings", "test_findings"], limit=50)
+ types = [f["biomarker_type"] for f in dashboard["top_findings"]]
+ assert types and "complex_method" not in types
+
+ targeted = await get_health(targets=["src/auth/service.py"], include=["unverified"])
+ listed = [f["biomarker_type"] for f in targeted.get("findings", [])]
+ assert listed and "complex_method" not in listed
+ # Nor does it lead a file.
+ for row in targeted.get("metrics", []):
+ assert row.get("primary_biomarker") != "complex_method"
+
+
+async def test_provisional_health_type_only_when_opted_in(setup_mcp, health_data, monkeypatch):
+ from repowise.server.mcp_server import get_health
+
+ _set(monkeypatch, "nested_complexity", "provisional")
+ default = await get_health(only=["top_findings"], limit=50)
+ assert "nested_complexity" not in [f["biomarker_type"] for f in default["top_findings"]]
+
+ opted = await get_health(only=["top_findings"], include=["unverified"], limit=50)
+ rows = [f for f in opted["top_findings"] if f["biomarker_type"] == "nested_complexity"]
+ assert rows and all(f["verification"] == UNVERIFIED_LABEL for f in rows)
+ assert all(
+ "verification" not in f
+ for f in opted["top_findings"]
+ if f["biomarker_type"] != "nested_complexity"
+ )
+ assert "unknown_include_keys" not in opted
+
+
+async def test_crud_reads_leave_withheld_types_out(session, health_data, monkeypatch):
+ from repowise.core.persistence.crud import get_dead_code_findings, get_health_findings
+
+ _set(monkeypatch, "complex_method", "hidden")
+ _set(monkeypatch, "unused_export", "hidden")
+ shown = {f.biomarker_type for f in await get_health_findings(session, health_data)}
+ assert "complex_method" not in shown and shown
+ every = {
+ f.biomarker_type
+ for f in await get_health_findings(session, health_data, include_withheld=True)
+ }
+ assert "complex_method" in every
+ kinds = {f.kind for f in await get_dead_code_findings(session, health_data)}
+ assert kinds == {"unreachable_file"}
diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.py
index 0f66d85ac..c53745374 100644
--- a/tests/unit/server/mcp/test_health.py
+++ b/tests/unit/server/mcp/test_health.py
@@ -1479,11 +1479,11 @@ async def test_metric_rows_say_whether_a_file_is_test_material(setup_mcp, health
"""
from repowise.server.mcp_server import get_health
- result = await get_health(only=["worst_files", "high_leverage_files"])
- by_path = {m["file_path"]: m for m in result["worst_files"]}
+ result = await get_health(only=["worst_files", "test_worst_files", "high_leverage_files"])
+ by_path = {m["file_path"]: m for m in result["worst_files"] + result["test_worst_files"]}
assert by_path["tests/test_service.py"]["is_test"] is True
assert by_path["src/auth/service.py"]["is_test"] is False
- # Both ranked file lists carry it.
+ # Every ranked file list carries it.
assert all("is_test" in m for m in result["high_leverage_files"])
@@ -1545,6 +1545,9 @@ async def test_targeted_mode_asks_only_about_the_files_it_was_given(
async def test_kpis_still_include_test_files(setup_mcp, health_data_with_tests):
"""Excluding test material from the KPIs is a scoring change, not a display one.
+ The ranked worst-file list is a worklist, so it is production only and the
+ test files rank in ``test_worst_files``.
+
Measured across this workspace, dropping tests moves NLOC-weighted
``average_health`` 7.52 -> 6.87 on this repo, 7.07 -> 6.27 on the backend
and 7.59 -> 7.46 on the frontend: test files score *better* than
@@ -1553,9 +1556,10 @@ async def test_kpis_still_include_test_files(setup_mcp, health_data_with_tests):
"""
from repowise.server.mcp_server import get_health
- result = await get_health(only=["kpis", "worst_files"])
+ result = await get_health(only=["kpis", "worst_files", "test_worst_files"])
assert result["kpis"]["file_count"] == 3
- assert any(m["file_path"] == "tests/test_service.py" for m in result["worst_files"])
+ assert all(m["file_path"] != "tests/test_service.py" for m in result["worst_files"])
+ assert [m["file_path"] for m in result["test_worst_files"]] == ["tests/test_service.py"]
@pytest.mark.asyncio
diff --git a/tests/unit/server/test_dead_code.py b/tests/unit/server/test_dead_code.py
index 5584be7b7..351308835 100644
--- a/tests/unit/server/test_dead_code.py
+++ b/tests/unit/server/test_dead_code.py
@@ -141,9 +141,9 @@ async def test_list_dead_code_safe_only(client: AsyncClient, app) -> None:
params={"safe_only": True},
)
assert resp.status_code == 200
- data = resp.json()
- assert len(data) == 1
- assert data[0]["safe_to_delete"] is True
+ # The only stored-safe row is a whole file, which reads back as a review
+ # candidate: file-level findings are never deletion-ready.
+ assert resp.json() == []
@pytest.mark.asyncio
@@ -155,7 +155,8 @@ async def test_dead_code_summary(client: AsyncClient, app) -> None:
assert resp.status_code == 200
data = resp.json()
assert data["total_findings"] == 2
- assert data["deletable_lines"] == 50 # Only the safe-to-delete finding
+ # The stored-safe row is a whole file, re-derived as review-only.
+ assert data["deletable_lines"] == 0
assert "unreachable_file" in data["by_kind"]
@@ -220,3 +221,36 @@ async def test_resolve_finding_invalid_status(client: AsyncClient, app) -> None:
json={"status": "invalid_status"},
)
assert resp.status_code == 400
+
+
+async def test_stored_safe_unreachable_file_is_review_only_on_every_surface(
+ client: AsyncClient, app
+) -> None:
+ from repowise.core.persistence.models import HealthFileMetric
+ from repowise.server.services.attention import _dead_code_items
+
+ repo = await create_test_repo(client)
+ await _insert_dead_code(app.state.session_factory, repo["id"])
+ async with get_session(app.state.session_factory) as session:
+ session.add(
+ HealthFileMetric(
+ repository_id=repo["id"],
+ file_path="src/dead_module.py",
+ score=9.0,
+ max_ccn=1,
+ max_nesting=1,
+ nloc=50,
+ has_test_file=False,
+ module="src",
+ is_test=False,
+ )
+ )
+
+ resp = await client.get(f"/api/repos/{repo['id']}/files/src/dead_module.py")
+ assert resp.status_code == 200
+ assert [f["safe_to_delete"] for f in resp.json()["dead_code"]] == [False]
+
+ async with get_session(app.state.session_factory) as session:
+ items, total, _ = await _dead_code_items(session, repo["id"])
+ assert (items, total) == ([], 0)