Skip to content

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

feat(health): dataflow-verify advisory perf findings and wire refactoring config (#684)

Raghav Chamadiya4df5199a54da
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index fe1ebaf57..ef873acab 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -284,6 +284,14 @@ measured performance, and never fold it into the defect score. The
commit-agreement precision study and its caveats are published in the
[perf-detection methodology](https://github.com/repowise-dev/repowise-bench/blob/master/perf-detection/METHODOLOGY.md).
+**Verified findings.** `serial_await_in_loop` and `nested_loop_quadratic` are
+advisory because a quick scan cannot tell whether a loop's iterations depend on
+each other. When a deeper analysis can prove they do not, the finding is marked
+verified: it asserts the fix (fan out the awaits, or a genuine quadratic scan)
+instead of hedging, and carries `dataflow_verified: true`. The check is
+conservative (anything it cannot prove stays advisory) and only touches
+Python, TypeScript, JavaScript, and Go. It changes the wording, not the score.
+
Performance surfaces exactly where maintainability does: a `performance_average`
on the overview summary and MCP `kpis`, a per-file `performance_score`, a
Performance KPI card and per-pillar finding filter on the dashboard, the
diff --git a/docs/CONFIG.md b/docs/CONFIG.md
index ed4821615..6f082e9a9 100644
--- a/docs/CONFIG.md
+++ b/docs/CONFIG.md
@@ -130,7 +130,7 @@ refactoring:
enabled: true # the deterministic plans (zero LLM, in the health pass)
detectors:
disabled: [] # e.g. [move_method] to silence one detector
- min_confidence: medium # low | medium | high (the surface gate)
+ min_confidence: low # low | medium | high (confidence floor)
llm:
enabled: true # code generation, on by default; set false to disable
provider: null # falls back to the repo's configured LLM provider
@@ -141,6 +141,12 @@ refactoring:
health pass. Code generation is the only part that calls a provider: it is on
by default but never runs during indexing, only on an explicit request (set
`llm.enabled: false` to disable it).
+- `enabled: false` skips the whole deterministic detector pass; `detectors.disabled`
+ silences named detectors (`extract_class`, `split_file`, ...) while the rest run.
+- `min_confidence` is a floor applied when the plans are detected, so a plan below it
+ is never persisted (just like a disabled marker). Changing it takes effect on the
+ next `init` / `update`. Surfaces that accept a `min_confidence` query parameter can
+ only narrow further from this floor, not below it.
- Per-path disables reuse the `.repowise/health-rules.json` glob mechanism (the
same one markers use).
- Full reference: [REFACTORING.md](REFACTORING.md).
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_quadratic.py b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_quadratic.py
index 6cd7360c0..8c80aff2f 100644
--- a/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_quadratic.py
+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/nested_loop_quadratic.py
@@ -31,6 +31,24 @@ class NestedLoopQuadraticDetector:
for hit in ctx.perf_hits:
if hit.kind != _KIND:
continue
+ if hit.promoted:
+ # Dataflow proved the loop's iterations are independent, so the
+ # inner loop is a genuine full scan (not an early-terminating or
+ # accumulating search), a real O(n^2) pass.
+ details = {"dataflow_verified": True}
+ reason = (
+ "a loop nested inside another loop (O(n^2)) sits in a "
+ "hot/central function; its iterations are independent, so "
+ "this is a full quadratic scan; replace the inner loop with "
+ "a set/map lookup if it is a search"
+ )
+ else:
+ details = {}
+ reason = (
+ "a loop nested inside another loop (O(n^2)) sits in a "
+ "hot/central function; check the inner bound or use a "
+ "set/map lookup if it is a search"
+ )
out.append(
BiomarkerResult(
biomarker_type=self.name,
@@ -38,12 +56,8 @@ class NestedLoopQuadraticDetector:
function_name=hit.function,
line_start=hit.line,
line_end=hit.line,
- details={},
- reason=(
- "a loop nested inside another loop (O(n^2)) sits in a "
- "hot/central function; check the inner bound or use a "
- "set/map lookup if it is a search"
- ),
+ details=details,
+ reason=reason,
)
)
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 84dc94e99..5dc32a8f8 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
@@ -38,6 +38,20 @@ class SerialAwaitInLoopDetector:
if hit.kind != _KIND:
continue
phrasing = _BOUNDARY_PHRASING.get(hit.detail, "an awaited I/O call")
+ if hit.promoted:
+ # Dataflow proved the loop carries no data dependence between
+ # iterations: assert the fan-out instead of hedging on it.
+ details = {"boundary_kind": hit.detail, "dataflow_verified": True}
+ reason = (
+ f"{phrasing} is awaited serially in a loop whose iterations "
+ "carry no data dependence; fan out with gather / Promise.all"
+ )
+ else:
+ details = {"boundary_kind": hit.detail}
+ reason = (
+ f"{phrasing} is awaited serially in a loop; if the "
+ "iterations are independent, fan out with gather / Promise.all"
+ )
out.append(
BiomarkerResult(
biomarker_type=self.name,
@@ -45,12 +59,8 @@ class SerialAwaitInLoopDetector:
function_name=hit.function,
line_start=hit.line,
line_end=hit.line,
- details={"boundary_kind": hit.detail},
- reason=(
- f"{phrasing} is awaited serially in a loop; if the "
- "iterations are independent, fan out with "
- "gather / Promise.all"
- ),
+ details=details,
+ reason=reason,
)
)
return out
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.py
index e944f1926..574652f41 100644
--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py
+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py
@@ -203,6 +203,14 @@ class PerfHit:
# chain ``A -> B -> ... -> sink`` (PR4). Empty for same-function hits —
# its emptiness is what distinguishes the two cases downstream.
path: tuple[str, ...] = ()
+ # Set by the dataflow promotion pass (``perf.promotion``) when intra-
+ # procedural reaching definitions PROVE the enclosing loop carries no data
+ # dependence between iterations, turning an advisory "if the iterations are
+ # independent" hedge into an asserted finding. Only ever flipped for the
+ # advisory markers the promotion pass targets; left ``False`` everywhere the
+ # proof is unavailable (no dialect, guard trip, non-convergence) or the loop
+ # genuinely carries a dependence. The biomarker sharpens its message when set.
+ promoted: bool = False
@dataclass(frozen=True)
diff --git a/packages/core/src/repowise/core/analysis/health/config.py b/packages/core/src/repowise/core/analysis/health/config.py
index fa7276ba6..74a4aba6f 100644
--- a/packages/core/src/repowise/core/analysis/health/config.py
+++ b/packages/core/src/repowise/core/analysis/health/config.py
@@ -42,7 +42,7 @@ from pathlib import Path
import structlog
-from repowise.core.repo_config import get_repowise_dir
+from repowise.core.repo_config import get_repowise_dir, load_repo_config
from .models import Severity
@@ -51,6 +51,11 @@ log = structlog.get_logger(__name__)
HEALTH_RULES_FILENAME = "health-rules.json"
+# Confidence floor labels a repo may set under ``refactoring.min_confidence``.
+# Ordered low -> high; mirrors ``refactoring.models.CONFIDENCE_LEVELS`` without
+# importing the refactoring package (which triggers detector registration).
+_CONFIDENCE_LEVELS: tuple[str, ...] = ("low", "medium", "high")
+
# Accepted severity labels for ``severity_overrides`` values, normalized to
# the ``Severity`` enum. Anything else is dropped with a warning on load.
_SEVERITY_BY_NAME: dict[str, Severity] = {s.value: s for s in Severity}
@@ -109,23 +114,97 @@ class HealthConfig:
# preset (explicit keys win). Per-path remaps live on each ``HealthRule``.
severity_overrides: dict[str, Severity] = field(default_factory=dict)
profile: str | None = None
+ # Refactoring-layer knobs, sourced from the ``refactoring:`` block of
+ # ``.repowise/config.yaml`` (the same file the ``refactoring.llm.*`` keys
+ # already round-trip through). ``refactoring_enabled`` gates the whole
+ # deterministic detector pass; ``disabled_refactorings`` silences named
+ # detectors (``extract_class`` / ``split_file`` / ...); ``refactoring_
+ # min_confidence`` is the confidence floor applied at detection time, so a
+ # repo can suppress low-confidence plans exactly as it can disable a
+ # biomarker. Defaults keep every detector on with no floor.
+ refactoring_enabled: bool = True
+ disabled_refactorings: list[str] = field(default_factory=list)
+ refactoring_min_confidence: str | None = None
@classmethod
def load(cls, repo_path: Path | str) -> HealthConfig:
"""Load `.repowise/health-rules.json` for *repo_path*.
- Missing file → empty config. Malformed file → empty config + a
- single warning log. Never raises.
+ The per-file biomarker overrides come from ``health-rules.json``; the
+ refactoring-layer knobs come from the ``refactoring:`` block of
+ ``.repowise/config.yaml`` (loaded here and merged onto the same config
+ object). Missing file → empty config. Malformed file → empty config +
+ a single warning log. Never raises.
"""
+ cfg = cls._load_refactoring(repo_path)
rules_path = get_repowise_dir(repo_path) / HEALTH_RULES_FILENAME
if not rules_path.exists():
- return cls()
+ return cfg
try:
raw = json.loads(rules_path.read_text(encoding="utf-8"))
except (OSError, ValueError) as exc:
log.warning("health_rules_load_failed", path=str(rules_path), error=str(exc))
+ return cfg
+ rules_cfg = cls.from_dict(raw)
+ rules_cfg.refactoring_enabled = cfg.refactoring_enabled
+ rules_cfg.disabled_refactorings = cfg.disabled_refactorings
+ rules_cfg.refactoring_min_confidence = cfg.refactoring_min_confidence
+ return rules_cfg
+
+ @classmethod
+ def _load_refactoring(cls, repo_path: Path | str) -> HealthConfig:
+ """Read the ``refactoring:`` block from ``.repowise/config.yaml``.
+
+ Returns a config carrying only the refactoring knobs (biomarker fields
+ left at their defaults). Never raises: a missing/malformed file or an
+ unexpected shape degrades to the defaults (everything on, no floor).
+ """
+ try:
+ raw = load_repo_config(repo_path)
+ except Exception as exc: # defensive: config.yaml read must never break load
+ log.debug("refactoring_config_load_failed", error=str(exc))
return cls()
- return cls.from_dict(raw)
+ return cls._from_refactoring_block(
+ raw.get("refactoring") if isinstance(raw, dict) else None
+ )
+
+ @classmethod
+ def _from_refactoring_block(cls, block: object) -> HealthConfig:
+ """Parse the ``refactoring`` mapping into refactoring-knob fields."""
+ if not isinstance(block, dict):
+ return cls()
+ enabled = block.get("enabled")
+ detectors = block.get("detectors")
+ disabled_raw = detectors.get("disabled") if isinstance(detectors, dict) else None
+ disabled = [str(d) for d in disabled_raw or [] if isinstance(d, str)]
+ floor_raw = block.get("min_confidence")
+ floor = None
+ if isinstance(floor_raw, str) and floor_raw.strip().lower() in _CONFIDENCE_LEVELS:
+ floor = floor_raw.strip().lower()
+ elif floor_raw is not None:
+ log.warning("refactoring_config_bad_min_confidence", value=floor_raw)
+ return cls(
+ refactoring_enabled=bool(enabled) if isinstance(enabled, bool) else True,
+ disabled_refactorings=disabled,
+ refactoring_min_confidence=floor,
+ )
+
+ def has_overrides(self) -> bool:
+ """True when this config carries any analysis-time override.
+
+ The pipeline only bothers building an analyzer-config dict when
+ something here would change the analysis: a disabled/severity-remapped
+ biomarker, or any refactoring-layer knob set away from its default.
+ """
+ return bool(
+ self.disabled_biomarkers
+ or self.rules
+ or self.severity_overrides
+ or self.profile
+ or not self.refactoring_enabled
+ or self.disabled_refactorings
+ or self.refactoring_min_confidence
+ )
@classmethod
def from_dict(cls, raw: object) -> HealthConfig:
@@ -218,4 +297,7 @@ class HealthConfig:
"per_file_disabled": self.per_file_disabled(file_paths),
"severity_overrides": dict(self._repo_severity_overrides()),
"per_file_severity_overrides": self.per_file_severity_overrides(file_paths),
+ "refactoring_enabled": self.refactoring_enabled,
+ "disabled_refactorings": list(self.disabled_refactorings),
+ "refactoring_min_confidence": self.refactoring_min_confidence,
}
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 483fb1f7d..e513e6edd 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -41,6 +41,7 @@ from .models import HealthFileMetricData, HealthFindingData, HealthReport, Sever
from .perf import (
CallGraphIndex,
PerfRanker,
+ apply_perf_promotions,
collect_blocking_io_under_lock,
collect_centrality_gated,
collect_crossfn_io_in_loop,
@@ -361,6 +362,8 @@ class HealthAnalyzer:
dup_report = DuplicationReport()
disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))
+ refactoring_enabled: bool = bool(cfg.get("refactoring_enabled", True))
+ refactoring_min_confidence: str | None = cfg.get("refactoring_min_confidence")
# Repo-wide SCC index (import cycles), computed once and threaded into
# each file's RefactoringContext so Break Cycle never recomputes it.
file_scc_index = build_file_scc_index(self.graph)
@@ -392,6 +395,10 @@ class HealthAnalyzer:
# Cross-function N+1: augment perf_hits before the biomarker stage.
self._apply_crossfn_perf(walked)
+ # Dataflow promotion: mark advisory perf hits whose loop is provably
+ # iteration-independent (runs after the graph passes so the
+ # centrality-gated nested-loop hits are present to promote).
+ apply_perf_promotions(walked)
for pf, fcx in walked:
# Side-effect: bump Symbol.complexity_estimate when we can
@@ -420,6 +427,8 @@ class HealthAnalyzer:
repo_active_contributors_90d=repo_active_contributors,
severity_overrides=file_severity_overrides or None,
disabled_refactorings=disabled_refactorings,
+ refactoring_enabled=refactoring_enabled,
+ refactoring_min_confidence=refactoring_min_confidence,
file_scc_index=file_scc_index,
)
metrics.append(file_metric)
@@ -553,8 +562,13 @@ class HealthAnalyzer:
# Cross-function N+1: augment perf_hits before the biomarker stage.
walked = list(walked)
self._apply_crossfn_perf(walked)
+ # Dataflow promotion: mark advisory perf hits whose loop is provably
+ # iteration-independent (after the graph passes populate the hits).
+ apply_perf_promotions(walked)
disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))
+ refactoring_enabled: bool = bool(cfg.get("refactoring_enabled", True))
+ refactoring_min_confidence: str | None = cfg.get("refactoring_min_confidence")
file_scc_index = build_file_scc_index(self.graph)
findings: list[HealthFindingData] = []
metrics: list[HealthFileMetricData] = []
@@ -582,6 +596,8 @@ class HealthAnalyzer:
repo_active_contributors_90d=repo_active_contributors,
severity_overrides=file_severity_overrides or None,
disabled_refactorings=disabled_refactorings,
+ refactoring_enabled=refactoring_enabled,
+ refactoring_min_confidence=refactoring_min_confidence,
file_scc_index=file_scc_index,
)
metrics.append(file_metric)
@@ -747,6 +763,8 @@ class HealthAnalyzer:
repo_active_contributors_90d: int | None = None,
severity_overrides: dict[str, Severity] | None = None,
disabled_refactorings: list[str] | None = None,
+ refactoring_enabled: bool = True,
+ refactoring_min_confidence: str | None = None,
file_scc_index: dict[str, tuple[str, ...]] | None = None,
) -> tuple[HealthFileMetricData, list[HealthFindingData], list[RefactoringSuggestion]]:
file_path = pf.file_info.path
@@ -843,6 +861,10 @@ class HealthAnalyzer:
# Refactoring layer: reuse the data just computed (class cohesion
# components + this file's findings) to emit structured suggestions.
# Fault-isolated per detector; degrades to [] on any missing signal.
+ # Disabled outright from config => skip the whole pass (and its
+ # dataflow re-parse) for this file.
+ if not refactoring_enabled:
+ return metric, findings, []
rctx = RefactoringContext(
file_path=file_path,
language=pf.file_info.language,
@@ -857,7 +879,11 @@ class HealthAnalyzer:
function_analyses=self._extract_method_analyses(pf, findings),
blame_index=blame_index,
)
- suggestions = detect_refactorings(rctx, disabled=disabled_refactorings or ())
+ suggestions = detect_refactorings(
+ rctx,
+ disabled=disabled_refactorings or (),
+ min_confidence=refactoring_min_confidence,
+ )
return metric, findings, suggestions
def _is_hotspot(self, meta: dict | object) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/health/perf/__init__.py b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
index 08282a034..2fc06c919 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/__init__.py
@@ -21,6 +21,7 @@ from .crossfn import collect_crossfn_io_in_loop
from .dialects import PERF_DIALECTS, BasePerfDialect
from .gated import collect_blocking_io_under_lock, collect_centrality_gated
from .io_boundaries import collect_io_names
+from .promotion import apply_perf_promotions
from .ranking import PerfRanker
from .reachability import ReachInfo, path_to_sink, reachable_to_sink
@@ -30,6 +31,7 @@ __all__ = [
"CallGraphIndex",
"PerfRanker",
"ReachInfo",
+ "apply_perf_promotions",
"collect_blocking_io_under_lock",
"collect_centrality_gated",
"collect_crossfn_io_in_loop",
diff --git a/packages/core/src/repowise/core/analysis/health/perf/promotion.py b/packages/core/src/repowise/core/analysis/health/perf/promotion.py
new file mode 100644
index 000000000..88e999fd1
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/perf/promotion.py
@@ -0,0 +1,284 @@
+"""Advisory -> asserted promotion of perf findings via intra-procedural dataflow.
+
+Two perf markers are advisory *by construction* because a file-local pass cannot
+prove the one thing that would make them certain - that the loop's iterations do
+not depend on each other:
+
+ * ``serial_await_in_loop`` - an awaited I/O call run once per iteration. The fix
+ (fan out with ``gather`` / ``Promise.all``) is only valid when iteration i+1
+ does not consume a value iteration i produced.
+ * ``nested_loop_quadratic`` - a data-dependent loop nested in another. The
+ "use a set/map lookup" advice presumes the inner loop is a genuine full scan,
+ not an accumulation that carries state.
+
+This module supplies exactly that missing proof, and only that. For a function
+already carrying one of those advisory hits it runs the dataflow layer
+(:func:`dataflow.analyze_function` - CFG + reaching definitions) over the *one*
+loop the hit sits in and checks for a **loop-carried true dependence**: a use of
+some variable, inside the loop, that can read a value a previous iteration wrote.
+When none exists the iterations are provably independent and the hit is marked
+``promoted`` (the biomarker then asserts rather than hedges). When the proof is
+unavailable - no def/use dialect for the language, the CFG guard trips, the
+fixpoint does not converge, no enclosing loop is found, or a genuine carried
+dependence *is* present - the hit is left advisory. Precision over recall: a
+false promotion is the one way to burn the perf pillar's trust, so every
+uncertain case degrades to silence.
+
+**Soundness of the carried-dependence check.** Using reaching definitions plus a
+per-iteration must-def analysis, a loop use of ``v`` is *upward-exposed* (can see
+a previous iteration's value) when, on some path from the loop header to the use,
+``v`` is not redefined first. A loop carries a dependence iff some in-loop use is
+upward-exposed to an in-loop definition of the same variable. The loop induction
+variable is redefined at the header on every path, so it is never flagged; an
+accumulator (``acc = acc + x``) reads before its same-iteration write, so it is.
+The analysis tracks only local-variable data flow - attribute/field state, global
+mutation, aliasing, and I/O ordering are out of scope - so it is a *necessary*
+condition checker: it can only ever REFUSE to promote (find a possible
+dependence), never invent independence where local flow shows a carry. That
+directionality is what keeps the promotion sound.
+
+**Budget.** The dataflow build runs ONLY for functions that already hold an
+advisory hit - a strict subset of the perf scan, itself a subset of the walk. A
+file with no such hit is never re-parsed. The same flagged-only discipline the
+Extract Method consumer uses, keyed on the perf hit instead of a structural smell.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+import structlog
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from ..complexity import FileComplexity
+ from ..dataflow.cfg import CFG
+ from ..dataflow.defuse import FunctionDefUse
+ from ..dataflow.reaching import ReachingDefinitions
+
+log = structlog.get_logger(__name__)
+
+# The dataflow layer and the complexity walker are imported lazily inside the
+# functions below (never at module load): ``perf/__init__`` is pulled in while
+# the complexity walker is still initialising (``perf_walk`` -> ``perf.dialects``),
+# and the dataflow layer imports the biomarker detectors, so an eager import here
+# would close an import cycle. The same lazy discipline ``perf.crossfn`` uses.
+
+# The advisory markers this pass can turn into asserted findings. Both hedge on
+# iteration independence, which the loop-carried-dependence proof settles.
+PROMOTABLE_KINDS: frozenset[str] = frozenset({"serial_await_in_loop", "nested_loop_quadratic"})
+
+
+def apply_perf_promotions(walked: Iterable[tuple[Any, FileComplexity]]) -> None:
+ """Mark provably-independent advisory perf hits ``promoted``, in place.
+
+ Mirrors ``engine._apply_crossfn_perf``: it mutates each file's ``perf_hits``
+ in place and is fully failure-isolated, so a promotion hiccup never blocks
+ the health report. Must run AFTER the graph-dependent perf passes so the
+ centrality-gated ``nested_loop_quadratic`` hits are present.
+ """
+ for pf, fcx in walked:
+ try:
+ promoted_lines = _promotable_lines_for_file(pf, fcx)
+ except Exception as exc: # never let a single file break the pass
+ log.debug(
+ "perf_promotion_failed", path=getattr(pf.file_info, "path", "?"), error=str(exc)
+ )
+ continue
+ if not promoted_lines:
+ continue
+ fcx.perf_hits = [
+ replace(h, promoted=True)
+ if (h.kind in PROMOTABLE_KINDS and h.line in promoted_lines and not h.promoted)
+ else h
+ for h in fcx.perf_hits
+ ]
+
+
+def _promotable_lines_for_file(pf: Any, fcx: FileComplexity) -> set[int]:
+ """The advisory-hit lines in *fcx* the dataflow proof clears for promotion.
+
+ Returns an empty set (never raises up to the caller for the common cases)
+ when the file has no promotable advisory hit, the language has no def/use
+ dialect, or the parse fails - the documented degrade-to-silence outcomes.
+ """
+ target_lines = {h.line for h in fcx.perf_hits if h.kind in PROMOTABLE_KINDS}
+ if not target_lines:
+ return set()
+
+ from ..complexity.ast_utils import _collect_function_nodes
+ from ..dataflow.analyze import analyze_function
+ from ..dataflow.dialects.base import get_defuse_dialect
+ from ..dataflow.parsing import parse_source
+
+ language = pf.file_info.language
+ if get_defuse_dialect(language) is None:
+ return set() # no dialect -> silence (Python / TS / JS / Go only)
+
+ abs_path = pf.file_info.abs_path
+ try:
+ source = Path(abs_path).read_bytes()
+ except OSError:
+ return set()
+
+ parsed = parse_source(abs_path, language, source)
+ if parsed is None:
+ return set()
+ root, lmap = parsed
+
+ promoted: set[int] = set()
+ for fn_node in _collect_function_nodes(root, lmap):
+ fstart = fn_node.start_point[0] + 1
+ fend = fn_node.end_point[0] + 1
+ hits_here = {ln for ln in target_lines if fstart <= ln <= fend}
+ if not hits_here:
+ continue
+ analyzed = analyze_function(fn_node, language, lmap)
+ if analyzed is None:
+ continue # guard trip / non-convergence / no dialect -> stay advisory
+ cfg, def_use, reaching = analyzed
+ for line in hits_here:
+ if _loop_iterations_independent(cfg, def_use, reaching, line):
+ promoted.add(line)
+ return promoted
+
+
+# ---------------------------------------------------------------------------
+# The loop-carried-dependence proof
+# ---------------------------------------------------------------------------
+
+
+def _loop_iterations_independent(
+ cfg: CFG, def_use: FunctionDefUse, reaching: ReachingDefinitions, line: int
+) -> bool:
+ """True iff the innermost loop containing *line* carries no data dependence.
+
+ ``reaching`` is accepted for interface symmetry with the dataflow layer (and
+ to assert the fixpoint converged); the proof itself is realised with a
+ per-iteration must-def analysis over the CFG + def/use facts, which is what
+ distinguishes an intra-iteration read from a cross-iteration one.
+ """
+ if not reaching.converged:
+ return False
+ loop = _innermost_loop_containing(cfg, line)
+ if loop is None:
+ return False # no loop enclosing the hit -> nothing proven
+ loop_blocks, header_id = loop
+
+ # Variables written somewhere inside the loop body - only these can carry a
+ # value from one iteration into the next.
+ in_loop_defs: set[str] = {d.var for d in def_use.definitions if d.block_id in loop_blocks}
+ if not in_loop_defs:
+ return True # nothing the loop writes -> nothing to carry
+
+ defined_before = _must_defined_before_block(cfg, def_use, loop_blocks, header_id)
+
+ for bid in loop_blocks:
+ bdu = def_use.block(bid)
+ if bdu is None:
+ continue
+ local_def_lines: dict[str, list[int]] = {}
+ for d in bdu.defs:
+ local_def_lines.setdefault(d.var, []).append(d.line)
+ must_here = defined_before.get(bid, frozenset())
+ for use in bdu.uses:
+ v = use.name
+ if v not in in_loop_defs:
+ continue # loop-invariant or param read -> not carried
+ if v in must_here:
+ continue # redefined on every path before this block this iteration
+ earlier = local_def_lines.get(v)
+ if earlier and any(dl < use.line for dl in earlier):
+ continue # a same-block write strictly precedes the read (current iter)
+ # Upward-exposed to an in-loop definition: the read can observe a
+ # value a previous iteration wrote -> a loop-carried dependence.
+ return False
+ return True
+
+
+def _innermost_loop_containing(cfg: CFG, line: int) -> tuple[frozenset[int], int] | None:
+ """The (blocks, header_id) of the smallest natural loop covering *line*."""
+ best: tuple[frozenset[int], int] | None = None
+ for latch, header in cfg.back_edges():
+ blocks = _natural_loop(cfg, latch, header)
+ if not _blocks_cover_line(cfg, blocks, line):
+ continue
+ if best is None or len(blocks) < len(best[0]):
+ best = (blocks, header)
+ return best
+
+
+def _natural_loop(cfg: CFG, latch: int, header: int) -> frozenset[int]:
+ """The natural loop of back-edge ``latch -> header``.
+
+ ``{header}`` plus every node that reaches *latch* without passing through
+ *header* - the classic natural-loop set. Header's own predecessors are never
+ traversed (it is seeded into the set first), so the pre-loop block and any
+ outer structure stay out.
+ """
+ loop = {header}
+ if latch not in loop:
+ loop.add(latch)
+ stack = [latch]
+ while stack:
+ n = stack.pop()
+ for p in cfg.block(n).predecessors:
+ if p not in loop:
+ loop.add(p)
+ stack.append(p)
+ return frozenset(loop)
+
+
+def _blocks_cover_line(cfg: CFG, blocks: frozenset[int], line: int) -> bool:
+ """True if any statement in *blocks* spans *line* (1-indexed)."""
+ for bid in blocks:
+ for stmt in cfg.block(bid).statements:
+ if stmt.start_line <= line <= stmt.end_line:
+ return True
+ return False
+
+
+def _must_defined_before_block(
+ cfg: CFG, def_use: FunctionDefUse, loop_blocks: frozenset[int], header_id: int
+) -> dict[int, frozenset[str]]:
+ """Variables guaranteed written before each loop block, within one iteration.
+
+ A forward *must* (intersection) analysis over the loop's blocks, treating the
+ header as the iteration start (nothing defined yet) and ignoring the back-edge
+ - so it measures what a single pass from the header definitely writes before a
+ given block. With back-edges removed the loop subgraph is a DAG whose block-id
+ order is a valid topological order, so one pass in id order reaches the
+ fixpoint. A use whose variable is in this set was redefined this iteration and
+ cannot read a previous one.
+ """
+ defs_in_block: dict[int, frozenset[str]] = {}
+ for bid in loop_blocks:
+ bdu = def_use.block(bid)
+ defs_in_block[bid] = frozenset(d.var for d in bdu.defs) if bdu is not None else frozenset()
+
+ defined_in: dict[int, frozenset[str]] = {}
+ defined_out: dict[int, frozenset[str]] = {}
+ for block in cfg.blocks: # emission (id) order
+ bid = block.id
+ if bid not in loop_blocks:
+ continue
+ if bid == header_id:
+ din: frozenset[str] = frozenset()
+ else:
+ pred_outs = [
+ defined_out[p]
+ for p in block.predecessors
+ if p in loop_blocks and p in defined_out and not _is_back_edge(cfg, p, bid)
+ ]
+ din = frozenset.intersection(*pred_outs) if pred_outs else frozenset()
+ defined_in[bid] = din
+ defined_out[bid] = din | defs_in_block[bid]
+ return defined_in
+
+
+def _is_back_edge(cfg: CFG, src: int, dst: int) -> bool:
+ """True if ``src -> dst`` is a loop back-edge (into a loop header, src > dst)."""
+ return cfg.block(dst).kind == "loop_header" and src > dst
diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
index e6ef79744..c3ee066fe 100644
--- a/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
+++ b/packages/core/src/repowise/core/analysis/health/refactoring/registry.py
@@ -15,7 +15,7 @@ from collections.abc import Sequence
import structlog
-from .models import RefactoringContext, RefactoringSuggestion
+from .models import CONFIDENCE_LEVELS, RefactoringContext, RefactoringSuggestion
log = structlog.get_logger(__name__)
@@ -67,15 +67,47 @@ def registered_detectors(*, disabled: Sequence[str] = ()) -> list[RefactoringDet
def detect_refactorings(
- ctx: RefactoringContext, *, disabled: Sequence[str] = ()
+ ctx: RefactoringContext,
+ *,
+ disabled: Sequence[str] = (),
+ min_confidence: str | None = None,
) -> list[RefactoringSuggestion]:
- """Run every registered detector on *ctx*, fault-isolated per detector."""
+ """Run every registered detector on *ctx*, fault-isolated per detector.
+
+ *min_confidence* is an optional confidence floor (``"low"`` / ``"medium"``
+ / ``"high"``): a suggestion whose ``confidence`` ranks below it is dropped
+ at detection time, so a repo can suppress low-confidence plans from config
+ exactly as it disables a detector. An unset or unrecognised floor keeps
+ every suggestion.
+ """
+ floor_idx = _confidence_floor_index(min_confidence)
out: list[RefactoringSuggestion] = []
for detector in registered_detectors(disabled=disabled):
try:
- out.extend(detector.detect(ctx))
+ for suggestion in detector.detect(ctx):
+ if floor_idx and _confidence_rank(suggestion.confidence) < floor_idx:
+ continue
+ out.append(suggestion)
except Exception as exc:
# One bad detector must not break the health pass; degrade to
# "no suggestion" for this file.
log.debug("refactoring_detector_failed", detector=detector.name, error=str(exc))
return out
+
+
+def _confidence_rank(level: str) -> int:
+ """Ordinal of a confidence label; unknown labels rank at the floor (0)."""
+ try:
+ return CONFIDENCE_LEVELS.index(level)
+ except ValueError:
+ return 0
+
+
+def _confidence_floor_index(min_confidence: str | None) -> int:
+ """Ordinal of the confidence floor, or 0 (no floor) when unset/unknown."""
+ if not min_confidence:
+ return 0
+ try:
+ return CONFIDENCE_LEVELS.index(min_confidence.strip().lower())
+ except (ValueError, AttributeError):
+ return 0
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index c18382f3b..981a40f0f 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -289,7 +289,7 @@ def run_partial_analysis(
_hcfg = HealthConfig.load(repo_path)
_analyzer_config = (
_hcfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])
- if (_hcfg.disabled_biomarkers or _hcfg.rules)
+ if _hcfg.has_overrides()
else None
)
partial_health_report = _health_analyzer.analyze(
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 0a7572037..a889a95ab 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -204,7 +204,7 @@ async def _run_health_analysis(
analyzer_config: dict[str, object] | None = None
if repo_path is not None:
cfg = HealthConfig.load(repo_path)
- if cfg.disabled_biomarkers or cfg.rules:
+ if cfg.has_overrides():
file_paths = [pf.file_info.path for pf in parsed_files]
analyzer_config = cfg.to_analyzer_config(file_paths)
diff --git a/tests/unit/health/test_health_config.py b/tests/unit/health/test_health_config.py
index f688848f3..ed1cd4cfb 100644
--- a/tests/unit/health/test_health_config.py
+++ b/tests/unit/health/test_health_config.py
@@ -167,3 +167,70 @@ def test_malformed_file_falls_back_silently(tmp_path: Path):
cfg = HealthConfig.load(tmp_path)
assert cfg.disabled_biomarkers == []
assert cfg.rules == []
+
+
+# -- refactoring block (config.yaml) --------------------------------------
+
+
+def _write_config_yaml(tmp_path: Path, body: str) -> Path:
+ repowise = tmp_path / ".repowise"
+ repowise.mkdir(exist_ok=True)
+ (repowise / "config.yaml").write_text(body, encoding="utf-8")
+ return tmp_path
+
+
+def test_refactoring_defaults_when_no_config(tmp_path: Path):
+ cfg = HealthConfig.load(tmp_path)
+ assert cfg.refactoring_enabled is True
+ assert cfg.disabled_refactorings == []
+ assert cfg.refactoring_min_confidence is None
+ assert cfg.has_overrides() is False
+
+
+def test_refactoring_block_round_trips(tmp_path: Path):
+ _write_config_yaml(
+ tmp_path,
+ "refactoring:\n"
+ " enabled: true\n"
+ " detectors:\n"
+ " disabled:\n"
+ " - split_file\n"
+ " - move_method\n"
+ " min_confidence: high\n",
+ )
+ cfg = HealthConfig.load(tmp_path)
+ assert cfg.refactoring_enabled is True
+ assert cfg.disabled_refactorings == ["split_file", "move_method"]
+ assert cfg.refactoring_min_confidence == "high"
+ assert cfg.has_overrides() is True
+ out = cfg.to_analyzer_config([])
+ assert out["refactoring_enabled"] is True
+ assert out["disabled_refactorings"] == ["split_file", "move_method"]
+ assert out["refactoring_min_confidence"] == "high"
+
+
+def test_refactoring_disabled_flag(tmp_path: Path):
+ _write_config_yaml(tmp_path, "refactoring:\n enabled: false\n")
+ cfg = HealthConfig.load(tmp_path)
+ assert cfg.refactoring_enabled is False
+ assert cfg.has_overrides() is True
+
+
+def test_refactoring_min_confidence_normalized_and_validated(tmp_path: Path):
+ _write_config_yaml(tmp_path, "refactoring:\n min_confidence: MEDIUM\n")
+ cfg = HealthConfig.load(tmp_path)
+ assert cfg.refactoring_min_confidence == "medium"
+ # An out-of-range floor is dropped (degrade to no floor), never raised.
+ _write_config_yaml(tmp_path, "refactoring:\n min_confidence: bogus\n")
+ cfg = HealthConfig.load(tmp_path)
+ assert cfg.refactoring_min_confidence is None
+
+
+def test_refactoring_block_coexists_with_health_rules(tmp_path: Path):
+ _write(tmp_path, {"disabled_biomarkers": ["dry_violation"]})
+ _write_config_yaml(
+ tmp_path, "refactoring:\n detectors:\n disabled:\n - extract_class\n"
+ )
+ cfg = HealthConfig.load(tmp_path)
+ assert cfg.disabled_biomarkers == ["dry_violation"]
+ assert cfg.disabled_refactorings == ["extract_class"]
diff --git a/tests/unit/health/test_perf_promotion.py b/tests/unit/health/test_perf_promotion.py
new file mode 100644
index 000000000..f3c3a584b
--- /dev/null
+++ b/tests/unit/health/test_perf_promotion.py
@@ -0,0 +1,193 @@
+"""Unit tests for the advisory -> asserted perf promotion (loop-carried proof).
+
+Best-effort like the other dataflow tests: each skips when the Python tree-sitter
+pack is missing rather than failing. The proof must be SOUND in one direction:
+it may only ever refuse to promote a genuinely carried loop; it must never
+promote one.
+"""
+
+from __future__ import annotations
+
+import textwrap
+
+import pytest
+
+from repowise.core.analysis.health.complexity.ast_utils import _collect_function_nodes
+from repowise.core.analysis.health.complexity.languages import get_language_map
+from repowise.core.analysis.health.dataflow import analyze_function
+from repowise.core.analysis.health.perf.promotion import _loop_iterations_independent
+
+
+def _require_python() -> None:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip("tree-sitter language pack missing for python")
+ if _get_language("python") is None:
+ pytest.skip("tree-sitter language pack missing for python")
+
+
+def _independent(src: str, marker: str) -> bool:
+ """Analyze the first function in *src* and run the proof at *marker*'s line."""
+ _require_python()
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+
+ body = textwrap.dedent(src)
+ lmap = get_language_map("python")
+ parser = Parser(_get_language("python"))
+ tree = parser.parse(body.encode())
+ nodes = _collect_function_nodes(tree.root_node, lmap)
+ assert nodes, "no function node parsed"
+ analyzed = analyze_function(nodes[0], "python", lmap)
+ assert analyzed is not None, "analysis returned None"
+ cfg, def_use, reaching = analyzed
+ line = next(i for i, ln in enumerate(body.splitlines(), start=1) if marker in ln)
+ return _loop_iterations_independent(cfg, def_use, reaching, line)
+
+
+# -- provably independent (should promote) --------------------------------
+
+
+def test_for_loop_append_is_independent():
+ assert _independent(
+ """
+ async def f(items):
+ results = []
+ for item in items:
+ r = await fetch(item.id) # HIT
+ results.append(r)
+ return results
+ """,
+ "HIT",
+ )
+
+
+def test_range_index_for_loop_is_independent():
+ assert _independent(
+ """
+ async def f(urls):
+ out = []
+ for i in range(len(urls)):
+ r = await fetch(urls[i]) # HIT
+ out.append(r)
+ return out
+ """,
+ "HIT",
+ )
+
+
+def test_pre_loop_invariant_read_is_independent():
+ assert _independent(
+ """
+ async def f(items, base):
+ prefix = compute(base)
+ for item in items:
+ r = await fetch(prefix, item) # HIT
+ store(r)
+ """,
+ "HIT",
+ )
+
+
+def test_compute_then_use_same_iteration_is_independent():
+ assert _independent(
+ """
+ async def f(items):
+ for item in items:
+ key = derive(item)
+ r = await fetch(key) # HIT
+ emit(r)
+ """,
+ "HIT",
+ )
+
+
+# -- provably carried (must NOT promote) ----------------------------------
+
+
+def test_accumulator_is_carried():
+ assert not _independent(
+ """
+ async def f(items):
+ acc = 0
+ for item in items:
+ acc = acc + await fetch(item) # HIT
+ return acc
+ """,
+ "HIT",
+ )
+
+
+def test_augmented_accumulator_is_carried():
+ assert not _independent(
+ """
+ async def f(items):
+ total = []
+ for item in items:
+ r = await fetch(item) # HIT
+ total += [r]
+ use_running(total, r)
+ return total
+ """,
+ "HIT",
+ )
+
+
+def test_while_manual_increment_is_carried():
+ assert not _independent(
+ """
+ async def f(n):
+ i = 0
+ while i < n:
+ r = await fetch(i) # HIT
+ i = i + 1
+ return r
+ """,
+ "HIT",
+ )
+
+
+def test_conditional_definition_is_carried():
+ # ``prev`` is defined only on the then-branch, but read unconditionally, so a
+ # later iteration can read an earlier iteration's ``prev``.
+ assert not _independent(
+ """
+ async def f(items):
+ prev = None
+ for item in items:
+ r = await fetch(item, prev) # HIT
+ if item.ok:
+ prev = r
+ """,
+ "HIT",
+ )
+
+
+def test_running_dependency_across_iterations_is_carried():
+ assert not _independent(
+ """
+ async def f(items):
+ cursor = start()
+ for item in items:
+ page = await fetch(cursor) # HIT
+ cursor = page.next
+ """,
+ "HIT",
+ )
+
+
+# -- degrade-to-silence ---------------------------------------------------
+
+
+def test_line_outside_any_loop_is_not_independent():
+ # A line that sits in no loop cannot be proven -> refuse (advisory stays).
+ assert not _independent(
+ """
+ async def f(x):
+ r = await fetch(x) # HIT
+ return r
+ """,
+ "HIT",
+ )
diff --git a/tests/unit/health/test_perf_promotion_engine.py b/tests/unit/health/test_perf_promotion_engine.py
new file mode 100644
index 000000000..56be8f9d9
--- /dev/null
+++ b/tests/unit/health/test_perf_promotion_engine.py
@@ -0,0 +1,173 @@
+"""File-level promotion pass: in-place marking, budget, and biomarker output."""
+
+from __future__ import annotations
+
+import textwrap
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.health.biomarkers import FileContext
+from repowise.core.analysis.health.biomarkers.serial_await_in_loop import BIOMARKER as SERIAL
+from repowise.core.analysis.health.complexity import FileComplexity, PerfHit
+from repowise.core.analysis.health.perf.promotion import apply_perf_promotions
+
+
+def _require_python() -> None:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip("tree-sitter language pack missing for python")
+ if _get_language("python") is None:
+ pytest.skip("tree-sitter language pack missing for python")
+
+
+@dataclass
+class _FileInfo:
+ path: str
+ abs_path: str
+ language: str
+
+
+@dataclass
+class _ParsedFile:
+ file_info: _FileInfo
+
+
+def _write(tmp_path: Path, name: str, src: str) -> str:
+ p = tmp_path / name
+ p.write_text(textwrap.dedent(src), encoding="utf-8")
+ return str(p)
+
+
+def _walked_entry(tmp_path: Path, name: str, src: str, hits: list[PerfHit]):
+ abs_path = _write(tmp_path, name, src)
+ pf = _ParsedFile(_FileInfo(path=name, abs_path=abs_path, language="python"))
+ fcx = FileComplexity(functions=[], classes=[], perf_hits=hits)
+ return pf, fcx
+
+
+def _line_of(src: str, marker: str) -> int:
+ body = textwrap.dedent(src)
+ return next(i for i, ln in enumerate(body.splitlines(), start=1) if marker in ln)
+
+
+def test_independent_hit_is_promoted_in_place(tmp_path: Path):
+ _require_python()
+ src = """
+ async def f(items):
+ out = []
+ for item in items:
+ r = await fetch(item.id) # HIT
+ out.append(r)
+ return out
+ """
+ line = _line_of(src, "HIT")
+ hits = [PerfHit(kind="serial_await_in_loop", line=line, function="f", detail="network")]
+ pf, fcx = _walked_entry(tmp_path, "indep.py", src, hits)
+
+ apply_perf_promotions([(pf, fcx)])
+
+ assert fcx.perf_hits[0].promoted is True
+ # The biomarker now asserts rather than hedges, and flags verification.
+ results = SERIAL.detect(_ctx(fcx))
+ assert results and results[0].details.get("dataflow_verified") is True
+ assert "carry no data dependence" in results[0].reason
+
+
+def test_carried_hit_is_not_promoted(tmp_path: Path):
+ _require_python()
+ src = """
+ async def f(items):
+ cursor = start()
+ for item in items:
+ page = await fetch(cursor) # HIT
+ cursor = page.next
+ """
+ line = _line_of(src, "HIT")
+ hits = [PerfHit(kind="serial_await_in_loop", line=line, function="f", detail="network")]
+ pf, fcx = _walked_entry(tmp_path, "carried.py", src, hits)
+
+ apply_perf_promotions([(pf, fcx)])
+
+ assert fcx.perf_hits[0].promoted is False
+ results = SERIAL.detect(_ctx(fcx))
+ assert results and "dataflow_verified" not in results[0].details
+ assert "if the iterations are independent" in results[0].reason
+
+
+def test_budget_no_dataflow_without_advisory_hit(tmp_path: Path, monkeypatch):
+ """The dataflow build runs ONLY for files carrying a promotable advisory hit."""
+ _require_python()
+ from repowise.core.analysis.health.dataflow import analyze as analyze_mod
+
+ calls = {"n": 0}
+ real = analyze_mod.analyze_function
+
+ def _counting(*args, **kwargs):
+ calls["n"] += 1
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(analyze_mod, "analyze_function", _counting)
+
+ indep = """
+ async def f(items):
+ out = []
+ for item in items:
+ r = await fetch(item.id) # HIT
+ out.append(r)
+ return out
+ """
+ # A file with a non-promotable perf hit (io_in_loop) and no advisory marker
+ # must never be analyzed.
+ io_only = """
+ def g(items):
+ for item in items:
+ db.execute(item) # NOHIT
+ """
+ line = _line_of(indep, "HIT")
+ e1 = _walked_entry(
+ tmp_path,
+ "indep.py",
+ indep,
+ [PerfHit(kind="serial_await_in_loop", line=line, function="f", detail="network")],
+ )
+ e2 = _walked_entry(
+ tmp_path,
+ "io_only.py",
+ io_only,
+ [PerfHit(kind="io_in_loop", line=_line_of(io_only, "NOHIT"), function="g", detail="db")],
+ )
+
+ apply_perf_promotions([e1, e2])
+
+ # Exactly the one function holding the advisory hit was analyzed; the
+ # io_in_loop-only file was never parsed for dataflow.
+ assert calls["n"] == 1
+ assert e1[1].perf_hits[0].promoted is True
+ assert e2[1].perf_hits[0].promoted is False
+
+
+def test_unsupported_language_degrades_to_silence(tmp_path: Path):
+ # A language with no def/use dialect leaves the hit advisory, never raises.
+ abs_path = _write(tmp_path, "a.rb", "def f; end\n")
+ pf = _ParsedFile(_FileInfo(path="a.rb", abs_path=abs_path, language="ruby"))
+ fcx = FileComplexity(
+ functions=[],
+ classes=[],
+ perf_hits=[PerfHit(kind="serial_await_in_loop", line=1, function="f")],
+ )
+ apply_perf_promotions([(pf, fcx)])
+ assert fcx.perf_hits[0].promoted is False
+
+
+def _ctx(fcx: FileComplexity) -> FileContext:
+ return FileContext(
+ file_path="x.py",
+ language="python",
+ nloc=10,
+ has_test_file=False,
+ module=None,
+ perf_hits=fcx.perf_hits,
+ )
diff --git a/tests/unit/health/test_refactoring_registry.py b/tests/unit/health/test_refactoring_registry.py
new file mode 100644
index 000000000..e334fb798
--- /dev/null
+++ b/tests/unit/health/test_refactoring_registry.py
@@ -0,0 +1,72 @@
+"""Registry-level gating: disabled detectors + the config confidence floor."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.health.refactoring import registry
+from repowise.core.analysis.health.refactoring.models import (
+ RefactoringContext,
+ RefactoringSuggestion,
+)
+from repowise.core.analysis.health.refactoring.registry import (
+ RefactoringDetector,
+ detect_refactorings,
+)
+
+
+def _suggestion(confidence: str, name: str = "fake") -> RefactoringSuggestion:
+ return RefactoringSuggestion(
+ refactoring_type=name,
+ file_path="a.py",
+ target_symbol="X",
+ line_start=1,
+ line_end=2,
+ plan={},
+ evidence={},
+ impact_delta=0.0,
+ effort_bucket="S",
+ blast_radius={},
+ confidence=confidence,
+ )
+
+
+class _FakeDetector(RefactoringDetector):
+ name = "fake_all_confidences"
+
+ def detect(self, ctx: RefactoringContext) -> list[RefactoringSuggestion]:
+ return [_suggestion("low"), _suggestion("medium"), _suggestion("high")]
+
+
+def _one_detector(monkeypatch):
+ monkeypatch.setattr(registry, "_REGISTRY", [_FakeDetector()])
+
+
+def _ctx() -> RefactoringContext:
+ return RefactoringContext(file_path="a.py", language="python", nloc=10)
+
+
+def test_no_floor_keeps_all(_one_detector):
+ out = detect_refactorings(_ctx())
+ assert [s.confidence for s in out] == ["low", "medium", "high"]
+
+
+def test_medium_floor_drops_low(_one_detector):
+ out = detect_refactorings(_ctx(), min_confidence="medium")
+ assert [s.confidence for s in out] == ["medium", "high"]
+
+
+def test_high_floor_keeps_only_high(_one_detector):
+ out = detect_refactorings(_ctx(), min_confidence="high")
+ assert [s.confidence for s in out] == ["high"]
+
+
+def test_unknown_floor_is_no_floor(_one_detector):
+ out = detect_refactorings(_ctx(), min_confidence="bogus")
+ assert len(out) == 3
+
+
+def test_disabled_detector_emits_nothing(_one_detector):
+ out = detect_refactorings(_ctx(), disabled=["fake_all_confidences"])
+ assert out == []