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
fix(health): keep dormant and dead code out of Fix first and the perf queue (#3253)
Raghav Chamadiyab30d96d9fd29
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.mdindex ab0a43021..dedab112a 100644--- a/docs/architecture/code-health.md+++ b/docs/architecture/code-health.md@@ -664,6 +664,8 @@ reason:| `below_min_worth` | A refactoring recovering under `MIN_WORTH` (0.5) or with no steps; a loop-built string that is bounded or not in production || `history_only` | Only git-history findings || `deprecated` | Deprecated functions |+| `gated_off` | Functions a same-file constant-false flag switches off (`complexity/gating.py`): the body opens with `if not FLAG: return` or is one `if FLAG:` block. For performance this is the opportunity state `expected` with reason `gated_off`, and the default queue counts it under `gated_off`. `totals.dormant` counts the distinct functions |+| `unreachable` | Targets an open dead-code finding with confidence 0.8 or more, or marked safe to delete, covers: the whole file, the symbol's lines, or its name || `inherent_dispatch` | One dispatch holds 60% or more of the decision points (labels: 8 of 9 such rows rejected), unless a duplicate also sits in it || `small_function` | Under 30 code lines and CCN 15 (on 67 labelled rows this cut drops 13 rejected and 4 accepted) || `no_concrete_step` | No first edit with a file and line or a named group |diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 42abdc730..3a629f8ea 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -190,7 +190,16 @@ edit, the expected gain, the effort and the tests to run afterwards.What stays out, and is counted as excluded with a reason: test files, tooling,generated and vendored code, docs and examples, files whose only findings comefrom git history, changes that would recover under half a point, items with no-concrete first edit, and kinds that reviewers found not worth doing.+concrete first edit, kinds that reviewers found not worth doing, code a sure+dead-code finding covers (the fix is to delete it), and functions a constant flag+switches off. A function counts as switched off when its body opens with+`if not FLAG: return ...` (or is one `if FLAG:` block) and `FLAG` is a+module-level `False`, `0` or `None` (`const FLAG = false` in TypeScript or+JavaScript) that nothing in the same file assigns again. Those functions are+counted as **dormant** next to the excluded totals rather than dropped silently.+Only the file itself is read: a flag imported from another module, or flipped+from outside with `setattr` or a test's monkeypatch, still reads as off, and the+function is counted as dormant, not hidden.Items rank by value first (health recovered, or how far the code sits past sizeand complexity bars), then by tier: `now` (worth doing, safe to start), `next`@@ -237,7 +246,8 @@ Findings group into **opportunities**, one per place you would edit (the functioholding the loop, or a helper every caller goes through). Each opportunity carriesone state: `plan_ready` (a proven fix strategy), `advisory` (a strategy withunproven prerequisites), `investigate` (no supported strategy) or `expected` (the-repetition is real and nothing should change, such as deleting N files). The+repetition is real and nothing should change, such as deleting N files, or the+function that holds it is switched off by a constant flag, reason `gated_off`). Thedefault queue holds production `plan_ready` and `advisory` opportunities, ranked bycost first; state only breaks ties. Everything left out is counted by reason.diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.mdindex 39e24904b..70d87e159 100644--- a/docs/layers/REFACTORING.md+++ b/docs/layers/REFACTORING.md@@ -90,8 +90,9 @@ the code needs no attention: check the findings inBy default the open, repository-wide list shows only what[Fix first](CODE_HEALTH.md#fix-first) would take: opportunities in shipped code-that recover real health and name a concrete edit. The response counts the rest-and the reasons they were held back. Ask for the full inventory with `scope=all`+that recover real health and name a concrete edit, outside dead code and outside+functions a constant flag switches off. The response counts the rest and the+reasons they were held back. Ask for the full inventory with `scope=all`(MCP: `refactoring_scope="all"`; dashboard: **Full inventory**). A call that namesa file, or a triaged status, gets the full inventory automatically.diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex a0cd508e3..32a966cd3 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -329,7 +329,7 @@ One ranked queue across refactoring, performance and code-shape work, the same o| `items` | Up to five: `id`, `tier`, `kind`, `title`, `target`, `why`, `gain`, `effort`, `confidence`, `next_call` || `tier` | `now` (worth doing, safe to start), `next` (worth doing, needs judgment), `later` || `kind` | `refactor` (one file's composed refactoring), `perf_fix` (one intervention with its sinks), `finding` (a code-shape finding with no plan) |-| `totals` | `candidates`, `eligible`, `shown`, and `excluded` counted by reason |+| `totals` | `candidates`, `eligible`, `shown`, `excluded` counted by reason (`gated_off`: a constant flag in the same file switches the function off; `unreachable`: sure dead code, delete it), and `dormant`: distinct functions kept out as `gated_off` || `by_improves`, `basis`, `model_version`, `detail_call` | Rollup, basis, and the call that opens the lead in full |Items are ordered by value first, then tier. History markers (churn, ownership, co-change, prior fixes) never create or lead an item; they ride on an item under `context`, and history-only files count under `totals.excluded.history_only`. `fix_first` always describes production code, whatever `scope` says; `limit` caps the items, never which leads.diff --git a/packages/core/src/repowise/core/analysis/change_health/service.py b/packages/core/src/repowise/core/analysis/change_health/service.pyindex 7a12b209c..eaa42ba6b 100644--- a/packages/core/src/repowise/core/analysis/change_health/service.py+++ b/packages/core/src/repowise/core/analysis/change_health/service.py@@ -482,12 +482,22 @@ def _priority(finding: ChangeFinding) -> tuple:)+#: What an ``expected`` cause says, by its actionability reason.+_INHERENT = "Nothing to change: the repetition is inherent or already batched."+_EXPECTED_TEXT: dict[str | None, str] = {+ "inherent_to_boundary": _INHERENT,+ "loop_already_chunked": _INHERENT,+ "gated_off": "Nothing to change while a constant-False flag switches this function off.",+ None: _INHERENT,+}++def _suggestion(finding: HealthFindingData, perf: PerfOpportunityView | None) -> str:if perf is not None:if perf.actionability_state == "plan_ready" and perf.intervention_symbol:return f"Hoist or batch the repeated call in {perf.intervention_symbol}."if perf.actionability_state == "expected":- return "Nothing to change: the repetition is inherent or already batched."+ return _EXPECTED_TEXT.get(perf.actionability_reason, _EXPECTED_TEXT[None])return perf.actionability_reason or "Confirm the cost before changing it."return finding.reason or f"Review the {finding.biomarker_type.replace('_', ' ')}."diff --git a/packages/core/src/repowise/core/analysis/health/complexity/gating.py b/packages/core/src/repowise/core/analysis/health/complexity/gating.pynew file mode 100644index 000000000..9a07119a9--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/gating.py@@ -0,0 +1,199 @@+"""Whether a function is switched off by a constant flag in its own file.++A function whose body opens with ``if not FLAG: return ...`` (or is one+``if FLAG:`` block), where ``FLAG`` is a module-level ``False`` / ``0`` /+``None`` that nothing in the file assigns again, runs none of its work. A+finding on that work is real but dormant: nothing to fix while the switch is+off. Python and TypeScript / JavaScript (``const FLAG = false``).++Ceiling: same file only. A flag imported from another module, or one a test+flips with ``monkeypatch`` (the usual way a kill switch is exercised), is read+as the file says. Upgrade path: resolve the imported name through the graph.+"""++from __future__ import annotations++import re+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from tree_sitter import Node++#: Literal kinds that make a module constant falsy, and those that are ``False`` itself.+_FALSY = frozenset({"false", "none", "null", "undefined", "integer", "number"})+_FALSE = frozenset({"false"})+_ECMASCRIPT = frozenset({"typescript", "tsx", "javascript", "jsx", "svelte", "vue"})+#: Plain assignments a guard may follow (``summary = {...}`` before the ``if``).+_LEAD_STATEMENTS = 2+_DECLARATIONS = frozenset({"lexical_declaration", "variable_declaration"})+_ASSIGNMENTS = frozenset({"assignment", "assignment_expression"})+#: Node kinds that do work: an assignment holding one is no plain assignment.+_WORK = frozenset(+ {"call", "call_expression", "new_expression", "await", "await_expression", "yield"}+)+#: A line this long is minified or generated: read as written rather than scanned.+_LONG_LINE = 2000+++def _text(node: Node) -> str:+ return (node.text or b"").decode("utf-8", errors="replace")+++def _falsy_literal(node: Node | None) -> str | None:+ """``"false"`` for a ``False`` literal, ``"falsy"`` for ``0`` / ``None``, else ``None``."""+ if node is None or node.type not in _FALSY:+ return None+ if node.type in ("integer", "number") and _text(node).strip() != "0":+ return None+ return "false" if node.type in _FALSE else "falsy"+++def _declared(root: Node, language: str) -> dict[str, str]:+ """Module-level ``NAME = <falsy literal>`` (Python) or ``const NAME = ...`` (TS/JS)."""+ out: dict[str, str] = {}+ for stmt in root.named_children:+ if stmt.type == "export_statement":+ stmt = stmt.child_by_field_name("declaration") or stmt+ node = stmt.named_children[0] if stmt.named_children else None+ if language == "python" and node is not None and node.type == "assignment":+ pairs = [(node.child_by_field_name("left"), node.child_by_field_name("right"))]+ elif stmt.type == "lexical_declaration" and stmt.children[0].type == "const":+ pairs = [+ (d.child_by_field_name("name"), d.child_by_field_name("value"))+ for d in stmt.named_children+ if d.type == "variable_declarator"+ ]+ else:+ continue+ for name, value in pairs:+ kind = _falsy_literal(value)+ if name is not None and name.type == "identifier" and kind:+ out[_text(name)] = kind+ return out+++def _written_again(name: str, source: str) -> bool:+ """Any line besides the declaration that could assign *name*.++ A text scan, deliberately loose: a keyword argument or a local of the same+ name reads as a write, which only keeps a function in the queue.+ """+ if any(len(line) > _LONG_LINE for line in source.splitlines()):+ return True+ word = re.escape(name)+ write = re.compile(+ rf"\b(?:global|nonlocal|for|as)\b[^\n]*\b{word}\b"+ rf"|\b{word}\b[^\n=]*(?<![=!<>])=(?!=)"+ rf"|\b{word}\s*(?::=|\+\+|--)"+ )+ return len(write.findall(source)) > 1+++def module_false_constants(root: Node, source: bytes, language: str) -> dict[str, str]:+ """Module constants that are falsy and never assigned again, by name.++ Reads the root's own statements, so it costs no walk of its own.+ """+ if language != "python" and language not in _ECMASCRIPT:+ return {}+ declared = _declared(root, language)+ if not declared:+ return {}+ text = source.decode("utf-8", errors="replace")+ return {name: kind for name, kind in declared.items() if not _written_again(name, text)}+++def _unwrap(node: Node | None) -> Node | None:+ while node is not None and node.type == "parenthesized_expression" and node.named_children:+ node = node.named_children[0]+ return node+++def _negates(cond: Node, consts: dict[str, str]) -> bool:+ """``not FLAG`` / ``!FLAG`` for any falsy flag; ``FLAG is False`` /+ ``== false`` for a ``False`` one."""+ if cond.type in ("not_operator", "unary_expression"):+ arg = _unwrap(cond.child_by_field_name("argument"))+ operator = cond.child_by_field_name("operator")+ bang = cond.type == "not_operator" or (operator is not None and _text(operator) == "!")+ return bang and arg is not None and arg.type == "identifier" and _text(arg) in consts+ if cond.type in ("comparison_operator", "binary_expression"):+ named = cond.named_children+ ops = {_text(c) for c in cond.children if not c.is_named}+ return (+ len(named) == 2+ and named[0].type == "identifier"+ and consts.get(_text(named[0])) == "false"+ and named[1].type in _FALSE+ and len(ops) == 1+ and ops <= {"is", "==", "==="}+ )+ return False+++def _only_returns(block: Node | None) -> bool:+ if block is None:+ return False+ if block.type == "return_statement":+ return True+ body = [c for c in block.named_children if "comment" not in c.type]+ return len(body) == 1 and body[0].type == "return_statement"+++def _plain_assignment(stmt: Node) -> bool:+ """An assignment or declaration that calls nothing: ``summary = {...}``."""+ if stmt.type == "expression_statement":+ named = stmt.named_children+ if len(named) != 1 or named[0].type not in _ASSIGNMENTS:+ return False+ elif stmt.type not in _DECLARATIONS:+ return False+ stack = [stmt]+ while stack:+ node = stack.pop()+ if node.type in _WORK:+ return False+ stack.extend(node.named_children)+ return True+++def _statements(body: Node) -> list[Node]:+ """The body's statements, a leading docstring left out."""+ named = [c for c in body.named_children if "comment" not in c.type]+ first = named[0] if named else None+ if (+ first is not None+ and first.type == "expression_statement"+ and first.named_children+ and first.named_children[0].type == "string"+ ):+ named = named[1:]+ return named+++def is_gated_off(body: Node, consts: dict[str, str]) -> bool:+ """Whether the body returns at once behind, or sits wholly inside, a constant-false flag."""+ if not consts:+ return False+ stmts = _statements(body)+ if len(stmts) == 1 and stmts[0].type == "if_statement":+ cond = _unwrap(stmts[0].child_by_field_name("condition"))+ if (+ cond is not None+ and cond.type == "identifier"+ and _text(cond) in consts+ and stmts[0].child_by_field_name("alternative") is None+ ):+ return True+ for stmt in stmts[: _LEAD_STATEMENTS + 1]:+ if stmt.type == "if_statement":+ cond = _unwrap(stmt.child_by_field_name("condition"))+ return (+ cond is not None+ and _negates(cond, consts)+ and _only_returns(stmt.child_by_field_name("consequence"))+ and stmt.child_by_field_name("alternative") is None+ )+ if not _plain_assignment(stmt):+ return False+ return Falsediff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex 6eacb2005..d6b25ebfb 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -121,6 +121,9 @@ class FunctionComplexity:# True when the declaration is marked deprecated or the body's top level# issues a deprecation warning. ``complexity/deprecation.py``.deprecated: bool = False+ # True when the body returns at once behind, or sits wholly inside, a+ # module constant that is ``False`` in this file. ``complexity/gating.py``.+ gated_off: bool = False# 1-indexed (start, end) lines of the first block that reaches# ``max_nesting``, when the function nests at all: the concrete place to# start flattening it. ``cyclomatic._walk_function_body``.diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex 25f18b0a1..a746066c5 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -31,6 +31,7 @@ The whole-file passes share one descent of the tree (``file_scan``):- ``test_case``: whether a walked function is a test case- ``dispatch``: how much of the CCN is one dispatch on one value- ``deprecation``: whether a function is marked deprecated+- ``gating``: whether a constant-false flag switches a function off- ``mock_walk``: per-function mock-setup counting (test-quality)- ``error_handling``: error-handling anti-patterns- ``perf_walk``: the performance-risk pass@@ -55,6 +56,7 @@ from .cyclomatic import _walk_function_bodyfrom .deprecation import is_deprecatedfrom .dispatch import dispatch_points, dispatch_sharefrom .file_scan import scan_file+from .gating import is_gated_off, module_false_constantsfrom .languages import get_language_mapfrom .mock_walk import _count_mock_setup, file_may_contain_mocks@@ -163,6 +165,7 @@ def walk_file(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)+ flags = module_false_constants(tree.root_node, source, language)for fn_node in _collect_function_nodes(tree.root_node, lmap):body = fn_node.child_by_field_name("body") or fn_nodedeepest: list[int] = []@@ -204,6 +207,7 @@ def walk_file(dispatch_share=dispatch_share(dispatch.points, ccn),dispatch_arm=dispatch.arm,deprecated=is_deprecated(fn_node, body, name, lmap, source),+ gated_off=body is not fn_node and is_gated_off(body, flags),deepest_block=(deepest[0], deepest[1]) if deepest else None,)functions.append(fc)diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex 0061adaef..ba54a4377 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -389,24 +389,30 @@ log = structlog.get_logger(__name__)HEALTH_ANALYZER_VERSION = 39-def _mark_deprecated(+#: Function facts a finding inside the function carries in its details.+_FUNCTION_FACTS = ("deprecated", "gated_off")+++def _mark_function_facts(findings: list[HealthFindingData], functions: list[FunctionComplexity]) -> None:- """Stamp ``deprecated: true`` on each function-level finding inside a- deprecated function. Absent, not false, everywhere else, so the details of- every other finding are byte-for-byte what they were."""- spans = [(fc.name, fc.start_line, fc.end_line) for fc in functions if fc.deprecated]- if not spans:- return+ """Stamp ``deprecated: true`` / ``gated_off: true`` on each function-level+ finding inside a function with that fact. Absent, not false, everywhere+ else, so the details of every other finding are byte-for-byte what they+ were."""+ spans = [+ (fact, fc.name, fc.start_line, fc.end_line)+ for fc in functions+ for fact in _FUNCTION_FACTS+ if getattr(fc, fact, False)+ ]for finding in findings:if finding.function_name is None:continueline = finding.line_start- if any(- name == finding.function_name and (line is None or start <= line <= end)- for name, start, end in spans- ):- finding.details["deprecated"] = True+ for fact, name, start, end in spans:+ if name == finding.function_name and (line is None or start <= line <= end):+ finding.details[fact] = True#: Function-size findings whose fix starts at the deepest nested block.@@ -1637,7 +1643,7 @@ class HealthAnalyzer:findings = attach_impacts(biomarker_results, deductions)for f in findings:f.file_path = file_path- _mark_deprecated(findings, fc_list)+ _mark_function_facts(findings, fc_list)_stamp_symbol_lines(findings, fcx)_mark_deepest_block(findings, fc_list)diff --git a/packages/core/src/repowise/core/analysis/health/finding_identity.py b/packages/core/src/repowise/core/analysis/health/finding_identity.pyindex 8d777d4d6..1a1dc2c30 100644--- a/packages/core/src/repowise/core/analysis/health/finding_identity.py+++ b/packages/core/src/repowise/core/analysis/health/finding_identity.py@@ -77,6 +77,7 @@ _DERIVED_DETAIL_KEYS = frozenset("reliable_entry_reachability","dispatch_share","deprecated",+ "gated_off","loop_line","deepest_block",}diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.pyindex a28f1757f..cd983528b 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py@@ -20,7 +20,8 @@ Row shapes (field names are the SQL columns):``line_start``, ``line_end``, ``reason``, ``health_impact``, ``public_id``,``dimension``, ``status`` (absent = open), and ``details`` /``details_json`` (``ccn``, ``nloc``, ``max_nesting``) for the numbers a- sentence quotes, and ``deprecated`` for a function on its way out.+ sentence quotes, ``deprecated`` for a function on its way out and+ ``gated_off`` for one a constant-false flag switches off.``refactoring``The ``refactoring_opportunities`` columns, ``details`` (or``details_json``) carrying ``steps``, ``validation_profiles``,@@ -39,6 +40,11 @@ Row shapes (field names are the SQL columns):``target_symbol`` can give a finding with no plan of its own its firstconcrete step. Every Extract Helper plan's occurrences say where verifiedduplicates sit.+``dead_code``+ ``dead_code_findings`` rows: ``kind``, ``file_path``, ``symbol_name``,+ ``start_line``, ``end_line``, ``confidence``, ``safe_to_delete``,+ ``status``. A unit an open row of :data:`DEAD_CONFIDENCE` or more (or one+ safe to delete) covers is ``unreachable``: the fix is to delete it."""from __future__ import annotations@@ -66,6 +72,7 @@ from repowise.core.analysis.health.worth import (SIZE_MARKERS,WORTH_MAGNITUDE,dispatch_shaped,+ dormant,low_priority,magnitude,measure,@@ -103,6 +110,8 @@ from .model import ()Rows = Iterable[Any]+#: A dead-code finding's ``(symbol, start line, end line)``; no symbol for a whole file.+DeadSpan = tuple[str | None, int | None, int | None]#: A refactoring whose credited gain is under this is not worth an item. The#: refactoring model credits only the share of a finding a plan removes and@@ -138,6 +147,9 @@ DEFAULT_LIMIT = 10#: drops more than 4 rejected.SMALL_NLOC = 30SMALL_CCN = 15+#: A dead-code finding this sure (or marked safe to delete) makes its target+#: ``unreachable``: no plan beats deleting it.+DEAD_CONFIDENCE = 0.8#: Class-level findings: a fix names member groups, which only a plan holds.CLASS_MARKERS = frozenset({"low_cohesion", "god_class"})#: Kinds the baseline raters found not worth doing: a refactoring led by one@@ -313,11 +325,13 @@ class _Files:cuts: tuple[float, float] | None,clones: Mapping[str, list[tuple[int, int]]] | None = None,extractions: Mapping[tuple[str, str], list[Any]] | None = None,+ dead: Mapping[str, list[DeadSpan]] | None = None,) -> None:self.by_path = {field(m, "file_path"): m for m in metrics}self.functions = functionsself.clones = clones or {}self.extractions = extractions or {}+ self.dead = dead or {}if cuts is None:production = [m for m in self.by_path.values() if not field(m, "is_test")]cuts = (@@ -421,17 +435,40 @@ class _Files:)return None- def unit_exclusion(self, path: str, symbol: str | None, complexity: bool) -> str | None:+ def unreachable(self, path: str, symbol: str | None, line: int | None) -> bool:+ """Whether a sure dead-code finding covers ``symbol`` (at ``line``) in+ ``path``: the whole file, the line inside the finding's span, or, for a+ finding stored with no lines, the same name as written (``Old.run`` is+ not ``New.run``)."""+ name_here = text.short_symbol(symbol)+ for name, start, end in self.dead.get(path, ()):+ if name is None:+ return True+ if start and end:+ if line and start <= line <= end:+ return True+ elif name_here and name == name_here:+ return True+ return False++ def unit_exclusion(+ self, path: str, symbol: str | None, complexity: bool, line: int | None = None+ ) -> str | None:"""Why a unit on ``symbol`` is not a candidate, or ``None``.- A deprecated function is on its way out. A complexity unit on a+ Unreachable code is deleted, not fixed. A deprecated function is on its+ way out, and a dormant one does not run. A complexity unit on afunction that is mostly one dispatch on one value is usually fine asit is, unless a duplicate also sits in it; one on a small function isnot worth an item."""+ if self.unreachable(path, symbol, line):+ return "unreachable"shape = self.shape(path, symbol)if shape.get("deprecated"):return "deprecated"+ if dormant(shape):+ return "gated_off"if not complexity:return Noneif dispatch_shaped(shape) and not self.cloned(path, shape):@@ -1218,6 +1255,7 @@ def _refactor_exclusion(path,lead.get("target_symbol"),complexity=lead.get("refactoring_type") == "extract_method",+ line=lead.get("line_start"),)if reason is None and not _concrete(lead, plans.get(lead.get("plan_id"))):return "no_concrete_step"@@ -1234,12 +1272,27 @@ def _finding_exclusion(finding: Any, files: _Files) -> str | None:field(finding, "file_path"),field(finding, "function_name"),complexity=field(finding, "biomarker_type") in SIZE_MARKERS,+ line=field(finding, "line_start"),)if reason is None and files.first_step(finding) is None:return "no_concrete_step"return reason+def _dead_spans(rows: Rows) -> dict[str, list[DeadSpan]]:+ """Sure, open dead-code findings by file: ``(symbol, start, end)``, the+ symbol ``None`` for an unreachable file."""+ out: dict[str, list[DeadSpan]] = defaultdict(list)+ for row in rows:+ sure = _num(field(row, "confidence")) >= DEAD_CONFIDENCE or field(row, "safe_to_delete")+ whole = field(row, "kind") == "unreachable_file"+ name = None if whole else field(row, "symbol_name")+ if _open(row) and sure and (whole or name):+ span = (name, field(row, "start_line"), field(row, "end_line"))+ out[field(row, "file_path")].append(span)+ return dict(out)++def _clone_spans(plans: Iterable[Any]) -> dict[str, list[tuple[int, int]]]:"""Where verified duplicates sit, by file: the occurrences an ExtractHelper plan names. Those come from clone pairs the detector verified@@ -1324,6 +1377,7 @@ def build_fix_first(refactoring: Rows = (),performance: Rows = (),plans: Rows = (),+ dead_code: Rows = (),limit: int | None = DEFAULT_LIMIT,scope: str = "production",basis: Mapping[str, str | None] | None = None,@@ -1345,7 +1399,8 @@ def build_fix_first(names a function but stored no line. ``validate(path, function, start, end)``is the validation profile (``basis``, ``via``, ``total``, ``tests``,``commands``) of a finding with no plan, read lazily for the items shown;- without it such an item's Verify stays unknown.+ without it such an item's Verify stays unknown. ``dead_code`` rows make+ the units they cover ``unreachable``."""metrics = list(metrics)findings = list(findings)@@ -1371,7 +1426,14 @@ def build_fix_first(hot_cuts,_clone_spans(plans),_extractions(plans),+ _dead_spans(dead_code),)+ dormant_functions: set[tuple[str, str | None]] = set()++ def exclude(reason: str, path: str, symbol: str | None) -> None:+ excluded[reason] += 1+ if reason == "gated_off":+ dormant_functions.add((path, text.short_symbol(symbol)))def scope_reason(path: str, context: str | None = None) -> str | None:"""Why ``path`` is out of scope, counted; ``None`` when it is in."""@@ -1400,7 +1462,7 @@ def build_fix_first(if reason is None:reason = _refactor_exclusion(gain, steps, plan_rows, files, path)if reason is not None:- excluded[reason] += 1+ exclude(reason, path, steps[0].get("target_symbol") if steps else None)refactoring_reasons[field(row, "opportunity_id")] = reasonif reason is not None:continue@@ -1420,7 +1482,7 @@ def build_fix_first(# actionability, one predicate for every surface); Fix first adds its path# rules and needs a stored plan to quote.perf_contexts = DEFAULT_QUEUE_CONTEXTS | {"test"} if keep_tests else DEFAULT_QUEUE_CONTEXTS- for (path, _symbol), rows in groups.items():+ for (path, symbol), rows in groups.items():if out_of_scope(path, "production"):continuerows.sort(key=lambda r: (field(r, "rank_position") or 0, field(r, "opportunity_id")))@@ -1428,12 +1490,17 @@ def build_fix_first(queued = [r for r, reason in zip(rows, reasons, strict=True) if reason is None]ready = [r for r in queued if _has_plan(r)]if not ready:- excluded["no_plan" if queued else reasons[0] or "no_plan"] += 1+ # Dormant only when every row is: one live row speaks for the group.+ live = [r for r in reasons if r != "gated_off"]+ exclude("no_plan" if queued else (live[0] if live else "gated_off"), path, symbol)continueworth = [r for r in ready if _perf_worth(r)]if not worth:excluded["below_min_worth"] += 1continue+ if files.unreachable(path, symbol, (symbol_lines or {}).get(symbol)):+ excluded["unreachable"] += 1+ continueunits.append(_perf_unit(worth, files, symbol_lines))for path, (shape, history) in split.items():@@ -1452,7 +1519,8 @@ def build_fix_first(reasons = {id(f): _finding_exclusion(f, files) for f in shape}eligible = primary_finding([f for f in shape if reasons[id(f)] is None])if eligible is None:- excluded[reasons[id(lead)] or next(r for r in reasons.values() if r)] += 1+ culprit = lead if reasons[id(lead)] else next(f for f in shape if reasons[id(f)])+ exclude(reasons[id(culprit)], path, field(culprit, "function_name"))continueunits.append(_finding_unit(eligible, files, files.first_step(eligible), validate))@@ -1470,6 +1538,7 @@ def build_fix_first(eligible=len(units),shown=len(shown),excluded=excluded,+ dormant=len(dormant_functions),),by_improves={k: by_improves.get(k, 0) for k in FIX_IMPROVES},basis=dict(basis) if basis is not None else _basis(metrics),@@ -1479,6 +1548,7 @@ def build_fix_first(__all__ = ["CLASS_MARKERS",+ "DEAD_CONFIDENCE","DEFAULT_LIMIT","DISPATCH_SHARE","GAIN_CUTS",diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/model.py b/packages/core/src/repowise/core/analysis/health/fix_first/model.pyindex 922710627..ae59daa3a 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/model.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/model.py@@ -36,8 +36,10 @@ FIX_LEVELS: tuple[str, ...] = get_args(FixLevel)FixFactBasis = Literal["measured", "inferred", "unknown"]FIX_FACT_BASES: tuple[str, ...] = get_args(FixFactBasis)-# ``unknown``, ``expected`` and ``no_strategy`` are the performance default-# queue's own reasons (``opportunity_rank.DEFAULT_QUEUE_EXCLUSIONS``).+# ``unknown``, ``gated_off``, ``expected`` and ``no_strategy`` are the+# performance default queue's own reasons (``opportunity_rank.DEFAULT_QUEUE_EXCLUSIONS``);+# ``gated_off`` also keeps out any other unit in a function a constant-false+# flag switches off. ``unreachable``: an open dead-code finding covers the target.FixExclusion = Literal["test","tooling",@@ -51,6 +53,8 @@ FixExclusion = Literal["vendored","docs_example","deprecated",+ "gated_off",+ "unreachable","inherent_dispatch","small_function","no_concrete_step",@@ -216,6 +220,8 @@ class FixTotals:eligible: int = 0shown: int = 0excluded: dict[str, int] = field(default_factory=_exclusions)+ #: Distinct functions with work kept out as ``gated_off``: dormant, not gone.+ dormant: int = 0@dataclass(frozen=True, slots=True)diff --git a/packages/core/src/repowise/core/analysis/health/perf/actionability.py b/packages/core/src/repowise/core/analysis/health/perf/actionability.pyindex 79b6f15d0..8054a3530 100644--- a/packages/core/src/repowise/core/analysis/health/perf/actionability.py+++ b/packages/core/src/repowise/core/analysis/health/perf/actionability.py@@ -16,14 +16,23 @@ Three separate questions live here and must not collapse into one label:from __future__ import annotations+from collections.abc import Sequencefrom dataclasses import dataclass, replacefrom typing import Any, Literal+from ..worth import dormant+FixSafety = Literal["proven", "advisory"]OpportunityConfidence = Literal["high", "medium", "low"]-# ``expected``: the repetition is real and there is nothing to change.+# ``expected``: the repetition is real and there is nothing to change, either+# by its nature or for a reason :func:`expected_reason` reads off the group+# (``gated_off``: a constant-false flag switches the function off).ActionabilityState = Literal["plan_ready", "advisory", "investigate", "expected"]+#: Reasons :func:`expected_reason` gives, in precedence order. The default+#: queue counts each under its own name rather than as ``expected``.+EXPECTED_REASONS: tuple[str, ...] = ("gated_off",)+# Refusals that are facts about the code, not missing proofs: nothing to investigate._EXPECTED_REFUSALS = frozenset({"inherent_to_boundary", "loop_already_chunked"})FixStrategy = Literal[@@ -280,16 +289,36 @@ def assess_fix(return FixAssessment(None, ("supported_strategy_for_marker",))+def expected_reason(members: Sequence[Any]) -> str | None:+ """Why a group needs no change whatever its strategy, or ``None``.++ ``gated_off``: every member sits in a function a constant-false flag in+ its own file switches off. Reasons are checked in precedence order.+ """+ if members and all(dormant(facts.details) for facts in members):+ return "gated_off"+ return None++def actionability(- assessment: FixAssessment, evidence_confidence: OpportunityConfidence+ assessment: FixAssessment,+ evidence_confidence: OpportunityConfidence,+ *,+ expected_reason: str | None = None,) -> Actionability:"""What to do with this group next, and why not more.Deliberately not a restatement of fix safety. A proven strategy resting ona call path we could not resolve reliably is still only advisory, and thedemotion names the fact that would promote it. A group with no strategy is- kept as investigation evidence rather than dropped.+ kept as investigation evidence rather than dropped. A group with an+ *expected_reason* (:func:`expected_reason`) has nothing to change, so it is+ ``expected`` under that reason and carries no fix."""+ # With or without a strategy: a group with none would otherwise be+ # ``investigate``, and there is nothing to investigate either.+ if expected_reason is not None:+ return Actionability("expected", expected_reason, "low", (), None)fix = assessment.fixif fix is None:state: ActionabilityState = (diff --git a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py b/packages/core/src/repowise/core/analysis/health/perf/opportunities.pyindex 6f083bbf9..313600932 100644--- a/packages/core/src/repowise/core/analysis/health/perf/opportunities.py+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunities.py@@ -27,6 +27,7 @@ from .actionability import (PerformanceFix,actionability,assess_fix,+ expected_reason,provenance_confidence,)from .causal import (@@ -175,7 +176,11 @@ def _assemble(key: Any, members: list[Any], cap: int) -> PerformanceOpportunity:[facts.details for facts in members],cross_function=any(facts.cross_function for facts in members),)- acted = actionability(assessment, evidence_confidence)+ acted = actionability(+ assessment,+ evidence_confidence,+ expected_reason=expected_reason(members),+ )magnitude = loop_magnitude(marker, [facts.details for facts in members])factors = rank_factors(marker=marker,diff --git a/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py b/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.pyindex afbc2152b..547bbced8 100644--- a/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py+++ b/packages/core/src/repowise/core/analysis/health/perf/opportunity_rank.py@@ -19,7 +19,8 @@ from __future__ import annotationsfrom math import log2from typing import Any-from ..rows import field+from ..rows import detail_map, field+from .actionability import EXPECTED_REASONSBOUNDARY_POINTS = {"subprocess": 5, "network": 4, "db": 4, "lock": 3, "filesystem": 2}"""What one crossing of each boundary costs, as an order of magnitude.@@ -141,7 +142,7 @@ are true and stay one filter away, but none of them is work to schedule. Each iscounted by :func:`default_queue_exclusion` so leaving it out is never silent."""-DEFAULT_QUEUE_EXCLUSIONS = ("test", "tooling", "unknown", "expected", "no_strategy")+DEFAULT_QUEUE_EXCLUSIONS = ("test", "tooling", "unknown", *EXPECTED_REASONS, "expected", "no_strategy")"""Every reason the default queue leaves a cause out, in the order it is checked."""_LEVERAGE_BANDS = ((1, "isolated"), (3, "local"), (9, "shared"))@@ -292,7 +293,10 @@ def default_queue_exclusion(state = field(item, "actionability_state")if state in DEFAULT_QUEUE_STATES:return None- return "expected" if state == "expected" else "no_strategy"+ if state != "expected":+ return "no_strategy"+ reason = field(item, "actionability_reason") or detail_map(item).get("actionability_reason")+ return reason if reason in EXPECTED_REASONS else "expected"def default_queue_counts(items: list[Any]) -> dict[str, Any]:diff --git a/packages/core/src/repowise/core/analysis/health/worth.py b/packages/core/src/repowise/core/analysis/health/worth.pyindex 88bf76bcc..6c9dedebe 100644--- a/packages/core/src/repowise/core/analysis/health/worth.py+++ b/packages/core/src/repowise/core/analysis/health/worth.py@@ -106,11 +106,19 @@ _ERROR_KINDS: dict[str, LowPriority] = {}+def dormant(facts: Mapping[str, Any]) -> bool:+ """Whether a finding's details, or a measured shape, place it in a function+ a constant-false flag in its own file switches off (``complexity/gating.py``).+ Its work never runs while the flag is off, so it is no work to schedule."""+ return bool(facts.get("gated_off"))++def measure(findings: Iterable[Any]) -> dict[str, int]:"""A function's largest measured CCN, size and nesting across its findings.``severe`` is set when any of them is critical or a brain method,``deprecated`` when any sits in a function marked deprecated,+ ``gated_off`` when any sits in a :func:`dormant` function,``dispatch_pct`` is the largest stored dispatch share in percent,``start`` / ``end`` span the function as its size findings place it, and``deep_start`` / ``deep_end`` are its deepest nested block's lines.@@ -122,6 +130,8 @@ def measure(findings: Iterable[Any]) -> dict[str, int]:details = detail_map(f)if details.get("deprecated"):shape["deprecated"] = 1+ if dormant(details):+ shape["gated_off"] = 1deepest = details.get("deepest_block")if isinstance(deepest, dict) and deepest.get("start") and "deep_start" not in shape:shape["deep_start"] = int(deepest["start"])@@ -299,6 +309,7 @@ __all__ = ["WORTH_MAGNITUDE","LowPriority","dispatch_shaped",+ "dormant","finding_priorities","low_priority","magnitude",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.pyindex 46e858a48..0b76740c7 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/fix_first.py@@ -31,7 +31,12 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.finding_registry import excluded_typesfrom repowise.core.analysis.health.fix_first import DEFAULT_LIMIT, FixFirstQueue, build_fix_first-from repowise.core.analysis.health.fix_first.build import MIN_WORTH, hot_cut, hot_cut_offset+from repowise.core.analysis.health.fix_first.build import (+ DEAD_CONFIDENCE,+ MIN_WORTH,+ hot_cut,+ hot_cut_offset,+)from repowise.core.analysis.health.perf.opportunity_rank import DEFAULT_QUEUE_STATESfrom repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSIONfrom repowise.core.analysis.health.refactoring.models import (@@ -46,6 +51,7 @@ from repowise.core.analysis.health.rows import detail_mapfrom repowise.core.analysis.health.scoring import history_biomarkersfrom ...models import (+ DeadCodeFinding,GitMetadata,GraphMetric,GraphNode,@@ -55,6 +61,7 @@ from ...models import (RefactoringOpportunity,RefactoringSuggestion,)+from ...sql import json_text#: Files read for plan-less finding items, by open code-shape deduction.#: Ceiling: a file past this rank never becomes a finding item. The queue@@ -275,6 +282,9 @@ async def _performance(session: AsyncSession, repo_id: str) -> list[Any]:p.plan_state == "available",p.fix_strategy.is_not(None),)+ # The reason is no column: read for ``expected`` rows only, in SQL, so+ # the default queue counts each expected reason with no decode.+ reason = json_text(p.details_json, "actionability_reason")return _plain(await session.execute(select(@@ -294,6 +304,9 @@ async def _performance(session: AsyncSession, repo_id: str) -> list[Any]:p.affected_call_sites_total,p.affected_files_total,p.status,+ case((p.actionability_state == "expected", reason)).label(+ "actionability_reason"+ ),case((ready, p.details_json)).label("details_json"),).where(p.repository_id == repo_id, p.status == "open")@@ -302,6 +315,34 @@ async def _performance(session: AsyncSession, repo_id: str) -> list[Any]:)+def _sure_dead_code(repo_id: str) -> Any:+ d = DeadCodeFinding+ return and_(+ d.repository_id == repo_id,+ d.status == "open",+ or_(d.confidence >= DEAD_CONFIDENCE, d.safe_to_delete.is_(True)),+ )+++async def _dead_code(session: AsyncSession, repo_id: str) -> list[Any]:+ """Open dead-code findings sure enough to make what they cover ``unreachable``."""+ d = DeadCodeFinding+ return _plain(+ await session.execute(+ select(+ d.kind,+ d.file_path,+ d.symbol_name,+ d.start_line,+ d.end_line,+ d.confidence,+ d.safe_to_delete,+ d.status,+ ).where(_sure_dead_code(repo_id))+ )+ )++def _decoded(rows: list[Any]) -> list[Any]:"""``details_json`` decoded once into ``details``, which the builder reads first."""if not rows:@@ -366,6 +407,12 @@ async def _symbol_lines(session: AsyncSession, repo_id: str, performance: list[Afor step in (row.details.get("plan") or {}).get("steps") or ()if not step.get("line") and "::" in (step.get("symbol") or "")}+ # And each cause's own function, which the dead-code join places by line.+ wanted |= {+ row.intervention_symbol+ for row in performance+ if row.details and "::" in (row.intervention_symbol or "")+ }if not wanted:return {}g = GraphNode@@ -456,6 +503,16 @@ async def _stamp(session: AsyncSession, repo_id: str) -> tuple[Any, ...]:)).one())+ # Dead-code rows carry no ``updated_at``; a triage change moves the count.+ stamps.extend(+ (+ await session.execute(+ select(func.max(DeadCodeFinding.analyzed_at), func.count()).where(+ _sure_dead_code(repo_id)+ )+ )+ ).one()+ )return tuple(stamps)@@ -548,6 +605,7 @@ async def _build(refactoring=refactoring,performance=performance,plans=await _plans(session, repository_id, steps, full),+ dead_code=await _dead_code(session, repository_id),limit=limit,scope=scope,item_id=item_id,diff --git a/packages/core/src/repowise/core/persistence/sql.py b/packages/core/src/repowise/core/persistence/sql.pyindex a4cb796fd..4e5929e01 100644--- a/packages/core/src/repowise/core/persistence/sql.py+++ b/packages/core/src/repowise/core/persistence/sql.py@@ -10,6 +10,10 @@ from __future__ import annotationsfrom collections.abc import Iterablefrom typing import Any+from sqlalchemy import String, literal+from sqlalchemy.ext.compiler import compiles+from sqlalchemy.sql.functions import FunctionElement+#: The escape character to pass as ``escape=`` on every ``like``/``ilike``#: paired with :func:`escape_like`. SQLite has no default LIKE escape#: character, so it has to be declared on the call for the escaping below to@@ -28,6 +32,32 @@ def escape_like(value: str) -> str:return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")+class json_text(FunctionElement): # noqa: N801 - reads as the SQL function it renders+ """One top-level key of a JSON text column, as text, in SQL.++ SQLite and PostgreSQL spell it differently and neither indexes it, so it+ narrows a read the caller already scoped; it never drives a filter.+ """++ type = String()+ inherit_cache = True++ def __init__(self, column: Any, key: str) -> None:+ super().__init__(column, literal(key, String()))+++@compiles(json_text)+def _json_text_sqlite(element: json_text, compiler: Any, **kw: Any) -> str:+ column, key = (compiler.process(c, **kw) for c in element.clauses)+ return f"json_extract({column}, '$.' || {key})"+++@compiles(json_text, "postgresql")+def _json_text_postgresql(element: json_text, compiler: Any, **kw: Any) -> str:+ column, key = (compiler.process(c, **kw) for c in element.clauses)+ return f"(CAST({column} AS JSON) ->> {key})"++def rule_predicate(model: Any, rule: Any, value: Any) -> Any:"""One ``analysis.health.queue_rules.FilterRule`` as a SQL predicate on *model*.diff --git a/packages/types/src/fix-first.ts b/packages/types/src/fix-first.tsindex e1ba8995f..08960c04a 100644--- a/packages/types/src/fix-first.ts+++ b/packages/types/src/fix-first.ts@@ -37,6 +37,8 @@ export type FixExclusion =| "vendored"| "docs_example"| "deprecated"+ | "gated_off"+ | "unreachable"| "inherent_dispatch"| "small_function"| "no_concrete_step"@@ -117,6 +119,8 @@ export interface FixFirstTotals {eligible: number;shown: number;excluded: Record<FixExclusion, number>;+ /** Distinct functions with work kept out as `gated_off`: dormant, not gone. */+ dormant: number;}export interface FixFirstQueue<Item = FixItem> {diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 4f6e5bd76..25359f4bd 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -1662,6 +1662,7 @@ export interface FixTotals {eligible?: number;shown?: number;excluded?: Record<string, number>;+ dormant?: number;}export interface FixVerify {diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 91e32ba9d..1dca711f2 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -597,9 +597,18 @@ export type PerformanceOpportunityQuery = {offset?: number;};+/** Why the default queue leaves a cause out (`opportunity_rank.DEFAULT_QUEUE_EXCLUSIONS`). */+export type PerformanceQueueExclusion =+ | "test"+ | "tooling"+ | "unknown"+ | "gated_off"+ | "expected"+ | "no_strategy";+export interface PerformanceDefaultQueue {total: number;- excluded: Record<"test" | "tooling" | "unknown" | "expected" | "no_strategy", number>;+ excluded: Record<PerformanceQueueExclusion, number>;}export interface PerformanceOpportunitySummary {diff --git a/packages/ui/__tests__/health/fix-first.test.tsx b/packages/ui/__tests__/health/fix-first.test.tsxindex e43416ed3..07292cb97 100644--- a/packages/ui/__tests__/health/fix-first.test.tsx+++ b/packages/ui/__tests__/health/fix-first.test.tsx@@ -50,6 +50,20 @@ describe("Fix first header", () => {);});+ it("counts dormant functions apart from what they excluded", () => {+ const queue: FixFirstQueue = {+ ...FIX_FIRST_QUEUE,+ totals: {+ ...FIX_FIRST_QUEUE.totals,+ excluded: { ...FIX_FIRST_QUEUE.totals.excluded, gated_off: 3, unreachable: 2 },+ dormant: 1,+ },+ };+ const sentence = fixFirstScopeSentence(queue);+ expect(sentence).toContain("3 switched off by a constant flag, 2 in dead code (delete it)");+ expect(sentence).toMatch(/Dormant: 1 function behind a disabled flag\.$/);+ });+it("omits a rule that excluded nothing", () => {const queue: FixFirstQueue = {...FIX_FIRST_QUEUE,diff --git a/packages/ui/__tests__/health/fixtures/fix-first.ts b/packages/ui/__tests__/health/fixtures/fix-first.tsindex 5d0f9ba6a..4b56672f2 100644--- a/packages/ui/__tests__/health/fixtures/fix-first.ts+++ b/packages/ui/__tests__/health/fixtures/fix-first.ts@@ -616,11 +616,14 @@ export const FIX_FIRST_QUEUE: FixFirstQueue = {"vendored": 0,"docs_example": 0,"deprecated": 0,+ "gated_off": 0,+ "unreachable": 0,"inherent_dispatch": 0,"small_function": 0,"no_concrete_step": 0,"low_value_kind": 0- }+ },+ "dormant": 0},"by_improves": {"defect": 266,diff --git a/packages/ui/src/health/fix-first/scope.ts b/packages/ui/src/health/fix-first/scope.tsindex 866eb740e..b08cbf59e 100644--- a/packages/ui/src/health/fix-first/scope.ts+++ b/packages/ui/src/health/fix-first/scope.ts@@ -43,6 +43,8 @@ export const EXCLUSION_LABEL: Record<FixExclusion, string> = {below_min_worth: "below the worth floor",history_only: "history only",deprecated: "deprecated",+ gated_off: "switched off by a constant flag",+ unreachable: "in dead code (delete it)",inherent_dispatch: "one long dispatch on a value",small_function: "small functions",no_concrete_step: "with no concrete first edit",@@ -62,6 +64,8 @@ const EXCLUSION_ORDER: FixExclusion[] = ["below_min_worth","history_only","deprecated",+ "gated_off",+ "unreachable","inherent_dispatch","small_function","no_concrete_step",@@ -70,16 +74,22 @@ const EXCLUSION_ORDER: FixExclusion[] = [/*** The header line, exact about scope: how many items are shown out of how- * many are eligible, and what each rule left out. A zero count is omitted- * because it excluded nothing.+ * many are eligible, what each rule left out, and how many functions a+ * constant flag keeps dormant. A zero count is omitted because it excluded+ * nothing.*/export function fixFirstScopeSentence(queue: FixFirstQueue<unknown>): string {- const { shown, eligible, excluded } = queue.totals;+ const { shown, eligible, excluded, dormant } = queue.totals;const head = `${formatNumber(shown)} of ${formatNumber(eligible)} eligible item${eligible === 1 ? "" : "s"}.`;const parts = exclusionPhrase(excluded);- return parts ? `${head} Excluded: ${parts}.` : head;+ const sentence = parts ? `${head} Excluded: ${parts}.` : head;+ return dormant+ ? `${sentence} Dormant: ${formatNumber(dormant)} function${+ dormant === 1 ? "" : "s"+ } behind a disabled flag.`+ : sentence;}/**diff --git a/packages/web/src/components/code-health/fix-first-section.test.tsx b/packages/web/src/components/code-health/fix-first-section.test.tsxindex f7a6beed1..d899f0432 100644--- a/packages/web/src/components/code-health/fix-first-section.test.tsx+++ b/packages/web/src/components/code-health/fix-first-section.test.tsx@@ -70,11 +70,14 @@ function queue(items: FixItem[]): FixFirstQueue {vendored: 0,docs_example: 0,deprecated: 0,+ gated_off: 0,+ unreachable: 0,inherent_dispatch: 0,small_function: 0,no_concrete_step: 0,low_value_kind: 0,},+ dormant: 0,},by_improves: { defect: 4, maintainability: 0, performance: 0 },model_version: 1,diff --git a/tests/unit/change_health/test_regressions.py b/tests/unit/change_health/test_regressions.pyindex 52204e680..fa975bf06 100644--- a/tests/unit/change_health/test_regressions.py+++ b/tests/unit/change_health/test_regressions.py@@ -245,3 +245,18 @@ def test_an_expected_cause_says_there_is_nothing_to_change():intervention_symbol=None,)assert "inherent_to_boundary" not in _suggestion(SimpleNamespace(), perf)+++def test_a_gated_cause_says_a_constant_flag_switches_it_off():+ perf = SimpleNamespace(+ actionability_state="expected", actionability_reason="gated_off", intervention_symbol=None+ )+ text = _suggestion(SimpleNamespace(), perf)+ assert "constant-False flag" in text and "inherent" not in text+++def test_an_unlisted_expected_reason_keeps_the_inherent_sentence():+ perf = SimpleNamespace(+ actionability_state="expected", actionability_reason="something_new", intervention_symbol=None+ )+ assert "inherent" in _suggestion(SimpleNamespace(), perf)diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex ffac48ad2..0d7a0bcb6 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -51,11 +51,14 @@ def test_each_exclusion_is_counted_by_reason() -> None:"vendored": 0,"docs_example": 0,"deprecated": 0,+ "gated_off": 0,+ "unreachable": 0,"inherent_dispatch": 0,"small_function": 0,"no_concrete_step": 0,"low_value_kind": 0,}+ assert queue.totals.dormant == 0assert queue.totals.eligible == 3assert queue.totals.candidates == 3 + 7assert queue.by_improves == {"defect": 2, "maintainability": 0, "performance": 1}diff --git a/tests/unit/health/test_gated_off.py b/tests/unit/health/test_gated_off.pynew file mode 100644index 000000000..5494156ab--- /dev/null+++ b/tests/unit/health/test_gated_off.py@@ -0,0 +1,383 @@+"""``gated_off``: a function a constant-false flag in its own file switches off,+and ``unreachable``: work a sure dead-code finding covers.++Both keep a unit out of Fix first, the refactoring default scope (which reads+Fix first's reasons) and the performance default queue, and both are counted.+"""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.complexity import walk_file+from repowise.core.analysis.health.engine import _mark_function_facts+from repowise.core.analysis.health.finding_identity import finding_public_id+from repowise.core.analysis.health.fix_first import build_fix_first+from repowise.core.analysis.health.models import HealthFindingData, Severity+from repowise.core.analysis.health.perf.opportunities import build_performance_opportunities+from repowise.core.analysis.health.perf.opportunity_rank import (+ default_queue_counts,+ default_queue_exclusion,+)+from tests.unit.health.fix_first_rows import FINDINGS, METRICS, REFACTORING, _perf++# The shape of ``decisions/evolution.py``: a documented kill switch, then a+# function that builds its result and returns it at once behind the switch.+_EVOLUTION = """+SEMANTIC_SUPERSESSION_ENABLED = False+LIVE = False+FROM_ENV = os.environ.get("REPOWISE_FLAG") == "1"+LATER = False+LATER = True+NOTHING = None+++def configure(on):+ global LIVE+ LIVE = on+++def detect_supersessions_and_conflicts(session, touched_ids):+ \"\"\"Record supersedes/conflicts edges.\"\"\"+ summary = {"supersedes": 0, "conflicts": 0, "flipped": 0}+ if not SEMANTIC_SUPERSESSION_ENABLED:+ return summary+ for decision in touched_ids:+ session.get(decision)+ return summary+++def wholly_inside():+ if SEMANTIC_SUPERSESSION_ENABLED:+ work()+++def is_false_guard():+ if SEMANTIC_SUPERSESSION_ENABLED is False:+ return None+ work()+++def live_global():+ if not LIVE:+ return+ work()+++def live_env():+ if not FROM_ENV:+ return+ work()+++def reassigned_at_module_level():+ if not LATER:+ return+ work()+++def none_is_not_false():+ if NOTHING is False:+ return+ work()+++def guard_with_else():+ if not SEMANTIC_SUPERSESSION_ENABLED:+ return+ else:+ work()+++def logs_before_returning():+ if not SEMANTIC_SUPERSESSION_ENABLED:+ log()+ return+ work()+++def guard_after_a_loop():+ for x in xs:+ work(x)+ if not SEMANTIC_SUPERSESSION_ENABLED:+ return+"""++_TS = """+export const ENABLED = false;+let MUTABLE = false;+const ON = true;++export function guarded(rows: string[]) {+ const out = {};+ if (!ENABLED) return out;+ return rows;+}++const wholly = () => {+ if (ENABLED) {+ work();+ }+};++class Store {+ strict() {+ if (ENABLED === false) {+ return 1;+ }+ work();+ }+ onFlag() {+ if (!ON) return;+ work();+ }+}++function mutable() {+ if (!MUTABLE) {+ return;+ }+ work();+}+"""+++def _gated(language: str, path: str, source: str) -> set[str]:+ fcx = walk_file(path, language, source.encode())+ if not fcx.functions:+ pytest.skip(f"{language} grammar unavailable")+ return {fc.name for fc in fcx.functions if fc.gated_off}+++def test_a_constant_false_guard_in_the_same_file_gates_the_function() -> None:+ assert _gated("python", "/tmp/evolution.py", _EVOLUTION) == {+ "detect_supersessions_and_conflicts",+ "wholly_inside",+ "is_false_guard",+ }+++def test_a_live_flag_is_never_gated() -> None:+ gated = _gated("python", "/tmp/evolution.py", _EVOLUTION)+ for name in ("live_global", "live_env", "reassigned_at_module_level", "configure"):+ assert name not in gated+++def test_typescript_const_false_gates_and_let_or_true_does_not() -> None:+ assert _gated("typescript", "/tmp/store.ts", _TS) == {"guarded", "wholly", "strict"}+++def test_the_dogfood_function_is_gated() -> None:+ import pathlib++ import repowise.core.analysis.decisions.evolution as evolution++ source = pathlib.Path(evolution.__file__).read_text(encoding="utf-8")+ assert "detect_supersessions_and_conflicts" in _gated("python", evolution.__file__, source)+++def _finding(name: str = "run", line: int = 10, **details) -> HealthFindingData:+ return HealthFindingData(+ biomarker_type="complex_method",+ severity=Severity.HIGH,+ file_path="src/a.py",+ function_name=name,+ line_start=line,+ line_end=line + 20,+ details={"ccn": 20, **details},+ health_impact=1.0,+ )+++def test_findings_in_a_gated_function_carry_the_fact_and_keep_their_id() -> None:+ fcx = walk_file("/tmp/evolution.py", "python", _EVOLUTION.encode())+ if not fcx.functions:+ pytest.skip("python grammar unavailable")+ gated = next(fc for fc in fcx.functions if fc.name == "detect_supersessions_and_conflicts")+ inside, outside = _finding(gated.name, gated.start_line + 1), _finding("live_env", 1)+ before = finding_public_id(inside)+ _mark_function_facts([inside, outside], fcx.functions)+ assert inside.details["gated_off"] is True and "gated_off" not in outside.details+ assert finding_public_id(inside) == before+++# --- Fix first ---------------------------------------------------------------------+++def _fix_finding(**details) -> dict:+ complex_run = FINDINGS[1]+ return {**complex_run, "details": {**complex_run["details"], **details}}+++def test_a_gated_function_is_no_item_and_counts_as_dormant() -> None:+ queue = build_fix_first(metrics=METRICS[:1], findings=[_fix_finding(gated_off=True)])+ assert queue.items == ()+ assert queue.totals.excluded["gated_off"] == 1 and queue.totals.dormant == 1+ assert len(build_fix_first(metrics=METRICS[:1], findings=[_fix_finding()]).items) == 1+++def test_a_plan_on_a_gated_function_leaves_the_refactoring_default_scope() -> None:+ queue = build_fix_first(+ metrics=METRICS[:1], findings=[_fix_finding(gated_off=True)], refactoring=REFACTORING[:1]+ )+ assert queue.refactoring_reasons["refop2_core"] == "gated_off"+ # The plan and the finding it leaves behind sit in one function.+ assert queue.totals.excluded["gated_off"] == 2 and queue.totals.dormant == 1+++def _perf_finding(line: int, **details) -> HealthFindingData:+ return HealthFindingData(+ biomarker_type="io_in_loop",+ severity=Severity.MEDIUM,+ file_path="src/repo.py",+ function_name="load_all",+ line_start=line,+ line_end=line,+ details={"boundary_kind": "db", "cross_function": False, "path": [], **details},+ health_impact=0.0,+ dimension="performance",+ )+++def test_a_cause_in_a_gated_function_leaves_the_performance_default_queue() -> None:+ (gated,) = build_performance_opportunities(+ [_perf_finding(10, gated_off=True), _perf_finding(12, gated_off=True)]+ )+ (live,) = build_performance_opportunities([_perf_finding(10)])+ assert (gated.actionability_state, gated.actionability_reason, gated.fix) == (+ "expected",+ "gated_off",+ None,+ )+ assert live.actionability_state != "expected"+ assert default_queue_exclusion(gated) == "gated_off"+ assert default_queue_counts([gated, live])["excluded"]["gated_off"] == 1+++def test_one_live_call_site_keeps_the_cause() -> None:+ (mixed,) = build_performance_opportunities(+ [_perf_finding(10, gated_off=True), _perf_finding(12)]+ )+ assert mixed.actionability_reason != "gated_off"+++def test_fix_first_counts_a_gated_cause_by_its_reason() -> None:+ row = _perf(+ "perf3_gated", "x", actionability_state="expected", plan_state="no_safe_plan",+ fix_strategy=None,+ )+ row["details"] = {"actionability_reason": "gated_off"}+ expected = {**row, "opportunity_id": "perf3_exp", "intervention_symbol": "src/repo.py::other",+ "details": {"actionability_reason": "inherent_to_boundary"}}+ queue = build_fix_first(metrics=[METRICS[3]], performance=[row, expected])+ assert queue.items == ()+ assert queue.totals.excluded["gated_off"] == 1 and queue.totals.excluded["expected"] == 1+ assert queue.totals.dormant == 1+++# --- dead code -----------------------------------------------------------------------+++def _dead(**over) -> dict:+ return {+ "kind": "unused_internal", "file_path": "src/core.py", "symbol_name": "run",+ "start_line": 10, "end_line": 60, "confidence": 0.9, "safe_to_delete": False,+ "status": "open", **over,+ }+++ "dead",+ [+ _dead(),+ _dead(kind="unreachable_file", symbol_name=None, start_line=None, end_line=None),+ _dead(confidence=0.5, safe_to_delete=True),+ _dead(start_line=None, end_line=None),+ ],+)+def test_sure_dead_code_makes_its_target_unreachable(dead: dict) -> None:+ queue = build_fix_first(+ metrics=METRICS[:1], findings=[_fix_finding()], refactoring=REFACTORING[:1],+ dead_code=[dead],+ )+ assert queue.items == ()+ assert queue.refactoring_reasons["refop2_core"] == "unreachable"+ assert queue.totals.excluded["unreachable"] == 2 and queue.totals.dormant == 0+++ "dead",+ [+ _dead(confidence=0.5),+ _dead(status="false_positive"),+ _dead(start_line=100, end_line=120),+ _dead(file_path="src/other.py"),+ ],+)+def test_unsure_or_elsewhere_dead_code_leaves_the_target(dead: dict) -> None:+ queue = build_fix_first(metrics=METRICS[:1], findings=[_fix_finding()], dead_code=[dead])+ assert len(queue.items) == 1 and queue.totals.excluded["unreachable"] == 0+++def test_a_cause_in_dead_code_is_unreachable() -> None:+ dead = _dead(file_path="src/repo.py", symbol_name="load_all", start_line=None, end_line=None)+ queue = build_fix_first(metrics=[METRICS[3]], performance=[_perf("perf3_a", "s")],+ dead_code=[dead])+ assert queue.items == () and queue.totals.excluded["unreachable"] == 1+++def test_only_a_plain_assignment_may_come_before_the_guard() -> None:+ source = _EVOLUTION + """++def works_before_the_guard(session):+ session.execute("delete from t")+ if not SEMANTIC_SUPERSESSION_ENABLED:+ return+++def calls_in_an_assignment(session):+ rows = session.execute("select 1")+ if not SEMANTIC_SUPERSESSION_ENABLED:+ return rows+"""+ gated = _gated("python", "/tmp/evolution.py", source)+ assert not gated & {"works_before_the_guard", "calls_in_an_assignment"}+ assert "detect_supersessions_and_conflicts" in gated+++def test_a_minified_file_is_read_as_written() -> None:+ source = "const ENABLED = false;\nfunction f() { if (!ENABLED) return; work(); }\n"+ assert _gated("javascript", "/tmp/a.js", source) == {"f"}+ assert _gated("javascript", "/tmp/a.js", source + "var x = 1;" * 300 + "\n") == set()+++def test_dead_code_on_one_method_leaves_its_same_named_sibling() -> None:+ # ``Old.run`` (lines 10-20) is dead; ``New.run`` (line 40) is live.+ dead = [_dead(symbol_name="run", start_line=10, end_line=20)]+ live = {**_fix_finding(), "function_name": "New.run", "line_start": 40, "line_end": 70}+ queue = build_fix_first(metrics=METRICS[:1], findings=[live], dead_code=dead)+ assert len(queue.items) == 1 and queue.totals.excluded["unreachable"] == 0+ named = [_dead(symbol_name="Old.run", start_line=None, end_line=None)]+ queue = build_fix_first(metrics=METRICS[:1], findings=[live], dead_code=named)+ assert len(queue.items) == 1+++def test_a_perf_cause_is_placed_by_its_function_line() -> None:+ dead = [_dead(file_path="src/repo.py", symbol_name="run", start_line=10, end_line=20)]+ rows = [_perf("perf3_new", "s", intervention_symbol="src/repo.py::New.run")]+ lines = {"src/repo.py::New.run": 40}+ queue = build_fix_first(metrics=[METRICS[3]], performance=rows, dead_code=dead,+ symbol_lines=lines)+ assert len(queue.items) == 1+ queue = build_fix_first(metrics=[METRICS[3]], performance=rows, dead_code=dead,+ symbol_lines={"src/repo.py::New.run": 12})+ assert queue.items == () and queue.totals.excluded["unreachable"] == 1+++def test_one_live_row_keeps_a_perf_group_out_of_the_dormant_count() -> None:+ gated = _perf("perf3_a", "x", actionability_state="expected", plan_state="no_safe_plan",+ fix_strategy=None, details={"actionability_reason": "gated_off"})+ other = _perf("perf3_b", "y", actionability_state="investigate", plan_state="no_safe_plan",+ fix_strategy=None, rank_position=1)+ queue = build_fix_first(metrics=[METRICS[3]], performance=[gated, other])+ assert queue.totals.excluded["no_strategy"] == 1 and queue.totals.dormant == 0diff --git a/tests/unit/persistence/test_fix_first_loader.py b/tests/unit/persistence/test_fix_first_loader.pyindex 0c6753d9d..a24e81323 100644--- a/tests/unit/persistence/test_fix_first_loader.py+++ b/tests/unit/persistence/test_fix_first_loader.py@@ -284,3 +284,39 @@ async def test_a_finding_item_with_no_tests_stays_unknown(async_session) -> Noneloaded = await load_fix_first(async_session, rid)walk = next(i for i in loaded.items if i.target.file_path == "src/plain.py")assert (walk.verify.tests, walk.verify.basis) == ((), "unknown")+++async def test_loader_counts_dormant_causes_and_dead_code(async_session) -> None:+ from repowise.core.persistence.models import DeadCodeFinding+ from tests.unit.health.fix_first_rows import _perf++ rid = (await insert_repo(async_session)).id+ async_session.add(HealthFileMetric(repository_id=rid, file_path="src/repo.py", score=8.0,+ nloc=90, is_test=False))+ gated = _perf("perf3_gated", "x", actionability_state="expected", plan_state="no_safe_plan",+ fix_strategy=None, intervention_symbol="src/repo.py::off")+ gated = _with_json(gated, "details")+ gated["details_json"] = json.dumps({"actionability_reason": "gated_off"})+ live = _perf("perf3_live", "y")+ async_session.add_all([+ PerformanceOpportunity(repository_id=rid, **gated),+ PerformanceOpportunity(repository_id=rid, **_with_json(live, "details")),+ DeadCodeFinding(repository_id=rid, kind="unused_internal", file_path="src/repo.py",+ symbol_name="load_all", confidence=0.9, status="open"),+ ])+ await async_session.flush()+ queue = await load_fix_first(async_session, rid)+ assert queue.items == ()+ assert queue.totals.excluded["gated_off"] == 1 and queue.totals.dormant == 1+ assert queue.totals.excluded["unreachable"] == 1+++def test_json_text_renders_for_both_dialects() -> None:+ from sqlalchemy import column, select+ from sqlalchemy.dialects import postgresql, sqlite++ from repowise.core.persistence.sql import json_text++ query = select(json_text(column("details_json"), "actionability_reason"))+ assert "json_extract(details_json" in str(query.compile(dialect=sqlite.dialect()))+ assert "CAST(details_json AS JSON) ->>" in str(query.compile(dialect=postgresql.dialect()))diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.pyindex 1710b85be..8848c22a0 100644--- a/tests/unit/server/test_performance_opportunities.py+++ b/tests/unit/server/test_performance_opportunities.py@@ -322,7 +322,14 @@ async def test_the_default_queue_reports_what_it_leaves_out(app, client: AsyncClassert [item["intervention_symbol"] for item in default["items"]] == ["src/shared.py::load"]assert default["summary"]["default_queue"] == {"total": 1,- "excluded": {"test": 1, "tooling": 0, "unknown": 0, "expected": 1, "no_strategy": 1},+ "excluded": {+ "test": 1,+ "tooling": 0,+ "unknown": 0,+ "gated_off": 0,+ "expected": 1,+ "no_strategy": 1,+ },}asked = await _page(client, repo_id, actionability="investigate")assert [item["intervention_symbol"] for item in asked["items"]] == ["src/clients.py::each"]diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.pyindex a41f82dba..1e3d1696f 100644--- a/tests/unit/server/test_wire_vocabulary_parity.py+++ b/tests/unit/server/test_wire_vocabulary_parity.py@@ -115,6 +115,12 @@ def test_fix_first_vocabularies_match_python() -> None:assert match and set(re.findall(r'"([A-Z]+)"', match.group(1))) == set(FIX_EFFORTS)+def test_performance_queue_exclusions_match_python() -> None:+ from repowise.core.analysis.health.perf.opportunity_rank import DEFAULT_QUEUE_EXCLUSIONS++ assert _union_members("PerformanceQueueExclusion", "health.ts") == set(DEFAULT_QUEUE_EXCLUSIONS)++def test_agent_prompt_flavors_match_python() -> None:from repowise.core.agent_prompts import FLAVORS