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 real but low-value work out of the Fix first top tier (#2965)
Raghav Chamadiyad6265a9223cb
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex 8c6c29a19..32609321e 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -667,7 +667,7 @@ that is worth doing. Everything else is left out and counted in| `below_min_worth` | A refactoring that recovers under 0.5 health on its file, or has no steps; a string built in a loop that is bounded or not in production code. || `history_only` | A file whose only findings come from git history (churn, ownership, co-change). History is context on an item, never the item. || `deprecated` | A function marked deprecated. |-| `inherent_dispatch` | A function where one dispatch on one value holds 60% or more of its decision points, unless a duplicate also sits in it. On the dev labels that share held 9 complexity rows, 8 of them rejected. |+| `inherent_dispatch` | A function where one dispatch on one value holds 60% or more of its decision points, unless a duplicate also sits in it (then it is listed as `later`). On the dev labels that share held 9 complexity rows, 8 of them rejected. || `small_function` | A complexity unit under 30 code lines and under CCN 15. On the 67 labelled dev rows that cut drops 13 rejected and 4 accepted. || `no_concrete_step` | No first edit with a file and a line or a named group: a cycle with no import line to cut, a move with no destination, a split with no named groups, a class finding with no member groups. || `low_value_kind` | A kind raters found not worth doing: Extract Class (0 of 14), Move Method (0 of 34), low cohesion (0 of 46), long method (0 of 10), and long parameter lists (0 of 2, thinly measured). |@@ -682,6 +682,25 @@ and the plan is safe to start), `next` (worth doing, the fix needs judgment),`later`. No kind takes more than 3 of the first 5 places while another has an itemworth doing.+**Lower priority.** A `later` item is real and stays listed, after every `now` and+`next` item, with the reason it can wait as its tier reason. Code shape decides+(`analysis/health/worth.py`, one rule for every default list); the hot-file bonus+orders items but never lifts one out of `later`, and a later item's rank facts+read "value within later" and its shape-only size. A function-size problem is+`later` when the function is under CCN 40, 200 lines and nesting 6 (nesting under+8 counts only in a function of 100 lines or more) and not both CCN 25 and nesting+5; when one dispatch on one value holds 60% of its decisions; when its nesting is+one else-if or ternary chain; or when it is long with CCN under 20 and nesting+under 5, however long. Otherwise, from CCN 80, 400 lines or nesting 8 a+function is worth doing whatever its branching. A complex condition and a single error site (a swallowed or broad+catch, an unwrap or panic) are `later` too: each is a local fix. The same rule orders the+default findings list (`get_health`, the REST findings list): findings worth doing+first lead, and each other one carries `lower_priority`, the reason it can wait.+Class-design findings (god class, low cohesion, long parameter lists) and findings+that rest on git history alone are lower priority there. A performance+opportunity carries `lower_priority` unless production code runs it over data+that grows.+**Verify.** Each item carries up to 5 tests from its stored validation profile,each with how it reaches the changed code (call graph, import graph, a matchingname or a coverage report), and the command that runs them. A finding with nodiff --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 3e7dd2085..8155cac20 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@@ -61,6 +61,17 @@ from repowise.core.analysis.health.perf.opportunity_rank import (from repowise.core.analysis.health.rows import detail_map, field, json_fieldfrom repowise.core.analysis.health.scoring import biomarker_dimensionfrom repowise.core.analysis.health.suggestions import suggestion_for+from repowise.core.analysis.health.worth import (+ LOW_PRIORITY_LABEL,+ SIZE_MARKERS,+ WORTH_MAGNITUDE,+ dispatch_shaped,+ low_priority,+ magnitude,+ measure,+ perf_low_priority,+ worth_size,+)from repowise.core.analysis.next_call import ActionCommandfrom repowise.core.code_origin import path_origin@@ -99,21 +110,15 @@ Rows = Iterable[Any]MIN_WORTH = 0.5#: Credited health gain cut points for value 1, 2 and 3.GAIN_CUTS = (0.5, 1.5, 3.0)-#: Problem-size cut points for value 1 to 4. Health credit is calibrated per-#: finding and saturates, so a function far past every bar would rank with a-#: tidy one without these. Each cut is a multiple of the detector's own bar.-#: CCN 20 is twice the complex_method bar; 40, 80 and 150 double on from it.-SIZE_CCN = (20, 40, 80, 150)-#: 100 lines is past the large_method bar; 800 is a module living in one body.-SIZE_NLOC = (100, 200, 400, 800)-#: Nesting 5 is one past the nested_complexity bar; 8 is unreadable.-SIZE_NESTING = (5, 6, 8, 99)+#: Problem size, value 1 to 4, reads ``worth.SIZE_*``: health credit is+#: calibrated per finding and saturates, so a function far past every bar+#: would rank with a tidy one without them.#: A critical finding or a brain method is at least this size.SIZE_SEVERE = 2#: Measured size (CCN, lines or nesting alone, before the severity floor and#: the hot-file bonus) from which an item leads as "break up", naming the whole#: problem: CCN 40, 200 lines or nesting 6.-SIZE_BREAK_UP = 2+SIZE_BREAK_UP = WORTH_MAGNITUDE#: The highest value any unit reaches.VALUE_MAX = 4#: A file in the top fifth of production files by churn or dependents is hot.@@ -123,15 +128,10 @@ MAX_TESTS = 5MAX_STEPS = 5MAX_CONTEXT = 3#: In the first HEAD places no kind takes more than HEAD_PER_KIND, unless the-#: other kinds have nothing at value 2 or above.+#: other kinds have nothing above the later tier.HEAD = 5HEAD_PER_KIND = 3DEFAULT_LIMIT = 10-#: Findings that measure one function's size; a unit led by one of them, or by-#: an Extract Method step, is a function-level complexity unit.-SIZE_MARKERS = frozenset(- {"complex_method", "nested_complexity", "brain_method", "large_method", "bumpy_road"}-)#: A function-level complexity unit needs this many code lines or this CCN.#: Picked on the dev labels (67 complexity rows): 30 / 15 drops 13 rejected#: small functions and 4 accepted ones; no cut that keeps every accepted row@@ -260,18 +260,9 @@ def _gain_value(gain: float, hot: bool) -> int:return min(3, sum(gain >= cut for cut in GAIN_CUTS) + int(hot))-def _magnitude(shape: Mapping[str, int]) -> int:- """How far the measured CCN, size or nesting sits past its bar, 0 to 4."""- return max(- sum(shape.get("ccn", 0) >= c for c in SIZE_CCN),- sum(shape.get("nloc", 0) >= c for c in SIZE_NLOC),- sum(shape.get("max_nesting", 0) >= c for c in SIZE_NESTING),- )--def _size_value(shape: Mapping[str, int], hot: bool) -> int:"""How big the problem is, 0 to 4; a hot file counts one more."""- base = max(_magnitude(shape), SIZE_SEVERE if shape.get("severe") else 0)+ base = max(magnitude(shape), SIZE_SEVERE if shape.get("severe") else 0)return min(VALUE_MAX, base + int(hot and base > 0))@@ -371,7 +362,7 @@ class _Files:),(),)- return _measure(found)+ return measure(found)def cloned(self, path: str, shape: Mapping[str, int]) -> bool:"""Whether a stored duplicate overlaps the function ``shape`` spans."""@@ -439,7 +430,7 @@ class _Files:return "deprecated"if not complexity:return None- if shape.get("dispatch_pct", 0) >= DISPATCH_SHARE * 100 and not self.cloned(path, shape):+ if dispatch_shaped(shape) and not self.cloned(path, shape):return "inherent_dispatch"if _small(shape):return "small_function"@@ -490,7 +481,13 @@ class _Files:return out-def _tier(value: int, confidence: str, ready: bool) -> tuple[str, str]:+def _tier(value: int, confidence: str, ready: bool, low: str | None) -> tuple[str, str]:+ """The tier and its reason, from a value that leaves the hot-file bonus+ out: history orders items within a tier but never lifts one. A problem+ the shape rule calls lower priority (``worth.low_priority``) is ``later``+ whatever its value."""+ if low is not None:+ return "later", LOW_PRIORITY_LABEL[low]if value >= 2 and LEVEL_RANK.get(confidence, 0) >= 1 and ready:return "now", "worth doing, and the plan is safe to start"if value >= 2:@@ -511,10 +508,12 @@ def _finish(rank_inputs: Callable[[], list[FixRankFact]],fields: Callable[[], dict[str, Any]],may_lead: bool = True,+ low: str | None = None,+ cold_value: int | None = None,) -> _Unit:confidence = confidence if confidence in LEVEL_RANK else "low"effort = effort if effort in FIX_EFFORTS else "M"- tier, why_tier = _tier(value, confidence, ready)+ tier, why_tier = _tier(value if cold_value is None else cold_value, confidence, ready, low)item_id = fix_id(kind, source_id)def write(rank: int) -> FixItem:@@ -525,7 +524,8 @@ def _finish(kind=kind,improves=improves,why_ranked=(- FixRankFact("value", str(value)),+ # A later item ranks by value only among later items.+ FixRankFact("value" if low is None else "value within later", str(value)),*rank_inputs(),FixRankFact("tier", why_tier),),@@ -708,13 +708,14 @@ def _refactor_unit(shape = files.shape(path, lead.get("target_symbol"))size = _size_value(shape, hot)cloned = lead_type == "extract_method" and files.cloned(path, shape)+ low = low_priority(marker, shape, function_size=lead_type == "extract_method")def fields() -> dict[str, Any]:lead_plan = plans.get(lead.get("plan_id"))start, end = _span(lead_plan)body = _plan_body(lead_plan)if (- _magnitude(shape) >= SIZE_BREAK_UP+ magnitude(shape) >= SIZE_BREAK_UPand lead_type == "extract_method"and startand end@@ -815,7 +816,8 @@ def _refactor_unit(return _finish(kind="refactor",source_id=field(row, "opportunity_id"),- value=_lifted(max(_gain_value(gain, hot), size), cloned),+ value=_value(gain, shape, cloned, hot=hot),+ cold_value=_value(gain, shape, cloned, hot=False),ready=mechanical or confidence == "high",score=_num(field(row, "rank_score")),confidence=confidence if confidence in LEVEL_RANK else "medium",@@ -823,17 +825,20 @@ def _refactor_unit(improves=dimension if dimension in FIX_IMPROVES else "maintainability",rank_inputs=lambda: [FixRankFact("health gain", f"{gain:.2f}"),- FixRankFact("problem size", str(size)),+ FixRankFact("problem size", str(size if low is None else worth_size(shape))),FixRankFact("hot file", "yes" if hot else "no"),FixRankFact("duplicate inside", "yes" if cloned else "no"),],fields=fields,+ low=low,)-def _lifted(value: int, cloned: bool) -> int:- """A complexity unit with a duplicate in the same function is one step- more worth doing: raters accepted that shape almost every time."""+def _value(gain: float, shape: Mapping[str, int], cloned: bool, *, hot: bool) -> int:+ """The larger of the gain and the problem size, one step more when a+ duplicate sits in the same function: raters accepted that shape almost+ every time."""+ value = max(_gain_value(gain, hot), _size_value(shape, hot))return min(VALUE_MAX, value + 1) if cloned else value@@ -1073,6 +1078,7 @@ def _perf_unit(confidence=confidence,effort=effort or "M",improves="performance",+ low=perf_low_priority(lead),rank_inputs=lambda: [FixRankFact("runs in", field(lead, "execution_context") or "unknown"),FixRankFact("entry reachable", text.REACH_ANSWER.get(exposure or "", "unknown")),@@ -1099,12 +1105,13 @@ def _finding_unit(lead: Any, files: _Files, first: FixStep) -> _Unit:shape = files.shape(path, function)size = _size_value(shape, hot)cloned = marker in SIZE_MARKERS and files.cloned(path, shape)+ low = low_priority(marker, shape, error_kind=detail_map(lead).get("kind"))def fields() -> dict[str, Any]:where = function or text.basename(path)summary = text.first_sentence(suggestion_for(marker))line = field(lead, "line_start")- if _magnitude(shape) >= SIZE_BREAK_UP and function and marker in SIZE_MARKERS:+ if magnitude(shape) >= SIZE_BREAK_UP and function and marker in SIZE_MARKERS:title = f"Break up {where} ({text.size_brief(shape)})"else:title = text.FINDING_TITLE.get(marker, "Address the finding in {where}").format(@@ -1123,7 +1130,7 @@ def _finding_unit(lead: Any, files: _Files, first: FixStep) -> _Unit:[FixFact("finding", text.marker_label(marker)),*([FixFact("size", size_text)] if (size_text := text.size_line(shape)) else []),- FixFact("severity", field(lead, "severity") or "unknown"),+ FixFact("severity", _severity(field(lead, "severity"), low)),*files.common_facts(path),][:MAX_FACTS]),@@ -1150,7 +1157,8 @@ def _finding_unit(lead: Any, files: _Files, first: FixStep) -> _Unit:return _finish(kind="finding",source_id=public_id or f"{path}::{marker}::{function or ''}",- value=_lifted(max(_gain_value(impact, hot), size), cloned),+ value=_value(impact, shape, cloned, hot=hot),+ cold_value=_value(impact, shape, cloned, hot=False),ready=False,score=impact,confidence="medium",@@ -1158,14 +1166,21 @@ def _finding_unit(lead: Any, files: _Files, first: FixStep) -> _Unit:improves=dimension if dimension in FIX_IMPROVES else "defect",rank_inputs=lambda: [FixRankFact("health gain", f"{impact:.2f}"),- FixRankFact("problem size", str(size)),+ FixRankFact("problem size", str(size if low is None else worth_size(shape))),FixRankFact("hot file", "yes" if hot else "no"),FixRankFact("duplicate inside", "yes" if cloned else "no"),],fields=fields,+ low=low,)+def _severity(severity: str | None, low: str | None) -> str:+ """The detector's severity; on a later item it says the tier overrides it."""+ severity = severity or "unknown"+ return severity if low is None else f"{severity} by the detector; lower priority by shape"++def _small(shape: Mapping[str, int]) -> bool:"""Under both size floors. A function whose size findings carry no linecount is measured by its span, which bounds its code lines from above; one@@ -1239,6 +1254,7 @@ def _order(units: list[_Unit]) -> list[_Unit]:ranked = sorted(units,key=lambda u: (+ u.tier == "later",-u.value,TIER_RANK[u.tier],-LEVEL_RANK.get(u.confidence, 0),@@ -1256,7 +1272,7 @@ def _order(units: list[_Unit]) -> list[_Unit]:(ufor u in ranked- if u.value >= 2+ if u.tier != "later"and u.kind != pick.kindand taken[u.kind] < HEAD_PER_KIND),@@ -1282,41 +1298,6 @@ def _by_function(findings: Iterable[Any]) -> dict[tuple[str, str], list[Any]]:return dict(out)-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,- ``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.- """- shape: dict[str, int] = {}- for f in findings:- if field(f, "severity") == "critical" or field(f, "biomarker_type") == "brain_method":- shape["severe"] = 1- details = detail_map(f)- if details.get("deprecated"):- shape["deprecated"] = 1- deepest = details.get("deepest_block")- if isinstance(deepest, dict) and deepest.get("start") and "deep_start" not in shape:- shape["deep_start"] = int(deepest["start"])- shape["deep_end"] = int(deepest.get("end") or deepest["start"])- share = details.get("dispatch_share")- if isinstance(share, (int, float)):- shape["dispatch_pct"] = max(shape.get("dispatch_pct", 0), round(share * 100))- if field(f, "biomarker_type") in SIZE_MARKERS:- start, end = field(f, "line_start"), field(f, "line_end")- if start and end:- shape["start"] = min(shape.get("start", start), start)- shape["end"] = max(shape.get("end", end), end)- for k in ("ccn", "nloc", "max_nesting", "lcom4", "method_count"):- v = details.get(k)- if isinstance(v, (int, float)) and v > shape.get(k, 0):- shape[k] = int(v)- return shape--def _basis(metrics: Rows) -> dict[str, str | None]:stamped = [(str(at), at, m) for m in metrics if (at := field(m, "updated_at"))]if not stamped:diff --git a/packages/core/src/repowise/core/analysis/health/perf/serving.py b/packages/core/src/repowise/core/analysis/health/perf/serving.pyindex 3b91eb69d..2e1e5bd70 100644--- a/packages/core/src/repowise/core/analysis/health/perf/serving.py+++ b/packages/core/src/repowise/core/analysis/health/perf/serving.py@@ -21,6 +21,7 @@ from repowise.core.analysis.health.finding_identity import finding_public_idfrom repowise.core.analysis.health.fix_first.text import perf_costfrom repowise.core.analysis.health.queue_rules import NULL_VALUE, FilterRule, SortKeysfrom repowise.core.analysis.health.rows import detail_map, field, json_field+from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL, perf_low_priorityfrom .opportunities import PERFORMANCE_MODEL_VERSIONfrom .opportunity_rank import DEFAULT_QUEUE_STATES, NON_LEADING_MARKERS@@ -376,6 +377,8 @@ def serialize(row: Any, link: PlanLink, *, summary: bool = False) -> dict[str, A"plan_reference": link.public_id,"plan_status": link.state,"plan_reason": link.reason,+ # Why it can wait; the stored rank already orders by loop size.+ "lower_priority": LOW_PRIORITY_LABEL.get(perf_low_priority(row) or ""),}if summary:return payloaddiff --git a/packages/core/src/repowise/core/analysis/health/worth.py b/packages/core/src/repowise/core/analysis/health/worth.pynew file mode 100644index 000000000..88bf76bcc--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/worth.py@@ -0,0 +1,308 @@+"""Whether a measured problem is worth doing first, or real but lower priority.++Every default list reads this one rule, so a function judged lower priority+here is lower priority everywhere. Code shape decides: how far the function+sits past each detector's bar, and whether its branching is one dispatch on+one value. Git history may order items within a tier; it never lifts an item+into the top one.++A lower-priority problem is still real and stays listed. Its label says why it+can wait and never reads as the next thing to do.+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Iterable, Mapping, Sequence+from typing import Any, Literal++from .complexity.dispatch import DISPATCH_SHARE+from .rows import detail_map, field++#: Problem-size cut points. Each is a multiple of the detector's own bar: CCN+#: 20 is twice the complex_method bar and 40, 80 and 150 double on from it;+#: 100 lines is past the large_method bar and 800 is a module in one body;+#: nesting 5 is one past the nested_complexity bar and 8 is unreadable.+SIZE_CCN = (20, 40, 80, 150)+SIZE_NLOC = (100, 200, 400, 800)+SIZE_NESTING = (5, 6, 8, 99)+#: Findings that measure one function's size.+SIZE_MARKERS = frozenset(+ {"complex_method", "nested_complexity", "brain_method", "large_method", "bumpy_road"}+)+#: How far past its bars (see :func:`worth_size`) a function must sit to be+#: worth doing first: CCN 40, 200 lines or nesting 6. The same size from which+#: an item is titled "break up".+WORTH_MAGNITUDE = 2+#: From this size (CCN 80, 400 lines or nesting 8) a function is worth doing+#: first whatever its branching looks like: a dispatch that big has arms worth+#: splitting out. Length with simple control flow stays lower priority.+EXTREME_MAGNITUDE = 3+#: A function at least this branchy and this deep is worth doing first even+#: under the size bars: tangled, not just long.+TANGLED_CCN = 25+TANGLED_NESTING = 5++LowPriority = Literal[+ "dispatch",+ "chain",+ "near_bar",+ "deep_block",+ "straight",+ "condition",+ "swallow",+ "broad_catch",+ "unwrap",+ "handler",+ "design",+ "history",+ "bounded_loop",+ "unmeasured_cost",+ "not_production",+ "unknown_context",+ "unreached_call",+]++#: Why an item can wait, as the tier reason a surface shows beside it.+LOW_PRIORITY_LABEL: dict[str, str] = {+ "dispatch": (+ "lower priority: most of its branching is one dispatch on one value, "+ "which usually reads fine as written"+ ),+ "chain": "lower priority: one long else-if or ternary chain, deep by count but flat to read",+ "near_bar": "lower priority: past the bar, but under CCN 40, 200 lines and nesting 6",+ "deep_block": "lower priority: deeply nested, but under 100 lines",+ "straight": "lower priority: long, but its control flow is simple",+ "condition": "lower priority: the fix is one condition, not the function",+ "swallow": "lower priority: a swallowed error, which is sometimes deliberate",+ "broad_catch": "lower priority: a broad catch, which may be deliberate at a boundary",+ "unwrap": "lower priority: an unwrap or panic that may be unreachable",+ "handler": "lower priority: error handling at one site",+ "design": "lower priority: a design signal that seldom needs a change on its own",+ "history": "lower priority: it rests on git history alone, not on the code's shape",+ "bounded_loop": "lower priority: the loop is bounded",+ "unmeasured_cost": "lower priority: nothing shows the loop grows with the data",+ "not_production": "lower priority: it runs outside production code",+ "unknown_context": "lower priority: where this code runs is unknown",+ "unreached_call": "lower priority: no entry point is known to reach it",+}++#: Findings about one expression or one error site: real, and small to fix.+_LOCAL_MARKERS: dict[str, LowPriority] = {+ "complex_conditional": "condition",+ "error_handling": "handler",+}+#: Class and signature findings whose fix raters seldom took (the Fix first+#: low-value kinds): real, and a judgment call.+_DESIGN_MARKERS = frozenset({"god_class", "low_cohesion", "primitive_obsession"})+#: An error_handling finding's stored ``kind``, by the reason it can wait.+_ERROR_KINDS: dict[str, LowPriority] = {+ "swallowed_catch": "swallow",+ "go_swallow": "swallow",+ "bare_except": "swallow",+ "broad_except": "broad_catch",+ "unsafe_unwrap": "unwrap",+ "panic_macro": "unwrap",+}+++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,+ ``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.+ """+ shape: dict[str, int] = {}+ for f in findings:+ if field(f, "severity") == "critical" or field(f, "biomarker_type") == "brain_method":+ shape["severe"] = 1+ details = detail_map(f)+ if details.get("deprecated"):+ shape["deprecated"] = 1+ deepest = details.get("deepest_block")+ if isinstance(deepest, dict) and deepest.get("start") and "deep_start" not in shape:+ shape["deep_start"] = int(deepest["start"])+ shape["deep_end"] = int(deepest.get("end") or deepest["start"])+ share = details.get("dispatch_share")+ if isinstance(share, (int, float)):+ shape["dispatch_pct"] = max(shape.get("dispatch_pct", 0), round(share * 100))+ if field(f, "biomarker_type") in SIZE_MARKERS:+ start, end = field(f, "line_start"), field(f, "line_end")+ if start and end:+ shape["start"] = min(shape.get("start", start), start)+ shape["end"] = max(shape.get("end", end), end)+ for k in ("ccn", "nloc", "max_nesting", "lcom4", "method_count"):+ v = details.get(k)+ if isinstance(v, (int, float)) and v > shape.get(k, 0):+ shape[k] = int(v)+ return shape+++def magnitude(shape: Mapping[str, int]) -> int:+ """How far the measured CCN, size or nesting sits past its bar, 0 to 4."""+ return max(+ sum(shape.get("ccn", 0) >= c for c in SIZE_CCN),+ sum(shape.get("nloc", 0) >= c for c in SIZE_NLOC),+ sum(shape.get("max_nesting", 0) >= c for c in SIZE_NESTING),+ )+++def dispatch_shaped(shape: Mapping[str, int]) -> bool:+ """Most of the function's branching is one dispatch on one value."""+ return shape.get("dispatch_pct", 0) >= DISPATCH_SHARE * 100+++#: Nesting this share of the CCN or more is one else-if or ternary chain,+#: each arm nested in the last: deep by count, flat to read.+CHAIN_SHARE = 0.8+++def _chained(shape: Mapping[str, int]) -> bool:+ ccn = shape.get("ccn", 0)+ return ccn >= SIZE_CCN[0] and shape.get("max_nesting", 0) >= CHAIN_SHARE * ccn+++def worth_size(shape: Mapping[str, int]) -> int:+ """:func:`magnitude` with nesting under 8 counted only in a function past+ the length bar: moderate depth in a short function is a small fix."""+ nloc = shape.get("nloc") or 0+ if not nloc and shape.get("start") and shape.get("end"):+ nloc = shape["end"] - shape["start"] + 1+ if nloc >= SIZE_NLOC[0] or shape.get("max_nesting", 0) >= SIZE_NESTING[2]:+ return magnitude(shape)+ return magnitude({**shape, "max_nesting": 0})+++def low_priority(+ marker: str | None,+ shape: Mapping[str, int],+ *,+ function_size: bool = False,+ error_kind: str | None = None,+) -> LowPriority | None:+ """Why a problem of kind ``marker`` on a function of ``shape`` can wait,+ or ``None`` when it is worth doing first. ``function_size`` judges any+ marker but a local one as a function-size problem (an Extract Method plan+ answers the function's size, whichever finding led it). ``error_kind`` is+ an error_handling finding's stored ``kind``, which picks its reason.++ A condition or one error site is a local fix. A function-size problem is+ worth doing first when the function is far past a bar+ (:data:`WORTH_MAGNITUDE`) and its branching is not one dispatch, when it is+ both branchy and deep (CCN 25 and nesting 5), or when it is past+ :data:`EXTREME_MAGNITUDE` whatever its branching. An else-if or ternary+ chain is flat however deep it counts; length with CCN under 20 and nesting+ under 5 is a table or a straight sequence, however long. Other kinds keep+ their own rules, so they get ``None``.+ """+ if marker in _DESIGN_MARKERS:+ return "design"+ local = _LOCAL_MARKERS.get(marker or "")+ if local == "handler":+ return _ERROR_KINDS.get(error_kind or "", "handler")+ if local is not None:+ return local+ if marker not in SIZE_MARKERS and not function_size:+ return None+ if not any(shape.get(k) for k in ("ccn", "nloc", "max_nesting")):+ return None # nothing measured: no grounds to call it small+ return _size_reason(shape)+++def _size_reason(shape: Mapping[str, int]) -> LowPriority | None:+ """:func:`low_priority` for a measured function-size problem."""+ if _chained(shape):+ return "chain"+ size = worth_size(shape)+ # Past the bar on length alone, however long: wiring, a table, a sequence.+ simple = shape.get("ccn", 0) < SIZE_CCN[0] and shape.get("max_nesting", 0) < SIZE_NESTING[0]+ if size >= WORTH_MAGNITUDE and simple:+ return "straight"+ if size >= EXTREME_MAGNITUDE:+ return None+ if dispatch_shaped(shape):+ return "dispatch"+ if shape.get("ccn", 0) >= TANGLED_CCN and shape.get("max_nesting", 0) >= TANGLED_NESTING:+ return None+ if size < WORTH_MAGNITUDE:+ return "deep_block" if magnitude(shape) >= WORTH_MAGNITUDE else "near_bar"+ return None+++def finding_priorities(findings: Sequence[Any]) -> list[LowPriority | None]:+ """:func:`low_priority` for each finding, in order. A function's shape is+ measured over every finding on it in ``findings``; a finding that rests+ on git history alone is ``history``."""+ from .models import split_by_origin++ history = {id(f) for f in split_by_origin(findings)[1]}+ by_function: dict[tuple[str, str], list[Any]] = defaultdict(list)+ for f in findings:+ if field(f, "function_name"):+ by_function[(field(f, "file_path"), field(f, "function_name"))].append(f)+ out: list[LowPriority | None] = []+ for f in findings:+ if id(f) in history:+ out.append("history")+ continue+ key = (field(f, "file_path"), field(f, "function_name"))+ out.append(+ low_priority(+ field(f, "biomarker_type"),+ measure(by_function.get(key, [f])),+ error_kind=detail_map(f).get("kind"),+ )+ )+ return out+++#: Performance causes that cost once per call, not once per loop iteration:+#: they lead when an entry point reaches them.+_PER_CALL_MARKERS = frozenset({"hot_path_sync_io", "blocking_sync_in_async", "blocking_io_under_lock"})+#: Causes whose cost grows with the data by their shape alone.+_GROWING_MARKERS = frozenset({"goroutine_in_unbounded_loop", "sql_cartesian_join"})+++def perf_low_priority(row: Any) -> LowPriority | None:+ """Why a performance opportunity can wait. In production code a loop cause+ leads when its loop grows with the data, a per-call cause when an entry+ point reaches it, and an unbounded goroutine loop or a cartesian join+ always; the reason names whichever fact is missing."""+ context = field(row, "execution_context")+ if context != "production":+ return "unknown_context" if context in (None, "unknown") else "not_production"+ marker = field(row, "biomarker_type")+ facets = detail_map(row).get("facets") or {}+ if marker in _GROWING_MARKERS:+ return None+ if marker in _PER_CALL_MARKERS:+ return None if facets.get("exposure") == "entry_reachable" else "unreached_call"+ magnitude_ = facets.get("loop_magnitude")+ if magnitude_ == "grows_with_data":+ return None+ return "bounded_loop" if magnitude_ == "bounded" else "unmeasured_cost"+++__all__ = [+ "CHAIN_SHARE",+ "EXTREME_MAGNITUDE",+ "LOW_PRIORITY_LABEL",+ "SIZE_CCN",+ "SIZE_MARKERS",+ "SIZE_NESTING",+ "SIZE_NLOC",+ "TANGLED_CCN",+ "TANGLED_NESTING",+ "WORTH_MAGNITUDE",+ "LowPriority",+ "dispatch_shaped",+ "finding_priorities",+ "low_priority",+ "magnitude",+ "measure",+ "perf_low_priority",+ "worth_size",+]diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex fe14e0801..3772ea715 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -82,6 +82,7 @@ from .health import (get_health_summary,get_perf_coverage,get_scored_file_paths,+ health_finding_priorities,list_health_snapshots,prune_unscored_health_rows,replace_governance_findings,@@ -173,6 +174,7 @@ __all__ = ["get_symbol_names","get_test_coverage_summary","has_branch_lines",+ "health_finding_priorities","is_new_doc_drift_row","list_evidence_for_opportunities","list_health_snapshots",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/health.py b/packages/core/src/repowise/core/persistence/crud/analysis/health.pyindex 05a2c61fc..ff79bff52 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/health.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/health.py@@ -34,6 +34,7 @@ from ....analysis.health.ranking import (from ....analysis.health.rows import detail_map, split_tests, split_unscoredfrom ....analysis.health.scope import scores_languagefrom ....analysis.health.scoring import ADVISORY_DIMENSION, SCORE_FIELDS, nloc_weighted_attr+from ....analysis.health.worth import LowPriority, finding_prioritiesfrom ....test_paths import is_test_related_pathfrom ...models import (DocDriftFinding,@@ -474,7 +475,8 @@ async def get_health_findings(include_withheld: bool = False,limit: int | None = None,) -> list[HealthFinding]:- """Findings for one repository, ordered by health impact.+ """Findings for one repository: worth doing first ahead of lower-priority+ ones (``worth.finding_priorities``), each part ordered by health impact.Finding types the registry withholds (``finding_registry``) are left out,so every surface built on this read shows only what has earned a place; a@@ -494,7 +496,7 @@ async def get_health_findings(reviewed without a second read.``file_paths`` scopes to a set of files in one read; an empty sequence- matches nothing. ``limit`` caps the rows read, highest impact first.+ matches nothing. ``limit`` caps the rows returned, in that order."""q = select(HealthFinding).where(HealthFinding.repository_id == repository_id)statuses = [s.strip() for s in status.split(",") if s.strip()]@@ -538,13 +540,45 @@ async def get_health_findings(allowed = [k for k, v in order.items() if v >= threshold]q = q.where(HealthFinding.severity.in_(allowed))q = q.order_by(HealthFinding.health_impact.desc())- if limit is not None:- q = q.limit(limit)result = await session.execute(q)- return _filter_excluded_paths(+ kept = _filter_excluded_paths(list(result.scalars().all()),await _health_exclude_spec(session, repository_id),)+ # A filter that drops some of a function's findings would misread its+ # shape, so the tier then reads every open finding on the kept files.+ narrowed = bool(types or exact or min_severity or dimension) or statuses != ["open"]+ reasons = (+ await health_finding_priorities(session, repository_id, kept)+ if narrowed+ else dict(zip((f.id for f in kept), finding_priorities(kept), strict=True))+ )+ # Stable: each tier keeps the impact order. The cap applies after the tier.+ ordered = sorted(kept, key=lambda f: reasons[f.id] is not None)+ return ordered if limit is None else ordered[:limit]+++async def health_finding_priorities(+ session: AsyncSession, repository_id: str, findings: Sequence[HealthFinding]+) -> dict[str, LowPriority | None]:+ """Each finding's ``worth`` reason by id, measured over every open,+ shown finding on its file: a list filtered by marker, severity or status+ still tiers a function by its whole shape."""+ paths = sorted({f.file_path for f in findings})+ peers: list[HealthFinding] = []+ for i in range(0, len(paths), _BATCH_SIZE):+ q = select(HealthFinding).where(+ HealthFinding.repository_id == repository_id,+ HealthFinding.status == "open",+ HealthFinding.file_path.in_(paths[i : i + _BATCH_SIZE]),+ HealthFinding.biomarker_type.not_in(excluded_types()),+ )+ peers.extend((await session.execute(q)).scalars().all())+ known = {f.id for f in peers}+ # A finding outside the open set (resolved, acknowledged) is measured with it.+ peers.extend(f for f in findings if f.id not in known)+ reasons = dict(zip((f.id for f in peers), finding_priorities(peers), strict=True))+ return {f.id: reasons[f.id] for f in findings}async def get_deduction_by_path(diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py b/packages/server/src/repowise/server/mcp_server/tool_health/blocks.pyindex 4f1cab351..7d8313dfe 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/blocks.py@@ -66,14 +66,20 @@ def _add_biomarkers(result: dict[str, Any], data: HealthData, pager: Pager) -> N"""findings, repository = data.findings, data.reference_repositoryresult["findings"] = pager.bound(- [_serialize_finding(f, repository) for f in findings.finding_rows],+ [+ _serialize_finding(f, repository, findings.lower_priority.get(f.id))+ for f in findings.finding_rows+ ],"findings",)result["findings_total"] = findings.findings_total# Dashboard mode only (targeted mode already set ``findings``), so this# uses the same production/test split as ``top_findings``.result["test_findings"] = pager.bound(- [_serialize_finding(f, repository) for f in findings.test_finding_rows],+ [+ _serialize_finding(f, repository, findings.lower_priority.get(f.id))+ for f in findings.test_finding_rows+ ],"test_findings",)result["test_findings_total"] = findings.test_findings_totaldiff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.pyindex 8d05d74a8..0cb1064e4 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py@@ -64,13 +64,23 @@ def build_dashboard("high_leverage_files": pager.bound(_high_leverage_rows(data, gap), "high_leverage_files"),"high_leverage_files_total": len(data.by_leverage),"top_findings": pager.bound(- [_serialize_finding(f, data.reference_repository) for f in findings.finding_rows],+ [+ _serialize_finding(+ f, data.reference_repository, findings.lower_priority.get(f.id)+ )+ for f in findings.finding_rows+ ],"top_findings",),"top_findings_total": findings.findings_total,# The test half of the same ranked set, kept out of the production list."test_findings": pager.bound(- [_serialize_finding(f, data.reference_repository) for f in findings.test_finding_rows],+ [+ _serialize_finding(+ f, data.reference_repository, findings.lower_priority.get(f.id)+ )+ for f in findings.test_finding_rows+ ],"test_findings",),"test_findings_total": findings.test_findings_total,diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/details.py b/packages/server/src/repowise/server/mcp_server/tool_health/details.pyindex 0bead93e4..c44c2b103 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/details.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/details.py@@ -9,7 +9,8 @@ from sqlalchemy import selectfrom repowise.core.analysis.health.counts import DEFAULT_COUNTSfrom repowise.core.analysis.health.refactoring.serving import evidence_blockfrom repowise.core.analysis.health.scope import DEFAULT_SCOPE-from repowise.core.persistence.crud import get_health_finding_by_public_id+from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL, finding_priorities+from repowise.core.persistence.crud import get_health_finding_by_public_id, get_health_findingsfrom repowise.core.persistence.crud.analysis.fix_first import load_fix_firstfrom repowise.core.persistence.models import HealthFindingfrom repowise.server.mcp_server._meta import build_meta as _build_meta@@ -79,6 +80,14 @@ async def _detail_response(return None+async def _lower_priority(session: Any, repository_id: str, finding: Any) -> str | None:+ """The finding's tier reason, measured over its file's open findings as+ the list measured it."""+ peers = await get_health_findings(session, repository_id, file_path=finding.file_path)+ reasons = dict(zip((f.id for f in peers), finding_priorities(peers), strict=True))+ return LOW_PRIORITY_LABEL.get(reasons.get(finding.id) or "")++async def _finding_detail_response(session: Any, repository: Any, reference_repository: str, finding_id: str) -> dict[str, Any]:@@ -87,7 +96,11 @@ async def _finding_detail_response("mode": "finding","finding_id": finding_id,"finding": (- _serialize_finding(match, reference_repository) if match else None+ _serialize_finding(+ match, reference_repository, await _lower_priority(session, repository.id, match)+ )+ if match+ else None),"resolved": match is not None,"_meta": _build_meta(diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py b/packages/server/src/repowise/server/mcp_server/tool_health/findings.pyindex dafba1249..ba3e05b79 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/findings.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/findings.py@@ -7,6 +7,7 @@ from typing import Anyfrom sqlalchemy import select+from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL, finding_prioritiesfrom repowise.core.persistence.models import HealthFindingfrom repowise.server.mcp_server.tool_health.population import Populationfrom repowise.server.mcp_server.tool_health.request import HealthRequest@@ -53,6 +54,18 @@ class FindingSets:findings_total: inttest_finding_rows: list[Any] = field(default_factory=list)test_findings_total: int = 0+ #: Row id -> why the finding can wait, for each lower-priority row.+ lower_priority: dict[Any, str] = field(default_factory=dict)+++def _tiered(rows: list[Any], measured_over: list[Any]) -> tuple[list[Any], dict[Any, str]]:+ """Ranked *rows* with those worth doing first ahead, and each later row's+ reason. Shapes are measured over *measured_over*, the set before any+ dimension filter, so a filter never changes a function's tier."""+ reasons = dict(zip((r.id for r in measured_over), finding_priorities(measured_over), strict=True))+ ranked = sorted(_rank_emitted(rows), key=lambda r: reasons.get(r.id) is not None)+ labels = {r.id: LOW_PRIORITY_LABEL[why] for r in ranked if (why := reasons.get(r.id))}+ return ranked, labelsdef _open_findings(repository: Any, req: HealthRequest) -> tuple[Any, ...]:@@ -82,8 +95,8 @@ async def load_targeted_findings(),"file_path",))- emitted = _rank_emitted(- [f for f in finding_rows if _in_dimensions(f, req.ranked_dimensions)]+ emitted, labels = _tiered(+ [f for f in finding_rows if _in_dimensions(f, req.ranked_dimensions)], finding_rows)return FindingSets(finding_rows=emitted,@@ -91,6 +104,7 @@ async def load_targeted_findings(legend_rows=emitted,emitted=emitted,findings_total=len(emitted),+ lower_priority=labels,)@@ -107,8 +121,8 @@ async def load_dashboard_findings()# ``lead_rows`` stays unfiltered: the leads and performance KPI must not# change because the caller asked to see one dimension.- emitted = _rank_emitted(- [r for r in lead_rows if _in_dimensions(r, req.ranked_dimensions)]+ emitted, labels = _tiered(+ [r for r in lead_rows if _in_dimensions(r, req.ranked_dimensions)], lead_rows)# Test findings get their own bucket instead of crowding the headline# list. Split before the cap, so each list is the top ``limit`` of its@@ -132,19 +146,19 @@ async def load_dashboard_findings(findings_total=len(prod_emitted),test_finding_rows=[by_id[i] for i in test_head_ids if i in by_id],test_findings_total=len(test_emitted),+ lower_priority=labels,)async def _read_lite_findings(session: Any, repository: Any, req: HealthRequest) -> list[Any]:"""Narrow read over every open finding.- The columns ``_leads_by_file`` reads, plus ``dimension`` and ``id``. A- SQLAlchemy ``Row`` exposes them as attributes, so the reduction and the- exclude filter run against it unchanged.-- ``details_json`` joins only when the performance dimension is asked for:- perf findings carry ``health_impact: 0``, so only then can one reach the- head, and the column is not worth its read cost otherwise.+ The columns ``_leads_by_file`` reads, plus ``dimension`` and ``id``, and+ what the worth tier measures a function by (``function_name``, the span,+ ``severity``, ``details_json``). A SQLAlchemy ``Row`` exposes them as+ attributes, so the reduction and the exclude filter run against it+ unchanged. Ceiling: ``details_json`` is read for every open finding, for+ the tier; storing the tier on the row would make this read narrow again."""lite_cols = [HealthFinding.id,@@ -153,17 +167,12 @@ async def _read_lite_findings(session: Any, repository: Any, req: HealthRequest)HealthFinding.biomarker_type,HealthFinding.reason,HealthFinding.dimension,+ HealthFinding.severity,+ HealthFinding.details_json,+ HealthFinding.function_name,+ HealthFinding.line_start,+ HealthFinding.line_end,]- if "performance" in req.dimension_filter:- lite_cols.append(HealthFinding.details_json)- if req.wants_performance_opportunities:- lite_cols.extend(- [- HealthFinding.function_name,- HealthFinding.line_start,- HealthFinding.line_end,- ]- )return list((await session.execute(diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.pyindex 63a74c1e8..f690abff6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/serialize.py@@ -99,7 +99,9 @@ def _legacy_health_finding_id(f: Any, repository: str) -> str:)-def _serialize_finding(f: HealthFinding, repository: str = "default") -> dict[str, Any]:+def _serialize_finding(+ f: HealthFinding, repository: str = "default", lower_priority: str | None = None+) -> dict[str, Any]:try:details = json.loads(f.details_json) if f.details_json else {}except Exception:@@ -128,6 +130,8 @@ def _serialize_finding(f: HealthFinding, repository: str = "default") -> dict[st**rank,# Provisional types only, and only when the caller opted into them.**({"verification": label} if label else {}),+ # Why it can wait, on a finding listed after those worth doing first.+ **({"lower_priority": lower_priority} if lower_priority else {}),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/targeted.py b/packages/server/src/repowise/server/mcp_server/tool_health/targeted.pyindex 12f38cfc6..b92ab67b7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/targeted.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/targeted.py@@ -43,7 +43,12 @@ def build_targeted("metrics": pager.bound(metric_payload, "metrics"),"metrics_total": len(metric_payload),"findings": pager.bound(- [_serialize_finding(f, data.reference_repository) for f in data.findings.finding_rows],+ [+ _serialize_finding(+ f, data.reference_repository, data.findings.lower_priority.get(f.id)+ )+ for f in data.findings.finding_rows+ ],"findings",),"findings_total": findings_total,diff --git a/packages/server/src/repowise/server/routers/code_health/findings_routes.py b/packages/server/src/repowise/server/routers/code_health/findings_routes.pyindex 0ff74bfb9..5f604d0aa 100644--- a/packages/server/src/repowise/server/routers/code_health/findings_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/findings_routes.py@@ -53,7 +53,9 @@ async def list_health_findings(counts: str = CountsQuery,session: AsyncSession = Depends(get_db_session),) -> list[dict]:- """Findings, ranked by health impact. Open work unless ``status`` says otherwise.+ """Findings worth doing first, then lower-priority ones labelled with why+ they can wait, each part ranked by health impact. Open work unless+ ``status`` says otherwise.The zero-impact dimensions, performance and advisory, are out of theunfiltered list by default. Their findings carry a health impact of zero by@@ -102,8 +104,11 @@ async def list_health_findings(# it under one would show work that sums past the figure above it.if parse_counts(counts) == "code_shape":findings = split_by_origin(findings)[0]+ shown = findings[:limit]+ # Measured over every open finding on each file, whatever this list kept.+ reasons = await crud.health_finding_priorities(session, repo_id, shown)return await _attach_symbol_ids(- session, repo_id, [_finding_to_dict(f) for f in findings[:limit]]+ session, repo_id, [_finding_to_dict(f, reasons[f.id]) for f in shown])diff --git a/packages/server/src/repowise/server/routers/code_health/serializers.py b/packages/server/src/repowise/server/routers/code_health/serializers.pyindex 5bda516d1..37886454e 100644--- a/packages/server/src/repowise/server/routers/code_health/serializers.py+++ b/packages/server/src/repowise/server/routers/code_health/serializers.py@@ -13,9 +13,10 @@ from repowise.core.analysis.health.aggregation import (from repowise.core.analysis.health.scoring import unclamped_scorefrom repowise.core.analysis.health.signals import FileSignalsfrom repowise.core.analysis.health.trends import FileTrend+from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL-def _finding_to_dict(f: Any) -> dict:+def _finding_to_dict(f: Any, lower_priority: str | None = None) -> dict:try:details = json.loads(f.details_json) if f.details_json else {}except Exception:@@ -38,6 +39,7 @@ def _finding_to_dict(f: Any) -> dict:"dimension": getattr(f, "dimension", None) or "defect",# "unverified" for a provisional type a caller asked for by name."verification": verification_label(f.biomarker_type),+ "lower_priority": LOW_PRIORITY_LABEL.get(lower_priority or ""),}diff --git a/packages/server/src/repowise/server/schemas/code_health.py b/packages/server/src/repowise/server/schemas/code_health.pyindex 6ae175e85..ae19ed8e4 100644--- a/packages/server/src/repowise/server/schemas/code_health.py+++ b/packages/server/src/repowise/server/schemas/code_health.py@@ -32,6 +32,8 @@ class HealthFindingResponse(BaseModel):dimension: str = "defect"#: ``"unverified"`` for a provisional finding type, else ``None``.verification: str | None = None+ #: Why the finding can wait, on a lower-priority finding; else ``None``.+ lower_priority: str | None = Noneclass HealthFindingWithSymbolResponse(HealthFindingResponse):diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex d3194b472..496553f6c 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -1875,6 +1875,7 @@ export interface HealthFindingResponse {status: string;dimension?: string;verification?: string | null;+ lower_priority?: string | null;}/**@@ -1897,6 +1898,7 @@ export interface HealthFindingWithSymbolResponse {status: string;dimension?: string;verification?: string | null;+ lower_priority?: string | null;symbol_id?: string | null;}diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 37fe28d62..91e32ba9d 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -342,6 +342,9 @@ export interface HealthFinding {/** `"unverified"` for a provisional finding type, shown because it was asked* for by name. Null or absent for a validated type. */verification?: string | null;+ /** Why the finding can wait ("lower priority: ..."); null when it is worth+ * doing first. Lower-priority findings are listed after the rest. */+ lower_priority?: string | null;}export type PerformanceExecutionContext = "production" | "tooling" | "test" | "unknown";@@ -490,6 +493,9 @@ export interface PerformanceOpportunity {/** Whether this cause may lead the dashboard. False for a marker below the* leading bar (lazy loads outside Django). Absent on an older store. */may_lead?: boolean;+ /** Why the opportunity can wait ("lower priority: ..."); null when its+ * production loop is known to grow with the data. */+ lower_priority?: string | null;/** Exact stored match. Never inferred from file, marker, or rank. */plan_id: string | null;plan_status: PerformancePlanStatus;diff --git a/packages/ui/__tests__/health/fixtures/performance-wire-contract.json b/packages/ui/__tests__/health/fixtures/performance-wire-contract.jsonindex b9da0a026..f63af3d79 100644--- a/packages/ui/__tests__/health/fixtures/performance-wire-contract.json+++ b/packages/ui/__tests__/health/fixtures/performance-wire-contract.json@@ -48,6 +48,7 @@"file_path","fix","intervention_symbol",+ "lower_priority","observations_total","opportunity_id","performance_model_version",diff --git a/packages/ui/__tests__/health/fixtures/performance.ts b/packages/ui/__tests__/health/fixtures/performance.tsindex b5ae42bc5..e041b242a 100644--- a/packages/ui/__tests__/health/fixtures/performance.ts+++ b/packages/ui/__tests__/health/fixtures/performance.ts@@ -46,6 +46,8 @@ export function opportunity(affected_call_sites_total: 2,affected_files_total: 2,observations_total: 6,+ // Carried on the wire; the queue does not render it yet.+ lower_priority: null,evidence: [{finding_id: "finding_1111",diff --git a/tests/unit/cli/test_health_cmd_controls.py b/tests/unit/cli/test_health_cmd_controls.pyindex 92793818a..c80697b3a 100644--- a/tests/unit/cli/test_health_cmd_controls.py+++ b/tests/unit/cli/test_health_cmd_controls.py@@ -129,6 +129,6 @@ def test_the_report_leads_with_fix_first() -> None:assert out.startswith("\nFix first (3 of 3 eligible")# The growing, reachable database loop leads; the refactor follows.assert " 1. Batch the database calls loops make through load_all " in out- assert " 2. Extract lines 20-35 of run into sum_rows (+1 more step) " in out+ assert " 2. Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows " in outassert "src/core.py:20" in outassert "verify: pytest tests/test_core_0.py" in outdiff --git a/tests/unit/health/fix_first_rows.py b/tests/unit/health/fix_first_rows.pyindex b8a96e824..c7dcf7f77 100644--- a/tests/unit/health/fix_first_rows.py+++ b/tests/unit/health/fix_first_rows.py@@ -28,9 +28,9 @@ FINDINGS = ["dimension": "defect"},{"file_path": "src/core.py", "biomarker_type": "complex_method", "severity": "high","function_name": "run", "line_start": 10, "line_end": 60, "health_impact": 1.0,- "reason": "run has cyclomatic complexity 14", "public_id": "finding_c1",+ "reason": "run has cyclomatic complexity 44", "public_id": "finding_c1","dimension": "defect",- "details": {"ccn": 14, "nloc": 50, "max_nesting": 4, "deepest_block": {"start": 30, "end": 44}}},+ "details": {"ccn": 44, "nloc": 50, "max_nesting": 4, "deepest_block": {"start": 30, "end": 44}}},{"file_path": "src/plain.py", "biomarker_type": "nested_complexity", "severity": "medium","function_name": "walk", "line_start": 5, "line_end": 40, "health_impact": 0.6,"reason": "walk nests 5 levels deep", "public_id": "finding_n1", "dimension": "defect",diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex 7fed0a7e1..3c042041f 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -83,13 +83,15 @@ def test_history_never_leads_and_rides_along_as_context() -> None:def test_text_quotes_the_stored_numbers() -> None:core = next(i for i in _build().items if i.kind == "refactor")- assert core.title == "Extract lines 20-35 of run into sum_rows (+1 more step)"+ assert core.title == (+ "Start breaking up run (CCN 44, 50 lines): first lift lines 20-35 into sum_rows"+ )# The size is a fact; the why says why it matters here.assert core.why == ("run has many independent paths through it; 9 files import it, ""changed 12 times in 90 days.")- assert ("size", "CCN 14, 50 lines, nests 4 deep") in [(f.label, f.value) for f in core.facts]+ assert ("size", "CCN 44, 50 lines, nests 4 deep") in [(f.label, f.value) for f in core.facts]assert core.action.steps[0].text == "Extract lines 20-35 of run into sum_rows(rows, limit) -> total"assert core.action.steps[1].text == "Extract lines 40-41 of run into a helper"# The model's credit is the gain, with one decimal; the builder does not re-judge it.@@ -143,12 +145,12 @@ def test_no_kind_takes_more_than_three_of_the_first_five() -> None:row["file_path"] = f"src/core{n}.py"row["details"]["steps"] = row["details"]["steps"][:1]refactors.append(row)- # Same value as the refactors (production, loop size unknown, reachable),- # lower tier.+ # A loop that grows but no entry point reaches: worth doing, ranked below+ # the refactors' value.perf = _perf("perf2_a", "s")perf["details"] = {**perf["details"],- "facets": {"loop_magnitude": "unknown", "exposure": "entry_reachable"},+ "facets": {"loop_magnitude": "grows_with_data", "exposure": "not_entry_reachable"},}queue = _build(refactoring=refactors, performance=[perf], findings=[])# The fourth place goes to the perf fix; the fifth back to a refactor,diff --git a/tests/unit/health/test_fix_first_precision.py b/tests/unit/health/test_fix_first_precision.pyindex 51a14282a..17269ffb6 100644--- a/tests/unit/health/test_fix_first_precision.py+++ b/tests/unit/health/test_fix_first_precision.py@@ -313,7 +313,24 @@ def _value(**facets) -> str:row = _perf("perf3_v", "src/db.py::fetch")row["details"] = {**row["details"], "facets": facets}item = _perf_queue(row).lead- return next(f.value for f in item.why_ranked if f.factor == "value")+ return next(f.value for f in item.why_ranked if f.factor in ("value", "value within later"))+++def test_only_a_loop_known_to_grow_leads() -> None:+ from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL+ from tests.unit.health.fix_first_rows import _perf++ def lead(**facets):+ row = _perf("perf3_t", "src/db.py::fetch")+ row["details"] = {**row["details"], "facets": facets}+ return _perf_queue(row).lead++ unknown = lead(loop_magnitude="unknown", exposure="entry_reachable")+ assert unknown.tier == "later"+ assert ("tier", LOW_PRIORITY_LABEL["unmeasured_cost"]) in [+ (f.factor, f.value) for f in unknown.why_ranked+ ]+ assert lead(loop_magnitude="grows_with_data").tier != "later"def test_an_unknown_loop_no_entry_reaches_drops_a_step() -> None:@@ -336,7 +353,9 @@ def _ranked(item, factor: str) -> str:def test_a_duplicate_inside_lifts_a_complexity_unit_one_step() -> None:plain = _queue([_finding()]).leadlifted = _queue([_finding()], plans=[_helper()]).lead- assert int(_ranked(lifted, "value")) == int(_ranked(plain, "value")) + 1+ # CCN 14 is near the bar, so both are later; the lift still orders them.+ value = "value within later"+ assert int(_ranked(lifted, value)) == int(_ranked(plain, value)) + 1assert _ranked(lifted, "duplicate inside") == "yes"assert "duplicated" in lifted.why and "duplicated" not in plain.whydiff --git a/tests/unit/health/test_worth.py b/tests/unit/health/test_worth.pynew file mode 100644index 000000000..cce42f560--- /dev/null+++ b/tests/unit/health/test_worth.py@@ -0,0 +1,205 @@+"""The shared worth rule: which problems lead a default list and which wait, labelled."""++from __future__ import annotations++from typing import get_args++import pytest++from repowise.core.analysis.health.fix_first import build_fix_first+from repowise.core.analysis.health.worth import LOW_PRIORITY_LABEL, LowPriority, low_priority+++ ("marker", "shape", "expected"),+ [+ # Far past a bar on code shape: worth doing first.+ ("complex_method", {"ccn": 47, "nloc": 191, "max_nesting": 5}, None),+ ("nested_complexity", {"ccn": 30, "nloc": 160, "max_nesting": 9}, None),+ ("large_method", {"ccn": 25, "nloc": 260, "max_nesting": 3}, None),+ # Past the bar, not by much.+ ("complex_method", {"ccn": 13, "nloc": 56, "max_nesting": 5}, "near_bar"),+ ("nested_complexity", {"ccn": 9, "nloc": 46, "max_nesting": 4}, "near_bar"),+ # Big, but one dispatch on one value, or one else-if chain.+ ("complex_method", {"ccn": 75, "nloc": 251, "max_nesting": 5, "dispatch_pct": 93}, "dispatch"),+ ("nested_complexity", {"ccn": 35, "nloc": 37, "max_nesting": 34}, "chain"),+ # Deep in one block of a short function.+ ("nested_complexity", {"ccn": 13, "nloc": 35, "max_nesting": 6}, "deep_block"),+ # Long, with simple control flow.+ ("large_method", {"ccn": 18, "nloc": 212, "max_nesting": 3}, "straight"),+ # Extreme size is worth doing whatever the branching looks like.+ ("complex_method", {"ccn": 530, "nloc": 2564, "max_nesting": 9, "dispatch_pct": 90}, None),+ # Length alone stays lower priority however long it is.+ ("large_method", {"ccn": 13, "nloc": 809, "max_nesting": 3}, "straight"),+ ("large_method", {"ccn": 14, "nloc": 60, "max_nesting": 3}, "near_bar"),+ # Nesting 8 counts at any length; under it, only past 100 lines.+ ("nested_complexity", {"ccn": 12, "nloc": 34, "max_nesting": 8}, None),+ ("nested_complexity", {"ccn": 12, "nloc": 99, "max_nesting": 6}, "deep_block"),+ ("nested_complexity", {"ccn": 12, "nloc": 100, "max_nesting": 6}, None),+ ("nested_complexity", {"ccn": 12, "nloc": 150, "max_nesting": 5}, "near_bar"),+ # The size bars, either side.+ ("complex_method", {"ccn": 39, "nloc": 120, "max_nesting": 4}, "near_bar"),+ ("complex_method", {"ccn": 40, "nloc": 120, "max_nesting": 4}, None),+ ("large_method", {"ccn": 22, "nloc": 199, "max_nesting": 4}, "near_bar"),+ ("large_method", {"ccn": 22, "nloc": 200, "max_nesting": 4}, None),+ # Branchy and deep under the bars, either side.+ ("nested_complexity", {"ccn": 25, "nloc": 73, "max_nesting": 5}, None),+ ("nested_complexity", {"ccn": 24, "nloc": 73, "max_nesting": 5}, "near_bar"),+ ("complex_method", {"ccn": 30, "nloc": 90, "max_nesting": 4}, "near_bar"),+ # Local fixes.+ ("complex_conditional", {"ccn": 32, "nloc": 75}, "condition"),+ ("error_handling", {}, "handler"),+ # Other kinds keep their own rules.+ ("split_file", {"ccn": 3}, None),+ ("god_class", {}, "design"),+ ("low_cohesion", {"lcom4": 4}, "design"),+ # Nothing measured is no ground to call a function small.+ ("complex_method", {}, None),+ ],+)+def test_low_priority_reads_code_shape(marker, shape, expected) -> None:+ assert low_priority(marker, shape) == expected+++ ("kind", "expected"),+ [+ ("swallowed_catch", "swallow"),+ ("go_swallow", "swallow"),+ ("broad_except", "broad_catch"),+ ("unsafe_unwrap", "unwrap"),+ ("panic_macro", "unwrap"),+ (None, "handler"),+ ],+)+def test_an_error_site_is_labelled_by_what_it_does(kind, expected) -> None:+ assert low_priority("error_handling", {}, error_kind=kind) == expected+++def test_an_extract_method_plan_is_judged_by_its_function() -> None:+ small = {"ccn": 10, "nloc": 40}+ assert low_priority("split_file", small) is None+ assert low_priority(None, small, function_size=True) == "near_bar"+ assert low_priority("complex_conditional", small, function_size=True) == "condition"+++def test_every_reason_has_a_label_that_does_not_ask_for_action() -> None:+ for reason in get_args(LowPriority):+ assert LOW_PRIORITY_LABEL[reason].startswith("lower priority: ")+++def _finding(path: str, name: str, details: dict, impact: float, marker="complex_method"):+ return {+ "file_path": path,+ "biomarker_type": marker,+ "severity": "high",+ "function_name": name,+ "line_start": 10,+ "line_end": 200,+ "health_impact": impact,+ "public_id": f"f_{name}",+ "dimension": "defect",+ "details": {**details, "deepest_block": {"start": 20, "end": 30}},+ }+++def test_history_orders_within_a_tier_but_never_lifts_a_small_function() -> None:+ metrics = [+ # The near-bar function sits in the busiest, most imported file.+ {"file_path": "src/hot.py", "nloc": 90, "is_test": False, "commit_count_90d": 40,+ "dependents": 30, "code_origin": "production"},+ {"file_path": "src/big.py", "nloc": 400, "is_test": False, "commit_count_90d": 1,+ "dependents": 1, "code_origin": "production"},+ *[+ {"file_path": f"src/quiet{i}.py", "nloc": 10, "is_test": False,+ "commit_count_90d": 0, "dependents": 0, "code_origin": "production"}+ for i in range(8)+ ],+ ]+ findings = [+ _finding("src/hot.py", "tidy", {"ccn": 14, "nloc": 40, "max_nesting": 4}, 3.0),+ _finding("src/big.py", "sprawl", {"ccn": 52, "nloc": 240, "max_nesting": 5}, 0.4),+ ]+ queue = build_fix_first(metrics=metrics, findings=findings)+ assert [(i.target.symbol, i.tier) for i in queue.items] == [+ ("sprawl", "next"),+ ("tidy", "later"),+ ]+ tidy = queue.items[1]+ assert ("tier", LOW_PRIORITY_LABEL["near_bar"]) in [+ (f.factor, f.value) for f in tidy.why_ranked+ ]+ # Still listed, still true: the item names the finding it came from, and+ # no rank fact or severity reads as top-tier work beside the tier reason.+ assert tidy.title == "Reduce the branching in tidy"+ ranked = {f.factor: f.value for f in tidy.why_ranked}+ assert "value" not in ranked and "value within later" in ranked+ assert ranked["problem size"] == "0"+ assert ("severity", "high by the detector; lower priority by shape") in [+ (f.label, f.value) for f in tidy.facts+ ]+++def test_a_cloned_dispatcher_stays_listed_but_waits() -> None:+ """A dispatcher with a duplicate inside is no longer excluded, so it is a+ candidate; the shape rule keeps it out of the top tier."""+ metrics = [{"file_path": "src/p.py", "nloc": 500, "is_test": False,+ "code_origin": "production"}]+ findings = [_finding("src/p.py", "parse", {"ccn": 75, "nloc": 251, "max_nesting": 5,+ "dispatch_share": 0.93}, 1.6)]+ plans = [{"public_id": "h1", "refactoring_type": "extract_helper",+ "plan": {"occurrences": [{"file": "src/p.py", "line_start": 40, "line_end": 60}]}}]+ (item,) = build_fix_first(metrics=metrics, findings=findings, plans=plans).items+ assert item.tier == "later"+ assert ("tier", LOW_PRIORITY_LABEL["dispatch"]) in [(f.factor, f.value) for f in item.why_ranked]+++def test_findings_are_tiered_per_function_and_history_waits() -> None:+ from repowise.core.analysis.health.worth import finding_priorities++ big = _finding("src/a.py", "big", {"ccn": 47, "nloc": 191, "max_nesting": 5}, 0.4)+ # Two findings on one function: the nesting finding alone says nothing+ # about size, the function's other finding does.+ deep = _finding("src/a.py", "big", {"max_nesting": 5}, 0.9, marker="nested_complexity")+ small = _finding("src/b.py", "small", {"ccn": 12, "nloc": 40}, 1.5)+ churn = {"file_path": "src/c.py", "biomarker_type": "change_entropy",+ "severity": "high", "health_impact": 2.5, "dimension": "defect"}+ rows = [churn, small, deep, big]+ assert finding_priorities(rows) == ["history", "near_bar", None, None]+++ ("context", "facets", "expected"),+ [+ ("production", {"loop_magnitude": "grows_with_data"}, None),+ ("production", {"loop_magnitude": "bounded"}, "bounded_loop"),+ ("production", {"loop_magnitude": "unknown"}, "unmeasured_cost"),+ ("production", {}, "unmeasured_cost"),+ ("tooling", {"loop_magnitude": "grows_with_data"}, "not_production"),+ ("unknown", {"loop_magnitude": "grows_with_data"}, "unknown_context"),+ ],+)+def test_a_perf_cause_leads_only_on_a_loop_that_grows(context, facets, expected) -> None:+ from repowise.core.analysis.health.worth import perf_low_priority++ row = {"execution_context": context, "biomarker_type": "io_in_loop",+ "details": {"facets": facets}}+ assert perf_low_priority(row) == expected+++ ("marker", "facets", "expected"),+ [+ ("hot_path_sync_io", {"exposure": "entry_reachable"}, None),+ ("hot_path_sync_io", {"exposure": "not_entry_reachable"}, "unreached_call"),+ ("blocking_sync_in_async", {}, "unreached_call"),+ ("goroutine_in_unbounded_loop", {}, None),+ ("sql_cartesian_join", {"loop_magnitude": "unknown"}, None),+ ],+)+def test_a_perf_cause_is_judged_by_its_kind(marker, facets, expected) -> None:+ from repowise.core.analysis.health.worth import perf_low_priority++ row = {"execution_context": "production", "biomarker_type": marker,+ "details": {"facets": facets}}+ assert perf_low_priority(row) == expecteddiff --git a/tests/unit/persistence/test_actions_loader.py b/tests/unit/persistence/test_actions_loader.pyindex c9f2bd009..9bb6539a1 100644--- a/tests/unit/persistence/test_actions_loader.py+++ b/tests/unit/persistence/test_actions_loader.py@@ -35,7 +35,7 @@ from tests.unit.persistence.helpers import insert_repoANCHOR = datetime(2026, 9, 28, 12, 0, tzinfo=UTC)#: A size finding's deepest nested block: Fix first's first concrete step.-DEEP = json.dumps({"deepest_block": {"start": 20, "end": 30}, "max_nesting": 4})+DEEP = json.dumps({"deepest_block": {"start": 20, "end": 30}, "ccn": 44, "max_nesting": 4})NOW = ANCHOR + timedelta(days=1)@@ -187,7 +187,7 @@ async def test_load_actions_view_composes_every_store(async_session) -> None:# higher-impact history marker, and the plan-ready loop; the fragile-file# rule does not repeat the file it already names.fixes = {a["target"]["path"]: a for a in rules["fix_first"]}- assert fixes["src/core.py"]["title"] == "Reduce the branching in run"+ assert fixes["src/core.py"]["title"] == "Break up run (CCN 44)"assert fixes["src/repo.py"]["title"] == "Batch the database calls loops make through Repo.load"assert fixes["src/repo.py"]["effort"] == "S"assert "fragile_file" not in rulesdiff --git a/tests/unit/persistence/test_health_findings_worth_order.py b/tests/unit/persistence/test_health_findings_worth_order.pynew file mode 100644index 000000000..be05df46d--- /dev/null+++ b/tests/unit/persistence/test_health_findings_worth_order.py@@ -0,0 +1,56 @@+"""The default findings read puts work worth doing first ahead, and a filtered+read still tiers a function by every finding on it."""++from __future__ import annotations++import pytest++from repowise.core.analysis.health.models import HealthFindingData, Severity+from repowise.core.persistence.crud.analysis import (+ get_health_findings,+ health_finding_priorities,+ save_health_findings,+)+from tests.unit.persistence.helpers import insert_repo+++def _finding(marker: str, function: str, impact: float, **details) -> HealthFindingData:+ return HealthFindingData(+ biomarker_type=marker,+ severity=Severity.HIGH,+ file_path="a.py",+ function_name=function,+ line_start=1,+ line_end=200,+ details=details,+ health_impact=impact,+ )+++async def test_worth_first_then_impact_and_filters_keep_the_whole_shape(async_session):+ repo = await insert_repo(async_session)+ await save_health_findings(+ async_session,+ repo.id,+ [+ # Near the bar, but the highest impact.+ _finding("complex_method", "tidy", 3.0, ccn=14, nloc=40),+ # Tangled: its CCN is on the complex_method row, its depth on this one.+ _finding("nested_complexity", "knot", 0.5, max_nesting=5),+ _finding("complex_method", "knot", 0.4, ccn=27, nloc=80),+ ],+ )+ await async_session.commit()++ rows = await get_health_findings(async_session, repo.id)+ assert [(f.function_name, f.biomarker_type) for f in rows] == [+ ("knot", "nested_complexity"),+ ("knot", "complex_method"),+ ("tidy", "complex_method"),+ ]++ # Filtered to the nesting marker alone, the function keeps its CCN.+ nested = await get_health_findings(async_session, repo.id, biomarker_type="nested_complexity")+ reasons = await health_finding_priorities(async_session, repo.id, nested)+ assert [reasons[f.id] for f in nested] == [None]