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.

fix(risk): apply .repowise/health-rules.json when rescoring commits (#4179)

Abdullah Azmi4ef01ad584a9
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 405410638..942f19974 100644
--- a/packages/core/src/repowise/core/analysis/change_health/service.py
+++ b/packages/core/src/repowise/core/analysis/change_health/service.py
@@ -114,7 +114,8 @@ class ChangeHealthDeltaService:
source = GitRevisionSource(repo_path)
self.source = source
self.repo_path = repo_path
- self.analyzer = analyzer or RevisionHealthAnalyzer()
+ self._custom_analyzer = analyzer is not None
+ self.analyzer = analyzer or RevisionHealthAnalyzer(repo_root=repo_path)
self.rules_fingerprint = rules_fingerprint
self._cache: OrderedDict[str, ChangeHealthDelta] = OrderedDict()
self._lock = threading.Lock()
@@ -320,16 +321,23 @@ class ChangeHealthDeltaService:
)
base_sources = self.source.read(pair.base_sha, base_paths)
rename = pair.rename_map()
- head_run = self.analyzer.analyze(
- head_sources, subject_paths=set(head_paths), dependents=index
- )
- base_run = self.analyzer.analyze(
+ analyzer = self._analyzer_for([*head_paths, *base_paths])
+ head_run = analyzer.analyze(head_sources, subject_paths=set(head_paths), dependents=index)
+ base_run = analyzer.analyze(
base_sources,
subject_paths=set(base_paths),
dependents=index if index is not None else _on_base(head_run, rename),
)
return _Sides(head_paths, head_sources, base_sources, head_run, base_run, rename)
+ def _analyzer_for(self, paths: list[str]) -> RevisionHealthAnalyzer:
+ if self._custom_analyzer or self.repo_path is None:
+ return self.analyzer
+ config = _analyzer_config(self.repo_path, paths)
+ if config is None:
+ return self.analyzer
+ return RevisionHealthAnalyzer(repo_root=self.repo_path, config=config)
+
def _surface(
self,
match: MatchResult,
@@ -502,8 +510,7 @@ def _nothing_compared(changes: list[FileChange], skipped: dict[str, str]) -> str
)
if all(r in NO_CODE_GAP for r in skipped.values()):
return (
- "Only query, template or other data files changed; "
- "health analysis does not cover them."
+ "Only query, template or other data files changed; health analysis does not cover them."
)
return "No changed file is health-analyzable, so nothing was compared."
@@ -738,3 +745,11 @@ def _unavailable(
fingerprint=fingerprint,
scope=scope or ScopeCounts(),
)
+
+
+def _analyzer_config(repo_path: str, paths: list[str]) -> dict[str, object] | None:
+ """The repo's `.repowise/health-rules.json` as analyzer config, or `None`."""
+ from ..health.config import HealthConfig
+
+ cfg = HealthConfig.load(repo_path)
+ return cfg.to_analyzer_config(paths) if cfg.has_overrides() else None
diff --git a/packages/core/src/repowise/core/analysis/change_review/service.py b/packages/core/src/repowise/core/analysis/change_review/service.py
index 207c7dde2..ead4cd1bb 100644
--- a/packages/core/src/repowise/core/analysis/change_review/service.py
+++ b/packages/core/src/repowise/core/analysis/change_review/service.py
@@ -19,6 +19,7 @@ from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any
+from ...repo_config import health_rules_fingerprint
from ..change_contracts import (
ContractImpact,
analyze_contract_impact,
@@ -176,9 +177,7 @@ class ChangeReviewService:
lanes["health"] = LaneState("unsupported", "the caller skipped this lane")
return None
else:
- service = self.delta_service or ChangeHealthDeltaService(
- self.source, repo_path=self.repo_path
- )
+ service = self.delta_service or self._default_delta_service()
delta = service.compare(
DeltaRequest(
repo_path=self.repo_path or "",
@@ -195,6 +194,12 @@ class ChangeReviewService:
)
return delta
+ def _default_delta_service(self) -> ChangeHealthDeltaService:
+ fingerprint = health_rules_fingerprint(self.repo_path) if self.repo_path else ""
+ return ChangeHealthDeltaService(
+ self.source, repo_path=self.repo_path, rules_fingerprint=fingerprint
+ )
+
def _risk(
self,
request: ChangeReviewRequest,
@@ -271,9 +276,7 @@ class ChangeReviewService:
base_parsed=inputs.base_parsed,
head_parsed=inputs.head_parsed,
changed_set={e.path for e in manifest if e.head_path},
- added_ranges_by_file={
- e.path: list(e.added_ranges) for e in manifest if e.added_ranges
- },
+ added_ranges_by_file={e.path: list(e.added_ranges) for e in manifest if e.added_ranges},
base_is_snapshot=inputs.base_is_snapshot,
)
lanes["contracts"] = LaneState(
@@ -298,9 +301,7 @@ class ChangeReviewService:
)
return evidence.tests
- def _independent(
- self, evidence: ChangeReviewEvidence, lanes: dict[str, LaneState]
- ) -> Any:
+ def _independent(self, evidence: ChangeReviewEvidence, lanes: dict[str, LaneState]) -> Any:
if evidence.independent is None or "independent_changes" in evidence.skip:
lanes["independent_changes"] = LaneState("unsupported", _NO_SOURCE)
return None
@@ -308,9 +309,7 @@ class ChangeReviewService:
# ``None`` here means one change, not a missing answer: the lane ran.
return partition_independent_changes(evidence.independent)
- def _branch_overlap(
- self, evidence: ChangeReviewEvidence, lanes: dict[str, LaneState]
- ) -> Any:
+ def _branch_overlap(self, evidence: ChangeReviewEvidence, lanes: dict[str, LaneState]) -> Any:
if "branch_overlap" in evidence.skip:
lanes["branch_overlap"] = LaneState("unsupported", "the caller skipped this lane")
return None
@@ -354,9 +353,7 @@ def _head_id(pair: RevisionPair) -> RevisionId:
)
-def _covering_tests(
- tests: Mapping[str, Any] | None, state: EvidenceState
-) -> CoveringTestEvidence:
+def _covering_tests(tests: Mapping[str, Any] | None, state: EvidenceState) -> CoveringTestEvidence:
"""The test lane's contribution to the directive, in the directive's terms."""
if tests is None:
return CoveringTestEvidence()
diff --git a/packages/core/src/repowise/core/analysis/health/config.py b/packages/core/src/repowise/core/analysis/health/config.py
index 5176331f6..dd5de0a0b 100644
--- a/packages/core/src/repowise/core/analysis/health/config.py
+++ b/packages/core/src/repowise/core/analysis/health/config.py
@@ -334,14 +334,17 @@ class HealthConfig:
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
+ return any(
+ (
+ self.disabled_biomarkers,
+ self.rules,
+ self.severity_overrides,
+ self.profile,
+ not self.refactoring_enabled,
+ self.disabled_refactorings,
+ self.refactoring_min_confidence,
+ self.assert_extra_names,
+ )
)
@classmethod
@@ -354,7 +357,9 @@ class HealthConfig:
rules: list[HealthRule] = []
raw_rules = raw.get("rules")
if raw_rules is not None and not isinstance(raw_rules, list | tuple):
- log.warning("health_rules_field_not_a_list", field="rules", got=type(raw_rules).__name__)
+ log.warning(
+ "health_rules_field_not_a_list", field="rules", got=type(raw_rules).__name__
+ )
raw_rules = []
for entry in raw_rules or []:
if not isinstance(entry, dict):
diff --git a/tests/unit/change_health/test_regressions.py b/tests/unit/change_health/test_regressions.py
index 0605055db..c23f8a598 100644
--- a/tests/unit/change_health/test_regressions.py
+++ b/tests/unit/change_health/test_regressions.py
@@ -296,6 +296,60 @@ def test_a_gated_cause_says_a_constant_flag_switches_it_off():
def test_an_unlisted_expected_reason_keeps_the_inherent_sentence():
perf = SimpleNamespace(
- actionability_state="expected", actionability_reason="something_new", intervention_symbol=None
+ actionability_state="expected",
+ actionability_reason="something_new",
+ intervention_symbol=None,
)
assert "inherent" in _suggestion(SimpleNamespace(), perf)
+
+
+# -- .repowise/health-rules.json applies when rescoring a commit --------------
+
+
+def test_repo_health_rules_silence_disabled_and_per_file_biomarkers(make_repo):
+ import json
+
+ from repowise.core.analysis.change_review import ChangeReviewRequest, ChangeReviewService
+ from repowise.core.repo_config import health_rules_fingerprint
+
+ repo = make_repo()
+ repo.commit("seed", {"src/legacy/mod.py": "x = 1\n", "src/active/app.py": "y = 1\n"})
+ per_path_rules = {
+ "rules": [
+ {"path": "src/legacy/**", "disabled_biomarkers": ["complex_method"]},
+ ],
+ }
+ repo.commit(
+ "add complex functions and per-path rule",
+ {
+ ".repowise/health-rules.json": json.dumps(per_path_rules),
+ "src/legacy/mod.py": python_complex("legacy_tangle", 18),
+ "src/active/app.py": python_complex("active_tangle", 18),
+ },
+ )
+
+ service = ChangeHealthDeltaService(repo_path=str(repo.path))
+ delta = service.compare(DeltaRequest(str(repo.path), "HEAD"))
+
+ assert delta.status == "available"
+ assert not any(
+ f.path == "src/legacy/mod.py" and f.biomarker_type == "complex_method"
+ for f in delta.findings
+ )
+ assert any(
+ f.path == "src/active/app.py" and f.biomarker_type == "complex_method"
+ for f in delta.findings
+ )
+
+ # Repo-wide disabled_biomarkers silences the marker everywhere.
+ repo.write(
+ ".repowise/health-rules.json",
+ json.dumps({"disabled_biomarkers": ["complex_method"]}),
+ )
+ review = ChangeReviewService(
+ GitRevisionSource(str(repo.path)), repo_path=str(repo.path)
+ ).review(ChangeReviewRequest(revspec="HEAD", baseline=0))
+ assert review.health is not None
+ assert review.health.fingerprint is not None
+ assert review.health.fingerprint.rules_fingerprint == health_rules_fingerprint(repo.path)
+ assert not any(f.biomarker_type == "complex_method" for f in review.health.findings)