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(ui): lead Code Health with Fix first and put the code in the plan drawers (#2831)
Raghav Chamadiyaad5755ec6be9
diff --git a/packages/api-client/src/code-health.ts b/packages/api-client/src/code-health.tsindex 93481b33a..5d69ad849 100644--- a/packages/api-client/src/code-health.ts+++ b/packages/api-client/src/code-health.ts@@ -24,6 +24,7 @@ import type {HealthScope,HealthCounts,} from "@repowise-dev/types/health";+import type { FixFirstQueue, FixItem, FixScope } from "@repowise-dev/types/fix-first";import type { Paginated } from "@repowise-dev/types";import { apiGet, apiPatch } from "./client";@@ -259,3 +260,29 @@ export async function getChurnComplexity(opts,);}++/**+ * Fix first: the ranked queue core builds, its lead, and what each eligibility+ * rule excluded. `scope: "all"` keeps test files in the queue.+ */+export async function getFixFirst(+ repoId: string,+ opts: { limit?: number; scope?: FixScope } = {},+): Promise<FixFirstQueue> {+ return apiGet<FixFirstQueue>(`/api/repos/${repoId}/health/fix-first`, {+ limit: opts.limit,+ scope: opts.scope,+ });+}++/** One Fix-first item by its stable id, wherever it ranks. */+export async function getFixFirstItem(+ repoId: string,+ fixId: string,+ opts: { scope?: FixScope } = {},+): Promise<FixItem> {+ return apiGet<FixItem>(+ `/api/repos/${repoId}/health/fix-first/${encodeURIComponent(fixId)}`,+ { scope: opts.scope },+ );+}diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/build.py b/packages/core/src/repowise/core/analysis/health/fix_first/build.pyindex 3951597ea..ee2c00824 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/build.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/build.py@@ -656,7 +656,6 @@ def _perf_unit(rows: list[Any], files: _Files) -> _Unit:call_sites = int(field(lead, "affected_call_sites_total") or 0)files_n = int(field(lead, "affected_files_total") or 1)amplification = facets.get("amplification")- call = f"{noun} call" if noun else "costly call"shaped = text.PERF_SHAPE.get(field(lead, "biomarker_type") or "")if shaped:title = shaped[0].format(name=name)@@ -666,22 +665,13 @@ def _perf_unit(rows: list[Any], files: _Files) -> _Unit:title = f"Move the {noun} call in {name} out of its loop"else:title = f"Fix the repeated work in {name}"- if shaped:- what, gain_text = shaped[1].format(name=name), shaped[2]- elif amplification == "quadratic":- what = f"{name} runs nested loops over the same data"- gain_text = "nested loop work that grows with the square of the data"- elif amplification == "per_call":- what, gain_text = f"{name} repeats a {call} on every call", f"one fewer {call} per call"- else:- what = f"{name} makes a {call} once per loop iteration"- gain_text = f"one {call} per loop iteration" + (- ", grows with the data"- if magnitude == "grows_with_data"- else ", bounded by a fixed loop"- if magnitude == "bounded"- else "; loop size unknown"- )+ what, gain_text = text.perf_cost(+ name,+ field(lead, "biomarker_type"),+ field(lead, "boundary_kind"),+ amplification,+ magnitude,+ )reach = []if call_sites > 1:reach.append(f"{call_sites} call sites in {text.plural(files_n, 'file')} reach it")diff --git a/packages/core/src/repowise/core/analysis/health/fix_first/text.py b/packages/core/src/repowise/core/analysis/health/fix_first/text.pyindex 2948189b4..b7f11eeac 100644--- a/packages/core/src/repowise/core/analysis/health/fix_first/text.py+++ b/packages/core/src/repowise/core/analysis/health/fix_first/text.py@@ -124,6 +124,41 @@ def problem(marker: str | None, subject: str) -> str:return f"{subject} {phrase}"+def perf_cost(+ name: str,+ marker: str | None,+ boundary: str | None,+ amplification: str | None,+ magnitude: str | None,+) -> tuple[str, str]:+ """A performance cause's problem and what fixing it buys, in words.++ One function so the Fix-first item and the performance drawer say the same+ thing about the same cause. The gain names the repeated work, never a time+ saving: nothing here was measured running.+ """+ noun = BOUNDARY_NOUN.get(boundary or "")+ call = f"{noun} call" if noun else "costly call"+ shaped = PERF_SHAPE.get(marker or "")+ if shaped:+ return shaped[1].format(name=name), shaped[2]+ if amplification == "quadratic":+ return (+ f"{name} runs nested loops over the same data",+ "nested loop work that grows with the square of the data",+ )+ if amplification == "per_call":+ return f"{name} repeats a {call} on every call", f"one fewer {call} per call"+ gain = f"one {call} per loop iteration" + (+ ", grows with the data"+ if magnitude == "grows_with_data"+ else ", bounded by a fixed loop"+ if magnitude == "bounded"+ else "; loop size unknown"+ )+ return f"{name} makes a {call} once per loop iteration", gain++def health_gain(value: float, *, ceiling: bool) -> str:shown = "under +0.1" if value < 0.05 else f"+{value:.1f}"return f"{'up to ' if ceiling else ''}{shown} health on this file"diff --git a/packages/server/src/repowise/server/services/performance_health.py b/packages/server/src/repowise/server/services/performance_health.pyindex 59118f9e1..2bfc8f7a4 100644--- a/packages/server/src/repowise/server/services/performance_health.py+++ b/packages/server/src/repowise/server/services/performance_health.py@@ -21,6 +21,7 @@ from typing import Any, Literalfrom sqlalchemy.ext.asyncio import AsyncSessionfrom repowise.core.analysis.health.finding_identity import finding_public_id+from repowise.core.analysis.health.fix_first.text import perf_costfrom repowise.core.analysis.health.perf.opportunities import (PERFORMANCE_MODEL_VERSION,model_state,@@ -493,6 +494,7 @@ class PerformanceHealthService:"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", {}),@@ -509,6 +511,18 @@ class PerformanceHealthService:}+def _gain_text(row: Any, facets: dict[str, Any]) -> str:+ """What fixing this cause buys, in the words the Fix-first item uses."""+ _problem, gain = perf_cost(+ "",+ row.biomarker_type,+ row.boundary_kind,+ facets.get("amplification"),+ facets.get("loop_magnitude"),+ )+ return gain++def _rescope(base: dict[str, Any],grouped: list[tuple[str, str | None, str, str, str, int]],diff --git a/packages/types/src/health.ts b/packages/types/src/health.tsindex f7f17e3d6..e76ac7e17 100644--- a/packages/types/src/health.ts+++ b/packages/types/src/health.ts@@ -472,6 +472,8 @@ export interface PerformanceOpportunity {/** Evidence confidence: how reliably the call path resolved. */confidence: PerformanceOpportunityConfidence;facets: PerformanceOpportunityFacets;+ /** What fixing this cause buys, in the words Fix first uses. Absent on an older server. */+ gain_text?: string;actionability_state: PerformanceActionabilityState;actionability_reason: string;prerequisites: string[];diff --git a/packages/ui/__tests__/health/code-health-lede.test.tsx b/packages/ui/__tests__/health/code-health-lede.test.tsxindex 2c3f1812a..091273a6e 100644--- a/packages/ui/__tests__/health/code-health-lede.test.tsx+++ b/packages/ui/__tests__/health/code-health-lede.test.tsx@@ -132,3 +132,18 @@ describe("CodeHealthLede: the worst test file", () => {expect(container.textContent).not.toContain("Test files are ranked apart");});});++describe("CodeHealthLede secondary, when Fix first leads the page", () => {+ it("keeps one line with the score and its band, and the ribbon behind More", () => {+ const { container } = render(<CodeHealthLede summary={summary()} variant="secondary" />);+ const summaryLine = container.querySelector("summary")!;+ expect(summaryLine.textContent).toContain("7.0");+ expect(summaryLine.textContent).toContain("out of 10 across 3,787 files");+ expect(summaryLine.textContent).toContain("More");+ // The other figures still exist, inside the closed disclosure.+ const details = container.querySelector("details")!;+ expect(details.open).toBe(false);+ expect(details.textContent).toContain("Maintainability");+ expect(details.textContent).toContain("Hotspot health");+ });+});diff --git a/packages/ui/__tests__/health/fix-first.test.tsx b/packages/ui/__tests__/health/fix-first.test.tsxnew file mode 100644index 000000000..37aaba012--- /dev/null+++ b/packages/ui/__tests__/health/fix-first.test.tsx@@ -0,0 +1,142 @@+/**+ * Fix first renders core's queue as it arrives: the header states the scope+ * exactly, the lead opens with its steps and Verify, and actions appear only+ * where the item can back them.+ */++import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import type { FixFirstQueue, FixItem } from "@repowise-dev/types/fix-first";++import { FixFirstList } from "../../src/health/fix-first/fix-first-list";+import { fixFirstScopeSentence, fixPlanLabel } from "../../src/health/fix-first/scope";+import { buildFixItemPrompt } from "../../src/health/ai-prompts/fix-first-prompt";+import { FIX_FIRST_QUEUE } from "./fixtures/fix-first";++const [REFACTOR, FINDING, PERF] = FIX_FIRST_QUEUE.items as [FixItem, FixItem, FixItem];++function renderList(overrides: Partial<React.ComponentProps<typeof FixFirstList>> = {}) {+ return render(+ <FixFirstList+ queue={FIX_FIRST_QUEUE}+ scope="production"+ onScopeChange={() => {}}+ fileHref={(path) => `/files/${path}`}+ planHref={(item) => (item.source.opportunity_id ? `/plan/${item.source.opportunity_id}` : null)}+ {...overrides}+ />,+ );+}++describe("Fix first header", () => {+ it("states shown of eligible and every nonzero exclusion with its count", () => {+ expect(fixFirstScopeSentence(FIX_FIRST_QUEUE)).toBe(+ "3 of 423 eligible items. Excluded: 612 in tests, 91 tooling, 5 generated or vendored, " ++ "158 expected repetition, 12 with no safe fix, 505 below the worth floor, 167 history only.",+ );+ });++ it("omits a rule that excluded nothing", () => {+ const queue: FixFirstQueue = {+ ...FIX_FIRST_QUEUE,+ totals: {+ ...FIX_FIRST_QUEUE.totals,+ excluded: { ...FIX_FIRST_QUEUE.totals.excluded, test: 0, generated: 0 },+ },+ };+ const sentence = fixFirstScopeSentence(queue);+ expect(sentence).not.toContain("in tests");+ expect(sentence).not.toContain("generated");+ });++ it("asks for scope=all when tests are included, and says so", () => {+ const onScopeChange = vi.fn();+ const { rerender } = renderList({ onScopeChange });+ fireEvent.click(screen.getByLabelText("Include tests"));+ expect(onScopeChange).toHaveBeenCalledWith("all");+ rerender(+ <FixFirstList queue={FIX_FIRST_QUEUE} scope="all" onScopeChange={onScopeChange} />,+ );+ expect(screen.getByText(/Test files are included\./)).toBeTruthy();+ });+});++describe("Fix first items", () => {+ it("renders tier as a word, the imperative title, and file:line linking to the file view", () => {+ renderList();+ const items = screen.getAllByRole("listitem").filter((li) => li.parentElement?.tagName === "OL");+ const lead = items[0]!;+ expect(within(lead).getByText("Now")).toBeTruthy();+ expect(within(lead).getByText(REFACTOR.title)).toBeTruthy();+ // The header location and the one step share a span, so both link the file.+ const [link] = within(lead).getAllByRole("link", {+ name: "packages/cli/src/repowise/cli/ui/repo_scanner.py:60",+ });+ expect(link!.getAttribute("href")).toBe("/files/packages/cli/src/repowise/cli/ui/repo_scanner.py");+ expect(within(lead).getByText(REFACTOR.why)).toBeTruthy();+ expect(within(lead).getByText("+1.7 health on this file")).toBeTruthy();+ expect(within(lead).getByText("Small")).toBeTruthy();+ });++ it("opens the lead with steps marked mechanical, Verify with reasons, and a copyable command", () => {+ renderList();+ expect(screen.getByText(/Extract lines 60-122 of quick_repo_scan into compute_info\(repo_path\)/)).toBeTruthy();+ expect(screen.getAllByText("Mechanical").length).toBe(1);+ expect(screen.getByText("tests/unit/cli/test_repo_scanner.py")).toBeTruthy();+ expect(+ screen.getAllByText(": reaches the changed code through the call-graph").length,+ ).toBe(4);+ expect(screen.getByText(REFACTOR.verify.command!)).toBeTruthy();+ expect(screen.getByRole("button", { name: "Copy command" })).toBeTruthy();+ });++ it("says no guarding tests were found when Verify is empty", () => {+ renderList();+ fireEvent.click(screen.getByRole("button", { name: new RegExp(FINDING.title.replace(/[()]/g, "\\$&")) }));+ expect(screen.getByText(/No guarding tests found/)).toBeTruthy();+ });++ it("names the plan by its unit, and offers none for a bare finding", () => {+ expect(fixPlanLabel(REFACTOR)).toBe("Open the refactoring plan");+ expect(fixPlanLabel(PERF)).toBe("Open the performance fix");+ expect(fixPlanLabel(FINDING)).toBeNull();+ renderList();+ expect(screen.getByRole("link", { name: "Open the refactoring plan" }).getAttribute("href")).toBe(+ "/plan/refop3_8ba13d978db910d160b1",+ );+ });++ it("offers triage only for an item backed by a finding id, and writes through the host", async () => {+ const onTriage = vi.fn().mockResolvedValue(undefined);+ renderList({ onTriage });+ fireEvent.click(screen.getByRole("button", { name: "Acknowledged" }));+ await waitFor(() => expect(onTriage).toHaveBeenCalledWith(REFACTOR, "acknowledged"));+ expect(await screen.findByText("Saved as acknowledged.")).toBeTruthy();++ // The perf item maps to no finding, so it has no triage control.+ fireEvent.click(screen.getByRole("button", { name: new RegExp(PERF.title) }));+ expect(screen.getAllByRole("button", { name: "Acknowledged" }).length).toBe(1);+ });++ it("says why nothing is listed when the queue is empty", () => {+ renderList({+ queue: { ...FIX_FIRST_QUEUE, items: [], lead: null, totals: { ...FIX_FIRST_QUEUE.totals, shown: 0 } },+ });+ expect(screen.getByText(/Nothing eligible to fix first/)).toBeTruthy();+ });+});++describe("Fix first agent prompt", () => {+ it("carries the steps and the Verify block", () => {+ const prompt = buildFixItemPrompt({ item: REFACTOR, flavor: "claude-code-mcp" });+ expect(prompt).toContain("## Verify");+ expect(prompt).toContain(`Run: \`${REFACTOR.verify.command}\``);+ expect(prompt).toContain("[mechanical]");+ expect(prompt).toContain('get_health(opportunity_id="refop3_8ba13d978db910d160b1")');+ });++ it("tells the agent to pin behaviour when no test guards the change", () => {+ const prompt = buildFixItemPrompt({ item: FINDING });+ expect(prompt).toContain("No guarding tests found.");+ });+});diff --git a/packages/ui/__tests__/health/fixtures/fix-first.ts b/packages/ui/__tests__/health/fixtures/fix-first.tsnew file mode 100644index 000000000..6be1a3fda--- /dev/null+++ b/packages/ui/__tests__/health/fixtures/fix-first.ts@@ -0,0 +1,614 @@+/**+ * A real Fix-first queue: three items read with `load_fix_first` from an index+ * of this repository (commit f72d50dc), one per kind. Totals are that run's, with+ * `shown` matching the three items kept here.+ */++import type { FixFirstQueue } from "@repowise-dev/types/fix-first";++export const FIX_FIRST_QUEUE: FixFirstQueue = {+ "items": [+ {+ "id": "fix1_2b0e5c0acbb469f46aa9",+ "rank": 3,+ "tier": "now",+ "kind": "refactor",+ "improves": "defect",+ "title": "Extract lines 60-122 of quick_repo_scan into compute_info",+ "target": {+ "file_path": "packages/cli/src/repowise/cli/ui/repo_scanner.py",+ "symbol": "quick_repo_scan",+ "line_start": 60,+ "line_end": 133+ },+ "why": "quick_repo_scan: CCN 15, 44 lines, nests 3 deep; 4 files import it, changed 5 times in 90 days.",+ "facts": [+ {+ "label": "health recoverable",+ "value": "+1.7",+ "basis": "inferred"+ },+ {+ "label": "steps",+ "value": "1 (1 mechanical)",+ "basis": "measured"+ },+ {+ "label": "files that import it",+ "value": "4",+ "basis": "measured"+ },+ {+ "label": "changes in 90 days",+ "value": "5",+ "basis": "measured"+ },+ {+ "label": "file size",+ "value": "149 lines",+ "basis": "measured"+ }+ ],+ "action": {+ "summary": "1 step, 1 mechanical",+ "steps": [+ {+ "order": 1,+ "text": "Extract lines 60-122 of quick_repo_scan into compute_info(repo_path) -> info",+ "file_path": "packages/cli/src/repowise/cli/ui/repo_scanner.py",+ "line": 60,+ "mechanical": true+ }+ ],+ "steps_total": 1,+ "mechanical": true+ },+ "gain": {+ "kind": "health_points",+ "value": 1.671,+ "text": "+1.7 health on this file"+ },+ "effort": {+ "bucket": "S",+ "basis": "sized by the stored plan"+ },+ "risk": {+ "level": "low",+ "dependents": 4,+ "files_touched": 1,+ "text": "Touches 1 file; 4 files import it."+ },+ "confidence": {+ "level": "high",+ "reason": "1 of 1 step proven mechanical by the plan"+ },+ "verify": {+ "tests": [+ {+ "path": "tests/unit/cli/test_repo_scanner.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/cli/test_edenai_reachability.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/cli/test_file_page_volume_prompt.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/cli/test_ui_package.py",+ "reason": "reaches the changed code through the call-graph"+ }+ ],+ "tests_total": 4,+ "command": "pytest tests/unit/cli/test_edenai_reachability.py tests/unit/cli/test_file_page_volume_prompt.py tests/unit/cli/test_repo_scanner.py tests/unit/cli/test_ui_package.py",+ "basis": "inferred"+ },+ "context": [+ {+ "label": "changes in 90 days",+ "value": "5"+ },+ {+ "label": "function hotspot",+ "value": "quick_repo_scan has been modified across 3 commits (repo p80=2) and carries CCN=15 / nesting=3"+ },+ {+ "label": "change entropy",+ "value": "changes are scattered across noisy commits (top 13% among files eligible for change-entropy ranking); a strong history-based fault predictor"+ }+ ],+ "source": {+ "opportunity_id": "refop3_8ba13d978db910d160b1",+ "plan_ids": [+ "refac3_28f8e2028062393ff0b2"+ ],+ "finding_ids": [+ "finding_daa787aeb0baf5bc61ad"+ ]+ },+ "next_call": {+ "tool": "get_health",+ "arguments": {+ "opportunity_id": "refop3_8ba13d978db910d160b1"+ }+ },+ "why_ranked": [+ {+ "factor": "value",+ "value": "3"+ },+ {+ "factor": "health gain",+ "value": "1.67"+ },+ {+ "factor": "problem size",+ "value": "0"+ },+ {+ "factor": "hot file",+ "value": "yes"+ },+ {+ "factor": "tier",+ "value": "worth doing, and the plan is safe to start"+ }+ ]+ },+ {+ "id": "fix1_8ac4c08f700f837e9087",+ "rank": 0,+ "tier": "next",+ "kind": "finding",+ "improves": "defect",+ "title": "Break up GraphFlow (CCN 260, 1,094 lines)",+ "target": {+ "file_path": "packages/ui/src/graph/graph-flow.tsx",+ "symbol": "GraphFlow",+ "line_start": 198,+ "line_end": 1654+ },+ "why": "GraphFlow: CCN 260, 1,094 lines, nests 7 deep; 4 files import it, changed 13 times in 90 days.",+ "facts": [+ {+ "label": "finding",+ "value": "nested_complexity",+ "basis": "measured"+ },+ {+ "label": "severity",+ "value": "critical",+ "basis": "measured"+ },+ {+ "label": "files that import it",+ "value": "4",+ "basis": "measured"+ },+ {+ "label": "changes in 90 days",+ "value": "13",+ "basis": "measured"+ }+ ],+ "action": {+ "summary": "Flatten the control flow.",+ "steps": [+ {+ "order": 1,+ "text": "Flatten the control flow.",+ "file_path": "packages/ui/src/graph/graph-flow.tsx",+ "line": 198,+ "mechanical": false+ }+ ],+ "steps_total": 1,+ "mechanical": false+ },+ "gain": {+ "kind": "health_points",+ "value": 1.821,+ "text": "up to +1.8 health on this file"+ },+ "effort": {+ "bucket": "M",+ "basis": "not sized; no stored plan covers this finding"+ },+ "risk": {+ "level": "low",+ "dependents": 4,+ "files_touched": 1,+ "text": "Touches 1 file; 4 files import it."+ },+ "confidence": {+ "level": "medium",+ "reason": "Measured from the code; no stored plan has checked a fix."+ },+ "verify": {+ "tests": [],+ "tests_total": 0,+ "command": null,+ "basis": "unknown"+ },+ "context": [+ {+ "label": "changes in 90 days",+ "value": "13"+ },+ {+ "label": "change entropy",+ "value": "changes are scattered across noisy commits (top 4.3% among files eligible for change-entropy ranking); a strong history-based fault predictor"+ },+ {+ "label": "function hotspot",+ "value": "GraphFlow has been modified across 19 commits (repo p80=2) and carries CCN=260 / nesting=7"+ }+ ],+ "source": {+ "opportunity_id": null,+ "plan_ids": [],+ "finding_ids": [+ "finding_23450305a33258e5bd64"+ ]+ },+ "next_call": {+ "tool": "get_health",+ "arguments": {+ "targets": [+ "packages/ui/src/graph/graph-flow.tsx"+ ],+ "include": [+ "biomarkers"+ ]+ }+ },+ "why_ranked": [+ {+ "factor": "value",+ "value": "4"+ },+ {+ "factor": "health gain",+ "value": "1.82"+ },+ {+ "factor": "problem size",+ "value": "4"+ },+ {+ "factor": "hot file",+ "value": "yes"+ },+ {+ "factor": "tier",+ "value": "worth doing; the fix needs judgment"+ }+ ]+ },+ {+ "id": "fix1_26c2da3b4c98f8fdef56",+ "rank": 14,+ "tier": "next",+ "kind": "perf_fix",+ "improves": "performance",+ "title": "Batch the database calls loops make through ensure_repo_registration",+ "target": {+ "file_path": "packages/server/src/repowise/server/repo_db.py",+ "symbol": "ensure_repo_registration",+ "line_start": null,+ "line_end": null+ },+ "why": "ensure_repo_registration makes a database call once per loop iteration; 2 call sites in 2 files reach it, an entry point reaches it, the loop grows with the data.",+ "facts": [+ {+ "label": "call sites",+ "value": "2",+ "basis": "measured"+ },+ {+ "label": "files",+ "value": "2",+ "basis": "measured"+ },+ {+ "label": "reachable from an entry point",+ "value": "Yes",+ "basis": "inferred"+ },+ {+ "label": "loop size",+ "value": "grows with data",+ "basis": "inferred"+ }+ ],+ "action": {+ "summary": "Batch the calls, or fetch the data once before the loop",+ "steps": [+ {+ "order": 1,+ "text": "Add a form of ensure_repo_registration that takes every key at once (ensure_repo_registration)",+ "file_path": "packages/server/src/repowise/server/repo_db.py",+ "line": null,+ "mechanical": false+ },+ {+ "order": 2,+ "text": "Collect the keys before the loop and call the batched form once (rediscover_repo_dbs)",+ "file_path": "packages/server/src/repowise/server/repo_db.py",+ "line": 274,+ "mechanical": false+ },+ {+ "order": 3,+ "text": "Collect the keys before the loop and call the batched form once (sync_workspace)",+ "file_path": "packages/server/src/repowise/server/routers/workspace.py",+ "line": 920,+ "mechanical": false+ }+ ],+ "steps_total": 3,+ "mechanical": false+ },+ "gain": {+ "kind": "performance",+ "value": null,+ "text": "one database call per loop iteration, grows with the data"+ },+ "effort": {+ "bucket": "M",+ "basis": "sized by the stored plan"+ },+ "risk": {+ "level": "medium",+ "dependents": null,+ "files_touched": 2,+ "text": "Touches 2 files."+ },+ "confidence": {+ "level": "medium",+ "reason": "The shared I/O sink is proven; no concrete batch API or result-equivalence proof is available."+ },+ "verify": {+ "tests": [+ {+ "path": "tests/unit/server/test_app_lifespan.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/server/test_app_workspace_registry.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/server/test_workspace_search_postgres.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/server/test_workspace_router.py",+ "reason": "reaches the changed code through the call-graph"+ }+ ],+ "tests_total": 4,+ "command": "pytest tests/unit/server/test_app_lifespan.py tests/unit/server/test_app_workspace_registry.py tests/unit/server/test_workspace_router.py tests/unit/server/test_workspace_search_postgres.py",+ "basis": "inferred"+ },+ "context": [+ {+ "label": "changes in 90 days",+ "value": "2"+ }+ ],+ "source": {+ "opportunity_id": "perf2_5ca551b7b7c3293951d0",+ "plan_ids": [],+ "finding_ids": []+ },+ "next_call": {+ "tool": "get_health",+ "arguments": {+ "opportunity_id": "perf2_5ca551b7b7c3293951d0"+ }+ },+ "why_ranked": [+ {+ "factor": "value",+ "value": "3"+ },+ {+ "factor": "runs in",+ "value": "production"+ },+ {+ "factor": "entry reachable",+ "value": "entry_reachable"+ },+ {+ "factor": "loop size",+ "value": "grows_with_data"+ },+ {+ "factor": "boundary",+ "value": "db"+ },+ {+ "factor": "tier",+ "value": "worth doing; the fix needs judgment"+ }+ ]+ }+ ],+ "lead": {+ "id": "fix1_2b0e5c0acbb469f46aa9",+ "rank": 3,+ "tier": "now",+ "kind": "refactor",+ "improves": "defect",+ "title": "Extract lines 60-122 of quick_repo_scan into compute_info",+ "target": {+ "file_path": "packages/cli/src/repowise/cli/ui/repo_scanner.py",+ "symbol": "quick_repo_scan",+ "line_start": 60,+ "line_end": 133+ },+ "why": "quick_repo_scan: CCN 15, 44 lines, nests 3 deep; 4 files import it, changed 5 times in 90 days.",+ "facts": [+ {+ "label": "health recoverable",+ "value": "+1.7",+ "basis": "inferred"+ },+ {+ "label": "steps",+ "value": "1 (1 mechanical)",+ "basis": "measured"+ },+ {+ "label": "files that import it",+ "value": "4",+ "basis": "measured"+ },+ {+ "label": "changes in 90 days",+ "value": "5",+ "basis": "measured"+ },+ {+ "label": "file size",+ "value": "149 lines",+ "basis": "measured"+ }+ ],+ "action": {+ "summary": "1 step, 1 mechanical",+ "steps": [+ {+ "order": 1,+ "text": "Extract lines 60-122 of quick_repo_scan into compute_info(repo_path) -> info",+ "file_path": "packages/cli/src/repowise/cli/ui/repo_scanner.py",+ "line": 60,+ "mechanical": true+ }+ ],+ "steps_total": 1,+ "mechanical": true+ },+ "gain": {+ "kind": "health_points",+ "value": 1.671,+ "text": "+1.7 health on this file"+ },+ "effort": {+ "bucket": "S",+ "basis": "sized by the stored plan"+ },+ "risk": {+ "level": "low",+ "dependents": 4,+ "files_touched": 1,+ "text": "Touches 1 file; 4 files import it."+ },+ "confidence": {+ "level": "high",+ "reason": "1 of 1 step proven mechanical by the plan"+ },+ "verify": {+ "tests": [+ {+ "path": "tests/unit/cli/test_repo_scanner.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/cli/test_edenai_reachability.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/cli/test_file_page_volume_prompt.py",+ "reason": "reaches the changed code through the call-graph"+ },+ {+ "path": "tests/unit/cli/test_ui_package.py",+ "reason": "reaches the changed code through the call-graph"+ }+ ],+ "tests_total": 4,+ "command": "pytest tests/unit/cli/test_edenai_reachability.py tests/unit/cli/test_file_page_volume_prompt.py tests/unit/cli/test_repo_scanner.py tests/unit/cli/test_ui_package.py",+ "basis": "inferred"+ },+ "context": [+ {+ "label": "changes in 90 days",+ "value": "5"+ },+ {+ "label": "function hotspot",+ "value": "quick_repo_scan has been modified across 3 commits (repo p80=2) and carries CCN=15 / nesting=3"+ },+ {+ "label": "change entropy",+ "value": "changes are scattered across noisy commits (top 13% among files eligible for change-entropy ranking); a strong history-based fault predictor"+ }+ ],+ "source": {+ "opportunity_id": "refop3_8ba13d978db910d160b1",+ "plan_ids": [+ "refac3_28f8e2028062393ff0b2"+ ],+ "finding_ids": [+ "finding_daa787aeb0baf5bc61ad"+ ]+ },+ "next_call": {+ "tool": "get_health",+ "arguments": {+ "opportunity_id": "refop3_8ba13d978db910d160b1"+ }+ },+ "why_ranked": [+ {+ "factor": "value",+ "value": "3"+ },+ {+ "factor": "health gain",+ "value": "1.67"+ },+ {+ "factor": "problem size",+ "value": "0"+ },+ {+ "factor": "hot file",+ "value": "yes"+ },+ {+ "factor": "tier",+ "value": "worth doing, and the plan is safe to start"+ }+ ]+ },+ "totals": {+ "candidates": 1973,+ "eligible": 423,+ "shown": 3,+ "excluded": {+ "test": 612,+ "tooling": 91,+ "generated": 5,+ "expected": 158,+ "no_plan": 12,+ "below_min_worth": 505,+ "history_only": 167+ }+ },+ "by_improves": {+ "defect": 266,+ "maintainability": 31,+ "performance": 126+ },+ "model_version": 1,+ "basis": {+ "analyzed_commit": "f72d50dc0c29a22bf30bb673321e9743ba638e4c",+ "health_analyzed_at": "2026-10-01T08:48:22.812504"+ }+};diff --git a/packages/ui/__tests__/health/performance-presentation.test.ts b/packages/ui/__tests__/health/performance-presentation.test.tsindex 24f9ede52..c12e52afa 100644--- a/packages/ui/__tests__/health/performance-presentation.test.ts+++ b/packages/ui/__tests__/health/performance-presentation.test.ts@@ -7,6 +7,7 @@ import {boundaryLabel,facetValueLabel,humanizeToken,+ moduleScopeLabel,opportunityEvidenceLine,opportunityTitle,planPresentation,@@ -178,3 +179,18 @@ describe("queue sections", () => {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");+ expect(moduleScopeLabel("src/jobs.py::__module__", true)).toBe("module scope of jobs.py");+ expect(moduleScopeLabel("src/jobs.py::run")).toBeNull();+ });++ it("never prints __module__ in a title or an evidence line", () => {+ const top = opportunity({ intervention_symbol: "src/jobs.py::__module__", terminal_sink: null });+ expect(opportunityTitle(top)).toBe("Database call inside a loop in module scope of jobs.py");+ expect(opportunityEvidenceLine(top)).toBe("module scope of src/jobs.py");+ });+});+diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsxindex c349ecfa7..dbb7a35fe 100644--- a/packages/ui/__tests__/health/performance-view.test.tsx+++ b/packages/ui/__tests__/health/performance-view.test.tsx@@ -857,3 +857,62 @@ describe("PerformanceView opened by a link", () => {expect(screen.queryByRole("dialog")).toBeNull();});});++describe("PerformanceView drawer, the fix itself", () => {+ it("names the unit a performance fix and states gain, effort and where to edit", async () => {+ const getDetail = vi.fn(async () =>+ resolvedDetail({+ gain_text: "one database call per loop iteration, grows with the data",+ plan_economics: { effort_bucket: "M", benefit: 1, cost: 1, risk: 1 },+ // `intervention_kind` arrives with PR 2817; read as optional until then.+ ...({ intervention_kind: "module" } as object),+ intervention_symbol: "src/jobs.py::__module__",+ }),+ );+ render(<PerformanceView adapter={adapter({ getPerformanceOpportunity: getDetail })} />);+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ expect(within(panel).getByText("Performance fix")).toBeTruthy();+ expect(+ await within(panel).findByText("one database call per loop iteration, grows with the data"),+ ).toBeTruthy();+ expect(within(panel).getByText("Effort").closest("div")!.textContent).toContain("Medium");+ expect(within(panel).getByText(/Edit top-level code,/)).toBeTruthy();+ expect(within(panel).getByText("module scope of src/jobs.py")).toBeTruthy();+ expect(within(panel).queryByText(/__module__/)).toBeNull();+ });++ it("gives every facet a glossary tooltip", async () => {+ render(<PerformanceView adapter={adapter()} />);+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ for (const facet of ["amplification", "exposure", "leverage", "change risk", "loop magnitude"]) {+ expect(within(panel).getByRole("button", { name: `What ${facet} means` })).toBeTruthy();+ }+ });++ it("widens the excerpt up to the loop header and names the sink once", async () => {+ const lines = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`);+ lines[5] = " for row in rows:";+ const readSource = vi.fn(async () => lines.join(String.fromCharCode(10)));+ render(<PerformanceView adapter={adapter({ readSource })} />);+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ expect(await within(panel).findByText("for row in rows:", { exact: false })).toBeTruthy();+ expect(within(panel).getByText("line 10")).toBeTruthy();+ expect(within(panel).queryByText("line 5")).toBeNull();+ expect(within(panel).getByText("The loop starts at line 6.")).toBeTruthy();+ // The sink is named once, under the code, not again above the title.+ expect(within(panel).getAllByText("src/db.py::fetch").length).toBe(1);+ });++ it("says so when no loop header sits within reach of the call", async () => {+ const lines = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`);+ const readSource = vi.fn(async () => lines.join(String.fromCharCode(10)));+ render(<PerformanceView adapter={adapter({ readSource })} />);+ await openFirstRow();+ const panel = await screen.findByRole("dialog");+ expect(await within(panel).findByText(/No for or while line within 15 lines/)).toBeTruthy();+ });+});+diff --git a/packages/ui/__tests__/health/triage-view-lead.test.tsx b/packages/ui/__tests__/health/triage-view-lead.test.tsxnew file mode 100644index 000000000..175212d47--- /dev/null+++ b/packages/ui/__tests__/health/triage-view-lead.test.tsx@@ -0,0 +1,59 @@+/**+ * When the host hands TriageView a lead (Fix first), it renders above the+ * score, and the score drops to one secondary line. Without one, the score+ * keeps leading, so a host that has not adopted Fix first is unchanged.+ */++import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { SWRConfig } from "swr";+import type { HealthOverviewResponse } from "@repowise-dev/types/health";++import { TriageView } from "../../src/health/triage-view";+import type { CodeHealthAdapter } from "../../src/health/code-health-adapter";++const overview = {+ summary: {+ average_health: 6.8,+ maintainability_average: 8.0,+ hotspot_health: 4.5,+ performance_average: 9.7,+ performance_findings: 942,+ file_count: 3787,+ open_findings: 14755,+ },+} as unknown as HealthOverviewResponse;++function adapter(): CodeHealthAdapter {+ return {+ cacheKey: `repo-${Math.random()}`,+ getOverview: vi.fn(async () => overview),+ navigate: vi.fn(),+ renderFileDrawer: () => null,+ } as unknown as CodeHealthAdapter;+}++function renderView(leadSlot?: React.ReactNode) {+ return render(+ <SWRConfig value={{ provider: () => new Map() }}>+ <TriageView adapter={adapter()} {...(leadSlot ? { leadSlot } : {})} />+ </SWRConfig>,+ );+}++describe("TriageView lead", () => {+ it("puts the lead first and the score behind one line", async () => {+ const { container } = renderView(<section data-testid="lead">Fix first</section>);+ await screen.findByText(/out of 10 across 3,787 files/);+ const lead = screen.getByTestId("lead");+ const details = container.querySelector("details")!;+ expect(lead.compareDocumentPosition(details) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(details.open).toBe(false);+ });++ it("keeps the full lede when no lead is given", async () => {+ const { container } = renderView();+ await screen.findByText("Maintainability");+ expect(container.querySelector("details")).toBeNull();+ });+});diff --git a/packages/ui/__tests__/overview/next-actions.test.tsx b/packages/ui/__tests__/overview/next-actions.test.tsxindex 3e97ea4bc..c2e521269 100644--- a/packages/ui/__tests__/overview/next-actions.test.tsx+++ b/packages/ui/__tests__/overview/next-actions.test.tsx@@ -175,3 +175,76 @@ describe("actionHref", () => {).toBe("/repos/r/decisions/d1");});});++describe("the fix_first rule", () => {+ // Shaped the way core's `fix_first` rule emits a Fix-first item: title and+ // why verbatim, the gain first among the facts, the steps as evidence.+ const fixFirst = action({+ id: "act_fix",+ rule: "fix_first",+ tier: "act_now",+ horizons: ["week", "quarter"],+ title: "Extract lines 60-122 of quick_repo_scan into compute_info",+ impact: "quick_repo_scan: CCN 15, 44 lines, nests 3 deep; 4 files import it, changed 5 times in 90 days.",+ why: [+ { label: "gain", value: "+1.7 health on this file", basis: "inferred" },+ { label: "files that import it", value: "4", basis: "measured" },+ ],+ target: {+ kind: "symbol",+ path: "packages/cli/src/repowise/cli/ui/repo_scanner.py",+ symbol: "quick_repo_scan",+ },+ surface: "findings",+ effort: "S",+ done_when: "It leaves Fix first on the next update.",+ details: [+ {+ path: "packages/cli/src/repowise/cli/ui/repo_scanner.py",+ line: 60,+ symbol: null,+ marker: null,+ severity: null,+ reason: "Extract lines 60-122 of quick_repo_scan into compute_info(repo_path) -> info",+ ref: null,+ },+ ],+ details_total: 1,+ commands: [+ {+ purpose: "The full item: steps, tests to run, risk",+ mcp: 'get_health(fix_id="fix1_2b0e5c0acbb469f46aa9")',+ cli: "repowise health",+ },+ ],+ });++ it("renders title, file:line and why on the row", () => {+ render(<NextActions data={response([fixFirst], [])} hrefFor={() => null} />);+ const row = screen.getByRole("listitem", { name: /Open Extract lines 60-122/ });+ expect(within(row).getByText("packages/cli/src/repowise/cli/ui/repo_scanner.py:60")).toBeInTheDocument();+ expect(within(row).getByText(/CCN 15, 44 lines/)).toBeInTheDocument();+ expect(within(row).getByText("+1.7 health on this file")).toBeInTheDocument();+ });++ it("hands the item to an agent with its steps and lookup, and no hot-path copy remains", async () => {+ render(<NextActions data={response([fixFirst], [])} hrefFor={() => null} />);+ fireEvent.click(screen.getByRole("listitem", { name: /Open Extract lines 60-122/ }));+ const dialog = await screen.findByRole("dialog");+ expect(within(dialog).getByRole("button", { name: /Copy prompt/ })).toBeInTheDocument();+ // The prompt is the last preformatted block; the commands above it are earlier ones.+ const blocks = dialog.querySelectorAll("pre");+ const prompt = blocks[blocks.length - 1]!.textContent ?? "";+ expect(prompt).toContain("Extract lines 60-122 of quick_repo_scan into compute_info");+ expect(prompt).toContain("repo_scanner.py:60");+ expect(document.body.textContent).not.toMatch(/hot path/i);+ });++ it("adds no location line when the title already names the file", () => {+ render(<NextActions data={response([], [action()])} hrefFor={() => null} />);+ const row = screen.getByRole("listitem", { name: /Open Raise test coverage/ });+ expect(within(row).queryByText("src/a.py:")).toBeNull();+ expect(within(row).getAllByText("src/a.py").length).toBe(1);+ });+});+diff --git a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsxindex 178ca97de..050199557 100644--- a/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx+++ b/packages/ui/__tests__/refactoring/opportunity-drawer.test.tsx@@ -6,9 +6,13 @@* instead of an empty list under "The steps, in order".*/-import { render, screen } from "@testing-library/react";-import { describe, expect, it } from "vitest";-import type { RefactoringOpportunityDetailResolved } from "@repowise-dev/types/refactoring";+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";+import type {+ OpportunityStep,+ RefactoringOpportunityDetailResolved,+ RefactoringPlan,+} from "@repowise-dev/types/refactoring";import { OpportunityDrawer } from "../../src/refactoring/opportunity-drawer";@@ -67,8 +71,8 @@ describe("OpportunityDrawer steps unavailable", () => {it("keeps triage and says the steps did not load", () => {renderDrawer(detail({ details_status: "unavailable", steps_total: null }));- expect(screen.getByRole("radiogroup", { name: "Triage this opportunity" })).toBeTruthy();- expect(screen.getByText(/The 7 steps for this opportunity could not be loaded/)).toBeTruthy();+ expect(screen.getByRole("radiogroup", { name: "Triage this refactoring plan" })).toBeTruthy();+ expect(screen.getByText(/The 7 steps for this refactoring plan could not be loaded/)).toBeTruthy();expect(screen.queryByText(/Showing 0 of/)).toBeNull();// The prompt is built from the steps, so it is not offered without them.expect(screen.queryByRole("button", { name: /Copy prompt/ })).toBeNull();@@ -82,3 +86,85 @@ describe("OpportunityDrawer steps unavailable", () => {expect(screen.getByRole("button", { name: /Copy prompt/ })).toBeTruthy();});});++const STEP: OpportunityStep = {+ plan_id: "refac3_step",+ refactoring_type: "extract_method",+ target_symbol: "quick_repo_scan",+ file_path: "packages/core/src/big.py",+ line_start: 3,+ line_end: 4,+ effort_bucket: "S",+ confidence: "high",+ impact_delta: 1.7,+ source_biomarker: "complex_method",+ relocated_by: null,+ applicability: { classification: "mechanical", reasons: [], facts: {}, unknowns: [] },+};++const PLAN = {+ id: "refac3_step",+ refactoring_type: "extract_method",+ file_path: "packages/core/src/big.py",+ target_symbol: "quick_repo_scan",+ line_start: 3,+ line_end: 4,+ plan: {},+ evidence: {},+ impact_delta: 1.7,+ effort_bucket: "S",+ blast_radius: {},+ confidence: "high",+ source_biomarker: "complex_method",+ rank_score: 1,+} as RefactoringPlan;++describe("OpportunityDrawer reach, verification and code", () => {+ it("states the blast radius for every type, importers included when stored", () => {+ renderDrawer(detail({ affected_files_total: 2, dependents: 4 }));+ expect(screen.getByText("Touches 2 files; 4 files import it.")).toBeTruthy();+ });++ it("says when importers were not recorded instead of implying none", () => {+ renderDrawer(detail());+ expect(screen.getByText("Touches 1 file; importers not recorded.")).toBeTruthy();+ });++ it("always shows Verify, with the explicit message when nothing guards the file", () => {+ renderDrawer(detail());+ expect(screen.getByText("Verify")).toBeTruthy();+ expect(screen.getByText(/No guarding tests found/)).toBeTruthy();+ });++ it("reads the step's span from the file for an inline excerpt", async () => {+ const readSource = vi.fn().mockResolvedValue(["a = 1", "b = 2", "c = 3", "d = 4", "e = 5"].join(String.fromCharCode(10)));+ render(+ <OpportunityDrawer+ detail={detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] })}+ open+ onOpenChange={() => {}}+ readSource={readSource}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Show the code" }));+ expect(await screen.findByText("c = 3")).toBeTruthy();+ expect(screen.getByText("d = 4")).toBeTruthy();+ expect(screen.queryByText("e = 5")).toBeNull();+ expect(readSource).toHaveBeenCalledWith("packages/core/src/big.py");+ // Generation is off, so the diff preview says how it would be drafted.+ expect(screen.getByText(/A diff preview is drafted by a model on request/)).toBeTruthy();+ });++ it("offers the model-drafted diff preview when the host turned generation on", () => {+ render(+ <OpportunityDrawer+ detail={detail({ steps: [STEP], steps_emitted: 1, plans: [PLAN] })}+ open+ onOpenChange={() => {}}+ onGenerateCode={vi.fn()}+ />,+ );+ fireEvent.click(screen.getByRole("button", { name: "Show the code" }));+ expect(screen.getByRole("button", { name: /Generate code/ })).toBeTruthy();+ });+});diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex e29088f16..47d5c9277 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -9,6 +9,11 @@ export type { AiPromptFlavor } from "./ai-prompts/shared";export { buildAiPrompt, type BuildPromptOptions } from "./ai-prompts/refactor-prompt";export { buildActionPrompt, type BuildActionPromptOptions } from "./ai-prompts/action-prompt";+export {+ buildFixItemPrompt,+ fixVerifyLines,+ type BuildFixItemPromptOptions,+} from "./ai-prompts/fix-first-prompt";export {buildCoverageAiPrompt,type BuildCoveragePromptOptions,diff --git a/packages/ui/src/health/ai-prompts/fix-first-prompt.ts b/packages/ui/src/health/ai-prompts/fix-first-prompt.tsnew file mode 100644index 000000000..71dd81076--- /dev/null+++ b/packages/ui/src/health/ai-prompts/fix-first-prompt.ts@@ -0,0 +1,118 @@+import type { FixItem } from "@repowise-dev/types/fix-first";++import { bulletList, closingSections, joinSections, repoSuffix, type AiPromptFlavor } from "./shared";++// ─────────────────────────────────────────────────────────────────────+// Fix first: one ranked item, handed to an agent with its Verify block+// ─────────────────────────────────────────────────────────────────────++export interface BuildFixItemPromptOptions {+ item: FixItem;+ flavor?: AiPromptFlavor;+ repoName?: string;+}++const OPENING: Record<AiPromptFlavor, string> = {+ generic:+ "You are a senior engineer in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Its facts come from stored analysis; treat them as leads to confirm against the code, not as ground truth.",+ "claude-code":+ "You are Claude Code in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Confirm each fact with Read and Grep before editing, and track the steps with TodoWrite.",+ "claude-code-mcp":+ "You are Claude Code in this repository, which Repowise indexes and serves over MCP. Repowise ranked the change below first among the work it found. Call the MCP lookup under \"Look closer\" for the full record before reading files by hand, then confirm each fact against the code.",+ cursor:+ "Work in this repository. Repowise, a code-intelligence index, ranked the change below first among the work it found. Open the target with @file, confirm each fact, then make the change.",+};++const CONSTRAINTS = [+ "**Confirm before changing.** The analysis is stored, not live; the code may have moved since it ran.",+ "**Keep behaviour.** This is a structural or performance change; what the code returns must not change.",+ "**Run Verify before and after.** If no guarding test exists, write one that pins today's behaviour first.",+ "**Say when it is wrong.** If the problem does not hold, or the change costs more than it saves, report that and stop.",+];++const EXPECTED = [+ "1. Whether the problem held, and what you changed.",+ "2. The Verify run, before and after, with its result.",+ "3. Anything you left undone, and why.",+];++function where(item: FixItem): string {+ const { file_path, symbol, line_start } = item.target;+ const loc = `\`${file_path}${line_start ? `:${line_start}` : ""}\``;+ return symbol ? `${loc} (\`${symbol.split("::").pop()}\`)` : loc;+}++/** The Verify block, worded the way the card words it. */+export function fixVerifyLines(item: FixItem): string {+ const { tests, tests_total, command } = item.verify;+ if (tests.length === 0) {+ return "No guarding tests found. Write a test that pins the current behaviour before you change anything.";+ }+ const listed = tests.map((t) => `- \`${t.path}\`${t.reason ? `: ${t.reason}` : ""}`);+ const more = tests_total - tests.length;+ return joinSections([+ listed.join("\n"),+ more > 0 ? `- …and ${more.toLocaleString()} more` : "",+ command ? `\nRun: \`${command}\`` : "",+ ]);+}++/**+ * Hand one Fix-first item to an agent: the change, why it ranks, the steps in+ * order, and how to verify it. Written so an agent with no prior context can+ * start from this text alone.+ */+export function buildFixItemPrompt({+ item,+ flavor = "generic",+ repoName,+}: BuildFixItemPromptOptions): string {+ const useMcp = flavor === "claude-code-mcp";+ const call = `${item.next_call.tool}(${Object.entries(item.next_call.arguments)+ .map(([k, v]) => `${k}=${JSON.stringify(v)}`)+ .join(", ")})`;+ const steps = item.action.steps.map(+ (s) =>+ `${s.order}. ${s.text} (\`${s.file_path}${s.line ? `:${s.line}` : ""}\`)${+ s.mechanical ? " [mechanical]" : " [judgment]"+ }`,+ );+ const moreSteps = item.action.steps_total - item.action.steps.length;++ return joinSections([+ OPENING[flavor],+ "",+ `## Fix first${repoSuffix(repoName)}`,+ "",+ `**${item.title}**`,+ "",+ item.why,+ "",+ "## Facts",+ "",+ bulletList([+ `Target: ${where(item)}`,+ `Gain: ${item.gain.text}`,+ `Effort: ${item.effort.bucket} (${item.effort.basis})`,+ `Risk: ${item.risk.text}`,+ `Confidence: ${item.confidence.level}. ${item.confidence.reason}`,+ ...item.facts.map((f) => `${f.label}: ${f.value}${f.basis === "measured" ? "" : ` (${f.basis})`}`),+ ]),+ "",+ steps.length+ ? joinSections([+ "## Steps, in order",+ "",+ steps.join("\n"),+ moreSteps > 0 ? `…and ${moreSteps.toLocaleString()} more; the lookup below returns them.` : "",+ "",+ ])+ : "",+ "## Verify",+ "",+ fixVerifyLines(item),+ "",+ useMcp ? joinSections(["## Look closer (Repowise MCP)", "", `\`${call}\``, ""]) : "",+ ...closingSections(CONSTRAINTS, EXPECTED),+ ]);+}diff --git a/packages/ui/src/health/code-health-adapter.ts b/packages/ui/src/health/code-health-adapter.tsindex 94745c532..eabd074e1 100644--- a/packages/ui/src/health/code-health-adapter.ts+++ b/packages/ui/src/health/code-health-adapter.ts@@ -131,6 +131,11 @@ export interface CodeHealthAdapter {* offers no link rather than a second map.*/mapHref?(opportunityId: string, filePath: string): string;+ /**+ * The file's text from the checkout, for an inline excerpt. Optional: a host+ * without it shows the location and no code.+ */+ readSource?(path: string): Promise<string>;/** Navigate to an href (host wires this to its router). */navigate(href: string): void;diff --git a/packages/ui/src/health/code-health-lede.tsx b/packages/ui/src/health/code-health-lede.tsxindex 921df5133..0a5babd93 100644--- a/packages/ui/src/health/code-health-lede.tsx+++ b/packages/ui/src/health/code-health-lede.tsx@@ -89,6 +89,12 @@ export interface CodeHealthLedeProps {pillar?: LedePillar;/** Rendered under the prose, for the host's pillar deep-links. */action?: React.ReactNode;+ /**+ * `secondary` when something else leads the page (Fix first on Code+ * Health): one line with the score and its band, and the prose and the+ * ribbon behind "More". `lead` is the full opening read.+ */+ variant?: "lead" | "secondary";}/** "3 months" / "1 month", from a day count. */@@ -103,6 +109,7 @@ export function CodeHealthLede({distribution,pillar = "health",action,+ variant = "lead",}: CodeHealthLedeProps) {const health = summary.average_health;const maint = summary.maintainability_average;@@ -159,7 +166,7 @@ export function CodeHealthLede({];- return (+ const full = (<div className="flex flex-col gap-6"><PageLedelabel="Code health"@@ -288,6 +295,44 @@ export function CodeHealthLede({<StatRibbon stats={stats} /></div>);++ if (variant === "lead") return full;++ return (+ <details className="group">+ <summary className="flex cursor-pointer list-none flex-wrap items-baseline gap-x-2.5 gap-y-1 rounded focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] [&::-webkit-details-marker]:hidden">+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Code health+ </span>+ <span+ className="text-[15px] font-semibold tabular-nums text-[var(--color-text-primary)]"+ {...(healthChip ? { style: { color: healthChip.color } } : {})}+ >+ {formatScore(health)}+ </span>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ out of 10 across {formatNumber(summary.file_count)} files+ </span>+ {healthChip ? (+ <span className="inline-flex items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <span+ aria-hidden+ className="inline-block h-1.5 w-1.5 rounded-full"+ style={{ background: healthChip.color }}+ />+ {healthChip.label}+ </span>+ ) : null}+ <span className="text-xs font-medium text-[var(--color-accent-primary)] group-open:hidden">+ More+ </span>+ <span className="hidden text-xs font-medium text-[var(--color-accent-primary)] group-open:inline">+ Less+ </span>+ </summary>+ <div className="mt-5">{full}</div>+ </details>+ );}/**diff --git a/packages/ui/src/health/fix-first/fix-first-item.tsx b/packages/ui/src/health/fix-first/fix-first-item.tsxnew file mode 100644index 000000000..93903c8fe--- /dev/null+++ b/packages/ui/src/health/fix-first/fix-first-item.tsx@@ -0,0 +1,366 @@+"use client";++/**+ * One Fix-first item: the change to make, where, why, and what it buys.+ *+ * Collapsed, it is one scan line per fact a person decides on. Expanded, it is+ * the work itself: the steps in order with which ones are mechanical, how to+ * verify the change, the history around the file (muted, never ranked on), and+ * the actions. Every word and number is the payload's; this component chooses+ * only where each one sits.+ */++import { useState, type ElementType } from "react";+import { Check, ChevronDown, Copy } from "lucide-react";+import type { FixItem, FixTier } from "@repowise-dev/types/fix-first";+import type { OpportunityStatus } from "@repowise-dev/types/refactoring";++import { AiPromptButton } from "../ai-prompt-button";+import { CONFIDENCE_LABEL, EFFORT_LABEL, STATUS_LABEL } from "../labels";+import { TIER_LABEL, fixLocation, fixPlanLabel, tierReason } from "./scope";++export type FixTriageStatus = Exclude<OpportunityStatus, "open">;++const TRIAGE: FixTriageStatus[] = ["acknowledged", "resolved", "false_positive"];++/**+ * Tier as a dot and a word. Grayscale on purpose: tier is priority, not health,+ * so it stays off the green/amber/red ramp, and the word carries the meaning.+ */+const TIER_DOT: Record<FixTier, string> = {+ now: "bg-[var(--color-text-primary)]",+ next: "bg-[var(--color-text-tertiary)]",+ later: "border border-[var(--color-text-tertiary)]",+};++const MICRO = "font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";++const LINK =+ "rounded 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)]";++export interface FixFirstItemProps {+ item: FixItem;+ expanded: boolean;+ onToggle: () => void;+ /** The file view for a path. The line rides along for hosts that can scroll to it. */+ fileHref?: ((path: string, line: number | null) => string | undefined) | undefined;+ /** Where "Open plan" lands: the refactoring plan or the performance fix. */+ planHref?: ((item: FixItem) => string | null) | undefined;+ /** Open the shared prompt modal for this item. */+ onAiPrompt?: ((item: FixItem) => void) | undefined;+ /** Triage every finding behind the item. Offered only when it maps to one. */+ onTriage?: ((item: FixItem, status: FixTriageStatus) => Promise<void>) | undefined;+ LinkComponent?: ElementType | undefined;+}++export function FixFirstItem({+ item,+ expanded,+ onToggle,+ fileHref,+ planHref,+ onAiPrompt,+ onTriage,+ LinkComponent,+}: FixFirstItemProps) {+ const Link = LinkComponent ?? "a";+ const panelId = `fix-${item.id}`;+ const location = fixLocation(item);+ const href = fileHref?.(item.target.file_path, item.target.line_start);+ const reason = tierReason(item);++ return (+ <li className="py-4">+ {/* Tier sits in its own column from sm; on a phone it rides above the+ title so the title keeps the width. */}+ <div className="flex min-w-0 flex-col gap-1 sm:flex-row sm:items-start sm:gap-3">+ <span+ className="inline-flex shrink-0 items-center gap-1.5 text-xs text-[var(--color-text-secondary)] sm:mt-[3px] sm:w-14"+ {...(reason ? { title: reason } : {})}+ >+ <span aria-hidden className={`h-2 w-2 shrink-0 rounded-full ${TIER_DOT[item.tier]}`} />+ {TIER_LABEL[item.tier]}+ </span>++ <div className="min-w-0 flex-1">+ <button+ type="button"+ onClick={onToggle}+ aria-expanded={expanded}+ aria-controls={panelId}+ className="group flex w-full min-w-0 items-start justify-between gap-3 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ <span className="min-w-0 text-[15px] font-semibold leading-snug text-[var(--color-text-primary)] [overflow-wrap:anywhere] [text-wrap:pretty] group-hover:text-[var(--color-accent-primary)]">+ {item.title}+ </span>+ <ChevronDown+ aria-hidden+ className={`mt-0.5 h-4 w-4 shrink-0 text-[var(--color-text-tertiary)] transition-transform ${+ expanded ? "rotate-180" : ""+ }`}+ />+ </button>++ <p className="mt-1 font-mono text-xs [overflow-wrap:anywhere]">+ {href ? (+ <Link href={href} className={LINK}>+ {location}+ </Link>+ ) : (+ <span className="text-[var(--color-text-secondary)]">{location}</span>+ )}+ </p>++ <p className="mt-1.5 max-w-[72ch] text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {item.why}+ </p>++ <dl className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1 text-xs text-[var(--color-text-tertiary)]">+ <Fact label="Gain" value={item.gain.text} />+ <Fact label="Effort" value={EFFORT_LABEL[item.effort.bucket]} title={item.effort.basis} />+ <Fact+ label="Confidence"+ value={CONFIDENCE_LABEL[item.confidence.level]}+ title={item.confidence.reason}+ />+ <Fact label="Risk" value={item.risk.text} />+ </dl>++ {expanded ? (+ <div id={panelId} className="mt-4 flex flex-col gap-5">+ <Steps item={item} fileHref={fileHref} LinkComponent={LinkComponent} />+ <FixVerify item={item} />+ {item.context.length > 0 ? (+ <section>+ <h4 className={MICRO}>Context</h4>+ <dl className="mt-1.5 flex flex-col gap-1 text-xs text-[var(--color-text-tertiary)]">+ {item.context.map((c) => (+ <div key={c.label} className="flex min-w-0 flex-wrap gap-x-1.5">+ <dt>{c.label}:</dt>+ <dd className="min-w-0 [overflow-wrap:anywhere]">{c.value}</dd>+ </div>+ ))}+ </dl>+ </section>+ ) : null}+ <Actions+ item={item}+ planHref={planHref}+ onAiPrompt={onAiPrompt}+ onTriage={onTriage}+ LinkComponent={LinkComponent}+ />+ </div>+ ) : null}+ </div>+ </div>+ </li>+ );+}++function Fact({ label, value, title }: { label: string; value: string; title?: string }) {+ return (+ <div className="flex min-w-0 items-baseline gap-1.5" {...(title ? { title } : {})}>+ <dt>{label}</dt>+ <dd className="min-w-0 text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">+ {value}+ {title ? <span className="sr-only">. {title}</span> : null}+ </dd>+ </div>+ );+}++function Steps({+ item,+ fileHref,+ LinkComponent,+}: Pick<FixFirstItemProps, "item" | "fileHref" | "LinkComponent">) {+ const Link = LinkComponent ?? "a";+ const { steps, steps_total } = item.action;+ if (steps.length === 0) {+ return (+ <section>+ <h4 className={MICRO}>Do this</h4>+ <p className="mt-1.5 text-sm text-[var(--color-text-secondary)]">{item.action.summary}</p>+ </section>+ );+ }+ return (+ <section>+ <h4 className={MICRO}>Steps</h4>+ <ol className="mt-1.5 flex flex-col gap-2">+ {steps.map((step) => {+ const where = `${step.file_path}${step.line ? `:${step.line}` : ""}`;+ const href = fileHref?.(step.file_path, step.line);+ return (+ <li key={step.order} className="flex min-w-0 gap-2.5 text-sm">+ <span className="w-5 shrink-0 text-right font-mono text-xs tabular-nums leading-5 text-[var(--color-text-tertiary)]">+ {step.order}.+ </span>+ <div className="min-w-0">+ <p className="text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {step.text}+ <span className="ml-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {step.mechanical ? "Mechanical" : "Judgment"}+ </span>+ </p>+ <p className="mt-0.5 font-mono text-xs [overflow-wrap:anywhere]">+ {href ? (+ <Link href={href} className={LINK}>+ {where}+ </Link>+ ) : (+ <span className="text-[var(--color-text-tertiary)]">{where}</span>+ )}+ </p>+ </div>+ </li>+ );+ })}+ </ol>+ {steps_total > steps.length ? (+ <p className="mt-1.5 text-xs text-[var(--color-text-tertiary)]">+ {`Showing ${steps.length} of ${steps_total} steps; the plan has the rest.`}+ </p>+ ) : null}+ </section>+ );+}++/** How to know the change held: the tests that guard it and the command to run them. */+export function FixVerify({ item }: { item: Pick<FixItem, "verify"> }) {+ const { tests, tests_total, command } = item.verify;+ return (+ <section>+ <h4 className={MICRO}>Verify</h4>+ {tests.length === 0 ? (+ <p className="mt-1.5 text-xs text-[var(--color-text-secondary)]">+ No guarding tests found. Write one that pins the current behaviour before changing it.+ </p>+ ) : (+ <>+ <ul className="mt-1.5 flex flex-col gap-1">+ {tests.map((t) => (+ <li key={t.path} className="min-w-0 text-xs">+ <span className="font-mono text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {t.path}+ </span>+ {t.reason ? (+ <span className="text-[var(--color-text-tertiary)]">{`: ${t.reason}`}</span>+ ) : null}+ </li>+ ))}+ </ul>+ {tests_total > tests.length ? (+ <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">+ {`${tests.length} of ${tests_total} tests listed.`}+ </p>+ ) : null}+ {command ? <CommandLine command={command} /> : null}+ </>+ )}+ </section>+ );+}++function CommandLine({ command }: { command: string }) {+ const [copied, setCopied] = useState(false);+ const copy = async () => {+ try {+ await navigator.clipboard.writeText(command);+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1600);+ } catch {+ /* clipboard blocked: the command stays selectable */+ }+ };+ return (+ <div className="mt-2 flex min-w-0 items-start gap-2 rounded bg-[var(--color-bg-inset)] px-2.5 py-1.5">+ <code className="min-w-0 flex-1 font-mono text-xs text-[var(--color-text-primary)] [overflow-wrap:anywhere]">+ {command}+ </code>+ <button+ type="button"+ onClick={() => void copy()}+ aria-label={copied ? "Copied" : "Copy command"}+ className="inline-flex shrink-0 items-center gap-1 rounded text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"+ >+ {copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}+ <span aria-hidden>{copied ? "Copied" : "Copy"}</span>+ </button>+ </div>+ );+}++function Actions({+ item,+ planHref,+ onAiPrompt,+ onTriage,+ LinkComponent,+}: Pick<FixFirstItemProps, "item" | "planHref" | "onAiPrompt" | "onTriage" | "LinkComponent">) {+ const Link = LinkComponent ?? "a";+ const planLabel = fixPlanLabel(item);+ const href = planLabel ? planHref?.(item) : null;+ const findings = item.source.finding_ids.length;+ const [saved, setSaved] = useState<FixTriageStatus | null>(null);+ const [failed, setFailed] = useState(false);+ const [pending, setPending] = useState(false);++ const triage = async (status: FixTriageStatus) => {+ if (!onTriage) return;+ setPending(true);+ setFailed(false);+ try {+ await onTriage(item, status);+ setSaved(status);+ } catch {+ setFailed(true);+ } finally {+ setPending(false);+ }+ };++ return (+ <section className="flex flex-col gap-3">+ <div className="flex flex-wrap items-center gap-x-4 gap-y-2">+ {href ? (+ <Link href={href} className={`text-sm font-medium ${LINK}`}>+ {planLabel}+ </Link>+ ) : null}+ {onAiPrompt ? (+ <AiPromptButton label="Copy prompt for an agent" onClick={() => onAiPrompt(item)} />+ ) : null}+ </div>+ {onTriage && findings > 0 ? (+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1.5 text-xs">+ <span className="text-[var(--color-text-tertiary)]">+ {`Mark the ${findings === 1 ? "finding" : `${findings} findings`} behind this as`}+ </span>+ {TRIAGE.map((status) => (+ <button+ key={status}+ type="button"+ disabled={pending || saved === status}+ onClick={() => void triage(status)}+ className="rounded-md border border-[var(--color-border-default)] px-2 py-1 font-medium text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] disabled:opacity-50"+ >+ {STATUS_LABEL[status]}+ </button>+ ))}+ <span+ role="status"+ className={failed ? "text-[var(--color-error)]" : "text-[var(--color-text-tertiary)]"}+ >+ {failed+ ? "Could not save that. Nothing changed."+ : saved+ ? `Saved as ${STATUS_LABEL[saved].toLowerCase()}.`+ : ""}+ </span>+ </div>+ ) : null}+ </section>+ );+}diff --git a/packages/ui/src/health/fix-first/fix-first-list.tsx b/packages/ui/src/health/fix-first/fix-first-list.tsxnew file mode 100644index 000000000..e07b1cef1--- /dev/null+++ b/packages/ui/src/health/fix-first/fix-first-list.tsx@@ -0,0 +1,143 @@+"use client";++/**+ * Fix first: the ranked list of what to fix in this repository, as core built+ * it. The header states the scope exactly (shown of eligible, and what each+ * rule excluded); the list is the payload's order. Shared by every host: the+ * host fetches, routes and writes, this renders.+ */++import { useState, type ElementType } from "react";+import type { FixFirstQueue, FixItem, FixScope } from "@repowise-dev/types/fix-first";++import { Skeleton, SkeletonRegion } from "../../ui/skeleton";+import { ApiError } from "../../shared/api-error";+import { toFriendlyMessage } from "../../lib/errors";+import { OverviewSection } from "../../overview/section";+import { AiPromptModal } from "../ai-prompt-modal";+import { buildFixItemPrompt } from "../ai-prompts/fix-first-prompt";+import { FixFirstItem, type FixTriageStatus } from "./fix-first-item";+import { fixFirstScopeSentence, fixLocation } from "./scope";++export interface FixFirstListProps {+ queue: FixFirstQueue | undefined;+ loading?: boolean | undefined;+ error?: unknown;+ onRetry?: (() => void) | undefined;+ /** `production` leaves test files out; `all` keeps them. Omit the setter to hide the toggle. */+ scope: FixScope;+ onScopeChange?: ((scope: FixScope) => void) | undefined;+ fileHref?: ((path: string, line: number | null) => string | undefined) | undefined;+ planHref?: ((item: FixItem) => string | null) | undefined;+ onTriage?: ((item: FixItem, status: FixTriageStatus) => Promise<void>) | undefined;+ repoName?: string | undefined;+ LinkComponent?: ElementType | undefined;+ /** Drop the section's top hairline when it opens the page. */+ flush?: boolean | undefined;+}++export function FixFirstList({+ queue,+ loading = false,+ error,+ onRetry,+ scope,+ onScopeChange,+ fileHref,+ planHref,+ onTriage,+ repoName,+ LinkComponent,+ flush = true,+}: FixFirstListProps) {+ // The lead opens expanded: it is the one thing this section says to do.+ const [open, setOpen] = useState<ReadonlySet<string> | null>(null);+ const expanded = open ?? new Set(queue?.lead ? [queue.lead.id] : []);+ const toggle = (id: string) => {+ const next = new Set(expanded);+ if (next.has(id)) next.delete(id);+ else next.add(id);+ setOpen(next);+ };+ const [promptFor, setPromptFor] = useState<FixItem | null>(null);++ const toggleTests = onScopeChange ? (+ <label className="inline-flex cursor-pointer items-center gap-1.5 text-xs text-[var(--color-text-secondary)]">+ <input+ type="checkbox"+ checked={scope === "all"}+ onChange={(e) => onScopeChange(e.target.checked ? "all" : "production")}+ className="h-3.5 w-3.5 accent-[var(--color-accent-primary)]"+ />+ Include tests+ </label>+ ) : undefined;++ const description = queue+ ? `${fixFirstScopeSentence(queue)}${scope === "all" ? " Test files are included." : ""}`+ : undefined;++ return (+ <OverviewSection+ title="Fix first"+ flush={flush}+ action={toggleTests}+ {...(description ? { description } : {})}+ >+ {error ? (+ <ApiError+ title="Couldn't load Fix first"+ message={toFriendlyMessage(error)}+ {...(onRetry ? { onRetry } : {})}+ />+ ) : loading && !queue ? (+ <SkeletonRegion className="flex flex-col gap-3" label="Loading Fix first">+ <Skeleton className="h-4 w-80 max-w-full" />+ <Skeleton className="h-20 w-full" />+ <Skeleton className="h-20 w-full" />+ </SkeletonRegion>+ ) : queue && queue.items.length === 0 ? (+ <p className="text-sm text-[var(--color-text-secondary)]">+ Nothing eligible to fix first. Every candidate was excluded by a rule listed above, or the+ index has no health analysis yet.+ </p>+ ) : queue ? (+ <ol className="flex flex-col divide-y divide-[var(--color-border-default)]">+ {queue.items.map((item) => (+ <FixFirstItem+ key={item.id}+ item={item}+ expanded={expanded.has(item.id)}+ onToggle={() => toggle(item.id)}+ fileHref={fileHref}+ planHref={planHref}+ onAiPrompt={setPromptFor}+ onTriage={onTriage}+ LinkComponent={LinkComponent}+ />+ ))}+ </ol>+ ) : null}++ <AiPromptModal+ open={promptFor !== null}+ onOpenChange={(next) => {+ if (!next) setPromptFor(null);+ }}+ getPrompt={+ promptFor+ ? (flavor) =>+ buildFixItemPrompt({+ item: promptFor,+ flavor,+ ...(repoName ? { repoName } : {}),+ })+ : null+ }+ filePath={promptFor ? fixLocation(promptFor) : null}+ title="Prompt for an agent"+ description="The change, why it ranks first, the steps in order, and how to verify it."+ />+ </OverviewSection>+ );+}diff --git a/packages/ui/src/health/fix-first/index.ts b/packages/ui/src/health/fix-first/index.tsnew file mode 100644index 000000000..6b7649847--- /dev/null+++ b/packages/ui/src/health/fix-first/index.ts@@ -0,0 +1,3 @@+export * from "./fix-first-list";+export * from "./fix-first-item";+export * from "./scope";diff --git a/packages/ui/src/health/fix-first/scope.ts b/packages/ui/src/health/fix-first/scope.tsnew file mode 100644index 000000000..8e8c15caa--- /dev/null+++ b/packages/ui/src/health/fix-first/scope.ts@@ -0,0 +1,80 @@+/**+ * Words for the Fix-first queue. Everything here reads fields core already+ * decided; nothing ranks, groups or counts. If a sentence needs a rule, the+ * rule belongs in `repowise.core.analysis.health.fix_first`.+ */++import type {+ FixExclusion,+ FixFirstQueue,+ FixItem,+ FixTier,+} from "@repowise-dev/types/fix-first";++import { formatNumber } from "../../lib/format";+import { WORK_UNIT_LABEL } from "../labels";++export const TIER_LABEL: Record<FixTier, string> = {+ now: "Now",+ next: "Next",+ later: "Later",+};++/** Core's own reason for the tier, from `why_ranked`. */+export function tierReason(item: Pick<FixItem, "why_ranked">): string | null {+ return item.why_ranked.find((f) => f.factor === "tier")?.value ?? null;+}++/**+ * Each exclusion as it reads after its count, in the order the sentence lists+ * them. Every key of `FixExclusion` is here, so a new rule fails type-check+ * until it has words.+ */+export const EXCLUSION_LABEL: Record<FixExclusion, string> = {+ test: "in tests",+ tooling: "tooling",+ generated: "generated or vendored",+ expected: "expected repetition",+ no_plan: "with no safe fix",+ below_min_worth: "below the worth floor",+ history_only: "history only",+};++const EXCLUSION_ORDER: FixExclusion[] = [+ "test",+ "tooling",+ "generated",+ "expected",+ "no_plan",+ "below_min_worth",+ "history_only",+];++/**+ * The header line, exact about scope: how many items are shown out of how+ * many are eligible, and what each rule left out. A zero count is omitted+ * because it excluded nothing.+ */+export function fixFirstScopeSentence(queue: FixFirstQueue<unknown>): string {+ const { shown, eligible, excluded } = queue.totals;+ const head = `${formatNumber(shown)} of ${formatNumber(eligible)} eligible item${+ eligible === 1 ? "" : "s"+ }.`;+ const parts = EXCLUSION_ORDER.filter((key) => (excluded[key] ?? 0) > 0).map(+ (key) => `${formatNumber(excluded[key])} ${EXCLUSION_LABEL[key]}`,+ );+ return parts.length ? `${head} Excluded: ${parts.join(", ")}.` : head;+}++/** `path:60`, or the path alone when core stored no line. */+export function fixLocation(item: Pick<FixItem, "target">): string {+ const { file_path, line_start } = item.target;+ return line_start ? `${file_path}:${line_start}` : file_path;+}++/** What "Open plan" opens, named for the unit it lands on; null for a finding. */+export function fixPlanLabel(item: Pick<FixItem, "kind">): string | null {+ if (item.kind === "refactor") return `Open the ${WORK_UNIT_LABEL.refactor}`;+ if (item.kind === "perf_fix") return `Open the ${WORK_UNIT_LABEL.perf_fix}`;+ return null;+}diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.tsindex c44947389..35ac3390e 100644--- a/packages/ui/src/health/index.ts+++ b/packages/ui/src/health/index.ts@@ -47,3 +47,4 @@ export * from "./coverage-view";export * from "./inferred-tests-view";export * from "./tests-reaching-list";export * from "./trend-view";+export * from "./fix-first";diff --git a/packages/ui/src/health/labels.ts b/packages/ui/src/health/labels.tsnew file mode 100644index 000000000..75f8d6829--- /dev/null+++ b/packages/ui/src/health/labels.ts@@ -0,0 +1,38 @@+/**+ * Words for the vocabularies more than one Code Health surface prints.+ *+ * One copy, imported everywhere: an effort bucket that read "Medium" on one tab+ * and "Moderate" on the next would be two vocabularies for one value.+ */++import type { Confidence, EffortBucket, OpportunityStatus } from "@repowise-dev/types/refactoring";++export const EFFORT_LABEL: Record<EffortBucket, string> = {+ S: "Small",+ M: "Medium",+ L: "Large",+ XL: "Extra large",+};++export const CONFIDENCE_LABEL: Record<Confidence, string> = {+ low: "Low",+ medium: "Medium",+ high: "High",+};++/** Triage states. Findings and refactoring plans share the vocabulary. */+export const STATUS_LABEL: Record<OpportunityStatus, string> = {+ open: "Open",+ acknowledged: "Acknowledged",+ resolved: "Resolved",+ false_positive: "False positive",+};++/**+ * The two units of work a person opens. A refactoring plan is one file's+ * ordered steps; a performance fix is one cause and the place to change it.+ */+export const WORK_UNIT_LABEL = {+ refactor: "refactoring plan",+ perf_fix: "performance fix",+} as const;diff --git a/packages/ui/src/health/performance/adapter.ts b/packages/ui/src/health/performance/adapter.tsindex 02aa1c37a..01fa9747a 100644--- a/packages/ui/src/health/performance/adapter.ts+++ b/packages/ui/src/health/performance/adapter.ts@@ -16,6 +16,7 @@ export type PerformanceViewAdapter = Pick<| "getRefactoringPlan"| "refactoringPlanHref"| "mapHref"+ | "readSource"| "fileHref"| "symbolHref"| "navigate"diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsxindex 10e6a3b4e..251dd4df1 100644--- a/packages/ui/src/health/performance/drawer.tsx+++ b/packages/ui/src/health/performance/drawer.tsx@@ -13,9 +13,12 @@ import type {import type { RecommendationValidation, RefactoringPlan } from "@repowise-dev/types/refactoring";import { AdaptivePanel } from "../../shared/adaptive-panel";+import { InfoTip } from "../../shared/info-tip";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 type { PerformanceViewAdapter } from "./adapter";import { RawObservations } from "./evidence";import {@@ -25,8 +28,12 @@ import {boundaryLabel,CONFIDENCE_LABEL,contextLabel,+ FACET_GLOSSARY,humanizeToken,- opportunityEvidenceLine,+ INTERVENTION_KIND_LABEL,+ interventionKind,+ loopHeaderAbove,+ moduleScopeLabel,opportunityTitle,planPresentation,siblingFixLabel,@@ -66,15 +73,19 @@ 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="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ <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 ? (@@ -375,16 +386,14 @@ export function OpportunityDrawer({onOpenChange={(open) => {if (!open) onClose();}}- eyebrow="Performance opportunity"- title={current ? opportunityTitle(current) : "Performance opportunity"}+ 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">- <p className="break-all font-mono text-xs text-[var(--color-text-secondary)]">- {opportunityEvidenceLine(current)}- </p>+ <WhereToEdit opportunity={current} />{unresolved ? <ModelStateNotice state={unresolved.model_state} /> : null}{resolved ? <ModelStateNotice state={resolved.model_state} /> : null}@@ -403,6 +412,10 @@ export function OpportunityDrawer({<MapLink adapter={adapter} opportunity={current} />+ <FixSummary opportunity={current} />++ <CodeSection opportunity={current} adapter={adapter} />+<Section 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)} />@@ -420,14 +433,28 @@ export function OpportunityDrawer({<Fieldlabel="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}/>- <Field label="Exposure" value={humanizeToken(current.facets.exposure)} />- <Field label="Leverage" value={humanizeToken(current.facets.leverage)} />- <Field label="Change risk" value={humanizeToken(current.facets.change_risk)} />{current.facets.loop_magnitude && current.facets.loop_magnitude !== "n/a" ? (<Fieldlabel="Loop magnitude"value={humanizeToken(current.facets.loop_magnitude)}+ hint={FACET_GLOSSARY.loop_magnitude}/>) : null}</dl>@@ -548,6 +575,97 @@ export function OpportunityDrawer({);}+/**+ * 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>+ );+}+/*** Where this cause sits on the one map.*diff --git a/packages/ui/src/health/performance/presentation.ts b/packages/ui/src/health/performance/presentation.tsindex 417bc0762..70cad4578 100644--- a/packages/ui/src/health/performance/presentation.ts+++ b/packages/ui/src/health/performance/presentation.ts@@ -11,6 +11,7 @@ import {import type { C4IoKind } from "@repowise-dev/types/external-systems";import { biomarkerLabel } from "../biomarker-glossary";+import { CONFIDENCE_LABEL } from "../labels";/*** Display derivations for the performance queue. Everything here reads fields@@ -54,11 +55,7 @@ export const ACTIONABILITY_HINT: Record<PerformanceActionabilityState, string> =expected: "The repetition is real and there is no change to make.",};-export const CONFIDENCE_LABEL: Record<PerformanceOpportunityConfidence, string> = {- high: "High",- medium: "Medium",- low: "Low",-};+export { CONFIDENCE_LABEL };export const FACET_LABEL: Record<PerformanceFacetKey, string> = {context: "Context",@@ -74,6 +71,81 @@ const PLAN_STATE_LABEL: Record<string, string> = {not_persisted: "Needs an index refresh",};+/**+ * Where the edit goes. The wire type gains `intervention_kind` with the+ * one-opportunity-per-intervention model (PR 2817); until that lands it is read+ * as optional here, and a row without it simply shows no kind.+ */+export type InterventionKind = "function" | "shared_helper" | "module";++export const INTERVENTION_KIND_LABEL: Record<InterventionKind, string> = {+ function: "The loop's own function",+ shared_helper: "A helper every caller shares",+ module: "Top-level code",+};++export function interventionKind(opportunity: PerformanceOpportunity): InterventionKind | null {+ const kind = (opportunity as { intervention_kind?: string | null }).intervention_kind;+ return kind && kind in INTERVENTION_KIND_LABEL ? (kind as InterventionKind) : null;+}++/** How far above a call the excerpt looks for the loop that repeats it. */+export const LOOP_SEARCH_LINES = 15;++const LOOP_HEADER = /^\s*(?:async\s+for|for|while)\b/;++/**+ * The loop header above a call, for the excerpt. The evidence stores the+ * call's line, not the loop's, so this scans upward for the nearest+ * `for` / `while` / `async for` line and says so when there is none in range.+ */+export function loopHeaderAbove(+ fileLines: string[],+ callLine: number,+ maxUp = LOOP_SEARCH_LINES,+): { start: number; note: string | null } {+ for (let line = callLine; line >= Math.max(1, callLine - maxUp); line -= 1) {+ if (LOOP_HEADER.test(fileLines[line - 1] ?? "")) {+ return { start: line, note: `The loop starts at line ${line}.` };+ }+ }+ return {+ start: callLine,+ note: `No for or while line within ${maxUp} lines above the call; the loop is further up or in a caller.`,+ };+}++const MODULE_SCOPE = "::__module__";++/**+ * `path::__module__` names top-level code, which has no function to call it+ * by. It reads as "module scope of path"; `short` keeps only the file name,+ * for a title.+ */+export function moduleScopeLabel(symbol: string, short = false): string | null {+ if (!symbol.endsWith(MODULE_SCOPE)) return null;+ const file = symbol.slice(0, -MODULE_SCOPE.length);+ return `module scope of ${short ? (file.split("/").pop() ?? file) : file}`;+}++/**+ * What each facet means, for the drawer's tooltips. The band edges mirror+ * `_LEVERAGE_BANDS` and `_CHANGE_RISK_BANDS` in core's `opportunity_rank.py`;+ * change both together.+ */+export const FACET_GLOSSARY = {+ amplification:+ "How the cost repeats. Per iteration: once per loop pass. Quadratic: nested loops over the same data. Per call: once each time the function runs.",+ exposure:+ "Whether an entry point reaches the loop's function in the call graph. Unknown when the graph could not say either way.",+ leverage:+ "How many call sites one fix settles. Isolated is 1, local up to 3, shared up to 9, broad 10 or more.",+ change_risk:+ "How many files holding evidence the edit reaches. Contained is 1, moderate up to 4, wide 5 or more.",+ loop_magnitude:+ "Whether the loop's trip count grows with the data. A bounded loop runs a fixed number of times.",+} as const;+/** The facet value used when an opportunity crosses no I/O boundary. */const NO_BOUNDARY = "none";@@ -142,7 +214,7 @@ export function opportunityCause(opportunity: PerformanceOpportunity): string {*/export function opportunitySubject(opportunity: PerformanceOpportunity): string {const symbol = opportunity.intervention_symbol?.trim();- if (symbol) return symbol.split("::").pop() ?? symbol;+ if (symbol) return moduleScopeLabel(symbol, true) ?? symbol.split("::").pop() ?? symbol;const first = opportunity.evidence[0]?.function_name;if (first) return first;return opportunity.file_path.split("/").pop() ?? opportunity.file_path;@@ -165,7 +237,7 @@ export function opportunityEvidenceLine(opportunity: PerformanceOpportunity): stconst sink = opportunity.terminal_sink?.trim();if (sink) return sink;const symbol = opportunity.intervention_symbol?.trim();- if (symbol) return symbol;+ if (symbol) return moduleScopeLabel(symbol) ?? symbol;const first = opportunity.evidence[0];if (first?.function_name) return `${opportunity.file_path}::${first.function_name}`;return opportunity.file_path;diff --git a/packages/ui/src/health/triage-view.tsx b/packages/ui/src/health/triage-view.tsxindex dfa7f64c1..1498e9da4 100644--- a/packages/ui/src/health/triage-view.tsx+++ b/packages/ui/src/health/triage-view.tsx@@ -88,6 +88,7 @@ export function TriageView({highlightPaths,hotspotsSlot,trendSlot,+ leadSlot,}: {adapter: CodeHealthAdapter;/** Trend fetched once by the host. Consumed by `trendSlot`; accepted here so@@ -118,6 +119,12 @@ export function TriageView({*/hotspotsSlot?: ReactNode;trendSlot?: ReactNode;+ /**+ * What the page leads with, above the score. When set, the score drops to+ * one secondary line with the rest behind "More": a ranked list of what to+ * fix answers "what do I do?" and the score only answers "how bad is it?".+ */+ leadSlot?: ReactNode;}) {const { cacheKey } = adapter;const { data: overview, isLoading, error, mutate } = useSWR<HealthOverviewResponse>(@@ -158,6 +165,8 @@ export function TriageView({if (isLoading) {return (<div className="flex flex-col gap-6">+ {/* The lead has its own request, so it never waits on this one. */}+ {leadSlot}{/* Shapes and widths match the real layout. A skeleton that does notcauses a reflow when content lands, which reads as slower thanshowing nothing. */}@@ -171,11 +180,14 @@ export function TriageView({if (error) {return (- <ApiError- title="Couldn't load health data"- message={`${toFriendlyMessage(error)} Index this repo if it has not been indexed yet.`}- onRetry={() => void mutate()}- />+ <div className="flex flex-col gap-6">+ {leadSlot}+ <ApiError+ title="Couldn't load health data"+ message={`${toFriendlyMessage(error)} Index this repo if it has not been indexed yet.`}+ onRetry={() => void mutate()}+ />+ </div>);}@@ -183,11 +195,13 @@ export function TriageView({return (<div className="flex flex-col gap-6 sm:gap-8">+ {leadSlot}<CodeHealthLedesummary={overview.summary}accuracy={overview.defect_accuracy ?? null}distribution={overview.distribution ?? null}pillar={overlay === "maintainability" ? "maintainability" : "health"}+ variant={leadSlot ? "secondary" : "lead"}/><OverviewSectiondiff --git a/packages/ui/src/overview/action-drawer.tsx b/packages/ui/src/overview/action-drawer.tsxindex 9d6a00bcb..a32f5c0cf 100644--- a/packages/ui/src/overview/action-drawer.tsx+++ b/packages/ui/src/overview/action-drawer.tsx@@ -12,6 +12,7 @@ import type {import { AiPromptBlock } from "../health/ai-prompt-modal";import { buildActionPrompt } from "../health/ai-prompts/action-prompt";import { biomarkerLabel } from "../health/biomarker-glossary";+import { EFFORT_LABEL } from "../health/labels";import { SeverityMark } from "../health/severity-mark";import type { Severity } from "../health/tokens";import { AdaptivePanel } from "../shared/adaptive-panel";@@ -22,12 +23,6 @@ const TIER_LABEL: Record<NextAction["tier"], string> = {improve_signal: "Improve what Repowise can see",};-const EFFORT_LABEL: Record<NextAction["effort"], string> = {- S: "Small",- M: "Medium",- L: "Large",-};-/** What the evidence link opens, named for the place it lands. */const EVIDENCE_LABEL: Record<ActionSurface, string> = {file: "Open the file",diff --git a/packages/ui/src/overview/next-actions.tsx b/packages/ui/src/overview/next-actions.tsxindex 4737aa18c..0865390e6 100644--- a/packages/ui/src/overview/next-actions.tsx+++ b/packages/ui/src/overview/next-actions.tsx@@ -11,6 +11,7 @@ import type {NextAction,} from "@repowise-dev/types/actions";+import { EFFORT_LABEL } from "../health/labels";import { SeverityMark } from "../health/severity-mark";import { CLICKABLE_ROW_CLS, clickableRowProps } from "../shared/responsive-table";import { RowOverflow } from "../shared/row-overflow";@@ -27,12 +28,6 @@ const TIER_HEADING: Record<ActionTier, string> = {improve_signal: "Improve what Repowise can see",};-const EFFORT_LABEL: Record<NextAction["effort"], string> = {- S: "Small",- M: "Medium",- L: "Large",-};-export interface NextActionsProps {/** `null` when the server predates actions; the section then renders nothing. */data: ActionsResponse | null;@@ -266,6 +261,20 @@ export function NextActions({);}+/**+ * `path:line` for an action whose title does not already name its file, so a+ * row like a Fix-first item ("Extract lines 60-122 of quick_repo_scan") says+ * where without opening it. The line is the first piece of evidence in that+ * file; titles that carry the path in backticks keep their own.+ */+export function actionLocation(action: NextAction): string | null {+ const { kind, path } = action.target;+ if ((kind !== "file" && kind !== "symbol") || !path) return null;+ if (action.title.includes(path)) return null;+ const line = action.details.find((d) => d.path === path && d.line)?.line;+ return line ? `${path}:${line}` : path;+}+function groupByTier(actions: NextAction[]): [ActionTier, NextAction[]][] {const out: [ActionTier, NextAction[]][] = [];for (const a of actions) {@@ -289,6 +298,7 @@ export function ActionRow({onAnswer?: ((state: ActionStateValue, message: string) => void) | undefined;}) {const plainTitle = action.title.replace(/`/g, "");+ const location = actionLocation(action);const items = [{ label: "Open details", icon: PanelRight, onSelect: onOpen },...(onAnswer@@ -329,6 +339,11 @@ export function ActionRow({{renderActionTitle(action.title)}</p></div>+ {location ? (+ <p className="mt-0.5 font-mono text-xs text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">+ {location}+ </p>+ ) : null}<p className="mt-1 max-w-[72ch] text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">{renderActionTitle(action.impact)}</p>diff --git a/packages/ui/src/refactoring/meta.tsx b/packages/ui/src/refactoring/meta.tsxindex 8a1f189f9..2d0a7fc58 100644--- a/packages/ui/src/refactoring/meta.tsx+++ b/packages/ui/src/refactoring/meta.tsx@@ -2,7 +2,7 @@import * as React from "react";import { ArrowRightLeft, CopyMinus, FileStack, Gauge, Scissors, Split, Unlink } from "lucide-react";-import type { Confidence, EffortBucket, RefactoringType } from "@repowise-dev/types/refactoring";+import type { Confidence, RefactoringType } from "@repowise-dev/types/refactoring";export interface RefactoringTypeMeta {label: string;@@ -77,18 +77,7 @@ export function typeAccent(type: RefactoringType | string): string {return `var(${typeMeta(type).accentVar})`;}-export const EFFORT_LABEL: Record<EffortBucket, string> = {- S: "Small",- M: "Medium",- L: "Large",- XL: "Extra large",-};--export const CONFIDENCE_LABEL: Record<Confidence, string> = {- low: "Low",- medium: "Medium",- high: "High",-};+export { CONFIDENCE_LABEL, EFFORT_LABEL } from "../health/labels";export const CONFIDENCE_DOT: Record<Confidence, string> = {high: "bg-[var(--color-success)]",diff --git a/packages/ui/src/refactoring/opportunity-drawer.tsx b/packages/ui/src/refactoring/opportunity-drawer.tsxindex cdd5caaf4..22267b1fa 100644--- a/packages/ui/src/refactoring/opportunity-drawer.tsx+++ b/packages/ui/src/refactoring/opportunity-drawer.tsx@@ -32,6 +32,10 @@ import { Skeleton, SkeletonRegion } from "../ui/skeleton";import { formatNumber } from "../lib/format";import { ValidationSummary } from "./validation-summary";import { CONFIDENCE_LABEL, EFFORT_LABEL, typeMeta } from "./meta";+import { CodeBlock } from "./plan-detail";+import { SourceExcerpt } from "./source-excerpt";+import { GenerateCodePanel } from "./generate-code-panel";+import { extractHelperDetail } from "./types";import {ORDERING_NOTE,STATUS_LABEL,@@ -41,12 +45,15 @@ import {isRelocated,} from "./opportunity";import type {+ GeneratedCode,OpportunityStatus,OpportunityStep,RefactoringOpportunityDetail,RefactoringOpportunityDetailResolved,+ RefactoringPlan,} from "@repowise-dev/types/refactoring";+/** The drill-down an agent should call. Same shape the performance drawer uses,* because it is the same agent surface. */export function opportunityHandoffCall(opportunityId: string): string {@@ -69,6 +76,13 @@ export interface OpportunityDrawerProps {/** Open one step as a single plan, in the plan inspector. */onOpenStep?: ((planId: string) => void) | undefined;fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;+ /**+ * The file's text, for a step's inline excerpt. The same read the file view+ * makes; omit it and a step shows only what its stored plan carries.+ */+ readSource?: ((path: string) => Promise<string>) | undefined;+ /** Opt-in model drafting of one step's diff. Omit when generation is off. */+ onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;}export function OpportunityDrawer({@@ -81,13 +95,15 @@ export function OpportunityDrawer({onStatusChange,onOpenStep,fileHref,+ readSource,+ onGenerateCode,}: OpportunityDrawerProps) {const resolved = detail?.found ? detail : null;return (<Sheet open={open} onOpenChange={onOpenChange}><SheetContentside="right"- closeLabel="Close opportunity"+ closeLabel="Close refactoring plan"className="w-full max-w-[680px] sm:w-[92vw]">{resolved ? (@@ -97,13 +113,15 @@ export function OpportunityDrawer({onStatusChange={onStatusChange}onOpenStep={onOpenStep}fileHref={fileHref}+ readSource={readSource}+ onGenerateCode={onGenerateCode}/>) : loading ? (<><SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">- Loading opportunity+ Loading refactoring plan</SheetTitle>- <SkeletonRegion className="space-y-4 px-5 py-5" label="Loading opportunity">+ <SkeletonRegion className="space-y-4 px-5 py-5" label="Loading refactoring plan"><Skeleton className="h-16 rounded-none" /><Skeleton className="h-40 rounded-none" /></SkeletonRegion>@@ -111,7 +129,7 @@ export function OpportunityDrawer({) : detail && !detail.found ? (<><SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">- Opportunity unavailable+ Refactoring plan unavailable</SheetTitle><div className="space-y-2 px-5 py-5 text-sm text-[var(--color-text-secondary)]"><p>@@ -131,12 +149,12 @@ export function OpportunityDrawer({) : error ? (<><SheetTitle className="border-b border-[var(--color-border-default)] px-5 py-4 pr-12 text-[15px]">- Opportunity unavailable+ Refactoring plan unavailable</SheetTitle><p className="px-5 py-5 text-sm text-[var(--color-text-secondary)]">{error}</p></>) : (- <SheetTitle className="sr-only">Refactoring opportunity</SheetTitle>+ <SheetTitle className="sr-only">Refactoring plan</SheetTitle>)}</SheetContent></Sheet>@@ -149,6 +167,8 @@ function DrawerBody({onStatusChange,onOpenStep,fileHref,+ readSource,+ onGenerateCode,}: {detail: RefactoringOpportunityDetailResolved;onAiPrompt?: ((detail: RefactoringOpportunityDetailResolved) => void) | undefined;@@ -160,8 +180,14 @@ function DrawerBody({| undefined;onOpenStep?: ((planId: string) => void) | undefined;fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;+ readSource?: ((path: string) => Promise<string>) | undefined;+ onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;}) {const meta = typeMeta(detail.lead_refactoring_type || "");+ const plansById = React.useMemo(+ () => new Map(detail.plans.map((plan) => [plan.id, plan])),+ [detail.plans],+ );const name = detail.file_path.split("/").pop() ?? detail.file_path;const others = detail.affected_files.filter((f) => f !== detail.file_path);// The opportunity resolved but its steps did not load. Everything else in the@@ -229,6 +255,10 @@ function DrawerBody({)}</div>+ <p className="border-b border-[var(--color-border-default)] px-5 py-2 text-[12px] text-[var(--color-text-secondary)]">+ {blastRadiusLine(detail)}+ </p>+<div className="flex-1 space-y-6 overflow-y-auto px-5 py-5">{/* Tri-state, stated in words. `null` is its own sentence: the layer hadno dominant finding to compare against, which is not the same claim@@ -245,7 +275,7 @@ function DrawerBody({<h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">Triage</h4>- <div role="radiogroup" aria-label="Triage this opportunity" className="flex flex-wrap gap-1.5">+ <div role="radiogroup" aria-label="Triage this refactoring plan" className="flex flex-wrap gap-1.5">{TRIAGE_STATUSES.map((option) => {const current = option.value === status;return (@@ -279,7 +309,7 @@ function DrawerBody({failed ? "mt-1 text-[11.5px] text-[var(--color-error)]" : "sr-only"}>- {failed ? "Could not save that. The opportunity is unchanged." : ""}+ {failed ? "Could not save that. The refactoring plan is unchanged." : ""}</p></section>) : null}@@ -295,8 +325,8 @@ function DrawerBody({) : null}{stepsUnavailable ? (<p className="text-[12.5px] text-[var(--color-text-secondary)]">- The {detail.step_count} step{detail.step_count === 1 ? "" : "s"} for this opportunity- could not be loaded. Try again shortly, or ask for it by id below.+ The {detail.step_count} step{detail.step_count === 1 ? "" : "s"} for this refactoring+ plan could not be loaded. Try again shortly, or ask for it by id below.</p>) : null}<ol className="space-y-3">@@ -305,8 +335,11 @@ function DrawerBody({key={step.plan_id}step={step}index={i}+ plan={plansById.get(step.plan_id)}onOpenStep={onOpenStep}fileHref={fileHref}+ readSource={readSource}+ onGenerateCode={onGenerateCode}/>))}</ol>@@ -317,11 +350,13 @@ function DrawerBody({) : null}</section>- {detail.validation_profiles.length > 0 ? (- <section>- <h4 className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">- Validation- </h4>+ {/* Always present: "nothing guards this" is the answer a person most+ needs before changing the file, so its absence is said, not hidden. */}+ <section>+ <h4 className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ Verify+ </h4>+ {detail.validation_profiles.length > 0 ? (<div className="space-y-4">{detail.validation_profiles.map((profile) => (<ValidationSummary@@ -331,8 +366,13 @@ function DrawerBody({/>))}</div>- </section>- ) : null}+ ) : (+ <p className="text-[12.5px] text-[var(--color-text-secondary)]">+ No guarding tests found. Write one that pins the current behaviour before applying+ these steps.+ </p>+ )}+ </section>{detail.evidence.length > 0 ? (<section>@@ -441,13 +481,20 @@ function DrawerBody({function StepCard({step,index,+ plan,onOpenStep,fileHref,+ readSource,+ onGenerateCode,}: {step: OpportunityStep;index: number;+ /** The step's stored plan, when the detail carried it. */+ plan?: RefactoringPlan | undefined;onOpenStep?: ((planId: string) => void) | undefined;fileHref?: ((path: string, line?: number | null) => string | undefined) | undefined;+ readSource?: ((path: string) => Promise<string>) | undefined;+ onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;}) {const meta = typeMeta(step.refactoring_type);const mechanical = step.applicability.classification === "mechanical";@@ -524,6 +571,80 @@ function StepCard({Not established: {step.applicability.unknowns.map(humanizeBiomarker).join(", ")}.</p>) : null}++ <StepCode step={step} plan={plan} readSource={readSource} onGenerateCode={onGenerateCode} /></li>);}++/**+ * The code a step changes, and a diff of the change when one is asked for.+ *+ * Closed by default: a drawer of seven open excerpts would bury the order of+ * the steps, which is the drawer's subject. The excerpt prefers the text the+ * stored plan carries (an extract-helper block); otherwise it reads the file+ * the way the file view does and cuts the step's span out of it.+ */+function StepCode({+ step,+ plan,+ readSource,+ onGenerateCode,+}: {+ step: OpportunityStep;+ plan?: RefactoringPlan | undefined;+ readSource?: ((path: string) => Promise<string>) | undefined;+ onGenerateCode?: ((plan: RefactoringPlan) => Promise<GeneratedCode>) | undefined;+}) {+ const [open, setOpen] = React.useState(false);+ const stored = plan ? extractHelperDetail(plan) : null;+ const canRead = Boolean(readSource && step.line_start);+ if (!stored?.snippet && !canRead && !plan) return null;+ return (+ <div className="mt-2">+ <button+ type="button"+ aria-expanded={open}+ onClick={() => setOpen((o) => !o)}+ className="rounded text-[12px] 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 ? "Hide the code" : "Show the code"}+ </button>+ {open ? (+ <div className="mt-2 space-y-3">+ {stored?.snippet ? (+ <CodeBlock code={stored.snippet} startLine={stored.snippetStartLine} />+ ) : canRead ? (+ <SourceExcerpt+ path={step.file_path}+ start={step.line_start!}+ end={step.line_end ?? step.line_start!}+ readSource={readSource!}+ />+ ) : null}+ {plan && onGenerateCode ? (+ <GenerateCodePanel plan={plan} onGenerate={onGenerateCode} />+ ) : plan ? (+ <p className="text-[11.5px] text-[var(--color-text-tertiary)]">+ A diff preview is drafted by a model on request. Code generation is off here.+ </p>+ ) : null}+ </div>+ ) : null}+ </div>+ );+}++/**+ * Who else the change reaches, in one line, for every type: the files the+ * steps edit, and the files that import the lead file when the store has it.+ */+export function blastRadiusLine(+ detail: Pick<RefactoringOpportunityDetailResolved, "affected_files_total" | "dependents">,+): string {+ const files = detail.affected_files_total;+ const touched = `Touches ${formatNumber(files)} file${files === 1 ? "" : "s"}`;+ if (detail.dependents == null) return `${touched}; importers not recorded.`;+ const deps = detail.dependents;+ return `${touched}; ${formatNumber(deps)} file${deps === 1 ? " imports" : "s import"} it.`;+}diff --git a/packages/ui/src/refactoring/opportunity.ts b/packages/ui/src/refactoring/opportunity.tsindex 53ff8243e..739b70ccf 100644--- a/packages/ui/src/refactoring/opportunity.ts+++ b/packages/ui/src/refactoring/opportunity.ts@@ -24,12 +24,7 @@ export const TRIAGE_STATUSES: { value: OpportunityStatus; label: string }[] = [{ value: "false_positive", label: "False positive" },];-export const STATUS_LABEL: Record<OpportunityStatus, string> = {- open: "Open",- acknowledged: "Acknowledged",- resolved: "Resolved",- false_positive: "False positive",-};+export { STATUS_LABEL } from "../health/labels";/*** Whether the file's dominant finding is what these steps address.diff --git a/packages/ui/src/refactoring/plan-detail.tsx b/packages/ui/src/refactoring/plan-detail.tsxindex fe22f6954..b331ccfba 100644--- a/packages/ui/src/refactoring/plan-detail.tsx+++ b/packages/ui/src/refactoring/plan-detail.tsx@@ -76,7 +76,7 @@ function FileRef({/** A read-only source block with a line-number gutter. Scrolls horizontally on* its own so a long line never widens the page. The gutter counts up from* `startLine` so the numbers match the file the block came from. */-function CodeBlock({ code, startLine }: { code: string; startLine: number | null }) {+export function CodeBlock({ code, startLine }: { code: string; startLine: number | null }) {const lines = code.split("\n");const base = startLine ?? 1;const gutterWidth = `${String(base + lines.length - 1).length}ch`;diff --git a/packages/ui/src/refactoring/refactoring-board.tsx b/packages/ui/src/refactoring/refactoring-board.tsxindex 99a7b8ca5..79efd8d47 100644--- a/packages/ui/src/refactoring/refactoring-board.tsx+++ b/packages/ui/src/refactoring/refactoring-board.tsx@@ -36,7 +36,7 @@ import { PaginationControls } from "../shared/pagination-controls";import { OpportunityRows } from "./opportunity-rows";import { RefactoringLede } from "./refactoring-lede";import { StartHere } from "./start-here";-import { CONFIDENCE_LABEL } from "./meta";+import { CONFIDENCE_LABEL, EFFORT_LABEL } from "./meta";import { STATUS_LABEL, TRIAGE_STATUSES } from "./opportunity";import type {Confidence,@@ -50,12 +50,6 @@ import type {const PAGE_SIZE = 60;const EFFORTS: EffortBucket[] = ["S", "M", "L", "XL"];-const EFFORT_LABEL_LONG: Record<EffortBucket, string> = {- S: "Small",- M: "Medium",- L: "Large",- XL: "Extra large",-};const CONFIDENCE_ORDER: Confidence[] = ["high", "medium", "low"];const SORT_OPTIONS: { value: RefactoringOrder; label: string }[] = [@@ -239,7 +233,7 @@ export function RefactoringBoard({}options={[{ value: "", label: "Any" },- ...EFFORTS.map((e) => ({ value: e, label: EFFORT_LABEL_LONG[e] })),+ ...EFFORTS.map((e) => ({ value: e, label: EFFORT_LABEL[e] })),]}/>{confidencesPresent.length > 1 ? (diff --git a/packages/ui/src/refactoring/source-excerpt.tsx b/packages/ui/src/refactoring/source-excerpt.tsxnew file mode 100644index 000000000..87cd17e36--- /dev/null+++ b/packages/ui/src/refactoring/source-excerpt.tsx@@ -0,0 +1,81 @@+"use client";++import * as React from "react";++import { CodeBlock } from "./plan-detail";++/** Lines of a span shown inline before the excerpt says it was cut. */+const EXCERPT_MAX_LINES = 40;++/**+ * A span of a file, read the way the file view reads it and cut to the lines+ * the analysis stored. Says so when the checkout no longer has those lines.+ */+export function SourceExcerpt({+ path,+ start,+ end,+ readSource,+ widen,+}: {+ path: string;+ start: number;+ end: number;+ readSource: (path: string) => Promise<string>;+ /**+ * Move the start up once the file is read, e.g. to the loop header above a+ * call. Returns the new first line and a note to print under the block.+ */+ widen?: ((fileLines: string[]) => { start: number; note: string | null }) | undefined;+}) {+ const [state, setState] = React.useState<+ { status: "loading" } | { status: "done"; text: string } | { status: "error" }+ >({ status: "loading" });+ React.useEffect(() => {+ let live = true;+ readSource(path).then(+ (text) => live && setState({ status: "done", text }),+ () => live && setState({ status: "error" }),+ );+ return () => {+ live = false;+ };+ }, [path, readSource]);++ if (state.status === "loading") {+ return <p className="text-[11.5px] text-[var(--color-text-tertiary)]">Reading the file.</p>;+ }+ if (state.status === "error") {+ return (+ <p className="text-[11.5px] text-[var(--color-text-tertiary)]">+ The file could not be read from the checkout.+ </p>+ );+ }+ const fileLines = state.text.split("\n");+ const widened = widen ? widen(fileLines) : null;+ const first = widened ? Math.min(widened.start, start) : start;+ const lines = fileLines.slice(first - 1, end);+ const shown = lines.slice(0, EXCERPT_MAX_LINES);+ if (shown.length === 0) {+ return (+ <p className="text-[11.5px] text-[var(--color-text-tertiary)]">+ Lines {start} to {end} are past the end of the file in the checkout; it changed since the+ analysis ran.+ </p>+ );+ }+ return (+ <div className="space-y-1">+ <CodeBlock code={shown.join("\n")} startLine={first} />+ {lines.length > shown.length ? (+ <p className="text-[11.5px] text-[var(--color-text-tertiary)]">+ First {shown.length} of {lines.length} lines shown.+ </p>+ ) : null}+ {widened?.note ? (+ <p className="text-[11.5px] text-[var(--color-text-tertiary)]">{widened.note}</p>+ ) : null}+ </div>+ );+}diff --git a/packages/web/src/app/repos/[id]/refactoring/page.tsx b/packages/web/src/app/repos/[id]/refactoring/page.tsxindex a8f6baa3f..367d6452f 100644--- a/packages/web/src/app/repos/[id]/refactoring/page.tsx+++ b/packages/web/src/app/repos/[id]/refactoring/page.tsx@@ -57,6 +57,7 @@ import {updateRefactoringOpportunityStatus,type RefactoringSettings,} from "@/lib/api/refactoring";+import { getFileContent } from "@/lib/api/files";const TYPE_VALUES = ["all", "structural", ...TYPE_ORDER] as const;type TypeFilter = (typeof TYPE_VALUES)[number];@@ -138,6 +139,8 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: striconst opportunities = useMemo(() => data?.items ?? [], [data?.items]);const prefix = `/repos/${repoId}`;const fileHref = useCallback((path: string) => fileEntityPath(prefix, path), [prefix]);+ // The read the file view makes, for a step's inline excerpt.+ const readSource = useCallback((path: string) => getFileContent(repoId, path), [repoId]);// The open opportunity comes from the URL, so a reload or a shared link lands// on the same drawer rather than the top of the list.@@ -331,6 +334,8 @@ export default function RefactoringPage({ params }: { params: Promise<{ id: strionStatusChange={onStatusChange}onOpenStep={(planId) => void setOpenPlanId(planId)}fileHref={fileHref}+ readSource={readSource}+ onGenerateCode={onGenerateCode}/><RefactoringDrawerdiff --git a/packages/web/src/components/code-health/fix-first-section.test.tsx b/packages/web/src/components/code-health/fix-first-section.test.tsxnew file mode 100644index 000000000..7c345d109--- /dev/null+++ b/packages/web/src/components/code-health/fix-first-section.test.tsx@@ -0,0 +1,105 @@+// @vitest-environment jsdom++import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { SWRConfig } from "swr";+import type { FixFirstQueue, FixItem } from "@repowise-dev/types/fix-first";++const getFixFirst = vi.fn();+const updateFindingStatus = vi.fn();+vi.mock("@/lib/api/code-health", () => ({+ getFixFirst: (...args: unknown[]) => getFixFirst(...args),+ updateFindingStatus: (...args: unknown[]) => updateFindingStatus(...args),+}));++import { FixFirstSection, fixPlanHref } from "./fix-first-section";++function item(overrides: Partial<FixItem>): FixItem {+ return {+ id: "fix1_a",+ rank: 0,+ tier: "now",+ kind: "refactor",+ improves: "defect",+ title: "Extract lines 60-122 of quick_repo_scan into compute_info",+ target: { file_path: "src/scan.py", symbol: "quick_repo_scan", line_start: 60, line_end: 133 },+ why: "quick_repo_scan: CCN 15, 44 lines.",+ facts: [],+ action: { summary: "1 step", steps: [], steps_total: 0, mechanical: true },+ gain: { kind: "health_points", value: 1.7, text: "+1.7 health on this file" },+ effort: { bucket: "S", basis: "sized by the stored plan" },+ risk: { level: "low", dependents: 4, files_touched: 1, text: "Touches 1 file." },+ confidence: { level: "high", reason: "proven mechanical" },+ verify: { tests: [], tests_total: 0, command: null, basis: "unknown" },+ context: [],+ source: { opportunity_id: "refop3_x", plan_ids: [], finding_ids: ["finding_1", "finding_2"] },+ next_call: { tool: "get_health", arguments: { opportunity_id: "refop3_x" } },+ why_ranked: [],+ ...overrides,+ };+}++function queue(items: FixItem[]): FixFirstQueue {+ return {+ items,+ lead: items[0] ?? null,+ totals: {+ candidates: 10,+ eligible: 4,+ shown: items.length,+ excluded: {+ test: 3,+ tooling: 0,+ generated: 0,+ expected: 0,+ no_plan: 0,+ below_min_worth: 3,+ history_only: 0,+ },+ },+ by_improves: { defect: 4, maintainability: 0, performance: 0 },+ model_version: 1,+ basis: { analyzed_commit: null, health_analyzed_at: null },+ };+}++function renderSection() {+ return render(+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>+ <FixFirstSection repoId="r1" />+ </SWRConfig>,+ );+}++describe("fixPlanHref", () => {+ it("opens a refactoring plan on Refactoring and a performance fix on Performance", () => {+ expect(fixPlanHref("r1", item({}))).toBe("/repos/r1/refactoring?opportunity=refop3_x");+ expect(+ fixPlanHref("r1", item({ kind: "perf_fix", source: { opportunity_id: "perf2_y", plan_ids: [], finding_ids: [] } })),+ ).toBe("/repos/r1/code-health?tab=performance&opportunity=perf2_y");+ expect(+ fixPlanHref("r1", item({ kind: "finding", source: { opportunity_id: null, plan_ids: [], finding_ids: ["f"] } })),+ ).toBeNull();+ });+});++describe("FixFirstSection", () => {+ it("asks for the production queue first, and the whole one when tests are included", async () => {+ getFixFirst.mockResolvedValue(queue([item({})]));+ renderSection();+ expect(await screen.findByText(/1 of 4 eligible items\. Excluded: 3 in tests/)).toBeTruthy();+ expect(getFixFirst).toHaveBeenCalledWith("r1", { limit: 10, scope: "production" });+ fireEvent.click(screen.getByLabelText("Include tests"));+ await waitFor(() => expect(getFixFirst).toHaveBeenCalledWith("r1", { limit: 10, scope: "all" }));+ });++ it("triages every finding behind an item through the existing per-finding write", async () => {+ getFixFirst.mockResolvedValue(queue([item({})]));+ updateFindingStatus.mockResolvedValue({});+ renderSection();+ fireEvent.click(await screen.findByRole("button", { name: "Resolved" }));+ await waitFor(() => expect(updateFindingStatus).toHaveBeenCalledTimes(2));+ expect(updateFindingStatus).toHaveBeenCalledWith("r1", "finding_1", "resolved");+ expect(updateFindingStatus).toHaveBeenCalledWith("r1", "finding_2", "resolved");+ });+});diff --git a/packages/web/src/components/code-health/fix-first-section.tsx b/packages/web/src/components/code-health/fix-first-section.tsxnew file mode 100644index 000000000..8d753e530--- /dev/null+++ b/packages/web/src/components/code-health/fix-first-section.tsx@@ -0,0 +1,71 @@+"use client";++/**+ * Fix first on the Code Health page: binds the shared {@link FixFirstList} to+ * web's `/api` client and `/repos/:id` routes. The queue arrives as core built+ * it; nothing here reorders, groups or recounts it.+ */++import { useCallback, useState } from "react";+import Link from "next/link";+import useSWR, { useSWRConfig } from "swr";+import { FixFirstList } from "@repowise-dev/ui/health";+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";+import type { FixFirstQueue, FixItem, FixScope } from "@repowise-dev/types/fix-first";+import { getFixFirst, updateFindingStatus } from "@/lib/api/code-health";++/** Items the section lists. The server caps the route at 50. */+const LIMIT = 10;++export function fixPlanHref(repoId: string, item: FixItem): string | null {+ const id = item.source.opportunity_id;+ if (!id) return null;+ const opp = encodeURIComponent(id);+ if (item.kind === "refactor") return `/repos/${repoId}/refactoring?opportunity=${opp}`;+ if (item.kind === "perf_fix") return `/repos/${repoId}/code-health?tab=performance&opportunity=${opp}`;+ return null;+}++export function FixFirstSection({ repoId, repoName }: { repoId: string; repoName?: string }) {+ const [scope, setScope] = useState<FixScope>("production");+ const key = `code-health-fix-first:${repoId}:${scope}`;+ const { data, error, isLoading, mutate } = useSWR<FixFirstQueue>(+ key,+ () => getFixFirst(repoId, { limit: LIMIT, scope }),+ { revalidateOnFocus: false, keepPreviousData: true },+ );+ const { mutate: mutateAll } = useSWRConfig();++ const onTriage = useCallback(+ async (item: FixItem, status: "acknowledged" | "resolved" | "false_positive") => {+ // A handful of ids per item; each is the existing per-finding PATCH.+ await Promise.all(+ item.source.finding_ids.map((id) => updateFindingStatus(repoId, id, status)),+ );+ // The queue and every health view that counts findings re-read.+ await mutateAll(+ (k) => typeof k === "string" && k.startsWith("code-health") && k.includes(repoId),+ undefined,+ { revalidate: true },+ );+ },+ [repoId, mutateAll],+ );++ const prefix = `/repos/${repoId}`;+ return (+ <FixFirstList+ queue={data}+ loading={isLoading}+ error={error}+ onRetry={() => void mutate()}+ scope={scope}+ onScopeChange={setScope}+ fileHref={(path) => fileEntityPath(prefix, path)}+ planHref={(item) => fixPlanHref(repoId, item)}+ onTriage={onTriage}+ LinkComponent={Link}+ {...(repoName ? { repoName } : {})}+ />+ );+}diff --git a/packages/web/src/components/code-health/performance-tab.tsx b/packages/web/src/components/code-health/performance-tab.tsxindex 794fe59ef..ed6417a82 100644--- a/packages/web/src/components/code-health/performance-tab.tsx+++ b/packages/web/src/components/code-health/performance-tab.tsx@@ -11,6 +11,7 @@ import {listHealthFindings,} from "@/lib/api/code-health";import { getRefactoringPlan } from "@/lib/api/refactoring";+import { getFileContent } from "@/lib/api/files";/** The queue's own filter state, kept out of the page's `tab` and `lens`. */const FILTER_PARAM = "perf";@@ -42,6 +43,7 @@ export function PerformanceTab({ repoId }: { repoId: string }) {`/repos/${repoId}/code-health?lens=performance&opportunity=${encodeURIComponent(opportunityId)}&file=${encodeURIComponent(filePath)}`,fileHref: (path) => fileEntityPath(prefix, path),symbolHref: (symbolId) => symbolEntityPath(prefix, symbolId),+ readSource: (path) => getFileContent(repoId, path),navigate: (href) => router.push(href),};}, [repoId, router]);diff --git a/packages/web/src/components/code-health/triage-tab.tsx b/packages/web/src/components/code-health/triage-tab.tsxindex e8798e790..d2846a969 100644--- a/packages/web/src/components/code-health/triage-tab.tsx+++ b/packages/web/src/components/code-health/triage-tab.tsx@@ -26,6 +26,7 @@ import {} from "@/lib/api/code-health";import type { HealthCounts, HealthScope } from "@repowise-dev/types/health";import { HealthFileDrawerHost } from "@/components/health/health-file-drawer-host";+import { FixFirstSection } from "@/components/code-health/fix-first-section";export function TriageTab({repoId: id,@@ -116,6 +117,7 @@ export function TriageTab({highlightPaths={highlightPaths}hotspotsSlot={hotspotsSlot}trendSlot={trendSlot}+ leadSlot={<FixFirstSection repoId={id} />}/>);}diff --git a/tests/unit/server/test_performance_opportunities.py b/tests/unit/server/test_performance_opportunities.pyindex 7775b614b..1710b85be 100644--- a/tests/unit/server/test_performance_opportunities.py+++ b/tests/unit/server/test_performance_opportunities.py@@ -383,6 +383,8 @@ async def test_detail_carries_the_facets_and_evidence_for_one_cause(assert body["evidence_emitted"] == 1assert body["evidence_next_cursor"] == 1assert body["plan_status"] == "available"+ # The same words the Fix-first item uses for this cause, from one core function.+ assert body["gain_text"].startswith("one database call per loop iteration")async def test_a_cause_that_stops_being_observed_is_resolved_not_deleted(