Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
perf(refactoring): store plan rank at finalize and serve plan lists from SQL (#3315)
Raghav Chamadiya4f6930814e32
diff --git a/docs/architecture/refactoring.md b/docs/architecture/refactoring.mdindex de9e003a5..cdeac2653 100644--- a/docs/architecture/refactoring.md+++ b/docs/architecture/refactoring.md@@ -61,6 +61,10 @@ same transaction that reconciles plans. `performance_fix` is excluded (theperformance layer owns those). Plans whose source finding the finding registrywithholds are left out of steps and evidence but stay addressable by id.+Plan rank and validation are worked out once per index, so plan lists and single+plans are served from SQL however many plans a repository has. An index written by+an older version keeps working, at the old speed, until its next update.+Serving (filters, views, scope, paging) lives in `serving.py`; the server reads itthrough `services/refactoring_health.py`, which MCP `get_health` and the REST routesshare, so the two surfaces cannot disagree. Scope `fix_first` takes its eligibilitydiff --git a/packages/core/alembic/versions/0101_refactoring_plan_rank.py b/packages/core/alembic/versions/0101_refactoring_plan_rank.pynew file mode 100644index 000000000..b2785e3ac--- /dev/null+++ b/packages/core/alembic/versions/0101_refactoring_plan_rank.py@@ -0,0 +1,47 @@+"""Persist each refactoring plan's rank, rank factors and validation.++The finalizer ranks and validates every live plan once per index, so the plan+list endpoints read ``ORDER BY rank_position`` instead of ranking the whole+repository per request. NULL means the plan was not ranked by the last+finalize, and readers rank live.++Local SQLite stores get the columns from ``init_db``'s additive reconciler;+this migration covers managed Postgres.++Revision ID: 0101+Revises: 0100+Create Date: 2026-10-10+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0101"+down_revision: str | None = "0100"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.add_column("refactoring_suggestions", sa.Column("rank_position", sa.Integer(), nullable=True))+ op.add_column("refactoring_suggestions", sa.Column("blast_size", sa.Integer(), nullable=True))+ op.add_column("refactoring_suggestions", sa.Column("rank_json", sa.Text(), nullable=True))+ op.create_index(+ "ix_refactoring_suggestions_repo_status_rank",+ "refactoring_suggestions",+ ["repository_id", "status", "rank_position"],+ )+++def downgrade() -> None:+ op.drop_index(+ "ix_refactoring_suggestions_repo_status_rank", table_name="refactoring_suggestions"+ )+ op.drop_column("refactoring_suggestions", "rank_json")+ op.drop_column("refactoring_suggestions", "blast_size")+ op.drop_column("refactoring_suggestions", "rank_position")diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.pyindex a880ba224..36acc269e 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/recommendations.py@@ -18,8 +18,11 @@ from typing import Any, Literalfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.effort import EFFORT_ORDERfrom repowise.core.analysis.health.grading import TARGET_SCOREfrom repowise.core.analysis.health.perf.ranking import _percentile_threshold+from repowise.core.analysis.health.queue_rules import FilterRule, SortKeys+from repowise.core.analysis.health.refactoring_summary import STRUCTURAL_TYPESfrom repowise.core.analysis.pr_blast import rank_tests_by_reachfrom repowise.core.analysis.test_collection import narrow_scopesfrom repowise.core.analysis.test_reachability import (@@ -924,6 +927,103 @@ class Recommendation:"validation": self.validation.as_dict(),}+ def rank_facts(self) -> dict[str, Any]:+ """What ranking added to the stored plan, persisted once at finalize."""+ return {+ "benefit": self.benefit,+ "leverage": self.leverage,+ "cost": self.cost,+ "risk": self.risk,+ "rank_score": self.rank_score,+ "dependents": self.dependents,+ "file_nloc": self.file_nloc,+ "file_weighted_deficit": self.file_weighted_deficit,+ # Enriched with the caller rollup, which the stored column lacks.+ "blast_radius": self.suggestion.blast_radius or {},+ "validation": self.validation.as_dict(),+ }+++_RANK_FACTS = (+ "benefit",+ "leverage",+ "cost",+ "risk",+ "rank_score",+ "dependents",+ "file_nloc",+ "file_weighted_deficit",+)+++def stored_recommendation(row: Any) -> Recommendation | None:+ """The recommendation finalize persisted on *row*, or ``None`` when it has+ none or an incomplete one, so the caller rebuilds it instead."""+ from .serving import validation_from_profile++ facts = _loads_dict(_attr(row, "rank_json", None))+ if not isinstance(facts.get("validation"), dict) or any(k not in facts for k in _RANK_FACTS):+ return None+ try:+ validation = validation_from_profile(facts["validation"])+ except TypeError:+ return None+ suggestion = rehydrate_suggestion(row)+ suggestion.blast_radius = dict(facts.get("blast_radius") or {})+ suggestion.validation = validation.as_dict()+ return Recommendation(+ suggestion=suggestion,+ validation=validation,+ **{name: facts[name] for name in _RANK_FACTS},+ )+++#: Each bucket's place in the shared effort scale, for the ``effort`` sort.+EFFORT_RANK = {bucket: rank for rank, bucket in enumerate(EFFORT_ORDER)}+#: Where a bucket outside the scale sorts: with ``L``.+UNKNOWN_EFFORT = EFFORT_RANK["L"]++#: The plan list's filters, read in SQL on a ranked store+#: (``persistence.sql.rule_predicate``) and in memory on the live path+#: (``queue_rules.keep``), so the two cannot disagree.+PLAN_FILTERS = (+ FilterRule("refactoring_types", "refactoring_type", "in", "set"),+ FilterRule("file_path", "file_path", "eq", "set"),+ FilterRule("confidences", "confidence", "in", "truthy"),+ FilterRule("efforts", "effort_bucket", "in", "truthy"),+)++#: The plan list's field sorts; every one but ``file`` breaks ties by the view+#: order. ``effort`` reads :data:`EFFORT_RANK` and ``canonical`` is the view.+PLAN_SORTS: dict[str, SortKeys] = {+ "health": (("impact_delta", True),),+ "blast": (("blast_size", True),),+ "file": (("file_path", False), ("target_symbol", False), ("id", False)),+}+++def plan_types(refactoring_type: str | None) -> tuple[str, ...] | None:+ """The plan types a list's ``refactoring_type`` names; ``structural`` is a lens."""+ if refactoring_type == "structural":+ return tuple(sorted(STRUCTURAL_TYPES))+ return (refactoring_type,) if refactoring_type else None+++def matches_search(suggestion: RefactoringSuggestion, query: str) -> bool:+ """Whether lower-cased *query* occurs in the plan's searchable text."""+ plan = suggestion.plan or {}+ haystack = " ".join(+ (+ suggestion.file_path,+ suggestion.target_symbol,+ suggestion.refactoring_type,+ suggestion.source_biomarker,+ str(plan.get("strategy") or ""),+ str(plan.get("intervention_symbol") or ""),+ )+ ).lower()+ return query in haystack+def _priority_components(suggestion: RefactoringSuggestion,@@ -1322,6 +1422,10 @@ __all__ = ["CONFIDENCE_RISK","DEFAULT_TEST_LIMIT","EFFORT_COST",+ "EFFORT_RANK",+ "PLAN_FILTERS",+ "PLAN_SORTS",+ "UNKNOWN_EFFORT","Recommendation","RecommendationView","ValidationEvidence",@@ -1339,9 +1443,12 @@ __all__ = ["enrich_blast_radius","hub_files","hydrate_recommendations",+ "matches_search",+ "plan_types","priority_score","rehydrate_suggestion","serialize_recommendations",+ "stored_recommendation","surface_confidence_risk","target_symbol_ids",]diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 3772ea715..2834d75a7 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -112,7 +112,10 @@ from .refactoring import (finalize_refactoring_suggestions,get_refactoring_suggestion,get_refactoring_suggestions,+ ranked_refactoring_suggestions,save_refactoring_suggestions,+ store_plan_ranks,+ summarize_open_plans,update_refactoring_suggestion_status,upsert_refactoring_suggestions,)@@ -191,6 +194,7 @@ __all__ = ["performance_facet_counts","performance_file_rollups","prune_unscored_health_rows",+ "ranked_refactoring_suggestions","refactoring_facet_counts","replace_dead_code_findings","replace_doc_drift_findings",@@ -207,7 +211,9 @@ __all__ = ["serialize_doc_drift_reference_row","serialize_doc_drift_row","sort_metrics_worst_first",+ "store_plan_ranks","summarize_confidence_rows",+ "summarize_open_plans","tests_covering","tests_covering_files","update_dead_code_status",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.pyindex e0f18e2c3..461e22c13 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring.py@@ -12,13 +12,26 @@ what makes them agree.from __future__ import annotationsimport json+from collections.abc import Mappingfrom typing import Any-from sqlalchemy import func, or_, select+from sqlalchemy import (+ Select,+ String,+ Text,+ bindparam,+ case,+ collate,+ func,+ or_,+ select,+ update,+)from sqlalchemy.ext.asyncio import AsyncSessionfrom ....analysis.finding_registry import excluded_typesfrom ...models import RefactoringSuggestion, _new_uuid, _now_utc+from ...sql import LIKE_ESCAPE, escape_like, rule_predicatefrom .._shared import _BATCH_SIZE, _finding_file_path# The finding-triage vocabulary, shared with health findings so Code Health has@@ -248,6 +261,9 @@ async def finalize_refactoring_suggestions(for name in _REFRESHED_COLUMNS:if name in values:setattr(row, name, values[name])+ # Unranked until the finalizer ranks the refreshed content; a finalize+ # that fails then leaves no stale rank beside fresh fields.+ row.rank_position = row.blast_size = row.rank_json = Noneif row.status == "resolved" and row.status_reason == "no_longer_detected":row.status = "open"row.status_reason = None@@ -475,3 +491,231 @@ async def count_refactoring_suggestions())return int((await session.execute(q)).scalar_one())+++# ---------------------------------------------------------------------------+# Persisted rank: written once per finalize, read by every plan list+# ---------------------------------------------------------------------------+++async def store_plan_ranks(+ session: AsyncSession, repository_id: str, recommendations: list[Any]+) -> None:+ """Persist rank position, rank facts and change surface for *recommendations*.++ Every other row is cleared first, so a plan the finalizer did not rank+ (resolved, or reopened by hand since) reads as unranked and its list falls+ back to ranking live until the next index. Neither write moves+ ``updated_at``: a rank is derived, not a change to the plan.+ """+ from ....analysis.health.refactoring.recommendations import blast_size, canonical_order++ table = RefactoringSuggestion.__table__+ await session.execute(+ update(table)+ .where(table.c.repository_id == repository_id, table.c.rank_position.is_not(None))+ .values(+ rank_position=None, blast_size=None, rank_json=None, updated_at=table.c.updated_at+ )+ )+ values = [+ {+ "plan_id": item.id,+ "position": position,+ "surface": blast_size(item.suggestion),+ "facts": json.dumps(item.rank_facts(), separators=(",", ":")),+ }+ for position, item in enumerate(canonical_order(recommendations))+ ]+ statement = (+ update(table)+ .where(table.c.id == bindparam("plan_id"))+ .values(+ rank_position=bindparam("position"),+ blast_size=bindparam("surface"),+ rank_json=bindparam("facts"),+ updated_at=table.c.updated_at,+ )+ )+ for index in range(0, len(values), _BATCH_SIZE):+ await session.execute(statement, values[index : index + _BATCH_SIZE])+++def _base_order(view: str, predicates: list[Any]) -> tuple[Select[Any], tuple[Any, ...]]:+ """The plan query and its view order, before any narrowing filter.++ ``file_spread`` deals one plan per file per round over the whole base set,+ files in order of their best plan, as :func:`apply_view` does in memory.+ """+ if view != "file_spread":+ query = select(RefactoringSuggestion).where(*predicates)+ return query, (RefactoringSuggestion.rank_position,)+ position = RefactoringSuggestion.rank_position+ spread = (+ select(+ RefactoringSuggestion.id.label("plan_id"),+ func.row_number()+ .over(partition_by=RefactoringSuggestion.file_path, order_by=position)+ .label("spread_round"),+ func.min(position).over(partition_by=RefactoringSuggestion.file_path).label("first"),+ )+ .where(*predicates)+ .subquery()+ )+ query = select(RefactoringSuggestion).join(spread, spread.c.plan_id == RefactoringSuggestion.id)+ return query, (spread.c.spread_round, spread.c.first)+++def _sort_keys(sort: str, base: tuple[Any, ...], *, byte_order: bool) -> tuple[Any, ...]:+ """A named sort from the shared table, ties broken by the view order.++ *byte_order* collates text as Python compares it; SQLite's default already+ does, and it has no ``"C"`` collation to name.+ """+ from ....analysis.health.refactoring.recommendations import (+ EFFORT_RANK,+ PLAN_SORTS,+ UNKNOWN_EFFORT,+ )++ if sort == "effort":+ bucket = case(EFFORT_RANK, value=RefactoringSuggestion.effort_bucket, else_=UNKNOWN_EFFORT)+ return (bucket, *base)+ keys = PLAN_SORTS.get(sort)+ if keys is None:+ return base+ ordered = []+ for name, descending in keys:+ column = getattr(RefactoringSuggestion, name)+ if byte_order and isinstance(column.type, String | Text):+ column = collate(column, "C")+ ordered.append(column.desc() if descending else column.asc())+ return (*ordered, *base)+++def _search_prefilter(search: str) -> list[Any]:+ """Every word of *search* in some searchable column: a superset of the+ exact match, which :func:`matches_search` then decides.++ A word ``plan_json`` may store escaped (non-ASCII, a quote, a backslash),+ or SQLite cannot case-fold (non-ASCII), is left to the exact match alone.+ """+ columns = (+ RefactoringSuggestion.file_path,+ RefactoringSuggestion.target_symbol,+ RefactoringSuggestion.refactoring_type,+ RefactoringSuggestion.source_biomarker,+ RefactoringSuggestion.plan_json,+ )+ return [+ or_(+ *(+ func.lower(column).like(f"%{escape_like(word)}%", escape=LIKE_ESCAPE)+ for column in columns+ )+ )+ for word in search.split()+ if word.isascii() and '"' not in word and "\\" not in word+ ]+++async def ranked_refactoring_suggestions(+ session: AsyncSession,+ repository_id: str,+ *,+ min_confidence: str | None = None,+ filters: Mapping[str, Any] | None = None,+ search: str = "",+ sort: str = "canonical",+ view: str = "canonical",+ limit: int | None = None,+ offset: int = 0,+) -> tuple[list[RefactoringSuggestion], int] | None:+ """One page of open plans in persisted rank order, and its total.++ *filters* are the params of the shared ``PLAN_FILTERS``. They narrow after+ the view is dealt, as the in-memory path does, so a filtered+ ``file_spread`` keeps the order the unfiltered one had. A search reads+ every row its SQL prefilter keeps, so its cost is bounded only by that+ prefilter. ``None`` when an open plan was not ranked by the last+ finalize: the caller ranks live.+ """+ from ....analysis.health.queue_rules import active_filters+ from ....analysis.health.refactoring.recommendations import (+ PLAN_FILTERS,+ matches_search,+ rehydrate_suggestion,+ )++ base = _suggestion_filters(+ repository_id,+ refactoring_type=None,+ file_paths=None,+ min_confidence=min_confidence,+ status="open",+ )+ unranked = await session.execute(+ select(RefactoringSuggestion.id)+ .where(*base, RefactoringSuggestion.rank_position.is_(None))+ .limit(1)+ )+ if unranked.first() is not None:+ return None+ query, order = _base_order(view, base)+ narrowing = [+ rule_predicate(RefactoringSuggestion, rule, value)+ for rule, value in active_filters(PLAN_FILTERS, filters or {})+ ]+ byte_order = session.get_bind().dialect.name == "postgresql"+ query = query.where(*narrowing, *_search_prefilter(search)).order_by(+ *_sort_keys(sort, order, byte_order=byte_order)+ )+ if search:+ # The prefilter bounds the read; the exact match is the shared one.+ rows = [+ row+ for row in (await session.execute(query)).scalars().all()+ if matches_search(rehydrate_suggestion(row), search)+ ]+ end = None if limit is None else offset + limit+ return rows[offset:end], len(rows)+ total = int(+ (await session.execute(select(func.count()).select_from(query.subquery()))).scalar_one()+ )+ query = query.offset(offset)+ if limit is not None:+ query = query.limit(limit)+ return list((await session.execute(query)).scalars().all()), total+++async def summarize_open_plans(+ session: AsyncSession, repository_id: str, *, min_confidence: str | None = None+) -> dict[str, Any]:+ """The plan board's chip counts over the open plans, from narrow columns.++ The plan payload is read only for the grouping types whose design count+ needs it.+ """+ from ....analysis.health.refactoring_summary import GROUPING_TYPES, summarize_plans++ kind = RefactoringSuggestion.refactoring_type+ rows = await session.execute(+ select(+ kind,+ RefactoringSuggestion.file_path,+ RefactoringSuggestion.effort_bucket,+ RefactoringSuggestion.impact_delta,+ case(+ (kind.in_(sorted(GROUPING_TYPES)), RefactoringSuggestion.plan_json), else_=None+ ).label("plan_json"),+ ).where(+ *_suggestion_filters(+ repository_id,+ refactoring_type=None,+ file_paths=None,+ min_confidence=min_confidence,+ status="open",+ )+ )+ )+ return summarize_plans(rows.all())diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.pyindex 38895583b..27c365b4c 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/refactoring_opportunities.py@@ -262,6 +262,32 @@ def _summary_payload(}+async def _rank_live_plans(session: AsyncSession, repository_id: str) -> list[Any]:+ """Rank and validate every live plan the lists can show, and store it.++ Performance plans are not composed here, but they share the plan lists, so+ their positions come from the same pass. Plans the finding registry+ withholds are left out: no list shows them, and the file-level test walk+ is batch-sensitive, so ranking them alongside would change the tests the+ shown plans list.+ """+ from ....analysis.health.refactoring.recommendations import hydrate_recommendations+ from .refactoring import shown_plan_predicate, store_plan_ranks++ rows = (+ await session.execute(+ select(RefactoringSuggestion).where(+ RefactoringSuggestion.repository_id == repository_id,+ RefactoringSuggestion.status.in_(tuple(_LIVE_PLAN_STATUSES)),+ shown_plan_predicate(),+ )+ )+ ).scalars()+ ranked = await hydrate_recommendations(session, repository_id, list(rows))+ await store_plan_ranks(session, repository_id, ranked)+ return ranked++async def finalize_refactoring_opportunities(session: AsyncSession,repository_id: str,@@ -283,7 +309,6 @@ async def finalize_refactoring_opportunities(compose_opportunities,opportunity_status,)- from ....analysis.health.refactoring.recommendations import hydrate_recommendationsfrom ....analysis.health.refactoring_summary import needs_designplan_rows = list(@@ -331,22 +356,22 @@ async def finalize_refactoring_opportunities(findings=findings,)- # Validation is resolved once, here, for exactly the plans that became- # steps. It used to be rebuilt on every request for every open plan, which- # is the single largest cost the serving path used to carry.+ # Rank and validation are resolved once, here, for every live plan. They+ # used to be rebuilt on every request for every open plan, which is the+ # single largest cost the serving path used to carry.+ ranked = await _rank_live_plans(session, repository_id)step_plan_ids = {step.plan_id for item in opportunities for step in item.steps}step_rows = [row for row in live_plans if row.public_id in step_plan_ids]validations: dict[str, dict[str, Any]] = {}file_figures: dict[str, dict[str, int]] = {}if step_rows:# Keyed by the storage id ``rehydrate_suggestion`` carries through, never- # by position: ``hydrate_recommendations`` returns its results in rank- # order, so zipping them against the input pairs most steps with another- # plan's validation profile.+ # by position: the ranked list is in rank order, so zipping it against+ # the rows pairs most steps with another plan's validation profile.public_by_storage = {row.id: row.public_id for row in step_rows}- for recommendation in await hydrate_recommendations(- session, repository_id, step_rows- ):+ for recommendation in ranked:+ if recommendation.id not in public_by_storage:+ continuepublic_id = public_by_storage.get(getattr(recommendation.suggestion, "id", None))diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex a9d58075e..5f0a21dae 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -1859,6 +1859,14 @@ class RefactoringSuggestion(Base):status_changed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ # The plan's place in the canonical rank, its rank factors and validation+ # profile (``rank_json``) and its change surface, written at finalize for+ # every live plan so a plan list is an ``ORDER BY``, not a hydration. NULL+ # on a row the last finalize did not rank: readers fall back to ranking live.+ rank_position: Mapped[int | None] = mapped_column(Integer, nullable=True)+ # A column only so the ``blast`` sort can be an ORDER BY.+ blast_size: Mapped[int | None] = mapped_column(Integer, nullable=True)+ rank_json: Mapped[str | None] = mapped_column(Text, nullable=True)created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False, default=_now_utc)@@ -1867,6 +1875,12 @@ class RefactoringSuggestion(Base):)__table_args__ = (+ Index(+ "ix_refactoring_suggestions_repo_status_rank",+ "repository_id",+ "status",+ "rank_position",+ ),Index("ix_refactoring_suggestions_repo_type_opportunity","repository_id",diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.pyindex 0a6cc3c02..fbeb830e8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py@@ -12,7 +12,6 @@ from __future__ import annotationsfrom pathlib import Path-from repowise.core.analysis.health.refactoring.recommendations import hydrate_recommendationsfrom repowise.core.persistence.crud import get_refactoring_suggestionfrom repowise.core.persistence.database import get_sessionfrom repowise.core.registry import mcp_tool_registry as mcp@@ -22,6 +21,7 @@ from repowise.server.mcp_server._helpers import (_unsupported_repo_all,)from repowise.server.mcp_server._meta import build_meta as _build_meta+from repowise.server.services.refactoring_health import RefactoringHealthService@mcp.tool(@@ -86,7 +86,9 @@ async def generate_refactoring_code(suggestion_id: str, repo: str | None = None)"detail": f"No refactoring plan with id {suggestion_id!r} in this repo.","_meta": _build_meta(repository=repository),}- recommendation = (await hydrate_recommendations(session, repository.id, [row]))[0]+ recommendation = await RefactoringHealthService(+ session, repository.id, ctx.alias or repository.name+ ).plan_recommendation(row)sug = recommendation.suggestionmeta = _build_meta(repository=repository)diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.pyindex f767f7e81..88c80ad7e 100644--- a/packages/server/src/repowise/server/routers/refactoring.py+++ b/packages/server/src/repowise/server/routers/refactoring.py@@ -19,20 +19,12 @@ from fastapi import APIRouter, Depends, HTTPException, Queryfrom pydantic import BaseModel, Fieldfrom sqlalchemy.ext.asyncio import AsyncSession-from repowise.core.analysis.health.effort import EFFORT_ORDER-from repowise.core.analysis.health.refactoring.recommendations import (- apply_view,- blast_size,- detail_recommendations,- hydrate_recommendations,-)from repowise.core.analysis.health.refactoring.serving import (CANONICAL_ORDERS,CANONICAL_VIEWS,DEFAULT_VIEW,parse_query,)-from repowise.core.analysis.health.refactoring_summary import STRUCTURAL_TYPES, summarize_plansfrom repowise.core.persistence import crudfrom repowise.core.persistence.crud.analysis.refactoring import ALLOWED_STATUSESfrom repowise.server.deps import get_db_session, verify_api_key@@ -43,7 +35,7 @@ from repowise.server.schemas import (RefactoringPlanStatusResponse,RefactoringRollupResponse,)-from repowise.server.services.refactoring_health import RefactoringHealthService+from repowise.server.services.refactoring_health import PlanListQuery, RefactoringHealthService_STEPS_PER_ROW = 3"""Steps carried on a queue row; the detail call pages the rest."""@@ -144,64 +136,8 @@ def _to_response(data: dict[str, Any]) -> RefactoringPlanResponse:return RefactoringPlanResponse(**data)-_STRUCTURAL_TYPES = STRUCTURAL_TYPES-_EFFORT_ORDER = {bucket: rank for rank, bucket in enumerate(EFFORT_ORDER)}---def _summary(recommendations: list[Any]) -> RefactoringSummary:- return RefactoringSummary(**summarize_plans(item.suggestion for item in recommendations))---def _csv_values(value: str | None) -> set[str]:- return {part.strip() for part in (value or "").split(",") if part.strip()}---def _matches_search(recommendation: Any, query: str) -> bool:- suggestion = recommendation.suggestion- plan = suggestion.plan or {}- haystack = " ".join(- (- suggestion.file_path,- suggestion.target_symbol,- suggestion.refactoring_type,- suggestion.source_biomarker,- str(plan.get("strategy") or ""),- str(plan.get("intervention_symbol") or ""),- )- ).lower()- return query in haystack---def _sort_recommendations(recommendations: list[Any], sort: str) -> list[Any]:- canonical_position = {item.id: index for index, item in enumerate(recommendations)}- if sort == "canonical":- return recommendations- if sort == "health":- return sorted(- recommendations,- key=lambda item: (-item.suggestion.impact_delta, canonical_position[item.id]),- )- if sort == "effort":- return sorted(- recommendations,- key=lambda item: (- _EFFORT_ORDER.get(item.suggestion.effort_bucket, 2),- canonical_position[item.id],- ),- )- if sort == "blast":- return sorted(- recommendations,- key=lambda item: (-blast_size(item.suggestion), canonical_position[item.id]),- )- return sorted(- recommendations,- key=lambda item: (- item.suggestion.file_path,- item.suggestion.target_symbol,- item.id,- ),- )+def _csv_values(value: str | None) -> frozenset[str]:+ return frozenset(part.strip() for part in (value or "").split(",") if part.strip())# ---------------------------------------------------------------------------@@ -232,34 +168,15 @@ async def get_refactoring_targets(honor *min_confidence* — so the summary and the plan list stay consistentunder a confidence filter."""- # Summary is computed over the unfiltered-by-type set so the chips can show- # every type's count even while one type is selected.- all_rows = await crud.get_refactoring_suggestions(- session, repo_id, min_confidence=min_confidence- )- by_type: dict[str, int] = {}- for row in all_rows:- by_type[row.refactoring_type] = by_type.get(row.refactoring_type, 0) + 1- summary = RefactoringSummary(- total=len(all_rows),- by_type=[- RefactoringTypeCount(type=t, count=c)- for t, c in sorted(by_type.items(), key=lambda kv: (-kv[1], kv[0]))- ],- )-- rows = (- all_rows- if refactoring_type is None- else [r for r in all_rows if r.refactoring_type == refactoring_type]- )- if file_path is not None:- rows = [r for r in rows if r.file_path == file_path]- recommendations = await hydrate_recommendations(session, repo_id, rows, view=view)- return RefactoringTargetsResponse(- summary=summary,- plans=[_to_response(recommendation.as_dict()) for recommendation in recommendations],+ body = await _service(session, repo_id).ranked_plans(+ PlanListQuery(+ refactoring_type=refactoring_type,+ min_confidence=min_confidence,+ file_path=file_path,+ view=view,+ ))+ return RefactoringTargetsResponse(**body)@router.get("/{repo_id}/refactoring/targets/page", response_model=RefactoringPlanPageResponse)@@ -279,58 +196,24 @@ async def get_refactoring_plan_page() -> RefactoringPlanPageResponse:"""Bounded list with server-owned filters and deterministic ordering.- Ranking is one batched pass over the repository plans, so priority keeps its- validation-basis input and a constant SQL shape. The symbol-level evidence- that orders each plan's tests is read only for the rows this response- returns.+ Reads the rank, factors and validation the finalizer stored: filters,+ order and paging are SQL, so the cost follows the page, not the plan count."""- rows = await crud.get_refactoring_suggestions(session, repo_id, min_confidence=min_confidence)- canonical = await hydrate_recommendations(- session, repo_id, rows, view="canonical", rank_only=True- )- summary = _summary(canonical)- structural_leads = [- item for item in canonical if item.suggestion.refactoring_type in _STRUCTURAL_TYPES- ][:12]-- ordered = apply_view(canonical, view)- if refactoring_type == "structural":- ordered = [- item for item in ordered if item.suggestion.refactoring_type in _STRUCTURAL_TYPES- ]- elif refactoring_type:- ordered = [item for item in ordered if item.suggestion.refactoring_type == refactoring_type]- if file_path is not None:- ordered = [item for item in ordered if item.suggestion.file_path == file_path]- confidences = _csv_values(confidence)- if confidences:- ordered = [item for item in ordered if item.suggestion.confidence in confidences]- efforts = _csv_values(effort)- if efforts:- ordered = [item for item in ordered if item.suggestion.effort_bucket in efforts]- normalized_search = (search or "").strip().lower()- if normalized_search:- ordered = [item for item in ordered if _matches_search(item, normalized_search)]- ordered = _sort_recommendations(ordered, sort)-- total = len(ordered)- page = ordered[offset : offset + limit]- next_offset = offset + len(page) if offset + len(page) < total else None- shown = list({id(item): item for item in [*page, *structural_leads]}.values())- detailed = {- id(item.suggestion): item- for item in await detail_recommendations(session, repo_id, shown)- }- page = [detailed[id(item.suggestion)] for item in page]- structural_leads = [detailed[id(item.suggestion)] for item in structural_leads]- return RefactoringPlanPageResponse(- items=[_to_response(item.as_dict()) for item in page],- total=total,- has_more=next_offset is not None,- next_offset=next_offset,- summary=summary,- structural_leads=[_to_response(item.as_dict()) for item in structural_leads],+ body = await _service(session, repo_id).ranked_plan_page(+ PlanListQuery(+ refactoring_type=refactoring_type,+ min_confidence=min_confidence,+ confidences=_csv_values(confidence),+ efforts=_csv_values(effort),+ file_path=file_path,+ search=(search or "").strip().lower(),+ sort=sort,+ view=view,+ limit=limit,+ offset=offset,+ ))+ return RefactoringPlanPageResponse(**body)# ---------------------------------------------------------------------------@@ -627,7 +510,7 @@ async def get_refactoring_plan(row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)if row is None:raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")- recommendation = (await hydrate_recommendations(session, repo_id, [row]))[0]+ recommendation = await _service(session, repo_id).plan_recommendation(row)return _to_response(recommendation.as_dict())@@ -742,7 +625,7 @@ async def generate_refactoring_code(row = await crud.get_refactoring_suggestion(session, repo_id, suggestion_id)if row is None:raise HTTPException(status_code=404, detail=f"refactoring plan not found: {suggestion_id}")- recommendation = (await hydrate_recommendations(session, repo_id, [row]))[0]+ recommendation = await _service(session, repo_id).plan_recommendation(row)sug = recommendation.suggestionbody = body or GenerateCodeRequest()diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.pyindex 2e858afe3..44a577d25 100644--- a/packages/server/src/repowise/server/services/refactoring_health.py+++ b/packages/server/src/repowise/server/services/refactoring_health.py@@ -10,21 +10,36 @@ drift apart.The session-free half (query parsing, the sort/filter/facet rules and everyresponse shape) is ``analysis/health/refactoring/serving.py``; this module-runs the reads and hands rows to it. Nothing here composes or ranks. Composition is-``analysis/health/refactoring/opportunity.py`` and it runs at index time; this-module reads what the finalizer wrote.+runs the reads and hands rows to it. Nothing here composes, and nothing ranks+except the plan-list fallback for a store the finalizer has not ranked.+Composition is ``analysis/health/refactoring/opportunity.py`` and it runs at+index time; this module reads what the finalizer wrote."""from __future__ import annotationsfrom collections import Counterfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, Literalfrom sqlalchemy import or_, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.analysis.health.queue_rules import keep, sort_keyfrom repowise.core.analysis.health.refactoring.identity import REFACTORING_MODEL_VERSION+from repowise.core.analysis.health.refactoring.recommendations import (+ EFFORT_RANK,+ PLAN_FILTERS,+ PLAN_SORTS,+ UNKNOWN_EFFORT,+ apply_view,+ blast_size,+ detail_recommendations,+ hydrate_recommendations,+ matches_search,+ plan_types,+ stored_recommendation,+)from repowise.core.analysis.health.refactoring.serving import (RefactoringQuery,directive_from_summary,@@ -36,8 +51,14 @@ from repowise.core.analysis.health.refactoring.serving import (summary_payload,validation_from_profile,)+from repowise.core.analysis.health.refactoring_summary import summarize_plansfrom repowise.core.analysis.health.rows import detail_map, json_fieldfrom repowise.core.persistence.crud.analysis.fix_first import load_fix_first+from repowise.core.persistence.crud.analysis.refactoring import (+ get_refactoring_suggestions,+ ranked_refactoring_suggestions,+ summarize_open_plans,+)from repowise.core.persistence.crud.analysis.refactoring_opportunities import (get_refactoring_opportunity,get_refactoring_summary,@@ -114,6 +135,72 @@ def _plan_window(return window+@dataclass(frozen=True, slots=True)+class PlanListQuery:+ """One plan-list request: the filters, search, order and page."""++ refactoring_type: str | None = None+ min_confidence: str | None = None+ confidences: frozenset[str] = frozenset()+ efforts: frozenset[str] = frozenset()+ file_path: str | None = None+ search: str = ""+ sort: str = "canonical"+ view: Literal["canonical", "file_spread"] = "canonical"+ limit: int | None = None+ offset: int = 0++ def filters(self) -> dict[str, Any]:+ """The params ``PLAN_FILTERS`` reads, on either path."""+ return {+ "refactoring_types": plan_types(self.refactoring_type),+ "file_path": self.file_path,+ "confidences": self.confidences,+ "efforts": self.efforts,+ }+++#: Structural plans a plan page leads with.+_STRUCTURAL_LEADS = 12+++def _live_sorted(items: list[Any], sort: str) -> list[Any]:+ """*items*, in view order, under a named sort from the shared table."""+ position = {id(item): index for index, item in enumerate(items)}++ def key(item: Any) -> tuple[Any, ...]:+ suggestion = item.suggestion+ if sort == "effort":+ bucket = EFFORT_RANK.get(suggestion.effort_bucket, UNKNOWN_EFFORT)+ return (bucket, position[id(item)])+ row = {+ "impact_delta": suggestion.impact_delta,+ "blast_size": blast_size(suggestion),+ "file_path": suggestion.file_path,+ "target_symbol": suggestion.target_symbol,+ "id": item.id,+ }+ return (*sort_key(PLAN_SORTS[sort], row), position[id(item)])++ if sort != "effort" and sort not in PLAN_SORTS:+ return items+ return sorted(items, key=key)+++def _plan_page_payload(+ items: list[Any], total: int, offset: int, summary: dict[str, Any], leads: list[Any]+) -> dict[str, Any]:+ next_offset = offset + len(items) if offset + len(items) < total else None+ return {+ "items": [item.as_dict() for item in items],+ "total": total,+ "has_more": next_offset is not None,+ "next_offset": next_offset,+ "summary": summary,+ "structural_leads": [item.as_dict() for item in leads],+ }++class RefactoringHealthService:"""Query, page, detail and headline over the materialized opportunities."""@@ -334,35 +421,16 @@ class RefactoringHealthService:async def plan_detail(self, plan_id: str) -> dict[str, Any]:"""Resolve one plan id without hydrating the repository.- Every read is a seek. The row comes from the storage-or-public id index,- its rank inputs from the one metric row and the one file's centrality,- and its validation from the profile the finalizer already resolved. The- payload is built by the same ``build_recommendations`` every surface- uses, so it is field-identical to the hydrated form; what is gone is the- two full-table reads and the test-reachability walk that made resolving- one id cost the repository.+ Every read is a seek: the row from the storage-or-public id index, and+ its rank and validation as :meth:`plan_recommendation` finds them."""- from repowise.core.analysis.health.refactoring.recommendations import (- build_recommendations,- rehydrate_suggestion,- )from repowise.core.persistence.crud import get_refactoring_suggestionrow = await get_refactoring_suggestion(self._session, self._repository_id, plan_id)if row is None:return {"resolved": False, "plan_id": plan_id, "reason": "unknown_plan_id"}owner = await self._owning_opportunity(row.public_id, row.file_path)- metric_by_path, centrality = await self._rank_inputs(row.file_path)- built = build_recommendations(- [rehydrate_suggestion(row)],- metric_by_path=metric_by_path,- centrality=centrality,- validations={- 0: stored_validation(owner, row.public_id)- or await self._performance_validation(row)- },- )- payload = built[0].as_dict() if built else plan_payload(row)+ payload = (await self.plan_recommendation(row, owner=owner)).as_dict()payload["id"] = row.public_id or row.idpayload["status"] = row.statusresult: dict[str, Any] = {"resolved": True, "plan_id": plan_id, "plan": payload}@@ -377,6 +445,146 @@ class RefactoringHealthService:}return result+ # -- plan lists ---------------------------------------------------------+ #+ # Each list reads the rank, factors and validation the finalizer stored, so+ # its cost follows the page. A store with an open plan the finalizer did+ # not rank is ranked per request instead. Remove that live path once every+ # served store has been indexed by a version that writes ranks.++ async def ranked_plans(self, query: PlanListQuery) -> dict[str, Any]:+ """Every open plan the query matches, ranked, with the per-type chips.++ The chips ignore the type and file filters, so each type keeps its+ total while one is selected, but honour ``min_confidence``.+ """+ stored = await ranked_refactoring_suggestions(+ self._session,+ self._repository_id,+ min_confidence=query.min_confidence,+ filters=query.filters(),+ view=query.view,+ )+ if stored is not None:+ chips = await summarize_open_plans(+ self._session, self._repository_id, min_confidence=query.min_confidence+ )+ plans = [stored_recommendation(row).as_dict() for row in stored[0]]+ else:+ rows = await get_refactoring_suggestions(+ self._session, self._repository_id, min_confidence=query.min_confidence+ )+ chips = summarize_plans(rows)+ kept = [row for row in rows if keep(PLAN_FILTERS, row, query.filters())]+ ranked = await hydrate_recommendations(+ self._session, self._repository_id, kept, view=query.view+ )+ plans = [item.as_dict() for item in ranked]+ return {"summary": {"total": chips["total"], "by_type": chips["by_type"]}, "plans": plans}++ async def ranked_plan_page(self, query: PlanListQuery) -> dict[str, Any]:+ """One page of open plans, its total, the chips and the structural leads."""+ stored = await ranked_refactoring_suggestions(+ self._session,+ self._repository_id,+ min_confidence=query.min_confidence,+ filters=query.filters(),+ search=query.search,+ sort=query.sort,+ view=query.view,+ limit=query.limit,+ offset=query.offset,+ )+ if stored is None:+ return await self._live_plan_page(query)+ rows, total = stored+ leads = await ranked_refactoring_suggestions(+ self._session,+ self._repository_id,+ min_confidence=query.min_confidence,+ filters={"refactoring_types": plan_types("structural")},+ limit=_STRUCTURAL_LEADS,+ )+ return _plan_page_payload(+ [stored_recommendation(row) for row in rows],+ total,+ query.offset,+ await summarize_open_plans(+ self._session, self._repository_id, min_confidence=query.min_confidence+ ),+ [stored_recommendation(row) for row in (leads[0] if leads else [])],+ )++ async def _live_plan_page(self, query: PlanListQuery) -> dict[str, Any]:+ """The page ranked per request. One batched ranking pass over the open+ plans; the symbol-level evidence that orders each plan's tests is read+ only for the rows this response returns."""+ rows = await get_refactoring_suggestions(+ self._session, self._repository_id, min_confidence=query.min_confidence+ )+ canonical = await hydrate_recommendations(+ self._session, self._repository_id, rows, view="canonical", rank_only=True+ )+ structural = plan_types("structural") or ()+ leads = [item for item in canonical if item.suggestion.refactoring_type in structural]+ leads = leads[:_STRUCTURAL_LEADS]+ filters = query.filters()+ ordered = _live_sorted(+ [+ item+ for item in apply_view(canonical, query.view)+ if keep(PLAN_FILTERS, item.suggestion, filters)+ and (not query.search or matches_search(item.suggestion, query.search))+ ],+ query.sort,+ )+ end = None if query.limit is None else query.offset + query.limit+ page = ordered[query.offset : end]+ shown = list({id(item): item for item in [*page, *leads]}.values())+ detailed = {+ id(item.suggestion): item+ for item in await detail_recommendations(self._session, self._repository_id, shown)+ }+ return _plan_page_payload(+ [detailed[id(item.suggestion)] for item in page],+ len(ordered),+ query.offset,+ summarize_plans(item.suggestion for item in canonical),+ [detailed[id(item.suggestion)] for item in leads],+ )++ async def plan_recommendation(self, row: Any, *, owner: Any = None) -> Any:+ """One stored plan as a ranked recommendation, without the repository.++ The finalizer persists each live plan's rank and validation, so this is+ normally a read of the row itself. A row it did not rank (an index+ written before that, or a plan reopened by hand since) is rebuilt from+ seeks: the one metric row, the one file's centrality and the validation+ profile its opportunity stored, through the same+ ``build_recommendations`` every surface uses.+ """+ from repowise.core.analysis.health.refactoring.recommendations import (+ build_recommendations,+ rehydrate_suggestion,+ stored_recommendation,+ )++ stored = stored_recommendation(row)+ if stored is not None:+ return stored+ if owner is None:+ owner = await self._owning_opportunity(row.public_id, row.file_path)+ metric_by_path, centrality = await self._rank_inputs(row.file_path)+ return build_recommendations(+ [rehydrate_suggestion(row)],+ metric_by_path=metric_by_path,+ centrality=centrality,+ validations={+ 0: stored_validation(owner, row.public_id)+ or await self._performance_validation(row)+ },+ )[0]+async def _performance_validation(self, row: Any) -> Any:"""A performance plan's profile, stored on its opportunity at finalize.diff --git a/tests/unit/server/test_refactoring_plan_rank.py b/tests/unit/server/test_refactoring_plan_rank.pynew file mode 100644index 000000000..bc4e6407d--- /dev/null+++ b/tests/unit/server/test_refactoring_plan_rank.py@@ -0,0 +1,318 @@+"""Plan lists read the rank finalize stored, and answer exactly as ranking live did.++The golden here is the live path itself: every query is answered once from the+stored rank with per-request ranking disabled, then again after the stored rank+is cleared, and the two responses must be identical.+"""++from __future__ import annotations++import pytest+from httpx import AsyncClient+from sqlalchemy import select, update++from repowise.core.analysis.health.refactoring import llm, recommendations+from repowise.core.persistence import crud+from repowise.core.persistence.crud.analysis.refactoring import _refactoring_row_kwargs+from repowise.core.persistence.models import RefactoringSuggestion+from repowise.server.services import refactoring_health as service++from .test_refactoring import _seed++pytestmark = pytest.mark.usefixtures("dry_violation_shown")++_EXTRA = [+ {+ "refactoring_type": "extract_method",+ "file_path": "pkg/leaf.py",+ "target_symbol": "long_one",+ "line_start": 210,+ "line_end": 260,+ "plan": {"strategy": "lift the parsing loop"},+ "evidence": {},+ "impact_delta": 1.2,+ "effort_bucket": "S",+ "blast_radius": {},+ "confidence": "high",+ "source_biomarker": "large_method",+ },+ {+ "refactoring_type": "split_file",+ "file_path": "pkg/hub.py",+ "target_symbol": "pkg/hub.py",+ "plan": {"groups": [{"suggested_file": "pkg/hub_io.py"}]},+ "evidence": {"group_count": 2},+ "impact_delta": 0.3,+ "effort_bucket": "XL",+ "blast_radius": {"files": ["pkg/hub.py", "pkg/a.py", "pkg/b.py"]},+ "confidence": "low",+ "source_biomarker": "",+ },+ {+ "refactoring_type": "performance_fix",+ "file_path": "pkg/b.py",+ "target_symbol": "load_all",+ "line_start": 12,+ "line_end": 18,+ "plan": {"opportunity_id": "perf_x", "steps": []},+ "evidence": {"rank_factors": {"loop_magnitude": 2.0}},+ "impact_delta": 0.0,+ "effort_bucket": "M",+ "blast_radius": {"call_sites": 2},+ "confidence": "medium",+ "source_biomarker": "io_in_loop",+ },+]++_QUERIES = [+ ("targets", {}),+ ("targets", {"view": "file_spread"}),+ ("targets", {"refactoring_type": "extract_method"}),+ ("targets", {"min_confidence": "medium", "file_path": "pkg/leaf.py"}),+ ("targets/page", {}),+ ("targets/page", {"limit": 2, "offset": 1}),+ ("targets/page", {"view": "file_spread", "refactoring_type": "structural"}),+ ("targets/page", {"sort": "health"}),+ ("targets/page", {"sort": "effort", "view": "file_spread"}),+ ("targets/page", {"sort": "blast"}),+ ("targets/page", {"sort": "file", "limit": 3}),+ ("targets/page", {"search": "helper.do_work"}),+ ("targets/page", {"search": "parsing loop"}),+ ("targets/page", {"confidence": "medium,high", "effort": "S,M", "view": "file_spread"}),+ ("targets/page", {"min_confidence": "medium", "limit": 1, "offset": 2}),+]+++async def _seed_ranked(client: AsyncClient, app) -> str:+ repo_id = await _seed(client, app)+ async with app.state.session_factory() as session:+ for plan in _EXTRA:+ session.add(RefactoringSuggestion(**_refactoring_row_kwargs(plan, repo_id)))+ # Ranked at finalize, never listed: lists show open plans only.+ session.add(+ RefactoringSuggestion(+ **_refactoring_row_kwargs({**_EXTRA[0], "target_symbol": "picked_up"}, repo_id),+ status="acknowledged",+ )+ )+ await session.flush()+ await crud.finalize_refactoring_opportunities(session, repo_id)+ await session.commit()+ return repo_id+++async def _answers(client: AsyncClient, repo_id: str) -> list[dict]:+ out = []+ for path, params in _QUERIES:+ response = await client.get(f"/api/repos/{repo_id}/refactoring/{path}", params=params)+ assert response.status_code == 200, (path, params, response.text)+ out.append(response.json())+ return out+++async def _unrank(app, repo_id: str, *, public_id: str | None = None) -> None:+ async with app.state.session_factory() as session:+ statement = update(RefactoringSuggestion).where(+ RefactoringSuggestion.repository_id == repo_id+ )+ if public_id is not None:+ statement = statement.where(RefactoringSuggestion.public_id == public_id)+ await session.execute(statement.values(rank_position=None, rank_json=None, blast_size=None))+ await session.commit()+++def _no_live_ranking(monkeypatch: pytest.MonkeyPatch) -> None:+ def refuse(*_args, **_kwargs):+ raise AssertionError("a ranked store must not be ranked per request")++ monkeypatch.setattr(service, "hydrate_recommendations", refuse)+ monkeypatch.setattr(service, "detail_recommendations", refuse)+ # The one-plan rebuild from seeks is the fallback too.+ monkeypatch.setattr(recommendations, "build_recommendations", refuse)+ monkeypatch.setattr(service.RefactoringHealthService, "_rank_inputs", refuse)+++async def test_stored_rank_answers_every_query_as_live_ranking_did(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ repo_id = await _seed_ranked(client, app)+ with monkeypatch.context() as patch:+ _no_live_ranking(patch)+ stored = await _answers(client, repo_id)+ await _unrank(app, repo_id)+ live = await _answers(client, repo_id)++ assert stored == live+ # The rank order is the canonical one: a non-empty default page leads with+ # the highest score among production plans.+ page = stored[4]+ assert page["total"] == 7+ assert [item["id"] for item in page["items"]] == [plan["id"] for plan in stored[0]["plans"]]+++async def test_a_plan_finalize_did_not_rank_sends_the_list_live(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ repo_id = await _seed_ranked(client, app)+ expected = await _answers(client, repo_id)+ async with app.state.session_factory() as session:+ reopened = (+ await session.execute(+ select(RefactoringSuggestion.public_id).where(+ RefactoringSuggestion.repository_id == repo_id,+ RefactoringSuggestion.refactoring_type == "move_method",+ )+ )+ ).scalar_one()+ await _unrank(app, repo_id, public_id=reopened)++ calls: list[int] = []+ hydrate = service.hydrate_recommendations++ async def counting(*args, **kwargs):+ calls.append(1)+ return await hydrate(*args, **kwargs)++ monkeypatch.setattr(service, "hydrate_recommendations", counting)+ assert await _answers(client, repo_id) == expected+ assert calls+++async def test_one_plan_reads_its_stored_rank(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ repo_id = await _seed_ranked(client, app)+ listed = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]+ _no_live_ranking(monkeypatch)+ for plan in listed:+ detail = (await client.get(f"/api/repos/{repo_id}/refactoring/{plan['id']}")).json()+ assert detail == plan++ # Code generation reads its plan the same way.+ seen: list[dict] = []++ class _Generated:+ def __init__(self, suggestion) -> None:+ self.suggestion = suggestion++ def to_dict(self) -> dict:+ return {+ "refactoring_type": self.suggestion.refactoring_type,+ "file_path": self.suggestion.file_path,+ "target_symbol": self.suggestion.target_symbol,+ "content": "",+ "diff": "",+ "provider": "stub",+ "model": "stub",+ "cached": False,+ "input_tokens": 0,+ "output_tokens": 0,+ "validation": self.suggestion.validation,+ }++ async def enrich(suggestion, **_kwargs):+ seen.append(suggestion.validation)+ return _Generated(suggestion)++ monkeypatch.setattr(llm, "llm_enrichment_enabled", lambda _config: True)+ monkeypatch.setattr(llm, "build_enrichment_provider", lambda *_a, **_k: object())+ monkeypatch.setattr(llm, "enrich_suggestion", enrich)+ response = await client.post(f"/api/repos/{repo_id}/refactoring/{listed[0]['id']}/generate-code")+ assert response.status_code == 200, response.text+ assert seen == [listed[0]["validation"]]+++async def test_resolving_a_ranked_plan_drops_it_and_keeps_the_rest_in_order(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ repo_id = await _seed_ranked(client, app)+ before = (await client.get(f"/api/repos/{repo_id}/refactoring/targets/page")).json()["items"]+ gone = before[1]["id"]+ patched = await client.patch(+ f"/api/repos/{repo_id}/refactoring/{gone}/status", json={"status": "resolved"}+ )+ assert patched.status_code == 200+ _no_live_ranking(monkeypatch)+ after = (await client.get(f"/api/repos/{repo_id}/refactoring/targets/page")).json()+ assert [item["id"] for item in after["items"]] == [+ item["id"] for item in before if item["id"] != gone+ ]+ assert after["total"] == len(before) - 1+++async def test_search_matches_what_the_live_match_accepts(+ client: AsyncClient, app, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Words the SQL prefilter cannot judge (JSON-escaped, or beyond ASCII case+ folding) still find their plans, and LIKE wildcards are literal."""+ repo_id = await _seed(client, app)+ async with app.state.session_factory() as session:+ for symbol, strategy in (+ ("parse_a_b", "keep 100% of rows"),+ ("parse_axb", "keep 1000 rows"),+ ("Über_load", "inline the Übergabe step"),+ ):+ session.add(+ RefactoringSuggestion(+ **_refactoring_row_kwargs(+ {**_EXTRA[0], "target_symbol": symbol, "plan": {"strategy": strategy}},+ repo_id,+ )+ )+ )+ await session.flush()+ await crud.finalize_refactoring_opportunities(session, repo_id)+ await session.commit()++ async def found(word: str) -> list[str]:+ body = (+ await client.get(+ f"/api/repos/{repo_id}/refactoring/targets/page", params={"search": word}+ )+ ).json()+ return sorted(item["target_symbol"] for item in body["items"])++ with monkeypatch.context() as patch:+ _no_live_ranking(patch)+ stored = {word: await found(word) for word in ("a_b", "100%", "übergabe", "über_load")}+ assert stored == {+ "a_b": ["parse_a_b"],+ "100%": ["parse_a_b"],+ "übergabe": ["Über_load"],+ "über_load": ["Über_load"],+ }+ await _unrank(app, repo_id)+ assert {word: await found(word) for word in stored} == stored+++async def test_finalize_ranks_only_live_plans(client: AsyncClient, app) -> None:+ repo_id = await _seed_ranked(client, app)+ async with app.state.session_factory() as session:+ await crud.update_refactoring_suggestion_status(+ session, repo_id, (await _ids(session, repo_id))[0], "resolved"+ )+ await crud.finalize_refactoring_opportunities(session, repo_id)+ await session.commit()+ rows = (+ await session.execute(+ select(RefactoringSuggestion).where(RefactoringSuggestion.repository_id == repo_id)+ )+ ).scalars()+ ranked: dict[str, list[int | None]] = {}+ for row in rows:+ ranked.setdefault(row.status, []).append(row.rank_position)+ assert ranked["resolved"] == [None]+ live = ranked["open"] + ranked["acknowledged"]+ assert sorted(live) == list(range(len(live)))+++async def _ids(session, repo_id: str) -> list[str]:+ return list(+ (+ await session.execute(+ select(RefactoringSuggestion.id)+ .where(RefactoringSuggestion.repository_id == repo_id)+ .order_by(RefactoringSuggestion.file_path, RefactoringSuggestion.target_symbol)+ )+ ).scalars()+ )diff --git a/tests/unit/server/test_refactoring_summary_golden.py b/tests/unit/server/test_refactoring_summary_golden.pyindex 7d9d9e629..a85b4282a 100644--- a/tests/unit/server/test_refactoring_summary_golden.py+++ b/tests/unit/server/test_refactoring_summary_golden.py@@ -8,7 +8,9 @@ from __future__ import annotationsfrom types import SimpleNamespace-from repowise.server.routers import refactoring+from repowise.core.analysis.health.refactoring.recommendations import plan_types+from repowise.core.analysis.health.refactoring_summary import summarize_plans+from repowise.server.routers.refactoring import RefactoringSummarydef _rec(kind: str, path: str, effort: str, impact: float) -> SimpleNamespace:@@ -31,8 +33,12 @@ _RECS = []+def _summary(recs: list[SimpleNamespace]) -> RefactoringSummary:+ return RefactoringSummary(**summarize_plans(item.suggestion for item in recs))++def test_summary_counts_and_threshold_edges() -> None:- assert refactoring._summary(_RECS).model_dump() == {+ assert _summary(_RECS).model_dump() == {"total": 8,"by_type": [{"type": "extract_method", "count": 2},@@ -55,7 +61,7 @@ def test_summary_counts_and_threshold_edges() -> None:def test_summary_of_nothing() -> None:- assert refactoring._summary([]).model_dump() == {+ assert _summary([]).model_dump() == {"total": 0,"by_type": [],"files_total": 0,@@ -71,7 +77,7 @@ def test_summary_of_nothing() -> None:def test_structural_lens() -> None:# break_cycle is advisory: evidence on an opportunity, never a structural lead.- assert set(refactoring._STRUCTURAL_TYPES) == {+ assert set(plan_types("structural")) == {"split_file","extract_class","move_method",