Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(mcp): page fix_first and serve refactoring plans from the queue (#3255)
Raghav Chamadiya702f656a5f4b
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 1a140428d..df4b50a31 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -323,14 +323,14 @@ Code-health scores and findings from the stored analysis, across defect risk, ma|-----------|------|---------|---------|| `targets` | list[string] | none (dashboard) | File paths or `module:<name>`. Misses are named in `unresolved` || `include` | list[string] | none | Blocks: `biomarkers`, `refactoring`, `trend`, `coverage`, `accuracy`, `signals`, `churn_complexity`, `doc_drift`, `semantics`, `unverified`. Dimension filters: `performance`, `defect`, `maintainability`, `advisory` |-| `only` | list[string] | none | Keep just these top-level keys; identity, totals and recovery fields always survive |-| `limit` | int | `20` | Max rows in every ranked list, capped at 50; `0` for none |-| `cursor` | int | `0` | Offset into a ranked list; the `recovery` block names the next call |+| `only` | list[string] | none | Keep just these top-level keys; identity, totals and recovery fields always survive. An unknown key is named in `unknown_only_keys` with `unknown_only_keys_hint` |+| `limit` | int | `20` | Max rows in every ranked list, capped at 50; `0` for none. `fix_first` shows five unless `limit` is passed with `only=["fix_first"]`, which pages up to 25; `refactoring_plans` up to 25 |+| `cursor` | int | `0` | Offset into a ranked list (and into `fix_first` when named in `only`); the `recovery` block names the next call || `fix_id` | string | none | Open one `fix_first` item in full || `finding_id`, `plan_id` | string | none | Open one finding or refactoring plan by id || `opportunity_id` | string | none | Open one opportunity: `perf...` for performance, `refop...` for a refactoring || `refactoring_view` | string | `"diversified"` | `diversified`, `canonical` or `file_spread` |-| `refactoring_scope` | string | `fix_first` without targets, `all` with | Which open refactoring opportunities to list |+| `refactoring_scope` | string | `fix_first` without targets, `all` with | Which open refactoring opportunities, and their plans, to list || `refactoring_type`, `refactoring_confidence`, `refactoring_effort` | string | none | Refactoring queue filters || `performance_view` | string | `detail` | `detail` or `summary` || `performance_context` | string | `production` | `production`, `tooling`, `test`, `unknown` or `all` |@@ -341,13 +341,15 @@ Code-health scores and findings from the stored analysis, across defect risk, maOnly one of `fix_id`, `finding_id`, `plan_id`, `opportunity_id` per call; passing two returns `mode: "conflict"`.-**Key return fields:** `mode`, `fix_first` (`lead`, up to five `items` each with a `next_call`, `totals`), `kpis`, `gap_analysis`, `worst_files`, `high_leverage_files` (ranked by `weighted_deficit`), `top_findings`, `unresolved`, and the opt-in blocks you named. `_meta.health_analysis` says whether stored analysis exists and which commit it describes.+**Key return fields:** `mode`, `fix_first` (`lead` with its `next_call`, up to five `items`, `counts`, `totals`), `kpis`, `gap_analysis`, `worst_files`, `high_leverage_files` (ranked by `weighted_deficit`), `top_findings`, `unresolved`, and the opt-in blocks you named. `_meta.health_analysis` says whether stored analysis exists and which commit it describes.The response is bounded. Pair `include` with `only` to keep one block, e.g. `get_health(include=["refactoring"], only=["refactoring_opportunities"])`.```-get_health(only=["fix_first"])+get_health(only=["fix_first"], limit=25)+get_health(only=["fix_first"], limit=25, cursor=25)get_health(fix_id="fix1_...")+get_health(include=["refactoring"], only=["refactoring_plans"], limit=15, refactoring_scope="all")get_health(targets=["src/api/server.py"], include=["signals"])get_health(include=["performance"], only=["performance_summary"])get_health(include=["coverage"], only=["coverage"])diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 32a966cd3..b6c224d14 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -107,7 +107,7 @@ The key is absent when every argument was understood. One entry per argument.## Next-call shape-Every suggested follow-up (`get_health`'s `fix_first[].next_call`, the refactoring and performance summaries' `next_call`, `get_risk`'s `directive.next_calls`) has one shape:+Every suggested follow-up (`get_health`'s `fix_first.lead.next_call`, the refactoring and performance summaries' `next_call`, `get_risk`'s `directive.next_calls`) has one shape:| Field | Meaning ||-------|---------|@@ -325,8 +325,10 @@ One ranked queue across refactoring, performance and code-shape work, the same o| Field | Meaning ||-------|---------|-| `lead` | Equal to `items[0]` |-| `items` | Up to five: `id`, `tier`, `kind`, `title`, `target`, `why`, `gain`, `effort`, `confidence`, `next_call` |+| `lead` | The queue's first item, whatever page `items` is, with its `next_call` |+| `items` | Up to five. With `only=["fix_first"]` the list pages from `cursor` and `recovery.fix_first` names the next page; a passed `limit` sets the page size, up to 25. Each: `id`, `tier`, `kind`, `title`, `target`, `why`, `gain`, `effort`, `confidence`; `get_health(fix_id=...)` returns one in full, with its `next_call` |+| `items_total`, `cursor` | The eligible items `items` was cut from, and where the page starts |+| `counts` | `inventory` (every unit considered), `in_scope` (less units excluded for where the code lives: `test`, `tooling`, `generated`, `vendored`, `docs_example`), `eligible` (became an item), `due` (eligible items in tier `now` or `next`), `shown` (items in this response), `excluded` (every non-zero exclusion, by reason) || `tier` | `now` (worth doing, safe to start), `next` (worth doing, needs judgment), `later` || `kind` | `refactor` (one file's composed refactoring), `perf_fix` (one intervention with its sinks), `finding` (a code-shape finding with no plan) || `totals` | `candidates`, `eligible`, `shown`, `excluded` counted by reason (`gated_off`: a constant flag in the same file switches the function off; `unreachable`: sure dead code, delete it), and `dormant`: distinct functions kept out as `gated_off` |@@ -365,7 +367,7 @@ Provisional finding types appear only with `include=["unverified"]`, each marked| `semantics` | `_meta.health_semantics`: the legend for deficit points and percentiles || `performance`, `defect`, `maintainability`, `advisory` | Filter findings to one dimension; `performance` also adds the performance queue |-`only` aliases: `biomarkers` -> `findings`, `accuracy` -> `defect_accuracy`, `refactoring` -> `refactoring_plans`. Dimension names have no single key and land in `unknown_only_keys`; for `signals` in targeted mode, name `metrics`.+`only` aliases: `biomarkers` -> `findings`, `accuracy` -> `defect_accuracy`, `refactoring` -> `refactoring_plans`. Dimension names have no single key and land in `unknown_only_keys`, beside `unknown_only_keys_hint`; for `signals` in targeted mode, name `metrics`.### Refactoring@@ -373,7 +375,7 @@ Provisional finding types appear only with `include=["unverified"]`, each marked`get_health(opportunity_id="refop...")` returns full steps, member plans, the validation profile and `next_actions`; `only=["refactoring_evidence"]` with `cursor` pages the evidence. `found` says whether the id matched; `status` is `open`, `acknowledged`, `resolved` or `false_positive`. `refactoring_summary` rolls up by type, effort, confidence and lifecycle.-`refactoring_plans` is the raw per-detector list, returned only when named in `only`: `extract_class` (cohesion `groups`), `extract_helper` (clone `occurrences`, `suggested_site`), `move_method`, `break_cycle` (`cut_edges`). Each carries `evidence`, `impact_delta`, `effort_bucket`, `blast_radius`, `file_weighted_deficit` and an `id` for `generate_refactoring_code`. An empty requested list has `refactoring_plans_status.reason`: `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`. See [REFACTORING.md](../layers/REFACTORING.md).+`refactoring_plans`, returned only when named in `only`, lists the plans of the refactoring queue in queue order: each opportunity's steps together, in step order, under the same `refactoring_scope`, filters and view as `refactoring_opportunities`, up to 25 per page. A row is compact: `id` (for `plan_id` and `generate_refactoring_code`), `refactoring_type`, `file_path`, `target_symbol`, `line_start`, `line_end`, `effort_bucket`, `confidence`, `impact_delta`, `source_biomarker`, `opportunity_id`, `classification` (`mechanical` or `judgment`) and `relocated_by` when set; `get_health(plan_id=...)` returns the plan in full (detector detail such as cohesion `groups` or `cut_edges`, `evidence`, `blast_radius`, validation). `refactoring_plans_total` counts plans in scope, `refactoring_plans_opportunities_total` the opportunities they are steps of, `refactoring_plans_scope` names the scope and `refactoring_plans_hidden` counts what the `fix_first` scope leaves out, by reason. Performance plans are listed by `performance_opportunities`. An empty requested list has `refactoring_plans_status.reason`: `no_applicable_findings`, `plan_analysis_indeterminate`, `no_eligible_targets` or `analysis_unavailable`. See [REFACTORING.md](../layers/REFACTORING.md).### Performancediff --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 cfbe532e4..7d93942a7 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@@ -63,6 +63,13 @@ FixExclusion = Literal[]FIX_EXCLUSIONS: tuple[str, ...] = get_args(FixExclusion)+#: Exclusions that say where the code lives, not whether the work is worth+#: doing: a unit excluded for one of these was never in scope.+SCOPE_EXCLUSIONS = frozenset({"test", "tooling", "generated", "vendored", "docs_example"})++#: Tiers a unit is due in: worth scheduling now, not just worth listing.+DUE_TIERS = frozenset({"now", "next"})+FixScope = Literal["production", "all"]FIX_SCOPES: tuple[str, ...] = get_args(FixScope)@@ -257,8 +264,28 @@ class FixFirstQueue:"basis": dict(self.basis),}+ def counts(self, shown: int) -> dict[str, Any]:+ """The five-level count vocabulary, on the full queue (``limit=None``).++ ``inventory`` every unit the builder considered; ``in_scope`` those not+ excluded by :data:`SCOPE_EXCLUSIONS`; ``eligible`` those that became an+ item; ``due`` eligible items in a :data:`DUE_TIERS` tier; ``shown`` what+ the caller emits; ``excluded`` every non-zero exclusion, by reason.+ """+ excluded = {reason: n for reason, n in self.totals.excluded.items() if n}+ out_of_scope = sum(n for reason, n in excluded.items() if reason in SCOPE_EXCLUSIONS)+ return {+ "inventory": self.totals.candidates,+ "in_scope": self.totals.candidates - out_of_scope,+ "eligible": self.totals.eligible,+ "due": sum(1 for item in self.items if item.tier in DUE_TIERS),+ "shown": shown,+ "excluded": excluded,+ }+__all__ = [+ "DUE_TIERS","EFFORT_RANK","FIX_EFFORTS","FIX_EXCLUSIONS",@@ -271,6 +298,7 @@ __all__ = ["FIX_SCOPES","FIX_TIERS","LEVEL_RANK",+ "SCOPE_EXCLUSIONS","TIER_RANK","FixAction","FixConfidence",diff --git a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py b/packages/core/src/repowise/core/analysis/health/refactoring/serving.pyindex a299aa041..e91209ce2 100644--- a/packages/core/src/repowise/core/analysis/health/refactoring/serving.py+++ b/packages/core/src/repowise/core/analysis/health/refactoring/serving.py@@ -13,7 +13,7 @@ from __future__ import annotationsfrom collections.abc import Iterable, Mapping, Sequencefrom dataclasses import dataclass-from typing import Any, Literal+from typing import Anyfrom repowise.core.analysis.health.queue_rules import FilterRulefrom repowise.core.analysis.health.rows import detail_map, field@@ -38,10 +38,6 @@ _VIEW_ORDERS: dict[str, str] = {CANONICAL_VIEWS = tuple(_VIEW_ORDERS)DEFAULT_VIEW = "diversified"-# The legacy plan list has no notion of the diversified order, so the new-# default resolves to the value that list has always defaulted to.-_PLAN_VIEWS = {"canonical": "canonical", "file_spread": "file_spread", "diversified": "canonical"}-# Which open opportunities a queue lists:## - ``fix_first`` the default for a repository-wide open queue: only the@@ -304,11 +300,6 @@ def parse_query()-def plan_view(view: str | None) -> Literal["canonical", "file_spread"]:- """The legacy plan list's view for a caller's ``refactoring_view``."""- return _PLAN_VIEWS.get(view or DEFAULT_VIEW, "canonical") # type: ignore[return-value]--# ---------------------------------------------------------------------------# Shapes# ---------------------------------------------------------------------------@@ -574,7 +565,6 @@ __all__ = ["next_actions","parse_query","plan_payload",- "plan_view","row_sort_key","serialize","stored_validation",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 5a007d89d..01c30f249 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@@ -551,7 +551,7 @@ async def load_fix_first(if full is None:full = await _build(session, repository_id, limit=None, scope=scope, item_id=None)_remember((*base, None, None), full)- queue = full if key[-2:] == (None, None) else _view(full, limit=limit, item_id=item_id)+ queue = full if key[-2:] == (None, None) else queue_view(full, limit=limit, item_id=item_id)_remember(key, queue)return queue@@ -569,13 +569,17 @@ def _remember(key: tuple[Any, ...], queue: FixFirstQueue) -> None:_cache.popitem(last=False)-def _view(full: FixFirstQueue, *, limit: int | None, item_id: str | None) -> FixFirstQueue:+def queue_view(+ full: FixFirstQueue, *, limit: int | None, offset: int = 0, item_id: str | None = None+) -> FixFirstQueue:"""What ``build_fix_first`` returns for this limit or id, from the full- queue: the same items at the same ranks, ``shown`` recounted."""+ queue: the same items at the same ranks, ``shown`` recounted. ``offset``+ skips that many items, for a page past the first."""if item_id is not None:items = tuple(i for i in full.items if i.id == item_id)else:- items = full.items if limit is None else full.items[: max(limit, 0)]+ start = max(offset, 0)+ items = full.items[start:] if limit is None else full.items[start : start + max(limit, 0)]return replace(full, items=items, totals=replace(full.totals, shown=len(items)))@@ -617,4 +621,4 @@ async def _build()-__all__ = ["CACHE_SIZE", "FINDING_FILES", "clear_fix_first_cache", "load_fix_first"]+__all__ = ["CACHE_SIZE", "FINDING_FILES", "clear_fix_first_cache", "load_fix_first", "queue_view"]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 c44b187af..7b0dfa30b 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@@ -631,6 +631,37 @@ async def list_refactoring_opportunities(return rows, total+async def refactoring_step_counts(+ session: AsyncSession,+ repository_id: str,+ *,+ order: str | None = None,+ **filters: Any,+) -> list[tuple[str, int]]:+ """Each matching opportunity's id and step count, in *order*: one narrow read,+ so a page of plans is located without decoding any details."""+ rows = await session.execute(+ select(RefactoringOpportunity.opportunity_id, RefactoringOpportunity.step_count)+ .where(*_opportunity_filters(repository_id, **filters))+ .order_by(*_order_by(order))+ )+ return [(opportunity_id, int(steps or 0)) for opportunity_id, steps in rows.all()]+++async def refactoring_opportunities_by_id(+ session: AsyncSession, repository_id: str, opportunity_ids: list[str], *, status: str = "open"+) -> dict[str, RefactoringOpportunity]:+ """The named current-model rows in *status*, by id: one read, no count."""+ if not opportunity_ids:+ return {}+ rows = await session.execute(+ select(RefactoringOpportunity).where(+ *_opportunity_filters(repository_id, status=status, opportunity_ids=opportunity_ids)+ )+ )+ return {row.opportunity_id: row for row in rows.scalars().all()}++async def refactoring_opportunity_ids(session: AsyncSession,repository_id: str,@@ -793,6 +824,8 @@ __all__ = ["get_refactoring_summary","list_refactoring_opportunities","refactoring_facet_counts",+ "refactoring_opportunities_by_id","refactoring_opportunity_ids",+ "refactoring_step_counts","update_refactoring_opportunity_status",]diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex 3fe4fbbbc..68fa560d0 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -323,11 +323,14 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {"performance_summary","high_leverage_files[]","secondary_rankings",+ # A named page holds up to 25 items; its tail goes last of all.+ "fix_first.items[]",),protected=("mode",- # The one lead, bounded by construction (at most five compact- # items): shedding it would leave the dashboard with nothing to do.+ # The one lead: shedding the block would leave the dashboard with+ # nothing to do. Bounded by construction (five compact items, or+ # one named page), and only its page's tail is ever trimmed."fix_first","fix_id","opportunity_id",@@ -780,6 +783,21 @@ def _emergency_fit(return+def _call_arguments(+ signature: inspect.Signature, args: tuple[Any, ...], kwargs: dict[str, Any]+) -> dict[str, Any] | None:+ """The call's arguments with defaults applied; ``None`` when the signature+ is not the tool's own (a bridged call budgets with an empty one)."""+ if not signature.parameters:+ return None+ try:+ bound = signature.bind_partial(*args, **kwargs)+ except TypeError:+ return None+ bound.apply_defaults()+ return dict(bound.arguments)++def _lead_with_dropped_targets(tool: str,result: dict[str, Any],@@ -886,7 +904,7 @@ def enforce_response_budget(emergency.attach(result)trimmed = True- run_post_enforce(tool, result)+ run_post_enforce(tool, result, _call_arguments(signature, args, kwargs))if result.get("truncated"):result.setdefault("_meta", {}).setdefault("state", {})["truncated"] = Truediff --git a/packages/server/src/repowise/server/mcp_server/_budget/hooks.py b/packages/server/src/repowise/server/mcp_server/_budget/hooks.pyindex ef70e9cd8..02b45fb30 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/hooks.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/hooks.py@@ -12,12 +12,13 @@ may route what it drops into recovery. Only the ``blocks`` strategy has thatwindow; the ``targets`` strategy attaches inside :func:`truncate_to_budget`.``post_enforce`` runs on the settled shape, after the final size check, for-claims about what was delivered.+claims about what was delivered. A hook registered ``with_call`` also gets the+call's arguments, defaults applied, so it can restate a follow-up call."""from __future__ import annotations-from collections.abc import Callable+from collections.abc import Callable, Mappingfrom typing import TYPE_CHECKING, Anyif TYPE_CHECKING:@@ -28,6 +29,8 @@ PostEnforceHook = Callable[[dict[str, Any]], None]_POST_SHED: dict[str, list[PostShedHook]] = {}_POST_ENFORCE: dict[str, list[PostEnforceHook]] = {}+#: Post-enforce hooks that take the call's arguments as a second argument.+_WITH_CALL: set[Any] = set()def register_post_shed(tool: str, hook: PostShedHook) -> None:@@ -35,9 +38,11 @@ def register_post_shed(tool: str, hook: PostShedHook) -> None:_register(_POST_SHED, tool, hook)-def register_post_enforce(tool: str, hook: PostEnforceHook) -> None:+def register_post_enforce(tool: str, hook: Any, *, with_call: bool = False) -> None:"""Register *hook* to run for *tool* once the delivered shape is settled."""_register(_POST_ENFORCE, tool, hook)+ if with_call:+ _WITH_CALL.add(hook)def _register(registry: dict[str, list[Any]], tool: str, hook: Any) -> None:@@ -54,10 +59,16 @@ def run_post_shed(tool: str, result: dict[str, Any], collector: OmissionCollectohook(result, collector)-def run_post_enforce(tool: str, result: dict[str, Any]) -> None:- """Run *tool*'s post-enforce hooks, in registration order."""+def run_post_enforce(+ tool: str, result: dict[str, Any], call: Mapping[str, Any] | None = None+) -> None:+ """Run *tool*'s post-enforce hooks, in registration order. A ``with_call``+ hook is skipped when the call's arguments are unknown."""for hook in _POST_ENFORCE.get(tool, ()):- hook(result)+ if hook not in _WITH_CALL:+ hook(result)+ elif call is not None:+ hook(result, call)def registered_hook_tools() -> frozenset[str]:diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/__init__.py b/packages/server/src/repowise/server/mcp_server/tool_health/__init__.pyindex e643908e9..11444aed6 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/__init__.py@@ -9,7 +9,6 @@ from __future__ import annotationsfrom repowise.core.analysis.health.aggregation import module_rollups as _module_rollupsfrom repowise.server.mcp_server.tool_health.coverage import _attach_coverage_decay-from repowise.server.mcp_server.tool_health.plans import _validation_profilefrom repowise.server.mcp_server.tool_health.serialize import (_health_finding_id,_perf_rank,@@ -28,6 +27,5 @@ __all__ = ["_rank_emitted","_refactoring_plan_id","_serialize_refactoring",- "_validation_profile","get_health",]diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.pyindex c9856569e..988c6d301 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/dashboard.py@@ -41,7 +41,7 @@ def build_dashboard()result: dict[str, Any] = {# The one lead; every block below ranks and describes.- **({"fix_first": _fix_first_block(data)} if data.fix_first is not None else {}),+ **({"fix_first": _fix_first_block(data, req, pager)} if data.fix_first is not None else {}),"mode": "dashboard","scope": pop.reported_scope,"counts": pop.reported_counts,@@ -104,12 +104,33 @@ def build_dashboard(return result, ModeTotals(metrics=None, trends=None, modules=len(all_modules))-def _fix_first_block(data: HealthData) -> dict[str, Any]:- """Core's queue in the compact projection, with the call for one full item."""- queue = data.fix_first- block = queue.as_dict(compact=True)- if queue.lead is not None:- block["detail_call"] = f"get_health(fix_id={queue.lead.id!r})"+def _fix_first_block(data: HealthData, req: HealthRequest, pager: Pager) -> dict[str, Any]:+ """Core's queue in the compact projection, its counts, and the call for one full item.++ ``lead`` is the queue's first item, whatever page ``items`` is;+ ``items_total`` is the eligible queue the items were cut from, starting at+ ``cursor``. Only the lead carries ``next_call``: it is the bulk of a compact+ item, every item's is one ``fix_id`` call away, and without it a named page+ of 25 fits the default budget.+ """+ page, full = data.fix_first, data.fix_first_full+ block = page.as_dict(compact=True)+ for item in block["items"]:+ item.pop("next_call", None)+ block["lead"] = full.lead.compact() if full.lead is not None else None+ block["counts"] = full.counts(shown=len(page.items))+ block["items_total"] = full.totals.eligible+ block["cursor"] = req.fix_first_cursor+ if full.lead is not None:+ block["detail_call"] = f"get_health(fix_id={full.lead.id!r})"+ if req.pages_fix_first:+ pager.note_page(+ "fix_first",+ start=req.fix_first_cursor,+ shown=len(page.items),+ total=full.totals.eligible,+ limit=req.fix_first_cap,+ )return blockdiff --git a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py b/packages/server/src/repowise/server/mcp_server/tool_health/loading.pyindex c2b517186..b718573cc 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/loading.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/loading.py@@ -19,12 +19,7 @@ from repowise.core.analysis.health.fix_first import FixFirstQueuefrom repowise.core.analysis.health.grading import TARGET_SCOREfrom repowise.core.analysis.health.perf.coverage import PerfCoverage, coverage_for_metricsfrom repowise.core.analysis.health.ranking import deduction_by_path, sort_metrics_worst_first-from repowise.core.analysis.health.refactoring.recommendations import (- Recommendation,- detail_recommendations,- hydrate_recommendations,-)-from repowise.core.analysis.health.refactoring.serving import plan_view+from repowise.core.analysis.health.refactoring.serving import parse_query as parse_refactoring_queryfrom repowise.core.analysis.health.signals import file_signalsfrom repowise.core.analysis.health.trends import project_scopefrom repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES@@ -36,13 +31,12 @@ from repowise.core.persistence.crud import (get_git_metadata_bulk,get_hotspot_file_paths,get_node_degree_counts_bulk,- get_refactoring_suggestions,get_test_file_paths,list_health_snapshots,load_coverage_for_repo,load_coverage_history,)-from repowise.core.persistence.crud.analysis.fix_first import load_fix_first+from repowise.core.persistence.crud.analysis.fix_first import load_fix_first, queue_viewfrom repowise.core.persistence.models import HealthFileMetricfrom repowise.server.mcp_server._helpers import filter_rows_by_attrfrom repowise.server.mcp_server.tool_health.findings import (@@ -61,11 +55,10 @@ from repowise.server.mcp_server.tool_health.population import Population, load_pfrom repowise.server.mcp_server.tool_health.request import HealthRequestfrom repowise.server.mcp_server.tool_health.summary import _leads_by_filefrom repowise.server.services.performance_health import PerformanceHealthService-from repowise.server.services.refactoring_health import RefactoringHealthService--FIX_FIRST_CAP = 5-"""Items in the dashboard's ``fix_first`` block, however large ``limit`` is.-The rest are one ``get_health(fix_id=...)`` or REST page away."""+from repowise.server.services.refactoring_health import (+ RefactoringHealthService,+ RefactoringPlanPage,+)@dataclass@@ -87,8 +80,9 @@ class HealthData:perf_coverage: PerfCoverage | None = Noneperf_findings_count: int = 0accuracy_rows: list[Any] = field(default_factory=list)- refactoring_rows: list[Any] = field(default_factory=list)- refactoring_recommendations: list[Recommendation] = field(default_factory=list)+ #: The queue's plans, read only when ``refactoring_plans`` is named.+ refactoring_plans: RefactoringPlanPage | None = None+ refactoring_plans_ignored: dict[str, str] = field(default_factory=dict)coverage_rows: list[Any] = field(default_factory=list)coverage_summary: dict[str, Any] = field(default_factory=dict)coverage_history: list[dict[str, Any]] = field(default_factory=list)@@ -98,6 +92,8 @@ class HealthData:churn_points: list[dict[str, Any]] = field(default_factory=list)snapshots: list[Any] = field(default_factory=list)fix_first: FixFirstQueue | None = None+ #: The whole queue the page was cut from: its lead and its counts.+ fix_first_full: FixFirstQueue | None = None# Dashboard only: the worst-first test files, ranked apart from# ``metric_rows`` so a test never heads the production worklist.test_metric_rows: list[HealthFileMetric] = field(default_factory=list)@@ -150,8 +146,8 @@ async def load_health_data(session, repository, pop, req, findings.lead_rows)data.accuracy_rows = await read_accuracy_rows(session, repository, pop, req)- data.refactoring_rows, data.refactoring_recommendations = await _read_refactoring_plans(- session, repository, pop, req+ data.refactoring_plans, data.refactoring_plans_ignored = await _read_refactoring_plans(+ session, repository, reference_repository, pop, req)data.refactoring, data.performance = await _read_pillars(session, repository, reference_repository, pop, req@@ -168,7 +164,7 @@ async def load_health_data(data.by_leverage, data.leads = _rank_leverage_and_leads(pop, metric_rows, findings, req, data.test_metric_rows)- data.fix_first = await _read_fix_first(session, repository, pop, req)+ data.fix_first, data.fix_first_full = await _read_fix_first(session, repository, pop, req)return data@@ -220,37 +216,27 @@ async def _read_perf_headline(async def _read_refactoring_plans(- session: Any, repository: Any, pop: Population, req: HealthRequest-) -> tuple[list[Any], list[Recommendation]]:- """Plans scoped to the same targets, exclude-filtered like findings."""+ session: Any, repository: Any, reference_repository: str, pop: Population, req: HealthRequest+) -> tuple[RefactoringPlanPage | None, dict[str, str]]:+ """The queue's plans, scoped, filtered and ordered as the queue is.++ ``refactoring_scope`` resolves as on the opportunity queue: ``fix_first``+ for the repository, ``all`` once targets are named.+ """if not req.plans_requested or pop.nothing_resolved:- return [], []- rows = pop.in_scope_rows(- await get_refactoring_suggestions(- session,- repository.id,- file_paths=list(pop.effective_targets) if pop.scoped else None,- ),- "file_path",- )- recommendations = await hydrate_recommendations(- session,- repository.id,- rows,- metric_rows=pop.all_metrics,- view=plan_view(req.refactoring_view),- rank_only=True,- )- # Every row is ranked; only the page the response emits, and the lede's- # lead plan, need the evidence that orders their tests.- shown = {0, *range(req.cursor, req.cursor + req.plans_cap)}- indexes = [index for index in sorted(shown) if index < len(recommendations)]- detailed = await detail_recommendations(- session, repository.id, [recommendations[index] for index in indexes]+ return None, {}+ query, ignored = parse_refactoring_query(+ view=req.refactoring_view,+ lead_type=req.refactoring_type,+ confidence=req.refactoring_confidence,+ effort=req.refactoring_effort,+ scope=req.refactoring_scope,+ file_paths=pop.target_paths,+ limit=req.plans_cap,+ offset=req.cursor,)- for index, item in zip(indexes, detailed, strict=True):- recommendations[index] = item- return rows, recommendations+ service = RefactoringHealthService(session, repository.id, reference_repository)+ return await service.plan_page(query), ignoredasync def _read_pillars(@@ -433,12 +419,15 @@ def _rank_leverage_and_leads(async def _read_fix_first(session: Any, repository: Any, pop: Population, req: HealthRequest-) -> FixFirstQueue | None:- """The dashboard's one lead: the Fix-first queue core builds from stored rows.+) -> tuple[FixFirstQueue | None, FixFirstQueue | None]:+ """The dashboard's one lead: the Fix-first queue core builds from stored rows,+ as the page this call emits and the whole queue.Always the production population, whatever ``scope`` says: a test file is- never the first thing to fix.+ never the first thing to fix. The full queue is cached per store write, so+ the page and the whole queue cost one build."""if pop.scoped or not req.wants("fix_first"):- return None- return await load_fix_first(session, repository.id, limit=min(req.limit, FIX_FIRST_CAP))+ return None, None+ full = await load_fix_first(session, repository.id, limit=None)+ return queue_view(full, limit=req.fix_first_cap, offset=req.fix_first_cursor), fulldiff --git a/packages/server/src/repowise/server/mcp_server/tool_health/paging.py b/packages/server/src/repowise/server/mcp_server/tool_health/paging.pyindex b6071de65..9460fa464 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/paging.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/paging.py@@ -7,12 +7,12 @@ shared omission store.from __future__ import annotations+from collections.abc import Mapping+from dataclasses import fieldsfrom typing import Any-from repowise.core.analysis.health.refactoring.recommendations import Recommendation-from repowise.server.mcp_server._budget import OmissionCollector-from repowise.server.mcp_server.tool_health.request import HealthRequest-from repowise.server.mcp_server.tool_health.serialize import _serialize_refactoring+from repowise.server.mcp_server._budget import OmissionCollector, register_post_enforce+from repowise.server.mcp_server.tool_health.request import PLANS_PAGE_CAP, HealthRequest_PAGED_COLLECTIONS = frozenset({@@ -37,11 +37,12 @@ _PAGED_COLLECTIONS = frozenset()# The queues page six at a time whatever ``limit`` says; see the pillar caps.-_QUEUE_COLLECTIONS = frozenset(- {"refactoring_plans", "refactoring_opportunities", "performance_opportunities"}-)+_QUEUE_COLLECTIONS = frozenset({"refactoring_opportunities", "performance_opportunities"})_QUEUE_PAGE = 6+#: A collection's fixed page, for naming a cut below ``limit`` a cap.+_COLLECTION_CAPS = {"refactoring_plans": PLANS_PAGE_CAP, "performance_opportunities": _QUEUE_PAGE}+class Pager:"""Bounds every emitted collection of one response and records the remainder."""@@ -82,6 +83,12 @@ class Pager:# leaving the caller with nothing to call.self.recoveries[label] = (0, min(len(rows), max(row_cap, 1), 50), len(rows))+ def note_page(self, label: str, *, start: int, shown: int, total: int, limit: int) -> None:+ """A page of ``total`` rows from ``start`` that holds ``shown``: the next+ page's recovery, when there is one."""+ if limit and start + shown < total:+ self.recoveries[label] = (start + shown, max(shown, 1), total - start - shown)+def recovery_block(self, result: dict[str, Any], req: HealthRequest) -> dict[str, dict[str, Any]] | None:@@ -93,30 +100,99 @@ class Pager:continuerecovery[label] = {"remaining": remaining,- "call": (- f"get_health(targets={req.raw_targets!r}, include={list(req.include or [])!r}, "- f"repo={req.repo!r}, limit={next_limit}, only={[root]!r}, "- f"refactoring_view='{req.refactoring_view}', cursor={next_cursor})"- ),+ "call": call_for(req, root, limit=next_limit, cursor=next_cursor),}return recovery or None- def report_omissions(- self, result: dict[str, Any], collector: OmissionCollector, reference_repository: str- ) -> None:+ def report_omissions(self, result: dict[str, Any], collector: OmissionCollector) -> None:"""Hand every dropped tail whose block survived to the omission store."""for label, dropped in self.omissions.items():root = label.split(".", 1)[0]if root in result:collector.add(f"{label} beyond emitted cap ({len(dropped)} dropped)",- [_omitted_row(row, reference_repository) for row in dropped],+ [_omitted_row(row) for row in dropped],)-def _omitted_row(row: Any, reference_repository: str) -> Any:- if isinstance(row, Recommendation):- return _serialize_refactoring(row, reference_repository)+#: Every queue argument the request takes except the view, which every call names.+_QUEUE_FILTERS = tuple(+ f.name+ for f in fields(HealthRequest)+ if f.init+ and f.name.startswith(("refactoring_", "performance_"))+ and f.name != "refactoring_view"+)+++def call_for(req: HealthRequest, root: str, *, limit: int, cursor: int) -> str:+ """The call that reads ``root`` again from ``cursor``, under the same+ arguments and queue filters, so the next page reads the same queue."""+ filters = "".join(+ f", {name}={value!r}" for name in _QUEUE_FILTERS if (value := getattr(req, name)) is not None+ )+ return (+ f"get_health(targets={req.raw_targets!r}, include={list(req.include or [])!r}, "+ f"repo={req.repo!r}, limit={limit}, only={[root]!r}, "+ f"refactoring_view='{req.refactoring_view}'{filters}, cursor={cursor})"+ )+++def _settle_pages(result: dict[str, Any], call: Mapping[str, Any]) -> None:+ """Restate each named page from what the response budget delivered.++ A page's next cursor is set before the budget runs; a trimmed tail would+ otherwise be skipped by the next call, and ``counts.shown`` would count+ rows that never arrived.+ """+ names = [f.name for f in fields(HealthRequest) if f.init]+ if any(name not in call for name in names):+ return # not get_health's own signature: nothing to restate the call from+ req = HealthRequest(**{name: call[name] for name in names})+ pager = Pager(req.limit, req.cursor)+ block = result.get("fix_first")+ if isinstance(block, dict) and isinstance(block.get("items"), list):+ shown = len(block["items"])+ if isinstance(block.get("counts"), dict):+ block["counts"]["shown"] = shown+ if req.pages_fix_first:+ total = int(block.get("items_total") or 0)+ pager.note_page(+ "fix_first",+ start=req.fix_first_cursor,+ shown=shown,+ total=total,+ limit=req.fix_first_cap,+ )+ _restate(result, pager, req, "fix_first")+ plans = result.get("refactoring_plans")+ if isinstance(plans, list) and "refactoring_plans_total" in result:+ total = int(result["refactoring_plans_total"] or 0)+ pager.note_page(+ "refactoring_plans",+ start=req.cursor,+ shown=len(plans),+ total=total,+ limit=req.plans_cap,+ )+ _restate(result, pager, req, "refactoring_plans")+++def _restate(result: dict[str, Any], pager: Pager, req: HealthRequest, label: str) -> None:+ """Replace ``label``'s recovery with the one ``pager`` holds, or drop it."""+ recovery = {key: value for key, value in (result.get("recovery") or {}).items() if key != label}+ if label in pager.recoveries:+ recovery[label] = (pager.recovery_block(result, req) or {})[label]+ if recovery:+ result["recovery"] = recovery+ else:+ result.pop("recovery", None)+++register_post_enforce("get_health", _settle_pages, with_call=True)+++def _omitted_row(row: Any) -> Any:return row.as_dict() if hasattr(row, "as_dict") else row@@ -127,11 +203,10 @@ def _stamp_collection_totals(for key, total in totals.items():if total is None:continue+ cap = _COLLECTION_CAPS.get(key)cap_reason = ("collection_cap"- if key in {"refactoring_plans", "performance_opportunities"}- and limit > _QUEUE_PAGE- and len(result.get(key, [])) == _QUEUE_PAGE+ if cap is not None and limit > cap and len(result.get(key, [])) == capelse "limit")_stamp_collection(result, key, total=total, reason=cap_reason)diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py b/packages/server/src/repowise/server/mcp_server/tool_health/plans.pyindex b51998d32..2132a5dfd 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/plans.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/plans.py@@ -1,19 +1,13 @@-"""Refactoring-plan projection for get_health: validation profiles and plan status."""+"""Refactoring-plan projection for get_health: the queue's plans and plan status."""from __future__ import annotations-import hashlib-import jsonfrom typing import TYPE_CHECKING, Any-from repowise.server.mcp_server._budget import (- OmissionCollector,- register_post_enforce,- register_post_shed,-)-from repowise.server.mcp_server.tool_health.paging import Pager, _stamp_collection+from repowise.server.mcp_server._budget import register_post_enforce+from repowise.server.mcp_server.tool_health.paging import Pager+from repowise.server.mcp_server.tool_health.pillars import _merge_ignoredfrom repowise.server.mcp_server.tool_health.request import HealthRequest-from repowise.server.mcp_server.tool_health.serialize import _serialize_refactoringif TYPE_CHECKING:from repowise.server.mcp_server.tool_health.loading import HealthData@@ -22,39 +16,36 @@ if TYPE_CHECKING:def _render_plans(result: dict[str, Any], data: HealthData, req: HealthRequest, pager: Pager) -> None:- """The plan list, its shared validation profiles, and why it may be empty.+ """The queue's plans in queue order, one compact row each, and why the list may be empty.- Canonical is the shared REST/MCP/CLI order. File diversity remains- available only through the explicitly named ``file_spread`` view.+ ``refactoring_scope`` and the refactoring filters apply as on the queue;+ ``get_health(plan_id=...)`` returns one plan in full (detector detail,+ evidence, validation)."""- recommendations = data.refactoring_recommendations- validation_profiles: dict[str, dict[str, Any]] = {}- plan_payload = []- for recommendation in pager.bound(- recommendations, "refactoring_plans", cap=req.plans_cap- ):- payload = _serialize_refactoring(recommendation, data.reference_repository)- validation = payload.pop("validation", None)- if validation:- profile_id, profile = _validation_profile(validation)- validation_profiles.setdefault(profile_id, profile)- payload["validation_profile_id"] = profile_id- plan_payload.append(payload)- result["refactoring_plans"] = plan_payload- if validation_profiles:- result["validation_profiles"] = list(validation_profiles.values())- _stamp_collection(- result,- "validation_profiles",- total=len(validation_profiles),- reason="profile_cap",+ page = data.refactoring_plans+ rows = [_plan_row(item) for item in page.items] if page is not None else []+ total = page.total if page is not None else 0+ result["refactoring_plans"] = rows+ result["refactoring_plans_total"] = total+ if page is not None:+ result["refactoring_plans_scope"] = page.scope+ # The opportunities the plans are steps of: the queue's own count.+ result["refactoring_plans_opportunities_total"] = page.opportunities_total+ if page.hidden is not None:+ result["refactoring_plans_hidden"] = page.hidden+ pager.note_page(+ "refactoring_plans",+ start=req.cursor,+ shown=page.next_offset - req.cursor,+ total=total,+ limit=req.plans_cap,)- result["refactoring_plans_total"] = len(data.refactoring_rows)+ _merge_ignored(result, data.refactoring_plans_ignored)if req.wants("refactoring_plans"):scoped = data.pop.scopedresult["refactoring_plans_status"] = _refactoring_plans_status(- available_plans_total=len(recommendations),- plans_emitted=len(plan_payload),+ available_plans_total=total,+ plans_emitted=len(rows),scoped=scoped,has_eligible_metrics=bool(data.metric_rows if scoped else data.pop.all_metrics),finding=next(iter(data.findings.emitted), None),@@ -64,32 +55,28 @@ def _render_plans(# type as ``suggestion_legend``, not per finding: the text is keyed by type.-def _validation_profile(validation: dict[str, Any]) -> tuple[str, dict[str, Any]]:- """Deduplicate a plan's repeated tests, targets, and command material."""- encoded = json.dumps(validation, sort_keys=True, separators=(",", ":"), default=str)- profile_id = "validation_" + hashlib.sha256(encoded.encode()).hexdigest()[:16]- tests = list(validation.get("tests") or [])- targets = list(validation.get("targets") or [])- profile = {- key: value- for key, value in validation.items()- if key not in {"tests", "targets", "commands", "truncated"}- }- profile.update(- {- "id": profile_id,- "tests": tests,- "tests_total": int(validation.get("total") or len(tests)),- "tests_emitted": len(tests),- "targets": targets,- "commands": list(validation.get("commands") or []),- "commands_total": len(validation.get("commands") or []),- "commands_emitted": len(validation.get("commands") or []),- }- )- if profile["tests_emitted"] < profile["tests_total"]:- profile["tests_reduced_reason"] = "analysis_source_cap"- return profile_id, profile+_PLAN_ROW_FIELDS = (+ "refactoring_type",+ "file_path",+ "target_symbol",+ "line_start",+ "line_end",+ "effort_bucket",+ "confidence",+ "impact_delta",+ "source_biomarker",+ "opportunity_id",+)+++def _plan_row(step: dict[str, Any]) -> dict[str, Any]:+ """One stored step as a list row; the full plan is one ``plan_id`` call away."""+ row: dict[str, Any] = {"id": step.get("plan_id")}+ row.update((name, step.get(name)) for name in _PLAN_ROW_FIELDS)+ row["classification"] = (step.get("applicability") or {}).get("classification")+ if step.get("relocated_by"):+ row["relocated_by"] = step["relocated_by"]+ return rowdef _finding_next_action(finding: Any, repo: str | None) -> dict[str, Any]:@@ -160,37 +147,6 @@ def _refactoring_plans_status(}-def _prune_orphaned_validation_profiles(- result: dict[str, Any], collector: OmissionCollector-) -> None:- """Drop profiles whose plan the response budget removed.-- A profile left behind by its shed plan is an id that resolves to nothing.- """- plans = result.get("refactoring_plans")- profiles = result.get("validation_profiles")- if not isinstance(plans, list) or not isinstance(profiles, list):- return- referenced = {- plan.get("validation_profile_id")- for plan in plans- if isinstance(plan, dict) and plan.get("validation_profile_id")- }- kept = [- profile- for profile in profiles- if isinstance(profile, dict) and profile.get("id") in referenced- ]- dropped = [profile for profile in profiles if profile not in kept]- if not dropped:- return- collector.add("validation_profiles no longer referenced after response budgeting", dropped)- result["validation_profiles"] = kept- result["validation_profiles_emitted"] = len(kept)- result["validation_profiles_reduced_reason"] = "response_budget"- result["truncated"] = True--def _reconcile_plan_status(result: dict[str, Any]) -> None:"""Keep plan availability honest after the final budget mutates collections."""status = result.get("refactoring_plans_status")@@ -208,5 +164,4 @@ def _reconcile_plan_status(result: dict[str, Any]) -> None:)-register_post_shed("get_health", _prune_orphaned_validation_profiles)register_post_enforce("get_health", _reconcile_plan_status)diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/projection.py b/packages/server/src/repowise/server/mcp_server/tool_health/projection.pyindex f7f07f9f0..899a90c3f 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/projection.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/projection.py@@ -32,14 +32,15 @@ _ALWAYS_KEPT = frozenset(})+# The miss seen in practice is a dimension or pillar name passed as a key.+_UNKNOWN_ONLY_HINT = (+ "`only` names response keys, such as fix_first, top_findings, "+ "performance_opportunities or refactoring_plans; a dimension such as "+ "performance is an `include` value. See docs/agent/MCP_TOOLS.md."+)+_PLAN_COMPANIONS = frozenset(- {- "refactoring_plans_status",- "validation_profiles",- "validation_profiles_total",- "validation_profiles_emitted",- "validation_profiles_reduced_reason",- }+ {"refactoring_plans_status", "refactoring_plans_opportunities_total"})@@ -119,4 +120,5 @@ def _project(if unknown:result["unknown_only_keys"] = unknown_stamp_collection(result, "unknown_only_keys", total=len(unknown))+ result["unknown_only_keys_hint"] = _UNKNOWN_ONLY_HINTreturn resultdiff --git a/packages/server/src/repowise/server/mcp_server/tool_health/request.py b/packages/server/src/repowise/server/mcp_server/tool_health/request.pyindex e279a0064..08e095d67 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/request.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/request.py@@ -22,6 +22,22 @@ _ONLY_ALIASES = {"refactoring": "refactoring_plans",}+DEFAULT_LIMIT = 20+"""Rows per ranked list when the caller passes no ``limit``."""++PLANS_PAGE_CAP = 25+"""Refactoring plans one response emits; ``cursor`` pages on."""++FIX_FIRST_CAP = 5+"""Items in the bare dashboard's ``fix_first`` block, however large ``limit`` is.+The rest are one ``only=["fix_first"]`` page or ``get_health(fix_id=...)`` away."""++FIX_FIRST_PAGE_CAP = 25+"""Items one ``only=["fix_first"]`` page emits when ``limit`` is passed: up to+this, ``cursor`` for the next page. With no ``limit`` a page is+:data:`FIX_FIRST_CAP`, so the call costs what the dashboard block does. Measured at about 16k chars for 25 items on a large+repository, inside the default 24k budget; the budget trims the tail beyond."""+_RANKED_DIMENSIONS_DEFAULT = {"defect", "maintainability"}"""Dimensions the impact-ranked findings list carries when none is asked for."""@@ -59,7 +75,8 @@ class HealthRequest:include: list[str] | Noneonly: list[str] | Nonerepo: str | None- limit: int+ #: ``None`` when the caller passed none; resolved to :data:`DEFAULT_LIMIT`.+ limit: int | Nonecursor: intrefactoring_view: strrefactoring_type: str | None@@ -84,10 +101,13 @@ class HealthRequest:module_targets: list[str] = field(init=False)file_targets: list[str] = field(init=False)withheld_types: frozenset[str] = field(init=False)+ #: The caller passed ``limit``: a response grows past a default only when asked.+ limit_explicit: bool = field(init=False)def __post_init__(self) -> None:+ self.limit_explicit = self.limit is not None# ``0`` means totals and no rows, as on the REST coverage route.- self.limit = max(self.limit, 0)+ self.limit = max(DEFAULT_LIMIT if self.limit is None else self.limit, 0)self.cursor = max(self.cursor, 0)if self.refactoring_view not in _REFACTORING_VIEWS:self.refactoring_view = _REFACTORING_VIEW_DEFAULT@@ -116,8 +136,28 @@ class HealthRequest:@propertydef plans_cap(self) -> int:- """How many refactoring plans one response emits, whatever ``limit`` says."""- return min(self.limit, 6)+ """How many refactoring plans one response emits: ``limit``, up to+ :data:`PLANS_PAGE_CAP`. Plans are compact rows, so a full page fits the budget."""+ return min(self.limit, PLANS_PAGE_CAP)++ @property+ def pages_fix_first(self) -> bool:+ """``fix_first`` named in ``only``: the queue pages by ``limit`` and+ ``cursor`` instead of the bare dashboard's fixed head."""+ return "fix_first" in self.only_set++ @property+ def fix_first_cap(self) -> int:+ """Fix-first items this response emits: a named page takes ``limit`` up+ to :data:`FIX_FIRST_PAGE_CAP` when one was passed, else the dashboard's head."""+ if self.pages_fix_first and self.limit_explicit:+ return min(self.limit, FIX_FIRST_PAGE_CAP)+ return min(self.limit, FIX_FIRST_CAP)++ @property+ def fix_first_cursor(self) -> int:+ """Where the Fix-first page starts: the bare dashboard always leads."""+ return self.cursor if self.pages_fix_first else 0def wants(self, block: str) -> bool:"""True when ``block`` survives the ``only`` projection.diff --git a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py b/packages/server/src/repowise/server/mcp_server/tool_health/tool.pyindex eb8ee7ade..0eecf07a1 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health/tool.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health/tool.py@@ -125,7 +125,7 @@ async def get_health(targets: list[str] | None = None,include: list[str] | None = None,repo: str | None = None,- limit: int = 20,+ limit: int | None = None,only: list[str] | None = None,refactoring_view: str = _REFACTORING_VIEW_DEFAULT,refactoring_type: str | None = None,@@ -164,7 +164,7 @@ async def get_health(``performance``/``defect``/``maintainability``/``advisory``do not: they filter rows into ``unknown_only_keys``.repo: usually omitted.- limit: max rows per ranked list, ``0`` for none.+ limit: max rows per ranked list (default 20), ``0`` for none.cursor: zero-based offset into a ranked list.fix_id/finding_id/plan_id: stable ``id`` of an item, finding or plan.opportunity_id: ``perf...``/``refop...``: the unit, its steps or@@ -250,7 +250,7 @@ async def get_health(await _attach_repository_analysis_meta(session, repository, result["_meta"])else:_attach_health_analysis_meta(result["_meta"], data.pop.all_metrics)- pager.report_omissions(result, omission_collector, reference_repository)+ pager.report_omissions(result, omission_collector)omission_collector.attach(result)_attach_semantics(result, req)# Server-side wall clock, as ``get_context`` reports.@@ -287,7 +287,9 @@ def _finish("top_findings": findings.findings_total,"test_findings": findings.test_findings_total,"churn_complexity": len(data.churn_points),- "refactoring_plans": len(data.refactoring_recommendations),+ "refactoring_plans": (+ data.refactoring_plans.total if data.refactoring_plans is not None else 0+ ),"performance_opportunities": (data.performance.page.total if data.performance.page is not None else 0),diff --git a/packages/server/src/repowise/server/services/refactoring_health.py b/packages/server/src/repowise/server/services/refactoring_health.pyindex 7fd7e3624..60e201d12 100644--- a/packages/server/src/repowise/server/services/refactoring_health.py+++ b/packages/server/src/repowise/server/services/refactoring_health.py@@ -43,7 +43,9 @@ from repowise.core.persistence.crud.analysis.refactoring_opportunities import (get_refactoring_summary,list_refactoring_opportunities,refactoring_facet_counts,+ refactoring_opportunities_by_id,refactoring_opportunity_ids,+ refactoring_step_counts,)from repowise.core.persistence.models import RefactoringOpportunity, RefactoringSuggestion@@ -63,6 +65,55 @@ class RefactoringPage:hidden: dict[str, Any] | None = None+@dataclass(frozen=True, slots=True)+class RefactoringPlanPage:+ """One page of the queue's plans: stored steps, each with its opportunity id."""++ items: list[dict[str, Any]]+ #: Plans in scope, and the opportunities they are steps of.+ total: int+ opportunities_total: int+ #: Where the next page starts: the page's offset plus the plans it covers.+ next_offset: int+ scope: str = "all"+ hidden: dict[str, Any] | None = None+++def _filters(query: RefactoringQuery) -> dict[str, Any]:+ """The store's filter arguments for *query*."""+ return {+ "status": query.status,+ "lead_types": list(query.lead_types) if query.lead_types else None,+ "confidence": query.confidence,+ "effort": query.effort,+ "file_paths": list(query.file_paths) if query.file_paths is not None else None,+ "path_contains": query.path_contains,+ "path_prefix": query.path_prefix,+ "mechanical_only": query.mechanical_only,+ "addresses_primary": query.addresses_primary,+ }+++def _plan_window(+ counts: list[tuple[str, int]], offset: int, limit: int+) -> dict[str, tuple[int, int]]:+ """Which steps of which opportunities fall in plans ``[offset, offset + limit)``.++ *counts* is ``(opportunity_id, step_count)`` in queue order; the result+ maps each touched opportunity to its ``(start, stop)`` step slice.+ """+ window: dict[str, tuple[int, int]] = {}+ position, end = 0, offset + max(limit, 0)+ for opportunity_id, steps in counts:+ if position >= end:+ break+ start, stop = max(offset - position, 0), min(end - position, steps)+ if start < stop:+ window[opportunity_id] = (start, stop)+ position += steps+ return window++class RefactoringHealthService:"""Query, page, detail and headline over the materialized opportunities."""@@ -95,21 +146,8 @@ class RefactoringHealthService:write) says which opportunities it takes, and one id-only read of thefiltered set counts what it leaves out, by reason."""- filters: dict[str, Any] = {- "status": query.status,- "lead_types": list(query.lead_types) if query.lead_types else None,- "confidence": query.confidence,- "effort": query.effort,- "file_paths": list(query.file_paths) if query.file_paths is not None else None,- "path_contains": query.path_contains,- "path_prefix": query.path_prefix,- "mechanical_only": query.mechanical_only,- "addresses_primary": query.addresses_primary,- }- shown_ids: list[str] | None = None- hidden: dict[str, Any] | None = None- if query.scope == "fix_first":- shown_ids, hidden = await self._fix_first_scope(filters)+ filters = _filters(query)+ shown_ids, hidden = await self._scope(query, filters)rows, total = await list_refactoring_opportunities(self._session,self._repository_id,@@ -147,6 +185,51 @@ class RefactoringHealthService:hidden=hidden,)+ async def plan_page(self, query: RefactoringQuery) -> RefactoringPlanPage:+ """The queue's plans in queue order: each opportunity's steps, in step order.++ A plan is a step of one opportunity, so the plan list is a view of the+ queue: the same scope, filters and order, paged by plan. One narrow read+ of step counts places the page; only the opportunities it touches are+ decoded.+ """+ filters = _filters(query)+ shown_ids, hidden = await self._scope(query, filters)+ counts = await refactoring_step_counts(+ self._session,+ self._repository_id,+ **filters,+ opportunity_ids=shown_ids,+ order=query.resolved_order,+ )+ window = _plan_window(counts, query.offset, query.limit)+ rows = await refactoring_opportunities_by_id(+ self._session, self._repository_id, list(window), status=query.status+ )+ # The window is in queue order; the read is not.+ items = [+ {**step, "opportunity_id": opportunity_id}+ for opportunity_id, (start, stop) in window.items()+ if opportunity_id in rows+ for step in (detail_map(rows[opportunity_id]).get("steps") or [])[start:stop]+ ]+ return RefactoringPlanPage(+ items=items,+ total=sum(steps for _id, steps in counts),+ opportunities_total=len(counts),+ next_offset=query.offset + sum(stop - start for start, stop in window.values()),+ scope=query.scope,+ hidden=hidden,+ )++ async def _scope(+ self, query: RefactoringQuery, filters: dict[str, Any]+ ) -> tuple[list[str] | None, dict[str, Any] | None]:+ """The ids a ``fix_first`` scope keeps and what it hides; ``all`` keeps every row."""+ if query.scope != "fix_first":+ return None, None+ return await self._fix_first_scope(filters)+async def _fix_first_scope(self, filters: dict[str, Any]) -> tuple[list[str], dict[str, Any]]:@@ -406,4 +489,4 @@ class RefactoringHealthService:return [plan_payload(by_id[pid]) for pid in plan_ids if pid in by_id]-__all__ = ["RefactoringHealthService", "RefactoringPage"]+__all__ = ["RefactoringHealthService", "RefactoringPage", "RefactoringPlanPage"]diff --git a/packages/types/src/fix-first.ts b/packages/types/src/fix-first.tsindex 1b0af9842..15f45a5ec 100644--- a/packages/types/src/fix-first.ts+++ b/packages/types/src/fix-first.ts@@ -124,6 +124,21 @@ export interface FixFirstTotals {dormant: number;}+/**+ * The five-level count vocabulary (`FixFirstQueue.counts` in core), read on the+ * whole queue: every unit considered, those in scope (not excluded for where+ * the code lives), those that became an item, those due (tier now or next),+ * and those this response shows; `excluded` holds the non-zero exclusions.+ */+export interface FixFirstCounts {+ inventory: number;+ in_scope: number;+ eligible: number;+ due: number;+ shown: number;+ excluded: Partial<Record<FixExclusion, number>>;+}+export interface FixFirstQueue<Item = FixItem> {items: Item[];/** `items[0]`, or null when nothing is eligible. */diff --git a/tests/unit/health/test_refactoring_serving.py b/tests/unit/health/test_refactoring_serving.pyindex fff4fcf8c..5ec3c5fb6 100644--- a/tests/unit/health/test_refactoring_serving.py+++ b/tests/unit/health/test_refactoring_serving.py@@ -23,7 +23,6 @@ from repowise.core.analysis.health.refactoring.serving import (next_actions,parse_query,plan_payload,- plan_view,row_sort_key,serialize,stored_validation,@@ -75,13 +74,6 @@ def test_parse_query_scope_follows_files_and_status() -> None:assert parse_query(view="canonical", order="file")[0].resolved_order == "file"-def test_plan_view_maps_the_new_default_to_canonical() -> None:- assert plan_view(None) == "canonical"- assert plan_view("diversified") == "canonical"- assert plan_view("file_spread") == "file_spread"- assert plan_view("unknown") == "canonical"--def test_evidence_block_names_the_next_cursor() -> None:assert evidence_block([{"a": 1}], 1, 0) == {"evidence": [{"a": 1}],diff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.pyindex c04e63535..35708cd2a 100644--- a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py@@ -566,7 +566,9 @@ async def test_canonical_emitter_reference_inventory(# leads with composed opportunities. The plan reference is still emitted by# get_health, so the inventory asks the call that carries it.responses["get_health"].append(- await get_health(include=["refactoring"], only=["refactoring_plans"])+ await get_health(+ include=["refactoring"], only=["refactoring_plans"], refactoring_scope="all"+ ))inventory = {emitter: [@@ -722,6 +724,7 @@ async def _seed_plan(session, repository_id: str) -> None:}],)+ await crud.finalize_refactoring_opportunities(session, repository_id)await session.commit()@@ -868,6 +871,7 @@ async def test_finding_and_plan_ids_are_stable_and_resolve_in_one_call(include=["biomarkers", "refactoring"],only=["top_findings", "refactoring_plans"],limit=10,+ refactoring_scope="all",)health_finding = health["top_findings"][0]health_lookup = await get_health(finding_id=health_finding["id"])diff --git a/tests/unit/server/mcp/test_health.py b/tests/unit/server/mcp/test_health.pyindex 9efbb901f..c1b871657 100644--- a/tests/unit/server/mcp/test_health.py+++ b/tests/unit/server/mcp/test_health.py@@ -232,6 +232,8 @@ async def _seed_plans(session, rid, plans):for p in plans],)+ # The plan list is a view of the opportunity queue the finalizer composes.+ await crud.finalize_refactoring_opportunities(session, rid)await session.commit()@@ -274,28 +276,6 @@ async def test_entity_recovery_retains_health_semantics_and_freshness(assert plan_detail["_meta"]["health_analysis"]["recomputed_this_call"] is False-def test_validation_profiles_deduplicate_without_dropping_commands_or_target_tests():- from repowise.server.mcp_server.tool_health import _validation_profile-- validation = {- "tests": ["tests/test_service.py::test_auth"],- "total": 1,- "commands": ["pytest tests/test_service.py::test_auth"],- "targets": [- {- "file_path": "src/auth/service.py",- "tests": ["tests/test_service.py::test_auth"],- "total": 1,- }- ],- }- _profile_id, profile = _validation_profile(validation)-- assert profile["commands"] == validation["commands"]- assert profile["commands_total"] == profile["commands_emitted"] == 1- assert profile["targets"][0]["tests"] == validation["targets"][0]["tests"]--@pytest.mark.asyncioasync def test_freshness_is_a_repository_fact_in_every_mode(setup_mcp, health_data, session):"""Whether the analysis recorded its commit cannot depend on the mode asked.@@ -500,7 +480,8 @@ async def test_get_health_dashboard_leads_with_fix_first(setup_mcp, health_data)block = (await get_health())["fix_first"]lead = block["lead"]- assert lead == block["items"][0]+ # Only the lead carries its next call; every item's is one fix_id away.+ assert {k: v for k, v in lead.items() if k != "next_call"} == block["items"][0]# The file's strongest code-shape finding, said in plain words.assert lead["kind"] == "finding"assert lead["target"]["file_path"] == "src/auth/service.py"@@ -1058,10 +1039,9 @@ async def test_include_names_work_as_only_aliases(setup_mcp, health_data, alias,if resolved == "refactoring_plans":allowed |= {"refactoring_plans_status",- "validation_profiles",- "validation_profiles_total",- "validation_profiles_emitted",- "validation_profiles_reduced_reason",+ "refactoring_plans_scope",+ "refactoring_plans_hidden",+ "refactoring_plans_opportunities_total",}assert set(result) - {"mode", "targets", "_meta"} <= allowed@@ -1475,19 +1455,16 @@ async def test_coverage_carries_its_trend_capped_to_the_newest_points(@pytest.mark.asyncio-async def test_refactoring_plans_spread_across_files(setup_mcp, health_data, session):- """The explicit file_spread view spreads the cap without changing rank.+async def test_refactoring_plans_follow_the_queue_in_queue_order(setup_mcp, health_data, session):+ """The plan list is a view of the opportunity queue: each opportunity's+ steps together, opportunities in the queue's order, paged by plan.- ``deficit_by_path`` is a *file* property, so a pure deficit sort puts every- plan on the worst file ahead of every plan on the second worst. Measured on- this repo's own index before the fix, asking for the top 8 plans returned 8- plans on a single file out of 1,903 — an agent asking "what should I- refactor?" got no view of the repo at all. Filed as C4.+ The old list ranked every stored plan per request, capped it at six and+ then lost most of those to the response budget: on large repositories a+ request for 15 plans returned 2 or 3, all performance fixes."""from repowise.server.mcp_server import get_health- # Six plans on the worst file, two on the other. Impact descends within the- # worst file so a deficit-then-impact sort would take all six of them first.await _seed_plans(session,health_data,@@ -1510,32 +1487,49 @@ async def test_refactoring_plans_spread_across_files(setup_mcp, health_data, sesfor i in range(2)],)+ queue = await get_health(+ include=["refactoring"], only=["refactoring_opportunities"], refactoring_scope="all"+ )+ order = [row["opportunity_id"] for row in queue["refactoring_opportunities"]]+ steps = {row["opportunity_id"]: row["steps_total"] for row in queue["refactoring_opportunities"]}- plans = (+ first = await get_health(+ include=["refactoring"], only=["refactoring_plans"], limit=4, refactoring_scope="all"+ )+ plans = first["refactoring_plans"]+ assert len(plans) == 4+ assert first["refactoring_plans_total"] == sum(steps.values()) == 8+ assert first["refactoring_plans_opportunities_total"] == len(order)+ assert first["refactoring_plans_scope"] == "all"+ # The next page keeps the scope it was asked under.+ call = first["recovery"]["refactoring_plans"]["call"]+ assert "refactoring_scope='all'" in call and call.endswith("cursor=4)")++ rest = (await get_health(include=["refactoring"],only=["refactoring_plans"],- limit=4,- refactoring_view="file_spread",+ limit=25,+ cursor=4,+ refactoring_scope="all",))["refactoring_plans"]- assert len(plans) == 4- # Both files are represented rather than the worst file owning the list.- assert len({p["file_path"] for p in plans}) == 2- # The worst file still leads — spreading reorders within the cap, it does- # not demote the worst file.- assert plans[0]["file_path"] == "src/auth/service.py"- # Within a file, the higher-impact plan still comes first.- worst = [p["target_symbol"] for p in plans if p["file_path"] == "src/auth/service.py"]- assert worst == sorted(worst, key=lambda t: int(t.split("_")[1]))+ every = plans + rest+ assert len(every) == 8 and len({p["id"] for p in every}) == 8+ # Opportunities in queue order, each one's steps contiguous.+ seen = [p["opportunity_id"] for p in every]+ assert list(dict.fromkeys(seen)) == order+ assert seen == sorted(seen, key=order.index)+ # A row is compact; the full plan is one call away and agrees with it.+ detail = await get_health(plan_id=every[0]["id"])+ assert detail["plan"]["file_path"] == every[0]["file_path"]+ assert "plan" not in every[0] and "evidence" not in every[0]@pytest.mark.asyncio-async def test_refactoring_spread_is_exhaustive_when_one_file_has_them_all(- setup_mcp, health_data, session-):- """One file holding every plan must still fill the cap — the round-robin- drains a file's queue rather than capping it at one row per file."""+async def test_refactoring_plans_honour_scope(setup_mcp, health_data, session):+ """``refactoring_scope="all"`` lists the inventory; the default lists what+ Fix first takes and counts the rest by reason, as the queue does."""from repowise.server.mcp_server import get_healthawait _seed_plans(@@ -1543,20 +1537,153 @@ async def test_refactoring_spread_is_exhaustive_when_one_file_has_them_all(health_data,[{- "file_path": "src/auth/service.py",- "target_symbol": f"only_{i}",+ "file_path": "src/utils/helpers.py",+ "target_symbol": "tiny","source_biomarker": "complex_method",- "impact_delta": 5.0 - i,+ "impact_delta": 0.01,}- for i in range(5)],)+ asked = {"include": ["refactoring"], "only": ["refactoring_plans"], "limit": 15}+ default = await get_health(**asked)+ everything = await get_health(**asked, refactoring_scope="all")+ queue = await get_health(+ include=["refactoring"], only=["refactoring_opportunities"], refactoring_scope="all"+ )- plans = (- await get_health(include=["refactoring"], only=["refactoring_plans"], limit=4)- )["refactoring_plans"]- assert len(plans) == 4- assert {p["file_path"] for p in plans} == {"src/auth/service.py"}+ assert default["refactoring_plans_scope"] == "fix_first"+ assert everything["refactoring_plans_scope"] == "all"+ assert everything["refactoring_plans_opportunities_total"] == (+ queue["refactoring_opportunities_total"]+ )+ hidden = default["refactoring_plans_hidden"]["total"]+ assert default["refactoring_plans_opportunities_total"] + hidden == (+ everything["refactoring_plans_opportunities_total"]+ )+ assert hidden >= 1+ assert default["refactoring_plans_total"] < everything["refactoring_plans_total"]+++async def test_fix_first_named_page_honours_limit_and_cursor(setup_mcp, health_data):+ """``only=["fix_first"]`` pages the queue by ``limit`` (up to 25) and+ ``cursor``; the bare dashboard keeps its five-item head. Both carry the+ count vocabulary and the same lead."""+ from repowise.server.mcp_server import get_health+ from repowise.server.mcp_server.tool_health.request import (+ FIX_FIRST_CAP,+ FIX_FIRST_PAGE_CAP,+ )++ dashboard = (await get_health(limit=50))["fix_first"]+ whole = await get_health(only=["fix_first"], limit=50)+ block = whole["fix_first"]+ eligible = block["counts"]["eligible"]+ assert eligible >= 1+ assert len(dashboard["items"]) == min(eligible, FIX_FIRST_CAP)+ assert len(block["items"]) == min(eligible, FIX_FIRST_PAGE_CAP)+ assert block["items_total"] == eligible+ counts = block["counts"]+ assert set(counts) == {"inventory", "in_scope", "eligible", "due", "shown", "excluded"}+ assert counts["inventory"] >= counts["in_scope"] >= counts["eligible"] >= counts["due"]+ assert counts["shown"] == len(block["items"])+ assert all(n > 0 for n in counts["excluded"].values())++ first = await get_health(only=["fix_first"], limit=1)+ assert len(first["fix_first"]["items"]) == 1+ if eligible > 1:+ assert first["recovery"]["fix_first"]["call"].endswith("cursor=1)")+ else:+ assert "fix_first" not in (first.get("recovery") or {})+ second = (await get_health(only=["fix_first"], limit=1, cursor=1))["fix_first"]+ assert second["cursor"] == 1+ assert second["items"] == block["items"][1:2]+ # The lead is the queue's, whatever page is shown.+ assert second["lead"] == block["lead"] == dashboard["lead"]+++async def test_fix_first_page_grows_only_when_limit_is_passed(+ setup_mcp, health_data, monkeypatch+):+ """``only=["fix_first"]`` with no ``limit`` costs what the dashboard block+ does (five items, with the next page named); a passed ``limit`` pages up to 25."""+ from dataclasses import replace++ from repowise.server.mcp_server import get_health+ from repowise.server.mcp_server.tool_health import loading++ real = loading.load_fix_first++ async def thirty(session, repository_id, **kwargs):+ queue = await real(session, repository_id, **kwargs)+ items = tuple(+ replace(queue.items[0], id=f"fix1_{index:020d}", rank=index) for index in range(30)+ )+ return replace(queue, items=items, totals=replace(queue.totals, eligible=30, shown=30))++ monkeypatch.setattr(loading, "load_fix_first", thirty)++ default = await get_health(only=["fix_first"])+ assert len(default["fix_first"]["items"]) == 5+ assert default["recovery"]["fix_first"]["remaining"] == 25+ call = default["recovery"]["fix_first"]["call"]+ assert "limit=5," in call and call.endswith("cursor=5)")+ asked = await get_health(only=["fix_first"], limit=25)+ assert len(asked["fix_first"]["items"]) == 25+ assert asked["recovery"]["fix_first"]["call"].endswith("cursor=25)")+ assert len((await get_health(only=["fix_first"], limit=50))["fix_first"]["items"]) == 25+ assert len((await get_health())["fix_first"]["items"]) == 5+++def test_limit_defaults_are_resolved_per_section():+ from repowise.server.mcp_server.tool_health.request import DEFAULT_LIMIT, HealthRequest++ def request(**kwargs):+ args = {+ name: None+ for name in (+ "targets", "include", "only", "repo", "limit", "refactoring_type",+ "refactoring_confidence", "refactoring_effort", "refactoring_scope",+ "performance_view", "performance_context", "performance_boundary",+ "performance_confidence", "performance_actionability", "performance_sort",+ )+ }+ args.update(cursor=0, refactoring_view="diversified", scope="all", counts="everything")+ args.update(kwargs)+ return HealthRequest(**args)++ unasked = request(only=["fix_first"])+ assert unasked.limit == DEFAULT_LIMIT and not unasked.limit_explicit+ assert unasked.fix_first_cap == 5+ assert request(only=["fix_first"], limit=25).fix_first_cap == 25+ assert request(only=["fix_first"], limit=3).fix_first_cap == 3+ assert request(limit=50).fix_first_cap == 5+++def test_fix_first_counts_split_scope_from_worth():+ from repowise.core.analysis.health.fix_first.model import FixFirstQueue, FixTotals++ excluded = dict.fromkeys(("test", "tooling", "below_min_worth", "vendored"), 0)+ excluded.update(test=4, tooling=1, below_min_worth=3)+ queue = FixFirstQueue(totals=FixTotals(candidates=10, eligible=2, shown=2, excluded=excluded))+ assert queue.counts(shown=1) == {+ "inventory": 10,+ "in_scope": 5,+ "eligible": 2,+ "due": 0,+ "shown": 1,+ "excluded": {"test": 4, "tooling": 1, "below_min_worth": 3},+ }+++async def test_unknown_only_keys_are_rejected_with_a_hint(setup_mcp, health_data):+ from repowise.server.mcp_server import get_health++ result = await get_health(only=["performance"])+ assert result["unknown_only_keys"] == ["performance"]+ assert "performance_opportunities" in result["unknown_only_keys_hint"]@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_health_semantics_matrix.py b/tests/unit/server/mcp/test_health_semantics_matrix.pyindex d9a4a97fa..7a36f09dc 100644--- a/tests/unit/server/mcp/test_health_semantics_matrix.py+++ b/tests/unit/server/mcp/test_health_semantics_matrix.py@@ -193,18 +193,21 @@ SEALED_HEALTH_SEMANTICS: tuple[HealthSemanticsCase, ...] = (name="performance plus refactoring",call=('get_health(include=["performance", "refactoring"], '- 'only=["performance_opportunities", "refactoring_plans"], limit=1)'+ 'only=["performance_opportunities", "refactoring_plans"], limit=1, '+ 'refactoring_scope="all")'),kwargs=_frozen(include=("performance", "refactoring"),only=("performance_opportunities", "refactoring_plans"),limit=1,+ refactoring_scope="all",),comparison="independent performance and refactoring projections",comparison_kwargs=_frozen(include=("performance", "refactoring"),only=("performance_opportunities", "refactoring_plans"),limit=1,+ refactoring_scope="all",),plans_requested=True,expected_plan_count=1,@@ -340,6 +343,7 @@ def _path(result: dict[str, Any], dotted: str) -> Any:async def _seed_case_evidence(case: HealthSemanticsCase, session, repository_id: str) -> None:from repowise.core.persistence.crud import (+ finalize_refactoring_opportunities,save_coverage_files,save_health_findings,save_health_snapshot,@@ -416,6 +420,8 @@ async def _seed_case_evidence(case: HealthSemanticsCase, session, repository_id:)plans.append({**plans[0], "file_path": "src/db/models.py", "target_symbol": "load_rows"})await save_refactoring_suggestions(session, repository_id, plans)+ # The plan list is a view of the opportunity queue the finalizer composes.+ await finalize_refactoring_opportunities(session, repository_id)await session.commit()diff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.pyindex 3fbec2166..d39a17392 100644--- a/tests/unit/server/mcp/test_performance_levels.py+++ b/tests/unit/server/mcp/test_performance_levels.py@@ -102,8 +102,10 @@ async def test_a_bare_dashboard_leads_with_something_to_do(setup_mcp, materializ# it points at the loop of its first caller, so its title names the helper.shared = [i for i in perf if i["title"].endswith(" load")]assert len(shared) == 1, perf- assert shared[0]["next_call"]["arguments"]["opportunity_id"].startswith("perf")- assert 0 < len(json.dumps(shared[0])) <= 1500+ # A list item's next call is one fix_id away; only the lead carries it inline.+ item = (await get_health(fix_id=shared[0]["id"]))["item"]+ assert item["next_call"]["arguments"]["opportunity_id"].startswith("perf")+ assert 0 < len(json.dumps(shared[0])) <= 1000@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.pyindex 581184256..bbf5d1b66 100644--- a/tests/unit/server/mcp/test_response_budget_contracts.py+++ b/tests/unit/server/mcp/test_response_budget_contracts.py@@ -266,43 +266,6 @@ def test_adversarial_payload_goldens_fit_and_recover_in_one_lookup(assert f'"id": {row_id}' not in joined-def test_health_budget_prunes_profiles_for_removed_plans(- setup_mcp: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch-) -> None:- import repowise.server.mcp_server as mcp_mod-- (tmp_path / ".repowise").mkdir()- monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))- plans = [- {"id": f"plan-{index}", "validation_profile_id": f"profile-{index}"}- for index in range(8)- ]- profiles = [- {- "id": f"profile-{index}",- "commands": [f"pytest tests/test_{index}.py " + "x" * 6_000],- }- for index in range(8)- ]- payload = {- "mode": "targets",- "targets": ["src/large.py"],- "refactoring_plans": plans,- "refactoring_plans_total": len(plans),- "validation_profiles": profiles,- "validation_profiles_total": len(profiles),- "_meta": {"contract_version": 1},- }-- result = _enforce("get_health", payload, ["refactoring"])- referenced = {plan["validation_profile_id"] for plan in result["refactoring_plans"]}- retained = {profile["id"] for profile in result["validation_profiles"]}- assert retained == referenced- assert result["validation_profiles_emitted"] == len(retained)- assert result["validation_profiles_reduced_reason"] == "response_budget"- assert result["_meta"]["response_budget"]["serialized_chars"] <= EXPANDED_RESPONSE_CHARS--def test_explicit_include_uses_the_expansion_tier(setup_mcp: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:@@ -687,3 +650,89 @@ def test_a_tool_with_no_graph_counts_claims_no_floor() -> None:result = _enforce("get_overview", _payload("get_overview", 0))assert "floor" not in result["_meta"]+++def _enforce_health(payload: dict[str, Any], **kwargs: Any) -> dict:+ """Budget *payload* as a ``get_health`` call with *kwargs*, hooks and all."""+ from repowise.server.mcp_server import ensure_full_surface, get_health++ ensure_full_surface()+ return enforce_response_budget(+ "get_health",+ payload,+ signature=inspect.signature(get_health),+ args=(),+ kwargs=kwargs,+ )+++def _fix_first_page(total: int, cursor: int = 0) -> dict[str, Any]:+ items = [{"id": f"fix1_{index}", "why": "w" * 2_000} for index in range(25)]+ return {+ "mode": "dashboard",+ "fix_first": {+ "items": items,+ "lead": items[0],+ "counts": {"inventory": total, "in_scope": total, "eligible": total, "due": 0,+ "shown": len(items), "excluded": {}},+ "items_total": total,+ "cursor": cursor,+ },+ "recovery": {"fix_first": {"remaining": total - cursor - 25, "call": "stale"}}+ if cursor + 25 < total+ else {},+ "_meta": {"contract_version": 1},+ }++[email protected](("total", "cursor"), [(100, 25), (50, 25)])+def test_a_trimmed_fix_first_page_restates_its_next_cursor(+ setup_mcp: str, total: int, cursor: int+) -> None:+ """The budget trims a 25-item page's tail; the next page must start at the+ first row the caller did not get, including on the last page, which had no+ next call before the trim."""+ result = _enforce_health(+ _fix_first_page(total, cursor), only=["fix_first"], limit=25, cursor=cursor+ )+ block = result["fix_first"]+ shown = len(block["items"])+ assert 0 < shown < 25+ assert block["counts"]["shown"] == shown+ recovery = result["recovery"]["fix_first"]+ assert recovery["remaining"] == total - cursor - shown+ assert recovery["call"].endswith(f"cursor={cursor + shown})")+ assert "only=['fix_first']" in recovery["call"]+++def test_a_trimmed_plan_page_restates_its_next_cursor(setup_mcp: str) -> None:+ plans = [{"id": f"refac4_{index}", "target_symbol": "s" * 2_000} for index in range(25)]+ payload = {+ "mode": "dashboard",+ "refactoring_plans": plans,+ "refactoring_plans_total": 25,+ "refactoring_plans_status": {"state": "available", "reason": None},+ "_meta": {"contract_version": 1},+ }+ result = _enforce_health(+ payload,+ include=["refactoring"],+ only=["refactoring_plans"],+ limit=25,+ refactoring_scope="all",+ )+ shown = len(result["refactoring_plans"])+ assert 0 < shown < 25+ recovery = result["recovery"]["refactoring_plans"]+ assert recovery["remaining"] == 25 - shown+ assert recovery["call"].endswith(f"cursor={shown})")+ assert "refactoring_scope='all'" in recovery["call"]+++def test_an_untrimmed_last_page_names_no_next_call(setup_mcp: str) -> None:+ payload = _fix_first_page(total=25)+ for item in payload["fix_first"]["items"]:+ item["why"] = "w"+ result = _enforce_health(payload, only=["fix_first"], limit=25)+ assert len(result["fix_first"]["items"]) == 25+ assert "fix_first" not in (result.get("recovery") or {})