Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(health): move per-file evaluation out of HealthAnalyzer into FileEvaluator (#4016)
Raghav Chamadiya9128c8dec469
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex bf2f6477b..0918e2579 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -273,7 +273,7 @@ A single pass over the parsed file list. For each file the analyzer:`max(ccn)` into `Symbol.complexity_estimate` as a side effect, so the`ContextAssembler` symbol ranker benefits even when a caller never touchesthe health tables.-3. **Evaluates the file** (`_evaluate_file`): builds a `FileContext` (nloc,+3. **Evaluates the file** (`FileEvaluator.evaluate` in `file_evaluator.py`): builds a `FileContext` (nloc,`has_test_file`, module, per-function and per-class metrics, the per-file`git_meta`, graph in-degree as `dependents_count`, the repo-wide p80 ofin-degree used as the `brain_method` floor, coverage fields when ingested,@@ -1138,7 +1138,7 @@ per-path `disabled_biomarkers` and `severity_overrides`, keyed by agitignore-semantics glob over the repo-relative POSIX path (every matching ruleapplies; disabled sets union) (`path`, with `path_glob` and `glob` asaccepted aliases). `to_analyzer_config(file_paths)` resolves the globs to-per-file disabled sets, which the engine honors in `_evaluate_file()`. The+per-file disabled sets, which the engine honors in `FileEvaluator.evaluate()`. Theschema and examples are in the[user guide](../layers/CODE_HEALTH.md#configuration).@@ -1222,7 +1222,7 @@ from `coverage/detector.parse`. Stdlib-only (no extra XML libraries).Users (not contributors) author `.repowise/health-rules.json`. To adda new override key (beyond `disabled_biomarkers`), extend`HealthConfig` and thread it through `to_analyzer_config()` ->-`engine._evaluate_file()`.+`FileEvaluator.evaluate()` in `file_evaluator.py`.---diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex e5b881679..a84422163 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -20,8 +20,6 @@ from __future__ import annotationsimport asyncioimport functoolsimport os-from collections.abc import Callable-from dataclasses import dataclassfrom datetime import UTC, datetimefrom pathlib import Path, PurePosixPathfrom typing import Any@@ -38,28 +36,26 @@ from ...ingestion.git_indexer.function_blame import (# Package attribution lives in one place, shared with the traverser and with# the `repowise update` backfill, so all three agree on what a package is.-from ...ingestion.package_roots import module_for as _module_for+from ...ingestion.package_roots import module_for as _module_for # noqa: F401 (re-export)from ...ingestion.package_roots import package_roots_from_paths as _package_rootsfrom ...ingestion.package_roots import scan_package_roots as _scan_package_rootsfrom ...installed_components import is_installed_componentfrom ..dead_code.file_reachability import file_dependency_neighborsfrom ..execution_roles import ExecutionRoles-from ..graph_view import HasEdge, ImportEdgeView+from ..graph_view import ImportEdgeViewfrom .asserts.lexicon import AssertVocabularyfrom .asserts.oracle_reach import collect_cross_file_oracles-from .biomarkers import FileContext, detect_all-from .biomarkers.function_hotspot import refresh_replayedfrom .complexity import FileComplexity, FunctionComplexity, walk_file-from .complexity.languages import has_health_dialectfrom .crossfn_perf import CrossFunctionPerfStagefrom .dataflow import FileDataflowCachefrom .duplication import ClonePair, DuplicationReportfrom .duplication.detector import clone_ranges, union_line_countfrom .duplication.isolation import detect_clones_with_isolation as detect_clones-from .finding_identity import SYMBOL_INDEX_KEY, SYMBOL_KEY, SYMBOL_LINE_KEY-from .function_blame_rollup import blame_commit_entries, commit_spans-from .history_refresh import BLAME_MARKERS, as_biomarker_result-from .models import HealthFileMetricData, HealthFindingData, HealthReport, Severity+from .file_evaluator import FileEvaluator, _read_source_lines, _RunConfig+from .file_evaluator import _mark_deepest_block as _mark_deepest_block+from .file_evaluator import _mark_function_facts as _mark_function_facts+from .file_evaluator import walked_functions as walked_functions+from .models import HealthFileMetricData, HealthFindingData, HealthReportfrom .perf import (CallGraphIndex,build_performance_opportunities,@@ -68,9 +64,7 @@ from .perf import (from .ranking import deduction_by_pathfrom .refactoring import (PerformancePlanPolicy,- RefactoringContext,RefactoringSuggestion,- detect_refactorings,performance_fix_suggestions,rank_suggestions,)@@ -79,13 +73,7 @@ from .repo_tests import RepoTestIndexfrom .repo_tests import _has_paired_test_file as _has_paired_test_filefrom .repo_tests import _path_basenames as _path_basenamesfrom .scope import scores_language-from .scoring import (- attach_impacts,- compute_kpis,- file_score_fields,- remap_severities,- score_file,-)+from .scoring import compute_kpisfrom .source_reader import SourceReader, disk_source_readerfrom .walk_cache import HealthWalkCache@@ -403,122 +391,6 @@ log = structlog.get_logger(__name__)HEALTH_ANALYZER_VERSION = 40-#: Function facts a finding inside the function carries in its details.-_FUNCTION_FACTS = ("deprecated", "gated_off")---def _mark_function_facts(- findings: list[HealthFindingData], functions: list[FunctionComplexity]-) -> None:- """Stamp ``deprecated: true`` / ``gated_off: true`` on each function-level- finding inside a function with that fact. Absent, not false, everywhere- else, so the details of every other finding are byte-for-byte what they- were."""- spans = [- (fact, fc.name, fc.start_line, fc.end_line)- for fc in functions- for fact in _FUNCTION_FACTS- if getattr(fc, fact, False)- ]- for finding in findings:- if finding.function_name is None:- continue- line = finding.line_start- for fact, name, start, end in spans:- if name == finding.function_name and (line is None or start <= line <= end):- finding.details[fact] = True---#: Function-size findings whose fix starts at the deepest nested block.-_DEEPEST_BLOCK_MARKERS = frozenset(- {"complex_method", "nested_complexity", "brain_method", "large_method", "bumpy_road"}-)---def _mark_deepest_block(- findings: list[HealthFindingData], functions: list[FunctionComplexity]-) -> None:- """Copy the function's deepest nested block onto its size findings as- ``deepest_block: {start, end}``, so a fix list can name where to start- without re-walking the file. Absent when the function does not nest."""- blocks = {- (fc.name, fc.start_line): fc.deepest_block- for fc in functions- if fc.deepest_block- }- if not blocks:- return- for finding in findings:- if finding.biomarker_type not in _DEEPEST_BLOCK_MARKERS:- continue- block = blocks.get((finding.function_name, finding.line_start))- if block:- # A mapping, not a pair: surfaces count every nested list as a collection.- finding.details["deepest_block"] = {"start": block[0], "end": block[1]}---def walked_functions(- fc_list: list[FunctionComplexity], language: str-) -> tuple[FunctionComplexity, ...]:- """The functions a file's biomarkers see, in document order.-- Sorted because the walker collects sibling nodes off a LIFO stack and so- returns them last-first, and a marker should report a file top-down. Two- rows can share a span (a one-line callback and its enclosing call), and a- stable sort leaves those in walk order.-- SQL routine metrics are text-counted and defect-uncalibrated; they exist- for symbol stamping and the ``sql_high_complexity`` marker- (maintainability). Holding them back here keeps the calibrated method- biomarkers (defect dimension) from firing on SQL.- """- if language == "sql":- return ()- return tuple(sorted(fc_list, key=lambda fc: (fc.start_line, fc.end_line)))----def _stamp_symbol_lines(findings: list[HealthFindingData], fcx: FileComplexity) -> None:- """Record the symbol each finding sits in, so its id can be anchored there.-- The finding id is the symbol plus the offset into it, so an edit above the- symbol leaves the id alone. The anchor is the innermost function or class- holding the finding's line and sharing its name; a finding the detector- left unnamed takes the innermost one of any name, recorded under- ``symbol``. ``symbol_index`` tells same-named symbols in one file apart (two- ``run`` methods, sibling ``it`` callbacks). A finding outside every symbol- keeps absolute lines, and a replayed stored finding keeps its anchor.- """- spans = sorted(- [(fc.start_line, fc.end_line, fc.name) for fc in fcx.functions]- + [(c.start_line, c.end_line, c.name) for c in fcx.classes]- )- for f in findings:- if f.line_start is None or SYMBOL_LINE_KEY in f.details:- continue- holding = [- span- for span in spans- if span[0] <= f.line_start <= span[1]- and (not f.function_name or span[2] == f.function_name)- ]- if not holding:- continue- start, _, name = max(holding, key=lambda span: (span[0], -span[1]))- stamp: dict = {SYMBOL_LINE_KEY: start}- if not f.function_name:- stamp[SYMBOL_KEY] = name- index = sum(1 for span in spans if span[2] == name and span[0] < start)- if index:- stamp[SYMBOL_INDEX_KEY] = index- f.details = {**f.details, **stamp}---# Method-level smells that make the dataflow / Extract Method pass worthwhile.-# Only files carrying one of these get a CFG + def/use + reaching pass built.-_EXTRACT_METHOD_SOURCES = frozenset({"large_method", "brain_method", "complex_method"})--def _log_duplication_diagnostics(report: DuplicationReport) -> None:"""Emit a debug line when a duplication guard fired.@@ -542,15 +414,6 @@ def _log_duplication_diagnostics(report: DuplicationReport) -> None:log.debug("health_duplication_limits", **diag)-def _commit_entries(fcx: FileComplexity, git_meta: dict) -> list:- """Split File's per-function commit sets: from the blame index, the stored- rows, or the blame a re-score took for a file stored without them."""- idx = git_meta.get("blame_index") or git_meta.get("commit_set_blame")- if isinstance(idx, BlameIndex):- return blame_commit_entries(fcx.functions, idx)- return list(git_meta.get("function_commit_shas") or ())--def _partner(file_path: str, pair: ClonePair) -> str:"""The other file of *pair*: *file_path* itself for a clone inside it."""return pair.file_b if pair.file_a == file_path else pair.file_a@@ -567,46 +430,10 @@ def _pct_of_kept(return round(dup_pct * share, 2)-def _read_source_lines(abs_path: str, read_source: SourceReader) -> list[str] | None:- """Read a file's source as 1-indexed lines for the Extract Helper snippet.-- Failure-isolated: a read or decode error yields ``None`` (the detector then- omits the snippet and keeps its line ranges), never an exception into the- health pass. Decodes UTF-8 leniently since the snippet is for display, not- re-parsing.- """- raw = read_source(abs_path)- if raw is None:- return None- try:- text = raw.decode("utf-8", errors="replace")- except (UnicodeError, AttributeError):- return None- return text.splitlines()--#: Partner files whose lines one analysis pass keeps (``_repo_lines``)._PARTNER_LINES_CACHE = 256-def _clone_sources(- file_path: str,- own_lines: list[str],- clones: list[ClonePair],- read_lines: Callable[[str], list[str] | None],-) -> dict[str, list[str]]:- """This file's lines plus each clone partner's, for text-level checks."""- out = {file_path: own_lines}- for clone in clones:- for path in (clone.file_a, clone.file_b):- if path in out:- continue- lines = read_lines(path)- if lines is not None:- out[path] = lines- return out--def _percentile_p80(counts: list[int]) -> int | None:"""80th percentile of *counts* using the inclusive-lower conventionalready used by ``churn_percentile`` in ``enrich.compute_percentiles``.@@ -696,66 +523,6 @@ def _compute_repo_active_contributors(git_meta_map: dict[str, dict]) -> int | Noreturn None-@dataclass(frozen=True, slots=True)-class _RunConfig:- """The analyzer config one pass reads, with its per-file overrides."""-- vocab: AssertVocabulary- disabled: list[str]- per_file_disabled: dict[str, set[str]]- severity_overrides: dict[str, Severity]- per_file_severity_overrides: dict[str, dict[str, Severity]]- disabled_refactorings: list[str]- refactoring_enabled: bool- refactoring_min_confidence: str | None-- @classmethod- def read(cls, config: dict | None) -> _RunConfig:- cfg = config or {}- return cls(- vocab=AssertVocabulary.from_analyzer_config(cfg),- disabled=list(cfg.get("disabled_biomarkers", ())),- per_file_disabled=cfg.get("per_file_disabled", {}) or {},- severity_overrides=cfg.get("severity_overrides", {}) or {},- per_file_severity_overrides=cfg.get("per_file_severity_overrides", {}) or {},- disabled_refactorings=list(cfg.get("disabled_refactorings", ())),- refactoring_enabled=bool(cfg.get("refactoring_enabled", True)),- refactoring_min_confidence=cfg.get("refactoring_min_confidence"),- )-- @property- def performance_fix(self) -> bool:- return self.refactoring_enabled and "performance_fix" not in self.disabled_refactorings-- def file_disabled(self, path: str) -> list[str]:- out = list(self.disabled)- for name in self.per_file_disabled.get(path) or ():- if name not in out:- out.append(name)- return out-- def file_severity_overrides(self, path: str) -> dict[str, Severity] | None:- out = dict(self.severity_overrides)- out.update(self.per_file_severity_overrides.get(path, {}))- return out or None---@dataclass(frozen=True, slots=True)-class _RepoInputs:- """Repo-wide inputs every file's evaluation reads, built once per pass."""-- paired_tests: set[str]- package_roots: set[str]- graph_view: HasEdge | None- dup_report: DuplicationReport- function_mod_p80: int | None- dependents_p80: int | None- active_contributors: int | None- file_scc_index: dict[str, tuple[str, ...]]- methods_by_file: dict[str, tuple[str, ...]]- dataflow_cache: FileDataflowCache--class HealthAnalyzer:"""Pure-Python health analyzer. No LLM, no network."""@@ -1119,9 +886,9 @@ class HealthAnalyzer:dataflow_cache = FileDataflowCache(self.read_source)self.perf_stage.run(walked, dataflow_cache, timings)with timed(timings, "analysis.health.repo_stats"):- inputs = self._repo_inputs(dup_report, fn_mod_p80, dataflow_cache)+ evaluator = self._file_evaluator(run, dup_report, fn_mod_p80, dataflow_cache)with timed(timings, "analysis.health.evaluate"):- metrics, findings, suggestions = self._evaluate_all(run, walked, inputs, on_step)+ metrics, findings, suggestions = self._evaluate_all(evaluator, walked, on_step)# KPIs are repo-wide; on an incremental run they would be biased# by the changed-files subset. Skip them in that case — the# ``persist`` step recomputes KPIs from the merged DB rows.@@ -1149,26 +916,25 @@ class HealthAnalyzer:),)- def _repo_inputs(+ def _file_evaluator(self,+ run: _RunConfig,dup_report: DuplicationReport,fn_mod_p80: int | None,dataflow_cache: FileDataflowCache,- ) -> _RepoInputs:- # PageRank is optional — graph_builder.symbol_pagerank exists but- # is symbol-level; we use file-level in-degree as the dependents- # signal (cheap, deterministic, conservative).+ ) -> FileEvaluator:+ """The repo-wide inputs every file's evaluation reads, built once per pass."""analyzed_paths = {pf.file_info.path for pf in self.parsed_files}- return _RepoInputs(+ return FileEvaluator(+ self,paired_tests=self.test_index.paired(analyzed_paths),package_roots=self._package_boundaries(analyzed_paths),- graph_view=ImportEdgeView(self.graph) if self.graph is not None else None,dup_report=dup_report,+ run=run,+ graph_view=ImportEdgeView(self.graph) if self.graph is not None else None,function_mod_p80=fn_mod_p80,dependents_p80=_compute_repo_dependents_p80(self.file_dependents()),active_contributors=_compute_repo_active_contributors(self.git_meta_map),- # Repo-wide SCC index (import cycles), computed once so Break- # Cycle never recomputes it per file.file_scc_index=build_file_scc_index(self.graph),methods_by_file=build_methods_by_file(self.graph),dataflow_cache=dataflow_cache,@@ -1176,46 +942,24 @@ class HealthAnalyzer:def _evaluate_all(self,- run: _RunConfig,+ evaluator: FileEvaluator,walked: list[tuple[Any, FileComplexity]],- inputs: _RepoInputs,on_step: Any | None,) -> tuple[list[HealthFileMetricData], list[HealthFindingData], list[RefactoringSuggestion]]:metrics: list[HealthFileMetricData] = []findings: list[HealthFindingData] = []suggestions: list[RefactoringSuggestion] = []for pf, fcx in walked:- path = pf.file_info.path- # Side-effect: bump Symbol.complexity_estimate when we can- # match by enclosing line range. Symbols not matched keep- # their default (1).+ # Side effect: stamp each matched symbol's complexity_estimate.self._populate_symbol_complexity(pf, fcx.functions)- file_metric, file_findings, file_suggestions = self._evaluate_file(- pf,- fcx,- inputs.paired_tests,- inputs.package_roots,- disabled=run.file_disabled(path),- dup_report=inputs.dup_report,- graph_view=inputs.graph_view,- repo_function_mod_p80=inputs.function_mod_p80,- repo_dependents_p80=inputs.dependents_p80,- repo_active_contributors_90d=inputs.active_contributors,- severity_overrides=run.file_severity_overrides(path),- disabled_refactorings=run.disabled_refactorings,- refactoring_enabled=run.refactoring_enabled,- refactoring_min_confidence=run.refactoring_min_confidence,- file_scc_index=inputs.file_scc_index,- methods_by_file=inputs.methods_by_file,- dataflow_cache=inputs.dataflow_cache,- )+ file_metric, file_findings, file_suggestions = evaluator.evaluate(pf, fcx)# Every dataflow consumer has read this file by now.- inputs.dataflow_cache.release(pf.file_info.abs_path)+ evaluator.dataflow_cache.release(pf.file_info.abs_path)metrics.append(file_metric)findings.extend(file_findings)suggestions.extend(file_suggestions)if on_step:- on_step(path)+ on_step(pf.file_info.path)return metrics, findings, suggestionsdef _kpis(@@ -1463,28 +1207,6 @@ class HealthAnalyzer:misses=self._walk_cache.misses,)- def _extract_method_analyses(- self,- pf: Any,- findings: list[HealthFindingData],- dataflow_cache: FileDataflowCache | None = None,- ) -> list[Any]:- """Dataflow analyses for the Extract Method detector, gated to files- that already carry a method-level smell.-- Building a CFG + def/use + reaching definitions is only useful where a- ``large_method`` / ``brain_method`` / ``complex_method`` finding fired,- so the dataflow pass runs for that small subset of files only --- everything else pays nothing. The shared *dataflow_cache* means a file- the promotion pass already analyzed is not parsed again here. Degrades- to ``[]`` on any read or analysis failure; the detector then yields no- suggestion.- """- if not any(getattr(f, "biomarker_type", "") in _EXTRACT_METHOD_SOURCES for f in findings):- return []- cache = dataflow_cache if dataflow_cache is not None else FileDataflowCache(self.read_source)- return cache.get(pf.file_info.abs_path, pf.file_info.language).flagged_analyses()-def _populate_symbol_complexity(self, pf: Any, fc_list: list[FunctionComplexity]) -> None:if not fc_list:return@@ -1498,191 +1220,6 @@ class HealthAnalyzer:# Cap at the ORM Integer; CCN beyond ~10k is implausible.sym.complexity_estimate = int(min(fc.ccn, 9999))- def _evaluate_file(- self,- pf: Any,- fcx: FileComplexity,- paired_tests: set[str],- package_roots: set[str],- *,- disabled: list[str],- dup_report: DuplicationReport,- graph_view: HasEdge | None = None,- repo_function_mod_p80: int | None = None,- repo_dependents_p80: int | None = None,- 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,- methods_by_file: dict[str, tuple[str, ...]] | None = None,- dataflow_cache: FileDataflowCache | None = None,- ) -> tuple[HealthFileMetricData, list[HealthFindingData], list[RefactoringSuggestion]]:- file_path = pf.file_info.path-- fc_list = fcx.functions- fns = walked_functions(fc_list, pf.file_info.language)- max_ccn = max((fc.ccn for fc in fc_list), default=1)- max_nesting = max((fc.max_nesting for fc in fc_list), default=0)- nloc = fcx.file_nloc-- dependents_count = self._dependents(file_path)-- cov = self.coverage_map.get(file_path)- if cov is None:- cov = self.coverage_map.get(file_path.replace("\\", "/"))- line_cov = cov.get("line_coverage_pct") if cov else None- branch_cov = cov.get("branch_coverage_pct") if cov else None- covered_lines: set[int] = set(cov.get("covered_lines") or ()) if cov else set()- total_coverable_lines = int(cov.get("total_coverable_lines", 0)) if cov else 0-- clones, dup_pct = self._without_kit_clones(- file_path,- dup_report.pairs_by_file.get(file_path, []),- dup_report.duplication_pct.get(file_path),- )- # Read only for clone-bearing files, keeping the read proportional.- source_lines = (- _read_source_lines(pf.file_info.abs_path, self.read_source) if clones else None- )- clone_sources = (- _clone_sources(file_path, source_lines, clones, self._repo_lines)- if source_lines is not None and pf.file_info.is_test- else {}- )-- # The enclosing package root, falling back to the top-level directory- # when the repo has no nested packages.- module = _module_for(file_path, package_roots)-- file_git_meta = self.git_meta_map.get(file_path, {}) or {}- blame_idx_obj = file_git_meta.get("blame_index")- blame_index = blame_idx_obj if isinstance(blame_idx_obj, BlameIndex) else None-- ctx = FileContext(- file_path=file_path,- language=pf.file_info.language,- nloc=nloc,- # ``pf.file_info.is_test`` is the decision ingestion already made- # for this file, with its language and pytest config in hand; read- # it rather than re-derive from the path string (#1103).- has_test_file=file_path in paired_tests- or pf.file_info.is_test- or fcx.has_inline_tests,- is_test=bool(pf.file_info.is_test),- # Kept separate from ``has_test_file`` on purpose. That flag means- # "a test imports this file, or is named for it"; this one means "the- # call graph records a test reaching this file". They disagree- # often, and collapsing them would leave no way to say which signal- # answered, or that one of them over-claims.- reached_by_tests=file_path in self.test_index.reached_files(),- module=module,- all_functions=fns,- class_metrics=fcx.classes,- git_meta=file_git_meta,- dependents_count=dependents_count,- repo_dependents_p80=repo_dependents_p80,- pagerank_score=0.0,- line_coverage_pct=line_cov,- branch_coverage_pct=branch_cov,- covered_lines=covered_lines,- total_coverable_lines=total_coverable_lines,- clones=list(clones),- duplication_pct=dup_pct,- clone_sources=clone_sources,- graph_view=graph_view,- blame_index=blame_index,- repo_function_mod_p80=repo_function_mod_p80,- repo_active_contributors_90d=repo_active_contributors_90d,- error_handling_hits=fcx.error_handling_hits,- perf_hits=fcx.perf_hits,- io_boundary_names=set(fcx.io_boundary_names),- cross_file_oracle_lines=frozenset(getattr(fcx, "cross_file_oracles", ())),- )-- biomarker_results = detect_all(ctx, disabled=disabled)- if blame_index is None:- for stored in self.stored_blame_findings.get(file_path, ()):- replayed = as_biomarker_result(stored)- if replayed.biomarker_type not in BLAME_MARKERS or replayed.biomarker_type in disabled:- continue- if replayed.biomarker_type == "function_hotspot" and not refresh_replayed(replayed, fns):- continue- biomarker_results.append(replayed)- biomarker_results = remap_severities(biomarker_results, severity_overrides)- scores, deductions = score_file(biomarker_results)- findings = attach_impacts(biomarker_results, deductions)- for f in findings:- f.file_path = file_path- _mark_function_facts(findings, fc_list)- _stamp_symbol_lines(findings, fcx)- _mark_deepest_block(findings, fc_list)-- # The overall surfaced score stays == the defect dimension (no blend- # yet); the per-dimension scores ride alongside it, additively. A- # language with no dialect stores none of them, and no complexity- # figures either: nothing walked the file.- analysed = has_health_dialect(pf.file_info.language)- metric = HealthFileMetricData(- file_path=file_path,- max_ccn=max_ccn if analysed else None,- max_nesting=max_nesting if analysed else None,- nloc=nloc,- # The stored field answers "does something test this file" - that is- # how the MCP payload documents it and how every UI renders it- # ("has tests" / "untested"). So it carries the union, not just the- # naming convention. Keeping it filename-only left the file table- # labelling a file untested while ``untested_hotspot`` stayed- # silent about it, which is the same disagreement issue #1740 is- # about, one layer further out. The two inputs stay separable on- # ``FileContext`` and in the biomarker's ``details``.- has_test_file=ctx.has_test_file or ctx.reached_by_tests,- module=module,- line_coverage_pct=line_cov,- branch_coverage_pct=branch_cov,- duplication_pct=dup_pct,- **file_score_fields(analysed, scores, findings),- is_test=bool(pf.file_info.is_test),- code_origin=self._origins.get(file_path) or self._origin(pf),- )-- # 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 build) for this file.- if not refactoring_enabled:- return metric, findings, []- rctx = RefactoringContext(- file_path=file_path,- language=pf.file_info.language,- nloc=nloc,- classes=fcx.classes,- findings=findings,- dependents_count=dependents_count,- clones=list(clones),- community_label_map=self.community_label_map,- graph=self.graph,- file_scc=(file_scc_index or {}).get(file_path),- file_methods=(- methods_by_file.get(file_path, ()) if methods_by_file is not None else None- ),- function_analyses=self._extract_method_analyses(pf, findings, dataflow_cache),- # Stored sets when no blame index, so a re-score matches the index.- commit_spans=commit_spans(fcx.functions, _commit_entries(fcx, file_git_meta)),- # The Extract Helper snippet; ``None`` unless the file carries clones.- source_lines=source_lines,- # Clone partners' lines, read only when one site may be a whole function.- read_lines=self._repo_lines,- )- suggestions = detect_refactorings(- rctx,- disabled=disabled_refactorings or (),- min_confidence=refactoring_min_confidence,- )- return metric, findings, suggestions-def _read_repo_lines(self, path: str) -> list[str] | None:"""*path*'s lines: the parsed file's own path, else under the repo root(an update's parsed set is the whole tree, but a caller may pass less)."""diff --git a/packages/core/src/repowise/core/analysis/health/file_evaluator.py b/packages/core/src/repowise/core/analysis/health/file_evaluator.pynew file mode 100644index 000000000..6d2200eea--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/file_evaluator.py@@ -0,0 +1,410 @@+"""Scores one walked file: biomarkers, findings, the file metric and its refactorings."""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass, field+from typing import TYPE_CHECKING, Any++from ...ingestion.git_indexer.function_blame import BlameIndex+from ...ingestion.package_roots import module_for as _module_for+from ..graph_view import HasEdge+from .asserts.lexicon import AssertVocabulary+from .biomarkers import FileContext, detect_all+from .biomarkers.base import BiomarkerResult+from .biomarkers.function_hotspot import refresh_replayed+from .complexity import FileComplexity, FunctionComplexity+from .complexity.languages import has_health_dialect+from .dataflow import FileDataflowCache+from .duplication import ClonePair, DuplicationReport+from .finding_identity import SYMBOL_INDEX_KEY, SYMBOL_KEY, SYMBOL_LINE_KEY+from .function_blame_rollup import blame_commit_entries, commit_spans+from .history_refresh import BLAME_MARKERS, as_biomarker_result+from .models import HealthFileMetricData, HealthFindingData, Severity+from .refactoring import RefactoringContext, RefactoringSuggestion, detect_refactorings+from .scoring import attach_impacts, file_score_fields, remap_severities, score_file+from .source_reader import SourceReader++if TYPE_CHECKING:+ from .engine import HealthAnalyzer++#: Function facts a finding inside the function carries in its details.+_FUNCTION_FACTS = ("deprecated", "gated_off")+++def _mark_function_facts(+ findings: list[HealthFindingData], functions: list[FunctionComplexity]+) -> None:+ """Stamp ``deprecated`` / ``gated_off`` on findings inside such a function; absent elsewhere."""+ spans = [+ (fact, fc.name, fc.start_line, fc.end_line)+ for fc in functions+ for fact in _FUNCTION_FACTS+ if getattr(fc, fact, False)+ ]+ for finding in findings:+ if finding.function_name is None:+ continue+ line = finding.line_start+ for fact, name, start, end in spans:+ if name == finding.function_name and (line is None or start <= line <= end):+ finding.details[fact] = True+++#: Function-size findings whose fix starts at the deepest nested block.+_DEEPEST_BLOCK_MARKERS = frozenset(+ {"complex_method", "nested_complexity", "brain_method", "large_method", "bumpy_road"}+)+++def _mark_deepest_block(+ findings: list[HealthFindingData], functions: list[FunctionComplexity]+) -> None:+ """Copy the function's deepest nested block onto its size findings as ``deepest_block``."""+ blocks = {+ (fc.name, fc.start_line): fc.deepest_block+ for fc in functions+ if fc.deepest_block+ }+ if not blocks:+ return+ for finding in findings:+ if finding.biomarker_type not in _DEEPEST_BLOCK_MARKERS:+ continue+ block = blocks.get((finding.function_name, finding.line_start))+ if block:+ finding.details["deepest_block"] = {"start": block[0], "end": block[1]}+++def walked_functions(+ fc_list: list[FunctionComplexity], language: str+) -> tuple[FunctionComplexity, ...]:+ """The functions a file's biomarkers see, in document order (stable sort).++ SQL is held back: its text-counted metrics are not calibrated for the method markers.+ """+ if language == "sql":+ return ()+ return tuple(sorted(fc_list, key=lambda fc: (fc.start_line, fc.end_line)))+++def _stamp_symbol_lines(findings: list[HealthFindingData], fcx: FileComplexity) -> None:+ """Anchor each finding on its innermost enclosing symbol, so edits above it keep the id.++ ``symbol_index`` separates same-named symbols; a replayed finding keeps its anchor.+ """+ spans = sorted(+ [(fc.start_line, fc.end_line, fc.name) for fc in fcx.functions]+ + [(c.start_line, c.end_line, c.name) for c in fcx.classes]+ )+ for f in findings:+ if f.line_start is None or SYMBOL_LINE_KEY in f.details:+ continue+ holding = [+ span+ for span in spans+ if span[0] <= f.line_start <= span[1]+ and (not f.function_name or span[2] == f.function_name)+ ]+ if not holding:+ continue+ start, _, name = max(holding, key=lambda span: (span[0], -span[1]))+ stamp: dict = {SYMBOL_LINE_KEY: start}+ if not f.function_name:+ stamp[SYMBOL_KEY] = name+ index = sum(1 for span in spans if span[2] == name and span[0] < start)+ if index:+ stamp[SYMBOL_INDEX_KEY] = index+ f.details = {**f.details, **stamp}+++#: Method-level smells that earn a file the dataflow pass for Extract Method.+_EXTRACT_METHOD_SOURCES = frozenset({"large_method", "brain_method", "complex_method"})+++def _commit_entries(fcx: FileComplexity, git_meta: dict) -> list:+ """Per-function commit sets: from the blame index, else the stored rows."""+ idx = git_meta.get("blame_index") or git_meta.get("commit_set_blame")+ if isinstance(idx, BlameIndex):+ return blame_commit_entries(fcx.functions, idx)+ return list(git_meta.get("function_commit_shas") or ())+++def _read_source_lines(abs_path: str, read_source: SourceReader) -> list[str] | None:+ """A file's lines for display, or ``None`` on any read or decode failure."""+ raw = read_source(abs_path)+ if raw is None:+ return None+ try:+ text = raw.decode("utf-8", errors="replace")+ except (UnicodeError, AttributeError):+ return None+ return text.splitlines()+++def _clone_sources(+ file_path: str,+ own_lines: list[str],+ clones: list[ClonePair],+ read_lines: Callable[[str], list[str] | None],+) -> dict[str, list[str]]:+ """This file's lines plus each clone partner's, for text-level checks."""+ out = {file_path: own_lines}+ for clone in clones:+ for path in (clone.file_a, clone.file_b):+ if path in out:+ continue+ lines = read_lines(path)+ if lines is not None:+ out[path] = lines+ return out+++@dataclass(frozen=True, slots=True)+class _RunConfig:+ """The analyzer config one pass reads, with its per-file overrides."""++ vocab: AssertVocabulary+ disabled: list[str]+ per_file_disabled: dict[str, set[str]]+ severity_overrides: dict[str, Severity]+ per_file_severity_overrides: dict[str, dict[str, Severity]]+ disabled_refactorings: list[str]+ refactoring_enabled: bool+ refactoring_min_confidence: str | None++ @classmethod+ def read(cls, config: dict | None) -> _RunConfig:+ cfg = config or {}+ return cls(+ vocab=AssertVocabulary.from_analyzer_config(cfg),+ disabled=list(cfg.get("disabled_biomarkers", ())),+ per_file_disabled=cfg.get("per_file_disabled", {}) or {},+ severity_overrides=cfg.get("severity_overrides", {}) or {},+ per_file_severity_overrides=cfg.get("per_file_severity_overrides", {}) or {},+ disabled_refactorings=list(cfg.get("disabled_refactorings", ())),+ refactoring_enabled=bool(cfg.get("refactoring_enabled", True)),+ refactoring_min_confidence=cfg.get("refactoring_min_confidence"),+ )++ @property+ def performance_fix(self) -> bool:+ return self.refactoring_enabled and "performance_fix" not in self.disabled_refactorings++ def file_disabled(self, path: str) -> list[str]:+ out = list(self.disabled)+ for name in self.per_file_disabled.get(path) or ():+ if name not in out:+ out.append(name)+ return out++ def file_severity_overrides(self, path: str) -> dict[str, Severity] | None:+ out = dict(self.severity_overrides)+ out.update(self.per_file_severity_overrides.get(path, {}))+ return out or None+++@dataclass(frozen=True, slots=True)+class FileEvaluator:+ """Evaluates each walked file against one pass's repo-wide inputs; later fields are optional."""++ analyzer: HealthAnalyzer+ paired_tests: set[str]+ package_roots: set[str]+ dup_report: DuplicationReport+ run: _RunConfig = field(default_factory=lambda: _RunConfig.read(None))+ graph_view: HasEdge | None = None+ function_mod_p80: int | None = None+ dependents_p80: int | None = None+ active_contributors: int | None = None+ file_scc_index: dict[str, tuple[str, ...]] | None = None+ methods_by_file: dict[str, tuple[str, ...]] | None = None+ dataflow_cache: FileDataflowCache | None = None++ def evaluate(+ self, pf: Any, fcx: FileComplexity+ ) -> tuple[HealthFileMetricData, list[HealthFindingData], list[RefactoringSuggestion]]:+ file_path = pf.file_info.path+ clones, dup_pct = self.analyzer._without_kit_clones(+ file_path,+ self.dup_report.pairs_by_file.get(file_path, []),+ self.dup_report.duplication_pct.get(file_path),+ )+ source_lines = (+ _read_source_lines(pf.file_info.abs_path, self.analyzer.read_source)+ if clones+ else None+ )+ ctx = self._context(pf, fcx, clones, dup_pct, source_lines)+ findings, scores = self._findings(ctx, fcx)+ metric = self._metric(pf, fcx, ctx, scores, findings)++ if not self.run.refactoring_enabled:+ return metric, findings, []+ return metric, findings, self._suggestions(pf, fcx, ctx, findings, source_lines)++ def _context(+ self,+ pf: Any,+ fcx: FileComplexity,+ clones: list[ClonePair],+ dup_pct: float | None,+ source_lines: list[str] | None,+ ) -> FileContext:+ """The biomarkers' view of the file."""+ analyzer = self.analyzer+ file_path = pf.file_info.path+ cov = analyzer.coverage_map.get(file_path)+ if cov is None:+ cov = analyzer.coverage_map.get(file_path.replace("\\", "/"))+ clone_sources = (+ _clone_sources(file_path, source_lines, clones, analyzer._repo_lines)+ if source_lines is not None and pf.file_info.is_test+ else {}+ )+ file_git_meta = analyzer.git_meta_map.get(file_path, {}) or {}+ blame_idx_obj = file_git_meta.get("blame_index")+ return FileContext(+ file_path=file_path,+ language=pf.file_info.language,+ nloc=fcx.file_nloc,+ # Ingestion's own test decision, not one re-derived from the path.+ has_test_file=file_path in self.paired_tests+ or pf.file_info.is_test+ or fcx.has_inline_tests,+ is_test=bool(pf.file_info.is_test),+ # Separate from has_test_file (import or name pairing) so each signal stays visible.+ reached_by_tests=file_path in analyzer.test_index.reached_files(),+ module=_module_for(file_path, self.package_roots),+ all_functions=walked_functions(fcx.functions, pf.file_info.language),+ class_metrics=fcx.classes,+ git_meta=file_git_meta,+ dependents_count=analyzer._dependents(file_path),+ repo_dependents_p80=self.dependents_p80,+ pagerank_score=0.0,+ line_coverage_pct=cov.get("line_coverage_pct") if cov else None,+ branch_coverage_pct=cov.get("branch_coverage_pct") if cov else None,+ covered_lines=set(cov.get("covered_lines") or ()) if cov else set(),+ total_coverable_lines=int(cov.get("total_coverable_lines", 0)) if cov else 0,+ clones=list(clones),+ duplication_pct=dup_pct,+ clone_sources=clone_sources,+ graph_view=self.graph_view,+ blame_index=blame_idx_obj if isinstance(blame_idx_obj, BlameIndex) else None,+ repo_function_mod_p80=self.function_mod_p80,+ repo_active_contributors_90d=self.active_contributors,+ error_handling_hits=fcx.error_handling_hits,+ perf_hits=fcx.perf_hits,+ io_boundary_names=set(fcx.io_boundary_names),+ cross_file_oracle_lines=frozenset(getattr(fcx, "cross_file_oracles", ())),+ )++ def _findings(+ self, ctx: FileContext, fcx: FileComplexity+ ) -> tuple[list[HealthFindingData], dict[str, float | None]]:+ """Run the biomarkers, score the file and stamp each finding's anchors."""+ file_path = ctx.file_path+ disabled = self.run.file_disabled(file_path)+ biomarker_results = detect_all(ctx, disabled=disabled)+ if ctx.blame_index is None:+ biomarker_results.extend(self._replayed(ctx, disabled))+ biomarker_results = remap_severities(+ biomarker_results, self.run.file_severity_overrides(file_path)+ )+ scores, deductions = score_file(biomarker_results)+ findings = attach_impacts(biomarker_results, deductions)+ for f in findings:+ f.file_path = file_path+ _mark_function_facts(findings, fcx.functions)+ _stamp_symbol_lines(findings, fcx)+ _mark_deepest_block(findings, fcx.functions)+ return findings, scores++ def _replayed(self, ctx: FileContext, disabled: list[str]) -> list[BiomarkerResult]:+ """Stored blame-marker findings this pass cannot recompute without a blame index."""+ out = []+ for stored in self.analyzer.stored_blame_findings.get(ctx.file_path, ()):+ replayed = as_biomarker_result(stored)+ if replayed.biomarker_type not in BLAME_MARKERS or replayed.biomarker_type in disabled:+ continue+ if replayed.biomarker_type == "function_hotspot" and not refresh_replayed(+ replayed, ctx.all_functions+ ):+ continue+ out.append(replayed)+ return out++ def _metric(+ self,+ pf: Any,+ fcx: FileComplexity,+ ctx: FileContext,+ scores: dict[str, float | None],+ findings: list[HealthFindingData],+ ) -> HealthFileMetricData:+ # A language with no dialect stores no scores and no complexity figures.+ analysed = has_health_dialect(pf.file_info.language)+ fc_list = fcx.functions+ return HealthFileMetricData(+ file_path=ctx.file_path,+ max_ccn=max((fc.ccn for fc in fc_list), default=1) if analysed else None,+ max_nesting=max((fc.max_nesting for fc in fc_list), default=0) if analysed else None,+ nloc=fcx.file_nloc,+ # "Does something test this file": the union of pairing and graph reach.+ has_test_file=ctx.has_test_file or ctx.reached_by_tests,+ module=ctx.module,+ line_coverage_pct=ctx.line_coverage_pct,+ branch_coverage_pct=ctx.branch_coverage_pct,+ duplication_pct=ctx.duplication_pct,+ **file_score_fields(analysed, scores, findings),+ is_test=bool(pf.file_info.is_test),+ code_origin=self.analyzer._origins.get(ctx.file_path) or self.analyzer._origin(pf),+ )++ def _suggestions(+ self,+ pf: Any,+ fcx: FileComplexity,+ ctx: FileContext,+ findings: list[HealthFindingData],+ source_lines: list[str] | None,+ ) -> list[RefactoringSuggestion]:+ file_path = ctx.file_path+ analyzer = self.analyzer+ rctx = RefactoringContext(+ file_path=file_path,+ language=pf.file_info.language,+ nloc=fcx.file_nloc,+ classes=fcx.classes,+ findings=findings,+ dependents_count=ctx.dependents_count,+ clones=list(ctx.clones),+ community_label_map=analyzer.community_label_map,+ graph=analyzer.graph,+ file_scc=(self.file_scc_index or {}).get(file_path),+ file_methods=(+ self.methods_by_file.get(file_path, ())+ if self.methods_by_file is not None+ else None+ ),+ function_analyses=self._extract_method_analyses(pf, findings),+ commit_spans=commit_spans(fcx.functions, _commit_entries(fcx, ctx.git_meta)),+ source_lines=source_lines,+ read_lines=analyzer._repo_lines,+ )+ return detect_refactorings(+ rctx,+ disabled=self.run.disabled_refactorings or (),+ min_confidence=self.run.refactoring_min_confidence,+ )++ def _extract_method_analyses(self, pf: Any, findings: list[HealthFindingData]) -> list[Any]:+ """Dataflow analyses for Extract Method, built only for files with a method-level smell."""+ if not any(getattr(f, "biomarker_type", "") in _EXTRACT_METHOD_SOURCES for f in findings):+ return []+ cache = (+ self.dataflow_cache+ if self.dataflow_cache is not None+ else FileDataflowCache(self.analyzer.read_source)+ )+ return cache.get(pf.file_info.abs_path, pf.file_info.language).flagged_analyses()diff --git a/tests/unit/health/test_deepest_block.py b/tests/unit/health/test_deepest_block.pyindex b47020e1e..6061fd6d1 100644--- a/tests/unit/health/test_deepest_block.py+++ b/tests/unit/health/test_deepest_block.py@@ -15,6 +15,7 @@ import pytestfrom repowise.core.analysis.health.complexity import walk_filefrom repowise.core.analysis.health.duplication import DuplicationReportfrom repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.file_evaluator import FileEvaluatorfrom repowise.core.analysis.health.finding_identity import finding_public_idfrom repowise.core.analysis.health.models import HealthFindingData, Severity@@ -79,14 +80,12 @@ def test_size_findings_carry_it_and_keep_their_id() -> None:),symbols=[],)- _, findings, _ = HealthAnalyzer(graph=None)._evaluate_file(- pf,- fcx,+ _, findings, _ = FileEvaluator(+ HealthAnalyzer(graph=None),paired_tests=set(),package_roots=set(),- disabled=[],dup_report=DuplicationReport(),- )+ ).evaluate(pf, fcx)nested = next(f for f in findings if f.biomarker_type == "nested_complexity")assert nested.details["deepest_block"] == {"start": 10, "end": 13}without = HealthFindingData(diff --git a/tests/unit/health/test_dispatch_and_deprecation.py b/tests/unit/health/test_dispatch_and_deprecation.pyindex a6e72f965..d641673fe 100644--- a/tests/unit/health/test_dispatch_and_deprecation.py+++ b/tests/unit/health/test_dispatch_and_deprecation.py@@ -18,6 +18,7 @@ from repowise.core.analysis.health.complexity import walk_filefrom repowise.core.analysis.health.complexity.dispatch import judged_ccn, judged_nestingfrom repowise.core.analysis.health.duplication import DuplicationReportfrom repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.file_evaluator import FileEvaluatorfrom repowise.core.analysis.health.finding_identity import finding_public_idfrom repowise.core.analysis.health.models import HealthFindingData, Severity@@ -452,14 +453,12 @@ def _evaluate(path: str):),symbols=[],)- return HealthAnalyzer(graph=None)._evaluate_file(- pf,- fcx,+ return FileEvaluator(+ HealthAnalyzer(graph=None),paired_tests=set(),package_roots=set(),- disabled=[],dup_report=DuplicationReport(),- )+ ).evaluate(pf, fcx)def test_complexity_findings_carry_dispatch_share_and_deprecated() -> None:diff --git a/tests/unit/health/test_file_nloc.py b/tests/unit/health/test_file_nloc.pyindex 7cc8306ea..3b0b68814 100644--- a/tests/unit/health/test_file_nloc.py+++ b/tests/unit/health/test_file_nloc.py@@ -9,6 +9,7 @@ from repowise.core.analysis.health.complexity import walk_filefrom repowise.core.analysis.health.complexity.walker import _count_file_nlocfrom repowise.core.analysis.health.duplication import DuplicationReportfrom repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.file_evaluator import FileEvaluatorfrom repowise.core.analysis.health.models import HealthFileMetricDataFIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lang_samples"@@ -87,14 +88,12 @@ def test_health_metric_nloc_uses_file_nloc():),symbols=[],)- metric, _, _ = HealthAnalyzer(graph=None)._evaluate_file(- pf,- fcx,+ metric, _, _ = FileEvaluator(+ HealthAnalyzer(graph=None),paired_tests=set(),package_roots=set(),- disabled=[],dup_report=DuplicationReport(),- )+ ).evaluate(pf, fcx)assert isinstance(metric, HealthFileMetricData)assert metric.nloc == fcx.file_nlocdiff --git a/tests/unit/health/test_finding_identity.py b/tests/unit/health/test_finding_identity.pyindex df2d5d94d..8e26029e8 100644--- a/tests/unit/health/test_finding_identity.py+++ b/tests/unit/health/test_finding_identity.py@@ -15,6 +15,7 @@ import pytestfrom repowise.core.analysis.health.complexity import walk_filefrom repowise.core.analysis.health.duplication import DuplicationReportfrom repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.file_evaluator import FileEvaluatorfrom repowise.core.analysis.health.finding_identity import (IDENTITY_DETAIL_KEYS,SYMBOL_INDEX_KEY,@@ -63,9 +64,12 @@ def _findings(source: str):),symbols=[],)- _, findings, _ = HealthAnalyzer(graph=None)._evaluate_file(- pf, fcx, paired_tests=set(), package_roots=set(), disabled=[], dup_report=DuplicationReport()- )+ _, findings, _ = FileEvaluator(+ HealthAnalyzer(graph=None),+ paired_tests=set(),+ package_roots=set(),+ dup_report=DuplicationReport(),+ ).evaluate(pf, fcx)return findingsdiff --git a/tests/unit/health/test_incremental_p80_override.py b/tests/unit/health/test_incremental_p80_override.pyindex d40dfd1fa..7d0ed7523 100644--- a/tests/unit/health/test_incremental_p80_override.py+++ b/tests/unit/health/test_incremental_p80_override.py@@ -30,17 +30,17 @@ def _parsed_file(path: str) -> SimpleNamespace:class _CaptureEvaluator(HealthAnalyzer):- """Engine whose ``_evaluate_file`` records the p80 override instead of+ """Engine that records the p80 each file is evaluated with instead ofdoing real biomarker work."""def __init__(self, *args, **kwargs) -> None:super().__init__(*args, **kwargs)self.captured_p80s: list[int | None] = []- def _evaluate_file(self, *args, **kwargs):- self.captured_p80s.append(kwargs.get("repo_function_mod_p80"))- pf = args[0]- return SimpleNamespace(file_path=pf.file_info.path, nloc=0, score=10.0), [], []+ def _evaluate_all(self, evaluator, walked, on_step):+ self.captured_p80s.extend(evaluator.function_mod_p80 for _ in walked)+ metrics = [SimpleNamespace(file_path=pf.file_info.path, nloc=0, score=10.0) for pf, _ in walked]+ return metrics, [], []def test_incremental_analyze_uses_override_not_walked_subset():diff --git a/tests/unit/health/test_severity_overrides_integration.py b/tests/unit/health/test_severity_overrides_integration.pyindex 425580edb..6ec2e3705 100644--- a/tests/unit/health/test_severity_overrides_integration.py+++ b/tests/unit/health/test_severity_overrides_integration.py@@ -1,7 +1,7 @@"""End-to-end: ``severity_overrides`` flows config -> engine -> score.Proves the wiring between ``HealthConfig.to_analyzer_config`` and the engine's-per-file remap (``_evaluate_file(severity_overrides=...)``), not just the two+per-file remap (``FileEvaluator.evaluate``), not just the twoends in isolation."""@@ -14,6 +14,7 @@ import pytestfrom repowise.core.analysis.health.complexity import walk_filefrom repowise.core.analysis.health.duplication import DuplicationReportfrom repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.file_evaluator import FileEvaluator, _RunConfigfrom repowise.core.analysis.health.models import Severity# A single high-CCN function: many independent branches drive ccn >= 9, which@@ -57,15 +58,13 @@ def _evaluate(severity_overrides):),symbols=[],)- metric, findings, _ = HealthAnalyzer(graph=None)._evaluate_file(- pf,- fcx,+ metric, findings, _ = FileEvaluator(+ HealthAnalyzer(graph=None),paired_tests=set(),package_roots=set(),- disabled=[],dup_report=DuplicationReport(),- severity_overrides=severity_overrides,- )+ run=_RunConfig.read({"severity_overrides": severity_overrides or {}}),+ ).evaluate(pf, fcx)return metric, findingsdiff --git a/tests/unit/health/test_unanalysed_languages.py b/tests/unit/health/test_unanalysed_languages.pyindex 8ec3a97bd..bea8ecc6d 100644--- a/tests/unit/health/test_unanalysed_languages.py+++ b/tests/unit/health/test_unanalysed_languages.py@@ -14,6 +14,7 @@ from repowise.core.analysis.health.complexity import FileComplexity, walk_filefrom repowise.core.analysis.health.complexity.languages import has_health_dialectfrom repowise.core.analysis.health.duplication import DuplicationReportfrom repowise.core.analysis.health.engine import HealthAnalyzer+from repowise.core.analysis.health.file_evaluator import FileEvaluatorfrom repowise.core.analysis.health.grading import band_for, distribution, headline_bandfrom repowise.core.analysis.health.models import HealthFileMetricDatafrom repowise.core.analysis.health.ranking import worst_metric@@ -62,9 +63,12 @@ def _evaluate(path: str, language: str, source: bytes, tmp_path) -> HealthFileMe),symbols=[],)- metric, _, _ = HealthAnalyzer(graph=None)._evaluate_file(- pf, fcx, paired_tests=set(), package_roots=set(), disabled=[], dup_report=DuplicationReport()- )+ metric, _, _ = FileEvaluator(+ HealthAnalyzer(graph=None),+ paired_tests=set(),+ package_roots=set(),+ dup_report=DuplicationReport(),+ ).evaluate(pf, fcx)return metric