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): share one dataflow parse per file across consumers (#755)

Raghav Chamadiya3c1d9008d56f
diff --git a/README.md b/README.md
index a7145c561..a17a74e50 100644
--- a/README.md
+++ b/README.md
@@ -89,7 +89,7 @@ Each layer is queryable from the CLI, the MCP tools, and the local dashboard.
| **◈ Git** | hotspots (churn × complexity) · ownership % · co-change pairs (hidden coupling) · bus factor · contributor profiles · module health · reviewer suggestions | Behavioral signals static analysis can't see |
| **◈ Docs** | LLM-generated wiki per module/file · incremental on every commit · freshness + confidence scoring · hybrid RAG search (FTS + vector via RRF) · selectable wiki styles (comprehensive / reference / tutorial / caveman) | Stays current, rebuilt every commit |
| **◈ Decisions** | architectural decisions mined from **8 sources**, evidence-backed (verified / fuzzy / unverified), linked to graph nodes, connected by `supersedes`/`refines`/`conflicts_with` edges, tracked for staleness | **★ Captured nowhere else** |
-| **★ Code Health** | **25 deterministic markers**, 1–10 per file · **three signals: defect risk · maintainability · performance** · coverage ingestion · trend alerts · **concrete graph-aware refactoring plans** (Extract Class / Helper / Move Method / Break Cycle / Split File) · **zero LLM, <30s** | **★ Defect-validated, with the fix attached. Our edge** |
+| **★ Code Health** | **25 deterministic markers**, 1–10 per file · **three signals: defect risk · maintainability · performance** · coverage ingestion · trend alerts · **concrete graph-aware refactoring plans** (Extract Class / Helper / Move Method / Break Cycle / Split File / Extract Method) · **zero LLM, <30s** | **★ Defect-validated, with the fix attached. Our edge** |
Full deep-dive on every layer (graph, git, docs, decisions, hooks, auto-sync,
dead code, CLAUDE.md generation): **[docs/INTELLIGENCE_LAYERS.md →](docs/INTELLIGENCE_LAYERS.md)**
@@ -105,7 +105,7 @@ concentrates through the graph and git history, then **fix** it with a concrete
refactoring plan your agent can execute.
<div align="center">
-<img src=".github/assets/health-loop.svg" alt="repowise code-health loop: 25 deterministic markers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Move Method, Break Cycle, Split File) your agent executes" width="100%" />
+<img src=".github/assets/health-loop.svg" alt="repowise code-health loop: 25 deterministic markers fan into three signals (defect risk, maintainability, performance), the graph and git history locate where risk concentrates, and refactoring intelligence emits concrete plans (Extract Class, Extract Helper, Move Method, Break Cycle, Split File, Extract Method) your agent executes" width="100%" />
</div>
repowise scores **every file 1–10** from **25 deterministic markers**:
@@ -167,13 +167,17 @@ A health score tells you a file is in trouble. Every other tool stops there, or
prints the same static sentence for every god class in every repo. repowise names
the **specific** fix, computed deterministically from the graph, the class model,
and git co-change: **Extract Class**, **Extract Helper**, **Move Method**,
-**Break Cycle**, and **Split File**. Each plan names the exact methods, edges, or
-symbols that move, and carries its **blast radius** (the callers and co-changing
-files that must move with it). Ranking is **graph-aware** (`impact × call-graph
-centrality × blast radius`), so a fix on a central hub outranks the same fix on a
-leaf. That is the wedge: CodeScene's AI refactoring stays within a single
-function, where repowise names the cross-file move and the dependents it ripples
-to.
+**Break Cycle**, **Split File**, and **Extract Method**. Each plan names the
+exact methods, edges, or symbols that move, and carries its **blast radius**
+(the callers and co-changing files that must move with it). Extract Method goes
+deepest: an intra-procedural dataflow pass (CFG + def/use + reaching
+definitions) finds the exact line span to lift out of an oversized method and
+infers the helper's parameters and return value, so the plan is
+behavior-preserving by construction. Ranking is **graph-aware** (`impact ×
+call-graph centrality × blast radius`), so a fix on a central hub outranks the
+same fix on a leaf. That is the wedge: CodeScene's AI refactoring stays within a
+single function, where repowise names the cross-file move and the dependents it
+ripples to.
The deterministic plan is the product; an optional LLM step (never in the
indexing path, only on explicit request) expands any plan into generated code
@@ -493,6 +497,7 @@ Worked example (*"Add rate limiting to all API endpoints"* in 5 calls instead of
| Health trend + declining alerts | ✅ rolling snapshots | ❌ | ❌ | ❌ | ✅ |
| Refactoring recommendations | ✅ deterministic | ❌ | ❌ | ❌ | ✅ |
| Concrete cross-file refactoring plans (Extract Class / Move Method / Break Cycle) | ✅ graph-aware + blast radius | ❌ | ❌ | ❌ | ⚠️ within-function only |
+| Dataflow-verified within-function plans (Extract Method with inferred signature) | ✅ CFG + reaching definitions | ❌ | ❌ | ❌ | ⚠️ LLM-generated, unverified |
| Git intelligence (hotspots, ownership, co-change) | ✅ | ❌ | ❌ | ❌ | ✅ |
| Bus factor analysis | ✅ | ❌ | ❌ | ❌ | ✅ |
| Dead code detection | ✅ | ❌ | ❌ | ❌ | ❌ |
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 4d130dc2f..0f7b58ba5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -11,6 +11,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Changed
+- **One dataflow parse per file.** The health pass's dataflow consumers (the Extract Method detector and the perf advisory-to-asserted promotion) now share a single lazily parsed per-file analysis instead of each re-reading and re-parsing the file, making the health pass measurably faster on large repos with identical output. The new per-function dataflow summary and point-lookup APIs this introduces are the foundation for upcoming dataflow-backed surfaces.
+
### Added
- **Worktrees just work.** `repowise init` and `repowise update` inside a linked git worktree now auto-detect the base checkout and seed the worktree's index from it, then catch up incrementally; no flags needed. `--seed-from <base>` remains as an explicit override and `--no-seed` forces a cold init. See [WORKTREES.md](WORKTREES.md). (#655 introduced the manual flag; this release makes it automatic.)
diff --git a/docs/CODE_HEALTH.md b/docs/CODE_HEALTH.md
index 31cda51f7..895df142f 100644
--- a/docs/CODE_HEALTH.md
+++ b/docs/CODE_HEALTH.md
@@ -304,7 +304,8 @@ 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.
+languages with a def/use dialect: Python, TypeScript, JavaScript, Go, Java, and
+Rust. 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
diff --git a/docs/REFACTORING.md b/docs/REFACTORING.md
index be031b723..36c506211 100644
--- a/docs/REFACTORING.md
+++ b/docs/REFACTORING.md
@@ -23,7 +23,7 @@ LLM layer (code generation) is a separate, strictly opt-in step ([below](#opt-in
<img src="../.github/assets/health-loop.svg" alt="repowise code-health loop: markers fan into three signals, the graph and git history locate risk, and refactoring intelligence emits concrete plans an agent executes" width="100%" />
</div>
-## The five detectors
+## The six detectors
Each detector is a self-contained module registered into a registry (adding a
refactoring type is a new file + a registry entry, like the marker registry).
@@ -37,6 +37,7 @@ one**, and produces stable-sorted, deterministic output.
| **Move Method** | A feature-envy method and the class it actually belongs to. | The method's entity set (fields/methods it touches, class-qualified) is built from the call graph; Jaccard distance to each class. Fires only when a foreign class is clearly nearer than its own. |
| **Break Cycle** | The minimal set of import edges to invert to break a dependency cycle. | A strongly-connected component in the import graph → greedy minimum feedback arc set (MFAS) over the real edges picks the smallest cut. |
| **Split File** | The cohesive files an oversized module should decompose into: which top-level symbols move to each new file, plus the import edits in every dependent. | Community detection (Leiden, Louvain fallback) over a weighted intra-file symbol graph (direct calls, shared local helpers, shared foreign modules); emits only when the partition's **modularity** clears a decomposability gate. The file-level analog of Extract Class. |
+| **Extract Method** | The exact line span to lift out of an oversized/complex method, with the helper's inferred signature: the parameters it needs (IN) and the value it must return (OUT). | Intra-procedural dataflow (CFG + def/use + reaching definitions) over methods a `large_method` / `brain_method` / `complex_method` finding already flagged. Only single-exit, statement-boundary spans that remove real complexity qualify; IN/OUT comes from liveness over the def/use facts, so the suggested helper is behavior-preserving by construction. |
The algorithms are derived from public academic literature (Fokaefs-Tsantalis
HAC for class splitting, Bavota feature-envy distance, MFAS for cycle breaking,
@@ -57,9 +58,9 @@ web).
| Field | Meaning |
|-------|---------|
-| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` \| `split_file` |
+| `refactoring_type` | `extract_class` \| `extract_helper` \| `move_method` \| `break_cycle` \| `split_file` \| `extract_method` |
| `file_path`, `target_symbol`, `line_start`, `line_end` | What the refactoring acts on. |
-| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, or the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`. |
+| `plan` | The concrete, type-specific plan: the split `groups` (methods + fields), the move `{method, from_class, to_class}`, the clone `occurrences` + `suggested_site`, the cycle + `cut_edges`, the file-split `groups` (`{name, symbols, suggested_file}`) + `residual` core + `shim_required`, or the method-extraction `span` + `params` + `returns`. |
| `evidence` | The signals that justify it: `lcom4`, `wmc`, clone token/line counts + `co_change_count`, Jaccard distances, cycle size, or the split's `modularity` + `symbol_count` + `group_count` + intra/cut edge counts. |
| `impact_delta` | The health score the refactoring would recover (the deduction of the marker it answers); `0` for the graph-native types that answer no marker. |
| `effort_bucket` | `S` \| `M` \| `L` \| `XL`, from the target's size. |
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
index fad08bc9f..894bebb4d 100644
--- a/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
@@ -3,8 +3,9 @@
This subpackage builds, per function, a control-flow graph (CFG), a def/use
classification, and reaching-definitions sets -- the semantic foundation for
dataflow-aware refactoring signals (Extract Method) and cross-layer consumers.
-It is deliberately standalone: nothing here is wired into the health engine yet,
-so the layer can be built and measured in isolation before it joins a hot path.
+The health engine consumes it through :class:`facts.FileDataflowCache` (one
+shared, lazily parsed object per file) for the Extract Method detector and the
+perf-promotion pass; request-time callers use :func:`lookup.function_analysis_at`.
**Layering (language-agnostic core, per-language dialects).**
@@ -17,6 +18,11 @@ so the layer can be built and measured in isolation before it joins a hot path.
zero core edits to add one.
- :mod:`analyze` -- composes the three stages behind one call.
- :mod:`gating` -- the flagged-only predicate and the CFG-only file harness.
+- :mod:`facts` -- the shared per-file service (parse once, analyze each
+ function once, every consumer reads the same object) and the curated
+ :class:`DataflowFacts` summary downstream surfaces derive from an analysis.
+- :mod:`lookup` -- point lookup of one function's analysis from live source
+ (the request-time entry point for callers outside the health pass).
**Performance contract (load-bearing).** Full dataflow is built ONLY for a
function a structural biomarker already flagged (``large_method`` /
@@ -46,6 +52,7 @@ from .dialects.base import (
StatementDefUse,
get_defuse_dialect,
)
+from .facts import DataflowFacts, DeadStore, FileDataflow, FileDataflowCache, derive_facts
from .gating import (
CFGPassStats,
FileCFGResult,
@@ -54,6 +61,7 @@ from .gating import (
is_flagged,
is_flagged_function,
)
+from .lookup import function_analysis_at
from .reaching import ReachingDefinitions, compute_reaching
from .slice import Extraction, find_extractions
@@ -63,12 +71,16 @@ __all__ = [
"BasicBlock",
"BlockDefUse",
"CFGPassStats",
+ "DataflowFacts",
+ "DeadStore",
"DefUseDialect",
"Definition",
"Extraction",
"FileAnalysisResult",
"FileAnalysisStats",
"FileCFGResult",
+ "FileDataflow",
+ "FileDataflowCache",
"FunctionAnalysis",
"FunctionCFG",
"FunctionDefUse",
@@ -82,7 +94,9 @@ __all__ = [
"build_cfgs_for_file",
"compute_def_use",
"compute_reaching",
+ "derive_facts",
"find_extractions",
+ "function_analysis_at",
"get_defuse_dialect",
"is_flagged",
"is_flagged_function",
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/facts.py b/packages/core/src/repowise/core/analysis/health/dataflow/facts.py
new file mode 100644
index 000000000..e450c05ff
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/facts.py
@@ -0,0 +1,381 @@
+"""Shared per-file dataflow service + the curated ``DataflowFacts`` summary.
+
+Before this module each dataflow consumer (the Extract Method detector, the
+perf-promotion pass) read and parsed its target file independently, so a file
+hit by two gates was parsed twice on top of the complexity walker's own parse.
+:class:`FileDataflow` ends that pattern: one lazy parse per file, one analysis
+per function, every consumer reads the same memoized :class:`FunctionAnalysis`.
+:class:`FileDataflowCache` shares those objects across consumers for the
+lifetime of one health pass.
+
+Laziness is the design's load-bearing property. Constructing a
+:class:`FileDataflow` costs nothing: no I/O, no parse. The source is read and
+parsed only when a consumer's gate actually fires (a promotable perf hit, a
+method-level smell), which preserves the layer's flagged-only budget exactly --
+an ungated file is never touched.
+
+:class:`DataflowFacts` is the single curated summary shape downstream surfaces
+(MCP tools, dead-code kinds, wiki context) derive from a
+:class:`FunctionAnalysis`. It is derivation only -- every field is read off the
+existing CFG / def-use / reaching primitives, no new analysis. Facts are raw
+and deterministic; suppression policy (underscore conventions, size floors)
+belongs to each consumer, not here.
+
+Failure contract: everything degrades to silence. An unreadable file, an
+unsupported language, a guard trip, or a non-converged fixpoint yields an empty
+list or ``None``, never a raise.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+import structlog
+
+from ..complexity.ast_utils import _collect_function_nodes, _find_function_entry_name
+from . import analyze as _analyze
+from .analyze import FunctionAnalysis
+from .dialects.base import get_defuse_dialect
+from .gating import is_flagged
+from .parsing import function_metrics, parse_source
+
+if TYPE_CHECKING:
+ from collections.abc import Iterable
+
+ from tree_sitter import Node
+
+ from ..complexity.languages import LanguageNodeMap
+
+log = structlog.get_logger(__name__)
+
+
+# ---------------------------------------------------------------------------
+# The curated facts summary
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class DeadStore:
+ """A write whose value no subsequent read can observe."""
+
+ var: str
+ line: int # 1-indexed
+
+
+@dataclass(frozen=True)
+class DataflowFacts:
+ """A function's dataflow summary, derived from one :class:`FunctionAnalysis`.
+
+ All name tuples are sorted and de-duplicated; ``params_read`` /
+ ``params_unused`` keep parameter declaration order. Identical source yields
+ identical facts (the determinism the CFG layer already guarantees).
+
+ Scope caveats consumers must respect: the layer tracks local-variable data
+ flow only. A "dead" store may still be observed by a closure, and ``reads``
+ names free variables (globals, imports, attributes are out of scope of the
+ def/use dialects).
+ """
+
+ name: str
+ start_line: int # 1-indexed
+ end_line: int # 1-indexed
+ params_read: tuple[str, ...]
+ params_unused: tuple[str, ...]
+ reads: tuple[str, ...] # free names: read but never defined locally
+ writes: tuple[str, ...] # locals defined (parameters excluded)
+ flows_out: tuple[str, ...] # locals whose value can reach the function exit
+ dead_stores: tuple[DeadStore, ...]
+ unreachable_lines: tuple[int, ...] # statement start lines in dead blocks
+ block_count: int
+ converged: bool
+
+
+def derive_facts(analysis: FunctionAnalysis) -> DataflowFacts:
+ """Read a :class:`DataflowFacts` summary off *analysis*'s primitives."""
+ def_use = analysis.def_use
+ cfg = analysis.cfg
+ reaching = analysis.reaching
+
+ param_names: list[str] = []
+ for occ in def_use.params:
+ if occ.name not in param_names:
+ param_names.append(occ.name)
+ param_set = set(param_names)
+
+ use_names = {u.name for bdu in def_use.blocks.values() for u in bdu.uses}
+ defined_names = {d.var for d in def_use.definitions}
+
+ # Parameter seeds are the first len(params) definitions (compute_def_use
+ # assigns their indices before any statement's) -- everything after is a
+ # body write site.
+ n_param_seeds = len(def_use.params)
+
+ live = _live_definition_indices(analysis)
+ dead_stores = tuple(
+ DeadStore(var=d.var, line=d.line)
+ for d in sorted(
+ (d for d in def_use.definitions if d.index >= n_param_seeds and d.index not in live),
+ key=lambda d: (d.line, d.var),
+ )
+ )
+
+ exit_defs = reaching.in_sets.get(cfg.exit_id, frozenset())
+ flows_out = tuple(sorted({def_use.definitions[i].var for i in exit_defs if i >= n_param_seeds}))
+
+ unreachable = cfg.reachable_ids()
+ unreachable_lines = tuple(
+ sorted(
+ {
+ stmt.start_line
+ for block in cfg.blocks
+ if block.id not in unreachable
+ for stmt in block.statements
+ }
+ )
+ )
+
+ return DataflowFacts(
+ name=analysis.name,
+ start_line=analysis.start_line,
+ end_line=analysis.end_line,
+ params_read=tuple(p for p in param_names if p in use_names),
+ params_unused=tuple(p for p in param_names if p not in use_names),
+ reads=tuple(sorted(use_names - defined_names)),
+ writes=tuple(sorted(defined_names - param_set)),
+ flows_out=flows_out,
+ dead_stores=dead_stores,
+ unreachable_lines=unreachable_lines,
+ block_count=len(cfg.blocks),
+ converged=reaching.converged,
+ )
+
+
+def _live_definition_indices(analysis: FunctionAnalysis) -> set[int]:
+ """Definition indices some read can observe (conservative: over-marks live).
+
+ A use of ``v`` at line ``L`` in block ``b`` observes:
+
+ - the latest same-block definition(s) of ``v`` strictly before ``L``, or,
+ when none exists, every definition of ``v`` reaching ``IN[b]``;
+ - plus, conservatively, any same-block definition of ``v`` AT line ``L``
+ (multiple statements on one line cannot be ordered by line numbers alone,
+ so ambiguity counts as live -- fewer dead stores, never a false one).
+
+ Anything the rules cannot prove observed stays potentially dead; the caller
+ subtracts this set from all body definitions to get the dead stores.
+ """
+ def_use = analysis.def_use
+ reaching = analysis.reaching
+ live: set[int] = set()
+
+ for bid, bdu in def_use.blocks.items():
+ if not bdu.uses:
+ continue
+ in_defs = reaching.in_sets.get(bid, frozenset())
+ in_by_var: dict[str, list[int]] = {}
+ for i in in_defs:
+ in_by_var.setdefault(reaching.definitions[i].var, []).append(i)
+ local_by_var: dict[str, list] = {}
+ for d in bdu.defs:
+ local_by_var.setdefault(d.var, []).append(d)
+
+ for use in bdu.uses:
+ local = local_by_var.get(use.name, [])
+ earlier = [d for d in local if d.line < use.line]
+ if earlier:
+ latest = max(d.line for d in earlier)
+ live.update(d.index for d in earlier if d.line == latest)
+ else:
+ live.update(in_by_var.get(use.name, ()))
+ live.update(d.index for d in local if d.line == use.line)
+
+ return live
+
+
+# ---------------------------------------------------------------------------
+# The shared per-file service
+# ---------------------------------------------------------------------------
+
+
+class FileDataflow:
+ """Lazy dataflow analyses for one file: parse once, analyze each function once.
+
+ Construction is free. The first accessor that needs the AST triggers the
+ (single) source read + parse; per-function analyses are memoized so a
+ function requested by two consumers is analyzed exactly once. Every failure
+ mode -- unreadable file, no def/use dialect, parse failure, guard trip,
+ non-convergence -- degrades to an empty result for the affected scope.
+ """
+
+ def __init__(self, abs_path: str, language: str, source: bytes | None = None) -> None:
+ self.abs_path = abs_path
+ self.language = language
+ self._source = source
+ self._parsed = False
+ self._root: Node | None = None
+ self._lmap: LanguageNodeMap | None = None
+ self._fn_nodes: list[Node] = []
+ # Memos keyed by position in ``_fn_nodes`` (start lines can collide
+ # for same-line lambdas; collection order is deterministic).
+ self._metrics: dict[int, tuple[int, int] | None] = {}
+ self._analyses: dict[int, FunctionAnalysis | None] = {}
+
+ # -- consumer entry points ------------------------------------------------
+
+ def flagged_analyses(self) -> list[FunctionAnalysis]:
+ """Analyses for the structurally flagged functions, in source order.
+
+ The Extract Method consumer's view: the same flagged-only gate (and the
+ same skips on metric failure, guard trip, or non-convergence) as
+ :func:`analyze.analyze_file`.
+ """
+ out: list[FunctionAnalysis] = []
+ for idx, fn_node in enumerate(self._functions()):
+ metrics = self._metrics_for(idx, fn_node)
+ if metrics is None:
+ continue
+ ccn, nloc = metrics
+ if not is_flagged(ccn=ccn, nloc=nloc):
+ continue
+ analysis = self._analysis_for(idx, fn_node)
+ if analysis is not None:
+ out.append(analysis)
+ return out
+
+ def analyses_covering(self, lines: Iterable[int]) -> list[FunctionAnalysis]:
+ """Analyses for every function whose span contains one of *lines*.
+
+ The perf-promotion consumer's view: no structural gate (the perf hit is
+ the gate), nested functions covering the same line are all returned so
+ the caller can try each enclosing scope.
+ """
+ wanted = set(lines)
+ if not wanted:
+ return []
+ out: list[FunctionAnalysis] = []
+ for idx, fn_node in enumerate(self._functions()):
+ fstart = fn_node.start_point[0] + 1
+ fend = fn_node.end_point[0] + 1
+ if not any(fstart <= ln <= fend for ln in wanted):
+ continue
+ analysis = self._analysis_for(idx, fn_node)
+ if analysis is not None:
+ out.append(analysis)
+ return out
+
+ def analysis_at(self, start_line: int, name: str | None = None) -> FunctionAnalysis | None:
+ """The analysis for the function starting at *start_line*.
+
+ Start-line match first; *name* disambiguates same-line collisions and,
+ when no function starts at *start_line* (bounds drifted), a unique name
+ match is the fallback. ``None`` on any miss or analysis failure.
+ """
+ nodes = list(enumerate(self._functions()))
+ by_line = [(i, n) for i, n in nodes if n.start_point[0] + 1 == start_line]
+ if name and len(by_line) != 1:
+ lmap = self._lmap
+ named = [
+ (i, n)
+ for i, n in (by_line or nodes)
+ if lmap is not None and _find_function_entry_name(n, lmap) == name
+ ]
+ if len(named) == 1:
+ by_line = named
+ if len(by_line) != 1:
+ return None
+ idx, fn_node = by_line[0]
+ return self._analysis_for(idx, fn_node)
+
+ # -- internals -------------------------------------------------------------
+
+ def _functions(self) -> list[Node]:
+ """The file's function nodes, parsing on first demand (empty on failure)."""
+ if self._parsed:
+ return self._fn_nodes
+ self._parsed = True
+ # No def/use dialect means no consumer can produce a result: skip the
+ # read + parse entirely (the promotion pass's early-exit, generalized).
+ if get_defuse_dialect(self.language) is None:
+ return self._fn_nodes
+ source = self._read_source()
+ if source is None:
+ return self._fn_nodes
+ parsed = parse_source(self.abs_path, self.language, source)
+ if parsed is None:
+ return self._fn_nodes
+ self._root, self._lmap = parsed
+ self._fn_nodes = _collect_function_nodes(self._root, self._lmap)
+ return self._fn_nodes
+
+ def _read_source(self) -> bytes | None:
+ if self._source is not None:
+ return self._source
+ try:
+ self._source = Path(self.abs_path).read_bytes()
+ except OSError:
+ return None
+ return self._source
+
+ def _metrics_for(self, idx: int, fn_node: Node) -> tuple[int, int] | None:
+ if idx not in self._metrics:
+ if self._lmap is None or self._source is None:
+ return None
+ self._metrics[idx] = function_metrics(fn_node, self._lmap, self._source)
+ return self._metrics[idx]
+
+ def _analysis_for(self, idx: int, fn_node: Node) -> FunctionAnalysis | None:
+ if idx in self._analyses:
+ return self._analyses[idx]
+ analysis = self._build_analysis(idx, fn_node)
+ self._analyses[idx] = analysis
+ return analysis
+
+ def _build_analysis(self, idx: int, fn_node: Node) -> FunctionAnalysis | None:
+ lmap = self._lmap
+ if lmap is None:
+ return None
+ try:
+ # Module-attribute call so test harnesses that patch
+ # ``analyze.analyze_function`` keep observing every build.
+ analyzed = _analyze.analyze_function(fn_node, self.language, lmap)
+ except Exception as exc:
+ log.debug("dataflow_facts_build_failed", path=self.abs_path, error=str(exc))
+ return None
+ if analyzed is None:
+ return None
+ cfg, def_use, reaching = analyzed
+ cfg.function_name = _find_function_entry_name(fn_node, lmap)
+ cfg.function_start_line = fn_node.start_point[0] + 1
+ metrics = self._metrics_for(idx, fn_node)
+ ccn, nloc = metrics if metrics is not None else (0, 0)
+ return FunctionAnalysis(
+ name=cfg.function_name,
+ start_line=cfg.function_start_line,
+ end_line=fn_node.end_point[0] + 1,
+ ccn=ccn,
+ nloc=nloc,
+ cfg=cfg,
+ def_use=def_use,
+ reaching=reaching,
+ fn_node=fn_node,
+ )
+
+
+class FileDataflowCache:
+ """Shares one :class:`FileDataflow` per file across a health pass's consumers.
+
+ Keyed by absolute path; entries are created lazily and hold no parse until
+ a consumer gate fires. The cache lives for one pass and is dropped with it.
+ """
+
+ def __init__(self) -> None:
+ self._by_path: dict[str, FileDataflow] = {}
+
+ def get(self, abs_path: str, language: str) -> FileDataflow:
+ fd = self._by_path.get(abs_path)
+ if fd is None:
+ fd = FileDataflow(abs_path, language)
+ self._by_path[abs_path] = fd
+ return fd
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/lookup.py b/packages/core/src/repowise/core/analysis/health/dataflow/lookup.py
new file mode 100644
index 000000000..62b0e43b3
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/lookup.py
@@ -0,0 +1,36 @@
+"""Point lookup: the dataflow analysis for one named function in one file.
+
+The entry point for callers outside the health pass (the MCP server serving
+per-symbol facts at request time) that hold verified symbol bounds and live
+source and need exactly one function's analysis -- no engine, no cache, no
+persistence. Composes :class:`facts.FileDataflow` over the supplied source and
+resolves the function by start line, disambiguated by name.
+
+Same silence contract as the rest of the layer: any miss (unsupported
+language, parse failure, no function at the given bounds, guard trip,
+non-convergence) returns ``None``, never a raise.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from .facts import FileDataflow
+
+if TYPE_CHECKING:
+ from .analyze import FunctionAnalysis
+
+
+def function_analysis_at(
+ abs_path: str,
+ language: str,
+ source: bytes,
+ start_line: int,
+ name: str | None = None,
+) -> FunctionAnalysis | None:
+ """Analyze the function starting at *start_line* (1-indexed) in *source*.
+
+ *name*, when given, disambiguates same-line definitions and serves as the
+ fallback match if no function starts exactly at *start_line*.
+ """
+ return FileDataflow(abs_path, language, source).analysis_at(start_line, name)
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 6af9250f3..47a302b7e 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -35,7 +35,7 @@ from .biomarkers import FileContext, detect_all
from .biomarkers.base import HasEdge
from .complexity import FileComplexity, FunctionComplexity, walk_file
from .coverage import is_test_file as _coverage_is_test_file
-from .dataflow import analyze_file
+from .dataflow import FileDataflowCache
from .duplication import DuplicationReport, detect_clones
from .models import HealthFileMetricData, HealthFindingData, HealthReport, Severity
from .perf import (
@@ -395,10 +395,14 @@ class HealthAnalyzer:
# Cross-function N+1: augment perf_hits before the biomarker stage.
self._apply_crossfn_perf(walked)
+ # One shared dataflow service for the whole pass: the promotion pass
+ # and the Extract Method detector below read the same lazily parsed
+ # per-file object, so no file is parsed twice for dataflow.
+ dataflow_cache = FileDataflowCache()
# 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)
+ apply_perf_promotions(walked, dataflow=dataflow_cache)
for pf, fcx in walked:
# Side-effect: bump Symbol.complexity_estimate when we can
@@ -430,6 +434,7 @@ class HealthAnalyzer:
refactoring_enabled=refactoring_enabled,
refactoring_min_confidence=refactoring_min_confidence,
file_scc_index=file_scc_index,
+ dataflow_cache=dataflow_cache,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -562,9 +567,11 @@ class HealthAnalyzer:
# Cross-function N+1: augment perf_hits before the biomarker stage.
walked = list(walked)
self._apply_crossfn_perf(walked)
+ # One shared dataflow service per pass (see the sync path above).
+ dataflow_cache = FileDataflowCache()
# Dataflow promotion: mark advisory perf hits whose loop is provably
# iteration-independent (after the graph passes populate the hits).
- apply_perf_promotions(walked)
+ apply_perf_promotions(walked, dataflow=dataflow_cache)
disabled_refactorings: list[str] = list(cfg.get("disabled_refactorings", ()))
refactoring_enabled: bool = bool(cfg.get("refactoring_enabled", True))
@@ -599,6 +606,7 @@ class HealthAnalyzer:
refactoring_enabled=refactoring_enabled,
refactoring_min_confidence=refactoring_min_confidence,
file_scc_index=file_scc_index,
+ dataflow_cache=dataflow_cache,
)
metrics.append(file_metric)
findings.extend(file_findings)
@@ -721,25 +729,27 @@ class HealthAnalyzer:
return walk_sql_file(pf.file_info, source)
return walk_file(path, language, source)
- def _extract_method_analyses(self, pf: Any, findings: list[HealthFindingData]) -> list[Any]:
+ 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 (and its re-parse) runs for that small subset of
- files only -- everything else pays nothing. Degrades to ``[]`` on any
- read or analysis failure; the detector then yields no suggestion.
+ 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 []
- path = pf.file_info.abs_path
- language = pf.file_info.language
- try:
- source = Path(path).read_bytes()
- except OSError:
- return []
- return analyze_file(path, language, source).functions
+ cache = dataflow_cache if dataflow_cache is not None else FileDataflowCache()
+ 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:
@@ -772,6 +782,7 @@ class HealthAnalyzer:
refactoring_enabled: bool = True,
refactoring_min_confidence: str | None = None,
file_scc_index: dict[str, tuple[str, ...]] | None = None,
+ dataflow_cache: FileDataflowCache | None = None,
) -> tuple[HealthFileMetricData, list[HealthFindingData], list[RefactoringSuggestion]]:
file_path = pf.file_info.path
@@ -874,7 +885,7 @@ class HealthAnalyzer:
# 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.
+ # dataflow build) for this file.
if not refactoring_enabled:
return metric, findings, []
rctx = RefactoringContext(
@@ -888,7 +899,7 @@ class HealthAnalyzer:
module_map=self.module_map,
graph=self.graph,
file_scc=(file_scc_index or {}).get(file_path),
- function_analyses=self._extract_method_analyses(pf, findings),
+ function_analyses=self._extract_method_analyses(pf, findings, dataflow_cache),
blame_index=blame_index,
)
suggestions = detect_refactorings(
diff --git a/packages/core/src/repowise/core/analysis/health/perf/promotion.py b/packages/core/src/repowise/core/analysis/health/perf/promotion.py
index 88e999fd1..e60d5efd6 100644
--- a/packages/core/src/repowise/core/analysis/health/perf/promotion.py
+++ b/packages/core/src/repowise/core/analysis/health/perf/promotion.py
@@ -46,7 +46,6 @@ Extract Method consumer uses, keyed on the perf hit instead of a structural smel
from __future__ import annotations
from dataclasses import replace
-from pathlib import Path
from typing import TYPE_CHECKING, Any
import structlog
@@ -57,6 +56,7 @@ if TYPE_CHECKING:
from ..complexity import FileComplexity
from ..dataflow.cfg import CFG
from ..dataflow.defuse import FunctionDefUse
+ from ..dataflow.facts import FileDataflowCache
from ..dataflow.reaching import ReachingDefinitions
log = structlog.get_logger(__name__)
@@ -72,17 +72,29 @@ log = structlog.get_logger(__name__)
PROMOTABLE_KINDS: frozenset[str] = frozenset({"serial_await_in_loop", "nested_loop_quadratic"})
-def apply_perf_promotions(walked: Iterable[tuple[Any, FileComplexity]]) -> None:
+def apply_perf_promotions(
+ walked: Iterable[tuple[Any, FileComplexity]],
+ dataflow: FileDataflowCache | None = None,
+) -> 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.
+
+ *dataflow* is the pass-wide :class:`FileDataflowCache` the engine threads
+ through every dataflow consumer, so a file this pass analyzes is parsed at
+ most once across the whole health pass. A private cache is created when the
+ caller supplies none (tests, standalone use).
"""
+ if dataflow is None:
+ from ..dataflow.facts import FileDataflowCache
+
+ dataflow = FileDataflowCache()
for pf, fcx in walked:
try:
- promoted_lines = _promotable_lines_for_file(pf, fcx)
+ promoted_lines = _promotable_lines_for_file(pf, fcx, dataflow)
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)
@@ -98,50 +110,30 @@ def apply_perf_promotions(walked: Iterable[tuple[Any, FileComplexity]]) -> None:
]
-def _promotable_lines_for_file(pf: Any, fcx: FileComplexity) -> set[int]:
+def _promotable_lines_for_file(
+ pf: Any, fcx: FileComplexity, dataflow: FileDataflowCache
+) -> 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.
+ dialect, or the parse fails - the documented degrade-to-silence outcomes,
+ all realised inside the shared per-file service.
"""
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
-
+ fd = dataflow.get(pf.file_info.abs_path, pf.file_info.language)
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 analysis in fd.analyses_covering(target_lines):
+ # A guard trip / non-convergence never reaches here (the service
+ # returns no analysis for that function -> the hit stays advisory).
+ hits_here = {ln for ln in target_lines if analysis.start_line <= ln <= analysis.end_line}
for line in hits_here:
- if _loop_iterations_independent(cfg, def_use, reaching, line):
+ if _loop_iterations_independent(
+ analysis.cfg, analysis.def_use, analysis.reaching, line
+ ):
promoted.add(line)
return promoted
diff --git a/tests/unit/health/test_dataflow_facts.py b/tests/unit/health/test_dataflow_facts.py
new file mode 100644
index 000000000..239f44db1
--- /dev/null
+++ b/tests/unit/health/test_dataflow_facts.py
@@ -0,0 +1,236 @@
+"""The shared per-file dataflow service and the DataflowFacts derivation."""
+
+from __future__ import annotations
+
+import textwrap
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.health.complexity import FileComplexity, PerfHit
+from repowise.core.analysis.health.dataflow import (
+ FileDataflow,
+ FileDataflowCache,
+ derive_facts,
+ function_analysis_at,
+)
+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")
+
+
+def _facts(src: str, start_line: int, name: str | None = None, path: str = "x.py"):
+ _require_python()
+ source = textwrap.dedent(src).encode()
+ analysis = function_analysis_at(path, "python", source, start_line, name)
+ assert analysis is not None
+ return derive_facts(analysis)
+
+
+# ---------------------------------------------------------------------------
+# DataflowFacts derivation
+# ---------------------------------------------------------------------------
+
+
+def test_dead_store_overwritten_before_use():
+ facts = _facts(
+ """
+ def f(x):
+ y = first(x)
+ y = second(x)
+ return y
+ """,
+ 2,
+ )
+ assert [(d.var, d.line) for d in facts.dead_stores] == [("y", 3)]
+ assert "y" in facts.writes
+ assert "y" in facts.flows_out
+
+
+def test_unreachable_lines_after_return():
+ facts = _facts(
+ """
+ def f(x):
+ if x:
+ return 1
+ return 2
+ cleanup()
+ """,
+ 2,
+ )
+ assert 6 in facts.unreachable_lines
+
+
+def test_params_read_and_unused():
+ facts = _facts(
+ """
+ def f(a, b):
+ return a + 1
+ """,
+ 2,
+ )
+ assert facts.params_read == ("a",)
+ assert facts.params_unused == ("b",)
+
+
+def test_tuple_unpack_partial_use_marks_unused_element_dead():
+ facts = _facts(
+ """
+ def f(pair):
+ a, b = pair
+ return a
+ """,
+ 2,
+ )
+ dead_vars = {d.var for d in facts.dead_stores}
+ assert "b" in dead_vars
+ assert "a" not in dead_vars
+
+
+def test_reads_are_free_names_only():
+ facts = _facts(
+ """
+ def f(x):
+ y = helper(x, CONSTANT)
+ return y
+ """,
+ 2,
+ )
+ assert "helper" in facts.reads or "CONSTANT" in facts.reads
+ assert "x" not in facts.reads # a parameter, not a free name
+ assert "y" not in facts.reads # a local, not a free name
+
+
+def test_self_referencing_assignment_keeps_prior_def_alive():
+ # ``y = y + 1`` reads the PREVIOUS def; neither write is a dead store here.
+ facts = _facts(
+ """
+ def f(x):
+ y = x
+ y = y + 1
+ return y
+ """,
+ 2,
+ )
+ assert facts.dead_stores == ()
+
+
+def test_facts_are_deterministic_across_instances():
+ src = textwrap.dedent(
+ """
+ def f(a, b):
+ total = 0
+ unused = a
+ for item in b:
+ total = total + item
+ return total
+ """
+ ).encode()
+ _require_python()
+ one = derive_facts(FileDataflow("x.py", "python", src).analysis_at(2))
+ two = derive_facts(FileDataflow("x.py", "python", src).analysis_at(2))
+ assert one == two
+
+
+# ---------------------------------------------------------------------------
+# Lookup
+# ---------------------------------------------------------------------------
+
+
+def test_lookup_miss_returns_none():
+ _require_python()
+ source = b"def f(x):\n return x\n"
+ assert function_analysis_at("x.py", "python", source, 99) is None
+
+
+def test_lookup_falls_back_to_unique_name_match():
+ _require_python()
+ source = b"\n\ndef target(x):\n return x\n"
+ analysis = function_analysis_at("x.py", "python", source, 1, name="target")
+ assert analysis is not None
+ assert analysis.name == "target"
+ assert analysis.start_line == 3
+
+
+def test_lookup_unsupported_language_is_silent():
+ assert function_analysis_at("x.zig", "zig", b"fn f() {}", 1) is None
+
+
+# ---------------------------------------------------------------------------
+# The shared cache: one parse per file across both consumers
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _FileInfo:
+ path: str
+ abs_path: str
+ language: str
+
+
+@dataclass
+class _ParsedFile:
+ file_info: _FileInfo
+
+
+def test_one_parse_when_promotion_and_extract_method_hit_same_file(tmp_path: Path, monkeypatch):
+ _require_python()
+ from repowise.core.analysis.health.dataflow import facts as facts_mod
+
+ # A function that is BOTH structurally flagged (ccn >= 9) and carries a
+ # promotable advisory hit, so the two consumer gates fire on one file.
+ branches = "\n".join(f" if r == {i}:\n out.append({i})" for i in range(9))
+ src = (
+ "async def f(items):\n"
+ " out = []\n"
+ " for item in items:\n"
+ " r = await fetch(item.id) # HIT\n"
+ f"{branches}\n"
+ " return out\n"
+ )
+ p = tmp_path / "both.py"
+ p.write_text(src, encoding="utf-8")
+ hit_line = next(i for i, ln in enumerate(src.splitlines(), start=1) if "HIT" in ln)
+
+ calls = {"n": 0}
+ real = facts_mod.parse_source
+
+ def _counting(*args, **kwargs):
+ calls["n"] += 1
+ return real(*args, **kwargs)
+
+ monkeypatch.setattr(facts_mod, "parse_source", _counting)
+
+ cache = FileDataflowCache()
+ pf = _ParsedFile(_FileInfo(path="both.py", abs_path=str(p), language="python"))
+ fcx = FileComplexity(
+ functions=[],
+ classes=[],
+ perf_hits=[PerfHit(kind="serial_await_in_loop", line=hit_line, function="f")],
+ )
+
+ # Consumer 1: the promotion pass.
+ apply_perf_promotions([(pf, fcx)], dataflow=cache)
+ assert fcx.perf_hits[0].promoted is True
+
+ # Consumer 2: the Extract Method view, through the same cache.
+ flagged = cache.get(str(p), "python").flagged_analyses()
+ assert flagged and flagged[0].name == "f"
+ assert flagged[0].ccn >= 9
+
+ assert calls["n"] == 1
+
+
+def test_cache_construction_does_not_touch_the_file(tmp_path: Path):
+ fd = FileDataflow(str(tmp_path / "missing.py"), "python")
+ # Nothing read or parsed yet; a consumer call on a missing file is silent.
+ assert fd.flagged_analyses() == []
+ assert fd.analyses_covering({1}) == []