Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): lead the Performance tab with the action, grouped by area (#4138)
Raghav Chamadiya8a93b0d769cb
diff --git a/docs/layers/PERFORMANCE.md b/docs/layers/PERFORMANCE.mdindex 2e11e339a..9ab91ec20 100644--- a/docs/layers/PERFORMANCE.md+++ b/docs/layers/PERFORMANCE.md@@ -134,7 +134,7 @@ competes with other kinds of work.|---|---|| CLI | `repowise health` and `repowise next` list performance work inside Fix first || MCP | `get_health(include=["performance"])`; open one cause with `opportunity_id` |-| Dashboard | Code Health, Performance tab: each cause with its steps and the raw observations as evidence |+| Dashboard | Code Health, Performance tab: one scope (Worth doing now, All production, Everything) with every count inside it, causes grouped by area, each with its steps and the raw observations as evidence |MCP filters: `performance_view` (`detail` or `summary`), `performance_context`(`production` by default; `tooling`, `test`, `unknown` or `all`),diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.tsindex e48728914..edb7e5ef6 100644--- a/packages/api-client/src/code-health.ts+++ b/packages/api-client/src/code-health.ts@@ -135,6 +135,9 @@ export async function getPerformanceOpportunities(actionability: opts.actionability,proof: opts.proof,role: opts.role,+ queue: opts.queue || undefined,+ area: opts.area,+ area_depth: opts.area_depth,view: opts.view,sort: opts.sort,file_paths: opts.file_paths?.length ? opts.file_paths.join(",") : undefined,diff --git a/packages/core/src/repowise/core/analysis/health/perf/serving.py b/packages/core/src/repowise/core/analysis/health/perf/serving.pyindex f24e81255..15d544cc0 100644--- a/packages/core/src/repowise/core/analysis/health/perf/serving.py+++ b/packages/core/src/repowise/core/analysis/health/perf/serving.py@@ -16,6 +16,8 @@ from collections.abc import Iterable, Sequencefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any, Literal+from repowise.core.analysis.areas import choose_depth, normalize_area+from repowise.core.analysis.areas.paths import area_atfrom repowise.core.analysis.execution_roles import EXECUTION_ROLESfrom repowise.core.analysis.health import queue_rulesfrom repowise.core.analysis.health.finding_identity import finding_public_id@@ -69,6 +71,9 @@ BOUNDARIES = ("db", "network", "filesystem", "subprocess", "lock", NULL_VALUE)ROLES = (*EXECUTION_ROLES, "all")"""One execution role, or ``all``. Absent means the roles the default queue holds."""+ANY = "all"+"""Asks for every state or every proof, where absence means the default queue's."""+DEFAULT_ACTIONABILITIES = DEFAULT_QUEUE_STATES"""``expected`` rows offer nothing to change and ``investigate`` rows no strategy to apply,so both are asked for, not queued. The summary's ``default_queue`` counts each one left out."""@@ -122,6 +127,8 @@ FILTERS: tuple[FilterRule, ...] = (FilterRule("proofs", "cost_proof", "in", "set"),FilterRule("roles", "execution_role", "in", "set"),FilterRule("file_paths", "file_path", "in", "set"),+ # One area at any depth, as ``<area>/``; the root area is no filter.+ FilterRule("area_prefix", "file_path", "prefix", "set"),# The default queue is the stored judgement (``queue.counts.perf_judgement``).FilterRule("queue_eligible", "queue_eligible", "is", "set"),)@@ -139,6 +146,12 @@ FACETS: tuple[Facet, ...] = ()FACET_FIELDS = tuple(column for _, column, _ in FACETS)+#: The stored default-queue verdict, grouped beside the facet fields so a+#: scope's facets can be counted inside the scope (:func:`fold_scoped_facets`).+#: Never emitted as a facet of its own.+_QUEUE_FACET: Facet = ("queue", "queue_eligible", "queue_eligible")+SCOPED_GROUP_FIELDS = (*FACET_FIELDS, "queue_eligible")+def sort_keys(sort: str | None) -> SortKeys:"""The keys for *sort*; an unknown sort reads as rank."""@@ -163,13 +176,135 @@ def _facet_selection(query: PerformanceQuery) -> dict[str, Any]:"boundary": query.boundary,"confidence": query.confidence,"actionabilities": (- None if query.actionability is None else frozenset({query.actionability})+ None if query.actionability in (None, ANY) else frozenset({query.actionability})),- "proofs": None if query.proof is None else frozenset({query.proof}),+ "proofs": None if query.proof in (None, ANY) else frozenset({query.proof}),"roles": None if query.role in (None, "all") else frozenset({query.role}),}+def _as_counts(folded: dict[str, dict[str, int]]) -> dict[str, list[dict[str, Any]]]:+ return {+ name: [+ {"value": value, "total": total}+ for value, total in sorted(counts.items(), key=lambda item: (-item[1], item[0]))+ ]+ for name, counts in folded.items()+ }+++def fold_scoped_facets(+ groups: Iterable[Sequence[Any]], query: PerformanceQuery, *, judged: bool = True+) -> dict[str, list[dict[str, Any]]]:+ """Facets counted inside the query's scope: every filter the store applies+ (the default queue's states, proof, role and stored verdict included)+ narrows every facet but its own, so a facet's values sum to the rows the+ query returns once that facet's own filter is lifted.++ *groups* are ``(*SCOPED_GROUP_FIELDS, count)``. Used by the dashboard;+ the agent surface keeps :func:`fold_facets`.+ """+ # The aggregate is already narrowed to the query's files and area.+ selection = {+ key: value+ for key, value in query.store_filters(judged=judged).items()+ if key not in ("file_paths", "area_prefix")+ }+ folded = queue_rules.fold_facets(+ groups,+ (*FACETS, _QUEUE_FACET),+ rules=FILTERS,+ selection=selection,+ null=NULL_VALUE,+ )+ folded.pop(_QUEUE_FACET[0], None)+ return _as_counts(folded)+++#: The dashboard's three scopes, as the queries that list them: the default+#: queue, every production cause, and everything.+SCOPES: dict[str, dict[str, Any]] = {+ "now": {},+ "production": {"actionability": ANY, "proof": ANY, "role": "all"},+ "all": {"context": "all", "actionability": ANY, "proof": ANY, "role": "all"},+}+++def scope_counts(groups: Iterable[Sequence[Any]], *, judged: bool = True) -> dict[str, int]:+ """How many causes each scope holds before the narrowing filters, from the+ same ``(*SCOPED_GROUP_FIELDS, count)`` groups the scoped facets fold, so+ within whatever file scope and language gate those groups carry."""+ rows = [dict(zip((*SCOPED_GROUP_FIELDS, "count"), group, strict=True)) for group in groups]+ counts: dict[str, int] = {}+ for name, args in SCOPES.items():+ query, _ = parse_query(**args, lift_defaults=True)+ params = {+ k: v+ for k, v in query.store_filters(judged=judged).items()+ if k not in ("file_paths", "area_prefix")+ }+ counts[name] = sum(int(row["count"]) for row in rows if keep(row, params))+ return counts+++AREA_LIMIT = 24+"""Areas a response names; the rest are counted in ``more``."""+++def area_facet(+ groups: Iterable[Sequence[Any]],+ *,+ base: str | None = None,+ depth: int | None = None,+ limit: int = AREA_LIMIT,+) -> dict[str, Any]:+ """The query's causes by area, with each area's actionability split.++ *groups* are ``(file_path, actionability_state, count)`` over the rows the+ query lists. Areas are directories at *depth* below *base* (chosen by+ :func:`choose_depth` when not given), ranked by plan-ready causes, then+ advisory, then size, so the area worth opening first leads.+ """+ by_file: dict[str, dict[str, int]] = {}+ for file_path, state, count in groups:+ states = by_file.setdefault(file_path, {})+ states[state] = states.get(state, 0) + int(count)+ weights = {path: sum(states.values()) for path, states in by_file.items()}+ root = normalize_area(base)+ chosen = depth if depth is not None and depth > 0 else choose_depth(weights, base=root)+ areas: dict[str, dict[str, int]] = {}+ for path, states in by_file.items():+ split = areas.setdefault(area_at(path, chosen), {})+ for state, count in states.items():+ split[state] = split.get(state, 0) + count+ # Files directly in the base sit in an area equal to it: its own files,+ # which opening again would not narrow.+ ranked = sorted(+ (+ {+ "area": area,+ "total": sum(split.values()),+ "actionability": split,+ **({"own": True} if area == root else {}),+ }+ for area, split in areas.items()+ ),+ key=lambda entry: (+ -entry["actionability"].get("plan_ready", 0),+ -entry["actionability"].get("advisory", 0),+ -entry["total"],+ entry["area"],+ ),+ )+ shown = ranked[: max(limit, 0)]+ return {+ "depth": chosen,+ "items": shown,+ "more": sum(entry["total"] for entry in ranked[len(shown) :]),+ "total": sum(weights.values()),+ }++def fold_facets(groups: Iterable[Sequence[Any]], query: PerformanceQuery) -> dict[str, list[dict[str, Any]]]:@@ -178,13 +313,7 @@ def fold_facets(folded = queue_rules.fold_facets(groups, FACETS, rules=FILTERS, selection=_facet_selection(query), null=NULL_VALUE)- return {- name: [- {"value": value, "total": total}- for value, total in sorted(counts.items(), key=lambda item: (-item[1], item[0]))- ]- for name, counts in folded.items()- }+ return _as_counts(folded)def facet_counts(rows: Iterable[Any], query: PerformanceQuery) -> dict[str, list[dict[str, Any]]]:@@ -221,6 +350,15 @@ class PerformanceQuery:file_paths: tuple[str, ...] | None = Nonelimit: int = 20offset: int = 0+ #: Keep to the stored default-queue verdict whatever else is chosen, so a+ #: state picked inside "worth doing now" stays inside it.+ queue: bool = False+ #: One area (a directory) at any depth; ``None`` is the whole repository.+ area: str | None = None++ @property+ def area_prefix(self) -> str | None:+ return f"{self.area}/" if self.area else None@propertydef status(self) -> str:@@ -246,29 +384,32 @@ class PerformanceQuery:@propertydef queue_eligible(self) -> bool | None:- return True if self.default_queue else None+ return True if self.default_queue or self.queue else Nonedef store_filters(self, *, judged: bool = True) -> dict[str, Any]:"""The store's filter arguments. On a store whose causes are not alljudged (``judged=False``), the default queue reads its rule live:the default states and proof instead of the stored verdict."""- live = self.default_queue and not judged+ live = (self.default_queue or self.queue) and not judgedreturn {"contexts": self.contexts,"boundary": self.boundary,"confidence": self.confidence,- "actionabilities": DEFAULT_ACTIONABILITIES if live else self.actionabilities,- "proofs": DEFAULT_QUEUE_PROOFS if live else self.proofs,- "roles": QUEUE_ROLES if live else self.roles,+ "actionabilities": (self.actionabilities or DEFAULT_ACTIONABILITIES)+ if live+ else self.actionabilities,+ "proofs": (self.proofs or DEFAULT_QUEUE_PROOFS) if live else self.proofs,+ "roles": (self.roles or QUEUE_ROLES) if live else self.roles,"queue_eligible": None if live else self.queue_eligible,"file_paths": self.file_paths,+ "area_prefix": self.area_prefix,}@propertydef actionabilities(self) -> frozenset[str] | None:"""One explicit state; else, under another context, the defaultqueue states (plan_ready, advisory). ``None`` for the default queue."""- if self.default_queue:+ if self.default_queue or self.actionability == ANY:return Noneif self.actionability is None:return DEFAULT_ACTIONABILITIES@@ -280,7 +421,7 @@ class PerformanceQuery:the measured causes, so every surface lists what the default queuecounts. ``None`` for the default queue. The ``proof`` facet says howmany unproven ones sit one filter away."""- if self.default_queue:+ if self.default_queue or self.proof == ANY:return Noneif self.proof is None:return DEFAULT_QUEUE_PROOFS@@ -325,11 +466,17 @@ def parse_query(file_paths: tuple[str, ...] | None = None,limit: int = 20,offset: int = 0,+ queue: bool = False,+ lift_defaults: bool = False,+ area: str | None = None,) -> tuple[PerformanceQuery, dict[str, str]]:"""Normalize caller input, reporting anything unrecognized by name.An unknown filter value must not read as an empty repository, so it isdropped from the query and named in the returned map instead.++ ``lift_defaults`` accepts ``all`` for state and proof, the dashboard's+ scopes; the agent surface leaves it off and keeps its vocabulary."""ignored: dict[str, str] = {}@@ -348,14 +495,22 @@ def parse_query(context=resolved_context,boundary=pick("performance_boundary", boundary, BOUNDARIES),confidence=pick("performance_confidence", confidence, CONFIDENCES),- actionability=pick("performance_actionability", actionability, ACTIONABILITIES),- proof=pick("performance_proof", proof, QUEUE_PROOFS),+ actionability=pick(+ "performance_actionability",+ actionability,+ (*ACTIONABILITIES, ANY) if lift_defaults else ACTIONABILITIES,+ ),+ proof=pick(+ "performance_proof", proof, (*QUEUE_PROOFS, ANY) if lift_defaults else QUEUE_PROOFS+ ),role=pick("performance_role", role, ROLES),view=pick("performance_view", view, CANONICAL_VIEWS) or "detail",sort=pick("performance_sort", sort, CANONICAL_SORTS) or DEFAULT_SORT,file_paths=file_paths,limit=max(0, limit),offset=max(0, offset),+ queue=queue,+ area=normalize_area(area) or None,),ignored,)@@ -407,12 +562,18 @@ def intervention_file(opportunity: PerformanceOpportunity) -> str:# ----------------------------------------------------------------------------def serialize(row: Any, link: PlanLink, *, summary: bool = False) -> dict[str, Any]:+def serialize(+ row: Any, link: PlanLink, *, summary: bool = False, decisions: bool = False+) -> dict[str, Any]:"""Rebuild the canonical opportunity payload from row plus details.Columns carry what a query filters or orders on and ``details_json``carries the rest, so no fact is stored twice and nothing here computesa value the writer already decided.++ ``decisions`` adds the fix, gain and effort to a ``summary`` row, for a+ list a person acts on from (the dashboard queue). The agent surface keeps+ its summary shape, so its responses do not grow."""details = detail_map(row)payload = {@@ -446,13 +607,39 @@ def serialize(row: Any, link: PlanLink, *, summary: bool = False) -> dict[str, A"lower_priority": LOW_PRIORITY_LABEL.get(perf_low_priority(row) or ""),}if summary:- return payload- return {**payload, **_detail_fields(row, details)}+ return {**payload, **_decision_fields(row, details)} if decisions else payload+ return {**payload, **_decision_fields(row, details), **_detail_fields(row, details)}+++def _decision_fields(row: Any, details: dict[str, Any]) -> dict[str, Any]:+ """What a row needs to be acted on from a list: the fix, its gain and its+ effort. Always on the detail view; on a summary row only when asked."""+ fix_strategy = field(row, "fix_strategy")+ plan = details.get("plan") or {}+ return {+ "gain_text": gain_text(row, details.get("facets") or {}),+ "fix": None+ if fix_strategy is None+ else {+ "strategy": fix_strategy,+ "safety": field(row, "fix_safety"),+ "rationale": details.get("fix_rationale") or "",+ **({"api": details["fix_api"]} if details.get("fix_api") else {}),+ },+ **(+ {+ "plan_economics": {+ key: plan.get(key) for key in ("effort_bucket", "benefit", "cost", "risk")+ }+ }+ if plan+ else {}+ ),+ }def _detail_fields(row: Any, details: dict[str, Any]) -> dict[str, Any]:"""What the ``detail`` view adds to the summary payload."""- fix_strategy = field(row, "fix_strategy")return {"terminal_sinks": details.get("terminal_sinks", []),"shared_path_suffix": details.get("shared_path_suffix", []),@@ -460,20 +647,11 @@ def _detail_fields(row: Any, details: dict[str, Any]) -> dict[str, Any]:"reliable_entry_reachability": details.get("reliable_entry_reachability"),"provenance": details.get("provenance"),"facets": details.get("facets", {}),- "gain_text": gain_text(row, details.get("facets") or {}),"actionability_reason": details.get("actionability_reason"),"prerequisites": details.get("prerequisites", []),"rank_factors": details.get("rank_factors", {}),"siblings": details.get("siblings", []),**plan_brief(details.get("plan")),- "fix": None- if fix_strategy is None- else {- "strategy": fix_strategy,- "safety": field(row, "fix_safety"),- "rationale": details.get("fix_rationale") or "",- **({"api": details["fix_api"]} if details.get("fix_api") else {}),- },}@@ -490,7 +668,8 @@ def gain_text(row: Any, facets: dict[str, Any]) -> str:def plan_brief(plan: dict[str, Any] | None) -> dict[str, Any]:- """The stored plan's validation, steps and economics, or nothing on an older store."""+ """The stored plan's validation and steps, or nothing on an older store.+ Its economics ride on every view (``_decision_fields``)."""if not plan:return {}validation = plan.get("validation") or {}@@ -498,9 +677,6 @@ def plan_brief(plan: dict[str, Any] | None) -> dict[str, Any]:return {"validation": {key: validation.get(key) for key in keys},"plan_steps": plan.get("steps", []),- "plan_economics": {- key: plan.get(key) for key in ("effort_bucket", "benefit", "cost", "risk")- },}@@ -613,6 +789,7 @@ def evidence_payload(row: Any) -> dict[str, Any]:__all__ = ["ACTIONABILITIES",+ "AREA_LIMIT","BOUNDARIES","CANONICAL_CONTEXTS","CANONICAL_SORTS",@@ -626,14 +803,17 @@ __all__ = ["FILTERS","PLAN_REASONS","ROLES",+ "SCOPES","SORTS","SUMMARY_UNAVAILABLE","PerformanceContext","PerformanceQuery","PlanLink",+ "area_facet","evidence_payload","facet_counts","fold_facets",+ "fold_scoped_facets","gain_text","intervention_file","keep",@@ -642,6 +822,7 @@ __all__ = ["plan_link","rescope_summary","row_sort_key",+ "scope_counts","serialize","sort_keys","summary_payload",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex a1be55994..f1d0c5a7f 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -109,6 +109,7 @@ from .performance import (list_opportunity_evidence,list_performance_opportunities,opportunity_details,+ performance_area_counts,performance_facet_counts,performance_file_rollups,)@@ -201,6 +202,7 @@ __all__ = ["load_ingest_at_commit","load_newest_ingest","opportunity_details",+ "performance_area_counts","performance_facet_counts","performance_file_rollups","plan_payoff",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py b/packages/core/src/repowise/core/persistence/crud/analysis/performance.pyindex 7a01ac8a4..8712ebb55 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/performance.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/performance.py@@ -574,6 +574,7 @@ async def list_performance_opportunities(roles: frozenset[str] | None = None,queue_eligible: bool | None = None,file_paths: tuple[str, ...] | None = None,+ area_prefix: str | None = None,sort: str = "rank",limit: int = 20,offset: int = 0,@@ -596,6 +597,7 @@ async def list_performance_opportunities(roles=roles,queue_eligible=queue_eligible,file_paths=file_paths,+ area_prefix=area_prefix,include_unverified=include_unverified,)total = int(@@ -627,7 +629,9 @@ async def performance_facet_counts(*,file_paths: tuple[str, ...] | None = None,include_unverified: bool = False,-) -> list[tuple[str, str | None, str, str, str, str, str, int]]:+ scoped: bool = False,+ area_prefix: str | None = None,+) -> list[tuple[Any, ...]]:"""Grouped counts over every open opportunity, in one aggregate statement.Returned pre-aggregation, one ``(*FACET_FIELDS, count)`` tuple per group,@@ -635,14 +639,19 @@ async def performance_facet_counts(with every filter applied *except* its own, or choosing one value woulderase the alternatives."""- from ....analysis.health.perf.serving import FACET_FIELDS+ from ....analysis.health.perf.serving import FACET_FIELDS, SCOPED_GROUP_FIELDS- columns = tuple(getattr(PerformanceOpportunity, name) for name in FACET_FIELDS)+ # ``scoped`` also groups by the stored queue verdict, for scope-aware facets.+ fields = SCOPED_GROUP_FIELDS if scoped else FACET_FIELDS+ columns = tuple(getattr(PerformanceOpportunity, name) for name in fields)result = await session.execute(select(*columns, func.count()).where(*_predicates(- repository_id, file_paths=file_paths, include_unverified=include_unverified+ repository_id,+ file_paths=file_paths,+ area_prefix=area_prefix,+ include_unverified=include_unverified,)).group_by(*columns)@@ -650,6 +659,27 @@ async def performance_facet_counts(return [tuple(row) for row in result.all()]+async def performance_area_counts(+ session: AsyncSession,+ repository_id: str,+ *,+ include_unverified: bool = False,+ **filters: Any,+) -> list[tuple[str, str, int]]:+ """``(file_path, actionability_state, count)`` over the rows *filters*+ (the serving layer's ``store_filters``) list, for the area facet."""+ result = await session.execute(+ select(+ PerformanceOpportunity.file_path,+ PerformanceOpportunity.actionability_state,+ func.count(),+ )+ .where(*_predicates(repository_id, include_unverified=include_unverified, **filters))+ .group_by(PerformanceOpportunity.file_path, PerformanceOpportunity.actionability_state)+ )+ return [(row[0], row[1], int(row[2])) for row in result.all()]++_ACTIONABILITY_STATES = ("plan_ready", "advisory", "investigate", "expected")"""The states a rollup breaks down. Named, so a fifth cannot vanish silently."""diff --git a/packages/server/src/repowise/server/routers/code_health/performance_routes.py b/packages/server/src/repowise/server/routers/code_health/performance_routes.pyindex 59761a7df..73ffc1626 100644--- a/packages/server/src/repowise/server/routers/code_health/performance_routes.py+++ b/packages/server/src/repowise/server/routers/code_health/performance_routes.py@@ -85,6 +85,22 @@ async def list_performance_opportunities("tooling and test, whose loops run once per process."),),+ queue: bool = Query(+ False,+ description=(+ "Keep to the default queue's stored verdict whatever state is chosen, "+ "so a state picked inside 'worth doing now' stays inside it."+ ),+ ),+ area: str | None = Query(+ None, description="One area (a directory) at any depth; absent is the whole repository."+ ),+ area_depth: int | None = Query(+ None,+ ge=1,+ le=32,+ description="Group the area facet at this directory depth; absent chooses one.",+ ),view: str = Query("detail"),sort: str = Query("rank"),file_paths: str | None = Query(@@ -116,9 +132,20 @@ async def list_performance_opportunities(file_paths=_paths(file_paths),limit=limit,offset=offset,+ queue=queue,+ lift_defaults=True,+ area=area,)page = await _service(session, repo_id, include_unverified=include_unverified).page(- query, evidence_per_item=_EVIDENCE_PER_ITEM, with_facets=True, with_summary=True+ query,+ evidence_per_item=_EVIDENCE_PER_ITEM,+ with_facets=True,+ with_summary=True,+ # The tab acts on summary rows, so they carry fix, gain and effort.+ row_decisions=True,+ # Every count the tab shows sits inside the scope it asked for.+ scoped_facets=True,+ area_depth=area_depth,)return {"items": label_previews(@@ -131,6 +158,8 @@ async def list_performance_opportunities("summary": page.summary,"counts": page.counts,"gated": page.gated,+ "scopes": page.scopes,+ "areas": page.areas,**({"ignored_arguments": ignored} if ignored else {}),}diff --git a/packages/server/src/repowise/server/services/performance_health.py b/packages/server/src/repowise/server/services/performance_health.pyindex 46f0fd5ad..6185602a7 100644--- a/packages/server/src/repowise/server/services/performance_health.py+++ b/packages/server/src/repowise/server/services/performance_health.py@@ -26,10 +26,13 @@ from repowise.core.analysis.health.perf.opportunities import model_statefrom repowise.core.analysis.health.perf.serving import (PerformanceQuery,PlanLink,+ area_facet,evidence_payload,fold_facets,+ fold_scoped_facets,plan_link,rescope_summary,+ scope_counts,serialize,summary_payload,unresolved_detail,@@ -43,6 +46,7 @@ from repowise.core.persistence.crud import (list_evidence_for_opportunities,list_opportunity_evidence,list_performance_opportunities,+ performance_area_counts,performance_facet_counts,)from repowise.core.persistence.crud.analysis.queue_counts import any_unjudged, unit_counts@@ -63,6 +67,11 @@ class PerformancePage:counts: dict[str, Any] = field(default_factory=dict)#: Open opportunities a language gate held back, ``{language: {count, ...}}``.gated: dict[str, dict] = field(default_factory=dict)+ #: Causes per dashboard scope (``now``, ``production``, ``all``) before the+ #: narrowing filters. Only with scoped facets.+ scopes: dict[str, int] = field(default_factory=dict)+ #: The query's causes by area (``serving.area_facet``). Only with scoped facets.+ areas: dict[str, Any] = field(default_factory=dict)class PerformanceHealthService:@@ -94,6 +103,9 @@ class PerformanceHealthService:evidence_per_item: int = 0,with_facets: bool = False,with_summary: bool = False,+ row_decisions: bool = False,+ scoped_facets: bool = False,+ area_depth: int | None = None,) -> PerformancePage:"""One page and its plan links, plus whatever else the caller renders.@@ -106,9 +118,13 @@ class PerformanceHealthService:every open opportunity, which is the only way to report the counts afilter control needs. It stays a single indexed aggregate over a tablethat already holds one row per cause rather than one per observation.++ ``scoped_facets`` counts every facet inside the query's own scope+ (its default-queue verdict and default states included), so the counts+ sum to the rows; the agent surface keeps the unscoped counts."""judged = not (- query.default_queue+ (query.default_queue or query.queue)and await any_unjudged(self._session, self._repository_id, "causes"))rows, total = await list_performance_opportunities(@@ -124,7 +140,12 @@ class PerformanceHealthService:evidence = await self._evidence_for(rows, evidence_per_item)items = [{- **serialize(row, links[row.opportunity_id], summary=query.view == "summary"),+ **serialize(+ row,+ links[row.opportunity_id],+ summary=query.view == "summary",+ decisions=row_decisions,+ ),**(evidence_block(evidence.get(row.opportunity_id, []), row.observations_total, 0@@ -136,12 +157,23 @@ class PerformanceHealthService:for row in rows]emitted = query.offset + len(items)+ facets: dict[str, list[dict[str, Any]]] = {}+ scopes: dict[str, int] = {}+ areas: dict[str, Any] = {}+ if with_facets and scoped_facets:+ facets, scopes, areas = await self._scoped_facets(+ query, judged=judged, area_depth=area_depth+ )+ elif with_facets:+ facets = await self._facets(query)return PerformancePage(items=items,total=total,offset=query.offset,next_offset=emitted if emitted < total else None,- facets=await self._facets(query) if with_facets else {},+ facets=facets,+ scopes=scopes,+ areas=areas,summary=await self.summary(query.contexts) if with_summary else {},counts=(await unit_counts(@@ -186,6 +218,46 @@ class PerformanceHealthService:links[row.opportunity_id] = plan_link(row, plan, public_id)return links+ async def _scoped_facets(+ self, query: PerformanceQuery, *, judged: bool, area_depth: int | None = None+ ) -> tuple[dict[str, list[dict[str, Any]]], dict[str, int], dict[str, Any]]:+ """Facets counted inside the query's scope and area, each scope's size,+ and the causes by area: one grouped aggregate and one per-file count."""+ filters = query.store_filters(judged=judged)+ grouped = await performance_facet_counts(+ self._session,+ self._repository_id,+ file_paths=query.file_paths,+ area_prefix=filters["area_prefix"],+ include_unverified=self._include_unverified,+ scoped=True,+ )+ by_file = await performance_area_counts(+ self._session,+ self._repository_id,+ include_unverified=self._include_unverified,+ **filters,+ )+ # The scope sizes describe the whole repository, so an opened area+ # does not shrink the scope control; that needs the unnarrowed groups.+ whole = (+ grouped+ if query.area is None+ else await performance_facet_counts(+ self._session,+ self._repository_id,+ file_paths=query.file_paths,+ include_unverified=self._include_unverified,+ scoped=True,+ )+ )+ queue_judged = not await any_unjudged(self._session, self._repository_id, "causes")+ return (+ fold_scoped_facets(grouped, query, judged=judged),+ scope_counts(whole, judged=queue_judged),+ area_facet(by_file, base=query.area, depth=area_depth),+ )+async def _facets(self, query: PerformanceQuery) -> dict[str, list[dict[str, Any]]]:"""Counts per filter value, each cross-filtered by the *other* filters."""grouped = await performance_facet_counts(diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 9a1b0b6e2..1c198b393 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -642,9 +642,17 @@ export type PerformanceOpportunityQuery = {boundary?: string;/** Evidence confidence, requested apart from fix safety and actionability. */confidence?: PerformanceOpportunityConfidence;- actionability?: PerformanceActionabilityState;- /** Absent means `proven`; `unproven` lists the causes the default queue leaves out. */- proof?: PerformanceCostProof;+ /** Absent means the default queue's states; `all` lifts them. */+ actionability?: PerformanceActionabilityState | "all";+ /** Absent means `proven`; `unproven` lists the causes the default queue leaves out;+ * `all` lifts the proof filter. */+ proof?: PerformanceCostProof | "all";+ /** Keep to the default queue's stored verdict whatever state is chosen (REST only). */+ queue?: boolean;+ /** One area (a directory) at any depth (REST only). */+ area?: string;+ /** Group the area facet at this directory depth; absent lets the server choose (REST only). */+ area_depth?: number;/** Absent means every role but startup, cli, ui, tooling and test; `all` lists every role. */role?: PerformanceExecutionRole | "all";/** `summary` drops the explanatory fields and keeps identity and counts. */@@ -717,9 +725,38 @@ export interface PerformanceOpportunitySummary {gated?: GatedByLanguage;}+/** The dashboard's three scopes: the default queue, every production cause, everything. */+export type PerformanceScope = "now" | "production" | "all";++/** One area of the queried causes, with its actionability split. */+export interface PerformanceAreaFacetEntry {+ area: string;+ total: number;+ /** The opened area's (or the root's) own files: opening it again narrows nothing. */+ own?: boolean;+ actionability: Partial<Record<PerformanceActionabilityState, number>>;+}++/** The queried causes by area, over the whole scope and filters, not one page. */+export interface PerformanceAreaFacet {+ /** The directory depth the areas are drawn at. */+ depth: number;+ /** Ranked by plan-ready causes, then advisory, then size. */+ items: PerformanceAreaFacetEntry[];+ /** Causes in areas past the response's limit. */+ more: number;+ total: number;+}+export interface PerformanceOpportunityPage extends Paginated<PerformanceOpportunity> {summary: PerformanceOpportunitySummary;+ /** Counted inside the requested scope and filters on the REST queue, so a+ * facet with no own selection sums to `total`. */facets: PerformanceFacets;+ /** Causes per scope, unfiltered. Absent from a server that predates scopes. */+ scopes?: Partial<Record<PerformanceScope, number>>;+ /** The causes by area. Absent from a server that predates it. */+ areas?: PerformanceAreaFacet;/** What a language gate held back, by language. Empty or absent when nothing was. */gated?: GatedByLanguage;/** Filter values the server did not recognize, named rather than dropped. */diff --git a/packages/ui/__tests__/health/context-tabs.test.tsx b/packages/ui/__tests__/health/context-tabs.test.tsxdeleted file mode 100644index f9ad2798a..000000000--- a/packages/ui/__tests__/health/context-tabs.test.tsx+++ /dev/null@@ -1,80 +0,0 @@-/**- * The "All" tab in ContextTabs.- *- * total (repository_total) and facets.context are counted over two- * different scopes: the former never narrows, the latter is cross-filtered by- * every other active selection. Badging "All" with the sum of the context- * facet keeps the row internally consistent -- the number on the button a- * user presses has to match what pressing it returns. The fallback to- * total exists only for a server that predates context scoping and sends- * no facets.context at all.- */-import { describe, expect, it } from "vitest";-import { render, screen } from "@testing-library/react";-import { ContextTabs } from "../../src/health/performance/filters.js";-import type { PerformanceFacets } from "@repowise-dev/types/health";--const scopedCounts = [- { value: "production", total: 22 },- { value: "tooling", total: 5 },- { value: "test", total: 12 },- { value: "unknown", total: 1 },-];--describe("ContextTabs -- the All badge", () => {- it("equals the sum of the context facet when another filter has narrowed it", () => {- render(- <ContextTabs- value="all"- facets={{ context: scopedCounts } as unknown as PerformanceFacets}- total={743}- collapsed={false}- onChange={() => {}}- />,- );- expect(screen.getByText("40")).toBeInTheDocument();- expect(screen.queryByText("743")).not.toBeInTheDocument();- });-- it("still adds tooling into production's badge when collapsed", () => {- render(- <ContextTabs- value="all"- facets={{ context: scopedCounts } as unknown as PerformanceFacets}- total={743}- collapsed- onChange={() => {}}- />,- );- expect(screen.getByText("40")).toBeInTheDocument();- expect(screen.getByText("Production & tooling")).toBeInTheDocument();- expect(screen.getByText("27")).toBeInTheDocument();- });-- it("falls back to repositoryTotal when the server sends no facets.context", () => {- render(- <ContextTabs- value="all"- facets={{} as unknown as PerformanceFacets}- total={743}- collapsed={false}- onChange={() => {}}- />,- );- expect(screen.getByText("743")).toBeInTheDocument();- });-- it("reads zero, not the unscoped total, when the facet is present but empty", () => {- render(- <ContextTabs- value="all"- facets={{ context: [] } as unknown as PerformanceFacets}- total={743}- collapsed={false}- onChange={() => {}}- />,- );- expect(screen.getByRole("tab", { name: /All 0/ })).toBeInTheDocument();- expect(screen.queryByText("743")).not.toBeInTheDocument();- });-});diff --git a/packages/ui/__tests__/health/fixtures/performance-wire-contract.json b/packages/ui/__tests__/health/fixtures/performance-wire-contract.jsonindex f63af3d79..237cf70bb 100644--- a/packages/ui/__tests__/health/fixtures/performance-wire-contract.json+++ b/packages/ui/__tests__/health/fixtures/performance-wire-contract.json@@ -1,9 +1,11 @@{"page": [+ "areas","facets","has_more","items","next_offset",+ "scopes","summary","total"],diff --git a/packages/ui/__tests__/health/fixtures/performance.ts b/packages/ui/__tests__/health/fixtures/performance.tsindex 4473211ce..19dc14526 100644--- a/packages/ui/__tests__/health/fixtures/performance.ts+++ b/packages/ui/__tests__/health/fixtures/performance.ts@@ -173,6 +173,13 @@ export function page(overrides: Partial<PerformanceOpportunityPage> = {}): Perfohas_more: true,next_offset: 3,facets: facets(),+ scopes: { now: 7, production: 10, all: 13 },+ areas: {+ depth: 1,+ total: 7,+ more: 0,+ items: [{ area: "src", total: 7, actionability: { investigate: 4, advisory: 2, plan_ready: 1 } }],+ },summary: {status: "current",total: 7,diff --git a/packages/ui/__tests__/health/performance-area-prompt.test.ts b/packages/ui/__tests__/health/performance-area-prompt.test.tsnew file mode 100644index 000000000..862f8ae00--- /dev/null+++ b/packages/ui/__tests__/health/performance-area-prompt.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from "vitest";++import { buildPerformanceAreaPrompt } from "../../src/health/ai-prompts/performance-area-prompt";+import { opportunity } from "./fixtures/performance";++const PAGED_NOTE = "later pages may hold more in this area";++describe("buildPerformanceAreaPrompt", () => {+ it("says the area's causes come from one page when the queue runs past it", () => {+ const opportunities = [opportunity({ opportunity_id: "a", file_path: "pkg/a/x.py" })];+ expect(buildPerformanceAreaPrompt({ area: "pkg/a", opportunities, paged: true })).toContain(PAGED_NOTE);+ expect(buildPerformanceAreaPrompt({ area: "pkg/a", opportunities })).not.toContain(PAGED_NOTE);+ });+});diff --git a/packages/ui/__tests__/health/performance-grouping.test.ts b/packages/ui/__tests__/health/performance-grouping.test.tsnew file mode 100644index 000000000..e7fb5c907--- /dev/null+++ b/packages/ui/__tests__/health/performance-grouping.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from "vitest";++import {+ actionabilityCounts,+ areaGroups,+ countsFromFacet,+ excludedReviews,+ facetAreaGroups,+} from "../../src/health/performance/grouping";+import { scopeAccount } from "../../src/health/performance/scope";+import { verdictOf } from "../../src/health/performance/verdict";+import { opportunity } from "./fixtures/performance";++const at = (id: string, file_path: string, state: "plan_ready" | "advisory" | "investigate", rank: number) =>+ opportunity({ opportunity_id: id, file_path, actionability_state: state, rank_position: rank });++const items = [+ at("a", "pkg/core/a.py", "advisory", 0),+ at("b", "pkg/server/b.py", "plan_ready", 1),+ at("c", "pkg/core/c.py", "advisory", 2),+ at("d", "pkg/web/d.py", "investigate", 3),+];++describe("performance grouping", () => {+ it("counts the loaded result by actionability", () => {+ expect(actionabilityCounts(items)).toEqual({ plan_ready: 1, advisory: 2, investigate: 1, expected: 0 });+ });++ it("reads the server's actionability facet as counts", () => {+ expect(countsFromFacet([{ value: "advisory", total: 4 }, { value: "bogus", total: 1 }])).toEqual({+ plan_ready: 0,+ advisory: 4,+ investigate: 0,+ expected: 0,+ });+ expect(countsFromFacet(undefined).advisory).toBe(0);+ });++ it("ranks areas by plan-ready, then advisory, keeping the server order inside", () => {+ const groups = areaGroups(items);+ expect(groups.map((g) => g.area)).toEqual(["pkg/server", "pkg/core", "pkg/web"]);+ expect(groups[1]!.items.map((i) => i.opportunity_id)).toEqual(["a", "c"]);+ });++ it("draws every area the server counts, holding the loaded causes at its depth", () => {+ const groups = facetAreaGroups(items, {+ depth: 2,+ total: 40,+ more: 0,+ items: [+ { area: "pkg/server", total: 10, actionability: { plan_ready: 1, expected: 9 } },+ { area: "pkg/core", total: 25, actionability: { advisory: 25 } },+ { area: "pkg/lib", total: 5, actionability: { investigate: 5 } },+ ],+ });+ expect(groups.map((g) => [g.area, g.total, g.items.length])).toEqual([+ ["pkg/server", 10, 1],+ ["pkg/core", 25, 2],+ // Counted by the server though no loaded cause sits in it.+ ["pkg/lib", 5, 0],+ ]);+ expect(groups[0]!.counts).toEqual({ plan_ready: 1, advisory: 0, investigate: 0, expected: 9 });+ });++ it("turns left-out counts into review links with the scope that lists them", () => {+ const reviews = excludedReviews({ test: 5, unmeasured_cost: 9, cold_path: 0, no_strategy: 2 });+ expect(reviews.map((r) => [r.reason, r.count])).toEqual([+ ["unmeasured_cost", 9],+ ["test", 5],+ ["no_strategy", 2],+ ]);+ expect(reviews[0]!.patch).toEqual({ scope: "production", proof: "unproven" });+ expect(reviews[1]!.patch).toEqual({ scope: "all", context: "test" });+ expect(reviews[2]!.patch).toEqual({ scope: "production", actionability: "investigate" });+ expect(excludedReviews(undefined)).toEqual([]);+ });++ it("leads with the scope's own count, named for the scope", () => {+ const groups = areaGroups(items);+ expect(verdictOf("now", 4, groups)).toEqual({+ value: 4,+ unit: "changes worth making now",+ areas: "Across 3 areas, led by pkg/server.",+ });+ expect(verdictOf("production", 1, groups.slice(0, 1)).unit).toBe("production cause");+ expect(verdictOf("all", 938, []).areas).toBeNull();+ });+});++describe("scope accounting", () => {+ const counts = { now: 4, production: 430, all: 938 };++ it("accounts for every hidden cause from the default queue", () => {+ expect(scopeAccount("now", counts)).toEqual([+ { count: 4, text: "worth doing now", scope: null },+ { count: 426, text: "more production causes are not ready to act on", scope: "production" },+ { count: 508, text: "are outside production code", scope: "all" },+ ]);+ });++ it("names the scope first and links the others", () => {+ expect(scopeAccount("production", counts).map((c) => [c.count, c.scope])).toEqual([+ [430, null],+ [4, "now"],+ [508, "all"],+ ]);+ expect(scopeAccount("all", counts).map((c) => [c.count, c.scope])).toEqual([+ [938, null],+ [430, "production"],+ [4, "now"],+ ]);+ });++ it("drops a clause with nothing behind it, but never the scope's own", () => {+ expect(scopeAccount("now", { now: 0, production: 0, all: 3 })).toEqual([+ { count: 0, text: "worth doing now", scope: null },+ { count: 3, text: "are outside production code", scope: "all" },+ ]);+ });+});diff --git a/packages/ui/__tests__/health/performance-presentation.test.ts b/packages/ui/__tests__/health/performance-presentation.test.tsindex ffe2bc5bc..cb54e13da 100644--- a/packages/ui/__tests__/health/performance-presentation.test.ts+++ b/packages/ui/__tests__/health/performance-presentation.test.ts@@ -15,7 +15,6 @@ import {whyRankedLabel,whyRankedPhrase,} from "../../src/health/performance/presentation";-import { contiguousSections } from "../../src/health/performance/queue";import { opportunity } from "./fixtures/performance";describe("performance presentation", () => {@@ -154,40 +153,6 @@ describe("performance presentation", () => {});});-describe("queue sections", () => {- it("splits the page into runs without moving a single row", () => {- const items = [- opportunity({ opportunity_id: "a", actionability_state: "plan_ready" }),- opportunity({ opportunity_id: "b", actionability_state: "advisory" }),- opportunity({ opportunity_id: "c", actionability_state: "advisory" }),- opportunity({ opportunity_id: "d", actionability_state: "investigate" }),- ];- const sections = contiguousSections(items);- expect(sections.map((s) => s.state)).toEqual(["plan_ready", "advisory", "investigate"]);- expect(sections.flatMap((s) => s.items.map((i) => i.opportunity_id))).toEqual([- "a",- "b",- "c",- "d",- ]);- });-- it("keeps an interleaved order intact rather than regrouping it", () => {- const items = [- opportunity({ opportunity_id: "a", actionability_state: "advisory" }),- opportunity({ opportunity_id: "b", actionability_state: "investigate" }),- opportunity({ opportunity_id: "c", actionability_state: "advisory" }),- ];- const sections = contiguousSections(items);- expect(sections).toHaveLength(3);- expect(sections.flatMap((s) => s.items.map((i) => i.opportunity_id))).toEqual(["a", "b", "c"]);- });-- it("returns nothing for an empty page", () => {- expect(contiguousSections([])).toEqual([]);- });-});-describe("module scope", () => {it("reads `<file>::__module__` as the module scope of that file", () => {expect(moduleScopeLabel("src/jobs.py::__module__")).toBe("module scope of src/jobs.py");diff --git a/packages/ui/__tests__/health/performance-query.test.ts b/packages/ui/__tests__/health/performance-query.test.tsindex 67bb110e9..41a25fc65 100644--- a/packages/ui/__tests__/health/performance-query.test.ts+++ b/packages/ui/__tests__/health/performance-query.test.ts@@ -4,105 +4,173 @@ import {clearNarrowing,INITIAL_FILTERS,narrowingCount,- parseFilters,- serializeFilters,+ narrowingKeysFor,+ parseLegacyFilters,+ readFilters,+ serverKey,toQuery,withFilter,+ withScope,+ writeFilters,+ type PerformanceFilterState,} from "../../src/health/performance/query";-describe("performance filter state", () => {- it("serializes only what differs from the default, and always the context", () => {- // Context is written even at its default so a shared link keeps meaning- // the context it was shared in, whatever the default becomes later.- expect(serializeFilters(INITIAL_FILTERS)).toBe("context=production");- const narrowed = withFilter(withFilter(INITIAL_FILTERS, "context", "all"), "boundary", "db");- expect(serializeFilters(narrowed)).toBe("context=all&boundary=db");+const write = (state: PerformanceFilterState, base = "") => {+ const params = new URLSearchParams(base);+ writeFilters(state, params);+ return params;+};++const read = (search: string) => readFilters(new URLSearchParams(search));++describe("performance scope and its URL", () => {+ it("writes the scope always and every other default never", () => {+ expect(write(INITIAL_FILTERS).toString()).toBe("scope=now");+ const state = withFilter(withScope(INITIAL_FILTERS, "all"), "boundary", "db");+ expect(write(state).toString()).toBe("scope=all&boundary=db");});- it("round trips every field through a query string", () => {- const state = {- context: "test" as const,+ it("round trips every field and leaves the page's own parameters alone", () => {+ const state: PerformanceFilterState = {+ scope: "all",+ context: "test",boundary: "filesystem",- confidence: "high" as const,- actionability: "plan_ready" as const,- proof: "unproven" as const,- role: "cli" as const,- sort: "leverage" as const,- offset: 40,+ confidence: "high",+ actionability: "advisory",+ proof: "unproven",+ role: "cli",+ sort: "leverage",+ page: 3,+ area: "packages/core",+ depth: 4,};- expect(parseFilters(serializeFilters(state))).toEqual(state);+ const params = write(state, "tab=performance&opportunity=perf1");+ expect(params.get("tab")).toBe("performance");+ expect(params.get("opportunity")).toBe("perf1");+ expect(readFilters(params)).toEqual(state);});- it("asks for unproven causes only when chosen", () => {- // Absent means the server's default: causes whose cost is measured.- expect(toQuery(INITIAL_FILTERS, { limit: 20 }).proof).toBeUndefined();- const unproven = withFilter(INITIAL_FILTERS, "proof", "unproven");- expect(toQuery(unproven, { limit: 20 }).proof).toBe("unproven");- expect(narrowingCount(unproven)).toBe(1);- expect(clearNarrowing(unproven).proof).toBeNull();+ it("keeps the root area, the empty string, through the URL", () => {+ const params = write({ ...INITIAL_FILTERS, area: "" });+ expect(params.has("area")).toBe(true);+ expect(readFilters(params).area).toBe("");});- it("asks for a cold role only when chosen", () => {- // Absent means the server's default: every role but startup, CLI, tooling and test.- expect(toQuery(INITIAL_FILTERS, { limit: 20 }).role).toBeUndefined();- const cli = withFilter(INITIAL_FILTERS, "role", "cli");- expect(toQuery(cli, { limit: 20 }).role).toBe("cli");- expect(narrowingCount(cli)).toBe(1);- expect(clearNarrowing(cli).role).toBeNull();+ it("removes the retired parameters on write", () => {+ const params = write(INITIAL_FILTERS, "perf=context%3Dtest&ctx=all&state=advisory&page=4");+ for (const key of ["perf", "ctx", "state", "page"]) expect(params.has(key)).toBe(false);});- it("round trips the expected actionability state", () => {- // expected sits out of the default queue but is still a real, selectable- // state: the round trip must not treat it as unrecognized.- const state = { ...INITIAL_FILTERS, actionability: "expected" as const };- expect(parseFilters(serializeFilters(state))).toEqual(state);+ it("maps a link minted before scopes onto the scope that lists the same causes", () => {+ expect(read("ctx=production").scope).toBe("now");+ expect(read("ctx=production&proof=unproven")).toMatchObject({+ scope: "production",+ proof: "unproven",+ });+ expect(read("ctx=production&state=investigate")).toMatchObject({+ scope: "production",+ actionability: "investigate",+ });+ expect(read("ctx=production&role=all")).toMatchObject({ scope: "production", role: null });+ expect(read("ctx=test")).toMatchObject({ scope: "all", context: "test" });+ expect(read("ctx=all")).toMatchObject({ scope: "all", context: null });+ expect(read("perf=context%3Dtooling%26offset%3D240")).toMatchObject({+ scope: "all",+ context: "tooling",+ page: 3,+ });+ expect(parseLegacyFilters("context=production&boundary=db")).toMatchObject({+ scope: "now",+ boundary: "db",+ });});it("drops a value the vocabulary does not contain instead of forwarding it", () => {- const parsed = parseFilters("context=production_tooling&actionability=nonsense&offset=-3");- expect(parsed.context).toBe("production");+ const parsed = read("scope=bogus&actionability=nonsense&page=-3");+ expect(parsed.scope).toBe("now");expect(parsed.actionability).toBeNull();- expect(parsed.offset).toBe(0);+ expect(parsed.page).toBe(1);+ // Proof and role cannot narrow "now", whose causes are all measured and served.+ expect(read("scope=now&proof=unproven&context=test")).toMatchObject({ proof: null, context: null });+ // "Worth doing now" holds plan-ready and advisory causes only.+ expect(read("scope=now&actionability=investigate").actionability).toBeNull();+ expect(read("scope=now&actionability=advisory").actionability).toBe("advisory");+ });+});++describe("performance scope queries", () => {+ it("asks for the default queue in 'now', and keeps a chosen state inside it", () => {+ expect(toQuery(INITIAL_FILTERS, { limit: 100 })).toEqual({+ context: "production",+ view: "summary",+ sort: "rank",+ limit: 100,+ offset: 0,+ });+ const advisory = toQuery({ ...INITIAL_FILTERS, actionability: "advisory" }, { limit: 100 });+ expect(advisory).toMatchObject({ actionability: "advisory", queue: true });});- it("returns to the first page when a filter narrows, and holds it when paging", () => {- const paged = withFilter(INITIAL_FILTERS, "offset", 20);- expect(paged.offset).toBe(20);- expect(withFilter(paged, "boundary", "db").offset).toBe(0);- expect(withFilter(paged, "offset", 40).offset).toBe(40);+ it("lifts every default in 'production' and 'all'", () => {+ const production = toQuery(withScope(INITIAL_FILTERS, "production"), { limit: 100 });+ expect(production).toMatchObject({+ context: "production",+ actionability: "all",+ proof: "all",+ role: "all",+ });+ expect(production.queue).toBeUndefined();+ const everything = toQuery(withScope(INITIAL_FILTERS, "all", { context: "test" }), { limit: 100 });+ expect(everything).toMatchObject({ context: "test", actionability: "all" });+ expect(toQuery(withScope(INITIAL_FILTERS, "all"), { limit: 100 }).context).toBe("all");+ expect(toQuery({ ...INITIAL_FILTERS, page: 3 }, { limit: 100 }).offset).toBe(200);});- it("sends canonical contexts, and the retired pairing only when told to collapse", () => {- const production = withFilter(INITIAL_FILTERS, "context", "production");- expect(toQuery(production, { limit: 20 }).context).toBe("production");- expect(toQuery(production, { limit: 20, collapseContexts: true }).context).toBe(+ it("sends the retired pairing only when told to collapse", () => {+ expect(toQuery(INITIAL_FILTERS, { limit: 20, collapseContexts: true }).context).toBe("production_tooling",);- const test = withFilter(INITIAL_FILTERS, "context", "test");- expect(toQuery(test, { limit: 20, collapseContexts: true }).context).toBe("test");- const unknown = withFilter(INITIAL_FILTERS, "context", "unknown");- expect(toQuery(unknown, { limit: 20 }).context).toBe("unknown");});+});- it("omits a narrowing parameter that is not set rather than sending an empty one", () => {- const query = toQuery(INITIAL_FILTERS, { limit: 20 });- expect(query).toEqual({- context: "production",- view: "detail",- sort: "rank",- limit: 20,- offset: 0,+describe("performance state changes", () => {+ it("returns to the first page on any filter, the area included, and resets depth with it", () => {+ const viewed = { ...INITIAL_FILTERS, page: 2, area: "src", depth: 3 };+ expect(withFilter(viewed, "boundary", "db")).toMatchObject({ page: 1, area: "src", boundary: "db" });+ expect(withFilter(viewed, "area", "src/a")).toMatchObject({ page: 1, area: "src/a", depth: null });+ expect(withFilter(viewed, "page", 3).area).toBe("src");+ expect(toQuery(viewed, { limit: 100 })).toMatchObject({ area: "src", area_depth: 3 });+ });++ it("keeps the filters a new scope can narrow by, and drops the state", () => {+ const state: PerformanceFilterState = {+ ...withScope(INITIAL_FILTERS, "all"),+ context: "test",+ boundary: "db",+ proof: "unproven",+ actionability: "expected",+ };+ expect(withScope(state, "production")).toMatchObject({+ scope: "production",+ context: null,+ boundary: "db",+ proof: "unproven",+ actionability: null,});- expect("boundary" in query).toBe(false);+ expect(withScope(state, "now")).toMatchObject({ boundary: "db", proof: null });+ expect(narrowingKeysFor("now")).toEqual(["boundary", "confidence"]);+ });++ it("keys the server query on every field, the area included", () => {+ expect(serverKey({ ...INITIAL_FILTERS, area: "src" })).not.toBe(serverKey(INITIAL_FILTERS));+ expect(serverKey(withScope(INITIAL_FILTERS, "production"))).not.toBe(serverKey(INITIAL_FILTERS));});- it("counts and clears the narrowing filters without touching context", () => {- let state = withFilter(INITIAL_FILTERS, "context", "test");- state = withFilter(state, "boundary", "db");- state = withFilter(state, "actionability", "advisory");+ it("counts and clears the narrowing, the state included, without leaving the scope", () => {+ const state = { ...withScope(INITIAL_FILTERS, "all"), boundary: "db", actionability: "advisory" as const };expect(narrowingCount(state)).toBe(2);const cleared = clearNarrowing(state);expect(narrowingCount(cleared)).toBe(0);- expect(cleared.context).toBe("test");+ expect(cleared.scope).toBe("all");});});diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsxindex 79033f29a..d76338066 100644--- a/packages/ui/__tests__/health/performance-view.test.tsx+++ b/packages/ui/__tests__/health/performance-view.test.tsx@@ -1,8 +1,7 @@-import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";-import { describe, expect, it, vi } from "vitest";+import { configure, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import { beforeAll, describe, expect, it, vi } from "vitest";import type { RefactoringPlan } from "@repowise-dev/types/refactoring";-import { ScopeLine } from "../../src/health/performance/filters";import { PerformanceView } from "../../src/health/performance-view";import {adapter,@@ -13,7 +12,20 @@ import {sibling,} from "./fixtures/performance";-const rows = () => screen.findAllByRole("listitem");+// The drawer and the prompt modal load on first open, which takes longer than+// the default second when the suite runs beside others.+configure({ asyncUtilTimeout: 5000 });+// Load the lazy chunks once up front, so no single test pays the first import.+beforeAll(async () => {+ await import("../../src/health/performance/drawer");+ await import("../../src/health/ai-prompt-modal");+});++/** The cause rows, not the chips or other list items on the page. */+const rows = async () =>+ (await screen.findAllByRole("listitem")).filter((li) =>+ li.hasAttribute("data-performance-opportunity"),+ );const openFirstRow = async () => {const [first] = await rows();fireEvent.click(first!);@@ -26,121 +38,235 @@ function expand(panel: HTMLElement, name: string | RegExp) {}describe("PerformanceView queue", () => {- it("leads with the canonical rollup rather than flat context counters", async () => {+ it("leads with the scope's own count and accounts for what the scope leaves out", async () => {render(<PerformanceView adapter={adapter()} />);- expect(await screen.findByText("Causal opportunities")).toBeTruthy();- expect(screen.getByText("a named safe intervention")).toBeTruthy();- expect(screen.getByText("read the evidence first")).toBeTruthy();- expect(screen.getByText("of 7 causes")).toBeTruthy();+ expect(await screen.findByText("changes worth making now")).toBeTruthy();+ expect(screen.getByText(/All in src\./)).toBeTruthy();+ // Every hidden cause is named, with a link to the scope that lists it.+ expect(screen.getByRole("button", { name: "3 more production causes are not ready to act on" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "3 are outside production code" })).toBeTruthy();});- it("keeps the four canonical contexts separate and counts them from the facets", async () => {+ it("offers one scope control, counted by the server", async () => {render(<PerformanceView adapter={adapter()} />);await rows();- expect(screen.getByRole("tab", { name: /Production 4/ })).toBeTruthy();- expect(screen.getByRole("tab", { name: /Tooling 1/ })).toBeTruthy();- expect(screen.getByRole("tab", { name: /Test suite 2/ })).toBeTruthy();- // Absent from the facets, so it counts zero and still gets its own tab.- expect(screen.getByRole("tab", { name: /Unclassified 0/ })).toBeTruthy();+ const scope = screen.getByRole("radiogroup", { name: "Scope" });+ expect(within(scope).getByRole("radio", { name: /Worth doing now 7/ })).toBeTruthy();+ expect(within(scope).getByRole("radio", { name: /All production 10/ })).toBeTruthy();+ expect(within(scope).getByRole("radio", { name: /Everything 13/ })).toBeTruthy();+ expect(screen.queryByRole("tab", { name: /Tooling/ })).toBeNull();});- it("asks the server for a canonical context and never the retired pairing", async () => {+ it("asks for each scope's causes, and moves to a scope from its sentence", async () => {const load = vi.fn(async () => page());render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);- fireEvent.click(await screen.findByRole("tab", { name: /Tooling 1/ }));+ await rows();+ expect(load).toHaveBeenLastCalledWith({+ context: "production",+ view: "summary",+ sort: "rank",+ limit: 100,+ offset: 0,+ });+ fireEvent.click(screen.getByRole("button", { name: "3 are outside production code" }));await waitFor(() =>- expect(load).toHaveBeenLastCalledWith({- context: "tooling",- view: "detail",- sort: "rank",- limit: 20,- offset: 0,- }),+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "all", actionability: "all", proof: "all", role: "all" }),+ ),);});- it("builds the narrowing filters from the server facets and refetches on change", async () => {+ it("offers the rest of production at the end of the queue worth doing now", async () => {const load = vi.fn(async () => page());render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);await rows();+ fireEvent.click(screen.getByRole("button", { name: "Show the 3 other production causes" }));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "production", actionability: "all" }),+ ),+ );+ });++ it("keeps the narrowing filters behind More filters and shows each active one as a chip", async () => {+ const load = vi.fn(async () => page());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ await rows();+ expect(screen.queryByLabelText("Boundary")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /More filters/ }));const boundary = screen.getByLabelText("Boundary");expect(within(boundary).getByRole("option", { name: "Database (4)" })).toBeTruthy();- expect(within(boundary).getByRole("option", { name: "In-process (1)" })).toBeTruthy();+ // Actionability has one control, the bar, not a second select here.+ expect(screen.queryByRole("combobox", { name: "Actionability" })).toBeNull();fireEvent.change(boundary, { target: { value: "db" } });await waitFor(() =>expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ boundary: "db" })),);+ const chip = await screen.findByRole("button", { name: "Remove filter Boundary: Database" });+ fireEvent.click(chip);+ await waitFor(() =>+ expect(screen.queryByRole("button", { name: /Remove filter Boundary/ })).toBeNull(),+ );});- it("labels the actionability select's empty option as excluding expected", async () => {+ it("states a facet with one value instead of offering a control that cannot narrow", async () => {render(<PerformanceView adapter={adapter()} />);await rows();- const actionability = screen.getByLabelText("Actionability");- expect(within(actionability).getByRole("option", { name: "All but expected" })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: /More filters/ }));+ expect(screen.queryByLabelText("Evidence confidence")).toBeNull();+ // Label and value only; counts belong to a select's options.+ expect(screen.getByText(/Evidence confidence:/)).toBeTruthy();+ expect(screen.queryByText(/matching/)).toBeNull();});- it("states a facet with one value instead of offering a control that cannot narrow", async () => {- render(<PerformanceView adapter={adapter()} />);+ it("draws the actionability bar from the server's counts and narrows on the server", async () => {+ const load = vi.fn(async () => page());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);await rows();- expect(screen.queryByLabelText("Evidence confidence")).toBeNull();- expect(screen.getByText("on 7 matching")).toBeTruthy();+ const bar = screen.getByRole("radiogroup", { name: "Actionability" });+ // The facet counts, which sum to the lede, not the three loaded rows.+ expect(within(bar).getByRole("radio", { name: /All 7/ })).toBeTruthy();+ expect(within(bar).getByRole("radio", { name: /Needs investigation 4/ })).toBeTruthy();+ fireEvent.click(within(bar).getByRole("radio", { name: /Plan ready 1/ }));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ actionability: "plan_ready", queue: true }),+ ),+ );});- it("states the rendered scope, the filtered total, and the repository total", async () => {- render(<PerformanceView adapter={adapter()} />);- // The per-page range belongs to the pagination control; this states what- // the selection covers and when it was computed, and says each once.- expect(await screen.findByText(/Showing/)).toBeTruthy();- const scope = screen- .getAllByRole("status")- .map((node) => node.textContent ?? "")- .find((text) => text.includes("opportunities"));- expect(scope).toContain("7 production opportunities");- expect(scope).toContain("848a8f1");- });-- it("groups the page into actionability sections without reordering it", async () => {- render(<PerformanceView adapter={adapter()} />);- const items = await rows();- expect(items).toHaveLength(3);- expect(screen.getAllByText("1 matching").length).toBeGreaterThan(0);- const headings = screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent ?? "");- expect(headings[0]).toContain("Plan ready");- expect(headings[1]).toContain("Advisory");- expect(headings[2]).toContain("Needs investigation");+ it("draws every area the server counts, with true totals and its top causes", async () => {+ const items = [+ opportunity({ opportunity_id: "a", file_path: "pkg/a/x.py", actionability_state: "advisory", rank_position: 0 }),+ opportunity({ opportunity_id: "b", file_path: "pkg/b/y.py", actionability_state: "plan_ready", rank_position: 1 }),+ ];+ const smallTop = opportunity({ opportunity_id: "c", file_path: "pkg/c/z.py", rank_position: 9 });+ const load = vi.fn(async (query?: { area?: string; limit?: number }) =>+ query?.area === "pkg/c"+ ? page({ items: [smallTop], total: 4, next_offset: null })+ : page({+ items,+ total: 10,+ next_offset: null,+ areas: {+ depth: 2,+ total: 10,+ more: 0,+ items: [+ { area: "pkg/b", total: 1, actionability: { plan_ready: 1 } },+ { area: "pkg/a", total: 5, actionability: { advisory: 5 } },+ { area: "pkg/c", total: 4, actionability: { investigate: 4 } },+ ],+ },+ }),+ );+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ await rows();+ const areas = screen.getAllByRole("region").map((node) => node.getAttribute("aria-label"));+ expect(areas.filter((a) => a?.startsWith("pkg/"))).toEqual([+ "pkg/b, 1 causes",+ "pkg/a, 5 causes",+ "pkg/c, 4 causes",+ ]);+ expect(screen.getByText(/Across 3 areas, led by pkg\/b\./)).toBeTruthy();+ // pkg/c has no loaded cause, so its card asks for its own top three.+ await waitFor(() =>+ expect(load).toHaveBeenCalledWith(expect.objectContaining({ area: "pkg/c", limit: 3 })),+ );+ expect(await screen.findByText(/Show all 5 in pkg\/a/)).toBeTruthy();+ // No page caveat: the counts are the scope's own.+ expect(screen.queryByText(/causes on this page/)).toBeNull();+ });++ it("opens an area on the server when a card asks to show all", async () => {+ const load = vi.fn(async () =>+ page({+ areas: {+ depth: 1,+ total: 7,+ more: 0,+ items: [+ { area: "src", total: 6, actionability: { advisory: 6 } },+ { area: "lib", total: 1, actionability: { advisory: 1 } },+ ],+ },+ }),+ );+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ await rows();+ fireEvent.click(screen.getByRole("button", { name: /Show all 6 in src/ }));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ area: "src" })),+ );+ expect(await screen.findByRole("button", { name: "Remove filter Area: src" })).toBeTruthy();});- it("keeps the green mark for a plan proven safe", async () => {+ it("says the accounting sentence once, never a hidden second copy", async () => {render(<PerformanceView adapter={adapter()} />);- const items = await rows();- const dot = (li: HTMLElement) =>- (li.querySelector("[aria-hidden='true'].rounded-full") as HTMLElement | null)?.style- .backgroundColor;- expect(dot(items[0]!)).toBe("var(--color-success)");- // Advisory with a stored plan: not proven safe, so not green.- expect(dot(items[1]!)).toBe("var(--color-text-tertiary)");+ await rows();+ const text = document.body.textContent ?? "";+ expect(text.split("are outside production code").length - 1).toBe(1);+ expect(document.querySelectorAll(".sr-only p, p.sr-only").length).toBe(0);});- it("shows the cause in words, where in mono, and the sink as separate evidence", async () => {+ it("leads each row with the fix, its gain, effort and safety, and the agent prompt", async () => {render(<PerformanceView adapter={adapter()} />);const [first] = await rows();expect(within(first!).getByText(/Database call inside a loop in/)).toBeTruthy();expect(within(first!).getByText("load").tagName).toBe("CODE");- expect(within(first!).getByText("src/db.py::fetch")).toBeTruthy();+ expect(within(first!).getByText("Run the independent awaits together")).toBeTruthy();+ expect(within(first!).getByText("Proven safe")).toBeTruthy();expect(within(first!).getByText(/2 call sites across 2 files/)).toBeTruthy();- expect(within(first!).getByText(/High evidence confidence/)).toBeTruthy();+ expect(within(first!).getByRole("button", { name: "Copy prompt for your agent" })).toBeTruthy();+ expect(within(first!).getByRole("link", { name: "Open plan" })).toBeTruthy();+ // The file is one verb among the row's others, behind its menu.+ expect(within(first!).queryByRole("button", { name: "Open file" })).toBeNull();+ fireEvent.click(within(first!).getByRole("button", { name: /More actions for/ }));+ expect(await screen.findByRole("button", { name: "Open the file" })).toBeTruthy();});- it("pages with the server cursor and never filters the page on the client", async () => {- const load = vi.fn(async () => page());+ it("offers no plan link where there is no plan, and says there is no fix yet", async () => {+ render(<PerformanceView adapter={adapter()} />);+ const items = await rows();+ const last = items[items.length - 1]!;+ expect(within(last).queryByRole("link", { name: "Open plan" })).toBeNull();+ expect(within(last).getByText(/No supported fix yet/)).toBeTruthy();+ });++ it("leaves the actionability bar out when the scope holds one state", async () => {+ const one = page({+ items: [page().items[1]!],+ total: 1,+ next_offset: null,+ facets: { ...page().facets, actionability: [{ value: "advisory", total: 1 }] },+ });+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => one })} />);+ await rows();+ expect(screen.queryByRole("radiogroup", { name: "Actionability" })).toBeNull();+ });++ it("pages with the server cursor only when the result outgrows one page", async () => {+ const load = vi.fn(async () => page({ total: 250, next_offset: 100 }));render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);await rows();fireEvent.click(screen.getByRole("button", { name: /next/i }));await waitFor(() =>- expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 3 })),+ expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ offset: 100 })),);});++ it("warms a cause's detail on hover through the key the drawer reads", async () => {+ const detail = vi.fn(async () => resolvedDetail());+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: detail })} />);+ const [first] = await rows();+ fireEvent.mouseEnter(first!);+ fireEvent.mouseEnter(first!);+ await waitFor(() => expect(detail).toHaveBeenCalledTimes(1));+ fireEvent.click(first!);+ await screen.findByRole("dialog");+ expect(detail).toHaveBeenCalledTimes(1);+ });});describe("PerformanceView states", () => {@@ -166,20 +292,62 @@ describe("PerformanceView states", () => {});it("distinguishes an analyzed empty repository from an unanalyzed one", async () => {- // Empty in every context, not merely outside the one on screen, so the- // answer is that nothing was found rather than that a filter hid it.const empty = page({items: [],total: 0,has_more: false,next_offset: null,+ scopes: { now: 0, production: 0, all: 0 },summary: { ...page().summary, total: 0, repository_total: 0 },});render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => empty })} />,);- expect(await screen.findByText("No supported pattern surfaced")).toBeTruthy();- expect(screen.getByText(/does not claim the code is fast/)).toBeTruthy();+ expect(+ await screen.findByText(+ "No performance changes worth making now in production code at 848a8f1",+ ),+ ).toBeTruthy();+ expect(screen.getByText(/read code shape, not latency/)).toBeTruthy();+ });++ it("names the scope of a good state and folds the left-out reasons into its sentence", async () => {+ const load = vi.fn(async () =>+ page({+ items: [],+ total: 0,+ has_more: false,+ next_offset: null,+ scopes: { now: 0, production: 5, all: 7 },+ summary: {+ ...page().summary,+ default_queue: { total: 0, excluded: { unmeasured_cost: 5, test: 2, cold_path: 0 } },+ },+ }),+ );+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ expect(await screen.findByRole("button", { name: "5 more production causes are not ready to act on" })).toBeTruthy();+ fireEvent.click(screen.getByRole("button", { name: "Why left out?" }));+ expect(screen.queryByRole("button", { name: /run rarely/ })).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "loop size unknown" }));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "production", proof: "unproven" }),+ ),+ );+ });++ it("reads an empty scope as clean, not as a filter that failed", async () => {+ const load = vi.fn(async () =>+ page({ items: [], total: 0, has_more: false, next_offset: null, scopes: { now: 0, production: 0, all: 3 } }),+ );+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);+ expect(+ await screen.findByText(+ "No performance changes worth making now in production code at 848a8f1",+ ),+ ).toBeTruthy();+ expect(screen.queryByText("No opportunities match these filters")).toBeNull();});it("offers a way back when a filter combination matches nothing", async () => {@@ -188,12 +356,11 @@ describe("PerformanceView states", () => {);render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);await rows();+ fireEvent.click(screen.getByRole("button", { name: /More filters/ }));fireEvent.change(screen.getByLabelText("Boundary"), { target: { value: "db" } });expect(await screen.findByText("No opportunities match these filters")).toBeTruthy();fireEvent.click(screen.getByRole("button", { name: "Clear filters" }));- await waitFor(() =>- expect(load).toHaveBeenLastCalledWith(expect.objectContaining({ context: "all" })),- );+ expect(await rows()).toHaveLength(3);});it("warns that a stale model can move ids", async () => {@@ -421,8 +588,11 @@ describe("PerformanceView drawer", () => {};render(<PerformanceView adapter={adapter({ getRefactoringPlan: async () => exact })} />);await openFirstRow();- fireEvent.click(await screen.findByRole("button", { name: "Copy the plan for an agent" }));- expect(await screen.findByText("Structured plan handoff")).toBeTruthy();+ const panel = await screen.findByRole("dialog");+ fireEvent.click(within(panel).getByRole("button", { name: "Copy prompt for your agent" }));+ expect(await screen.findByText("Prompt for your agent")).toBeTruthy();+ expect(await screen.findByText(/chars, approx/)).toBeTruthy();+ expect(document.body.textContent).not.toContain("Causal performance opportunity");});it("shows the plan prompt the server renders when the host serves one", async () => {@@ -449,7 +619,8 @@ describe("PerformanceView drawer", () => {/>,);await openFirstRow();- fireEvent.click(await screen.findByRole("button", { name: "Copy the plan for an agent" }));+ const panel = await screen.findByRole("dialog");+ fireEvent.click(within(panel).getByRole("button", { name: "Copy prompt for your agent" }));expect(await screen.findByText(/served plan-1 generic/)).toBeTruthy();expect(served).toHaveBeenCalledWith("plan-1", "generic");});@@ -457,8 +628,28 @@ describe("PerformanceView drawer", () => {it("falls back to the evidence handoff when no plan was verified", async () => {render(<PerformanceView adapter={adapter()} />);await openFirstRow();- fireEvent.click(await screen.findByRole("button", { name: "Copy an agent handoff" }));- expect(await screen.findByText("Agent handoff")).toBeTruthy();+ const panel = await screen.findByRole("dialog");+ fireEvent.click(within(panel).getByRole("button", { name: "Copy prompt for your agent" }));+ expect(await screen.findByText(/Causal performance opportunity/)).toBeTruthy();+ });++ it("opens the agent prompt straight from a row, without opening the drawer", async () => {+ const served = vi.fn(async (planId: string, flavor: string) => `served ${planId} ${flavor}`);+ render(<PerformanceView adapter={adapter({ getRefactoringPlanPrompt: served })} />);+ const [first] = await rows();+ fireEvent.click(within(first!).getByRole("button", { name: "Copy prompt for your agent" }));+ // No plan fetch on this host, so the evidence handoff, and no drawer.+ expect(await screen.findByText(/Causal performance opportunity/)).toBeTruthy();+ expect(screen.queryByText("Show this cause on the map")).toBeNull();+ expect(served).not.toHaveBeenCalled();+ });++ it("hands a whole area to an agent as one prompt", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await rows();+ fireEvent.click(screen.getByRole("button", { name: "Copy prompt for these 3" }));+ expect(await screen.findByText(/Performance causes in `src`/)).toBeTruthy();+ expect(document.body.textContent).toContain("perf2_investigate");});it("rejects a stored plan whose opportunity identity does not match", async () => {@@ -819,22 +1010,6 @@ describe("PerformanceView sort control", () => {});describe("PerformanceView compatibility", () => {- it("collapses production and tooling only when the server predates the vocabulary", async () => {- const load = vi.fn(async () => legacyPage());- render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: load })} />);- await rows();- expect(screen.getByRole("tab", { name: /Production & tooling/ })).toBeTruthy();- expect(screen.queryByRole("tab", { name: /Unclassified/ })).toBeNull();- expect(screen.queryByLabelText("Boundary")).toBeNull();-- fireEvent.click(screen.getByRole("tab", { name: /Production & tooling/ }));- await waitFor(() =>- expect(load).toHaveBeenLastCalledWith(- expect.objectContaining({ context: "production_tooling" }),- ),- );- });-it("re-asks with the spelling an older server accepts when a link restored a context", async () => {const load = vi.fn(async () => legacyPage());render(@@ -891,7 +1066,7 @@ describe("PerformanceView compatibility", () => {render(<PerformanceViewadapter={adapter({ getPerformanceOpportunities: load })}- initialFilters="context=test&boundary=db"+ initialFilters="scope=all&context=test&boundary=db"onFiltersChange={onFiltersChange}/>,);@@ -900,11 +1075,59 @@ describe("PerformanceView compatibility", () => {expect.objectContaining({ context: "test", boundary: "db" }),),);- fireEvent.click(screen.getByRole("tab", { name: /Production 4/ }));+ const scope = screen.getByRole("radiogroup", { name: "Scope" });+ fireEvent.click(within(scope).getByRole("radio", { name: /All production/ }));+ await waitFor(() =>+ expect(onFiltersChange).toHaveBeenLastCalledWith(+ "scope=production&boundary=db",+ expect.objectContaining({ scope: "production", context: null, boundary: "db" }),+ ),+ );+ });++ it("reads a link minted before scopes onto the scope that lists the same causes", async () => {+ const load = vi.fn(async () => page());+ render(+ <PerformanceView+ adapter={adapter({ getPerformanceOpportunities: load })}+ initialFilters="tab=performance&ctx=all&proof=unproven&state=advisory"+ />,+ );+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "all", proof: "unproven", actionability: "advisory" }),+ ),+ );+ expect(await screen.findByRole("button", { name: "Remove filter Showing: Advisory" })).toBeTruthy();+ });++ it("follows a URL it did not write while it stays mounted", async () => {+ const load = vi.fn(async () => page());+ const a = adapter({ getPerformanceOpportunities: load });+ const view = (search: string) => (+ <PerformanceView adapter={a} initialFilters={search} onFiltersChange={() => undefined} />+ );+ const { rerender } = render(view("scope=all&context=test&boundary=db"));+ await rows();+ const scope = screen.getByRole("radiogroup", { name: "Scope" });+ fireEvent.click(within(scope).getByRole("radio", { name: /All production/ }));+ // The host echoes the view's own write beside its own parameters.+ rerender(view("tab=performance&scope=production&boundary=db"));+ await waitFor(() =>+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "production", boundary: "db" }),+ ),+ );+ // A link followed (or back) replaces the state.+ rerender(view("tab=performance&scope=all&proof=unproven"));await waitFor(() =>- expect(onFiltersChange).toHaveBeenLastCalledWith("context=production&boundary=db"),+ expect(load).toHaveBeenLastCalledWith(+ expect.objectContaining({ context: "all", proof: "unproven" }),+ ),);+ expect(load).not.toHaveBeenLastCalledWith(expect.objectContaining({ boundary: "db" }));});+});describe("PerformanceView accessibility", () => {@@ -920,17 +1143,12 @@ describe("PerformanceView accessibility", () => {it("names every filter control and the row overflow", async () => {render(<PerformanceView adapter={adapter()} />);await rows();+ fireEvent.click(screen.getByRole("button", { name: /More filters/ }));expect(screen.getByLabelText("Boundary")).toBeTruthy();- expect(screen.getByLabelText("Actionability")).toBeTruthy();+ expect(screen.getByRole("radiogroup", { name: "Actionability" })).toBeTruthy();expect(screen.getAllByRole("button", { name: /More actions for/ }).length).toBeGreaterThan(0);});- it("announces the rendered scope through a status region", async () => {- render(<PerformanceView adapter={adapter()} />);- await rows();- const statuses = screen.getAllByRole("status").map((node) => node.textContent ?? "");- expect(statuses.some((text) => text.includes("opportunities"))).toBe(true);- });});describe("PerformanceView opened by a link", () => {@@ -1048,20 +1266,6 @@ describe("PerformanceView drawer, the fix itself", () => {});});-describe("ScopeLine", () => {- it.each([- ["all", 1, "1 opportunity"],- ["all", 2, "2 opportunities"],- ["production", 1, "1 production opportunity"],- ["production", 0, "0 production opportunities"],- ] as const)("names %s with %s as %s", (context, total, expected) => {- render(- <ScopeLine filteredTotal={total} repositoryTotal={total} context={context} narrowed={0} />,- );- expect(screen.getByRole("status").textContent).toContain(expected);- });-});-describe("performance drawer preview", () => {it("marks the cause when the detail response carries a preview note", async () => {const note = "preview, measured 40% precision on 30 judged causes, 2026-10-15";diff --git a/packages/ui/__tests__/lib/areas.test.ts b/packages/ui/__tests__/lib/areas.test.tsnew file mode 100644index 000000000..ce4db1008--- /dev/null+++ b/packages/ui/__tests__/lib/areas.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest";++import { areaOf, dirOf, groupByArea, inArea, separatingDepth } from "../../src/lib/areas";++describe("areas", () => {+ it("names a file's area at a depth, root files in the root area", () => {+ expect(dirOf("src/a/b.py")).toBe("src/a");+ expect(areaOf("src/a/b/c.py", 2)).toBe("src/a");+ expect(areaOf("src/a/b/c.py", 9)).toBe("src/a/b");+ expect(areaOf("README.md", 2)).toBe("");+ });++ it("separates one level below the directory every path shares", () => {+ expect(separatingDepth(["packages/core/x.py", "packages/server/y.py"])).toBe(2);+ expect(separatingDepth(["src/a/x.py", "lib/y.py"])).toBe(1);+ expect(separatingDepth(["a/b/c/d/e/f.py", "a/b/c/d/e/g.py"], 4)).toBe(4);+ expect(separatingDepth([])).toBe(1);+ });++ it("groups in first-seen order and keeps each group's order", () => {+ const groups = groupByArea(["src/b/1", "src/a/2", "src/b/3"], (p) => p, 2);+ expect(groups).toEqual([+ { area: "src/b", items: ["src/b/1", "src/b/3"] },+ { area: "src/a", items: ["src/a/2"] },+ ]);+ });++ it("holds a path inside its area at any depth, never a sibling with a shared prefix", () => {+ expect(inArea("src/a/b/c.py", "src/a")).toBe(true);+ expect(inArea("src/ab/c.py", "src/a")).toBe(false);+ // The root area is the files at the root, as groupByArea groups them.+ expect(inArea("x.py", "")).toBe(true);+ expect(inArea("src/x.py", "")).toBe(false);+ });+});diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex ab5daac50..57be40817 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -90,3 +90,7 @@ export {type FileHealthPromptInput,type FileHealthPromptSignals,} from "./ai-prompts/file-health-prompt";+export {+ buildPerformanceAreaPrompt,+ type BuildPerformanceAreaPromptOptions,+} from "./ai-prompts/performance-area-prompt";diff --git a/packages/ui/src/health/ai-prompts/file-health-prompt.ts b/packages/ui/src/health/ai-prompts/file-health-prompt.tsindex 2fa366314..dca8d7716 100644--- a/packages/ui/src/health/ai-prompts/file-health-prompt.ts+++ b/packages/ui/src/health/ai-prompts/file-health-prompt.ts@@ -1,6 +1,7 @@import type { PerformanceOpportunity } from "@repowise-dev/types/health";import { biomarkerInfo, CATEGORY_LABEL, splitByOrigin } from "../biomarker-glossary";+import { performanceCauseLine } from "./performance-causes";import { findingEntries, historyContextBlock, rankByImpact, remainderRollup } from "./findings";import {bulletList,@@ -245,27 +246,10 @@ function processSignals(signals: FileHealthPromptSignals | null | undefined): streturn bulletList([...churnFacts(signals), ...topologyFacts(signals)]);}-function causeLine(c: PerformanceOpportunity): string {- // Titled by marker and location, as every other surface titles a cause; the- // fix strategy is not the cause's name.- const first = c.evidence[0];- const symbol = c.intervention_symbol ?? first?.function_name ?? null;- const at = symbol ? ` in \`${symbol}\`` : "";- const line = first?.line_start != null ? ` (line ${first.line_start})` : "";- const reach =- c.affected_call_sites_total > 1- ? ` Reaches ${c.affected_call_sites_total} call sites across ${c.affected_files_total} file${pluralS(- c.affected_files_total,- )}.`- : "";- const fix = c.fix ? ` Recorded fix: ${c.fix.strategy} (${c.fix.safety}). ${c.fix.rationale}` : "";- return `**${biomarkerInfo(c.biomarker_type).label}**${at}${line} — ${c.actionability_reason}${reach}${fix}`;-}-function performanceCauses(causes: PerformanceOpportunity[]): string | null {if (causes.length === 0) return null;return [- bulletList(causes.slice(0, MAX_FILE_HEALTH_CAUSES).map(causeLine)),+ bulletList(causes.slice(0, MAX_FILE_HEALTH_CAUSES).map(performanceCauseLine)),causes.length > MAX_FILE_HEALTH_CAUSES? `…and ${causes.length - MAX_FILE_HEALTH_CAUSES} more open on this file.`: null,diff --git a/packages/ui/src/health/ai-prompts/performance-area-prompt.ts b/packages/ui/src/health/ai-prompts/performance-area-prompt.tsnew file mode 100644index 000000000..2ec582f00--- /dev/null+++ b/packages/ui/src/health/ai-prompts/performance-area-prompt.ts@@ -0,0 +1,88 @@+import type { PerformanceOpportunity } from "@repowise-dev/types/health";++import { performanceCauseLine } from "./performance-causes";+import {+ bulletList,+ closingSections,+ joinSections,+ pluralS,+ preamble,+ repoSuffix,+ verifySection,+ type AiPromptFlavor,+} from "./shared";++// ─────────────────────────────────────────────────────────────────────+// Performance causes in one area (the queue's bulk handoff)+// ─────────────────────────────────────────────────────────────────────++const PARTS = {+ source:+ "Repowise's static performance analysis grouped the repeated work below into causes, each one place to edit. They are reads of the code's shape, not measurements of a running system.",+ open: "the file and function each cause names, its callers and its tests",+ mcpTail:+ "For each cause, call `get_health(opportunity_id=\"...\")` with its id for the plan, its steps and the tests that guard it, then `get_risk([file])` before editing.",+};++/** Above this the prompt stops listing and says how many more there are. */+const MAX_CAUSES = 12;++const CONSTRAINTS = [+ "Take the causes in the order given; it is the analysis's ranking.",+ "One cause per change, each independently revertible.",+ "Confirm each cause against the code before editing. If the loop is bounded or the repetition is intended, skip it and say why.",+ "Preserve results exactly: a batched or reordered call must return what the loop returned.",+ "Run the tests that exercise each function before and after its change.",+];++const EXPECTED = [+ "1. The order you will take the causes in, and any you will skip with the reason.",+ "2. For each cause you change: the edit, the tests you ran, and why the result is unchanged.",+ "3. What is left, if anything, with a proposed next step.",+];++export interface BuildPerformanceAreaPromptOptions {+ /** The directory the causes share; empty for the repository root. */+ area: string;+ opportunities: PerformanceOpportunity[];+ /** The queue runs past the loaded page, so the area may hold more causes than these. */+ paged?: boolean;+ flavor?: AiPromptFlavor;+ repoName?: string;+}++function causeEntry(c: PerformanceOpportunity, index: number): string {+ return `${index + 1}. ${performanceCauseLine(c)}\n - Opportunity id: \`${c.opportunity_id}\`\n - Edit in: \`${c.file_path}\``;+}++export function buildPerformanceAreaPrompt({+ area,+ opportunities,+ paged = false,+ flavor = "generic",+ repoName,+}: BuildPerformanceAreaPromptOptions): string {+ const shown = opportunities.slice(0, MAX_CAUSES);+ const hidden = opportunities.length - shown.length;+ const files = Array.from(new Set(opportunities.map((c) => c.file_path)));+ return joinSections([+ preamble(flavor, PARTS),+ "",+ `## Performance causes in \`${area || "(repository root)"}\`${repoSuffix(repoName)}`,+ "",+ bulletList([+ `Causes: **${opportunities.length}** across ${files.length} file${pluralS(files.length)}.`,+ "Each cause folds every call site that shares one fix, so one edit settles all of them.",+ paged+ ? "These are the area's causes on one page of the ranked queue; later pages may hold more in this area."+ : null,+ ]),+ "",+ shown.map(causeEntry).join("\n\n"),+ hidden > 0 ? `\n…and ${hidden} more in this area; take them after the above.` : "",+ "",+ verifySection(null, files.slice(0, 5)),+ "",+ ...closingSections(CONSTRAINTS, EXPECTED),+ ]);+}diff --git a/packages/ui/src/health/ai-prompts/performance-causes.ts b/packages/ui/src/health/ai-prompts/performance-causes.tsnew file mode 100644index 000000000..3effcbcdf--- /dev/null+++ b/packages/ui/src/health/ai-prompts/performance-causes.ts@@ -0,0 +1,27 @@+import type { PerformanceOpportunity } from "@repowise-dev/types/health";++import { biomarkerInfo } from "../biomarker-glossary";+import { pluralS } from "./shared";++/**+ * One performance cause as a prompt bullet. Shared by every prompt that hands+ * causes over (one file's, one area's), so a cause reads the same in each.+ * Titled by marker and location, as every other surface titles a cause; the+ * fix strategy is not the cause's name.+ */+export function performanceCauseLine(c: PerformanceOpportunity): string {+ const first = c.evidence[0];+ const symbol = c.intervention_symbol ?? first?.function_name ?? null;+ const at = symbol ? ` in \`${symbol}\`` : "";+ const line = first?.line_start != null ? ` (line ${first.line_start})` : "";+ const reach =+ c.affected_call_sites_total > 1+ ? ` Reaches ${c.affected_call_sites_total} call sites across ${c.affected_files_total} file${pluralS(+ c.affected_files_total,+ )}.`+ : "";+ // A summary row carries the plan reason but not the actionability reason.+ const why = c.actionability_reason || c.plan_reason;+ const fix = c.fix ? ` Recorded fix: ${c.fix.strategy} (${c.fix.safety}). ${c.fix.rationale}` : "";+ return `**${biomarkerInfo(c.biomarker_type).label}**${at}${line} — ${why}${reach}${fix}`;+}diff --git a/packages/ui/src/health/performance-view.tsx b/packages/ui/src/health/performance-view.tsxindex a23769dd6..13c2d729a 100644--- a/packages/ui/src/health/performance-view.tsx+++ b/packages/ui/src/health/performance-view.tsx@@ -1,50 +1,52 @@"use client";-import { useEffect, useMemo, useState } from "react";-import useSWR from "swr";-import type {- PerformanceContextFilter,- PerformanceOpportunity,- PerformanceOpportunityDetail,- PerformanceOpportunityPage,-} from "@repowise-dev/types/health";-import type { RefactoringPlan } from "@repowise-dev/types/refactoring";+import { lazy, Suspense, useCallback, useEffect, useMemo, useState } from "react";+import type { PerformanceOpportunity } from "@repowise-dev/types/health";-import { PageLede } from "../shared/page-lede";+import { ActiveFilterChips, type ActiveFilterChip } from "../shared/more-filters";import { PaginationControls } from "../shared/pagination-controls";-import { StatRibbon } from "../stats/stat-ribbon";-import { AiPromptModal } from "./ai-prompt-modal";-import {- buildPerformanceOpportunityPrompt,- buildRefactoringPlanPrompt,- type AiPromptFlavor,-} from "./ai-prompt-builder";+import { Button } from "../ui/button";+import { useAiPromptAction } from "./ai-prompt-action";+import { ActionabilityBar } from "./performance/actionability-bar";import type { PerformanceViewAdapter } from "./performance/adapter";-import { capabilitiesOf } from "./performance/capabilities";-import { OpportunityDrawer } from "./performance/drawer";import {- ContextHint,- ContextTabs,- QueueFilters,- ScopeLine,- SortControl,-} from "./performance/filters";+ AREA_PREVIEW,+ AreaGroups,+ areaLabel,+ type AreaTopRows,+} from "./performance/area-groups";+import { useOpportunityDetail, usePrefetchDetail } from "./performance/cache";+import { NarrowingFilters, narrowingChipLabel, SortControl } from "./performance/filters";+import {+ areaGroups,+ countsFromFacet,+ excludedReviews,+ facetAreaGroups,+ type ExcludedReview,+} from "./performance/grouping";import { LegacyPerformanceFindings } from "./performance/legacy";-import { OpportunityQueue } from "./performance/queue";+import { ACTIONABILITY_LABEL } from "./performance/presentation";+import { usePerformancePrompts } from "./performance/prompts";import {clearNarrowing,- INITIAL_FILTERS,+ NARROWING_KEYS,narrowingCount,- parseFilters,- serializeFilters,+ narrowingKeysFor,+ PAGE_SIZE,+ readFilters,+ serverKey,toQuery,withFilter,- type NarrowingKey,+ withScope,+ writeFilters,type PerformanceFilterState,+ type PerformanceScope,} from "./performance/query";+import { QUIET_LINK_CLS, type RowCallbacks } from "./performance/queue";+import { ScopeControl, ScopeSentence, type ScopeCounts } from "./performance/scope";import {- EmptyQueue,FilteredEmpty,+ GoodState,IgnoredArgumentsNotice,LinkedCauseUnavailable,QueueError,@@ -52,19 +54,31 @@ import {StaleModelNotice,UnavailableQueue,} from "./performance/states";+import { usePerformanceFilters } from "./performance/use-filters";+import { usePerformanceQueue } from "./performance/use-queue";+import { PerformanceVerdict, verdictOf } from "./performance/verdict";/**- * The Performance tab: which repeated cost is worth an intervention, why it- * ranks where it does, and what evidence stands behind it.+ * The Performance tab: how many changes are worth making now, where they sit,+ * and a prompt for an agent to make each one.*- * Composition and state only. Grouping, ranking, filtering, paging, facet- * counts, and plan linkage are all decided by the server, so this surface and- * the agent surface cannot disagree about what one opportunity is.+ * One scope (worth doing now, all production, everything) decides which+ * causes exist, and every figure is counted inside it by the server: the+ * lede, the actionability bar and the filter counts. Grouping by area is a+ * pure derivation over the loaded page (`performance/grouping`).*/-export type { PerformanceViewAdapter };+export type { PerformanceViewAdapter, PerformanceFilterState };+export { readFilters as readPerformanceFilters, writeFilters as writePerformanceFilters };++const OpportunityDrawer = lazy(() => import("./performance/drawer"));-const PAGE_SIZE = 20;+/** How the good state names each scope. */+const GOOD_STATE_SCOPE: Record<PerformanceScope, string> = {+ now: "worth making now in production code",+ production: "found in production code",+ all: "found in any code",+};export function PerformanceView({adapter,@@ -74,102 +88,114 @@ export function PerformanceView({onOpenOpportunityChange,}: {adapter: PerformanceViewAdapter;- /** A serialized filter state, so a shared link opens the same queue. */+ /** The tab's URL parameters (or a pre-flat `perf` blob), so a shared link opens the same view. */initialFilters?: string | undefined;- /** Called with the serialized state whenever a filter moves. */- onFiltersChange?: ((search: string) => void) | undefined;+ /** Called on every change with the flat parameters and the state they encode. */+ onFiltersChange?: ((search: string, state: PerformanceFilterState) => void) | undefined;/*** A cause to open on arrival, by its stable id. A link from the map or the- * file drawer names one, and it need not be on the page the filters would- * have loaded, so it is resolved by id rather than looked for in the queue.+ * file drawer names one, and it need not be on the loaded page, so it is+ * resolved by id rather than looked for in the queue.*/openOpportunityId?: string | null;/** Called with the open cause's id, or null when the drawer closes. */onOpenOpportunityChange?: ((opportunityId: string | null) => void) | undefined;}) {- const [filters, setFilters] = useState<PerformanceFilterState>(() =>- initialFilters ? parseFilters(initialFilters) : INITIAL_FILTERS,+ const { filters, current, apply } = usePerformanceFilters(initialFilters, onFiltersChange);++ const { data, error, isLoading, mutate, capabilities, supported } = usePerformanceQueue(+ adapter,+ filters,);++ // The open cause. A click holds the row so the drawer paints at once; a+ // link or a sibling names an id, resolved through the same detail key.const [selected, setSelected] = useState<PerformanceOpportunity | null>(null);- const select = (next: PerformanceOpportunity | null) => {- setSelected(next);- setInternalOpenId(null);- onOpenOpportunityChange?.(next?.opportunity_id ?? null);- };- // A sibling link inside the drawer opens another opportunity by id, the- // same way a shared link does. The host may not feed `openOpportunityId`- // back synchronously (or at all, if it does not track the URL), so this- // state carries the request until the fetch below resolves it.const [internalOpenId, setInternalOpenId] = useState<string | null>(null);- const openById = (opportunityId: string) => {- setInternalOpenId(opportunityId);- onOpenOpportunityChange?.(opportunityId);- };- const effectiveOpenId = openOpportunityId ?? internalOpenId;- // The handoff carries the verified plan when the drawer proved one, so a- // plan-ready row hands over the ready payload rather than an instruction to- // re-derive it.- const [promptFor, setPromptFor] = useState<{- opportunity: PerformanceOpportunity;- plan: RefactoringPlan | null;- } | null>(null);-- // Core renders the plan prompt; held stable so the modal fetches once per flavor.- const planId = promptFor?.plan?.id;- const planPrompt = useMemo(- () =>- planId && adapter.getRefactoringPlanPrompt- ? (flavor: AiPromptFlavor) => adapter.getRefactoringPlanPrompt!(planId, flavor)- : undefined,- [planId, adapter],+ const select = useCallback(+ (next: PerformanceOpportunity | null) => {+ setSelected(next);+ setInternalOpenId(null);+ onOpenOpportunityChange?.(next?.opportunity_id ?? null);+ },+ [onOpenOpportunityChange],);-- const apply = (next: PerformanceFilterState) => {- setFilters(next);- onFiltersChange?.(serializeFilters(next));- };-- const load = adapter.getPerformanceOpportunities;- // What a response proved this server understands. It is part of the cache key- // so that learning it re-asks with the spelling the server accepts: a shared- // link can restore a production or tooling context before any response has- // been seen. It only ever flips for a server that predates the vocabulary, so- // a current one never pays for the correction.- const [collapse, setCollapse] = useState(false);- const key = `${collapse ? "legacy:" : ""}${serializeFilters(filters)}`;- const { data, error, isLoading, mutate } = useSWR<PerformanceOpportunityPage>(- load ? `performance-opportunities:${adapter.cacheKey}:${key}` : null,- () => load!(toQuery(filters, { limit: PAGE_SIZE, collapseContexts: collapse })),- { revalidateOnFocus: false, keepPreviousData: true },+ const openById = useCallback(+ (opportunityId: string) => {+ setInternalOpenId(opportunityId);+ onOpenOpportunityChange?.(opportunityId);+ },+ [onOpenOpportunityChange],);-- const capabilities = useMemo(() => capabilitiesOf(adapter, data), [adapter, data]);- useEffect(() => {- if (data) setCollapse(!capabilitiesOf(adapter, data).canonicalContexts);- }, [adapter, data]);-- // A link naming a cause opens it, whether or not the filters would have- // loaded the page it sits on. Resolved by id rather than searched for in the- // queue: this repository has 743 causes and a link is allowed to name any of- // them. The row shape and the detail shape share their fields, so what comes- // back drives the same drawer a click does.+ const effectiveOpenId = openOpportunityId ?? internalOpenId;const pendingId =effectiveOpenId && effectiveOpenId !== selected?.opportunity_id ? effectiveOpenId : null;- const { data: linked, error: linkError } = useSWR<PerformanceOpportunityDetail>(- pendingId && adapter.getPerformanceOpportunity- ? `performance-opportunity-link:${adapter.cacheKey}:${pendingId}`- : null,- () => adapter.getPerformanceOpportunity!(pendingId!, { evidenceLimit: 8 }),- { revalidateOnFocus: false },+ const { data: linked, error: linkError } = useOpportunityDetail(+ adapter,+ capabilities.detailById ? pendingId : null,);useEffect(() => {- // Both branches of the detail carry an id, so the discriminant decides:- // an id from a retired model resolves to a state, not to a cause, and- // opening a drawer on it would render an empty panel.+ // An id from a retired model resolves to a state, not a cause; opening a+ // drawer on it would render an empty panel.if (linked?.found) setSelected(linked);}, [linked]);- if (!load) return <LegacyPerformanceFindings adapter={adapter} />;+ const { openPrompt, promptModal } = useAiPromptAction();+ const prompts = usePerformancePrompts(adapter);+ const prefetch = usePrefetchDetail(adapter);+ const detailById = capabilities.detailById;+ const callbacks: RowCallbacks = useMemo(+ () => ({+ onInspect: select,+ onPrompt: (opportunity) => openPrompt(prompts.forOpportunity(opportunity)),+ onPrefetch: (id) => {+ if (detailById) prefetch(id);+ },+ }),+ [select, openPrompt, prompts, prefetch, detailById],+ );+ const onAreaPrompt = useCallback(+ (area: string, rows: PerformanceOpportunity[], partial: boolean) =>+ openPrompt(prompts.forArea(area, rows, partial)),+ [openPrompt, prompts],+ );+ const onOpenArea = useCallback(+ (area: string) => apply(withFilter(current.current, "area", area)),+ [apply],+ );++ const items = useMemo(() => data?.items ?? [], [data]);+ const counts = useMemo(() => countsFromFacet(data?.facets.actionability), [data]);+ // Every area in the scope with its true counts, from the server's facet; a+ // server that predates it groups the loaded page instead.+ const groups = useMemo(+ () => (data?.areas ? facetAreaGroups(items, data.areas) : areaGroups(items)),+ [data, items],+ );+ const focused = filters.area !== null;+ // An opened area that does not split further lists every loaded cause in it.+ const listAll = focused && groups.length <= 1;+ // A small area's causes may sit past the loaded page; a card asks for its top.+ // Page-independent: the area facet and each card's top do not move with it.+ const viewKey = serverKey({ ...filters, page: 1 });+ const load = adapter.getPerformanceOpportunities;+ const topRows: AreaTopRows | undefined = useMemo(+ () =>+ load+ ? {+ key: `${adapter.cacheKey}:${viewKey}`,+ load: async (area: string) =>+ (+ await load(+ toQuery(withFilter(current.current, "area", area), { limit: AREA_PREVIEW }),+ )+ ).items,+ }+ : undefined,+ [load, adapter.cacheKey, viewKey, current],+ );++ if (!supported) return <LegacyPerformanceFindings adapter={adapter} />;if (error && [404, 405].includes(Number((error as { status?: number }).status))) {return <LegacyPerformanceFindings adapter={adapter} />;}@@ -178,159 +204,176 @@ export function PerformanceView({if (!data) return null;const { summary, facets } = data;- // A server that predates context scoping sends no repository_total, and its- // total is already the repository-wide count.- const repositoryTotal = summary.repository_total ?? summary.total;- const narrowed = narrowingCount(filters);- // A repository with nothing in any context is clear, not filtered: offering- // to widen a selection that is hiding nothing would misread the answer.- const filtered = (narrowed > 0 || filters.context !== "all") && repositoryTotal > 0;-if (summary.status === "unavailable") return <UnavailableQueue summary={summary} />;- const stats = [- {- label: "Plan ready",- value: (summary.actionability?.plan_ready ?? 0).toLocaleString(),- sub: "a named safe intervention",- },- {- label: "Advisory",- value: (summary.actionability?.advisory ?? 0).toLocaleString(),- sub: "coherent, not proven safe",- },- {- label: "Needs investigation",- value: (summary.actionability?.investigate ?? 0).toLocaleString(),- sub: "read the evidence first",- },- {- label: "With a stored plan",- value: summary.with_plan_total.toLocaleString(),- sub: `of ${summary.total.toLocaleString()} causes`,- },+ // A server that predates context scoping sends no repository_total, and+ // one that predates scopes no scope sizes; both fall back to the summary.+ const repositoryTotal = summary.repository_total ?? summary.total;+ const scopes: ScopeCounts = {+ now: data.scopes?.now ?? summary.default_queue?.total ?? 0,+ production: data.scopes?.production ?? summary.context?.production ?? 0,+ all: data.scopes?.all ?? repositoryTotal,+ };+ const reviews = excludedReviews(summary.default_queue?.excluded);+ const toScope = (scope: PerformanceScope) => apply(withScope(filters, scope));+ const onReview = ({ patch: { scope, ...rest } }: ExcludedReview) =>+ apply(withScope(filters, scope, rest));+ const sentence = (+ <ScopeSentence+ scope={filters.scope}+ counts={scopes}+ reviews={reviews}+ onScope={toScope}+ onReview={onReview}+ />+ );+ const otherProduction = scopes.production - scopes.now;++ const chips: ActiveFilterChip[] = [+ ...NARROWING_KEYS.flatMap((key) => {+ const value = filters[key];+ return value+ ? [+ {+ key,+ label: narrowingChipLabel(key, value),+ onRemove: () => apply(withFilter(filters, key, null)),+ },+ ]+ : [];+ }),+ ...(filters.actionability+ ? [+ {+ key: "actionability",+ label: `Showing: ${ACTIONABILITY_LABEL[filters.actionability]}`,+ onRemove: () => apply(withFilter(filters, "actionability", null)),+ },+ ]+ : []),+ ...(filters.area !== null+ ? [+ {+ key: "area",+ label: `Area: ${areaLabel(filters.area)}`,+ onRemove: () => apply(withFilter(filters, "area", null)),+ },+ ]+ : []),];- // A zero does not lead: when nothing is proven safe, the ribbon opens on- // what there is, and "Plan ready: 0" still reads, just not first.- if (!summary.actionability?.plan_ready) {- const first = stats.shift();- if (first) stats.push(first);- }++ const selectedId = selected?.opportunity_id ?? null;return (<div className="space-y-8">- <div className="space-y-6">- <PageLede- label="Causal opportunities"- value={summary.total.toLocaleString()}- unit={- data.counts- ? `ranked causes, not repeated observations; ${data.counts.eligible.toLocaleString()} in the default queue, ${data.counts.inventory.toLocaleString()} in the repository`- : "ranked causes, not repeated observations"- }- layout="beside"- figureFooter={- <p className="text-caption text-[var(--color-text-tertiary)]">- Static, high-precision signals. They are not measured latency.- </p>- }+ {items.length > 0 ? (+ <PerformanceVerdict+ verdict={verdictOf(filters.scope, data.total, groups)}+ analyzedCommit={summary.analyzed_commit}>- <p>- Repeated caller paths fold into one cause, so the first row answers what to change- once while every raw observation stays readable as evidence.- </p>- <p>- Evidence confidence, actionability, and fix safety are three separate judgements. A- path the analysis resolved well is not automatically a change worth making.- </p>- </PageLede>- <StatRibbon stats={stats} />- </div>-- <section className="space-y-4 border-t border-[var(--color-border-default)] pt-8">- <div>- <h2 className="text-lg font-semibold text-[var(--color-text-primary)]">- Opportunity queue- </h2>- <p className="mt-1 max-w-[72ch] text-sm text-[var(--color-text-secondary)]">- Ranked with the actionable work first. Filters and their counts come from the server,- so narrowing one never hides the alternatives to it.- </p>- </div>+ {sentence}+ </PerformanceVerdict>+ ) : null}+ <section aria-label="Performance causes" className="space-y-4">{summary.status === "stale_model" ? <StaleModelNotice summary={summary} /> : null}{data.ignored_arguments ? (<IgnoredArgumentsNotice ignored={data.ignored_arguments} />) : null}- <ContextTabs- value={filters.context}- facets={facets}- total={repositoryTotal}- collapsed={!capabilities.canonicalContexts}- onChange={(context: PerformanceContextFilter) =>- apply(withFilter(filters, "context", context))- }- />- <ContextHint context={filters.context} />-- <SortControl- value={filters.sort}- onChange={(sort) => apply(withFilter(filters, "sort", sort))}- />-+ <div className="flex flex-wrap items-end justify-between gap-x-6 gap-y-3">+ <ScopeControl value={filters.scope} counts={scopes} onChange={toScope} />+ <SortControl+ value={filters.sort}+ onChange={(sort) => apply(withFilter(filters, "sort", sort))}+ />+ </div>{capabilities.serverFacets ? (- <QueueFilters+ <NarrowingFiltersfilters={filters}facets={facets}- onChange={(key: NarrowingKey, value) =>- apply(withFilter(filters, key, value as never))- }- onClear={() => apply(clearNarrowing(filters))}+ keys={narrowingKeysFor(filters.scope)}+ onChange={(key, value) => apply(withFilter(filters, key, value as never))}/>) : null}+ <ActiveFilterChips chips={chips} onClearAll={() => apply(clearNarrowing(filters))} />- <ScopeLine- filteredTotal={data.total}- repositoryTotal={repositoryTotal}- context={filters.context}- narrowed={narrowed}- analyzedCommit={summary.analyzed_commit}- />+ {items.length > 0 ? (+ <ActionabilityBar+ counts={counts}+ value={filters.actionability}+ onChange={(state) => apply(withFilter(filters, "actionability", state))}+ />+ ) : null}- {data.items.length === 0 ? (- filtered ? (- <FilteredEmpty onClear={() => apply({ ...clearNarrowing(filters), context: "all" })} />+ {items.length === 0 ? (+ // A scope with no causes is clean, not a failed filter.+ narrowingCount(filters) > 0 && repositoryTotal > 0 ? (+ <FilteredEmpty onClear={() => apply(clearNarrowing(filters))} />) : (- <EmptyQueue />+ <GoodState+ scope={GOOD_STATE_SCOPE[filters.scope]}+ analyzedCommit={summary.analyzed_commit}+ >+ {sentence}+ </GoodState>)) : (- <OpportunityQueue- items={data.items}- facets={facets}- adapter={adapter}- showSections={filters.actionability === null}- selectedId={selected?.opportunity_id ?? null}- onInspect={select}- />+ <div className="space-y-3">+ {focused ? (+ <button+ type="button"+ onClick={() => apply(withFilter(filters, "area", null))}+ className={`${QUIET_LINK_CLS} text-xs`}+ >+ Back to all areas+ </button>+ ) : null}+ <AreaGroups+ groups={groups}+ adapter={adapter}+ selectedId={selectedId}+ callbacks={callbacks}+ onOpenArea={onOpenArea}+ onAreaPrompt={onAreaPrompt}+ preview={listAll ? Number.POSITIVE_INFINITY : AREA_PREVIEW}+ topRows={topRows}+ />+ {data.areas && data.areas.more > 0 ? (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {data.areas.more.toLocaleString()} more{" "}+ {data.areas.more === 1 ? "cause sits" : "causes sit"} in smaller areas not+ listed here.+ </p>+ ) : null}+ </div>)}- <PaginationControls- offset={filters.offset}- shown={data.items.length}- total={data.total}- label="opportunities"- onPrevious={- filters.offset > 0- ? () => apply(withFilter(filters, "offset", Math.max(0, filters.offset - PAGE_SIZE)))- : undefined- }- onNext={- data.next_offset != null- ? () => apply(withFilter(filters, "offset", data.next_offset!))- : undefined- }- />+ {filters.scope === "now" && items.length > 0 && otherProduction > 0 ? (+ <Button variant="outline" size="sm" onClick={() => toScope("production")}>+ Show the {otherProduction.toLocaleString()} other production{" "}+ {otherProduction === 1 ? "cause" : "causes"}+ </Button>+ ) : null}++ {data.total > PAGE_SIZE ? (+ <PaginationControls+ offset={(filters.page - 1) * PAGE_SIZE}+ shown={items.length}+ total={data.total}+ label="causes"+ onPrevious={+ filters.page > 1+ ? () => apply(withFilter(filters, "page", filters.page - 1))+ : undefined+ }+ onNext={+ data.next_offset != null+ ? () => apply(withFilter(filters, "page", filters.page + 1))+ : undefined+ }+ />+ ) : null}</section>{pendingId && (linkError || linked?.found === false) ? (@@ -341,43 +384,21 @@ export function PerformanceView({/>) : null}- <OpportunityDrawer- opportunity={selected}- adapter={adapter}- detailEnabled={capabilities.detailById}- planEnabled={capabilities.planById}- onClose={() => select(null)}- onAgentHandoff={(opportunity, plan) => setPromptFor({ opportunity, plan })}- onSelectById={openById}- />+ {selected ? (+ <Suspense fallback={null}>+ <OpportunityDrawer+ opportunity={selected}+ adapter={adapter}+ detailEnabled={detailById}+ planEnabled={capabilities.planById}+ onClose={() => select(null)}+ onAgentPrompt={callbacks.onPrompt}+ onSelectById={openById}+ />+ </Suspense>+ ) : null}- <AiPromptModal- open={promptFor !== null}- onOpenChange={(open) => {- if (!open) setPromptFor(null);- }}- promptSource={planPrompt}- getPrompt={- // A host without the prompt route (an older server) builds the plan- // prompt here instead; remove with `buildRefactoringPlanPrompt`.- promptFor?.plan && !planPrompt- ? (flavor) => buildRefactoringPlanPrompt({ plan: promptFor.plan!, flavor })- : promptFor && !promptFor.plan- ? (flavor) =>- buildPerformanceOpportunityPrompt({- opportunity: promptFor.opportunity,- flavor,- })- : null- }- filePath={promptFor?.plan?.file_path ?? promptFor?.opportunity.file_path ?? null}- title={promptFor?.plan ? "Structured plan handoff" : "Agent handoff"}- description={- promptFor?.plan- ? "The stored plan for this exact opportunity, with its intervention, affected targets, and validation contract."- : "A ready-to-paste evidence handoff that asks an agent to verify the cause against the source before proposing any edit."- }- />+ {promptModal}</div>);}diff --git a/packages/ui/src/health/performance/actionability-bar.tsx b/packages/ui/src/health/performance/actionability-bar.tsxnew file mode 100644index 000000000..d99c2ce2b--- /dev/null+++ b/packages/ui/src/health/performance/actionability-bar.tsx@@ -0,0 +1,80 @@+"use client";++import type { PerformanceActionabilityState } from "@repowise-dev/types/health";++import { ProportionBar } from "../../shared/proportion-bar";+import { Segmented, type SegmentOption } from "../../shared/segmented";+import type { ActionabilityCounts } from "./grouping";+import { ACTIONABILITY_HINT, ACTIONABILITY_LABEL } from "./presentation";++/**+ * The scope's split by actionability, as one bar and the one control that+ * narrows by it. The server counts it inside the scope and every other+ * filter, so the segments sum to the lede's figure and a segment's count is+ * exactly what choosing it lists.+ */++const STATES: PerformanceActionabilityState[] = ["plan_ready", "advisory", "investigate", "expected"];++/** One neutral family, darkest where the change is surest; the segment names+ * carry the meaning, so no state borrows a health colour. */+const STATE_COLOR: Record<PerformanceActionabilityState, string> = {+ plan_ready: "var(--color-text-primary)",+ advisory: "var(--color-text-secondary)",+ investigate: "var(--color-text-tertiary)",+ expected: "var(--color-border-default)",+};++type Choice = PerformanceActionabilityState | "all";++export function ActionabilityBar({+ counts,+ value,+ onChange,+}: {+ /** Server counts inside the scope and the other filters. */+ counts: ActionabilityCounts;+ value: PerformanceActionabilityState | null;+ onChange: (state: PerformanceActionabilityState | null) => void;+}) {+ const total = STATES.reduce((sum, state) => sum + counts[state], 0);+ // Only the states this scope holds, and the chosen one, which keeps its+ // place so it can be cleared; an empty segment would name nothing to show.+ const states = STATES.filter((state) => counts[state] > 0 || value === state);+ const options: SegmentOption<Choice>[] = [+ { value: "all", label: "All", count: total.toLocaleString() },+ ...states.map((state) => ({+ value: state,+ label: ACTIONABILITY_LABEL[state],+ count: counts[state].toLocaleString(),+ hint: ACTIONABILITY_HINT[state],+ })),+ ];+ // One segment holding everything says nothing the counts below do not.+ const split = states.filter((state) => counts[state] > 0).length > 1;+ if (!split && value === null) return null;+ return (+ <div className="flex min-w-0 flex-col gap-2">+ {split ? (+ <ProportionBar+ label="Causes by actionability"+ legend={false}+ sort={false}+ size="sm"+ segments={states.map((state) => ({+ key: state,+ label: ACTIONABILITY_LABEL[state],+ value: counts[state],+ color: STATE_COLOR[state],+ }))}+ />+ ) : null}+ <Segmented+ label="Actionability"+ value={value ?? "all"}+ options={options}+ onChange={(next) => onChange(next === "all" ? null : next)}+ />+ </div>+ );+}diff --git a/packages/ui/src/health/performance/area-groups.tsx b/packages/ui/src/health/performance/area-groups.tsxnew file mode 100644index 000000000..7f748e837--- /dev/null+++ b/packages/ui/src/health/performance/area-groups.tsx@@ -0,0 +1,182 @@+"use client";++import { memo, useState } from "react";+import useSWR from "swr";+import { ChevronRight } from "lucide-react";+import type { PerformanceOpportunity } from "@repowise-dev/types/health";++import { bulkAgentPromptLabel } from "../ai-prompt-action";+import { AiPromptButton } from "../ai-prompt-button";+import type { PerformanceViewAdapter } from "./adapter";+import type { PerformanceAreaGroup } from "./grouping";+import { ACTIONABILITY_LABEL } from "./presentation";+import { OpportunityList, QUIET_LINK_CLS, type RowCallbacks } from "./queue";++/**+ * The queue grouped by area: one card per directory, the area with the most+ * plan-ready causes first, each showing its leading causes and a way to the+ * rest. A card is an object here, since it can be opened, collapsed and+ * handed to an agent as a batch.+ */++/** Causes a card lists before "Show all". */+export const AREA_PREVIEW = 3;++export function areaLabel(area: string): string {+ return area || "Repository root";+}++/** A card's heading: an area, or the opened area's own files. */+function cardLabel(group: PerformanceAreaGroup): string {+ if (!group.own) return areaLabel(group.area);+ return group.area ? `Files directly in ${group.area}` : "Files at the repository root";+}++/** Cards past this many never fetch their own rows, so a wide scope is not a burst. */+const FETCHING_CARDS = 8;++function countsLine(group: PerformanceAreaGroup): string {+ const parts = (["plan_ready", "advisory", "investigate", "expected"] as const)+ .filter((state) => group.counts[state] > 0)+ .map((state) => `${group.counts[state].toLocaleString()} ${ACTIONABILITY_LABEL[state].toLowerCase()}`);+ return parts.join(" · ");+}++/**+ * The top causes of one area when the loaded page holds too few of them:+ * keyed by the query, so it is fetched once per area and view.+ */+export interface AreaTopRows {+ key: string;+ load: (area: string) => Promise<PerformanceOpportunity[]>;+}++export function AreaGroups({+ groups,+ adapter,+ selectedId,+ callbacks,+ onOpenArea,+ onAreaPrompt,+ preview = AREA_PREVIEW,+ topRows,+}: {+ groups: PerformanceAreaGroup[];+ /** Fetches an area's top causes when the loaded page lacks them. */+ topRows?: AreaTopRows | undefined;+ adapter: PerformanceViewAdapter;+ selectedId: string | null;+ callbacks: RowCallbacks;+ /** Open one area on its own, every cause listed. */+ onOpenArea: (area: string) => void;+ /** `partial` when the rows are only the area's leading causes. */+ onAreaPrompt: (area: string, items: PerformanceOpportunity[], partial: boolean) => void;+ /** Causes each card lists before "Show all"; `Infinity` lists every one. */+ preview?: number;+}) {+ return (+ <div className="space-y-4">+ {groups.map((group, index) => (+ <AreaCard+ key={`${group.own ? "own:" : ""}${group.area}`}+ group={group}+ mayFetch={index < FETCHING_CARDS}+ adapter={adapter}+ selectedId={selectedId}+ callbacks={callbacks}+ onOpenArea={onOpenArea}+ onAreaPrompt={onAreaPrompt}+ preview={preview}+ topRows={topRows}+ />+ ))}+ </div>+ );+}++const AreaCard = memo(function AreaCard({+ group,+ adapter,+ selectedId,+ callbacks,+ onOpenArea,+ onAreaPrompt,+ preview,+ topRows,+ mayFetch,+}: {+ group: PerformanceAreaGroup;+ topRows?: AreaTopRows | undefined;+ mayFetch: boolean;+ adapter: PerformanceViewAdapter;+ selectedId: string | null;+ callbacks: RowCallbacks;+ onOpenArea: (area: string) => void;+ /** `partial` when the rows are only the area's leading causes. */+ onAreaPrompt: (area: string, items: PerformanceOpportunity[], partial: boolean) => void;+ preview: number;+}) {+ const [open, setOpen] = useState(true);+ const label = cardLabel(group);+ // The loaded page may hold none of a small area's causes; ask for them.+ // An own-files card cannot be asked for by area, which would list its subareas too.+ const short = group.items.length === 0 && group.total > 0 && !group.own && mayFetch;+ const { data: fetched } = useSWR<PerformanceOpportunity[]>(+ open && short && topRows ? `performance-area-top:${topRows.key}:${group.area}` : null,+ () => topRows!.load(group.area),+ { revalidateOnFocus: false },+ );+ const rows = short && fetched ? fetched : group.items;+ const shown = rows.slice(0, preview);+ const rest = group.total - shown.length;+ return (+ <section+ aria-label={`${label}, ${group.total} causes`}+ className="rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)]"+ >+ <header className="flex flex-col items-start gap-2 px-4 py-3 sm:flex-row sm:items-center sm:gap-3">+ <button+ type="button"+ onClick={() => setOpen((value) => !value)}+ aria-expanded={open}+ className="flex w-full min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded text-left sm:w-auto sm:flex-1 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <ChevronRight+ aria-hidden="true"+ className={`h-4 w-4 shrink-0 text-[var(--color-text-tertiary)] transition-transform ${open ? "rotate-90" : ""}`}+ />+ <span className="min-w-0 font-mono text-sm font-semibold text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {label}+ </span>+ <span className="shrink-0 text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {countsLine(group)}+ </span>+ </button>+ <AiPromptButton+ label={bulkAgentPromptLabel(rows.length)}+ onClick={() => onAreaPrompt(group.area, rows, rows.length < group.total)}+ />+ </header>+ {open ? (+ <div className="px-3 pb-3">+ <OpportunityList+ items={shown}+ adapter={adapter}+ selectedId={selectedId}+ callbacks={callbacks}+ label={`Causes in ${label}`}+ />+ {rest > 0 && !group.own ? (+ <button+ type="button"+ onClick={() => onOpenArea(group.area)}+ className={`${QUIET_LINK_CLS} mt-2 px-1 text-xs`}+ >+ Show all {group.total.toLocaleString()} in {label}+ </button>+ ) : null}+ </div>+ ) : null}+ </section>+ );+});diff --git a/packages/ui/src/health/performance/cache.ts b/packages/ui/src/health/performance/cache.tsnew file mode 100644index 000000000..9fc253448--- /dev/null+++ b/packages/ui/src/health/performance/cache.ts@@ -0,0 +1,140 @@+"use client";++import { useCallback } from "react";+import useSWR, { useSWRConfig } from "swr";+import type { PerformanceOpportunity, PerformanceOpportunityDetail } from "@repowise-dev/types/health";+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";++import { performancePlanDetail } from "../../refactoring/types";+import type { PerformanceViewAdapter } from "./adapter";++/**+ * One cache entry per cause and per plan, whoever asks: the drawer, a deep+ * link, a hover prefetch and the agent prompt all read the same key, so a+ * cause is fetched once however it was reached.+ */++const EVIDENCE_LIMIT = 8;++export const detailKey = (cacheKey: string, id: string) => `performance-opportunity:${cacheKey}:${id}`;+export const planKey = (cacheKey: string, id: string) => `performance-plan:${cacheKey}:${id}`;++/** Read once, never revalidated: an index's causes change only on a new index. */+const ONCE = { revalidateOnFocus: false, revalidateIfStale: false } as const;++const inflight = new Map<string, Promise<unknown>>();++/**+ * One request per key at a time, whoever starts it: a hover prefetch, the+ * drawer's own fetch and a prompt build all join the same promise.+ */+function fetchOnce<T>(key: string, fetcher: () => Promise<T>): Promise<T> {+ const pending = inflight.get(key) as Promise<T> | undefined;+ if (pending) return pending;+ const request = fetcher().finally(() => inflight.delete(key));+ inflight.set(key, request);+ return request;+}++/** Keys whose prefetch failed this session, so later hovers do not retry them. */+const failed = new Set<string>();++export function useOpportunityDetail(+ adapter: PerformanceViewAdapter,+ id: string | null,+): { data: PerformanceOpportunityDetail | undefined; error: unknown } {+ const fetchDetail = adapter.getPerformanceOpportunity;+ const key = id && fetchDetail ? detailKey(adapter.cacheKey, id) : null;+ const { data, error } = useSWR<PerformanceOpportunityDetail>(+ key,+ () => fetchOnce(key!, () => fetchDetail!(id!, { evidenceLimit: EVIDENCE_LIMIT })),+ ONCE,+ );+ return { data, error };+}++export function usePlan(adapter: PerformanceViewAdapter, planId: string | null) {+ const fetchPlan = adapter.getRefactoringPlan;+ const key = planId && fetchPlan ? planKey(adapter.cacheKey, planId) : null;+ return useSWR<RefactoringPlan>(key, () => fetchOnce(key!, () => fetchPlan!(planId!)), ONCE);+}+++/**+ * Fetch into the shared cache outside a render: for a prefetch on hover, or a+ * prompt built on click. Returns what is cached when it is, and joins a fetch+ * already in flight rather than starting a second.+ */+export function useCachedLoader() {+ const { cache, mutate } = useSWRConfig();+ return useCallback(+ <T,>(key: string, fetcher: () => Promise<T>): Promise<T> => {+ const hit = cache.get(key)?.data as T | undefined;+ if (hit !== undefined) return Promise.resolve(hit);+ return fetchOnce(key, fetcher).then(+ (value) => mutate(key, value, { revalidate: false }) as Promise<T>,+ );+ },+ [cache, mutate],+ );+}++/**+ * Warm one cause's detail on hover or focus. A key that failed once is not+ * retried by later hovers; opening the cause still asks again.+ */+export function usePrefetchDetail(adapter: PerformanceViewAdapter) {+ const load = useDetailLoader(adapter);+ return useCallback(+ (id: string) => {+ const key = detailKey(adapter.cacheKey, id);+ if (failed.has(key)) return;+ load(id).catch(() => failed.add(key));+ },+ [adapter, load],+ );+}++/** Load one cause's detail into the shared key; null when the host cannot. */+export function useDetailLoader(adapter: PerformanceViewAdapter) {+ const load = useCachedLoader();+ return useCallback(+ (id: string): Promise<PerformanceOpportunityDetail | null> => {+ const fetchDetail = adapter.getPerformanceOpportunity;+ if (!fetchDetail) return Promise.resolve(null);+ return load(detailKey(adapter.cacheKey, id), () =>+ fetchDetail(id, { evidenceLimit: EVIDENCE_LIMIT }),+ );+ },+ [adapter, load],+ );+}++/**+ * Whether a stored plan names this exact cause. A reindexed or reused row+ * must never be handed over as this one's fix, so the plan link and the+ * agent prompt both wait on this verdict.+ */+export function planMatches(plan: RefactoringPlan | undefined | null, opportunity: PerformanceOpportunity): boolean {+ return Boolean(+ plan &&+ plan.id === opportunity.plan_id &&+ plan.refactoring_type === "performance_fix" &&+ performancePlanDetail(plan).opportunityId === opportunity.opportunity_id,+ );+}++/** Load the stored plan into the shared key, returning it only when it matches. */+export function useVerifiedPlanLoader(adapter: PerformanceViewAdapter) {+ const load = useCachedLoader();+ return useCallback(+ async (opportunity: PerformanceOpportunity): Promise<RefactoringPlan | null> => {+ const fetchPlan = adapter.getRefactoringPlan;+ const id = opportunity.plan_status === "available" ? opportunity.plan_id : null;+ if (!id || !fetchPlan) return null;+ const plan = await load(planKey(adapter.cacheKey, id), () => fetchPlan(id));+ return planMatches(plan, opportunity) ? plan : null;+ },+ [adapter, load],+ );+}diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsxdeleted file mode 100644index 9479ad0a1..000000000--- a/packages/ui/src/health/performance/drawer.tsx+++ /dev/null@@ -1,837 +0,0 @@-"use client";--import useSWR from "swr";-import { Sparkles } from "lucide-react";-import type {- PerformanceOpportunity,- PerformanceOpportunityDetail,- PerformanceOpportunityPlanStep,- PerformanceOpportunitySibling,- PerformanceOpportunityValidation,- PerformanceModelState,-} from "@repowise-dev/types/health";-import type {- RecommendationValidation,- RefactoringPlan,- StepVerify,-} from "@repowise-dev/types/refactoring";--import { AdaptivePanel } from "../../shared/adaptive-panel";-import { CollapsibleSection } from "../../shared/collapsible-section";-import { InfoTip } from "../../shared/info-tip";-import { formatNumber } from "../../lib/format";-import { CommandLine } from "../../shared/command-line";-import { ProvenancePathList } from "../../shared/provenance-path-list";-import { performancePlanDetail } from "../../refactoring/types";-import { SourceExcerpt } from "../../refactoring/source-excerpt";-import { ValidationSummary } from "../../refactoring/validation-summary";-import { EFFORT_LABEL, WORK_UNIT_LABEL } from "../labels";-import { RelatedWork, useRelatedWork } from "../related-work";-import type { PerformanceViewAdapter } from "./adapter";-import { LowerPriorityTag } from "../lower-priority-tag";-import { PreviewBadge } from "../preview-badge";-import { RawObservations } from "./evidence";-import {- ACTIONABILITY_LABEL,- affectedSummary,- agentHandoffCall,- boundaryLabel,- CONFIDENCE_LABEL,- contextLabel,- FACET_GLOSSARY,- humanizeToken,- INTERVENTION_KIND_LABEL,- interventionKind,- loopHeaderAbove,- moduleScopeLabel,- opportunityTitle,- planPresentation,- siblingFixLabel,- whyRankedLabel,-} from "./presentation";--/** The queue's small validation shape, adapted onto the refactoring surface's- * reader rather than duplicated. The fields it doesn't materialize (per-target- * breakdown, affected paths) read as empty, not missing. */-function toRecommendationValidation(- validation: PerformanceOpportunityValidation,-): RecommendationValidation {- return {- basis: validation.basis,- via: validation.via,- total: validation.total,- tests: validation.tests,- truncated: false,- affected_files: [],- affected_symbols: [],- commands: validation.commands,- targets: [],- ...(validation.reasons ? { reasons: validation.reasons } : {}),- };-}--/**- * One opportunity in depth.- *- * The three judgements the analysis makes separately are shown separately:- * how well the evidence resolved, whether reducing the work is likely valid,- * and whether one named transformation is safe. Collapsing them would let- * strong evidence read as a safe fix.- */--function Field({- label,- value,- detail,- hint,-}: {- label: string;- value: string;- detail?: string | undefined;- /** What the facet means, from the glossary, on hover or tap. */- hint?: string | undefined;-}) {- return (- <div className="min-w-0">- <dt className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- {label}- {hint ? <InfoTip content={hint} label={`What ${label.toLowerCase()} means`} /> : null}- </dt>- <dd className="mt-0.5 text-sm font-medium text-[var(--color-text-primary)]">{value}</dd>- {detail ? (- <dd className="mt-0.5 text-xs text-[var(--color-text-tertiary)]">{detail}</dd>- ) : null}- </div>- );-}--function Section({ title, children }: { title: string; children: React.ReactNode }) {- return (- <section>- <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- {title}- </h4>- {children}- </section>- );-}--/** A resolved id that came from another model is not the same as a wrong id. */-function ModelStateNotice({ state }: { state: PerformanceModelState }) {- if (state.state === "current") return null;- const message =- state.state === "stale_model"- ? `This id was minted by performance model version ${state.requested_model_version ?? "an earlier release"}; the index now serves version ${state.performance_model_version}.`- : "This index does not recognize that opportunity id.";- return (- <p- role="status"- className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"- >- {message}- {state.refresh_required ? " Update the index to get the current grouping." : ""}- </p>- );-}--/**- * Fetch the stored plan and decide whether it names this exact opportunity.- * A reindexed or reused row must never be handed over as this one's fix, so- * both the link and the agent handoff wait on the same verdict.- */-function useVerifiedPlan(- opportunity: PerformanceOpportunity | null,- adapter: PerformanceViewAdapter,- enabled: boolean,-) {- const planId =- opportunity && planPresentation(opportunity).actionable ? opportunity.plan_id : null;- const { data, error, isLoading } = useSWR<RefactoringPlan>(- planId && enabled ? `performance-plan:${adapter.cacheKey}:${planId}` : null,- () => adapter.getRefactoringPlan!(planId!),- { revalidateOnFocus: false },- );- const matches = Boolean(- data &&- opportunity &&- data.id === opportunity.plan_id &&- data.refactoring_type === "performance_fix" &&- performancePlanDetail(data).opportunityId === opportunity.opportunity_id,- );- return { planId, data, error, isLoading, matches, verified: matches ? data! : null };-}--/** One sibling's fix, as a link when the drawer can open another opportunity,- * plain text otherwise (an agent-facing or read-only host, say). */-function SiblingLink({- sibling,- label,- onSelect,-}: {- sibling: PerformanceOpportunitySibling;- label: string;- onSelect?: ((opportunityId: string) => void) | undefined;-}) {- if (!onSelect) {- return <span className="font-medium text-[var(--color-text-secondary)]">{label}</span>;- }- return (- <button- type="button"- onClick={() => onSelect(sibling.opportunity_id)}- className="rounded font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"- >- {label}- </button>- );-}--/** Other causes on the same lines, one quiet line. A `preferred` sibling says- * plainly that its fix is the stronger one; the rest are just named. */-function SiblingsNote({- siblings,- onSelect,-}: {- siblings: PerformanceOpportunitySibling[];- onSelect?: ((opportunityId: string) => void) | undefined;-}) {- const preferred = siblings.filter((sibling) => sibling.relation === "preferred");- const rest = siblings.filter((sibling) => sibling.relation !== "preferred");- return (- <p className="mt-3 text-xs text-[var(--color-text-tertiary)]">- {preferred.map((sibling) => (- <span key={sibling.opportunity_id} className="block">- {siblingFixLabel(sibling)} is the stronger fix here; see{" "}- <SiblingLink sibling={sibling} label="this cause" onSelect={onSelect} />.- </span>- ))}- {rest.length > 0 ? (- <span className="block">- Also flagged on these lines:{" "}- {rest.map((sibling, index) => (- <span key={sibling.opportunity_id}>- {index > 0 ? ", " : ""}- <SiblingLink- sibling={sibling}- label={humanizeToken(sibling.biomarker_type)}- onSelect={onSelect}- />- </span>- ))}- .- </span>- ) : null}- </p>- );-}--/**- * The plan's edits in order; only the rarer mechanical ones are marked.- *- * Consecutive steps that make the same edit at different call sites read as- * one step with its locations: the server emits one step per site, and eight- * copies of "Collect the keys before the loop" said nothing seven times.- */-function PlanSteps({ steps }: { steps: PerformanceOpportunityPlanStep[] }) {- const groups: PerformanceOpportunityPlanStep[][] = [];- for (const step of [...steps].sort((a, b) => a.order - b.order)) {- const last = groups[groups.length - 1];- if (last && last[0]!.action === step.action && last[0]!.applicability === step.applicability) {- last.push(step);- } else {- groups.push([step]);- }- }- const where = (step: PerformanceOpportunityPlanStep) =>- step.file_path ? `${step.file_path}${step.line ? `:${step.line}` : ""}` : null;- return (- <ol className="mt-3 space-y-1.5">- {groups.map((group, index) => {- const first = group[0]!;- const places = group- .map((step) => ({ place: where(step), verify: step.verify }))- .filter((p): p is { place: string; verify: StepVerify | undefined } =>- Boolean(p.place),- );- return (- <li key={first.order} className="text-sm text-[var(--color-text-secondary)]">- <span className="tabular-nums text-[var(--color-text-tertiary)]">{index + 1}.</span>{" "}- {first.action}- {group.length > 1 ? (- <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">- {`at ${group.length} call sites`}- </span>- ) : null}- {first.applicability === "mechanical" ? (- <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">mechanical</span>- ) : null}- {places.length === 1 ? (- <>- <span className="ml-1.5 break-all font-mono text-xs text-[var(--color-text-tertiary)]">- {places[0]!.place}- </span>- <StepCheck verify={places[0]!.verify} />- </>- ) : places.length > 1 ? (- <ul className="mt-1 space-y-0.5 pl-5">- {places.map((p) => (- <li key={p.place} className="break-all font-mono text-xs text-[var(--color-text-tertiary)]">- {p.place}- <StepCheck verify={p.verify} />- </li>- ))}- </ul>- ) : null}- </li>- );- })}- </ol>- );-}--/**- * How to check one step, when it differs from the plan: the server omits- * `verify` on a step the plan's validation already checks.- */-function StepCheck({ verify }: { verify: StepVerify | undefined }) {- if (!verify) return null;- if (verify.coverage === "none") {- return (- <p className="mt-1 font-sans text-xs text-[var(--color-text-tertiary)]">- No test reaches this step.- </p>- );- }- return (- <>- {verify.commands.map((command) => (- <CommandLine key={command} command={command} />- ))}- </>- );-}--function PlanSection({- opportunity,- adapter,- enabled,- plan,-}: {- opportunity: PerformanceOpportunity;- adapter: PerformanceViewAdapter;- enabled: boolean;- plan: ReturnType<typeof useVerifiedPlan>;-}) {- const presentation = planPresentation(opportunity);- const { planId, data, error, isLoading, matches } = plan;- const href =- planId && matches- ? adapter.refactoringPlanHref?.(planId, opportunity.opportunity_id)- : undefined;- const steps = opportunity.plan_steps;-- return (- <Section title="Plan">- <p className="text-sm font-medium text-[var(--color-text-primary)]">{presentation.label}</p>- {opportunity.lower_priority ? (- <p className="mt-1">- <LowerPriorityTag reason={opportunity.lower_priority} />- </p>- ) : null}- {opportunity.preview ? (- <p className="mt-1">- <PreviewBadge note={opportunity.preview} />- </p>- ) : null}- <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">{presentation.detail}</p>- {opportunity.fix ? (- <p className="mt-2 text-sm text-[var(--color-text-secondary)]">- Proposed intervention: {humanizeToken(opportunity.fix.strategy).toLowerCase()}- {opportunity.fix.api ? (- <>- {" "}- (<code className="font-mono text-xs">{opportunity.fix.api}</code>)- </>- ) : null}- . {opportunity.fix.rationale}- </p>- ) : null}- {steps && steps.length > 0 ? <PlanSteps steps={steps} /> : null}- {planId && !enabled ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- This host cannot open the stored plan. Its id is{" "}- <span className="break-all font-mono">{planId}</span>.- </p>- ) : null}- {planId && enabled && isLoading ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">Checking the stored plan.</p>- ) : null}- {planId && enabled && error ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- The stored plan could not be loaded, so it is not offered here.- </p>- ) : null}- {data && !matches ? (- <p className="mt-2 text-sm text-[var(--color-warning)]">- The stored plan no longer names this opportunity. Update the index before handing it to- an agent.- </p>- ) : null}- {href ? (- <a- href={href}- className="mt-2 inline-block rounded text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"- >- Open the plan on Refactoring- </a>- ) : null}- </Section>- );-}--export function OpportunityDrawer({- opportunity,- adapter,- detailEnabled,- planEnabled,- onClose,- onAgentHandoff,- onSelectById,-}: {- /** The row that was inspected, held so the panel can render before the fetch. */- opportunity: PerformanceOpportunity | null;- adapter: PerformanceViewAdapter;- detailEnabled: boolean;- planEnabled: boolean;- onClose: () => void;- onAgentHandoff: (opportunity: PerformanceOpportunity, plan: RefactoringPlan | null) => void;- /** Open a sibling cause by id, replacing the drawer's contents in place. */- onSelectById?: ((opportunityId: string) => void) | undefined;-}) {- const id = opportunity?.opportunity_id ?? null;- const { data: detail } = useSWR<PerformanceOpportunityDetail>(- id && detailEnabled ? `performance-opportunity:${adapter.cacheKey}:${id}` : null,- () => adapter.getPerformanceOpportunity!(id!, { evidenceLimit: 8 }),- { revalidateOnFocus: false },- );-- // The row is the fallback body: a host without the detail call still reads- // every field the queue carried, and simply learns nothing extra.- const resolved = detail && detail.found ? detail : null;- const current: PerformanceOpportunity | null = resolved ?? opportunity;- const plan = useVerifiedPlan(current, adapter, planEnabled);-- return (- <AdaptivePanel- open={opportunity !== null}- onOpenChange={(open) => {- if (!open) onClose();- }}- eyebrow="Performance fix"- title={current ? opportunityTitle(current) : "Performance fix"}- widthClassName="md:max-w-[680px]"- >- {current ? (- <div className="flex min-h-0 flex-1 flex-col">- <div className="flex-1 space-y-7 overflow-y-auto px-5 py-5">- <WhereToEdit opportunity={current} />-- <StatusNotices detail={detail} />-- <MapLink adapter={adapter} opportunity={current} />-- <FixSummary opportunity={current} />-- <CodeSection opportunity={current} adapter={adapter} />-- {current.siblings && current.siblings.length > 0 ? (- <SiblingsNote siblings={current.siblings} onSelect={onSelectById} />- ) : null}-- <ChangeabilitySection current={current} />-- <PlanSection- opportunity={current}- adapter={adapter}- enabled={planEnabled}- plan={plan}- />-- <RelatedSection adapter={adapter} filePath={current.file_path} />-- <TestsSection current={current} adapter={adapter} />-- <EvidenceSection current={current} />-- <WhyRankedSection current={current} />-- <CallerPathsSection current={current} adapter={adapter} />-- <RawObservations- opportunityId={current.opportunity_id}- preview={current.evidence}- previewTruncated={current.evidence_truncated}- total={current.observations_total}- adapter={adapter}- />-- <AgentHandoffSection current={current} resolved={resolved} />- </div>-- <div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">- <button- type="button"- onClick={() => onAgentHandoff(current, plan.verified)}- className="inline-flex items-center justify-center gap-2 rounded-lg bg-[var(--color-model)] px-3.5 py-2 text-sm font-semibold text-[var(--color-text-on-model)] transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"- >- <Sparkles className="h-4 w-4" aria-hidden="true" />- {plan.verified ? "Copy the plan for an agent" : "Copy an agent handoff"}- </button>- </div>- </div>- ) : null}- </AdaptivePanel>- );-}--/**- * The fix in three facts a person decides on: what it buys (core's words),- * how big the change is, and where it goes.- */-/**- * Under the title: where the edit goes. The sink is not repeated here; it is- * named once, under the code it is reached from.- */-function WhereToEdit({ opportunity }: { opportunity: PerformanceOpportunity }) {- const kind = interventionKind(opportunity);- const symbol = opportunity.intervention_symbol?.trim();- const where = symbol ? (moduleScopeLabel(symbol) ?? symbol) : opportunity.file_path;- return (- <p className="text-xs text-[var(--color-text-tertiary)]">- Edit {kind ? `${INTERVENTION_KIND_LABEL[kind].toLowerCase()}, ` : ""}- <span className="break-all font-mono text-[var(--color-text-secondary)]">{where}</span>- </p>- );-}--function FixSummary({ opportunity }: { opportunity: PerformanceOpportunity }) {- const effort = opportunity.plan_economics?.effort_bucket;- const effortLabel =- effort && effort in EFFORT_LABEL ? EFFORT_LABEL[effort as keyof typeof EFFORT_LABEL] : null;- return (- <Section title={`The ${WORK_UNIT_LABEL.perf_fix}`}>- <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">- <Field- label="Gain"- value={opportunity.gain_text ?? "Not stated by this server"}- detail="The repeated work the fix removes. Not a measured time saving."- />- <Field- label="Effort"- value={effortLabel ?? "Not sized"}- {...(effortLabel ? {} : { detail: "No stored plan, so the change was not sized." })}- />- </dl>- </Section>- );-}--/**- * The code: the loop's call, read from the checkout at the line the first- * observation stored, and the sink it reaches. The sink is a symbol without a- * stored line, so it is named rather than excerpted.- */-function CodeSection({- opportunity,- adapter,-}: {- opportunity: PerformanceOpportunity;- adapter: PerformanceViewAdapter;-}) {- const first = opportunity.evidence.find((item) => item.line_start != null);- const sink = opportunity.terminal_sink?.trim();- if (!first && !sink) return null;- return (- <Section title="The code">- {first ? (- <div className="space-y-1.5">- <p className="text-xs text-[var(--color-text-tertiary)]">- Where the loop makes the call,{" "}- <span className="break-all font-mono text-[var(--color-text-secondary)]">- {first.file_path}:{first.line_start}- </span>- </p>- {adapter.readSource ? (- <SourceExcerpt- path={first.file_path}- start={first.line_start!}- end={(first.line_end ?? first.line_start!) + 2}- readSource={adapter.readSource}- widen={(fileLines) => loopHeaderAbove(fileLines, first.line_start!)}- />- ) : null}- </div>- ) : null}- {sink ? (- <p className="mt-3 text-xs text-[var(--color-text-tertiary)]">- It reaches{" "}- <span className="break-all font-mono text-[var(--color-text-secondary)]">- {moduleScopeLabel(sink) ?? sink}- </span>- .- </p>- ) : null}- </Section>- );-}--/** What the other lenses hold for the file this cause is fixed in. */-function RelatedSection({- adapter,- filePath,-}: {- adapter: PerformanceViewAdapter;- filePath: string;-}) {- const data = useRelatedWork(adapter.getRelatedWork, [filePath]);- return (- <RelatedWork- related={data?.files?.[0]}- relatedWorkHref={adapter.relatedWorkHref}- onNavigate={adapter.navigate}- exclude={["performance"]}- headingLevel="h4"- />- );-}--/**- * Where this cause sits on the one map.- *- * A link rather than a second canvas: the galaxy already exists, it already- * knows how to guarantee a file a node, and drawing a small copy of it here- * would put two fields with two geometries on one screen.- */-function MapLink({- adapter,- opportunity,-}: {- adapter: PerformanceViewAdapter;- opportunity: PerformanceOpportunity;-}) {- const href = adapter.mapHref?.(opportunity.opportunity_id, opportunity.file_path);- if (!href || !opportunity.file_path) return null;- return (- <a- href={href}- className="inline-block rounded text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"- >- Show this cause on the map- </a>- );-}--/** Whether the id resolved, and whether anything still supports it. */-function StatusNotices({ detail }: { detail: PerformanceOpportunityDetail | undefined }) {- const resolved = detail && detail.found ? detail : null;- const unresolved = detail && !detail.found ? detail : null;- return (- <>- {unresolved ? <ModelStateNotice state={unresolved.model_state} /> : null}- {resolved ? <ModelStateNotice state={resolved.model_state} /> : null}- {unresolved ? (- <p className="text-sm text-[var(--color-text-tertiary)]">{unresolved.detail}</p>- ) : null}- {resolved && resolved.lifecycle_status === "resolved" ? (- <p- role="status"- className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"- >- No observation supports this cause in the current index. It is kept so a saved- link still resolves.- </p>- ) : null}- </>- );-}--function ChangeabilitySection({ current }: { current: PerformanceOpportunity }) {- return (- <Section title="Whether it can be changed">- <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">- <Field- label="Actionability"- value={ACTIONABILITY_LABEL[current.actionability_state]}- detail={humanizeToken(current.actionability_reason)}- />- <Field- label="Actionability confidence"- value={CONFIDENCE_LABEL[current.facets.actionability_confidence]}- detail="Whether reducing the work is likely valid."- />- <Field- label="Fix safety"- value={current.fix ? humanizeToken(current.fix.safety) : "No named fix"}- detail={- current.fix- ? "Whether this one transformation is safe to apply."- : "No transformation was proposed, so none was judged safe."- }- />- </dl>- {current.prerequisites.length > 0 ? (- <div className="mt-3">- <p className="text-xs text-[var(--color-text-tertiary)]">- Missing before a fix can be named:- </p>- <ul className="mt-1 list-inside list-disc text-xs text-[var(--color-text-secondary)]">- {current.prerequisites.map((item) => (- <li key={item}>{humanizeToken(item)}</li>- ))}- </ul>- </div>- ) : null}- </Section>- );-}--function TestsSection({- current,- adapter,-}: {- current: PerformanceOpportunity;- adapter: PerformanceViewAdapter;-}) {- if (!current.validation) return null;- return (- <CollapsibleSection- title="Tests"- hint={- current.validation.total > 0- ? `${formatNumber(current.validation.total)} guarding`- : "none guarding"- }- defaultOpen={current.validation.total === 0}- >- <ValidationSummary- validation={toRecommendationValidation(current.validation)}- fileHref={adapter.fileHref}- />- </CollapsibleSection>- );-}--function EvidenceSection({ current }: { current: PerformanceOpportunity }) {- return (- <CollapsibleSection title="What the evidence shows">- <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">- <Field label="Context" value={contextLabel(current.execution_context)} />- <Field label="Boundary" value={boundaryLabel(current.boundary_kind)} />- <Field- label="Evidence confidence"- value={CONFIDENCE_LABEL[current.confidence]}- detail={`How reliably the call path resolved. Provenance: ${humanizeToken(current.provenance).toLowerCase()}.`}- />- <Field- label="Affected"- value={affectedSummary(current)}- detail={`${current.observations_total.toLocaleString()} observation${current.observations_total === 1 ? "" : "s"} fold into this cause.`}- />- <Field- label="Amplification"- value={humanizeToken(current.facets.amplification)}- hint={FACET_GLOSSARY.amplification}- />- <Field- label="Exposure"- value={humanizeToken(current.facets.exposure)}- hint={FACET_GLOSSARY.exposure}- />- <Field- label="Leverage"- value={humanizeToken(current.facets.leverage)}- hint={FACET_GLOSSARY.leverage}- />- <Field- label="Change risk"- value={humanizeToken(current.facets.change_risk)}- hint={FACET_GLOSSARY.change_risk}- />- {current.facets.loop_magnitude && current.facets.loop_magnitude !== "n/a" ? (- <Field- label="Loop magnitude"- value={humanizeToken(current.facets.loop_magnitude)}- hint={FACET_GLOSSARY.loop_magnitude}- />- ) : null}- </dl>- </CollapsibleSection>- );-}--function WhyRankedSection({ current }: { current: PerformanceOpportunity }) {- return (- <CollapsibleSection title="Why it ranks here">- <p className="text-sm text-[var(--color-text-secondary)]">- Position <span className="tabular-nums">{(current.rank_position + 1).toLocaleString()}</span>{" "}- in the queue.- </p>- {current.why_ranked.length > 0 ? (- <ul className="mt-2 space-y-1 text-sm text-[var(--color-text-secondary)]">- {current.why_ranked.map((factor) => (- <li key={factor.factor} className="tabular-nums">- {whyRankedLabel(factor)}- </li>- ))}- </ul>- ) : null}- </CollapsibleSection>- );-}--function CallerPathsSection({- current,- adapter,-}: {- current: PerformanceOpportunity;- adapter: PerformanceViewAdapter;-}) {- if (!current.evidence.some((item) => item.path.length > 0)) return null;- return (- <CollapsibleSection title="Caller to sink paths">- <ProvenancePathList- paths={current.evidence- .filter((item) => item.path.length > 0)- .map((item) => ({ nodes: item.path, provenance: item.provenance }))}- total={current.observations_total}- fileHref={adapter.fileHref}- {...(adapter.symbolHref ? { symbolHref: adapter.symbolHref } : {})}- />- </CollapsibleSection>- );-}--function AgentHandoffSection({- current,- resolved,-}: {- current: PerformanceOpportunity;- resolved: Extract<PerformanceOpportunityDetail, { found: true }> | null;-}) {- return (- <CollapsibleSection title="Hand this to an agent">- <p className="text-sm text-[var(--color-text-secondary)]">- Ask for the same record by its stable id:- </p>- <p className="mt-1 break-all rounded bg-[var(--color-bg-inset)] px-2 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">- {agentHandoffCall(current.opportunity_id)}- </p>- {resolved?.analyzed_commit ? (- <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">- Analyzed at{" "}- <span className="font-mono">{resolved.analyzed_commit.slice(0, 7)}</span>.- </p>- ) : null}- </CollapsibleSection>- );-}diff --git a/packages/ui/src/health/performance/drawer/fix.tsx b/packages/ui/src/health/performance/drawer/fix.tsxnew file mode 100644index 000000000..3765bd25c--- /dev/null+++ b/packages/ui/src/health/performance/drawer/fix.tsx@@ -0,0 +1,216 @@+"use client";++import type { PerformanceOpportunity, PerformanceOpportunitySibling } from "@repowise-dev/types/health";++import { SourceExcerpt } from "../../../refactoring/source-excerpt";+import { WORK_UNIT_LABEL } from "../../labels";+import { RelatedWork, useRelatedWork } from "../../related-work";+import type { PerformanceViewAdapter } from "../adapter";+import {+ effortLabel,+ humanizeToken,+ INTERVENTION_KIND_LABEL,+ interventionKind,+ loopHeaderAbove,+ moduleScopeLabel,+ siblingFixLabel,+} from "../presentation";+import { Field, Section } from "./layout";++/** The fix itself: where it goes, what it buys, the code it changes, and the+ * other causes on the same lines. */++/**+ * Under the title: where the edit goes. The sink is not repeated here; it is+ * named once, under the code it is reached from.+ */+export function WhereToEdit({ opportunity }: { opportunity: PerformanceOpportunity }) {+ const kind = interventionKind(opportunity);+ const symbol = opportunity.intervention_symbol?.trim();+ const where = symbol ? (moduleScopeLabel(symbol) ?? symbol) : opportunity.file_path;+ return (+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Edit {kind ? `${INTERVENTION_KIND_LABEL[kind].toLowerCase()}, ` : ""}+ <span className="break-all font-mono text-[var(--color-text-secondary)]">{where}</span>+ </p>+ );+}++export function FixSummary({ opportunity }: { opportunity: PerformanceOpportunity }) {+ const effort = effortLabel(opportunity);+ return (+ <Section title={`The ${WORK_UNIT_LABEL.perf_fix}`}>+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">+ <Field+ label="Gain"+ value={opportunity.gain_text ?? "Not stated by this server"}+ detail="The repeated work the fix removes. Not a measured time saving."+ />+ <Field+ label="Effort"+ value={effort ?? "Not sized"}+ {...(effort ? {} : { detail: "No stored plan, so the change was not sized." })}+ />+ </dl>+ </Section>+ );+}++/**+ * The code: the loop's call, read from the checkout at the line the first+ * observation stored, and the sink it reaches. The sink is a symbol without a+ * stored line, so it is named rather than excerpted.+ */+export function CodeSection({+ opportunity,+ adapter,+}: {+ opportunity: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+}) {+ const first = opportunity.evidence.find((item) => item.line_start != null);+ const sink = opportunity.terminal_sink?.trim();+ if (!first && !sink) return null;+ return (+ <Section title="The code">+ {first ? (+ <div className="space-y-1.5">+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Where the loop makes the call,{" "}+ <span className="break-all font-mono text-[var(--color-text-secondary)]">+ {first.file_path}:{first.line_start}+ </span>+ </p>+ {adapter.readSource ? (+ <SourceExcerpt+ path={first.file_path}+ start={first.line_start!}+ end={(first.line_end ?? first.line_start!) + 2}+ readSource={adapter.readSource}+ widen={(fileLines) => loopHeaderAbove(fileLines, first.line_start!)}+ />+ ) : null}+ </div>+ ) : null}+ {sink ? (+ <p className="mt-3 text-xs text-[var(--color-text-tertiary)]">+ It reaches{" "}+ <span className="break-all font-mono text-[var(--color-text-secondary)]">+ {moduleScopeLabel(sink) ?? sink}+ </span>+ .+ </p>+ ) : null}+ </Section>+ );+}++/** What the other lenses hold for the file this cause is fixed in. */+export function RelatedSection({+ adapter,+ filePath,+}: {+ adapter: PerformanceViewAdapter;+ filePath: string;+}) {+ const data = useRelatedWork(adapter.getRelatedWork, [filePath]);+ return (+ <RelatedWork+ related={data?.files?.[0]}+ relatedWorkHref={adapter.relatedWorkHref}+ onNavigate={adapter.navigate}+ exclude={["performance"]}+ headingLevel="h4"+ />+ );+}++/**+ * Where this cause sits on the one map.+ *+ * A link rather than a second canvas: the galaxy already exists, it already+ * knows how to guarantee a file a node, and drawing a small copy of it here+ * would put two fields with two geometries on one screen.+ */+export function MapLink({+ adapter,+ opportunity,+}: {+ adapter: PerformanceViewAdapter;+ opportunity: PerformanceOpportunity;+}) {+ const href = adapter.mapHref?.(opportunity.opportunity_id, opportunity.file_path);+ if (!href || !opportunity.file_path) return null;+ return (+ <a+ href={href}+ className="inline-block rounded text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ Show this cause on the map+ </a>+ );+}++/** One sibling's fix, as a link when the drawer can open another opportunity,+ * plain text otherwise (an agent-facing or read-only host, say). */+function SiblingLink({+ sibling,+ label,+ onSelect,+}: {+ sibling: PerformanceOpportunitySibling;+ label: string;+ onSelect?: ((opportunityId: string) => void) | undefined;+}) {+ if (!onSelect) {+ return <span className="font-medium text-[var(--color-text-secondary)]">{label}</span>;+ }+ return (+ <button+ type="button"+ onClick={() => onSelect(sibling.opportunity_id)}+ className="rounded font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {label}+ </button>+ );+}++/** Other causes on the same lines, one quiet line. A `preferred` sibling says+ * plainly that its fix is the stronger one; the rest are just named. */+export function SiblingsNote({+ siblings,+ onSelect,+}: {+ siblings: PerformanceOpportunitySibling[];+ onSelect?: ((opportunityId: string) => void) | undefined;+}) {+ const preferred = siblings.filter((sibling) => sibling.relation === "preferred");+ const rest = siblings.filter((sibling) => sibling.relation !== "preferred");+ return (+ <p className="mt-3 text-xs text-[var(--color-text-tertiary)]">+ {preferred.map((sibling) => (+ <span key={sibling.opportunity_id} className="block">+ {siblingFixLabel(sibling)} is the stronger fix here; see{" "}+ <SiblingLink sibling={sibling} label="this cause" onSelect={onSelect} />.+ </span>+ ))}+ {rest.length > 0 ? (+ <span className="block">+ Also flagged on these lines:{" "}+ {rest.map((sibling, index) => (+ <span key={sibling.opportunity_id}>+ {index > 0 ? ", " : ""}+ <SiblingLink+ sibling={sibling}+ label={humanizeToken(sibling.biomarker_type)}+ onSelect={onSelect}+ />+ </span>+ ))}+ .+ </span>+ ) : null}+ </p>+ );+}diff --git a/packages/ui/src/health/performance/drawer/index.tsx b/packages/ui/src/health/performance/drawer/index.tsxnew file mode 100644index 000000000..b5a951704--- /dev/null+++ b/packages/ui/src/health/performance/drawer/index.tsx@@ -0,0 +1,119 @@+"use client";++import type { PerformanceOpportunity } from "@repowise-dev/types/health";++import { AdaptivePanel } from "../../../shared/adaptive-panel";+import { AGENT_PROMPT_LABEL } from "../../ai-prompt-action";+import { AiPromptButton } from "../../ai-prompt-button";+import type { PerformanceViewAdapter } from "../adapter";+import { useOpportunityDetail } from "../cache";+import { RawObservations } from "../evidence";+import { opportunityTitle } from "../presentation";+import {+ CodeSection,+ FixSummary,+ MapLink,+ RelatedSection,+ SiblingsNote,+ WhereToEdit,+} from "./fix";+import {+ AgentHandoffSection,+ CallerPathsSection,+ ChangeabilitySection,+ EvidenceSection,+ TestsSection,+ WhyRankedSection,+} from "./judgements";+import { StatusNotices } from "./layout";+import { PlanSection, useVerifiedPlan } from "./plan";++/**+ * One opportunity in depth.+ *+ * The three judgements the analysis makes separately are shown separately:+ * how well the evidence resolved, whether reducing the work is likely valid,+ * and whether one named transformation is safe. Collapsing them would let+ * strong evidence read as a safe fix.+ *+ * Mounted only while a cause is open, and loaded on first open, so the queue+ * never pays for it.+ */+export default function OpportunityDrawer({+ opportunity,+ adapter,+ detailEnabled,+ planEnabled,+ onClose,+ onAgentPrompt,+ onSelectById,+}: {+ /** The row that was inspected, held so the panel can render before the fetch. */+ opportunity: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+ detailEnabled: boolean;+ planEnabled: boolean;+ onClose: () => void;+ onAgentPrompt: (opportunity: PerformanceOpportunity) => void;+ /** Open a sibling cause by id, replacing the drawer's contents in place. */+ onSelectById?: ((opportunityId: string) => void) | undefined;+}) {+ const { data: detail } = useOpportunityDetail(+ adapter,+ detailEnabled ? opportunity.opportunity_id : null,+ );++ // The row is the fallback body: a host without the detail call still reads+ // every field the queue carried, and simply learns nothing extra.+ const resolved = detail && detail.found ? detail : null;+ const current: PerformanceOpportunity = resolved ?? opportunity;+ const plan = useVerifiedPlan(current, adapter, planEnabled);++ return (+ <AdaptivePanel+ open+ onOpenChange={(open) => {+ if (!open) onClose();+ }}+ eyebrow="Performance fix"+ title={opportunityTitle(current)}+ widthClassName="md:max-w-[680px]"+ >+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex-1 space-y-7 overflow-y-auto px-5 py-5">+ <WhereToEdit opportunity={current} />+ <StatusNotices detail={detail} />+ <MapLink adapter={adapter} opportunity={current} />+ <FixSummary opportunity={current} />+ <CodeSection opportunity={current} adapter={adapter} />+ {current.siblings && current.siblings.length > 0 ? (+ <SiblingsNote siblings={current.siblings} onSelect={onSelectById} />+ ) : null}+ <ChangeabilitySection current={current} />+ <PlanSection opportunity={current} adapter={adapter} enabled={planEnabled} plan={plan} />+ <RelatedSection adapter={adapter} filePath={current.file_path} />+ <TestsSection current={current} adapter={adapter} />+ <EvidenceSection current={current} />+ <WhyRankedSection current={current} />+ <CallerPathsSection current={current} adapter={adapter} />+ <RawObservations+ opportunityId={current.opportunity_id}+ preview={current.evidence}+ previewTruncated={current.evidence_truncated}+ total={current.observations_total}+ adapter={adapter}+ />+ <AgentHandoffSection current={current} resolved={resolved} />+ </div>++ <div className="flex items-center gap-3 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3.5">+ <AiPromptButton+ label={AGENT_PROMPT_LABEL}+ onClick={() => onAgentPrompt(current)}+ className="px-3.5 py-2 text-sm"+ />+ </div>+ </div>+ </AdaptivePanel>+ );+}diff --git a/packages/ui/src/health/performance/drawer/judgements.tsx b/packages/ui/src/health/performance/drawer/judgements.tsxnew file mode 100644index 000000000..4d5ba25eb--- /dev/null+++ b/packages/ui/src/health/performance/drawer/judgements.tsx@@ -0,0 +1,230 @@+"use client";++import type {+ PerformanceOpportunity,+ PerformanceOpportunityDetail,+ PerformanceOpportunityValidation,+} from "@repowise-dev/types/health";+import type { RecommendationValidation } from "@repowise-dev/types/refactoring";++import { formatNumber } from "../../../lib/format";+import { CollapsibleSection } from "../../../shared/collapsible-section";+import { ProvenancePathList } from "../../../shared/provenance-path-list";+import { ValidationSummary } from "../../../refactoring/validation-summary";+import type { PerformanceViewAdapter } from "../adapter";+import {+ ACTIONABILITY_LABEL,+ affectedSummary,+ agentHandoffCall,+ boundaryLabel,+ CONFIDENCE_LABEL,+ contextLabel,+ FACET_GLOSSARY,+ humanizeToken,+ whyRankedLabel,+} from "../presentation";+import { Field, Section } from "./layout";++/** The judgement and evidence sections, most of them collapsed. The three+ * judgements stay separate: evidence confidence, actionability, fix safety. */++/** The queue's small validation shape, adapted onto the refactoring surface's+ * reader rather than duplicated. The fields it doesn't materialize (per-target+ * breakdown, affected paths) read as empty, not missing. */+function toRecommendationValidation(+ validation: PerformanceOpportunityValidation,+): RecommendationValidation {+ return {+ basis: validation.basis,+ via: validation.via,+ total: validation.total,+ tests: validation.tests,+ truncated: false,+ affected_files: [],+ affected_symbols: [],+ commands: validation.commands,+ targets: [],+ ...(validation.reasons ? { reasons: validation.reasons } : {}),+ };+}++export function ChangeabilitySection({ current }: { current: PerformanceOpportunity }) {+ return (+ <Section title="Whether it can be changed">+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">+ <Field+ label="Actionability"+ value={ACTIONABILITY_LABEL[current.actionability_state]}+ detail={humanizeToken(current.actionability_reason)}+ />+ <Field+ label="Actionability confidence"+ value={CONFIDENCE_LABEL[current.facets.actionability_confidence]}+ detail="Whether reducing the work is likely valid."+ />+ <Field+ label="Fix safety"+ value={current.fix ? humanizeToken(current.fix.safety) : "No named fix"}+ detail={+ current.fix+ ? "Whether this one transformation is safe to apply."+ : "No transformation was proposed, so none was judged safe."+ }+ />+ </dl>+ {current.prerequisites.length > 0 ? (+ <div className="mt-3">+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Missing before a fix can be named:+ </p>+ <ul className="mt-1 list-inside list-disc text-xs text-[var(--color-text-secondary)]">+ {current.prerequisites.map((item) => (+ <li key={item}>{humanizeToken(item)}</li>+ ))}+ </ul>+ </div>+ ) : null}+ </Section>+ );+}++export function TestsSection({+ current,+ adapter,+}: {+ current: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+}) {+ if (!current.validation) return null;+ return (+ <CollapsibleSection+ title="Tests"+ hint={+ current.validation.total > 0+ ? `${formatNumber(current.validation.total)} guarding`+ : "none guarding"+ }+ defaultOpen={current.validation.total === 0}+ >+ <ValidationSummary+ validation={toRecommendationValidation(current.validation)}+ fileHref={adapter.fileHref}+ />+ </CollapsibleSection>+ );+}++export function EvidenceSection({ current }: { current: PerformanceOpportunity }) {+ return (+ <CollapsibleSection title="What the evidence shows">+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">+ <Field label="Context" value={contextLabel(current.execution_context)} />+ <Field label="Boundary" value={boundaryLabel(current.boundary_kind)} />+ <Field+ label="Evidence confidence"+ value={CONFIDENCE_LABEL[current.confidence]}+ detail={`How reliably the call path resolved. Provenance: ${humanizeToken(current.provenance).toLowerCase()}.`}+ />+ <Field+ label="Affected"+ value={affectedSummary(current)}+ detail={`${current.observations_total.toLocaleString()} observation${current.observations_total === 1 ? "" : "s"} fold into this cause.`}+ />+ <Field+ label="Amplification"+ value={humanizeToken(current.facets.amplification)}+ hint={FACET_GLOSSARY.amplification}+ />+ <Field+ label="Exposure"+ value={humanizeToken(current.facets.exposure)}+ hint={FACET_GLOSSARY.exposure}+ />+ <Field+ label="Leverage"+ value={humanizeToken(current.facets.leverage)}+ hint={FACET_GLOSSARY.leverage}+ />+ <Field+ label="Change risk"+ value={humanizeToken(current.facets.change_risk)}+ hint={FACET_GLOSSARY.change_risk}+ />+ {current.facets.loop_magnitude && current.facets.loop_magnitude !== "n/a" ? (+ <Field+ label="Loop magnitude"+ value={humanizeToken(current.facets.loop_magnitude)}+ hint={FACET_GLOSSARY.loop_magnitude}+ />+ ) : null}+ </dl>+ </CollapsibleSection>+ );+}++export function WhyRankedSection({ current }: { current: PerformanceOpportunity }) {+ return (+ <CollapsibleSection title="Why it ranks here">+ <p className="text-sm text-[var(--color-text-secondary)]">+ Position <span className="tabular-nums">{(current.rank_position + 1).toLocaleString()}</span>{" "}+ in the queue.+ </p>+ {current.why_ranked.length > 0 ? (+ <ul className="mt-2 space-y-1 text-sm text-[var(--color-text-secondary)]">+ {current.why_ranked.map((factor) => (+ <li key={factor.factor} className="tabular-nums">+ {whyRankedLabel(factor)}+ </li>+ ))}+ </ul>+ ) : null}+ </CollapsibleSection>+ );+}++export function CallerPathsSection({+ current,+ adapter,+}: {+ current: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+}) {+ if (!current.evidence.some((item) => item.path.length > 0)) return null;+ return (+ <CollapsibleSection title="Caller to sink paths">+ <ProvenancePathList+ paths={current.evidence+ .filter((item) => item.path.length > 0)+ .map((item) => ({ nodes: item.path, provenance: item.provenance }))}+ total={current.observations_total}+ fileHref={adapter.fileHref}+ {...(adapter.symbolHref ? { symbolHref: adapter.symbolHref } : {})}+ />+ </CollapsibleSection>+ );+}++export function AgentHandoffSection({+ current,+ resolved,+}: {+ current: PerformanceOpportunity;+ resolved: Extract<PerformanceOpportunityDetail, { found: true }> | null;+}) {+ return (+ <CollapsibleSection title="Hand this to an agent">+ <p className="text-sm text-[var(--color-text-secondary)]">+ Ask for the same record by its stable id:+ </p>+ <p className="mt-1 break-all rounded bg-[var(--color-bg-inset)] px-2 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">+ {agentHandoffCall(current.opportunity_id)}+ </p>+ {resolved?.analyzed_commit ? (+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">+ Analyzed at{" "}+ <span className="font-mono">{resolved.analyzed_commit.slice(0, 7)}</span>.+ </p>+ ) : null}+ </CollapsibleSection>+ );+}diff --git a/packages/ui/src/health/performance/drawer/layout.tsx b/packages/ui/src/health/performance/drawer/layout.tsxnew file mode 100644index 000000000..c36e94c88--- /dev/null+++ b/packages/ui/src/health/performance/drawer/layout.tsx@@ -0,0 +1,90 @@+"use client";++import type { PerformanceModelState, PerformanceOpportunityDetail } from "@repowise-dev/types/health";++import { InfoTip } from "../../../shared/info-tip";++/** The drawer's building blocks: a labelled field, a section, and the notices+ * that say whether the id still resolves. */++export function Field({+ label,+ value,+ detail,+ hint,+}: {+ label: string;+ value: string;+ detail?: string | undefined;+ /** What the facet means, from the glossary, on hover or tap. */+ hint?: string | undefined;+}) {+ return (+ <div className="min-w-0">+ <dt className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {label}+ {hint ? <InfoTip content={hint} label={`What ${label.toLowerCase()} means`} /> : null}+ </dt>+ <dd className="mt-0.5 text-sm font-medium text-[var(--color-text-primary)]">{value}</dd>+ {detail ? (+ <dd className="mt-0.5 text-xs text-[var(--color-text-tertiary)]">{detail}</dd>+ ) : null}+ </div>+ );+}++export function Section({ title, children }: { title: string; children: React.ReactNode }) {+ return (+ <section>+ <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {title}+ </h4>+ {children}+ </section>+ );+}++/** A resolved id that came from another model is not the same as a wrong id. */+function ModelStateNotice({ state }: { state: PerformanceModelState }) {+ if (state.state === "current") return null;+ const message =+ state.state === "stale_model"+ ? `This id was minted by performance model version ${state.requested_model_version ?? "an earlier release"}; the index now serves version ${state.performance_model_version}.`+ : "This index does not recognize that opportunity id.";+ return (+ <p+ role="status"+ className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"+ >+ {message}+ {state.refresh_required ? " Update the index to get the current grouping." : ""}+ </p>+ );+}++/** Whether the id resolved, and whether anything still supports it. */+export function StatusNotices({ detail }: { detail: PerformanceOpportunityDetail | undefined }) {+ if (!detail) return null;+ if (!detail.found) {+ return (+ <>+ <ModelStateNotice state={detail.model_state} />+ <p className="text-sm text-[var(--color-text-tertiary)]">{detail.detail}</p>+ </>+ );+ }+ return (+ <>+ <ModelStateNotice state={detail.model_state} />+ {detail.lifecycle_status === "resolved" ? (+ <p+ role="status"+ className="border-l-2 border-[var(--color-warning)] py-1.5 pl-3 text-sm text-[var(--color-text-secondary)]"+ >+ No observation supports this cause in the current index. It is kept so a saved+ link still resolves.+ </p>+ ) : null}+ </>+ );+}diff --git a/packages/ui/src/health/performance/drawer/plan.tsx b/packages/ui/src/health/performance/drawer/plan.tsxnew file mode 100644index 000000000..94a08e60e--- /dev/null+++ b/packages/ui/src/health/performance/drawer/plan.tsx@@ -0,0 +1,221 @@+"use client";++import type {+ PerformanceOpportunity,+ PerformanceOpportunityPlanStep,+} from "@repowise-dev/types/health";+import type { StepVerify } from "@repowise-dev/types/refactoring";++import { CommandLine } from "../../../shared/command-line";+import type { PerformanceViewAdapter } from "../adapter";+import { planMatches, usePlan } from "../cache";+import { fixStrategyLabel, planPresentation } from "../presentation";+import { OpportunityTags } from "../tags";+import { Section } from "./layout";++/**+ * Fetch the stored plan and decide whether it names this exact opportunity.+ * A reindexed or reused row must never be handed over as this one's fix, so+ * both the link and the agent handoff wait on the same verdict.+ */+export function useVerifiedPlan(+ opportunity: PerformanceOpportunity | null,+ adapter: PerformanceViewAdapter,+ enabled: boolean,+) {+ const planId =+ opportunity && planPresentation(opportunity).actionable ? opportunity.plan_id : null;+ const { data, error, isLoading } = usePlan(adapter, enabled ? planId : null);+ const matches = Boolean(opportunity && planMatches(data, opportunity));+ return { planId, data, error, isLoading, matches };+}++/**+ * The plan's edits in order; only the rarer mechanical ones are marked.+ *+ * Consecutive steps that make the same edit at different call sites read as+ * one step with its locations: the server emits one step per site, and eight+ * copies of "Collect the keys before the loop" said nothing seven times.+ */+/** Consecutive steps making the same edit, as one group in order. */+export function groupPlanSteps(+ steps: PerformanceOpportunityPlanStep[],+): PerformanceOpportunityPlanStep[][] {+ const groups: PerformanceOpportunityPlanStep[][] = [];+ for (const step of [...steps].sort((a, b) => a.order - b.order)) {+ const last = groups[groups.length - 1];+ if (last && last[0]!.action === step.action && last[0]!.applicability === step.applicability) {+ last.push(step);+ } else {+ groups.push([step]);+ }+ }+ return groups;+}++interface StepPlace {+ place: string;+ verify: StepVerify | undefined;+}++function placesOf(group: PerformanceOpportunityPlanStep[]): StepPlace[] {+ return group.flatMap((step) =>+ step.file_path+ ? [{ place: `${step.file_path}${step.line ? `:${step.line}` : ""}`, verify: step.verify }]+ : [],+ );+}++/** Where one step's edits go: inline for one place, a list for several. */+function StepPlaces({ places }: { places: StepPlace[] }) {+ if (places.length === 1) {+ return (+ <>+ <span className="ml-1.5 break-all font-mono text-xs text-[var(--color-text-tertiary)]">+ {places[0]!.place}+ </span>+ <StepCheck verify={places[0]!.verify} />+ </>+ );+ }+ if (places.length === 0) return null;+ return (+ <ul className="mt-1 space-y-0.5 pl-5">+ {places.map((p) => (+ <li key={p.place} className="break-all font-mono text-xs text-[var(--color-text-tertiary)]">+ {p.place}+ <StepCheck verify={p.verify} />+ </li>+ ))}+ </ul>+ );+}++function PlanSteps({ steps }: { steps: PerformanceOpportunityPlanStep[] }) {+ const note = "ml-1.5 text-xs text-[var(--color-text-tertiary)]";+ return (+ <ol className="mt-3 space-y-1.5">+ {groupPlanSteps(steps).map((group, index) => {+ const first = group[0]!;+ return (+ <li key={first.order} className="text-sm text-[var(--color-text-secondary)]">+ <span className="tabular-nums text-[var(--color-text-tertiary)]">{index + 1}.</span>{" "}+ {first.action}+ {group.length > 1 ? <span className={note}>{`at ${group.length} call sites`}</span> : null}+ {first.applicability === "mechanical" ? <span className={note}>mechanical</span> : null}+ <StepPlaces places={placesOf(group)} />+ </li>+ );+ })}+ </ol>+ );+}++/**+ * How to check one step, when it differs from the plan: the server omits+ * `verify` on a step the plan's validation already checks.+ */+function StepCheck({ verify }: { verify: StepVerify | undefined }) {+ if (!verify) return null;+ if (verify.coverage === "none") {+ return (+ <p className="mt-1 font-sans text-xs text-[var(--color-text-tertiary)]">+ No test reaches this step.+ </p>+ );+ }+ return (+ <>+ {verify.commands.map((command) => (+ <CommandLine key={command} command={command} />+ ))}+ </>+ );+}++/** The proposed fix in a sentence, with its concrete construct when named. */+function ProposedFix({ fix }: { fix: NonNullable<PerformanceOpportunity["fix"]> }) {+ return (+ <p className="mt-2 text-sm text-[var(--color-text-secondary)]">+ Proposed intervention: {fixStrategyLabel(fix.strategy).toLowerCase()}+ {fix.api ? (+ <>+ {" "}+ (<code className="font-mono text-xs">{fix.api}</code>)+ </>+ ) : null}+ . {fix.rationale}+ </p>+ );+}++/** Where the stored plan stands: unreachable, loading, failed or stale. */+function StoredPlanStatus({+ plan,+ enabled,+}: {+ plan: ReturnType<typeof useVerifiedPlan>;+ enabled: boolean;+}) {+ const { planId, data, error, isLoading, matches } = plan;+ const quiet = "mt-2 text-xs text-[var(--color-text-tertiary)]";+ if (planId && !enabled) {+ return (+ <p className={quiet}>+ This host cannot open the stored plan. Its id is{" "}+ <span className="break-all font-mono">{planId}</span>.+ </p>+ );+ }+ if (planId && isLoading) return <p className={quiet}>Checking the stored plan.</p>;+ if (planId && error) {+ return <p className={quiet}>The stored plan could not be loaded, so it is not offered here.</p>;+ }+ if (data && !matches) {+ return (+ <p className="mt-2 text-sm text-[var(--color-warning)]">+ The stored plan no longer names this opportunity. Update the index before handing it to an+ agent.+ </p>+ );+ }+ return null;+}++export function PlanSection({+ opportunity,+ adapter,+ enabled,+ plan,+}: {+ opportunity: PerformanceOpportunity;+ adapter: PerformanceViewAdapter;+ enabled: boolean;+ plan: ReturnType<typeof useVerifiedPlan>;+}) {+ const presentation = planPresentation(opportunity);+ const href =+ plan.planId && plan.matches+ ? adapter.refactoringPlanHref?.(plan.planId, opportunity.opportunity_id)+ : undefined;+ const steps = opportunity.plan_steps ?? [];++ return (+ <Section title="Plan">+ <p className="text-sm font-medium text-[var(--color-text-primary)]">{presentation.label}</p>+ <OpportunityTags opportunity={opportunity} />+ <p className="mt-1 text-sm text-[var(--color-text-tertiary)]">{presentation.detail}</p>+ {opportunity.fix ? <ProposedFix fix={opportunity.fix} /> : null}+ {steps.length > 0 ? <PlanSteps steps={steps} /> : null}+ <StoredPlanStatus plan={plan} enabled={enabled} />+ {href ? (+ <a+ href={href}+ className="mt-2 inline-block rounded text-sm font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ Open the plan on Refactoring+ </a>+ ) : null}+ </Section>+ );+}diff --git a/packages/ui/src/health/performance/filters.tsx b/packages/ui/src/health/performance/filters.tsxindex 116d4c244..b8688c287 100644--- a/packages/ui/src/health/performance/filters.tsx+++ b/packages/ui/src/health/performance/filters.tsx@@ -1,24 +1,15 @@"use client";import type {- PerformanceContextFilter,- PerformanceExecutionContext,PerformanceFacetCount,PerformanceFacetKey,PerformanceFacets,} from "@repowise-dev/types/health";import { FilterSelect } from "../code-health-controls";-import { ViewTabs } from "../../shared/view-tabs";+import { MoreFilters } from "../../shared/more-filters";+import { FACET_LABEL, facetValueLabel } from "./presentation";import {- CONTEXT_HINT,- CONTEXT_ORDER,- FACET_LABEL,- contextLabel,- facetValueLabel,-} from "./presentation";-import {- narrowingCount,type NarrowingKey,type PerformanceFilterState,type PerformanceSort,@@ -30,187 +21,99 @@ import {* removes its own alternatives from the list.*/-function countOf(counts: PerformanceFacetCount[] | undefined, value: string): number {- return counts?.find((entry) => entry.value === value)?.total ?? 0;-}--/**- * The four canonical contexts stay separate and always visible, because a- * context with no rows is a fact about the repository worth reading. When the- * server predates the vocabulary they collapse to the pairing it understands.- */-export function ContextTabs({- value,- facets,- total,- collapsed,- onChange,-}: {- value: PerformanceContextFilter;- facets: PerformanceFacets;- total: number;- collapsed: boolean;- onChange: (context: PerformanceContextFilter) => void;-}) {- const counts = facets.context;- const contexts: PerformanceExecutionContext[] = collapsed- ? ["production", "test"]- : CONTEXT_ORDER;- // `total` is the unscoped repository_total; `counts` is facets.context,- // which the server has already narrowed by every other active filter.- // Badge "All" with the sum of the (narrowed) context facet so it agrees- // with what clicking it actually returns. Fall back to `total` only when- // the server sends no facets.context at all (a server predating context- // scoping, which also won't send a narrowed repository_total).- const scopedTotal = counts?.reduce((sum, entry) => sum + entry.total, 0) ?? total;- const tabs = [- { id: "all", label: "All", badge: scopedTotal },- ...contexts.map((context) => ({- id: context,- label:- collapsed && context === "production" ? "Production & tooling" : contextLabel(context),- badge:- collapsed && context === "production"- ? countOf(counts, "production") + countOf(counts, "tooling")- : countOf(counts, context),- })),- ];- return (- <ViewTabs- tabs={tabs}- value={value}- onValueChange={(next) => onChange(next as PerformanceContextFilter)}- />- );-}-interface NarrowingSpec {key: NarrowingKey;facet: PerformanceFacetKey;anyLabel: string;}+/**+ * The server filters behind "More filters". Actionability is not among them:+ * the actionability bar is that axis's one control. Context is offered only+ * in Everything, where more than production is listed.+ */const NARROWING: NarrowingSpec[] = [- // "expected" causes are real but offer nothing to change, so the default- // (no explicit selection) reads as "every other state" rather than "any".- { key: "actionability", facet: "actionability", anyLabel: "All but expected" },+ { key: "context", facet: "context", anyLabel: "Any context" },{ key: "boundary", facet: "boundary", anyLabel: "Any" },{ key: "confidence", facet: "confidence", anyLabel: "Any" },- // Unproven causes (loop size unknown) are counted but never queued by default.- { key: "proof", facet: "proof", anyLabel: "Measured only" },- // Startup, CLI, tooling and test loops run once per process, so the default- // leaves them out; each role stays one selection away.- { key: "role", facet: "role", anyLabel: "Served paths" },+ { key: "proof", facet: "proof", anyLabel: "Any" },+ { key: "role", facet: "role", anyLabel: "Any" },];/*** A facet with one value is a fact, not a choice, so it is stated rather than* offered as a control that could only ever return the same rows.*/+/** The label and its one value; the count belongs to the options, and one value has none to compare. */function SingleValueFact({ facet, only }: { facet: PerformanceFacetKey; only: PerformanceFacetCount }) {return (<p className="text-xs text-[var(--color-text-tertiary)]">- <span className="uppercase tracking-wider">{FACET_LABEL[facet]}</span>{" "}+ {FACET_LABEL[facet]}:{" "}<span className="text-[var(--color-text-secondary)]">{facetValueLabel(facet, only.value)}- </span>{" "}- <span className="tabular-nums">on {only.total.toLocaleString()} matching</span>+ </span></p>);}-export function QueueFilters({+/** One server filter: a select over its facet, or a stated fact when it has one value. */+function NarrowingControl({+ spec: { key, facet, anyLabel },filters,facets,onChange,- onClear,}: {+ spec: NarrowingSpec;filters: PerformanceFilterState;facets: PerformanceFacets;onChange: (key: NarrowingKey, value: string | null) => void;- onClear: () => void;}) {- const active = narrowingCount(filters);+ const counts = facets[facet] ?? [];+ if (counts.length === 1 && !filters[key]) return <SingleValueFact facet={facet} only={counts[0]!} />;return (- <div className="flex flex-wrap items-center gap-x-5 gap-y-3">- {NARROWING.map(({ key, facet, anyLabel }) => {- const counts = facets[facet] ?? [];- if (counts.length === 0) return null;- if (counts.length === 1 && !filters[key]) {- return <SingleValueFact key={key} facet={facet} only={counts[0]!} />;- }- return (- <FilterSelect- key={key}- label={FACET_LABEL[facet]}- value={filters[key] ?? ""}- onChange={(next) => onChange(key, next || null)}- options={[- { value: "", label: anyLabel },- ...counts.map((entry) => ({- value: entry.value,- label: `${facetValueLabel(facet, entry.value)} (${entry.total.toLocaleString()})`,- })),- ]}- />- );- })}- {active > 0 ? (- <button- type="button"- onClick={onClear}- className="rounded text-xs font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"- >- Clear {active} filter{active === 1 ? "" : "s"}- </button>- ) : null}- </div>+ <FilterSelect+ label={FACET_LABEL[facet]}+ value={filters[key] ?? ""}+ onChange={(next) => onChange(key, next || null)}+ options={[+ { value: "", label: anyLabel },+ ...counts.map((entry) => ({+ value: entry.value,+ label: `${facetValueLabel(facet, entry.value)} (${entry.total.toLocaleString()})`,+ })),+ ]}+ />);}/**- * What the queue currently describes, and what it was drawn from. The- * per-page range is the pagination control's job, so this states only what- * that control cannot: how the selection narrows the repository, and when the- * answer was computed.+ * Scope and sort stay visible; the rest of the server filters sit behind one+ * disclosure, which states how many are active while it is closed.*/-export function ScopeLine({- filteredTotal,- repositoryTotal,- context,- narrowed,- analyzedCommit,+export function NarrowingFilters({+ filters,+ facets,+ keys,+ onChange,}: {- filteredTotal: number;- repositoryTotal: number;- context: PerformanceContextFilter;- narrowed: number;- analyzedCommit?: string | null | undefined;+ filters: PerformanceFilterState;+ facets: PerformanceFacets;+ /** The filters the current scope can narrow by. */+ keys: readonly NarrowingKey[];+ onChange: (key: NarrowingKey, value: string | null) => void;}) {- const noun = filteredTotal === 1 ? "opportunity" : "opportunities";- const scope =- context === "all"- ? noun- : `${contextLabel(context as PerformanceExecutionContext).toLowerCase()} ${noun}`;- return (- <p role="status" className="text-xs text-[var(--color-text-tertiary)]">- <span className="tabular-nums">{filteredTotal.toLocaleString()}</span> {scope}- {narrowed > 0 ? ` under ${narrowed} filter${narrowed === 1 ? "" : "s"}` : ""}- {filteredTotal !== repositoryTotal ? (- <>- , from <span className="tabular-nums">{repositoryTotal.toLocaleString()}</span> in the- repository- </>- ) : null}- .- {analyzedCommit ? (- <>- {" "}- Analyzed at <span className="font-mono">{analyzedCommit.slice(0, 7)}</span>.- </>- ) : null}- </p>- );+ const specs = NARROWING.filter((spec) => keys.includes(spec.key));+ const active = specs.filter(({ key }) => filters[key] !== null).length;+ const controls = specs.filter((spec) => (facets[spec.facet] ?? []).length > 0).map((spec) => (+ <NarrowingControl key={spec.key} spec={spec} filters={filters} facets={facets} onChange={onChange} />+ ));+ if (controls.length === 0) return null;+ return <MoreFilters active={active}>{controls}</MoreFilters>;+}++/** The chip label for one active narrowing, "Boundary: Database". */+export function narrowingChipLabel(key: NarrowingKey, value: string): string {+ return `${FACET_LABEL[key]}: ${facetValueLabel(key, value)}`;}const SORT_OPTIONS: { value: PerformanceSort; label: string }[] = [@@ -237,12 +140,3 @@ export function SortControl({/>);}--export function ContextHint({ context }: { context: PerformanceContextFilter }) {- if (context === "all") return null;- return (- <p className="text-xs text-[var(--color-text-tertiary)]">- {CONTEXT_HINT[context as PerformanceExecutionContext]}- </p>- );-}diff --git a/packages/ui/src/health/performance/grouping.ts b/packages/ui/src/health/performance/grouping.tsnew file mode 100644index 000000000..7a12a3f5e--- /dev/null+++ b/packages/ui/src/health/performance/grouping.ts@@ -0,0 +1,143 @@+import type {+ PerformanceActionabilityState,+ PerformanceAreaFacet,+ PerformanceOpportunity,+ PerformanceQueueExclusion,+} from "@repowise-dev/types/health";++import { areaOf, groupByArea, separatingDepth } from "../../lib/areas";+import type { PerformanceFilterState, PerformanceScope } from "./query";++/**+ * Pure derivations over the loaded result: the actionability split, the area+ * groups, and the "left out" review links. Nothing here re-ranks a cause; the+ * server's order survives inside every group.+ */++export type ActionabilityCounts = Record<PerformanceActionabilityState, number>;++export function actionabilityCounts(items: readonly PerformanceOpportunity[]): ActionabilityCounts {+ const counts: ActionabilityCounts = { plan_ready: 0, advisory: 0, investigate: 0, expected: 0 };+ for (const item of items) counts[item.actionability_state] += 1;+ return counts;+}++/** The server's actionability facet as counts, every state present. */+export function countsFromFacet(+ facet: readonly { value: string; total: number }[] | undefined,+): ActionabilityCounts {+ const counts: ActionabilityCounts = { plan_ready: 0, advisory: 0, investigate: 0, expected: 0 };+ for (const entry of facet ?? []) {+ if (entry.value in counts) counts[entry.value as PerformanceActionabilityState] = entry.total;+ }+ return counts;+}++/** Plan ready and advisory: a named change exists, proven safe or not. */+export function actionableCount(counts: ActionabilityCounts): number {+ return counts.plan_ready + counts.advisory;+}++export interface PerformanceAreaGroup {+ area: string;+ /** The loaded causes in the area, in the server's order; may be fewer than `total`. */+ items: PerformanceOpportunity[];+ counts: ActionabilityCounts;+ /** Causes the area holds in the scope and filters. */+ total: number;+ /** The opened area's own files, which "Show all" would not narrow. */+ own?: boolean;+}++/**+ * Area cards from the server's area facet: every area in the scope with its+ * true counts, in the server's ranking, each holding the loaded causes that+ * sit in it at the facet's depth.+ */+export function facetAreaGroups(+ items: readonly PerformanceOpportunity[],+ facet: PerformanceAreaFacet,+): PerformanceAreaGroup[] {+ return facet.items.map((entry) => ({+ area: entry.area,+ total: entry.total,+ ...(entry.own ? { own: true } : {}),+ counts: countsFromFacet(+ Object.entries(entry.actionability).map(([value, total]) => ({ value, total: total ?? 0 })),+ ),+ items: items.filter((item) => areaOf(item.file_path, facet.depth) === entry.area),+ }));+}++/**+ * Causes grouped by the area of the file the edit goes in, at the depth where+ * the result's files first separate. Groups rank by plan-ready causes, then+ * advisory, then size, then the best rank inside them, so the area worth+ * opening first leads.+ */+export function areaGroups(items: readonly PerformanceOpportunity[]): PerformanceAreaGroup[] {+ const depth = separatingDepth(items.map((item) => item.file_path));+ return groupByArea(items, (item) => item.file_path, depth)+ .map((group) => ({+ ...group,+ counts: actionabilityCounts(group.items),+ total: group.items.length,+ }))+ .sort(+ (a, b) =>+ b.counts.plan_ready - a.counts.plan_ready ||+ b.counts.advisory - a.counts.advisory ||+ b.items.length - a.items.length ||+ a.items[0]!.rank_position - b.items[0]!.rank_position,+ );+}++export interface ExcludedReview {+ reason: PerformanceQueueExclusion;+ count: number;+ label: string;+ /** The scope and filters that list these causes. */+ patch: ReviewPatch;+}++export type ReviewPatch = Partial<PerformanceFilterState> & { scope: PerformanceScope };++const REVIEWS: Record<PerformanceQueueExclusion, { label: string; patch: ReviewPatch }> = {+ unmeasured_cost: { label: "loop size unknown", patch: { scope: "production", proof: "unproven" } },+ background_unproven: {+ label: "scheduled, growth not shown",+ patch: { scope: "production", proof: "background_unproven" },+ },+ no_strategy: {+ label: "need investigation",+ patch: { scope: "production", actionability: "investigate" },+ },+ expected: {+ label: "expected repetition",+ patch: { scope: "production", actionability: "expected" },+ },+ gated_off: {+ label: "switched off by a flag",+ patch: { scope: "production", actionability: "expected" },+ },+ cold_path: { label: "run rarely", patch: { scope: "production", actionability: "expected" } },+ cold_role: { label: "startup, CLI or UI only", patch: { scope: "production" } },+ test: { label: "in tests", patch: { scope: "all", context: "test" } },+ tooling: { label: "in tooling", patch: { scope: "all", context: "tooling" } },+ unknown: { label: "unclassified", patch: { scope: "all", context: "unknown" } },+};++/**+ * What the default queue left out, largest first, each with the filters that+ * list it. Zero counts are dropped: a reason with nothing behind it is not a+ * place worth sending anybody.+ */+export function excludedReviews(+ excluded: Partial<Record<PerformanceQueueExclusion, number>> | undefined,+): ExcludedReview[] {+ if (!excluded) return [];+ return (Object.entries(excluded) as [PerformanceQueueExclusion, number][])+ .filter(([reason, count]) => count > 0 && reason in REVIEWS)+ .map(([reason, count]) => ({ reason, count, ...REVIEWS[reason] }))+ .sort((a, b) => b.count - a.count);+}diff --git a/packages/ui/src/health/performance/presentation.ts b/packages/ui/src/health/performance/presentation.tsindex 2067b6e98..312c8b5a6 100644--- a/packages/ui/src/health/performance/presentation.ts+++ b/packages/ui/src/health/performance/presentation.ts@@ -12,7 +12,7 @@ import {import type { C4IoKind } from "@repowise-dev/types/external-systems";import { biomarkerLabel } from "../biomarker-glossary";-import { CONFIDENCE_LABEL } from "../labels";+import { CONFIDENCE_LABEL, EFFORT_LABEL } from "../labels";/*** Display derivations for the performance queue. Everything here reads fields@@ -352,6 +352,32 @@ export function planPresentation(opportunity: PerformanceOpportunity): PlanPresereturn { label: "No safe plan", detail: opportunity.plan_reason, actionable: false };}+/** Each fix strategy as the change a person would make (`actionability.FixStrategy`). */+const FIX_STRATEGY_LABEL: Record<string, string> = {+ parallelize_independent_awaits: "Run the independent awaits together",+ replace_membership_collection: "Use a set for the membership test",+ buffer_string_accumulation: "Build the string once with a buffer",+ batch_or_prefetch_io: "Batch or prefetch the calls",+ shrink_lock_scope: "Move the work out of the lock",+ push_reduction_into_query: "Do the reduction in the query",+ eager_load_relationship: "Load the relationship eagerly",+};++export function fixStrategyLabel(strategy: string): string {+ return FIX_STRATEGY_LABEL[strategy] ?? humanizeToken(strategy);+}++export const FIX_SAFETY_LABEL: Record<"proven" | "advisory", string> = {+ proven: "Proven safe",+ advisory: "Not proven safe",+};++/** The stored plan's effort bucket as a word, or null when nothing sized it. */+export function effortLabel(opportunity: PerformanceOpportunity): string | null {+ const effort = opportunity.plan_economics?.effort_bucket;+ return effort && effort in EFFORT_LABEL ? EFFORT_LABEL[effort as keyof typeof EFFORT_LABEL] : null;+}+/*** The copy that tells an agent which drill-down to call. Quotes the opportunity* id because that is the id the agent surface resolves.diff --git a/packages/ui/src/health/performance/prompts.ts b/packages/ui/src/health/performance/prompts.tsnew file mode 100644index 000000000..a2164b960--- /dev/null+++ b/packages/ui/src/health/performance/prompts.ts@@ -0,0 +1,69 @@+"use client";++import { useCallback, useMemo } from "react";+import type { PerformanceOpportunity } from "@repowise-dev/types/health";+import type { RefactoringPlan } from "@repowise-dev/types/refactoring";++import {+ buildPerformanceAreaPrompt,+ buildPerformanceOpportunityPrompt,+ buildRefactoringPlanPrompt,+ type AiPromptFlavor,+} from "../ai-prompt-builder";+import type { AiPromptRequest } from "../ai-prompt-action";+import type { PerformanceViewAdapter } from "./adapter";+import { useDetailLoader, useVerifiedPlanLoader } from "./cache";+import { opportunityTitle } from "./presentation";++/**+ * The agent prompts this tab hands over, as requests for the shared prompt+ * action. A cause's prompt is its verified stored plan when there is one,+ * else an evidence handoff built from its detail; both read the same cache+ * entries the drawer reads, so opening the prompt never refetches them.+ */+export function usePerformancePrompts(adapter: PerformanceViewAdapter) {+ const loadDetail = useDetailLoader(adapter);+ const loadPlan = useVerifiedPlanLoader(adapter);++ const forOpportunity = useCallback(+ (row: PerformanceOpportunity): AiPromptRequest => {+ // Resolved once per request, then reused across flavor switches.+ let resolved: Promise<{ opportunity: PerformanceOpportunity; plan: RefactoringPlan | null }> | null =+ null;+ const resolve = () =>+ (resolved ??= (async () => {+ const detail = await loadDetail(row.opportunity_id).catch(() => null);+ const opportunity = detail?.found ? detail : row;+ const plan = await loadPlan(opportunity).catch(() => null);+ return { opportunity, plan };+ })());+ const promptSource = async (flavor: AiPromptFlavor): Promise<string> => {+ const { opportunity, plan } = await resolve();+ if (!plan) return buildPerformanceOpportunityPrompt({ opportunity, flavor });+ // Core renders the plan prompt when the host serves it.+ return adapter.getRefactoringPlanPrompt+ ? adapter.getRefactoringPlanPrompt(plan.id, flavor)+ : buildRefactoringPlanPrompt({ plan, flavor });+ };+ return {+ title: "Prompt for your agent",+ description: `${opportunityTitle(row)}. The stored plan when one names this cause, else the evidence, with the tests to run.`,+ filePath: row.file_path,+ promptSource,+ };+ },+ [adapter, loadDetail, loadPlan],+ );++ const forArea = useCallback(+ (area: string, rows: PerformanceOpportunity[], paged = false): AiPromptRequest => ({+ title: "Prompt for your agent",+ description: `${rows.length.toLocaleString()} performance cause${rows.length === 1 ? "" : "s"} in this area${paged ? " on this page" : ""}, in ranked order, one change each.`,+ filePath: area || null,+ getPrompt: (flavor) => buildPerformanceAreaPrompt({ area, opportunities: rows, paged, flavor }),+ }),+ [],+ );++ return useMemo(() => ({ forOpportunity, forArea }), [forOpportunity, forArea]);+}diff --git a/packages/ui/src/health/performance/query.ts b/packages/ui/src/health/performance/query.tsindex 8ae8aab71..78e1796f5 100644--- a/packages/ui/src/health/performance/query.ts+++ b/packages/ui/src/health/performance/query.ts@@ -1,56 +1,79 @@import { PERFORMANCE_EXECUTION_ROLES } from "@repowise-dev/types/health";import type {PerformanceActionabilityState,- PerformanceContextFilter,PerformanceCostProof,+ PerformanceExecutionContext,PerformanceExecutionRole,PerformanceOpportunityConfidence,PerformanceOpportunityQuery,+ PerformanceScope,} from "@repowise-dev/types/health";/**- * The queue's filter state, and its round trip to a query string.+ * The tab's view state, its server query, and its round trip to the URL.*- * Every field here is a parameter the server answers, so narrowing is always a- * refetch and never a filter over the loaded page. A page can be a slice of a- * much larger result, so filtering it on the client would answer a different- * question than the count beside it.+ * One scope decides which causes exist (worth doing now, every production+ * cause, everything), and every number on the page is counted inside it. The+ * filters narrow within the scope and are all server-side, so a count and the+ * rows it describes never come from two different universes, the area+ * included.*/+export type { PerformanceScope };export type PerformanceSort = NonNullable<PerformanceOpportunityQuery["sort"]>;export interface PerformanceFilterState {- context: PerformanceContextFilter;+ scope: PerformanceScope;+ /** One execution context, inside Everything only. */+ context: PerformanceExecutionContext | null;boundary: string | null;confidence: PerformanceOpportunityConfidence | null;+ /** The actionability bar's selection. */actionability: PerformanceActionabilityState | null;+ /** Outside "now", whose causes are all measured and served. */proof: PerformanceCostProof | null;- role: PerformanceExecutionRole | "all" | null;+ role: PerformanceExecutionRole | null;sort: PerformanceSort;- offset: number;+ /** 1-based page of `PAGE_SIZE` causes. */+ page: number;+ /** One area (a directory) at any depth, narrowed on the server. */+ area: string | null;+ /** The directory depth area cards are drawn at; null lets the server choose. */+ depth: number | null;}-/**- * Production is the default view. Most of what the analysis finds sits in- * tests, benchmarks and CI scripts, and "this benchmark repeats work" is a- * fact about a benchmark rather than work to schedule. Every other context- * stays one tab away and keeps its count in the tab row.- */+/** The server's page ceiling: a default queue fits in one page almost always. */+export const PAGE_SIZE = 100;+export const INITIAL_FILTERS: PerformanceFilterState = {- context: "production",+ scope: "now",+ context: null,boundary: null,confidence: null,actionability: null,proof: null,role: null,sort: "rank",- offset: 0,+ page: 1,+ area: null,+ depth: null,};-/** The narrowing filters, apart from context, which is a permanent tab row. */-const NARROWING_KEYS = ["boundary", "confidence", "actionability", "proof", "role"] as const;+export const SCOPES: readonly PerformanceScope[] = ["now", "production", "all"];++/** The states the default queue holds. */+const NOW_STATES: readonly PerformanceActionabilityState[] = ["plan_ready", "advisory"];++/** The filters behind "More filters", each offered only where it can narrow. */+export const NARROWING_KEYS = ["context", "boundary", "confidence", "proof", "role"] as const;export type NarrowingKey = (typeof NARROWING_KEYS)[number];+export function narrowingKeysFor(scope: PerformanceScope): readonly NarrowingKey[] {+ if (scope === "now") return ["boundary", "confidence"];+ if (scope === "production") return ["boundary", "confidence", "proof", "role"];+ return NARROWING_KEYS;+}+const SORTS: readonly PerformanceSort[] = ["rank", "leverage", "observations"];const CONFIDENCES: readonly PerformanceOpportunityConfidence[] = ["high", "medium", "low"];const ACTIONABILITIES: readonly PerformanceActionabilityState[] = [@@ -60,9 +83,8 @@ const ACTIONABILITIES: readonly PerformanceActionabilityState[] = ["expected",];const PROOFS: readonly PerformanceCostProof[] = ["proven", "unproven", "background_unproven"];-const ROLES: readonly (PerformanceExecutionRole | "all")[] = ["all", ...PERFORMANCE_EXECUTION_ROLES];-const CONTEXTS: readonly PerformanceContextFilter[] = [- "all",+const ROLES: readonly PerformanceExecutionRole[] = PERFORMANCE_EXECUTION_ROLES;+const CONTEXTS: readonly PerformanceExecutionContext[] = ["production","tooling","test",@@ -70,94 +92,241 @@ const CONTEXTS: readonly PerformanceContextFilter[] = [];/**- * Build the server query. `collapseContexts` is set only when the server- * predates the canonical vocabulary, and is the one place the retired- * `production_tooling` spelling may be emitted.+ * Build the server query. Rows use the `summary` view, which carries what a+ * row is acted on by; plan steps and validation wait for the drawer.+ * `collapseContexts` is set only for a server that predates the canonical+ * vocabulary, and is the one place the retired `production_tooling` may go.*/export function toQuery(state: PerformanceFilterState,options: { limit: number; collapseContexts?: boolean },): PerformanceOpportunityQuery {- const context =- options.collapseContexts && (state.context === "production" || state.context === "tooling")- ? ("production_tooling" as const)- : state.context;const query: PerformanceOpportunityQuery = {- context,- view: "detail",+ view: "summary",sort: state.sort,limit: options.limit,- offset: state.offset,+ offset: (state.page - 1) * options.limit,};+ if (state.scope === "now") {+ query.context = "production";+ // A state chosen inside the default queue stays inside it.+ if (state.actionability) {+ query.actionability = state.actionability;+ query.queue = true;+ }+ } else {+ query.context = state.scope === "all" ? (state.context ?? "all") : "production";+ query.actionability = state.actionability ?? "all";+ query.proof = state.proof ?? "all";+ query.role = state.role ?? "all";+ }+ if (+ options.collapseContexts &&+ (query.context === "production" || query.context === "tooling")+ ) {+ query.context = "production_tooling";+ }if (state.boundary) query.boundary = state.boundary;if (state.confidence) query.confidence = state.confidence;- if (state.actionability) query.actionability = state.actionability;- if (state.proof) query.proof = state.proof;- if (state.role) query.role = state.role;+ if (state.area) query.area = state.area;+ if (state.depth) query.area_depth = state.depth;return query;}+/** A stable string for the server half of the state: the queue's cache key. */+export function serverKey(state: PerformanceFilterState): string {+ return [+ state.scope,+ state.context ?? "",+ state.boundary ?? "",+ state.confidence ?? "",+ state.actionability ?? "",+ state.proof ?? "",+ state.role ?? "",+ state.sort,+ state.page,+ state.area ?? "",+ state.depth ?? "",+ ].join("|");+}++/** URL parameters retired by the flat scope schema, still read so old links open. */+export const LEGACY_PARAMS = ["perf", "ctx", "state"] as const;+/**- * A stable string for the state. Keys are written in a fixed order and- * defaults are omitted, so an unchanged filter set always produces the same- * cache key and the same shareable link. Context is the exception and is- * always written, because it is the one default that decides which rows exist- * rather than how they are shown.+ * Write the state onto `params` in place. `scope` is always written: a link+ * that omits it would be read under whatever the default is when it opens.*/-export function serializeFilters(state: PerformanceFilterState): string {- const params = new URLSearchParams();- // Always written, unlike the other defaults: a link that omits it would be- // read under whatever the default is when it is opened, so a shared link- // would change meaning if that default ever moved again.- params.set("context", state.context);- if (state.boundary) params.set("boundary", state.boundary);- if (state.confidence) params.set("confidence", state.confidence);- if (state.actionability) params.set("actionability", state.actionability);- if (state.proof) params.set("proof", state.proof);- if (state.role) params.set("role", state.role);+export function writeFilters(state: PerformanceFilterState, params: URLSearchParams): void {+ for (const legacy of LEGACY_PARAMS) params.delete(legacy);+ params.set("scope", state.scope);+ for (const key of [+ "context",+ "boundary",+ "confidence",+ "actionability",+ "proof",+ "role",+ ] as const) {+ const value = state[key];+ if (value) params.set(key, value);+ else params.delete(key);+ }if (state.sort !== INITIAL_FILTERS.sort) params.set("sort", state.sort);- if (state.offset > 0) params.set("offset", String(state.offset));- return params.toString();+ else params.delete("sort");+ if (state.page > 1) params.set("page", String(state.page));+ else params.delete("page");+ // The root area is the empty string, so only null means "no area".+ if (state.area !== null) params.set("area", state.area);+ else params.delete("area");+ if (state.depth) params.set("depth", String(state.depth));+ else params.delete("depth");}function oneOf<T extends string>(value: string | null, allowed: readonly T[]): T | null {return value && (allowed as readonly string[]).includes(value) ? (value as T) : null;}-/**- * Read the state back. An unrecognized value falls back to the default rather- * than being forwarded to the server, so a hand-edited link cannot make the- * queue look empty.- */-export function parseFilters(search: string | URLSearchParams): PerformanceFilterState {- const params = typeof search === "string" ? new URLSearchParams(search) : search;- const offset = Number.parseInt(params.get("offset") ?? "", 10);+function positive(value: string | null): number | null {+ const n = Number.parseInt(value ?? "", 10);+ return Number.isFinite(n) && n > 0 ? n : null;+}++/** The narrowing fields every spelling shares. */+function narrowing(params: URLSearchParams) {return {- context: oneOf(params.get("context"), CONTEXTS) ?? INITIAL_FILTERS.context,boundary: params.get("boundary") || null,confidence: oneOf(params.get("confidence"), CONFIDENCES),- actionability: oneOf(params.get("actionability"), ACTIONABILITIES),+ actionability:+ oneOf(params.get("actionability"), ACTIONABILITIES) ??+ oneOf(params.get("state"), ACTIONABILITIES),proof: oneOf(params.get("proof"), PROOFS),role: oneOf(params.get("role"), ROLES),sort: oneOf(params.get("sort"), SORTS) ?? INITIAL_FILTERS.sort,- offset: Number.isFinite(offset) && offset > 0 ? offset : 0,};}-/** Change one filter. Any narrowing change returns to the first page. */+/**+ * A link minted before scopes named a context (`ctx`, or `context` inside the+ * `perf` blob). Production with no widening filter was the default queue;+ * production with one is the production scope; anything else is Everything.+ */+function fromLegacy(params: URLSearchParams, contextKey: string): PerformanceFilterState {+ const fields = narrowing(params);+ const context = params.get(contextKey);+ const page = positive(params.get("page")) ?? Math.floor((positive(params.get("offset")) ?? 0) / PAGE_SIZE) + 1;+ const widened =+ fields.proof !== null ||+ fields.role !== null ||+ params.get("role") === "all" ||+ fields.actionability === "investigate" ||+ fields.actionability === "expected";+ const scope: PerformanceScope =+ context && context !== "production" ? "all" : widened ? "production" : "now";+ return {+ ...INITIAL_FILTERS,+ ...fields,+ scope,+ context: scope === "all" ? oneOf(context, CONTEXTS) : null,+ proof: scope === "now" ? null : fields.proof,+ role: scope === "now" ? null : fields.role,+ page,+ area: params.get("area"),+ depth: positive(params.get("depth")),+ };+}++/**+ * Read the state back from the page's parameters. An unrecognized value falls+ * back to the default rather than reaching the server, so a hand-edited link+ * cannot make the queue look empty.+ */+export function readFilters(params: URLSearchParams): PerformanceFilterState {+ if (!params.has("scope")) {+ const blob = params.get("perf");+ if (blob !== null && !params.has("ctx")) return fromLegacy(new URLSearchParams(blob), "context");+ if (params.has("ctx")) return fromLegacy(params, "ctx");+ }+ const scope = oneOf(params.get("scope"), SCOPES) ?? INITIAL_FILTERS.scope;+ const fields = narrowing(params);+ return {+ ...fields,+ // "Worth doing now" holds plan-ready and advisory causes only.+ actionability:+ scope === "now" && !NOW_STATES.includes(fields.actionability ?? "plan_ready")+ ? null+ : fields.actionability,+ scope,+ context: scope === "all" ? oneOf(params.get("context"), CONTEXTS) : null,+ proof: scope === "now" ? null : fields.proof,+ role: scope === "now" ? null : fields.role,+ page: positive(params.get("page")) ?? 1,+ area: params.get("area"),+ depth: positive(params.get("depth")),+ };+}++/** A host string that predates the flat schema is the `perf` blob itself. */+export function parseLegacyFilters(blob: string): PerformanceFilterState {+ return fromLegacy(new URLSearchParams(blob), "context");+}++/**+ * Change one field. Every filter is the server's, so any change but the page+ * returns to the first page. A new area draws its cards at the depth the+ * server chooses inside it.+ */export function withFilter<K extends keyof PerformanceFilterState>(state: PerformanceFilterState,key: K,value: PerformanceFilterState[K],): PerformanceFilterState {- if (key === "offset") return { ...state, offset: value as number };- return { ...state, [key]: value, offset: 0 };+ if (key === "page") return { ...state, page: value as number };+ if (key === "scope") return withScope(state, value as PerformanceScope);+ if (key === "area") return withFilters(state, { area: value as string | null, depth: null });+ return withFilters(state, { [key]: value });+}++/** Apply several server filters as one change. */+export function withFilters(+ state: PerformanceFilterState,+ patch: Partial<PerformanceFilterState>,+): PerformanceFilterState {+ return { ...state, ...patch, page: 1 };+}++/**+ * Move to another scope, keeping the filters that still narrow there and+ * dropping the actionability selection, whose counts belong to the old scope.+ */+export function withScope(+ state: PerformanceFilterState,+ scope: PerformanceScope,+ patch: Partial<PerformanceFilterState> = {},+): PerformanceFilterState {+ const kept = narrowingKeysFor(scope);+ const next: PerformanceFilterState = { ...INITIAL_FILTERS, scope, sort: state.sort };+ for (const key of kept) (next as unknown as Record<string, unknown>)[key] = state[key];+ return { ...next, ...patch };}export function clearNarrowing(state: PerformanceFilterState): PerformanceFilterState {- return { ...state, boundary: null, confidence: null, actionability: null, proof: null, role: null, offset: 0 };+ return withFilters(state, {+ area: null,+ depth: null,+ context: null,+ boundary: null,+ confidence: null,+ actionability: null,+ proof: null,+ role: null,+ });}+/** Active narrowing filters, the actionability selection included. */export function narrowingCount(state: PerformanceFilterState): number {- return NARROWING_KEYS.filter((key) => state[key] !== null).length;+ return (+ NARROWING_KEYS.filter((key) => state[key] !== null).length ++ (state.actionability !== null ? 1 : 0)+ );}diff --git a/packages/ui/src/health/performance/queue.tsx b/packages/ui/src/health/performance/queue.tsxindex 65d25d4bc..8796829cd 100644--- a/packages/ui/src/health/performance/queue.tsx+++ b/packages/ui/src/health/performance/queue.tsx@@ -1,224 +1,196 @@"use client";import { memo, useState } from "react";-import { Copy, ExternalLink, FileCode, MoreHorizontal } from "lucide-react";+import { Copy, FileCode, MoreHorizontal } from "lucide-react";import { toast } from "sonner";-import type {- PerformanceActionabilityState,- PerformanceFacets,- PerformanceOpportunity,-} from "@repowise-dev/types/health";+import type { PerformanceOpportunity } from "@repowise-dev/types/health";import { Button } from "../../ui/button";import { Popover, PopoverContent, PopoverTrigger } from "../../ui/popover";import { CLICKABLE_ROW_CLS, clickableRowProps } from "../../shared/responsive-table";-import { LowerPriorityTag } from "../lower-priority-tag";-import { PreviewBadge } from "../preview-badge";+import { AGENT_PROMPT_LABEL } from "../ai-prompt-action";+import { AiPromptButton } from "../ai-prompt-button";import type { PerformanceViewAdapter } from "./adapter";import {- ACTIONABILITY_HINT,- ACTIONABILITY_LABEL,affectedSummary,agentHandoffCall,- boundaryLabel,- contextLabel,- CONFIDENCE_LABEL,- opportunityEvidenceLine,+ effortLabel,+ FIX_SAFETY_LABEL,+ fixStrategyLabel,opportunityCause,opportunitySubject,opportunityTitle,planPresentation,- whyRankedLabel,- whyRankedPhrase,} from "./presentation";+import { OpportunityTags } from "./tags";/**- * The queue: full-width rows under section headings, one primary verb each.- *- * Sections are contiguous runs of the server's order, never a regrouping. The- * server ranks actionable work first, so the runs read as tiers; if that order- * ever changed, the runs would still describe exactly what was returned.+ * Action-first rows: what to change, what it buys and what it costs, then the+ * verbs. The agent prompt is the primary one, because people fix these through+ * their agents; inspecting, the plan and the file are secondary.*/-interface Section {- state: PerformanceActionabilityState;- items: PerformanceOpportunity[];-}--export function contiguousSections(items: PerformanceOpportunity[]): Section[] {- const sections: Section[] = [];- for (const item of items) {- const last = sections[sections.length - 1];- if (last && last.state === item.actionability_state) last.items.push(item);- else sections.push({ state: item.actionability_state, items: [item] });- }- return sections;-}--function facetTotal(facets: PerformanceFacets, value: string): number | null {- const found = facets.actionability?.find((entry) => entry.value === value);- return found ? found.total : null;+export interface RowCallbacks {+ onInspect: (opportunity: PerformanceOpportunity) => void;+ onPrompt: (opportunity: PerformanceOpportunity) => void;+ /** Warm the detail the drawer and the prompt read, on hover or focus. */+ onPrefetch: (opportunityId: string) => void;}-export function OpportunityQueue({+export function OpportunityList({items,- facets,adapter,- showSections,selectedId,- onInspect,+ callbacks,+ label,}: {items: PerformanceOpportunity[];- facets: PerformanceFacets;adapter: PerformanceViewAdapter;- /** Sections are headings over one ranked list, so a narrowed queue drops them. */- showSections: boolean;selectedId: string | null;- onInspect: (opportunity: PerformanceOpportunity) => void;+ callbacks: RowCallbacks;+ label: string;}) {- const sections = showSections- ? contiguousSections(items)- : [{ state: items[0]?.actionability_state ?? "investigate", items }];-return (- <div className="space-y-8">- {sections.map((section, index) => (- <section key={`${section.state}-${index}`} aria-labelledby={`perf-section-${index}`}>- {showSections ? (- <div className="mb-1 flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1">- <h3- id={`perf-section-${index}`}- className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]"- >- {ACTIONABILITY_LABEL[section.state]}- {facetTotal(facets, section.state) != null ? (- <span className="ml-2 tabular-nums">- {facetTotal(facets, section.state)!.toLocaleString()} matching- </span>- ) : null}- </h3>- <p className="text-xs text-[var(--color-text-tertiary)]">- {ACTIONABILITY_HINT[section.state]}- </p>- </div>- ) : (- <h3 id={`perf-section-${index}`} className="sr-only">- Performance opportunities- </h3>- )}- <ul className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">- {section.items.map((opportunity) => (- <OpportunityRow- key={opportunity.opportunity_id}- opportunity={opportunity}- adapter={adapter}- selected={opportunity.opportunity_id === selectedId}- onInspect={onInspect}- />- ))}- </ul>- </section>+ <ul+ aria-label={label}+ className="divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]"+ >+ {items.map((opportunity) => (+ <OpportunityRow+ key={opportunity.opportunity_id}+ opportunity={opportunity}+ adapter={adapter}+ selected={opportunity.opportunity_id === selectedId}+ onInspect={callbacks.onInspect}+ onPrompt={callbacks.onPrompt}+ onPrefetch={callbacks.onPrefetch}+ />))}- </div>+ </ul>);}-function StatusMark({ opportunity }: { opportunity: PerformanceOpportunity }) {- const plan = planPresentation(opportunity);- // Green only where the plan is proven safe: an advisory cause can carry a- // stored plan while the "Plan ready" count beside the queue reads 0.- const tone =- plan.actionable && opportunity.actionability_state === "plan_ready"- ? "var(--color-success)"- : "var(--color-text-tertiary)";+/** The fix in one line: strategy, gain, effort and safety, each only when known. */+function FixLine({ opportunity }: { opportunity: PerformanceOpportunity }) {+ const effort = effortLabel(opportunity);+ const { fix, gain_text: gain } = opportunity;+ if (!fix) {+ return (+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">+ No supported fix yet: read the evidence before changing anything.+ </p>+ );+ }return (- <span className="inline-flex items-center gap-1.5 whitespace-nowrap text-xs font-medium text-[var(--color-text-secondary)]">- <span- aria-hidden="true"- className="h-1.5 w-1.5 shrink-0 rounded-full"- style={{ backgroundColor: tone }}- />- {plan.label}- </span>+ <p className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-[var(--color-text-secondary)]">+ <span className="font-medium text-[var(--color-text-primary)]">+ {fixStrategyLabel(fix.strategy)}+ </span>+ {gain ? <span>saves {gain}</span> : null}+ {effort ? (+ <span className="rounded border border-[var(--color-border-default)] px-1.5 font-mono text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">+ {effort} effort+ </span>+ ) : null}+ <span className="inline-flex items-center gap-1 text-[var(--color-text-tertiary)]">+ {fix.safety === "proven" ? (+ <span aria-hidden="true" className="h-1.5 w-1.5 rounded-full bg-[var(--color-success)]" />+ ) : null}+ {FIX_SAFETY_LABEL[fix.safety]}+ </span>+ </p>);}+/** A quiet link: secondary ink at rest, the accent only on hover and focus. */+export const QUIET_LINK_CLS =+ "rounded text-[var(--color-text-secondary)] underline-offset-2 hover:text-[var(--color-accent-primary)] hover:underline focus-visible:text-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";+/**- * Memoized because a page is twenty of these and the surrounding filter state- * changes far more often than any single row does. It takes the callback- * rather than a closure over one opportunity so the props stay comparable.+ * Memoized because a page is up to a hundred of these and the surrounding+ * filter state changes far more often than any single row does. It takes the+ * callbacks rather than closures over one opportunity so the props compare.*/const OpportunityRow = memo(function OpportunityRow({opportunity,adapter,selected,onInspect,+ onPrompt,+ onPrefetch,}: {opportunity: PerformanceOpportunity;adapter: PerformanceViewAdapter;selected: boolean;- onInspect: (opportunity: PerformanceOpportunity) => void;-}) {+} & RowCallbacks) {const title = opportunityTitle(opportunity);- const why = opportunity.why_ranked.slice(0, 3);+ const plan = planPresentation(opportunity);+ const planHref =+ plan.actionable && opportunity.plan_id+ ? adapter.refactoringPlanHref?.(opportunity.plan_id, opportunity.opportunity_id)+ : undefined;+ const prefetch = () => onPrefetch(opportunity.opportunity_id);+return (<lidata-performance-opportunity={opportunity.opportunity_id}aria-current={selected ? "true" : undefined}- className={`${CLICKABLE_ROW_CLS} flex items-start gap-3 px-1 py-4 sm:gap-4 ${+ aria-label={`Inspect ${title}`}+ className={`${CLICKABLE_ROW_CLS} group/row flex flex-col gap-3 px-1 py-4 sm:flex-row sm:items-start sm:gap-4 ${selected ? "bg-[var(--color-bg-elevated)]" : "hover:bg-[var(--color-bg-elevated)]"}`}- aria-label={`Inspect ${title}`}+ onMouseEnter={prefetch}+ onFocus={prefetch}{...clickableRowProps(() => onInspect(opportunity))}>- <span className="mt-0.5 w-7 shrink-0 text-right font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">- {(opportunity.rank_position + 1).toLocaleString()}- </span>-- <div className="min-w-0 flex-1">- <p className="text-[15px] font-semibold leading-snug text-[var(--color-text-primary)]">- {opportunityCause(opportunity)} in{" "}- <code className="font-mono text-[0.85em] [overflow-wrap:anywhere]">- {opportunitySubject(opportunity)}- </code>- </p>- <p className="mt-1 break-all font-mono text-xs text-[var(--color-text-secondary)]">- {opportunityEvidenceLine(opportunity)}- </p>- <p className="mt-1.5 text-xs text-[var(--color-text-tertiary)]">- {contextLabel(opportunity.execution_context)} ·{" "}- {boundaryLabel(opportunity.boundary_kind)} ·{" "}- <span className="tabular-nums">{affectedSummary(opportunity)}</span> ·{" "}- {CONFIDENCE_LABEL[opportunity.confidence]} evidence confidence- </p>- {opportunity.lower_priority ? (- <p className="mt-1">- <LowerPriorityTag reason={opportunity.lower_priority} />- </p>- ) : null}- {opportunity.preview ? (- <p className="mt-1">- <PreviewBadge note={opportunity.preview} />+ <div className="flex min-w-0 flex-1 gap-3">+ <span className="mt-0.5 w-7 shrink-0 text-right font-mono text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {(opportunity.rank_position + 1).toLocaleString()}+ </span>+ <div className="min-w-0 flex-1">+ <p className="text-[15px] font-semibold leading-snug text-[var(--color-text-primary)]">+ {opportunityCause(opportunity)} in{" "}+ <code className="font-mono text-[0.85em] [overflow-wrap:anywhere]">+ {opportunitySubject(opportunity)}+ </code></p>- ) : null}- {why.length > 0 ? (- <p- className="mt-1 text-xs text-[var(--color-text-tertiary)]"- title={`Ranked on ${why.map(whyRankedLabel).join(", ")}`}- >- Why here: {why.map(whyRankedPhrase).join(", ")}+ <FixLine opportunity={opportunity} />+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">+ <span className="break-all font-mono">{opportunity.file_path}</span> ·{" "}+ <span className="tabular-nums">{affectedSummary(opportunity)}</span></p>- ) : null}- <div className="mt-2 sm:hidden">- <StatusMark opportunity={opportunity} />+ <OpportunityTags opportunity={opportunity} />+ {planHref ? (+ <p className="mt-2 text-xs">+ <a+ href={planHref}+ onClick={(event) => event.stopPropagation()}+ className={QUIET_LINK_CLS}+ >+ Open plan+ </a>+ </p>+ ) : null}</div></div>- <div className="flex shrink-0 items-center gap-1 sm:gap-3">- <span className="hidden sm:inline">- <StatusMark opportunity={opportunity} />- </span>- <RowOverflow opportunity={opportunity} adapter={adapter} title={title} />+ <div className="flex shrink-0 items-center gap-1 pl-10 sm:pl-0">+ {/* Quiet per row: a ghost button shown on hover, focus and the+ selected row, always in the tab order; the filled prompt lives on+ the area header and in the drawer. Interim styling until the+ shared row-action component (L-nav) lands, then swap to it. */}+ <AiPromptButton+ label={AGENT_PROMPT_LABEL}+ onClick={() => onPrompt(opportunity)}+ className={`border-transparent bg-transparent transition-opacity focus-visible:opacity-100 sm:group-hover/row:opacity-100 sm:group-focus-within/row:opacity-100 ${+ selected ? "" : "sm:opacity-0"+ }`}+ />+ <RowOverflow+ opportunity={opportunity}+ title={title}+ onOpenFile={() => adapter.navigate(adapter.fileHref(opportunity.file_path))}+ /></div></li>);@@ -233,31 +205,19 @@ async function copy(text: string, what: string) {}}-/**- * Secondary actions. Inspect is the row itself, so nothing here repeats it and- * each entry names a different kind of destination.- */+/** The row's other verbs: open the file, and the ids an agent or a script+ * resolves the cause by. */function RowOverflow({opportunity,- adapter,title,+ onOpenFile,}: {opportunity: PerformanceOpportunity;- adapter: PerformanceViewAdapter;title: string;+ onOpenFile: () => void;}) {const [open, setOpen] = useState(false);- const plan = planPresentation(opportunity);- const planHref =- plan.actionable && opportunity.plan_id- ? adapter.refactoringPlanHref?.(opportunity.plan_id, opportunity.opportunity_id)- : undefined;-- const item = (- label: string,- Icon: typeof Copy,- onClick: () => void,- ) => (+ const item = (label: string, Icon: typeof Copy, onClick: () => void) => (<buttontype="button"onClick={() => {@@ -270,7 +230,6 @@ function RowOverflow({{label}</button>);-return (<Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild>@@ -289,18 +248,11 @@ function RowOverflow({className="w-64 p-1"onClick={(event) => event.stopPropagation()}>- {item("Open the file", FileCode, () =>- adapter.navigate(adapter.fileHref(opportunity.file_path)),- )}- {planHref- ? item("Open the plan on Refactoring", ExternalLink, () => adapter.navigate(planHref))- : null}+ {item("Open the file", FileCode, onOpenFile)}{item("Copy the agent drill-down", Copy, () =>copy(agentHandoffCall(opportunity.opportunity_id), "Drill-down call"),)}- {item("Copy the opportunity id", Copy, () =>- copy(opportunity.opportunity_id, "Opportunity id"),- )}+ {item("Copy the opportunity id", Copy, () => copy(opportunity.opportunity_id, "Opportunity id"))}</PopoverContent></Popover>);diff --git a/packages/ui/src/health/performance/scope.tsx b/packages/ui/src/health/performance/scope.tsxnew file mode 100644index 000000000..3a06d58da--- /dev/null+++ b/packages/ui/src/health/performance/scope.tsx@@ -0,0 +1,184 @@+"use client";++import { useState } from "react";+import type { PerformanceScope } from "@repowise-dev/types/health";++import { Segmented } from "../../shared/segmented";+import type { ExcludedReview } from "./grouping";+import { QUIET_LINK_CLS } from "./queue";++/**+ * The one scope control and the sentence that accounts for what the scope+ * leaves out. Every figure on the page is counted inside the selected scope;+ * the sentence is where the rest of the repository is named, each part a+ * link to the scope that lists it.+ */++export type ScopeCounts = Record<PerformanceScope, number>;++const SCOPE_LABEL: Record<PerformanceScope, string> = {+ now: "Worth doing now",+ production: "All production",+ all: "Everything",+};++const SCOPE_HINT: Record<PerformanceScope, string> = {+ now: "Production causes with a fix to make, whose cost is shown to grow with the data.",+ production: "Every production cause, including expected repetition and ones without a fix yet.",+ all: "Every cause, in tests, tooling and unclassified code too.",+};++export function ScopeControl({+ value,+ counts,+ onChange,+}: {+ value: PerformanceScope;+ counts: ScopeCounts;+ onChange: (scope: PerformanceScope) => void;+}) {+ return (+ <Segmented+ label="Scope"+ value={value}+ onChange={onChange}+ options={(["now", "production", "all"] as const).map((scope) => ({+ value: scope,+ label: SCOPE_LABEL[scope],+ count: counts[scope].toLocaleString(),+ hint: SCOPE_HINT[scope],+ }))}+ />+ );+}++/** One clause of the accounting sentence; `scope` makes its figure a link. */+export interface ScopeClause {+ count: number;+ text: string;+ scope: PerformanceScope | null;+}++const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);++/**+ * What the selected scope shows and where the rest of the repository is, as+ * clauses. Zero-count clauses are dropped: nothing hidden is not worth a link.+ */+export function scopeAccount(scope: PerformanceScope, counts: ScopeCounts): ScopeClause[] {+ const { now, production, all } = counts;+ const outside = all - production;+ const waiting = production - now;+ const clauses: ScopeClause[] =+ scope === "now"+ ? [+ { count: now, text: "worth doing now", scope: null },+ {+ count: waiting,+ text: `more production ${plural(waiting, "cause is", "causes are")} not ready to act on`,+ scope: "production",+ },+ {+ count: outside,+ text: `${plural(outside, "is", "are")} outside production code`,+ scope: "all",+ },+ ]+ : scope === "production"+ ? [+ { count: production, text: plural(production, "production cause", "production causes"), scope: null },+ { count: now, text: "worth doing now", scope: "now" },+ {+ count: outside,+ text: `more ${plural(outside, "is", "are")} outside production code`,+ scope: "all",+ },+ ]+ : [+ { count: all, text: plural(all, "cause across all code", "causes across all code"), scope: null },+ { count: production, text: "in production", scope: "production" },+ { count: now, text: "worth doing now", scope: "now" },+ ];+ return clauses.filter((clause, index) => index === 0 || clause.count > 0);+}++/**+ * The accounting sentence, with the default queue's left-out breakdown behind+ * a disclosure on it rather than in a second list.+ */+export function ScopeSentence({+ scope,+ counts,+ reviews,+ onScope,+ onReview,+}: {+ scope: PerformanceScope;+ counts: ScopeCounts;+ reviews: ExcludedReview[];+ onScope: (scope: PerformanceScope) => void;+ onReview: (review: ExcludedReview) => void;+}) {+ const [open, setOpen] = useState(false);+ const clauses = scopeAccount(scope, counts);+ return (+ <div className="space-y-2 text-sm text-[var(--color-text-secondary)]">+ {/* Said once, visibly: a second hidden copy for screen readers was read+ (and copied) twice, and a live region around these links would+ re-announce them on every count change. */}+ <p>+ {clauses.map((clause, index) => (+ <span key={clause.text}>+ {index === 0 ? "" : scope === "now" ? ". " : ", "}+ {clause.scope ? (+ <button type="button" onClick={() => onScope(clause.scope!)} className={QUIET_LINK_CLS}>+ <span className="tabular-nums">{clause.count.toLocaleString()}</span> {clause.text}+ </button>+ ) : (+ <>+ <span className="tabular-nums">{clause.count.toLocaleString()}</span> {clause.text}+ </>+ )}+ </span>+ ))}+ .+ {reviews.length > 0 ? (+ <>+ {" "}+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen((value) => !value)}+ className={`${QUIET_LINK_CLS} text-xs`}+ >+ {open ? "Hide why" : "Why left out?"}+ </button>+ </>+ ) : null}+ </p>+ {open ? <LeftOutBreakdown reviews={reviews} onReview={onReview} /> : null}+ </div>+ );+}++/** Why the default queue left each cause out, counts as text, reasons as links. */+function LeftOutBreakdown({+ reviews,+ onReview,+}: {+ reviews: ExcludedReview[];+ onReview: (review: ExcludedReview) => void;+}) {+ return (+ <ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-[var(--color-text-tertiary)]">+ {reviews.map((review) => (+ <li key={review.reason}>+ <span className="tabular-nums">{review.count.toLocaleString()}</span>{" "}+ <button type="button" onClick={() => onReview(review)} className={QUIET_LINK_CLS}>+ {review.label}+ </button>+ </li>+ ))}+ </ul>+ );+}diff --git a/packages/ui/src/health/performance/states.tsx b/packages/ui/src/health/performance/states.tsxindex 51f107585..0e3c7864c 100644--- a/packages/ui/src/health/performance/states.tsx+++ b/packages/ui/src/health/performance/states.tsx@@ -54,14 +54,32 @@ export function UnavailableQueue({ summary }: { summary: PerformanceOpportunityS);}-/** Analyzed, and nothing supported surfaced. Say exactly that. */-export function EmptyQueue() {+/**+ * Analyzed, and nothing in this scope needs a change: the good state. It+ * names the scope and commit it holds for; the accounting sentence beneath+ * says where the rest of the repository is, so "clear" is a statement about+ * something specific and the reader can check the rest.+ */+export function GoodState({+ scope,+ analyzedCommit,+ children,+}: {+ /** "worth doing now in production code", "in all code". */+ scope: string;+ analyzedCommit: string | null | undefined;+ /** The accounting sentence for the scope. */+ children?: React.ReactNode;+}) {+ const at = analyzedCommit ? ` at ${analyzedCommit.slice(0, 7)}` : "";return (<EmptyStatetone="positive"- title="No supported pattern surfaced"- description="The detectors are high precision and low recall, so an empty queue means nothing they recognize was found. It does not measure latency and does not claim the code is fast."- />+ title={`No performance changes ${scope}${at}`}+ description="The detectors read code shape, not latency, and are high precision and low recall."+ >+ {children}+ </EmptyState>);}diff --git a/packages/ui/src/health/performance/tags.tsx b/packages/ui/src/health/performance/tags.tsxnew file mode 100644index 000000000..a39e9a78d--- /dev/null+++ b/packages/ui/src/health/performance/tags.tsx@@ -0,0 +1,25 @@+"use client";++import type { PerformanceOpportunity } from "@repowise-dev/types/health";++import { LowerPriorityTag } from "../lower-priority-tag";+import { PreviewBadge } from "../preview-badge";++/** The tags a cause can carry, on its row and in its drawer: why it can wait,+ * and a language cell served as a preview. */+export function OpportunityTags({ opportunity }: { opportunity: PerformanceOpportunity }) {+ return (+ <>+ {opportunity.lower_priority ? (+ <p className="mt-1">+ <LowerPriorityTag reason={opportunity.lower_priority} />+ </p>+ ) : null}+ {opportunity.preview ? (+ <p className="mt-1">+ <PreviewBadge note={opportunity.preview} />+ </p>+ ) : null}+ </>+ );+}diff --git a/packages/ui/src/health/performance/use-filters.ts b/packages/ui/src/health/performance/use-filters.tsnew file mode 100644index 000000000..1d9d2a0ad--- /dev/null+++ b/packages/ui/src/health/performance/use-filters.ts@@ -0,0 +1,77 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";++import {+ INITIAL_FILTERS,+ parseLegacyFilters,+ readFilters,+ writeFilters,+ type PerformanceFilterState,+} from "./query";++/** A host string is the flat parameters, or a link minted before them. */+export function initialState(initial: string | undefined): PerformanceFilterState {+ if (!initial) return INITIAL_FILTERS;+ const params = new URLSearchParams(initial);+ // A host that predates the flat schema hands over the blob itself.+ return params.has("context") && !params.has("ctx") && !params.has("scope")+ ? parseLegacyFilters(initial)+ : readFilters(params);+}++/** The flat parameters a state writes; equal strings mean the same view. */+function encode(state: PerformanceFilterState): string {+ const params = new URLSearchParams();+ writeFilters(state, params);+ return params.toString();+}++/**+ * The tab's filter state, seeded from the host's URL string and kept in step+ * with it: a URL the view did not write itself (a link followed while the tab+ * stays mounted, back or forward) replaces the state.+ *+ * `current` is read through a ref so two changes in one tick compose, and so+ * callbacks handed to memoized cards need not change with every filter.+ */+export function usePerformanceFilters(+ initialFilters: string | undefined,+ onFiltersChange: ((search: string, state: PerformanceFilterState) => void) | undefined,+) {+ const [filters, setFilters] = useState(() => initialState(initialFilters));+ const current = useRef(filters);+ current.current = filters;+ // What this view handed the host and has not yet seen come back, oldest+ // first, so an intermediate URL from two quick changes is not read as a jump.+ const written = useRef<string[]>([]);++ const apply = useCallback(+ (next: PerformanceFilterState) => {+ current.current = next;+ setFilters(next);+ if (onFiltersChange) {+ const search = encode(next);+ written.current.push(search);+ onFiltersChange(search, next);+ }+ },+ [onFiltersChange],+ );++ useEffect(() => {+ const incoming = initialState(initialFilters);+ const key = encode(incoming);+ const echo = written.current.indexOf(key);+ if (echo >= 0) {+ written.current.splice(0, echo + 1);+ return;+ }+ if (key === encode(current.current)) return;+ written.current = [];+ current.current = incoming;+ setFilters(incoming);+ }, [initialFilters]);++ return { filters, current, apply };+}diff --git a/packages/ui/src/health/performance/use-queue.ts b/packages/ui/src/health/performance/use-queue.tsnew file mode 100644index 000000000..1bb5f307a--- /dev/null+++ b/packages/ui/src/health/performance/use-queue.ts@@ -0,0 +1,34 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import useSWR from "swr";+import type { PerformanceOpportunityPage } from "@repowise-dev/types/health";++import type { PerformanceViewAdapter } from "./adapter";+import { capabilitiesOf } from "./capabilities";+import { PAGE_SIZE, serverKey, toQuery, type PerformanceFilterState } from "./query";++/**+ * One page of the queue for the server half of the filter state. The view+ * fields (actionability segment, open area) are not in the key, so choosing+ * one never refetches.+ */+export function usePerformanceQueue(adapter: PerformanceViewAdapter, filters: PerformanceFilterState) {+ const load = adapter.getPerformanceOpportunities;+ // What a response proved this server understands. It is part of the cache key+ // so that learning it re-asks with the spelling the server accepts: a shared+ // link can restore a production or tooling context before any response has+ // been seen. It only ever flips for a server that predates the vocabulary.+ const [collapse, setCollapse] = useState(false);+ const key = `${collapse ? "legacy:" : ""}${serverKey(filters)}`;+ const swr = useSWR<PerformanceOpportunityPage>(+ load ? `performance-opportunities:${adapter.cacheKey}:${key}` : null,+ () => load!(toQuery(filters, { limit: PAGE_SIZE, collapseContexts: collapse })),+ { revalidateOnFocus: false, keepPreviousData: true },+ );+ const capabilities = useMemo(() => capabilitiesOf(adapter, swr.data), [adapter, swr.data]);+ useEffect(() => {+ if (swr.data) setCollapse(!capabilitiesOf(adapter, swr.data).canonicalContexts);+ }, [adapter, swr.data]);+ return { ...swr, capabilities, supported: Boolean(load) };+}diff --git a/packages/ui/src/health/performance/verdict.tsx b/packages/ui/src/health/performance/verdict.tsxnew file mode 100644index 000000000..ead91c52d--- /dev/null+++ b/packages/ui/src/health/performance/verdict.tsx@@ -0,0 +1,84 @@+"use client";++import type { ReactNode } from "react";+import type { PerformanceScope } from "@repowise-dev/types/health";++import { PageLede } from "../../shared/page-lede";+import { areaLabel } from "./area-groups";+import type { PerformanceAreaGroup } from "./grouping";++/**+ * The lede: the count in the selected scope, named for that scope, then+ * where the causes sit. The accounting sentence beneath it names the rest of+ * the repository; the method notes live behind the label's info tip.+ */++export interface Verdict {+ value: number;+ unit: string;+ /** Where the loaded causes sit, or null when there are none to place. */+ areas: string | null;+}++const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);++const UNIT: Record<PerformanceScope, [string, string]> = {+ now: ["change worth making now", "changes worth making now"],+ production: ["production cause", "production causes"],+ all: ["cause across all code", "causes across all code"],+};++/**+ * The figure is the scope's total under its filters, the same number the+ * actionability bar sums to; the area sentence describes the loaded page.+ */+export function verdictOf(+ scope: PerformanceScope,+ total: number,+ groups: readonly PerformanceAreaGroup[],+): Verdict {+ const [one, many] = UNIT[scope];+ const lead = groups[0];+ return {+ value: total,+ unit: plural(total, one, many),+ areas: !lead+ ? null+ : groups.length === 1+ ? `All in ${areaLabel(lead.area)}.`+ : `Across ${groups.length} areas, led by ${areaLabel(lead.area)}.`,+ };+}++export function PerformanceVerdict({+ verdict,+ analyzedCommit,+ children,+}: {+ verdict: Verdict;+ analyzedCommit: string | null | undefined;+ /** The accounting sentence for the scope. */+ children: ReactNode;+}) {+ return (+ <PageLede+ label="Performance"+ labelHint="Static, high-precision signals read from the code's shape, not measured latency. Repeated call paths fold into one cause, one place to edit, so a row answers what to change once and every observation stays readable as evidence. Evidence confidence, actionability and fix safety are separate judgements."+ value={verdict.value.toLocaleString()}+ unit={verdict.unit}+ >+ {children}+ {verdict.areas || analyzedCommit ? (+ <p className="text-caption text-[var(--color-text-tertiary)]">+ {verdict.areas}+ {analyzedCommit ? (+ <>+ {verdict.areas ? " " : ""}Analysed at{" "}+ <span className="font-mono">{analyzedCommit.slice(0, 7)}</span>.+ </>+ ) : null}+ </p>+ ) : null}+ </PageLede>+ );+}diff --git a/packages/ui/src/lib/areas.ts b/packages/ui/src/lib/areas.tsnew file mode 100644index 000000000..cf5f849b8--- /dev/null+++ b/packages/ui/src/lib/areas.ts@@ -0,0 +1,75 @@+/**+ * Areas: a directory at some depth, the unit every lens groups files by.+ *+ * Pure path arithmetic so any surface (a queue grouped by area, the area map,+ * an area card) names the same area for the same file. Paths are+ * repository-relative with `/` separators, as the index stores them.+ */++/** The area of files that sit at the repository root. */+export const ROOT_AREA = "";++/** The directory part of a path, without the file name. */+export function dirOf(path: string): string {+ const i = path.lastIndexOf("/");+ return i < 0 ? ROOT_AREA : path.slice(0, i);+}++/** The first `depth` directories of `path`'s directory, or the root area. */+export function areaOf(path: string, depth: number): string {+ const dir = dirOf(path);+ if (!dir || depth <= 0) return ROOT_AREA;+ return dir.split("/").slice(0, depth).join("/");+}++/**+ * The depth at which `paths` first separate: one level below the directory+ * they all share, so a repository whose code all lives under `src/` groups by+ * `src/<area>` rather than putting everything in one `src` area. Never below+ * 1, and never deeper than `maxDepth`.+ */+export function separatingDepth(paths: readonly string[], maxDepth = 8): number {+ const dirs = paths.map((p) => dirOf(p).split("/").filter(Boolean));+ if (dirs.length === 0) return 1;+ let shared = 0;+ const first = dirs[0]!;+ while (+ shared < first.length &&+ dirs.every((d) => d.length > shared + 1 && d[shared] === first[shared])+ ) {+ shared += 1;+ }+ return Math.min(Math.max(shared + 1, 1), maxDepth);+}++export interface AreaGroup<T> {+ area: string;+ items: T[];+}++/**+ * Items grouped by area, groups in first-seen order and items in their given+ * order, so a ranked list stays ranked inside each group.+ */+export function groupByArea<T>(+ items: readonly T[],+ pathOf: (item: T) => string,+ depth: number,+): AreaGroup<T>[] {+ const groups = new Map<string, T[]>();+ for (const item of items) {+ const area = areaOf(pathOf(item), depth);+ const bucket = groups.get(area);+ if (bucket) bucket.push(item);+ else groups.set(area, [item]);+ }+ return Array.from(groups, ([area, grouped]) => ({ area, items: grouped }));+}++/**+ * Whether `path` sits inside `area`, at any depth. The root area is the files+ * at the repository root, as `groupByArea` groups them, not every path.+ */+export function inArea(path: string, area: string): boolean {+ return area === ROOT_AREA ? dirOf(path) === ROOT_AREA : path.startsWith(`${area}/`);+}diff --git a/packages/ui/src/shared/more-filters.tsx b/packages/ui/src/shared/more-filters.tsxnew file mode 100644index 000000000..72be88321--- /dev/null+++ b/packages/ui/src/shared/more-filters.tsx@@ -0,0 +1,104 @@+"use client";++import { useId, useRef, useState, type ReactNode } from "react";+import { ChevronRight, X } from "lucide-react";++/**+ * Secondary filters behind one disclosure that states how many are active+ * while it is closed, plus every active filter as a chip that removes it.+ * The primary axis of a list stays visible beside it; this holds the rest.+ */+export function MoreFilters({+ active,+ label = "More filters",+ children,+}: {+ /** How many of the hidden filters are set. */+ active: number;+ label?: string;+ children: ReactNode;+}) {+ const [open, setOpen] = useState(false);+ const panelId = useId();+ return (+ <div className="min-w-0">+ <button+ type="button"+ onClick={() => setOpen((value) => !value)}+ aria-expanded={open}+ aria-controls={panelId}+ className="inline-flex items-center gap-1 rounded text-xs font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <ChevronRight aria-hidden="true" className={`h-3.5 w-3.5 transition-transform ${open ? "rotate-90" : ""}`} />+ {label}+ {active > 0 ? (+ <span className="tabular-nums text-[var(--color-text-tertiary)]">+ <span aria-hidden="true">({active})</span>+ <span className="sr-only">, {active} active</span>+ </span>+ ) : null}+ </button>+ <div id={panelId} hidden={!open} className={open ? "mt-3 flex flex-wrap items-center gap-x-5 gap-y-3" : "hidden"}>+ {open ? children : null}+ </div>+ </div>+ );+}++export interface ActiveFilterChip {+ key: string;+ label: string;+ onRemove: () => void;+}++/** Every active narrowing as a chip that removes it; "Clear all" past one. */+export function ActiveFilterChips({+ chips,+ onClearAll,+ clearAllLabel = "Clear all",+ listLabel = "Active filters",+ removeLabel = (label) => `Remove filter ${label}`,+}: {+ chips: ActiveFilterChip[];+ onClearAll: () => void;+ clearAllLabel?: string;+ listLabel?: string;+ removeLabel?: (label: string) => string;+}) {+ const list = useRef<HTMLUListElement>(null);+ // Removing a chip unmounts the focused button; keep keyboard focus in the+ // list rather than dropping it to the page.+ const remove = (chip: ActiveFilterChip) => {+ chip.onRemove();+ requestAnimationFrame(() => list.current?.querySelector("button")?.focus());+ };+ if (chips.length === 0) return null;+ return (+ <ul ref={list} aria-label={listLabel} className="flex flex-wrap items-center gap-2">+ {chips.map((chip) => (+ <li key={chip.key}>+ <button+ type="button"+ onClick={() => remove(chip)}+ aria-label={removeLabel(chip.label)}+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2.5 py-0.5 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {chip.label}+ <X aria-hidden="true" className="h-3 w-3" />+ </button>+ </li>+ ))}+ {chips.length > 1 ? (+ <li>+ <button+ type="button"+ onClick={onClearAll}+ className="rounded text-xs font-medium text-[var(--color-accent-primary)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {clearAllLabel}+ </button>+ </li>+ ) : null}+ </ul>+ );+}diff --git a/packages/web/src/components/code-health/performance-tab.tsx b/packages/web/src/components/code-health/performance-tab.tsxindex 3e7d68646..3b5e59280 100644--- a/packages/web/src/components/code-health/performance-tab.tsx+++ b/packages/web/src/components/code-health/performance-tab.tsx@@ -2,7 +2,12 @@import { useCallback, useMemo } from "react";import { useRouter, useSearchParams } from "next/navigation";-import { PerformanceView, type PerformanceViewAdapter } from "@repowise-dev/ui/health";+import {+ PerformanceView,+ writePerformanceFilters,+ type PerformanceFilterState,+ type PerformanceViewAdapter,+} from "@repowise-dev/ui/health";import { fileEntityPath, symbolEntityPath } from "@repowise-dev/ui/shared/entity";import {getPerformanceOpportunities,@@ -14,11 +19,18 @@ import { getRefactoringPlan, getRefactoringPlanPrompt } from "@/lib/api/refactorimport { getFileContent } from "@/lib/api/files";import { getRelatedWork, relatedWorkHref } from "@/lib/api/related-work";-/** The queue's own filter state, kept out of the page's `tab` and `lens`. */-const FILTER_PARAM = "perf";/** Shared with the map, which uses the same name to pin a cause's files. */const OPPORTUNITY_PARAM = "opportunity";+/**+ * The URL as it is now, read at call time. Closing over `useSearchParams`+ * would mint new callbacks on every URL change, and the queue's rows are+ * memoized against them.+ */+function currentParams(): URLSearchParams {+ return new URLSearchParams(window.location.search);+}+export function PerformanceTab({ repoId }: { repoId: string }) {const router = useRouter();const searchParams = useSearchParams();@@ -53,17 +65,17 @@ export function PerformanceTab({ repoId }: { repoId: string }) {};}, [repoId, router]);- // A filtered queue is worth sharing and worth surviving a reload, so the- // serialized state rides in one parameter beside the page's own.+ // Every view is a URL: the tab's state rides flat beside the page's own+ // parameters (`ctx`, `sort`, `page`, `area`, ...), and a link minted with+ // the older `perf` blob is still read and rewritten on the first change.const onFiltersChange = useCallback(- (search: string) => {- const sp = new URLSearchParams(searchParams.toString());- if (search) sp.set(FILTER_PARAM, search);- else sp.delete(FILTER_PARAM);+ (_search: string, state: PerformanceFilterState) => {+ const sp = currentParams();+ writePerformanceFilters(state, sp);const qs = sp.toString();router.replace(qs ? `?${qs}` : "?", { scroll: false });},- [router, searchParams],+ [router],);// The open cause rides in the URL beside the filters, so the link the map@@ -71,19 +83,19 @@ export function PerformanceTab({ repoId }: { repoId: string }) {// link worth sending to somebody.const onOpenOpportunityChange = useCallback((opportunityId: string | null) => {- const sp = new URLSearchParams(searchParams.toString());+ const sp = currentParams();if (opportunityId) sp.set(OPPORTUNITY_PARAM, opportunityId);else sp.delete(OPPORTUNITY_PARAM);const qs = sp.toString();router.replace(qs ? `?${qs}` : "?", { scroll: false });},- [router, searchParams],+ [router],);return (<PerformanceViewadapter={adapter}- initialFilters={searchParams.get(FILTER_PARAM) ?? undefined}+ initialFilters={searchParams.toString()}onFiltersChange={onFiltersChange}openOpportunityId={searchParams.get(OPPORTUNITY_PARAM)}onOpenOpportunityChange={onOpenOpportunityChange}diff --git a/tests/unit/analysis/test_areas.py b/tests/unit/analysis/test_areas.pyindex 604f145ee..ddf645c25 100644--- a/tests/unit/analysis/test_areas.py+++ b/tests/unit/analysis/test_areas.py@@ -142,3 +142,33 @@ def test_detail_lists_are_bounded_and_worst_first():assert detail["test_reach"]["with_test_file"] == 1assert detail["distribution"]["total_files"] == 3assert area_detail(index, "nope") is None+++def test_area_at_and_choose_depth_split_where_the_work_separates() -> None:+ from repowise.core.analysis.areas import area_at, choose_depth, group_counts++ assert area_at("a/b/c.py", 1) == "a"+ assert area_at("a/b/c.py", 5) == "a/b"+ assert area_at("x.py", 2) == ""+ # One shared chain, then three packages: the split is below the chain.+ weights = {+ "pkg/src/core/a.py": 2,+ "pkg/src/server/b.py": 2,+ "pkg/src/web/c.ts": 1,+ }+ assert choose_depth(weights) == 3+ assert set(group_counts(weights, 3)) == {"pkg/src/core", "pkg/src/server", "pkg/src/web"}+ # Above the small-queue line, three areas are needed before a split counts.+ big = {path: weight * 10 for path, weight in weights.items()}+ two = {"pkg/a/x.py": 10, "pkg/b/y.py": 10}+ assert choose_depth(big) == 3+ assert choose_depth({"pkg/a/x.py": 2, "pkg/b/y.py": 2}) == 2+ assert choose_depth(two) == 2+ # Inside an area, the depth is chosen below it.+ assert choose_depth(weights, base="pkg/src/core") >= 4+ # No depth splits a lone file; the shallowest is kept.+ assert choose_depth({"a/b.py": 3}) == 1+ assert choose_depth({}) == 1+ # Plain paths weigh one each, and a caller can relax the thresholds.+ assert choose_depth(["a/x.py", "b/y.py"], min_areas=1, small=0) == 1+ assert choose_depth(["src/ui/a.ts", "src/web/b.ts", "x/y.py"], base="src", min_areas=1) == 2diff --git a/tests/unit/health/test_perf_serving.py b/tests/unit/health/test_perf_serving.pyindex 7da0eb38a..05da6dd8d 100644--- a/tests/unit/health/test_perf_serving.py+++ b/tests/unit/health/test_perf_serving.py@@ -20,12 +20,14 @@ from repowise.core.analysis.health.perf.serving import (PerformanceQuery,facet_counts,fold_facets,+ fold_scoped_facets,intervention_file,keep,parse_query,plan_link,rescope_summary,row_sort_key,+ serialize,summary_payload,)from repowise.core.analysis.health.rows import field@@ -77,6 +79,37 @@ def test_plan_link_states() -> None:assert (linked.state, linked.row_id, linked.public_id) == ("available", "7", "plan:x")+def test_summary_view_keeps_what_a_row_is_acted_on_by() -> None:+ row = {+ "opportunity_id": "perf1",+ "biomarker_type": "io_in_loop",+ "boundary_kind": "db",+ "fix_strategy": "batch_or_prefetch_io",+ "fix_safety": "advisory",+ "details": {+ "facets": {"amplification": "per_iteration", "loop_magnitude": "grows_with_data"},+ "fix_rationale": "One sink.",+ "plan": {"effort_bucket": "S", "benefit": 1.0, "cost": 1.0, "risk": 1.0,+ "steps": [{"order": 1}], "validation": {"total": 0}},+ },+ }+ link = plan_link({"plan_state": "no_safe_plan"}, None)+ # The agent surface's summary shape does not grow.+ bare = serialize(row, link, summary=True)+ assert not {"fix", "gain_text", "plan_economics"} & bare.keys()+ summary = serialize(row, link, summary=True, decisions=True)+ assert summary["fix"] == {+ "strategy": "batch_or_prefetch_io", "safety": "advisory", "rationale": "One sink."+ }+ assert summary["gain_text"]+ assert summary["plan_economics"]["effort_bucket"] == "S"+ # The heavy plan fields stay on the detail view only.+ assert "plan_steps" not in summary and "validation" not in summary+ detail = serialize(row, plan_link({"plan_state": "no_safe_plan"}, None))+ assert detail["plan_steps"] == [{"order": 1}]+ assert detail["fix"] == summary["fix"]++def test_intervention_file_prefers_the_symbol() -> None:def opp(symbol: str | None, evidence: list[dict[str, Any]]) -> Any:return SimpleNamespace(intervention_symbol=symbol, evidence=evidence)@@ -317,3 +350,128 @@ async def test_an_unjudged_store_reads_the_default_queue_rule_live(store) -> Nonawait session.commit()live = [i["opportunity_id"] for i in (await service.page(parse_query()[0])).items]assert live == judged == ["perf_0"]+++_SCOPES = [+ # Worth doing now: the stored default-queue verdict.+ {},+ {"queue": True, "actionability": "advisory"},+ # All production causes, every state, proof and role.+ {"actionability": "all", "proof": "all", "role": "all"},+ # Everything.+ {"context": "all", "actionability": "all", "proof": "all", "role": "all"},+ {"context": "all", "actionability": "all", "proof": "all", "role": "all", "boundary": "db"},+ {"context": "test", "actionability": "all", "proof": "all", "role": "all"},+]++#: Facet name and the query attribute that narrows it.+_OWN = {+ "context": "context",+ "boundary": "boundary",+ "confidence": "confidence",+ "actionability": "actionability",+ "proof": "proof",+ "role": "role",+}++[email protected]("args", _SCOPES)+async def test_scoped_facets_sum_to_the_rows_the_scope_returns(store, args) -> None:+ """Every number the dashboard shows sits inside its scope: a facet with no+ own selection sums to the query's total, and a selected value equals it."""+ from repowise.core.persistence.crud.analysis.performance import (+ list_performance_opportunities,+ performance_facet_counts,+ )++ session, repository_id = store+ query, ignored = parse_query(**args, limit=100, lift_defaults=True)+ assert not ignored+ _, total = await list_performance_opportunities(+ session, repository_id, **query.store_filters(), sort=query.sort, limit=100+ )+ grouped = await performance_facet_counts(session, repository_id, scoped=True)+ facets = fold_scoped_facets(grouped, query)+ assert "queue" not in facets+ for name, attribute in _OWN.items():+ counts = {entry["value"]: entry["total"] for entry in facets[name]}+ chosen = getattr(query, attribute)+ if chosen in (None, "all"):+ assert sum(counts.values()) == total, name+ else:+ assert counts.get(chosen, 0) == total, name+++def test_all_lifts_the_default_state_and_proof() -> None:+ query, ignored = parse_query(actionability="all", proof="all", role="all", lift_defaults=True)+ assert not ignored+ assert (query.actionabilities, query.proofs, query.roles) == (None, None, None)+ assert query.queue_eligible is None+ held, _ = parse_query(queue=True, actionability="investigate")+ assert held.queue_eligible is True+ assert held.actionabilities == {"investigate"}+ # The agent surface keeps its vocabulary: "all" is named, not applied.+ _, ignored = parse_query(actionability="all", proof="all")+ assert set(ignored) == {"performance_actionability", "performance_proof"}+ # An explicit proof survives the live default-queue rule on an unjudged store.+ live, _ = parse_query(queue=True, actionability="advisory", proof="proven")+ assert live.store_filters(judged=False)["proofs"] == {"proven"}+++async def test_scope_counts_equal_what_each_scope_lists(store) -> None:+ """The scope control's numbers are the totals its scopes return."""+ from repowise.core.analysis.health.perf.serving import SCOPES, scope_counts+ from repowise.core.persistence.crud.analysis.performance import (+ list_performance_opportunities,+ performance_facet_counts,+ )++ session, repository_id = store+ grouped = await performance_facet_counts(session, repository_id, scoped=True)+ counts = scope_counts(grouped)+ assert set(counts) == {"now", "production", "all"}+ for name, args in SCOPES.items():+ query, _ = parse_query(**args, limit=100, lift_defaults=True)+ _, total = await list_performance_opportunities(+ session, repository_id, **query.store_filters(), sort=query.sort, limit=100+ )+ assert counts[name] == total, name+ assert counts["now"] <= counts["production"] <= counts["all"]+++def test_area_facet_ranks_areas_and_splits_their_states() -> None:+ from repowise.core.analysis.health.perf.serving import area_facet++ groups = [+ ("pkg/a/x.py", "advisory", 3),+ ("pkg/a/y.py", "expected", 5),+ ("pkg/b/z.py", "plan_ready", 1),+ ("pkg/c/w.py", "investigate", 2),+ ]+ facet = area_facet(groups)+ assert facet["depth"] == 2+ assert [entry["area"] for entry in facet["items"]] == ["pkg/b", "pkg/a", "pkg/c"]+ assert facet["items"][1] == {+ "area": "pkg/a", "total": 8, "actionability": {"advisory": 3, "expected": 5},+ }+ assert facet["total"] == sum(entry["total"] for entry in facet["items"]) + facet["more"]+ # A chosen depth wins; a limit counts the rest in ``more``.+ assert area_facet(groups, depth=1)["items"] == [+ {"area": "pkg", "total": 11, "actionability": {"advisory": 3, "expected": 5,+ "plan_ready": 1, "investigate": 2}},+ ]+ assert area_facet(groups, limit=1)["more"] == 10+ # Files directly in the opened area are its own files, flagged as such.+ inside = area_facet([("pkg/a/x.py", "advisory", 1), ("pkg/a/b/y.py", "advisory", 1)], base="pkg/a")+ own = [entry for entry in inside["items"] if entry.get("own")]+ assert [entry["area"] for entry in own] == ["pkg/a"]+++def test_an_area_narrows_by_directory_never_by_a_shared_prefix() -> None:+ query, _ = parse_query(area="pkg/a/", lift_defaults=True)+ assert query.area == "pkg/a"+ assert query.store_filters()["area_prefix"] == "pkg/a/"+ rows = [{"file_path": "pkg/a/x.py", "status": "open"}, {"file_path": "pkg/ab/y.py", "status": "open"}]+ only_area = {"status": "open", "area_prefix": query.area_prefix}+ assert [r["file_path"] for r in rows if keep(r, only_area)] == ["pkg/a/x.py"]+ assert parse_query(area="")[0].store_filters()["area_prefix"] is Nonediff --git a/tests/unit/server/mcp/test_performance_levels.py b/tests/unit/server/mcp/test_performance_levels.pyindex 9ddc5acc6..d577b8f56 100644--- a/tests/unit/server/mcp/test_performance_levels.py+++ b/tests/unit/server/mcp/test_performance_levels.py@@ -463,9 +463,15 @@ async def test_rest_and_the_agent_surface_project_the_same_rows(actionability=None,view="detail",sort="rank",+ proof=None,+ role=None,+ queue=False,+ area=None,+ area_depth=None,file_paths=None,limit=6,offset=0,+ include_unverified=False,session=session,)@@ -516,3 +522,38 @@ async def test_a_plan_is_validated_by_a_test_named_for_its_file_when_no_edge_reaassert "tests/test_a.py" in opportunity["validation"]["tests"]assert plan["validation"]["via"] == "name-match"assert "pytest tests/test_a.py" in plan["validation"]["commands"]+++async def test_the_mcp_queue_shapes_do_not_grow(setup_mcp, materialized):+ """The dashboard's summary rows carry fix, gain and effort; the agent+ surface's do not, and its default rows keep exactly their keys."""+ from repowise.server.mcp_server import get_health++ default = await get_health(include=["performance"], only=["performance_opportunities"])+ summary = await get_health(+ include=["performance"],+ only=["performance_opportunities"],+ performance_view="summary",+ )+ assert set(default["performance_opportunities"][0]) == {+ "actionability_reason", "actionability_state", "affected_call_sites_total",+ "affected_files_total", "biomarker_type", "biomarker_types",+ "biomarker_types_emitted", "biomarker_types_total", "boundary_kind", "confidence",+ "evidence", "evidence_emitted", "evidence_next_cursor", "evidence_reduced_reason",+ "evidence_total", "evidence_truncated", "execution_context", "facets", "file_path",+ "fix", "gain_text", "intervention_kind", "intervention_symbol", "lower_priority",+ "may_lead", "observations_total", "opportunity_id", "performance_model_version",+ "plan_economics", "plan_id", "plan_reason", "plan_reference", "plan_status",+ "plan_steps", "plan_steps_emitted", "plan_steps_total", "prerequisites",+ "prerequisites_emitted", "prerequisites_total", "provenance", "rank_factors",+ "rank_position", "rank_score", "reliable_entry_reachability",+ "resource_fingerprints", "resource_fingerprints_emitted",+ "resource_fingerprints_total", "shared_path_suffix", "shared_path_suffix_emitted",+ "shared_path_suffix_total", "siblings", "siblings_emitted", "siblings_total",+ "terminal_sink", "terminal_sinks", "terminal_sinks_emitted", "terminal_sinks_total",+ "validation", "why_ranked", "why_ranked_emitted", "why_ranked_total",+ }+ assert not {"fix", "gain_text", "plan_economics"} & set(+ summary["performance_opportunities"][0]+ )diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.pyindex cafcd3e29..87d8dd3fb 100644--- a/tests/unit/server/test_performance_opportunities.py+++ b/tests/unit/server/test_performance_opportunities.py@@ -121,7 +121,16 @@ async def test_naming_no_context_asks_about_production(assert body["items"][0]["opportunity_id"] == opportunity_idassert body["summary"]["repository_total"] == 2assert "ignored_arguments" not in body- assert {entry["value"] for entry in body["facets"]["context"]} == {"production", "test"}+ # The dashboard's facets count inside the scope it asked for; the other+ # contexts are counted by the scope sizes, not by this scope's facets.+ assert {entry["value"] for entry in body["facets"]["context"]} == {"production"}+ assert body["scopes"]["all"] == 2+++#: The dashboard's "Everything" scope: every context, state, proof and role.+_EVERYTHING = {"context": "all", "actionability": "all", "proof": "all", "role": "all"}+#: Every production cause.+_PRODUCTION = {"actionability": "all", "proof": "all", "role": "all"}async def test_opportunities_are_grouped_bounded_and_split_by_context(@@ -250,11 +259,22 @@ async def test_facets_keep_the_alternatives_a_selected_filter_would_erase() -> None:"""A facet counted under its own filter reports every other value as zero."""repo_id, _ = await _seed(app, client)- facets = (await _page(client, repo_id, context="test"))["facets"]+ facets = (await _page(client, repo_id, **{**_EVERYTHING, "context": "test"}))["facets"]assert {entry["value"] for entry in facets["context"]} == {"production", "test"}assert {entry["value"]: entry["total"] for entry in facets["context"]}["production"] == 1# A filter on another dimension does narrow this one.- assert (await _page(client, repo_id, boundary="network"))["facets"]["context"] == []+ narrowed = await _page(client, repo_id, **_EVERYTHING, boundary="network")+ assert narrowed["facets"]["context"] == []+++async def test_scoped_facets_sum_to_the_total_the_scope_lists(app, client: AsyncClient) -> None:+ """The lede figure is the scope's total, and the actionability bar sums to it."""+ repo_id, _ = await _seed(app, client)+ for params, scope in (({}, "now"), (_PRODUCTION, "production"), (_EVERYTHING, "all")):+ page = await _page(client, repo_id, **params)+ assert page["total"] == page["scopes"][scope], scope+ states = sum(entry["total"] for entry in page["facets"]["actionability"])+ assert states == page["total"], scopedef _filesystem_finding(path: str, line: int, path_nodes: list[str]) -> HealthFindingData:@@ -298,7 +318,8 @@ async def test_expected_sits_out_of_the_default_queue_but_not_the_facet(assert all(item["actionability_state"] != "expected" for item in default["items"])assert default["summary"]["repository_total"] >= default["total"]- facets = default["facets"]+ # Counted inside the production scope, where it can be listed.+ facets = (await _page(client, repo_id, **_PRODUCTION))["facets"]assert {entry["value"]: entry["total"] for entry in facets["actionability"]}.get("expected") == 1@@ -349,7 +370,8 @@ async def test_the_default_queue_reports_what_it_leaves_out(app, client: AsyncCl"background_unproven": 0,},}- proof = {entry["value"]: entry["total"] for entry in default["facets"]["proof"]}+ production = await _page(client, repo_id, **_PRODUCTION)+ proof = {entry["value"]: entry["total"] for entry in production["facets"]["proof"]}assert proof["unproven"] >= 1asked = await _page(client, repo_id, actionability="investigate")assert [item["intervention_symbol"] for item in asked["items"]] == ["src/clients.py::each"]@@ -563,7 +585,8 @@ async def test_cold_and_unproven_background_roles_sit_one_filter_away(assert [item["intervention_symbol"] for item in default["items"]] == ["src/c.py::run"]excluded = default["summary"]["default_queue"]["excluded"]assert (excluded["cold_role"], excluded["background_unproven"]) == (1, 1)- roles = {entry["value"]: entry["total"] for entry in default["facets"]["role"]}+ production = await _page(client, repo_id, **_PRODUCTION)+ roles = {entry["value"]: entry["total"] for entry in production["facets"]["role"]}assert roles == {"request": 1, "cli": 1, "scheduled_job": 1}assert default["items"][0]["facets"]["execution_role"] == "request"@@ -646,3 +669,16 @@ async def test_a_finding_stored_before_role_owner_is_keyed_on_its_loop_owner(assert details["src/c.py"]["execution_role"] == "request"assert details["src/e.py"]["role_owner"] == "src/e.py::load"assert details["src/e.py"]["execution_role"] == "event_consumer"+++async def test_an_opened_area_narrows_the_rows_but_not_the_scope_sizes(+ app, client: AsyncClient+) -> None:+ repo_id, _ = await _seed(app, client)+ whole = await _page(client, repo_id, **_EVERYTHING)+ assert whole["areas"]["total"] == whole["total"]+ assert sum(entry["total"] for entry in whole["areas"]["items"]) + whole["areas"]["more"] == whole["total"]+ area = whole["areas"]["items"][0]["area"]+ opened = await _page(client, repo_id, **_EVERYTHING, area=area)+ assert opened["total"] == whole["areas"]["items"][0]["total"]+ assert opened["scopes"] == whole["scopes"]