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
feat(health): rank work by complexity removed times reach, and share the lead with Do next (#3366)
Raghav Chamadiyae61660fe2f44
diff --git a/docs/layers/CODE_HEALTH.md b/docs/layers/CODE_HEALTH.mdindex b6a5d3c62..aef09bb72 100644--- a/docs/layers/CODE_HEALTH.md+++ b/docs/layers/CODE_HEALTH.md@@ -107,9 +107,13 @@ Dormant functions are counted next to the excluded totals, not dropped silently.Only the file itself is read: a flag imported from another module, or flipped fromoutside with `setattr` or a test's monkeypatch, still reads as off.-Items rank by value first (health recovered, or how far the code sits past size and-complexity bars), then by tier. No single kind takes more than 3 of the first 5-places while another kind has work worth doing.+Items rank by value first (how far the code sits past size and complexity bars,+one step more in a widely imported file), then by tier. Within a value, the+complexity a fix removes times how widely the file is imported decides, so a+4,000-line loop outranks a long print routine. A performance fix ranks by what runs+it: a request or message handler, then a scheduled job, then code with no role+evidence. No kind takes more than 3 of the first 5 places while another has work+worth doing.| Tier | Meaning ||---|---|@@ -129,7 +133,10 @@ dashboard, in `get_health` and in `repowise health --format json` (`queue_countsFix first items sit beside a live secret, fresh regressions, fragile files, fileswith knowledge loss, broken doc references, a dead-code batch, missing or stalecoverage, and decisions waiting for review. Rows are grouped as **Now**, **Worth-planning** and **Improve what Repowise can see**. Dismissing or snoozing a row takes effect at once.+planning** and **Improve what Repowise can see**. Within a group, rows rank by value+times confidence over effort, and the top due Fix first item leads its group, so Do+next and Fix first lead with the same work. Dismissing or+snoozing a row takes effect at once.A fragile file asks for tests only when no measured coverage and no test in thecode graph reaches it; otherwise the row asks you to simplify its lead function.diff --git a/packages/core/src/repowise/core/analysis/actions/engine.py b/packages/core/src/repowise/core/analysis/actions/engine.pyindex f2d6b99d2..14af743ae 100644--- a/packages/core/src/repowise/core/analysis/actions/engine.py+++ b/packages/core/src/repowise/core/analysis/actions/engine.py@@ -12,7 +12,7 @@ from typing import Any, NamedTuplefrom .context import RepoContext, build_contextfrom .facts import RepoFacts-from .model import HORIZONS, RULE_RANK, TIER_RANK, Action, RuleOutcome+from .model import HORIZONS, RULE_RANK, TIER_RANK, Action, RuleOutcome, shared_priorityfrom .rules import code, hygiene, signalfrom .summary import summarize@@ -41,6 +41,9 @@ KEEP_PER_HORIZON = 20#: every other rule with something to say has had one.PER_RULE_HEAD = 2+#: The places every surface shows first: the overview's next actions.+NEXT_ACTIONS_HEAD = 3+@dataclass(frozen=True, slots=True)class ActionStateRecord:@@ -70,11 +73,24 @@ def _naive(value: datetime) -> datetime:return value.astimezone(UTC).replace(tzinfo=None) if value.tzinfo else value+def _priority(action: dict[str, Any]) -> float:+ """The action's stored priority; a view stored before actions carried one+ reads :func:`shared_priority` from its value or severity."""+ stored = action.get("priority")+ if stored is not None:+ return stored+ return shared_priority(+ action.get("value"), action["severity"], action["confidence"], action["effort"]+ )++def _order(actions: list[Ranked]) -> list[Ranked]:+ # Priority orders a tier; rule rank and the rule's own weight only break ties.ranked = sorted(actions,key=lambda r: (TIER_RANK[r.action["tier"]],+ -_priority(r.action),RULE_RANK[r.action["rule"]],-r.weight,r.action["id"],@@ -94,6 +110,26 @@ def _order(actions: list[Ranked]) -> list[Ranked]:else:rest.append(r)out.extend(head + rest)+ return _reserve_fix_first(out)+++def _reserve_fix_first(ordered: list[Ranked]) -> list[Ranked]:+ """The Fix first lead first in its tier's block, so Do next and Fix first+ lead with the same work. It never moves across tiers: an ``act_now`` row+ stays above a ``plan`` lead. The rule emits only due items, and its+ priorities follow the queue's order, so the lead has the highest."""+ leads = [+ (_priority(r.action), r.weight, -i)+ for i, r in enumerate(ordered)+ if r.action["rule"] == "fix_first"+ ]+ if not leads:+ return ordered+ at = -max(leads)[2]+ tier = ordered[at].action["tier"]+ first = next(i for i, r in enumerate(ordered) if r.action["tier"] == tier)+ out = list(ordered)+ out.insert(first, out.pop(at))return outdiff --git a/packages/core/src/repowise/core/analysis/actions/model.py b/packages/core/src/repowise/core/analysis/actions/model.pyindex 92c12f1fc..c55812d0b 100644--- a/packages/core/src/repowise/core/analysis/actions/model.py+++ b/packages/core/src/repowise/core/analysis/actions/model.py@@ -10,6 +10,7 @@ import hashlibfrom dataclasses import dataclassfrom typing import Any, Literal, get_args+from repowise.core.analysis.health.queue.order import priority as queue_priorityfrom repowise.core.analysis.next_call import ActionCommand#: Bumped when a rule's output changes meaning or shape; stored views built@@ -82,6 +83,24 @@ TIER_RANK: dict[str, int] = {"act_now": 0, "plan": 1, "improve_signal": 2}#: worse outranks a claim that it is costly, which outranks tidiness.RULE_RANK: dict[str, int] = {rule: i for i, rule in enumerate(ACTION_RULES)}+#: An action's value (0-4, as the Fix first queue values work) when its rule+#: has none of its own: what its severity says.+SEVERITY_VALUE: dict[str, int] = {"critical": 4, "high": 3, "medium": 2, "low": 1}+++def effective_value(value: int | None, severity: str) -> int:+ """An action's value: its own, else its severity's (also for a view+ stored before actions carried one)."""+ return value if value is not None else SEVERITY_VALUE.get(severity, 1)+++def shared_priority(+ value: int | None, severity: str, confidence: str, effort: str+) -> float:+ """The number Do next orders a tier on: the queue's ``value x confidence /+ effort`` (``queue.order.priority``)."""+ return queue_priority(effective_value(value, severity), confidence, effort)+@dataclass(frozen=True, slots=True)class WhyFact:@@ -144,6 +163,11 @@ class Action:done_when: str#: Rule-local ordering weight, comparable only within its rule.weight: float = 0.0+ #: The shared value every rule ranks on; ``None`` reads :data:`SEVERITY_VALUE`.+ value: int | None = None+ #: The number Do next orders the tier on; ``None`` reads :func:`shared_priority`.+ #: Set by a rule whose own queue already orders its actions (Fix first).+ priority: float | None = Nonetarget_symbol: str | None = None#: What makes this action the same action next time, when the target alone#: does not: two performance opportunities can share a symbol, and a@@ -165,6 +189,16 @@ class Action:details_total: int = 0commands: tuple[ActionCommand, ...] = ()+ @property+ def effective_value(self) -> int:+ return effective_value(self.value, self.severity)++ @property+ def effective_priority(self) -> float:+ if self.priority is not None:+ return self.priority+ return shared_priority(self.value, self.severity, self.confidence, self.effort)+@propertydef action_id(self) -> str:identity = self.identity or f"{self.target_path}:{self.target_symbol or ''}"@@ -189,6 +223,8 @@ class Action:"surface": self.surface,"effort": self.effort,"confidence": self.confidence,+ "value": self.effective_value,+ "priority": round(self.effective_priority, 4),"done_when": self.done_when,"command": self.command,"marker": self.marker,diff --git a/packages/core/src/repowise/core/analysis/actions/rules/code.py b/packages/core/src/repowise/core/analysis/actions/rules/code.pyindex 22f9eb8f1..f294fd1d2 100644--- a/packages/core/src/repowise/core/analysis/actions/rules/code.py+++ b/packages/core/src/repowise/core/analysis/actions/rules/code.py@@ -2,13 +2,22 @@from __future__ import annotations+import mathimport posixpathfrom collections import defaultdictfrom datetime import datetimefrom ..context import HISTORY_TOO_SHORT, RepoContextfrom ..facts import FileFacts, RepoFacts-from ..model import Action, ActionCommand, ActionDetail, RuleOutcome, WhyFact, fingerprint+from ..model import (+ Action,+ ActionCommand,+ ActionDetail,+ RuleOutcome,+ WhyFact,+ fingerprint,+ shared_priority,+)from ._text import code, plural#: Files that tell the week's story as well as the quarter's: busy fragile@@ -503,6 +512,7 @@ def _ancestors(path: str) -> list[str]:#: Fix-first tiers that become actions; ``later`` stays on the Code Health page.+#: Both are due, so both are listed this week as well as this quarter._FIX_FIRST_TIER = {"now": "act_now", "next": "plan"}@@ -521,18 +531,25 @@ def fix_first(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:if "fix_first" in facts.unavailable:return RuleOutcome(rule, "unavailable", facts.unavailable["fix_first"])actions = []+ # Do next's number for each item, held to the queue's order: a later item+ # never outranks an earlier one, whatever its effort.+ ceiling = math.inffor item in facts.fix_first:tier = _FIX_FIRST_TIER.get(item.tier)if tier is None:continue+ effort = _effort(item.effort.bucket)+ confidence = "high" if item.confidence.level == "high" else "medium"+ severity = "high" if tier == "act_now" else "medium"+ ceiling = min(ceiling, shared_priority(item.value, severity, confidence, effort))target = item.targetsymbol = target.symbolactions.append(Action(rule=rule,tier=tier,- horizons=("week", "quarter") if tier == "act_now" else ("quarter",),- severity="high" if tier == "act_now" else "medium",+ horizons=("week", "quarter"),+ severity=severity,title=item.title,impact=item.why,why=(@@ -544,10 +561,12 @@ def fix_first(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:target_symbol=symbol,identity=item.id,surface="performance" if item.kind == "perf_fix" else "findings",- effort=_effort(item.effort.bucket),- confidence="high" if item.confidence.level == "high" else "medium",+ effort=effort,+ confidence=confidence,done_when="It leaves Fix first on the next update.",weight=float(len(facts.fix_first) - item.rank),+ value=item.value,+ priority=ceiling,evidence_ids=tuple(x for x in (item.source.opportunity_id, *item.source.finding_ids) if x),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 27379721a..4fb00aa84 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@@ -80,9 +80,12 @@ from repowise.core.analysis.health.queue.value import (perf_confidence,perf_ready,perf_value,+ perf_worth,+ removed,shape_value,size_value,tier,+ worth,)from repowise.core.analysis.health.rows import detail_map, field, json_fieldfrom repowise.core.analysis.health.scoring import biomarker_dimension@@ -90,6 +93,7 @@ from repowise.core.analysis.health.suggestions import suggestion_forfrom repowise.core.analysis.health.worth import (SIZE_MARKERS,WORTH_MAGNITUDE,+ execution_role,low_priority,magnitude,measure,@@ -127,7 +131,8 @@ Rows = Iterable[Any]#: 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 = WORTH_MAGNITUDE-#: A file in the top fifth of production files by churn or dependents is hot.+#: A file in the top fifth of production files by dependents is central (one+#: value step); by churn it changes often (orders within a band only).HOT_QUANTILE = 0.8MAX_FACTS = 5MAX_TESTS = 5@@ -150,7 +155,7 @@ class _Unit:kind: strtier: strvalue: int- score: float+ worth: floatconfidence: streffort: strimproves: str@@ -269,8 +274,11 @@ class _Files:def nloc(self, path: str) -> int | None:return field(self.by_path.get(path), "nloc")- def hot(self, path: str) -> bool:- return self.commits(path) >= self.churn_cut or (self.dependents(path) or 0) >= self.deps_cut+ def central(self, path: str) -> bool:+ return (self.dependents(path) or 0) >= self.deps_cut++ def churning(self, path: str) -> bool:+ return self.commits(path) >= self.churn_cutdef shape(self, path: str, symbol: str | None) -> dict[str, int]:"""The measured size of ``symbol`` in ``path``, from its findings."""@@ -368,7 +376,7 @@ class _Files:return f"{head}{text.exposure(deps, self.commits(path), self.coverage(path))}."def context(self, path: str) -> tuple[FixContext, ...]:- """History is context: shown beside the item, never ranked on."""+ """History is context: shown beside the item, never lifting its band."""out: list[FixContext] = []commits = self.commits(path)if commits:@@ -401,7 +409,7 @@ def _finish(source_id: str,value: int,ready: bool,- score: float,+ worth: float,confidence: str,effort: str,improves: str,@@ -423,17 +431,19 @@ def _finish(tier=unit_tier,kind=kind,improves=improves,+ value=value,why_ranked=(# 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("worth in band", f"{worth:.0f}"),FixRankFact("tier", why_tier),),**fields(),)return _Unit(- item_id, kind, unit_tier, value, score, confidence, effort, improves, write, may_lead+ item_id, kind, unit_tier, value, worth, confidence, effort, improves, write, may_lead)@@ -607,10 +617,13 @@ def _refactor_unit()mechanical = mechanical_n == len(steps)confidence = field(row, "confidence") or "medium"- hot = files.hot(path)+ central, churning = files.central(path), files.churning(path)dimension = biomarker_dimension(marker) if marker else "maintainability"shape = files.shape(path, lead.get("target_symbol"))- size = size_value(shape, hot)+ size = size_value(shape, central)+ ccn_removed = sum(_extraction_worth(plans.get(s.get("plan_id")))[0] for s in steps)+ deps = details.get("dependents")+ deps = files.dependents(path) if deps is None else depscloned = lead_type == "extract_method" and files.cloned(path, shape)low = low_priority(marker, shape, function_size=lead_type == "extract_method")@@ -648,9 +661,7 @@ def _refactor_unit()if len(steps) > 1:title += f" (+{text.plural(len(steps) - 1, 'more step')})"- dependents = details.get("dependents")- if dependents is None:- dependents = files.dependents(path)+ dependents = depsfix_steps = tuple(_refactor_step(i + 1, s, plans.get(s.get("plan_id"))) for i, s in enumerate(steps))@@ -721,17 +732,18 @@ def _refactor_unit(return _finish(kind="refactor",source_id=field(row, "opportunity_id"),- value=shape_value(gain, shape, cloned, hot=hot),- cold_value=shape_value(gain, shape, cloned, hot=False),+ value=shape_value(gain, shape, cloned, central=central),+ cold_value=shape_value(gain, shape, cloned, central=False),ready=mechanical or confidence == "high",- score=_num(field(row, "rank_score")),+ worth=worth(removed(ccn_removed, gain), deps, churning),confidence=confidence if confidence in LEVEL_RANK else "medium",effort=effort_bucket,improves=dimension if dimension in FIX_IMPROVES else "maintainability",rank_inputs=lambda: [FixRankFact("health gain", f"{gain:.2f}"),+ FixRankFact("complexity removed", str(ccn_removed)),FixRankFact("problem size", str(size if low is None else worth_size(shape))),- FixRankFact("hot file", "yes" if hot else "no"),+ *_reach_facts(deps, central, churning),FixRankFact("duplicate inside", "yes" if cloned else "no"),],fields=fields,@@ -739,6 +751,15 @@ def _refactor_unit()+def _reach_facts(deps: int | None, central: bool, churning: bool) -> list[FixRankFact]:+ """What reach and history add: importers lift the band when central,+ churn only orders inside it."""+ return [+ FixRankFact("files that import it", f"{deps or 0}{' (top fifth)' if central else ''}"),+ FixRankFact("changes often", "yes" if churning else "no"),+ ]++def _audited_steps(steps: list[Mapping[str, Any]]) -> tuple[list[Mapping[str, Any]], int]:"""The steps an item may carry, and how many it held back: steps of akind not yet audited stay in the full plan, never in the item."""@@ -928,20 +949,22 @@ def _perf_unit(}confidence = perf_confidence(facets)+ call_sites = int(field(lead, "affected_call_sites_total") or 0)return _finish(kind="perf_fix",may_lead=details.get("may_lead") is not False,source_id=f"{path}::{symbol or path}",value=perf_value(lead, facets),ready=perf_ready(lead, plan),- score=_num(field(lead, "rank_score")),+ worth=perf_worth(call_sites, files.churning(path)),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")),+ FixRankFact("run by", execution_role(lead)),+ FixRankFact("call sites", str(call_sites)),FixRankFact("loop size", text.loop_size(magnitude)),FixRankFact("boundary", text.BOUNDARY_NOUN.get(field(lead, "boundary_kind") or "", "none")@@ -959,11 +982,14 @@ class _FindingRank:"""What a finding's value and tier read: one rule for the item and the stored judgement."""shape: dict[str, int]- hot: bool+ central: bool+ churning: boolcloned: boollow: str | Nonevalue: intcold_value: int+ ccn_removed: int+ worth: float@propertydef tier(self) -> str:@@ -974,16 +1000,21 @@ def _finding_rank(finding: Any, files: _Files) -> _FindingRank:path = field(finding, "file_path")marker = field(finding, "biomarker_type") or ""impact = _num(field(finding, "health_impact"))- hot = files.hot(path)+ central, churning = files.central(path), files.churning(path)shape = files.shape(path, field(finding, "function_name"))cloned = marker in SIZE_MARKERS and files.cloned(path, shape)+ # Breaking up the whole function takes out its whole CCN.+ ccn = shape.get("ccn", 0) if marker in SIZE_MARKERS else 0return _FindingRank(shape,- hot,+ central,+ churning,cloned,low_priority(marker, shape, error_kind=detail_map(finding).get("kind")),- shape_value(impact, shape, cloned, hot=hot),- shape_value(impact, shape, cloned, hot=False),+ shape_value(impact, shape, cloned, central=central),+ shape_value(impact, shape, cloned, central=False),+ ccn,+ worth(removed(ccn, impact), files.dependents(path), churning),)@@ -995,8 +1026,8 @@ def _finding_unit(lead: Any, files: _Files, first: FixStep, validate: Validate |public_id = field(lead, "public_id")dimension = biomarker_dimension(marker)rank = _finding_rank(lead, files)- shape, hot, cloned, low = rank.shape, rank.hot, rank.cloned, rank.low- size = size_value(shape, hot)+ shape, cloned, low = rank.shape, rank.cloned, rank.low+ size = size_value(shape, rank.central)def fields() -> dict[str, Any]:where = function or text.basename(path)@@ -1055,14 +1086,15 @@ def _finding_unit(lead: Any, files: _Files, first: FixStep, validate: Validate |value=rank.value,cold_value=rank.cold_value,ready=False,- score=impact,+ worth=rank.worth,confidence="medium",effort="M",improves=dimension if dimension in FIX_IMPROVES else "defect",rank_inputs=lambda: [FixRankFact("health gain", f"{impact:.2f}"),+ FixRankFact("complexity removed", str(rank.ccn_removed)),FixRankFact("problem size", str(size if low is None else worth_size(shape))),- FixRankFact("hot file", "yes" if hot else "no"),+ *_reach_facts(files.dependents(path), rank.central, rank.churning),FixRankFact("duplicate inside", "yes" if cloned else "no"),],fields=fields,@@ -1238,7 +1270,7 @@ def build_fix_first(keeps every eligible item. ``basis`` is the analysis stamp when the callerread it apart; otherwise it comes from the metrics' ``updated_at``.``item_id`` keeps just that item, at its rank, for a lookup by id.- ``hot_cuts`` are the (churn, dependents) thresholds for a hot file when the+ ``hot_cuts`` are the (churn, dependents) thresholds for a churning and a central file when thecaller measured them over more files than it passed in ``metrics``; see:func:`hot_cut` for the rule. ``symbol_lines`` maps a symbol id(``path::name``) to its first line, for a performance plan step thatdiff --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 4e8100bed..1cb8a5f72 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@@ -191,6 +191,9 @@ class FixItem:source: FixSourcenext_call: ActionCommandwhy_ranked: tuple[FixRankFact, ...] = ()+ #: The value band (``queue.value``) Do next ranks the item on; ``None`` on a+ #: snapshot stored before items carried it.+ value: int | None = Nonedef as_dict(self) -> dict[str, Any]:return asdict(self)diff --git a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py b/packages/core/src/repowise/core/analysis/health/queue/eligibility.pyindex 5ebe15e30..0088eecaf 100644--- a/packages/core/src/repowise/core/analysis/health/queue/eligibility.py+++ b/packages/core/src/repowise/core/analysis/health/queue/eligibility.py@@ -29,6 +29,7 @@ from ..worth import (cost_proof,dispatch_shaped,dormant,+ execution_role,lead_reason,perf_facets,)@@ -426,11 +427,10 @@ def _role_reason(item: Any) -> Reason | None:A loop only startup, a CLI, tooling or tests run is paid once per process.A scheduled job's loop matters only once it is shown to grow with the data."""- facets = perf_facets(item)- role = field(item, "execution_role") or facets.get("execution_role") or "unknown"+ role = execution_role(item)if role in COLD_ROLES:return "cold_role"- if role == "scheduled_job" and facets.get("loop_magnitude") != "grows_with_data":+ if role == "scheduled_job" and perf_facets(item).get("loop_magnitude") != "grows_with_data":return "background_unproven"return Nonediff --git a/packages/core/src/repowise/core/analysis/health/queue/order.py b/packages/core/src/repowise/core/analysis/health/queue/order.pyindex d99355245..8bed3b8c3 100644--- a/packages/core/src/repowise/core/analysis/health/queue/order.py+++ b/packages/core/src/repowise/core/analysis/health/queue/order.py@@ -1,6 +1,6 @@-"""The one cross-kind order of eligible work: tier, value, confidence, effort.+"""The one cross-kind order of eligible work: value band, tier, then priority.-Reads any unit with ``id``, ``kind``, ``tier``, ``value``, ``score``,+Reads any unit with ``id``, ``kind``, ``tier``, ``value``, ``worth``,``confidence``, ``effort`` and ``may_lead``. Imports nothing from thesurfaces, so each of them can read the rank tables from here."""@@ -10,7 +10,7 @@ from __future__ import annotationsfrom collections import Counterfrom typing import Literal, Protocol, TypeVar, get_args-from ..effort import EFFORT_ORDER+from ..effort import EFFORT_WEIGHTTier = Literal["now", "next", "later"]TIERS: tuple[str, ...] = get_args(Tier)@@ -19,7 +19,6 @@ DUE_TIERS = frozenset({"now", "next"})TIER_RANK = {t: i for i, t in enumerate(TIERS)}LEVEL_RANK = {"high": 2, "medium": 1, "low": 0}-EFFORT_RANK = {e: i for i, e in enumerate(EFFORT_ORDER)}#: In the first HEAD places no kind takes more than HEAD_PER_KIND, unless the#: other kinds have nothing above the later tier.@@ -37,7 +36,7 @@ class Ranked(Protocol):@propertydef value(self) -> int: ...@property- def score(self) -> float: ...+ def worth(self) -> float: ...@propertydef confidence(self) -> str: ...@property@@ -49,14 +48,19 @@ class Ranked(Protocol):R = TypeVar("R", bound=Ranked)-def _key(u: Ranked) -> tuple[bool, int, int, int, int, float, str]:+def priority(worth: float, confidence: str, effort: str) -> float:+ """``worth x confidence / effort``: the order inside a value band and tier,+ shared with Do next. High confidence counts in full, low a third."""+ trust = (1 + LEVEL_RANK.get(confidence, 0)) / 3+ return worth * trust / EFFORT_WEIGHT.get(effort, EFFORT_WEIGHT["M"])+++def _key(u: Ranked) -> tuple[bool, int, int, float, str]:return (u.tier == "later",-u.value,TIER_RANK[u.tier],- -LEVEL_RANK.get(u.confidence, 0),- EFFORT_RANK.get(u.effort, 1),- -u.score,+ -priority(u.worth, u.confidence, u.effort),u.id,)@@ -92,7 +96,6 @@ def order(units: list[R]) -> list[R]:__all__ = ["DUE_TIERS",- "EFFORT_RANK","HEAD","HEAD_PER_KIND","LEVEL_RANK",@@ -101,4 +104,5 @@ __all__ = ["Ranked","Tier","order",+ "priority",]diff --git a/packages/core/src/repowise/core/analysis/health/queue/value.py b/packages/core/src/repowise/core/analysis/health/queue/value.pyindex eadb35820..d6f991cd9 100644--- a/packages/core/src/repowise/core/analysis/health/queue/value.py+++ b/packages/core/src/repowise/core/analysis/health/queue/value.py@@ -1,16 +1,21 @@-"""How much a unit of work is worth, 0 to :data:`VALUE_MAX`, and the tier it earns.+"""How much a unit of work is worth, and the tier it earns.-Code shape sets the value; a hot file adds one step, and history never lifts a-unit into a higher tier (:func:`tier` reads the value without that step).+The value band, 0 to :data:`VALUE_MAX`, is code shape plus reach: a file in the+top fifth by importers adds one step, which never lifts a unit into a higher+tier (:func:`tier` reads the value without it). Inside a band, :func:`worth`+orders by complexity removed times reach; history (a file that changes often)+only re-orders units there."""from __future__ import annotationsfrom collections.abc import Mapping+from math import log2from typing import Any+from ...execution_roles import COLD_ROLES, LEADING_ROLESfrom ..rows import field-from ..worth import LOW_PRIORITY_LABEL, lead_reason, magnitude+from ..worth import LOW_PRIORITY_LABEL, SIZE_CCN, execution_role, lead_reason, magnitudefrom .order import LEVEL_RANK#: Credited health gain cut points for value 1, 2 and 3.@@ -22,49 +27,89 @@ GAIN_CUTS = (0.5, 1.5, 3.0)SIZE_SEVERE = 2#: The highest value any unit reaches.VALUE_MAX = 4+#: One health point recoverable counts as this much complexity removed (the+#: first CCN bar), so a plan with no measured CCN removal still has a worth.+GAIN_CCN = SIZE_CCN[0]+#: A performance cause counts as a function at the worth bar (CCN 40), times+#: the reach of the call sites one fix settles.+PERF_CCN = SIZE_CCN[1]+#: On a file in the top fifth by churn. History re-orders inside a band only.+CHURN_WEIGHT = 1.25-def gain_value(gain: float, hot: bool) -> int:- return min(3, sum(gain >= cut for cut in GAIN_CUTS) + int(hot))+def gain_value(gain: float, central: bool) -> int:+ return min(3, sum(gain >= cut for cut in GAIN_CUTS) + int(central))-def size_value(shape: Mapping[str, int], hot: bool) -> int:- """How big the problem is, 0 to 4; a hot file counts one more."""+def size_value(shape: Mapping[str, int], central: bool) -> int:+ """How big the problem is, 0 to 4; a widely imported file counts one more."""base = max(magnitude(shape), SIZE_SEVERE if shape.get("severe") else 0)- return min(VALUE_MAX, base + int(hot and base > 0))+ return min(VALUE_MAX, base + int(central and base > 0))-def shape_value(gain: float, shape: Mapping[str, int], cloned: bool, *, hot: bool) -> int:+def shape_value(gain: float, shape: Mapping[str, int], cloned: bool, *, central: bool) -> int:"""A refactoring's or a finding's value: the larger of the gain and theproblem 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))+ value = max(gain_value(gain, central), size_value(shape, central))return min(VALUE_MAX, value + 1) if cloned else value+def removed(ccn: int, gain: float) -> float:+ """Complexity a unit removes: the CCN it takes out, or its health gain+ counted at :data:`GAIN_CCN` per point, whichever is larger."""+ return max(float(ccn), gain * GAIN_CCN)+++def reach(dependents: int | None) -> float:+ """How far a change reaches: 1 plus log2 of one more than its importers."""+ return 1 + log2(1 + max(dependents or 0, 0))+++def worth(removed_ccn: float, dependents: int | None, churning: bool) -> float:+ """The order inside a value band: complexity removed times :func:`reach`,+ :data:`CHURN_WEIGHT` more on a file that changes often. Unbounded on+ purpose: the band saturates, so a CCN 963 loop and a CCN 150 wizard share+ it, and only this tells them apart."""+ return removed_ccn * reach(dependents) * (CHURN_WEIGHT if churning else 1.0)+++#: The band a production database or network call in a loop that grows with+#: the data earns, by the role running it. Once per request or message is the+#: costliest work Fix first holds, so it shares the top band with the largest+#: functions; a scheduled job's is one step below. With no role evidence+#: (``unknown``) it is valued as any proven cause.+_ROLE_VALUE = {"scheduled_job": 3, **dict.fromkeys(LEADING_ROLES, VALUE_MAX)}++def perf_value(row: Any, facets: Mapping[str, Any]) -> int:- """A performance cause's value. A production, entry-reachable database or- network call in a loop that grows with the data is the costliest kind of- work Fix first holds, so it shares the top band with the largest- functions; capped below it, it never reached a top ten that size fills."""+ """A performance cause's value, read off the role running its loop+ (``execution_roles``): request or message, then a scheduled job, then no+ evidence; a cold role (startup, CLI, UI, tooling, tests) never leads."""production = field(row, "execution_context") == "production"- reachable = facets.get("exposure") == "entry_reachable"- reason = lead_reason(field(row, "biomarker_type"), facets)+ role = execution_role(row)if (production- and reachable+ and role in _ROLE_VALUEand facets.get("loop_magnitude") == "grows_with_data"and field(row, "boundary_kind") in ("db", "network")):- return VALUE_MAX- value = 2 if production and reason is None else 1- # No traffic data: a loop of unknown size that no entry point reaches is- # most often an admin or maintenance path, where an N+1 is cheap.- if reason == "unmeasured_cost" and not reachable:+ return _ROLE_VALUE[role]+ reason = lead_reason(field(row, "biomarker_type"), facets)+ value = 2 if production and reason is None and role not in COLD_ROLES else 1+ # No traffic data: a loop of unknown size that no request, message or job+ # runs is most often an admin or maintenance path, where an N+1 is cheap.+ if reason == "unmeasured_cost" and role not in _ROLE_VALUE:value -= 1return value+def perf_worth(call_sites: int, churning: bool) -> float:+ """A performance cause's :func:`worth`: :data:`PERF_CCN`, reaching as far+ as the call sites one fix settles."""+ return worth(PERF_CCN, call_sites - 1, churning)++def perf_confidence(facets: Mapping[str, Any]) -> str:"""How sure the strategy is; ``low`` when it was not recorded."""level = facets.get("actionability_confidence") or "low"@@ -95,14 +140,21 @@ def tier(value: int, confidence: str, ready: bool, low: str | None) -> tuple[str__all__ = [+ "CHURN_WEIGHT",+ "GAIN_CCN","GAIN_CUTS",+ "PERF_CCN","SIZE_SEVERE","VALUE_MAX","gain_value","perf_confidence","perf_ready","perf_value",+ "perf_worth",+ "reach",+ "removed","shape_value","size_value","tier",+ "worth",]diff --git a/packages/core/src/repowise/core/analysis/health/worth.py b/packages/core/src/repowise/core/analysis/health/worth.pyindex a4d1ed919..a64a18027 100644--- a/packages/core/src/repowise/core/analysis/health/worth.py+++ b/packages/core/src/repowise/core/analysis/health/worth.py@@ -291,6 +291,13 @@ def perf_facets(row: Any) -> Mapping[str, Any]:return field(row, "facets") or detail_map(row).get("facets") or {}+def execution_role(row: Any) -> str:+ """The role running a cause's loop: the stored column, else its facet;+ ``unknown`` on an index stored before roles were. Which role a function+ gets is decided in :mod:`repowise.core.analysis.execution_roles`."""+ return field(row, "execution_role") or perf_facets(row).get("execution_role") or "unknown"++def lead_reason(marker: str | None, facets: Mapping[str, Any]) -> LowPriority | None:"""Why a performance cause may not lead, or ``None`` when it may.@@ -335,6 +342,7 @@ __all__ = ["cost_proof","dispatch_shaped","dormant",+ "execution_role","finding_priorities","lead_reason","low_priority",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 a465cfb75..a5dff420f 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@@ -298,6 +298,7 @@ async def _performance(session: AsyncSession, repo_id: str) -> list[Any]:p.rank_position,p.rank_score,p.execution_context,+ p.execution_role,p.boundary_kind,p.biomarker_type,p.actionability_state,diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex 3144ce79e..71ff01531 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1755,7 +1755,8 @@ class QueueVerdict:``queue_eligible`` is NULL until the first judgement (a store writtenbefore the columns), ``False`` with the one ``queue_reason`` that kept theunit out, or ``True``; ``queue_value`` (0-4) and ``queue_tier`` are set on- eligible units only.+ eligible units only. ``queue_value`` is the reach-aware band: a central+ file (top fifth by importers) adds a step, churn does not."""queue_eligible: Mapped[bool | None] = mapped_column(Boolean, nullable=True)diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.pyindex a37549e67..9b2a4ad96 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py@@ -5,13 +5,14 @@ from __future__ import annotationsimport loggingfrom typing import Any+from repowise.core.analysis.actions.engine import NEXT_ACTIONS_HEADfrom repowise.core.persistence.crud.analysis.actions import load_actions_viewlogger = logging.getLogger(__name__)#: Rows per horizon. The UI previews five; an agent orienting needs the head,#: and ``total`` says how much sits behind it.-_PER_HORIZON = 3+_PER_HORIZON = NEXT_ACTIONS_HEAD_FIELDS = ("id", "tier", "title", "impact", "done_when")diff --git a/packages/server/src/repowise/server/schemas/actions.py b/packages/server/src/repowise/server/schemas/actions.pyindex d337eb193..1cce61e3e 100644--- a/packages/server/src/repowise/server/schemas/actions.py+++ b/packages/server/src/repowise/server/schemas/actions.py@@ -45,6 +45,12 @@ class NextAction(BaseModel):surface: streffort: Literal["S", "M", "L"]confidence: Literal["high", "medium"]+ value: int = Field(+ default=0, description="0-4: the Fix first value band, or what the severity says."+ )+ priority: float = Field(+ default=0.0, description="Value x confidence / effort: the order inside a tier."+ )done_when: strcommand: str | None = Nonemarker: str | None = Nonediff --git a/packages/types/src/actions.ts b/packages/types/src/actions.tsindex 099cdb215..2ce363d85 100644--- a/packages/types/src/actions.ts+++ b/packages/types/src/actions.ts@@ -99,6 +99,10 @@ export interface NextAction {surface: ActionSurface;effort: "S" | "M" | "L";confidence: "high" | "medium";+ /** 0 to 4: the Fix first value band, or what the severity says. */+ value: number;+ /** Value x confidence / effort: the order inside a tier. */+ priority: number;done_when: string;command: string | null;/** The biomarker behind the action, for the glossary label. */diff --git a/packages/types/src/fix-first.ts b/packages/types/src/fix-first.tsindex 2b177a402..76d172fb7 100644--- a/packages/types/src/fix-first.ts+++ b/packages/types/src/fix-first.ts@@ -101,6 +101,8 @@ export interface FixItem {next_call: ActionCommand;/** The value inputs and the tier reason, so the order is explainable. */why_ranked: { factor: string; value: string }[];+ /** The value band, 0 to 4, Do next ranks the item on; null on an older snapshot. */+ value?: number | null;}/** The projection a list renders; the full item is one lookup away. */diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex 58ffcd5e7..8b6696ebd 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -1623,6 +1623,7 @@ export interface FixItem {source: FixSource;next_call: ActionCommand;why_ranked?: FixRankFact[];+ value?: number | null;}export interface FixRankFact {@@ -2268,6 +2269,10 @@ export interface NextAction {surface: string;effort: "S" | "M" | "L";confidence: "high" | "medium";+ /** 0-4: the Fix first value band, or what the severity says. */+ value?: number;+ /** Value x confidence / effort: the order inside a tier. */+ priority?: number;done_when: string;command?: string | null;marker?: string | null;diff --git a/packages/ui/__tests__/health/fixtures/fix-first.ts b/packages/ui/__tests__/health/fixtures/fix-first.tsindex 81794cb79..bd23b97fe 100644--- a/packages/ui/__tests__/health/fixtures/fix-first.ts+++ b/packages/ui/__tests__/health/fixtures/fix-first.ts@@ -11,6 +11,7 @@ export const FIX_FIRST_QUEUE: FixFirstQueue = {{"id": "fix1_2b0e5c0acbb469f46aa9","rank": 3,+ "value": 4,"tier": "now","kind": "refactor","improves": "defect",@@ -163,6 +164,7 @@ export const FIX_FIRST_QUEUE: FixFirstQueue = {{"id": "fix1_8ac4c08f700f837e9087","rank": 0,+ "value": 4,"tier": "next","kind": "finding","improves": "defect",@@ -296,6 +298,7 @@ export const FIX_FIRST_QUEUE: FixFirstQueue = {{"id": "fix1_26c2da3b4c98f8fdef56","rank": 14,+ "value": 4,"tier": "next","kind": "perf_fix","improves": "performance",@@ -450,6 +453,7 @@ export const FIX_FIRST_QUEUE: FixFirstQueue = {"lead": {"id": "fix1_2b0e5c0acbb469f46aa9","rank": 3,+ "value": 4,"tier": "now","kind": "refactor","improves": "defect",diff --git a/packages/ui/__tests__/overview/next-actions.test.tsx b/packages/ui/__tests__/overview/next-actions.test.tsxindex 939ce68a2..ce68f9174 100644--- a/packages/ui/__tests__/overview/next-actions.test.tsx+++ b/packages/ui/__tests__/overview/next-actions.test.tsx@@ -22,6 +22,8 @@ function action(overrides: Partial<NextAction> = {}): NextAction {surface: "file",effort: "M",confidence: "high",+ value: 3,+ priority: 1.5,done_when: "Line coverage on this file reaches 80%.",command: null,marker: null,diff --git a/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsxindex 173bb8c06..23bb946f3 100644--- a/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx+++ b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx@@ -18,6 +18,8 @@ function action(id: string, title: string, tier: NextAction["tier"] = "plan"): Nsurface: "file",effort: "M",confidence: "high",+ value: 3,+ priority: 1.5,done_when: "Coverage reaches 80%.",command: null,marker: null,diff --git a/tests/unit/analysis/test_actions_rules.py b/tests/unit/analysis/test_actions_rules.pyindex 7e65d8b77..2fab87eb4 100644--- a/tests/unit/analysis/test_actions_rules.py+++ b/tests/unit/analysis/test_actions_rules.py@@ -10,7 +10,7 @@ from datetime import datetime, timedeltafrom repowise.core.analysis.actions import ActionStateRecord, RepoFacts, compose_actionsfrom repowise.core.analysis.actions.context import build_context-from repowise.core.analysis.actions.engine import KEEP_PER_HORIZON+from repowise.core.analysis.actions.engine import KEEP_PER_HORIZON, rank_actionsfrom repowise.core.analysis.actions.facts import (CoverageState,DeadFacts,@@ -21,7 +21,7 @@ from repowise.core.analysis.actions.facts import (RecentFinding,SecretFacts,)-from repowise.core.analysis.actions.model import TIER_RANK, Action+from repowise.core.analysis.actions.model import SEVERITY_VALUE, TIER_RANK, Actionfrom repowise.core.analysis.actions.rules import code, hygiene, signalANCHOR = datetime(2026, 9, 28, 12, 0)@@ -277,7 +277,9 @@ def test_fix_first_emits_now_and_next_and_leaves_later() -> None:("plan", items[0].title),("act_now", items[1].title),]- assert actions[1].horizons == ("week", "quarter") and actions[0].horizons == ("quarter",)+ # Both are due, so both are this week's as well as this quarter's.+ assert actions[1].horizons == actions[0].horizons == ("week", "quarter")+ assert [a.value for a in actions] == [i.value for i in items[:2]]assert actions[0].surface == "performance"assert actions[1].commands[0].mcp == f'get_health(fix_id="{items[1].id}")'assert len({a.action_id for a in actions}) == 2@@ -509,6 +511,86 @@ def test_engine_keeps_the_full_total_past_the_cap() -> None:assert quarter["total"] == KEEP_PER_HORIZON + 5+def _ruled(*actions: Action) -> dict:+ return {+ "anchor": None, "week_start": None, "context": {}, "rules": [],+ "actions": [(a.weight, a.as_dict()) for a in actions],+ }+++def _act(rule: str, tier: str, path: str, **kw) -> Action:+ base = dict(+ rule=rule, tier=tier, horizons=("week", "quarter"), severity="high", title=path,+ impact="", why=(), target_kind="file", target_path=path, surface="file",+ effort="M", confidence="medium", done_when="",+ )+ return Action(**{**base, **kw})+++def test_engine_ranks_a_tier_by_value_confidence_and_effort() -> None:+ # Rule order alone put the folder first; per unit of effort the Fix first+ # item (value 4, M) and a one-line doc fix (low, S, high) are worth more.+ ruled = _ruled(+ _act("fix_concentration", "plan", "src/", effort="L"),+ _act("fix_first", "plan", "src/big.py", value=4),+ _act("broken_doc_refs", "plan", "docs/a.md", severity="low", effort="S",+ confidence="high"),+ )+ quarter = rank_actions(ruled, now=NOW)["horizons"]["quarter"]["actions"]+ assert [a["rule"] for a in quarter] == ["fix_first", "broken_doc_refs", "fix_concentration"]+ assert [a["value"] for a in quarter] == [4, 1, 3]+++def test_the_fix_first_lead_leads_its_tier_and_never_crosses_one() -> None:+ secrets = [_act("live_secret", "act_now", f"src/s{i}.py", effort="S") for i in range(3)]+ fragile = _act("fragile_file", "plan", "src/hot.py", confidence="high") # priority 1.5+ lead = _act("fix_first", "plan", "src/big.py", value=4, weight=3.0, priority=1.0)+ second = _act("fix_first", "plan", "src/other.py", value=4, weight=2.0, priority=1.0)+ view = rank_actions(_ruled(*secrets, fragile, second, lead), now=NOW)+ for horizon in ("week", "quarter"):+ actions = view["horizons"][horizon]["actions"]+ # Every act_now row stays above it; the lead opens the plan block.+ assert [a["tier"] for a in actions[:3]] == ["act_now"] * 3+ assert [a["target"]["path"] for a in actions[3:]] == [+ "src/big.py", "src/hot.py", "src/other.py",+ ]+++def test_fix_first_actions_keep_the_queue_order() -> None:+ items = _fix_items()+ actions = _run(code.fix_first, _facts(fix_first=items)).actions+ priorities = [a.effective_priority for a in actions]+ # A later item never outranks an earlier one, whatever its effort.+ assert priorities == sorted(priorities, reverse=True)+ assert [a["priority"] for a in (x.as_dict() for x in actions)] == [+ round(p, 4) for p in priorities+ ]+++def test_an_older_fix_first_snapshot_ranks_on_severity() -> None:+ from repowise.core.analysis.health.fix_first import FixFirstQueue+ from repowise.core.persistence.read_snapshots import decode_or_none++ stored = FixFirstQueue(items=_fix_items()).as_dict()+ for item in stored["items"]:+ del item["value"]+ old = decode_or_none(FixFirstQueue, stored)+ assert old is not None and all(i.value is None for i in old.items)+ actions = _run(code.fix_first, _facts(fix_first=old.items)).actions+ assert [a.effective_value for a in actions] == [+ SEVERITY_VALUE[a.severity] for a in actions+ ]+++def test_a_stored_action_without_a_value_ranks_on_its_severity() -> None:+ old = _act("stale_decision", "plan", "docs/d.md", severity="critical").as_dict()+ del old["value"], old["priority"]+ new = _act("fix_concentration", "plan", "src/").as_dict()+ ruled = {**_ruled(), "actions": [(0.0, new), (0.0, old)]}+ quarter = rank_actions(ruled, now=NOW)["horizons"]["quarter"]["actions"]+ assert [a["rule"] for a in quarter] == ["stale_decision", "fix_concentration"]++def _secret_action(view) -> dict:return next(a for a in view["horizons"]["quarter"]["actions"] if a["rule"] == "live_secret")diff --git a/tests/unit/health/fix_first_rows.py b/tests/unit/health/fix_first_rows.pyindex c7dcf7f77..9612510fb 100644--- a/tests/unit/health/fix_first_rows.py+++ b/tests/unit/health/fix_first_rows.py@@ -100,7 +100,8 @@ PLANS = [def _perf(opp: str, sink: str, **over) -> dict:row = {"opportunity_id": opp, "rank_position": 0, "rank_score": 20,- "execution_context": "production", "boundary_kind": "db", "biomarker_type": "io_in_loop",+ "execution_context": "production", "execution_role": "request", "boundary_kind": "db",+ "biomarker_type": "io_in_loop","actionability_state": "advisory", "plan_state": "available","fix_strategy": "batch_or_prefetch_io", "fix_safety": "advisory","file_path": "src/repo.py", "intervention_symbol": "src/repo.py::load_all",diff --git a/tests/unit/health/test_fix_first_build.py b/tests/unit/health/test_fix_first_build.pyindex 8c758d093..a72b99d06 100644--- a/tests/unit/health/test_fix_first_build.py+++ b/tests/unit/health/test_fix_first_build.py@@ -152,13 +152,10 @@ 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)- # 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": "grows_with_data", "exposure": "not_entry_reachable"},- }+ # A loop that grows but no request, message or job is known to run:+ # worth doing, ranked below the refactors' value.+ perf = _perf("perf2_a", "s", execution_role="unknown")+ perf["details"] = {**perf["details"], "facets": {"loop_magnitude": "grows_with_data"}}queue = _build(refactoring=refactors, performance=[perf], findings=[])# The fourth place goes to the perf fix; the fifth back to a refactor,# since no other kind has anything left at value 2 or above.diff --git a/tests/unit/health/test_fix_first_precision.py b/tests/unit/health/test_fix_first_precision.pyindex 1cc3c22de..99ef05538 100644--- a/tests/unit/health/test_fix_first_precision.py+++ b/tests/unit/health/test_fix_first_precision.py@@ -304,13 +304,13 @@ def test_other_causes_keep_an_unknown_loop() -> None:assert len(_perf_queue(row).items) == 1-# --- F8: unknown loops no entry point reaches -----------------------------------+# --- F8: unknown loops no request, message or job runs -------------------------------def _value(**facets) -> str:+def _value(role: str = "unknown", **facets) -> str:from tests.unit.health.fix_first_rows import _perf- row = _perf("perf3_v", "src/db.py::fetch")+ row = _perf("perf3_v", "src/db.py::fetch", execution_role=role)row["details"] = {**row["details"], "facets": facets}item = _perf_queue(row).leadreturn next(f.value for f in item.why_ranked if f.factor in ("value", "value within later"))@@ -333,15 +333,16 @@ def test_only_a_loop_known_to_grow_leads() -> None:assert lead(loop_magnitude="grows_with_data").tier != "later"-def test_an_unknown_loop_no_entry_reaches_drops_a_step() -> None:- assert _value(loop_magnitude="unknown", exposure="not_entry_reachable") == "0"+def test_an_unknown_loop_no_hot_role_runs_drops_a_step() -> None:assert _value(loop_magnitude="unknown") == "0"+ # A name-derived entry point no longer counts: only the role does.+ assert _value(loop_magnitude="unknown", exposure="entry_reachable") == "0"def test_reach_keeps_an_unknown_loop_a_step_below_a_known_one() -> None:# An unproven cost never earns the value a loop known to grow does.- assert _value(loop_magnitude="unknown", exposure="entry_reachable") == "1"- assert _value(loop_magnitude="grows_with_data", exposure="not_entry_reachable") == "2"+ assert _value("request", loop_magnitude="unknown") == "1"+ assert _value(loop_magnitude="grows_with_data") == "2"# --- lift: a duplicate inside the function ---------------------------------------@@ -484,7 +485,13 @@ def test_a_module_scope_cause_reads_module_scope_of_its_file() -> None:def test_a_production_reachable_growing_db_loop_is_in_the_top_band() -> None:from repowise.core.analysis.health.queue.value import VALUE_MAX- assert _value(loop_magnitude="grows_with_data", exposure="entry_reachable") == str(VALUE_MAX)+ grows = {"loop_magnitude": "grows_with_data"}+ # Request or message, then a scheduled job, then no role evidence; a cold+ # role never leads.+ assert _value("request", **grows) == _value("event_consumer", **grows) == str(VALUE_MAX)+ assert _value("scheduled_job", **grows) == "3"+ assert _value("unknown", **grows) == "2"+ assert _value("cli", **grows) == "1"def test_it_outranks_a_large_function_that_needs_judgment_on_score() -> None:diff --git a/tests/unit/health/test_queue_value_order.py b/tests/unit/health/test_queue_value_order.pynew file mode 100644index 000000000..432b06830--- /dev/null+++ b/tests/unit/health/test_queue_value_order.py@@ -0,0 +1,111 @@+"""Rank-order golden for the Fix first queue: value band, tier, then worth.++Modelled on a large agent repository where the band alone could not tell a+4,226-line conversation loop from a status-printing wizard: both are past+every size bar, so the old order fell back to per-finding health credit,+which saturates, and ranked the loop 25th. Each item below says why it sits+where it does.+"""++from __future__ import annotations++from repowise.core.analysis.health.fix_first import build_fix_first+from tests.unit.health.fix_first_rows import AT, _perf++# Central and churning from 10 importers and 10 commits in 90 days.+_CUTS = (10.0, 10.0)+++def _metric(path: str, dependents: int, commits: int) -> dict:+ return {"file_path": path, "score": 3.0, "nloc": 900, "is_test": False,+ "commit_count_90d": commits, "dependents": dependents,+ "analyzed_commit": "abc", "updated_at": AT}+++def _finding(path: str, function: str, impact: float, **details) -> dict:+ return {"file_path": path, "biomarker_type": "complex_method", "severity": "high",+ "function_name": function, "line_start": 10, "line_end": 10 + details["nloc"],+ "health_impact": impact, "reason": f"{function} is complex",+ "public_id": f"finding_{function}", "dimension": "defect",+ "details": {**details, "deepest_block": {"start": 40, "end": 60}}}+++METRICS = [+ _metric("agent/conversation_loop.py", dependents=32, commits=40),+ _metric("cli/status.py", dependents=7, commits=40),+ _metric("gateway/config.py", dependents=487, commits=40),+ _metric("gateway/sessions.py", dependents=3, commits=2),+ _metric("lib/parse.py", dependents=0, commits=0),+]++FINDINGS = [+ _finding("agent/conversation_loop.py", "run_conversation", 0.25,+ ccn=963, nloc=4226, max_nesting=9),+ # A wizard: long and branchy, but it prints; its health credit is the+ # highest of the large functions, which is what used to rank it first.+ _finding("cli/status.py", "show_status", 0.72, ccn=153, nloc=478, max_nesting=6),+ _finding("gateway/config.py", "load_gateway_config", 0.52, ccn=151, nloc=341, max_nesting=6),+ # Past the bars by less: CCN 45 over 120 lines, in a file nothing imports.+ _finding("lib/parse.py", "parse_block", 1.6, ccn=45, nloc=120, max_nesting=6),+]++PERFORMANCE = [+ # A request handler's growing database loop: the top band.+ _perf("perf_req", "gateway/db.py::fetch", file_path="gateway/sessions.py",+ intervention_symbol="gateway/sessions.py::list_sessions"),+ # The same loop with no role evidence: a step below a request's.+ _perf("perf_unknown", "gateway/db.py::save", file_path="gateway/sessions.py",+ intervention_symbol="gateway/sessions.py::sync_all", execution_role="unknown"),+]++#: (finding's function or cause's id, value band, why it sits here).+GOLDEN = [+ ("run_conversation", "4", "largest complexity removed (963) x reach of 32 importers"),+ ("load_gateway_config", "4", "CCN 151 x reach of 487 importers outweighs the wizard"),+ ("show_status", "4", "the wizard: band 4 on size, CCN 153 x reach of only 7 importers"),+ ("perf_req", "4", "request-run growing db loop: top band, worth a CCN 40 x 3 call sites"),+ ("perf_unknown", "2", "the same loop with no role evidence: band 2, worth 103"),+ ("parse_block", "2", "band 2 on size and gain; worth 45 (no importers) is below 103"),+]+++def _queue():+ return build_fix_first(+ metrics=METRICS, findings=FINDINGS, performance=PERFORMANCE, hot_cuts=_CUTS,+ limit=None,+ )+++def _key(item) -> str:+ return item.target.symbol if item.kind == "finding" else item.source.opportunity_id+++def _value(item) -> str:+ return next(f.value for f in item.why_ranked if f.factor in ("value", "value within later"))+++def test_rank_order_golden() -> None:+ items = _queue().items+ got = [(_key(i), _value(i)) for i in items]+ assert got == [(symbol, band) for symbol, band, _why in GOLDEN]+++def test_the_giant_outranks_the_wizard_on_complexity_removed_times_reach() -> None:+ by_symbol = {i.target.symbol: i for i in _queue().items}+ giant, wizard = by_symbol["run_conversation"], by_symbol["show_status"]+ ranked = {f.factor: f.value for f in giant.why_ranked}+ assert ranked["complexity removed"] == "963"+ assert ranked["files that import it"] == "32 (top fifth)"+ assert giant.rank < wizard.rank+ # The wizard still earns more health credit: worth, not credit, orders the band.+ assert giant.gain.value < wizard.gain.value+++def test_history_orders_within_a_band_and_never_lifts_one() -> None:+ quiet = [{**m, "commit_count_90d": 0} for m in METRICS]+ base = {_key(i): _value(i) for i in _queue().items}+ calm = build_fix_first(metrics=quiet, findings=FINDINGS, performance=PERFORMANCE,+ hot_cuts=_CUTS, limit=None)+ assert {_key(i): _value(i) for i in calm.items} == base+ churn = {f.factor: f.value for f in calm.items[0].why_ranked}["changes often"]+ assert churn == "no"