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(performance): default the opportunity queue to production context (#2003)
Raghav Chamadiyacd0a321e234b
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 167c88f69..1875e62f6 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -742,7 +742,7 @@ representations of the same work in one response. The `include` **dimension** na| `refactoring_view` | string | No | Named ordering for `refactoring_opportunities`. `diversified` (default) round-robins the rank order over cause, refactoring type and area, because the ranked head is a genuine run of ties; `canonical` is the published rank order verbatim, ties and all; `file_spread` asked for one row per file, which a composed opportunity satisfies by construction, so it resolves onto the diversified order. Both older values keep working. It also selects the legacy `refactoring_plans` list's view, where `diversified` resolves to that list's historical `canonical` default. || `cursor` | int | No | Zero-based offset into a ranked collection; the `recovery` block names the exact next call. || `performance_view` | string | No | `detail` (default) or `summary`. `summary` keeps identity, counts and plan state and drops the explanatory fields. |-| `performance_context` | string | No | `production` / `tooling` / `test` / `unknown` / `all`. |+| `performance_context` | string | No | `production` (default) / `tooling` / `test` / `unknown` / `all`. The summary block is scoped to the same context as the queue; `repository_total` stays the count over every context. || `performance_boundary` | string | No | `db` / `network` / `filesystem` / `subprocess` / `lock` / `none`. || `performance_confidence` | string | No | Evidence confidence: `high` / `medium` / `low`. Fix safety and actionability are separate facets. || `performance_sort` | string | No | `rank` (default) / `leverage` / `observations`. |@@ -986,7 +986,7 @@ materialized the analysis yet, or did so under an older model.```get_health() # the leadget_health(include=["performance"], only=["performance_summary"])-get_health(include=["performance"], only=["performance_opportunities"], performance_context="production")+get_health(include=["performance"], only=["performance_opportunities"], performance_context="all")get_health(opportunity_id="perf2_...") # the cause, its plan, its evidenceget_health(opportunity_id="perf2_...", only=["performance_evidence"], cursor=3)```diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex fa2c55ce8..98d2ed6f5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -162,6 +162,7 @@ async def _performance_blocks(one of the three does not pay for the other two."""page = None+ query = Noneignored: dict[str, str] = {}if included:# The lede quotes only the first row and no evidence, so a projection@@ -186,7 +187,13 @@ async def _performance_blocks()return _PerformanceBlocks(page=page,- summary=await service.summary() if included and wants("performance_summary") else None,+ summary=(+ # Scoped to the same context as the queue beside it, so two blocks+ # in one answer cannot state totals that contradict each other.+ await service.summary(query.contexts if query else None)+ if included and wants("performance_summary")+ else None+ ),# The bare dashboard lead: one primary-key read of the current summary# row, so it does not grow with the repository and never touches the# queue.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 eedd0d84d..408262fa5 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@@ -56,7 +56,13 @@ def _item(item: dict[str, Any]) -> dict[str, Any]:@router.get("/api/repos/{repo_id}/health/performance-opportunities")async def list_performance_opportunities(repo_id: str,- context: str = Query("all"),+ context: str | None = Query(+ None,+ description=(+ "Execution context to scope to: production, tooling, test, unknown "+ "or all. Defaults to production."+ ),+ ),boundary: str | None = Query(None),confidence: str | None = Query(None),actionability: str | None = Query(None),diff --git a/packages/server/src/repowise/server/services/health_map.py b/packages/server/src/repowise/server/services/health_map.pyindex 72c6bca10..a8735bb9d 100644--- a/packages/server/src/repowise/server/services/health_map.py+++ b/packages/server/src/repowise/server/services/health_map.py@@ -178,8 +178,9 @@ class HealthMapService:"file into the drawn field."),"opportunity_queue": (- f"/api/repos/{repo_id}/health/performance-opportunities lists every "- "open opportunity, drawn or not."+ f"/api/repos/{repo_id}/health/performance-opportunities lists open "+ "opportunities, drawn or not, in production code; pass "+ "context=all for every execution context."),"raise_cap": f"cap accepts up to {MAX_MAP_CAP}.",},diff --git a/packages/server/src/repowise/server/services/performance_health.py b/packages/server/src/repowise/server/services/performance_health.pyindex c2d25e490..c29a80ad9 100644--- a/packages/server/src/repowise/server/services/performance_health.py+++ b/packages/server/src/repowise/server/services/performance_health.py@@ -43,6 +43,18 @@ PerformanceContext = Literal["production", "tooling", "test", "unknown", "all"]CANONICAL_CONTEXTS = ("production", "tooling", "test", "unknown")"""The whole vocabulary. ``all`` is every one of them, never a subset."""+DEFAULT_CONTEXT: PerformanceContext = "production"+"""What a caller that names no context is asking about.++Measured on a 17-repository corpus: 56.5% of opportunities are outside+production code, and the markers concentrated there are the ones that fail+hand-labelling. Test fixtures, benchmark harnesses, CI scripts and mocks are+real code, but "this benchmark repeats work" is a fact about a benchmark, not+performance work someone should schedule. Defaulting to production makes the+first answer the one a reader can act on; every other context stays one+selection away and is counted in ``repository_total`` either way.+"""+_DEPRECATED_CONTEXTS = {"production_tooling": frozenset({"production", "tooling"})}"""Accepted for one compatibility window and never emitted as canonical.@@ -87,7 +99,7 @@ class PerformanceQuery:unrecognized value is reported rather than silently read as "no results"."""- context: PerformanceContext = "all"+ context: PerformanceContext = DEFAULT_CONTEXTboundary: str | None = Noneconfidence: str | None = Noneactionability: str | None = None@@ -162,11 +174,13 @@ def parse_query(ignored[name] = valuereturn None- resolved_context: PerformanceContext = "all"+ resolved_context: PerformanceContext = DEFAULT_CONTEXTif context:if context in CANONICAL_CONTEXTS or context == "all" or context in _DEPRECATED_CONTEXTS:resolved_context = context # type: ignore[assignment]else:+ # Named, so the caller learns the value was not understood, then+ # treated as absent like every other unrecognized filter.ignored["performance_context"] = contextreturn (PerformanceQuery(@@ -250,7 +264,7 @@ class PerformanceHealthService:offset=query.offset,next_offset=emitted if emitted < total else None,facets=await self._facets(query) if with_facets else {},- summary=await self.summary() if with_summary else {},+ summary=await self.summary(query.contexts) if with_summary else {},)async def _evidence_for(@@ -337,13 +351,27 @@ class PerformanceHealthService:# -- headline ----------------------------------------------------------- async def summary(self) -> dict[str, Any]:- """The compact rollup, from the one-row current summary.+ async def summary(self, contexts: frozenset[str] | None = None) -> dict[str, Any]:+ """The compact rollup, over *contexts* when one is selected.Reads by primary key, so a bare dashboard pays one statement for its- performance headline however large the repository is.+ performance headline however large the repository is. Selecting a+ context costs one more aggregate and rewrites the counts to describe+ that context, because a headline that counted the whole repository+ beside a queue that showed one slice of it would state a number the+ list below it contradicts.++ ``repository_total`` survives every scoping, so the census of what was+ analyzed is never the thing a filter hides."""- return _summary_of(await get_performance_summary(self._session, self._repository_id))+ base = _summary_of(await get_performance_summary(self._session, self._repository_id))+ if base["status"] == "unavailable":+ return base+ base["repository_total"] = base["total"]+ if contexts is None:+ return base+ grouped = await performance_facet_counts(self._session, self._repository_id)+ return _rescope(base, grouped, contexts)async def directive(self) -> dict[str, Any]:"""One bounded next action for a bare dashboard call.@@ -521,6 +549,43 @@ class PerformanceHealthService:}+def _rescope(+ base: dict[str, Any],+ grouped: list[tuple[str, str | None, str, str, str, int]],+ contexts: frozenset[str],+) -> dict[str, Any]:+ """Recount one stored rollup over *contexts*, from the facet aggregate.++ The same grouped counts the filter control is drawn from, summed a second+ way. Deriving the scoped headline here keeps one materialized row as the+ only stored rollup: a per-context rollup would be four more rows to write,+ version and keep honest for a number two sums recover exactly.+ """+ actionability: dict[str, int] = {}+ context: dict[str, int] = {}+ boundary: dict[str, int] = {}+ total = 0+ with_plan = 0+ for execution_context, boundary_kind, _confidence, state, plan_state, count in grouped:+ if execution_context not in contexts:+ continue+ total += count+ actionability[state] = actionability.get(state, 0) + count+ context[execution_context] = context.get(execution_context, 0) + count+ key = boundary_kind or "none"+ boundary[key] = boundary.get(key, 0) + count+ if plan_state == "available":+ with_plan += count+ return {+ **base,+ "total": total,+ "actionability": actionability,+ "context": context,+ "boundary": boundary,+ "with_plan_total": with_plan,+ }++def _summary_of(row: Any) -> dict[str, Any]:"""The canonical rollup for one stored summary row, or its absence.diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex 417c0de1a..732f05906 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -426,7 +426,12 @@ export interface PerformanceOpportunitySummary {/** `current` once materialized, `stale_model` after a model bump, or* `unavailable` when this index has not been analyzed yet. */status: "current" | "stale_model" | "unavailable";+ /** Causes in the selected context. Equal to `repository_total` under `all`. */total: number;+ /** Causes in every context, so a scoped headline never hides the census.+ * Absent from a server that predates context scoping, whose `total` is+ * already the repository-wide count. */+ repository_total?: number;performance_model_version?: number;/** The model the stored rows were written by, when it trails the current one. */materialized_model_version?: number;diff --git a/packages/ui/__tests__/health/fixtures/performance-wire-contract.json b/packages/ui/__tests__/health/fixtures/performance-wire-contract.jsonindex f1f127db8..71044b3af 100644--- a/packages/ui/__tests__/health/fixtures/performance-wire-contract.json+++ b/packages/ui/__tests__/health/fixtures/performance-wire-contract.json@@ -14,6 +14,7 @@"context","materialized_model_version","performance_model_version",+ "repository_total","status","total","with_plan_total"diff --git a/packages/ui/__tests__/health/fixtures/performance.ts b/packages/ui/__tests__/health/fixtures/performance.tsindex 9ea2a940d..18ed7dc1d 100644--- a/packages/ui/__tests__/health/fixtures/performance.ts+++ b/packages/ui/__tests__/health/fixtures/performance.ts@@ -159,6 +159,7 @@ export function page(overrides: Partial<PerformanceOpportunityPage> = {}): Perfosummary: {status: "current",total: 7,+ repository_total: 7,performance_model_version: 2,analyzed_commit: "848a8f180abc",actionability: { plan_ready: 1, advisory: 2, investigate: 4 },diff --git a/packages/ui/__tests__/health/performance-query.test.ts b/packages/ui/__tests__/health/performance-query.test.tsindex b5e5de612..6f0148fc9 100644--- a/packages/ui/__tests__/health/performance-query.test.ts+++ b/packages/ui/__tests__/health/performance-query.test.ts@@ -11,14 +11,12 @@ import {} from "../../src/health/performance/query";describe("performance filter state", () => {- it("serializes only what differs from the default", () => {- expect(serializeFilters(INITIAL_FILTERS)).toBe("");- const narrowed = withFilter(- withFilter(INITIAL_FILTERS, "context", "production"),- "boundary",- "db",- );- expect(serializeFilters(narrowed)).toBe("context=production&boundary=db");+ 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");});it("round trips every field through a query string", () => {@@ -35,7 +33,7 @@ describe("performance filter state", () => {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("all");+ expect(parsed.context).toBe("production");expect(parsed.actionability).toBeNull();expect(parsed.offset).toBe(0);});@@ -61,7 +59,13 @@ describe("performance filter state", () => {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: "all", view: "detail", sort: "rank", limit: 20, offset: 0 });+ expect(query).toEqual({+ context: "production",+ view: "detail",+ sort: "rank",+ limit: 20,+ offset: 0,+ });expect("boundary" in query).toBe(false);});diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsxindex 3fa78d417..02e8bb417 100644--- a/packages/ui/__tests__/health/performance-view.test.tsx+++ b/packages/ui/__tests__/health/performance-view.test.tsx@@ -80,7 +80,7 @@ describe("PerformanceView queue", () => {.getAllByRole("status").map((node) => node.textContent ?? "").find((text) => text.includes("opportunities"));- expect(scope).toContain("7 opportunities");+ expect(scope).toContain("7 production opportunities");expect(scope).toContain("848a8f1");});@@ -138,7 +138,15 @@ describe("PerformanceView states", () => {});it("distinguishes an analyzed empty repository from an unanalyzed one", async () => {- const empty = page({ items: [], total: 0, has_more: false, next_offset: null });+ // 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,+ summary: { ...page().summary, total: 0, repository_total: 0 },+ });render(<PerformanceView adapter={adapter({ getPerformanceOpportunities: async () => empty })} />,);diff --git a/packages/ui/src/health/performance-view.tsx b/packages/ui/src/health/performance-view.tsxindex ba6243209..d60a64968 100644--- a/packages/ui/src/health/performance-view.tsx+++ b/packages/ui/src/health/performance-view.tsx@@ -152,8 +152,13 @@ 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);- const filtered = narrowed > 0 || filters.context !== "all";+ // 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} />;@@ -225,7 +230,7 @@ export function PerformanceView({<ContextTabsvalue={filters.context}facets={facets}- total={summary.total}+ total={repositoryTotal}collapsed={!capabilities.canonicalContexts}onChange={(context: PerformanceContextFilter) =>apply(withFilter(filters, "context", context))@@ -246,7 +251,7 @@ export function PerformanceView({<ScopeLinefilteredTotal={data.total}- repositoryTotal={summary.total}+ repositoryTotal={repositoryTotal}context={filters.context}narrowed={narrowed}analyzedCommit={summary.analyzed_commit}diff --git a/packages/ui/src/health/performance/query.ts b/packages/ui/src/health/performance/query.tsindex 65b77680d..f74f40dc9 100644--- a/packages/ui/src/health/performance/query.ts+++ b/packages/ui/src/health/performance/query.ts@@ -25,8 +25,14 @@ export interface PerformanceFilterState {offset: number;}+/**+ * 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.+ */export const INITIAL_FILTERS: PerformanceFilterState = {- context: "all",+ context: "production",boundary: null,confidence: null,actionability: null,@@ -82,11 +88,16 @@ export function toQuery(/*** 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.+ * 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.*/export function serializeFilters(state: PerformanceFilterState): string {const params = new URLSearchParams();- if (state.context !== INITIAL_FILTERS.context) params.set("context", state.context);+ // 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);diff --git a/packages/web/src/components/health/health-file-drawer-host.tsx b/packages/web/src/components/health/health-file-drawer-host.tsxindex d291e8ed2..47f019605 100644--- a/packages/web/src/components/health/health-file-drawer-host.tsx+++ b/packages/web/src/components/health/health-file-drawer-host.tsx@@ -44,6 +44,9 @@ export function HealthFileDrawerHost({getPerformanceOpportunities(repoId, {file_paths: [filePath as string],limit: FILE_CAUSE_LIMIT,+ // Every context. The reader opened this one file, so the question is+ // what was found in it, not whether it is production code.+ context: "all",}),{ revalidateOnFocus: false },);diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.pyindex 171470370..8e7ff04d9 100644--- a/tests/unit/server/test_performance_opportunities.py+++ b/tests/unit/server/test_performance_opportunities.py@@ -89,6 +89,25 @@ async def _page(client: AsyncClient, repo_id: str, **params) -> dict:).json()+async def test_naming_no_context_asks_about_production(+ client: AsyncClient, app+) -> None:+ """Most of what the analysis finds is not production code.++ A caller that names no context is asking what to fix, so the default view+ is the code that ships. Everything else stays one argument away and keeps+ its count in the facets and in ``repository_total``.+ """+ repo_id, opportunity_id = await _seed(app, client)+ body = await _page(client, repo_id)++ assert body["total"] == 1+ assert body["items"][0]["opportunity_id"] == opportunity_id+ assert body["summary"]["repository_total"] == 2+ assert "ignored_arguments" not in body+ assert {entry["value"] for entry in body["facets"]["context"]} == {"production", "test"}++async def test_opportunities_are_grouped_bounded_and_split_by_context(client: AsyncClient, app) -> None:@@ -101,11 +120,19 @@ async def test_opportunities_are_grouped_bounded_and_split_by_context(assert page["items"][0]["confidence"] == "medium"assert page["items"][0]["plan_status"] == "available"assert page["items"][0]["plan_id"]- assert page["summary"]["total"] == 2- assert page["summary"]["context"] == {"production": 1, "test": 1}+ # The headline describes the context on screen, so it cannot state a+ # number the queue under it contradicts. The census survives beside it.+ assert page["summary"]["total"] == 1+ assert page["summary"]["repository_total"] == 2+ assert page["summary"]["context"] == {"production": 1}assert page["summary"]["with_plan_total"] == 1assert page["summary"]["status"] == "current"+ every = await _page(client, repo_id, context="all", limit=1)+ assert every["summary"]["total"] == 2+ assert every["summary"]["repository_total"] == 2+ assert every["summary"]["context"] == {"production": 1, "test": 1}+test_page = await _page(client, repo_id, context="test")assert test_page["total"] == 1assert test_page["items"][0]["plan_id"] is None@@ -184,10 +211,16 @@ async def test_the_retired_context_spelling_still_answers_but_is_never_echoed(async def test_an_unrecognized_filter_value_is_reported_not_read_as_no_data(app, client: AsyncClient) -> None:- """Silently emptying the queue would look like a clean repository."""+ """Silently emptying the queue would look like a clean repository.++ An unrecognized value is named and then treated as absent, which is what+ every other ignored filter does, so it reads as the default view rather+ than as an empty one.+ """repo_id, _ = await _seed(app, client)body = await _page(client, repo_id, context="staging", boundary="pigeon")- assert body["total"] == 2+ assert body["total"] == 1+ assert body["items"][0]["execution_context"] == "production"assert body["ignored_arguments"] == {"performance_context": "staging","performance_boundary": "pigeon",