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
perf(health): walk each file's tree once for every whole-file complexity pass (#2865)
Raghav Chamadiya73e6479ec463
diff --git a/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py b/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.pyindex 25c3f9bfb..623870f7f 100644--- a/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py+++ b/packages/core/src/repowise/core/analysis/health/biomarkers/error_handling.py@@ -14,7 +14,7 @@ ships in its own ``error_handling`` category with an advisory 0.5 cap anda floored 0.5 weight, and is excluded from the defect-calibration roster.Detection happens in the complexity walker's whole-tree pass (see-``complexity.error_handling._collect_error_handling``); this detector just lifts+``complexity.error_handling._eh_visit``); this detector just liftsthe pre-collected hits into findings. Precision-first: unsupportedlanguages and parse failures yield zero hits, never a false positive."""diff --git a/packages/core/src/repowise/core/analysis/health/complexity/README.md b/packages/core/src/repowise/core/analysis/health/complexity/README.mdindex a33a96109..1dcb06ef2 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/README.md+++ b/packages/core/src/repowise/core/analysis/health/complexity/README.md@@ -10,10 +10,11 @@ Tree-sitter AST walker. Single AST pass per file computes:> | `walker.py` | Orchestration (`walk_file` / `walk_file_complexity`) + public re-exports |> | `models.py` | Output dataclasses (`FunctionComplexity`, `ClassComplexity`, `PerfHit`, ...) |> | `ast_utils.py` | Name/text helpers, callee-name reading, function-node collection, parameter counting |-> | `nloc.py` | Non-blank / non-comment line counting |+> | `file_scan.py` | The one descent the whole-file passes share (NLOC index, error handling, class nodes, Rust test spans, perf import names) |+> | `nloc.py` | Non-blank / non-comment line counting (`CodeLineIndex`) |> | `cyclomatic.py` | The CCN / cognitive / max-nesting engine (`_walk_function_body`) |> | `assertions.py` | Assertion-block detection (test-quality smells) |-> | `error_handling.py` | Error-handling anti-pattern detection (`_collect_error_handling`) |+> | `error_handling.py` | Error-handling anti-pattern detection (`_eh_visit`) |> | `perf_walk.py` | Performance-risk pass (`_collect_perf_hits`) |> | `class_analysis.py` | Class-level LCOM4 / god-class metrics (`_compute_lcom4`) |> | `languages.py` | Per-language tree-sitter `LanguageNodeMap` registry (extension point) |@@ -45,7 +46,11 @@ that opt in — see "Class-level metrics" below.## Performance characteristicsOne parser instance per process (lazy-loaded via the ingestion registry).-Single pass per file — no AST re-traversal. The walker re-parses the file+One descent per file feeds every whole-file pass (`file_scan.py`); the+per-function passes walk only their function's body, and the perf pass keeps+its own descent for the loop / async / lock context it carries down the tree.+Function and class NLOC are prefix-sum lookups, not subtree walks. The walker+re-parses the filebecause `ParsedFile` does not carry the tree-sitter `Node` across theingestion boundary; cost is acceptable (≲ 1 ms for typical files).diff --git a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.pyindex 3a650ee84..04eed012a 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/class_analysis.py@@ -15,7 +15,7 @@ from typing import TYPE_CHECKINGfrom .ast_utils import _IDENTIFIER_SUFFIX, _find_namefrom .languages import LanguageNodeMapfrom .models import ClassComplexity, CohesionGroup, FunctionComplexity-from .nloc import _count_nloc+from .nloc import CodeLineIndexif TYPE_CHECKING:from tree_sitter import Node@@ -40,26 +40,6 @@ def _class_name(node: Node) -> str:return _find_name(node)-def _collect_class_nodes(root: Node, lmap: LanguageNodeMap) -> list[Node]:- """All class-like grouping nodes in the file (pre-order).-- Descends through the whole tree so nested classes are found too;- each becomes its own ``ClassComplexity``.- """- out: list[Node] = []- stack: list[Node] = [root]- while stack:- node = stack.pop()- # ``is_named`` filters out keyword tokens that share a type name- # with an expression node (e.g. the ``class`` keyword vs a- # ``class`` expression in tree-sitter-typescript).- if node.type in lmap.class_kinds and node.is_named:- out.append(node)- for child in node.children:- stack.append(child)- return out--def _collect_class_methods(class_node: Node, lmap: LanguageNodeMap) -> list[Node]:"""Direct method nodes of *class_node*.@@ -277,16 +257,21 @@ def _compute_lcom4(def _collect_classes(- root: Node,+ class_nodes: list[Node],lmap: LanguageNodeMap,source: bytes,fc_by_node_id: dict[int, FunctionComplexity],+ code_lines: CodeLineIndex,) -> list[ClassComplexity]:- """Build ``ClassComplexity`` for every class-like node in the file."""+ """Build ``ClassComplexity`` for every class-like node in the file.++ *class_nodes* are every named ``class_kinds`` node in the file, nested+ classes included, in the order ``file_scan`` found them.+ """if not lmap.class_kinds:return []classes: list[ClassComplexity] = []- for class_node in _collect_class_nodes(root, lmap):+ for class_node in class_nodes:method_nodes = _collect_class_methods(class_node, lmap)method_fcs = [fc_by_node_id[m.id] for m in method_nodes if m.id in fc_by_node_id]# Keep nodes and FCs aligned (a method missing from the function@@ -299,7 +284,7 @@ def _collect_classes(start_line=class_node.start_point[0] + 1,end_line=class_node.end_point[0] + 1,method_count=len(method_fcs),- total_nloc=_count_nloc(class_node, source),+ total_nloc=code_lines.count(class_node, source),methods=method_fcs,lcom4=lcom4,max_method_ccn=max((fc.ccn for fc in method_fcs), default=0),diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.pyindex e5c8a7bb5..6cb79b5b6 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py@@ -298,12 +298,14 @@ def _walk_function_body(# Check if this is a case/arm inside a flat match — skip it.# In Rust the parent chain is match_arm → match_block → match_expression,- # so we check both parent and grandparent.- _parent = node.parent+ # so we check both parent and grandparent. ``node.parent`` costs far+ # more than the rest of this visit, so it is read only for a case node+ # once a flat match exists for it to belong to.is_flat_match_arm = Falseif (- node.type in lmap.case_kinds- and _parent is not None+ flat_match_ids+ and node.type in lmap.case_kinds+ and (_parent := node.parent) is not Noneand (_parent.id in flat_match_idsor (_parent.parent is not None and _parent.parent.id in flat_match_ids)diff --git a/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py b/packages/core/src/repowise/core/analysis/health/complexity/error_handling.pyindex d1e8d2ce7..f6334139f 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/error_handling.py@@ -4,7 +4,7 @@ Ported from the bench-validated detector (24/24 fixtures across 11languages). Precision-first: every detector targets the unambiguousshape and degrades to "no signal" rather than guessing.-``_collect_error_handling`` is a whole-tree pass emitting one+``_eh_visit`` runs on each node of the walker's single file scan, emitting one``ErrorHandlingHit`` per swallowed catch / bare except / Rust panic-unwrap /Go err-swallow it finds, anywhere in the file (not just function bodies)."""@@ -221,43 +221,54 @@ def _eh_go_hit(node: Node) -> bool:return False-def _collect_error_handling(- root: Node, language: str, lmap: LanguageNodeMap-) -> list[ErrorHandlingHit]:- """Whole-tree pass: every error-handling anti-pattern with its line.+# The node types ``_eh_rust_hit`` / ``_eh_go_hit`` can fire on.+_EH_RUST_KINDS = frozenset({"call_expression", "macro_invocation"})+_EH_GO_KINDS = frozenset({"if_statement", "short_var_declaration", "assignment_statement"})- Catch-clause shapes reuse the ``LanguageNodeMap`` catch kinds (Python- ``except_clause``; JS/TS/Java/C++/C# ``catch_clause``; Kotlin++def _eh_node_kinds(language: str, lmap: LanguageNodeMap) -> frozenset[str]:+ """Every node type ``_eh_visit`` can emit a hit on, so the shared file scan+ skips the call for every other node."""+ kinds = set(lmap.catch_kinds)+ if language == "rust":+ kinds |= _EH_RUST_KINDS+ elif language == "go":+ kinds |= _EH_GO_KINDS+ return frozenset(kinds)+++def _eh_visit(+ node: Node, language: str, lmap: LanguageNodeMap, hits: list[ErrorHandlingHit]+) -> None:+ """Append the error-handling anti-pattern at *node*, if it is one.++ Called by ``file_scan`` for each node anywhere in the file (module-level+ code too: anti-patterns are not confined to function bodies), which sorts+ the hits by line. Catch-clause shapes reuse the ``LanguageNodeMap`` catch+ kinds (Python ``except_clause``; JS/TS/Java/C++/C# ``catch_clause``; Kotlin``catch_block``); Rust and Go have no catch nodes and use their own- recognizers. Module-level code is covered too — anti-patterns are not- confined to function bodies.+ recognizers."""- hits: list[ErrorHandlingHit] = []catch_kinds = lmap.catch_kinds- is_python = language == "python"- is_rust = language == "rust"- is_go = language == "go"- stack: list[Node] = [root]- while stack:- node = stack.pop()- if catch_kinds and node.type in catch_kinds:- block = _eh_find_body_block(node)- if block is not None and _eh_body_is_swallowed(block, language):- hits.append(ErrorHandlingHit("swallowed_catch", node.start_point[0] + 1))- if is_python and _eh_is_bare_except(node) and not _eh_body_ends_in_raise(block, language):- # ``except:`` / ``except BaseException:`` also swallow- # KeyboardInterrupt & SystemExit; ``except Exception:`` cannot.- kind = "bare_except" if _eh_catches_base(node) else "broad_except"- hits.append(ErrorHandlingHit(kind, node.start_point[0] + 1))- elif is_rust and _eh_rust_hit(node):- # A panic-family macro aborts unconditionally; unwrap/expect converts- # a Result/Option into a panic. Different claims → different kinds.- # ``.unwrap()`` inside a ``#[test]`` is the intended failure signal.- if not _eh_rust_in_test(node):- kind = "panic_macro" if node.type == "macro_invocation" else "unsafe_unwrap"- hits.append(ErrorHandlingHit(kind, node.start_point[0] + 1))- elif is_go and _eh_go_hit(node):- hits.append(ErrorHandlingHit("go_swallow", node.start_point[0] + 1))- stack.extend(node.children)- hits.sort(key=lambda h: h.line)- return hits+ if catch_kinds and node.type in catch_kinds:+ block = _eh_find_body_block(node)+ if block is not None and _eh_body_is_swallowed(block, language):+ hits.append(ErrorHandlingHit("swallowed_catch", node.start_point[0] + 1))+ if (+ language == "python"+ and _eh_is_bare_except(node)+ and not _eh_body_ends_in_raise(block, language)+ ):+ # ``except:`` / ``except BaseException:`` also swallow+ # KeyboardInterrupt & SystemExit; ``except Exception:`` cannot.+ kind = "bare_except" if _eh_catches_base(node) else "broad_except"+ hits.append(ErrorHandlingHit(kind, node.start_point[0] + 1))+ elif language == "rust" and _eh_rust_hit(node):+ # A panic-family macro aborts unconditionally; unwrap/expect converts+ # a Result/Option into a panic. Different claims → different kinds.+ # ``.unwrap()`` inside a ``#[test]`` is the intended failure signal.+ if not _eh_rust_in_test(node):+ kind = "panic_macro" if node.type == "macro_invocation" else "unsafe_unwrap"+ hits.append(ErrorHandlingHit(kind, node.start_point[0] + 1))+ elif language == "go" and _eh_go_hit(node):+ hits.append(ErrorHandlingHit("go_swallow", node.start_point[0] + 1))diff --git a/packages/core/src/repowise/core/analysis/health/complexity/file_scan.py b/packages/core/src/repowise/core/analysis/health/complexity/file_scan.pynew file mode 100644index 000000000..48655d8d3--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/file_scan.py@@ -0,0 +1,173 @@+"""One descent of a file's tree for every whole-file pass of the walker.++File NLOC, the NLOC of each function and class, the error-handling+anti-patterns, the class nodes, the Rust test-only spans and the perf pass's+I/O import names each used to walk+the whole tree, or a whole subtree per function and class, on their own. This+visits each node once and hands every pass what it reads there.++The stack discipline (pop the last, push the children in order) is the one the+separate passes used, so the order hits and class nodes are found in, which+the output keeps, is unchanged.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING++from ..perf.io_boundaries import _finish_io_names, _io_visit+from .error_handling import _eh_node_kinds, _eh_rust_attr_is_test, _eh_visit+from .languages import LanguageNodeMap+from .models import ErrorHandlingHit+from .nloc import CodeLineIndex, _is_docstring_stmt, _source_lines++if TYPE_CHECKING:+ from tree_sitter import Node++# ``function_item`` / ``mod_item`` / ``impl_item`` are the Rust item kinds a+# ``#[cfg(test)]`` (or ``#[test]`` / ``#[tokio::test]`` / ``#[rstest]``, for a+# bare fn) attribute can gate. ``mod``/``impl`` are containers: their whole+# span is test-only once gated, including any nested fn that carries no+# attribute of its own, the same reason ``#[cfg(test)] mod tests { .. }``+# hides ordinary-looking helper fns from the file-level heuristic.+_RUST_TEST_ITEM_KINDS = frozenset({"function_item", "mod_item", "impl_item"})+_RUST_ATTR_SIBLING_KINDS = frozenset({"attribute_item", "line_comment", "block_comment"})+++@dataclass+class FileScan:+ """What the single descent collected for one file."""++ lines: CodeLineIndex+ error_handling_hits: list[ErrorHandlingHit]+ class_nodes: list[Node]+ #: 1-indexed ``(start_line, end_line)`` spans of Rust test-only code.+ rust_test_line_ranges: tuple[tuple[int, int], ...]+ #: ``perf.io_boundaries.collect_io_names`` for the file, or ``{}`` when+ #: the scan was not asked for it.+ io_names: dict[str, str]+++def _rust_item_is_test(node: Node) -> bool:+ """True when a Rust item's preceding attributes mark it test-only.++ Uses :func:`repowise.core.analysis.health.complexity.error_handling._eh_rust_attr_is_test`,+ shared with the error-handling pass so both recognize the identical+ attribute grammar.+ """+ sib = node.prev_sibling+ while sib is not None and sib.type in _RUST_ATTR_SIBLING_KINDS:+ if sib.type == "attribute_item" and _eh_rust_attr_is_test(+ (sib.text or b"").decode("utf-8", errors="replace")+ ):+ return True+ sib = sib.prev_sibling+ return False+++# Bits of the per-node context the descent carries.+_IN_COMMENT = 1 # under a comment: no NLOC anywhere+_IN_DOCSTRING = 2 # under a comment or docstring: no function / class NLOC+_IN_RUST_TEST = 4 # inside a recorded Rust test span: record no nested one+++def scan_file(+ root: Node, language: str, lmap: LanguageNodeMap, source: bytes, *, io_names: bool+) -> FileScan:+ """Walk *root* once and collect every whole-file pass's facts.++ *io_names* asks for the perf pass's import map too; the walker sets it only+ when that pass runs for the language.++ A Rust test span is recorded for an item whose attributes mark it, and not+ again for any item nested inside it: its span already covers them, which+ is what lets ``perf.gated._in_rust_test_range`` silence an undecorated+ helper inside a ``#[cfg(test)] mod``. Rust-only; every other language gets+ ``()``.+ """+ lines = _source_lines(source)+ nonblank = [bool(line.strip()) for line in lines]+ n_lines = len(lines)+ file_rows: set[int] = set()+ code_rows: set[int] = set()+ leaves: list[tuple[int, int, int]] = []+ excluded: list[tuple[int, int]] = []+ hits: list[ErrorHandlingHit] = []+ class_nodes: list[Node] = []+ rust_ranges: list[tuple[int, int]] = []+ io_bound: dict[str, str] = {}+ io_rebound: set[str] = set()++ eh_kinds = _eh_node_kinds(language, lmap)+ class_kinds = lmap.class_kinds+ is_rust = language == "rust"++ stack: list[tuple[Node, int]] = [(root, 0)]+ pop = stack.pop+ push = stack.append+ while stack:+ node, ctx = pop()+ t = node.type+ if io_names:+ _io_visit(node, t, language, io_bound, io_rebound)+ if t in eh_kinds:+ _eh_visit(node, language, lmap, hits)+ if class_kinds and t in class_kinds and node.is_named:+ class_nodes.append(node)+ if (+ is_rust+ and not ctx & _IN_RUST_TEST+ and t in _RUST_TEST_ITEM_KINDS+ and _rust_item_is_test(node)+ ):+ rust_ranges.append((node.start_point[0] + 1, node.end_point[0] + 1))+ ctx |= _IN_RUST_TEST+ if not ctx & _IN_DOCSTRING:+ if "comment" in t:+ ctx |= _IN_COMMENT | _IN_DOCSTRING+ excluded.append((node.start_byte, node.end_byte))+ elif t == "expression_statement" and _is_docstring_stmt(node):+ ctx |= _IN_DOCSTRING+ excluded.append((node.start_byte, node.end_byte))+ elif not ctx & _IN_COMMENT and "comment" in t:+ ctx |= _IN_COMMENT++ children = node.children+ if children:+ for child in children:+ push((child, ctx))+ continue+ if ctx & _IN_COMMENT:+ continue+ start_byte = node.start_byte+ if start_byte >= node.end_byte:+ continue+ first = node.start_point[0]+ last = node.end_point[0]+ in_docstring = ctx & _IN_DOCSTRING+ if first == last:+ # Most leaves sit on one line; skip building a row list for them.+ if first < n_lines and nonblank[first]:+ file_rows.add(first)+ if not in_docstring:+ code_rows.add(first)+ else:+ rows = [row for row in range(first, min(last, n_lines - 1) + 1) if nonblank[row]]+ file_rows.update(rows)+ if not in_docstring:+ code_rows.update(rows)+ if not in_docstring:+ leaves.append((start_byte, first, last))++ hits.sort(key=lambda h: h.line)+ # Recorded right to left; the spans are disjoint, so reversing restores+ # source order, the order the left-to-right walk this replaced produced.+ rust_ranges.reverse()+ return FileScan(+ lines=CodeLineIndex(nonblank, file_rows, code_rows, leaves, excluded),+ error_handling_hits=hits,+ class_nodes=class_nodes,+ rust_test_line_ranges=tuple(rust_ranges),+ io_names=_finish_io_names(io_bound, io_rebound),+ )diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex df5a8bb5f..afc7efab8 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -183,7 +183,7 @@ class ErrorHandlingHit:"""One error-handling anti-pattern occurrence in a file.Collected by the walker's whole-tree pass (see- ``_collect_error_handling``) and consumed by the ``error_handling``+ ``complexity.error_handling._eh_visit``) and consumed by the ``error_handling``biomarker. ``kind`` is one of:- ``swallowed_catch`` — a catch/except whose body has no real handlingdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/nloc.py b/packages/core/src/repowise/core/analysis/health/complexity/nloc.pyindex a2ced73a0..3a25fed9a 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/nloc.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/nloc.py@@ -1,12 +1,13 @@"""Non-blank / non-comment line counting over tree-sitter nodes and raw bytes.``_count_nloc`` measures a single node's span; ``_count_file_nloc`` is the-no-tree fallback (used when parsing is unavailable); ``_count_file_nloc_tree``-excludes comment-only lines using the parsed tree.+no-tree fallback (used when parsing is unavailable); ``CodeLineIndex`` answers+file, function and class NLOC from the walker's single descent of the tree."""from __future__ import annotations+from bisect import bisect_left, bisect_rightfrom typing import TYPE_CHECKINGif TYPE_CHECKING:@@ -85,7 +86,7 @@ def _count_nloc(node: Node, source: bytes) -> int:Blank, comment-only and docstring-only lines are excluded, so a functionor class NLOC measures substance the same way file-level NLOC does- (``_count_file_nloc_tree``), rather than counting documentation as code.+ (``CodeLineIndex.file_nloc``), rather than counting documentation as code."""start = node.start_point[0]end = node.end_point[0]@@ -103,12 +104,86 @@ def _count_file_nloc(source: bytes) -> int:return sum(1 for line in text.splitlines() if line.strip())-def _count_file_nloc_tree(root_node: Node, source: bytes) -> int:- """Count lines that have at least one non-comment token.+class CodeLineIndex:+ """Every NLOC a walk asks for, answered from one descent of the file.- Lines where all content is inside comment nodes are excluded; lines- with real code plus a trailing comment still count.+ ``file_scan`` feeds it each code leaf once; function and class NLOC are then+ prefix-sum lookups instead of a fresh subtree walk per node, which re-read+ a nested function's leaves once per enclosing scope. ``file_nloc`` drops+ comment-only lines but keeps module and class docstrings, as file-level+ NLOC always has.++ ``count`` matches ``_count_nloc`` exactly. A node's leaves are the code+ leaves inside its byte span, so the lines strictly between its first and+ last covered line hold no leaf from outside it and come from the prefix+ sum; those two lines are covered by the node's own first and last leaf. A+ node inside a comment or docstring, whose file-wide exclusion is not the+ node's own, falls back to the subtree walk."""- # File-level NLOC keeps counting module/class docstrings (only comment-only- # lines are dropped), so ``drop_docstrings`` stays off here.- return len(_code_line_numbers(root_node, _source_lines(source), drop_docstrings=False))++ __slots__ = (+ "_code_prefix",+ "_excluded_ends",+ "_excluded_starts",+ "_leaf_end_rows",+ "_leaf_start_rows",+ "_leaf_starts",+ "_nonblank",+ "file_nloc",+ )++ def __init__(+ self,+ nonblank: list[bool],+ file_rows: set[int],+ code_rows: set[int],+ leaves: list[tuple[int, int, int]],+ excluded: list[tuple[int, int]],+ ) -> None:+ # *leaves* (start byte, start row, end row) and *excluded* (start byte,+ # end byte) arrive in the scan's right-to-left pre-order. Both are+ # disjoint spans, so reversing sorts them by start byte.+ leaves.reverse()+ excluded.reverse()+ self.file_nloc = len(file_rows)+ self._nonblank = nonblank+ self._leaf_starts = [leaf[0] for leaf in leaves]+ self._leaf_start_rows = [leaf[1] for leaf in leaves]+ self._leaf_end_rows = [leaf[2] for leaf in leaves]+ self._excluded_starts = [span[0] for span in excluded]+ self._excluded_ends = [span[1] for span in excluded]+ prefix = [0] * (len(nonblank) + 1)+ running = 0+ for row in range(len(nonblank)):+ if row in code_rows:+ running += 1+ prefix[row + 1] = running+ self._code_prefix = prefix++ def _code_rows_before(self, row: int) -> int:+ prefix = self._code_prefix+ return prefix[row] if row < len(prefix) else prefix[-1]++ def _is_code_row(self, row: int) -> int:+ return 1 if row < len(self._nonblank) and self._nonblank[row] else 0++ def count(self, node: Node, source: bytes) -> int:+ """``_count_nloc(node, source)`` without walking *node*'s subtree."""+ start_byte = node.start_byte+ end_byte = node.end_byte+ k = bisect_right(self._excluded_starts, start_byte) - 1+ if k >= 0 and self._excluded_ends[k] >= end_byte:+ return _count_nloc(node, source)+ if node.end_point[0] < node.start_point[0]:+ return 0+ first_leaf = bisect_left(self._leaf_starts, start_byte)+ end_leaf = bisect_left(self._leaf_starts, end_byte)+ if first_leaf >= end_leaf:+ return 0+ first = self._leaf_start_rows[first_leaf]+ last = self._leaf_end_rows[end_leaf - 1]+ count = self._is_code_row(first)+ if last > first:+ count += self._is_code_row(last)+ count += self._code_rows_before(last) - self._code_rows_before(first + 1)+ return countdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.pyindex f64ef36cf..5941043fa 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/perf_walk.py@@ -3,9 +3,9 @@io_in_loop / string_concat_in_loop / blocking_sync_in_async and the Phase-7loop-level / centrality-gated markers.-One whole-tree pass mirroring ``_collect_error_handling`` but carrying the-per-node context the perf signal needs: loop depth, in-async, lock depth, and-the enclosing function name. Two non-negotiable refinements (Phase-0 gate: they+One whole-tree pass, kept apart from the walker's shared ``file_scan`` because+it carries the per-node context the perf signal needs down the tree: loop depth,+in-async, lock depth, and the enclosing function name. Two non-negotiable refinements (Phase-0 gate: theytook precision from 49% to 79%) are baked in:1. Loop-BODY scoping — only calls under a loop node's ``body`` field runper-iteration; a call in the ``for x in <iterable>`` header runs once.@@ -24,7 +24,6 @@ from typing import TYPE_CHECKINGfrom ..perf.dialects import PERF_DIALECTSfrom ..perf.dialects.base import BasePerfDialect as BasePerfDialectClass-from ..perf.io_boundaries import collect_io_namesfrom ..perf.loop_facts import LoopFactsfrom .ast_utils import _dart_signature_sibling, _find_function_entry_name, _find_namefrom .languages import LanguageNodeMap@@ -207,8 +206,13 @@ def _is_block_loop_body_scope(return False+def perf_pass_runs(language: str, lmap: LanguageNodeMap) -> bool:+ """Whether ``_collect_perf_hits`` does anything for *language*."""+ return bool(lmap.call_kinds) and language in PERF_DIALECTS++def _collect_perf_hits(- root: Node, language: str, lmap: LanguageNodeMap+ root: Node, language: str, lmap: LanguageNodeMap, io_names: dict[str, str]) -> tuple[list[PerfHit], dict[str, str], list[PerfFnFacts]]:"""Whole-tree perf pass → ``(hits, io_boundary_names, fn_facts)``.@@ -220,16 +224,17 @@ def _collect_perf_hits(genuinely per-iteration calls are flagged. Returns nothing for languagesthat opt out of the perf pass (empty ``call_kinds``).+ *io_names* is ``perf.io_boundaries.collect_io_names`` for *root*, which the+ walker's shared file descent collects whenever ``perf_pass_runs``.+Alongside the same-function ``hits``, it accumulates ``fn_facts`` (one:class:`PerfFnFacts` per enclosing function that has any loop-nested callor a bare sink) — the input to PR4's cross-function reachability."""- call_kinds = lmap.call_kinds- dialect = PERF_DIALECTS.get(language)- if not call_kinds or dialect is None:+ if not perf_pass_runs(language, lmap):return [], {}, []-- io_names = collect_io_names(root, language)+ call_kinds = lmap.call_kinds+ dialect = PERF_DIALECTS[language]has_db_import = any(k == "db" for k in io_names.values())markers = dialect.markersdo_string_concat = "string_concat_in_loop" in markersdiff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex 4f71754f6..d886b206d 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -19,9 +19,11 @@ function. Module-level lambdas, such as route callbacks, produce theirown ``FunctionComplexity`` row.This module is the orchestrator: ``walk_file`` parses the source once and-drives the individual passes, each of which lives in its own sibling module:+drives the individual passes, each of which lives in its own sibling module.+The whole-file passes share one descent of the tree (``file_scan``):- ``models``: the output dataclasses+- ``file_scan``: the shared descent: NLOC index, error handling, classes- ``ast_utils``: name/text helpers, function-node collection, params- ``nloc``: non-blank / non-comment line counting- ``cyclomatic``: the CCN / cognitive / nesting engine@@ -37,8 +39,6 @@ drives the individual passes, each of which lives in its own sibling module:from __future__ import annotations-from typing import TYPE_CHECKING-import structlogfrom ..asserts.lexicon import assert_dialect as _assert_dialect@@ -53,13 +53,9 @@ from .class_analysis import _collect_classesfrom .cyclomatic import _walk_function_bodyfrom .deprecation import is_deprecatedfrom .dispatch import dispatch_points, dispatch_share-from .error_handling import _collect_error_handling, _eh_rust_attr_is_test+from .file_scan import scan_filefrom .languages import get_language_mapfrom .mock_walk import _count_mock_setup, file_may_contain_mocks-from .test_case import is_test_case--if TYPE_CHECKING:- from tree_sitter import Node# Re-exported so the package façade (``__init__``) and downstream consumers# keep importing the output schema from ``complexity.walker`` unchanged.@@ -76,8 +72,9 @@ from .models import (# ``_count_file_nloc`` is re-exported for ``tests/unit/health/test_file_nloc.py``,# which imports it directly from this module.-from .nloc import _count_file_nloc, _count_file_nloc_tree, _count_nloc-from .perf_walk import _collect_perf_hits+from .nloc import _count_file_nloc+from .perf_walk import _collect_perf_hits, perf_pass_runs+from .test_case import is_test_case__all__ = ["ClassComplexity",@@ -162,6 +159,8 @@ def walk_file(# which leaves the narrow tier alone and is what every language counted# before this existed.asserts = _assert_dialect(language, extra_assert_names)+ run_perf = perf_pass_runs(language, lmap)+ scan = scan_file(tree.root_node, language, lmap, source, io_names=run_perf)for fn_node in _collect_function_nodes(tree.root_node, lmap):body = fn_node.child_by_field_name("body") or fn_nodedeepest: list[int] = []@@ -182,7 +181,7 @@ def walk_file(ccn=ccn,max_nesting=max_nest,cognitive=cognitive,- nloc=_count_nloc(body, source),+ nloc=scan.lines.count(body, source),bumps=bumps,param_count=_count_parameters(fn_node),complex_conditions=conditions,@@ -201,18 +200,20 @@ def walk_file(functions.append(fc)fc_by_node_id[fn_node.id] = fc- classes = _collect_classes(tree.root_node, lmap, source, fc_by_node_id)- perf_hits, io_boundary_names, perf_fn_facts = _collect_perf_hits(tree.root_node, language, lmap)+ classes = _collect_classes(scan.class_nodes, lmap, source, fc_by_node_id, scan.lines)+ perf_hits, io_boundary_names, perf_fn_facts = _collect_perf_hits(+ tree.root_node, language, lmap, scan.io_names+ )return FileComplexity(functions=functions,classes=classes,- file_nloc=_count_file_nloc_tree(tree.root_node, source),- error_handling_hits=_collect_error_handling(tree.root_node, language, lmap),+ file_nloc=scan.lines.file_nloc,+ error_handling_hits=scan.error_handling_hits,perf_hits=perf_hits,io_boundary_names=io_boundary_names,perf_fn_facts=perf_fn_facts,has_inline_tests=_detect_inline_tests(source, language),- rust_test_line_ranges=_rust_test_line_ranges(tree.root_node, language),+ rust_test_line_ranges=scan.rust_test_line_ranges,)@@ -245,56 +246,3 @@ def _detect_inline_tests(source: bytes, language: str) -> bool:if language != "rust":return Falsereturn any(marker in source for marker in _RUST_INLINE_TEST_MARKERS)---# ``function_item`` / ``mod_item`` / ``impl_item`` are the Rust item kinds a-# ``#[cfg(test)]`` (or ``#[test]`` / ``#[tokio::test]`` / ``#[rstest]``, for a-# bare fn) attribute can gate. ``mod``/``impl`` are containers: their whole-# span is test-only once gated, including any nested fn that carries no-# attribute of its own — the same reason ``#[cfg(test)] mod tests { .. }``-# hides ordinary-looking helper fns from the file-level heuristic above.-_RUST_TEST_ITEM_KINDS = ("function_item", "mod_item", "impl_item")---def _rust_test_line_ranges(root: Node, language: str) -> tuple[tuple[int, int], ...]:- """1-indexed ``(start_line, end_line)`` spans of Rust test-only code.-- Walks the SAME tree ``walk_file`` already parsed (no extra parse). Marks a- ``mod_item`` / ``impl_item`` / ``function_item`` whose immediately- preceding attribute siblings include a test marker- (:func:`repowise.core.analysis.health.complexity.error_handling._eh_rust_attr_is_test`,- shared with the error-handling walker so both passes recognize the- identical attribute grammar), and does not descend into a marked node —- its span already covers everything nested inside. Rust-only; every other- language gets ``()``, so :func:`repowise.core.analysis.health.perf.gated._in_rust_test_range`- is a no-op for it.- """- if language != "rust":- return ()-- ranges: list[tuple[int, int]] = []-- def _text(node: Node) -> str:- return (node.text or b"").decode("utf-8", errors="replace")-- def _is_marked(node: Node) -> bool:- sib = node.prev_sibling- while sib is not None and sib.type in (- "attribute_item",- "line_comment",- "block_comment",- ):- if sib.type == "attribute_item" and _eh_rust_attr_is_test(_text(sib)):- return True- sib = sib.prev_sibling- return False-- def _walk(node: Node) -> None:- if node.type in _RUST_TEST_ITEM_KINDS and _is_marked(node):- ranges.append((node.start_point[0] + 1, node.end_point[0] + 1))- return # span already covers every nested item; don't descend- for child in node.children:- _walk(child)-- _walk(root)- return tuple(ranges)diff --git a/packages/core/src/repowise/core/analysis/health/perf/gated.py b/packages/core/src/repowise/core/analysis/health/perf/gated.pyindex a15dda630..c7b5aec81 100644--- a/packages/core/src/repowise/core/analysis/health/perf/gated.py+++ b/packages/core/src/repowise/core/analysis/health/perf/gated.py@@ -43,7 +43,7 @@ def _in_rust_test_range(line: int, ranges: tuple[tuple[int, int], ...]) -> bool:*ranges* is ``FileComplexity.rust_test_line_ranges``, computed once perfile by the walker from the tree it already parsed (see- ``complexity.walker._rust_test_line_ranges``) — empty for every language+ ``complexity.file_scan.scan_file``) — empty for every languagebut Rust, so this is a no-op everywhere else. Checked here, at the singlechoke point both centrality-gated markers share, so a function inside a``#[cfg(test)] mod`` / ``#[test]`` fn — invisible to the file-leveldiff --git a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.pyindex 7f1798b26..af1be1462 100644--- a/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py+++ b/packages/core/src/repowise/core/analysis/health/perf/io_boundaries.py@@ -127,75 +127,92 @@ def collect_io_names(tree_root: _NodeLike, language: str) -> dict[str, str]:A whole-tree scan of import nodes (import statements live at module scopebut a defensive full walk also catches function-local imports). Names that- do not originate from a classified I/O library are simply absent.+ do not originate from a classified I/O library are simply absent. The+ complexity walker runs the same :func:`_io_visit` from its shared file+ descent instead of calling this."""names: dict[str, str] = {}- # Names rebound by a plain local assignment (``requests = {...}``) that- # shadows the import. ``sink_kind`` has no call-site position, so full- # per-scope resolution would need a walker rewrite; instead we drop any- # import name that is also an assignment target *anywhere* in the file. That- # is coarser than true scoping (it also suppresses a genuine ``requests.get``- # in a file that rebinds ``requests`` elsewhere — a recall trade for- # precision), but closes the shadowed-receiver false flag with no new pass.rebound: set[str] = set()stack: list[_NodeLike] = [tree_root]while stack:node = stack.pop()- # ``import`` covers Python / TS / Java / Go import nodes; C# spells its- # import a ``using_directive`` (and Go an ``import_spec``), Rust a- # ``use_declaration`` — none of which contains the substring "import".- if node.type == "call" and language == "ruby":- # Ruby's import statement is a method call: ``require "net/http"``.- # Classify the quoted feature path; its segments bind lowercase- # (``net`` / ``httparty``), which the Ruby dialect normalises its- # constant receivers against. ``require_relative`` paths are local- # files and never classify — harmless to run through the table.- method = (- node.child_by_field_name("method") if hasattr(node, "child_by_field_name") else None- )- if method is not None and (method.text or b"") in (b"require", b"require_relative"):- kind, bound = _classify_import(node)- if kind is not None:- for name in bound:- names.setdefault(name, kind)- elif node.type == "declUses" and language == "pascal":- # Pascal's ``uses`` clause is one flat node listing every unit- # (``uses SysUtils, Classes, IdHTTP;``), unlike Go's grouped- # import which nests a per-line ``import_spec`` leaf. Classifying- # the whole node would pick whichever unit's kind resolves first- # out of an unordered set and bind ALL of them to it (so- # ``IdHTTP`` could inherit ``db`` from a ``FireDAC`` listed in the- # same clause) -- so each ``moduleName`` child is classified on- # its own instead.- for child in node.children:- if child.type != "moduleName":- continue- kind, bound = _classify_import(child)- if kind is not None:- for name in bound:- names.setdefault(name, kind)- elif "import" in node.type or node.type in ("using_directive", "use_declaration"):- # Classify only the *leaf* import node. A Go grouped- # ``import ( "database/sql"; "regexp" )`` is an ``import_declaration``- # wrapping per-line ``import_spec`` leaves; classifying the wrapper- # binds every name in the block to whichever line resolves first- # (so ``regexp`` would inherit ``db``). Skip a node that contains a- # nested import-spec — its children carry the scoped truth.- has_spec_child = any("import_spec" in c.type for c in node.children)- if not has_spec_child:- kind, bound = _classify_import(node)- if kind is not None:- for name in bound:- names.setdefault(name, kind)- elif node.type == "assignment":- # Python assignment target; ``x = ...`` shadows an imported ``x``.- target = (- node.child_by_field_name("left") if hasattr(node, "child_by_field_name") else None- )- if target is not None and target.type == "identifier" and target.text is not None:- rebound.add(target.text.decode("utf-8", "replace"))+ _io_visit(node, node.type, language, names, rebound)for child in node.children:stack.append(child)+ return _finish_io_names(names, rebound)+++def _io_visit(+ node: _NodeLike, node_type: str, language: str, names: dict[str, str], rebound: set[str]+) -> None:+ """Bind the I/O names an import at *node* brings in, or note a rebinding.++ *rebound* collects names rebound by a plain local assignment+ (``requests = {...}``) that shadows the import. ``sink_kind`` has no+ call-site position, so full per-scope resolution would need a walker+ rewrite; instead :func:`_finish_io_names` drops any import name that is+ also an assignment target *anywhere* in the file. That is coarser than true+ scoping (it also suppresses a genuine ``requests.get`` in a file that+ rebinds ``requests`` elsewhere, a recall trade for precision), but closes+ the shadowed-receiver false flag with no new pass.+ """+ # ``import`` covers Python / TS / Java / Go import nodes; C# spells its+ # import a ``using_directive`` (and Go an ``import_spec``), Rust a+ # ``use_declaration`` — none of which contains the substring "import".+ if node_type == "call" and language == "ruby":+ # Ruby's import statement is a method call: ``require "net/http"``.+ # Classify the quoted feature path; its segments bind lowercase+ # (``net`` / ``httparty``), which the Ruby dialect normalises its+ # constant receivers against. ``require_relative`` paths are local+ # files and never classify — harmless to run through the table.+ method = (+ node.child_by_field_name("method") if hasattr(node, "child_by_field_name") else None+ )+ if method is not None and (method.text or b"") in (b"require", b"require_relative"):+ kind, bound = _classify_import(node)+ if kind is not None:+ for name in bound:+ names.setdefault(name, kind)+ elif node_type == "declUses" and language == "pascal":+ # Pascal's ``uses`` clause is one flat node listing every unit+ # (``uses SysUtils, Classes, IdHTTP;``), unlike Go's grouped+ # import which nests a per-line ``import_spec`` leaf. Classifying+ # the whole node would pick whichever unit's kind resolves first+ # out of an unordered set and bind ALL of them to it (so+ # ``IdHTTP`` could inherit ``db`` from a ``FireDAC`` listed in the+ # same clause) -- so each ``moduleName`` child is classified on+ # its own instead.+ for child in node.children:+ if child.type != "moduleName":+ continue+ kind, bound = _classify_import(child)+ if kind is not None:+ for name in bound:+ names.setdefault(name, kind)+ elif "import" in node_type or node_type in ("using_directive", "use_declaration"):+ # Classify only the *leaf* import node. A Go grouped+ # ``import ( "database/sql"; "regexp" )`` is an ``import_declaration``+ # wrapping per-line ``import_spec`` leaves; classifying the wrapper+ # binds every name in the block to whichever line resolves first+ # (so ``regexp`` would inherit ``db``). Skip a node that contains a+ # nested import-spec — its children carry the scoped truth.+ has_spec_child = any("import_spec" in c.type for c in node.children)+ if not has_spec_child:+ kind, bound = _classify_import(node)+ if kind is not None:+ for name in bound:+ names.setdefault(name, kind)+ elif node_type == "assignment":+ # Python assignment target; ``x = ...`` shadows an imported ``x``.+ target = (+ node.child_by_field_name("left") if hasattr(node, "child_by_field_name") else None+ )+ if target is not None and target.type == "identifier" and target.text is not None:+ rebound.add(target.text.decode("utf-8", "replace"))+++def _finish_io_names(names: dict[str, str], rebound: set[str]) -> dict[str, str]:+ """*names* without the ones a plain assignment rebinds (see :func:`_io_visit`)."""for name in rebound:names.pop(name, None)return namesdiff --git a/tests/unit/health/test_file_scan.py b/tests/unit/health/test_file_scan.pynew file mode 100644index 000000000..83d162faf--- /dev/null+++ b/tests/unit/health/test_file_scan.py@@ -0,0 +1,111 @@+"""The walker's single file descent answers what the per-node walks did.++``CodeLineIndex.count`` replaces a subtree walk per function and class, so it+is checked against that walk (``_count_nloc``, kept as the reference) on every+named node of every fixture, including nodes inside comments and docstrings,+which take the fallback.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.complexity.file_scan import scan_file+from repowise.core.analysis.health.complexity.languages import get_language_map+from repowise.core.analysis.health.complexity.nloc import (+ _code_line_numbers,+ _count_nloc,+ _source_lines,+)+from repowise.core.ingestion.models import EXTENSION_TO_LANGUAGE++FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "lang_samples"++_SNIPPETS = {+ "python": (+ b'"""Module docstring."""\n'+ b"def outer(a): # trailing comment on the def line\n"+ b' """Docstring\n\n spanning lines."""\n'+ b" # a comment-only line\n"+ b"\n"+ b" def inner():\n"+ b' "only a docstring"\n'+ b" x = '''multi\n\n line'''\n"+ b" if a:\n"+ b' "a bare string opening a block"\n'+ b" return lambda: (yield)\n"+ b" return x\r\n"+ b"class K:\n"+ b' """Class doc."""\n'+ b" def m(self): return 1\n"+ ),+ "typescript": (+ b"/** header */\n"+ b"export function f(a: number) { // note\n"+ b" const g = () => {\n"+ b" /* block\n comment */\n"+ b" return a;\n"+ b" };\n"+ b" return `tmpl\n\n ${a}`;\n"+ b"}\n"+ b"class C { m() { return 1; } }\n"+ ),+}+++def _parse(path: str, language: str, source: bytes):+ from tree_sitter import Parser++ from repowise.core.ingestion.parser import _get_language, grammar_tag_for+ from repowise.core.ingestion.sfc_source import prepare_source++ grammar = _get_language(grammar_tag_for(language, path))+ if grammar is None:+ pytest.skip(f"{language} tree-sitter pack missing")+ return Parser(grammar).parse(prepare_source(language, source, path=path))+++def _cases():+ for path in sorted(FIXTURES.rglob("*")):+ language = EXTENSION_TO_LANGUAGE.get(path.suffix.lower())+ if path.is_file() and language and get_language_map(language) is not None:+ yield pytest.param(str(path), language, path.read_bytes(), id=path.name)+ for language, source in _SNIPPETS.items():+ suffix = ".py" if language == "python" else ".ts"+ yield pytest.param(f"snippet{suffix}", language, source, id=f"snippet-{language}")++[email protected](("path", "language", "source"), list(_cases()))+def test_line_index_matches_the_subtree_walk_on_every_node(path, language, source):+ tree = _parse(path, language, source)+ scan = scan_file(tree.root_node, language, get_language_map(language), source, io_names=False)+ root = tree.root_node+ assert scan.lines.file_nloc == len(+ _code_line_numbers(root, _source_lines(source), drop_docstrings=False)+ )+ stack = [root]+ while stack:+ node = stack.pop()+ stack.extend(node.children)+ if node.is_named:+ assert scan.lines.count(node, source) == _count_nloc(node, source), (+ node.type,+ node.start_point,+ )+++def test_rust_test_spans_come_back_in_source_order():+ source = (+ b"#[cfg(test)]\nmod a {\n #[test]\n fn t() {}\n}\n"+ b"fn prod() {}\n"+ b"#[test]\nfn b() {}\n"+ )+ fcx = walk_file("t.rs", "rust", source)+ if not fcx.functions:+ pytest.skip("rust tree-sitter pack missing")+ # The nested ``#[test] fn t`` sits inside ``mod a``'s span and is not+ # recorded again.+ assert fcx.rust_test_line_ranges == ((2, 5), (8, 8))