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(vscode): per-file change risk, symbol hover detail, and server discovery fixes (#691)
Raghav Chamadiya2180e225691f
diff --git a/README.md b/README.mdindex 67dc46d52..457660ebe 100644--- a/README.md+++ b/README.md@@ -310,13 +310,15 @@ pattern scan) · **Costs** · **Workspace**## VS Code extension-The **Repowise** extension puts the index where code gets written: inline health-diagnostics and gutter heat on the files you open, refactoring plans as CodeLens,-change risk before you push (what your change touches, who should review it, and-any missing co-changes or tests), and the same dashboards (health, architecture,+The **Repowise** extension puts the index where code gets written: know what+your change breaks before you push (your riskiest files ranked, what is+downstream, forgotten companion files, missing tests, suggested reviewers),+health signals in the gutter and status bar, callers and ownership on hover,+refactoring plans as CodeLens, and the full dashboards (health, architecture,knowledge graph, decisions, docs) inside the editor. One install also registers-the Repowise MCP server with VS Code, so the same local index serves both you and-your AI agent.+the Repowise MCP server with VS Code, so the same local index serves both you+and your AI agent. Quiet by default, everything toggleable, nothing leaves your+machine.Install from the Marketplace (search **Repowise**) or Open VSX, then run**Repowise: Set Up This Repository**. Full guide indiff --git a/docs/VSCODE.md b/docs/VSCODE.mdindex 1be789d57..bf4956163 100644--- a/docs/VSCODE.md+++ b/docs/VSCODE.md@@ -1,10 +1,10 @@# Repowise for VS Code-The Repowise extension brings the local index into your editor and registers the-Repowise MCP server with VS Code, so the same index serves both you and your AI-coding agent. It is a thin client over the local `repowise` CLI and server:-everything is computed on your machine and nothing about your code leaves it-through the extension.+The Repowise extension puts your repository's structure, history, and health+inside the editor, and registers the Repowise MCP server with VS Code so the+same index serves both you and your AI coding agent. It is a thin client over+the local `repowise` CLI and server: everything is computed on your machine and+nothing about your code leaves it through the extension.## Install@@ -15,71 +15,93 @@ through the extension.index, or follow the **Get Started with Repowise** walkthrough.The extension activates only in trusted workspaces and does no work at startup-beyond registering its commands. It discovers a running server from the lockfile-under `.repowise/`, or offers to start one when you first need data.+beyond registering its commands. It discovers a running server automatically,+or offers to start one when you first need data.++## Know before you push++**Analyze Change Risk** (Source Control title bar or command palette) scores+your uncommitted work against its base branch and opens a panel with the whole+story of the change:++- A summary strip up top: how many files are affected downstream, how many+ usual companion files you have not touched, and how many changed files have+ no associated test. Each chip jumps to its section.+- **Riskiest files in this change**: your changed files ranked by how risky+ history and structure say they are, so you review in the right order. Files+ that change unusually often are marked as hotspots.+- **Downstream of your changes**: the files that depend on what you edited.+- **Usually changes together**: companion files your history says belong to+ this change but are untouched. Advisory, not a rule.+- **Changed without a test**, and **suggested reviewers** with one-click copy+ for the PR description.++While you edit, a quiet co-change hint can appear in the status bar when the+files you are touching have a strong history of changing together with a file+you have not opened. It is dismissible per change set, never a popup, and+tunable or off in settings (`repowise.changeIntel.*`). Plenty of edits+legitimately touch only part of a cluster, so it informs without nagging.++## Editor-native signals-## What it surfaces--### Editor-native signals--- **Diagnostics** for the files you open, published to the Problems panel. Quiet- by default: only high-severity findings, capped at Warning. Lower-severity- findings live in the gutter and tree views.- **Gutter heat**: a severity-tiered strip next to lines with findings in thevisible editor.- **File health in the status bar**: defect, maintainability, and performance- scores for the active file.+ scores for the active file; click to open the health dashboard focused on it.- **File explorer badges** on the worst-health files (threshold configurable).- **Refactoring CodeLens** above symbols with a detected plan, including**Copy plan for agent** (the same payload the web Refactoring tab produces).-- **Hovers** with file health, hotspot flag, primary owner, and governing- decisions.-- **Change risk** from the SCM title bar: score your change against its base and- see what it touches. The panel shows the drivers behind the score plus, for the- files you have changed, what is downstream of them, which files your history- says usually change alongside them, any changed file with no test, and the best- reviewers (ownership x co-change), with a one-click copy for the PR.-- **A quiet co-change nudge**: when the files you are editing have a strong- history of changing together with a file you have not touched, a subtle- status-bar item offers to show you. It is advisory and dismissible per change- set, never a popup, and off or tunable from Settings- (`repowise.changeIntel.*`). Plenty of edits legitimately touch only part of a- cluster, so this informs without nagging.--### Tree views--A single Repowise activity-bar container with a **Home** overview, a **Findings**-tree (health, hotspots, ownership, dead code), and a **Refactoring** tree. All-lazy: data is fetched on first expand and refreshed only when the index moves.--### Dashboards+- **Hovers**: line 1 of a file shows its health scores, primary owner, and+ governing decisions. Hovering a symbol shows what kind of symbol it is, how+ many callers and callees it has, who owns the file, and the decisions that+ govern it. Fetched only when you hover, then cached+ (`repowise.hover.symbolDetail`).+- **Diagnostics** (off by default): opt in to publish high-severity findings to+ the Problems panel (`repowise.diagnostics.enabled`). The quieter surfaces+ above carry the full detail either way.++## Tree views++A single Repowise activity-bar container with a **Home** overview, a+**Findings** tree (health, hotspots, ownership, dead code), and a+**Refactoring** tree. All lazy: data is fetched on first expand and refreshed+only when the index moves.++## DashboardsEditor-tab webviews rendered from the same shared visualization library the web-app uses (no duplicated components): **health overview**, **C4 architecture**,+app uses (no duplicated components): **health overview**, **architecture map**,**knowledge graph** (with node search, path finder, and community detail),-**refactoring plans**, **decision timeline**, and a **docs browser**.+**refactoring plans**, **decision timeline**, and a **docs browser**. A theme+switcher in the Home view keeps them matched to your editor or pinned light or+dark.## MCP for your AI agentOne install registers the Repowise MCP server with VS Code, so agent-mode-assistants query the index through task-shaped tools instead of guessing from+assistants query the index through purpose-built tools instead of guessing fromopen files. For editors that read a config file, run **Repowise: Configure MCPfor this Workspace** to write `.vscode/mcp.json`.## Settings+The fastest way to tune everything is **Repowise: Open Settings**, a panel+covering every surface with plain-language descriptions. The full list:+| Setting | Default | Purpose ||---|---|---|| `repowise.server.autoStart` | `ask` | Start the local server automatically, ask first, or never |-| `repowise.server.port` | discover | Override the server port instead of using lockfile discovery |+| `repowise.server.port` | discover | Override the server port instead of automatic discovery || `repowise.cliPath` | PATH | Absolute path to the `repowise` executable |-| `repowise.diagnostics.enabled` | `true` | Show health findings in the Problems panel |+| `repowise.diagnostics.enabled` | `false` | Publish health findings to the Problems panel || `repowise.diagnostics.minSeverity` | `high` | Lowest severity surfaced in the Problems panel || `repowise.diagnostics.dimensions` | all | Health dimensions included in the Problems panel || `repowise.gutterHeat.enabled` | `true` | Shade the gutter next to findings || `repowise.fileDecorations.enabled` | `true` | Badge the worst-health files in the explorer |+| `repowise.fileDecorations.maxScore` | `4` | Health score at or below which a file is badged || `repowise.codeLens.enabled` | `true` | Show refactoring plan lenses |-| `repowise.hover.enabled` | `true` | Show file health context on hover |+| `repowise.hover.enabled` | `true` | Show health context on hover |+| `repowise.hover.symbolDetail` | `true` | Callers, ownership, and decisions on symbol hover || `repowise.risk.baseBranch` | default branch | Base branch change risk is scored against || `repowise.changeIntel.cochangeNudge` | `true` | Show the quiet "usually change together" status-bar hint || `repowise.changeIntel.cochangeMinScore` | `4` | Minimum historical co-change count before a related file is surfaced |diff --git a/packages/types/src/blast-radius.ts b/packages/types/src/blast-radius.tsindex b2e3d5d8a..ae6b8bae9 100644--- a/packages/types/src/blast-radius.ts+++ b/packages/types/src/blast-radius.ts@@ -8,11 +8,11 @@export interface DirectRiskEntry {path: string;- /** 0–1 normalised. UI multiplies by 10 for display. */+ /** centrality * (1 + temporal_hotspot); unbounded, compare within a change set. */risk_score: number;- /** 0–1 normalised. */+ /** 0-1 normalised. */temporal_hotspot: number;- /** 0–1 centrality fraction. */+ /** Raw graph centrality (pagerank); typically well below 1. */centrality: number;}diff --git a/packages/vscode/README.md b/packages/vscode/README.mdindex 7894dd4bf..6adf3ce58 100644--- a/packages/vscode/README.md+++ b/packages/vscode/README.md@@ -1,57 +1,91 @@# Repowise for VS Code-Repowise is the codebase intelligence layer for you and your AI coding agent. It indexes your repository once and builds five layers on top: a real dependency graph, git history signals (hotspots, ownership, hidden coupling), always-current architecture docs, mined architectural decisions, and defect-validated code health with concrete refactoring plans. Everything is computed locally and served from a local server.+**Know your codebase. Know your change. Before you push.**-This extension brings that index into VS Code, for both halves of how code gets written today:+Repowise indexes your repository once, locally, and turns its structure and history into answers: which files are risky, what your edit touches downstream, who should review it, and why the code is shaped the way it is. This extension puts those answers where you already are: the gutter, the status bar, a hover, the Source Control view.-- **For you:** discover or start the local Repowise server for the current workspace, see connection and setup state at a glance, and get guided from a fresh clone to a fully indexed repository without leaving the editor.-- **For your AI agent:** one install registers the Repowise MCP server with VS Code, so agent-mode assistants query the index through task-shaped tools and answer "why does auth work this way?" from grounded architecture, history, and health data instead of guessing from open files.+And because modern code is written by two of you, one install also wires the same intelligence into your AI agent through MCP. Your assistant answers "why does auth work this way?" from your real architecture, history, and health data instead of guessing from open files.-## What you get+Everything runs on your machine. Everything is free.-- **Inline health signals** on the files you open: a gutter heat strip for the full set of findings, file health scores in the status bar, and an optional Problems panel surface (off by default, opt in from Settings) for high-severity findings.-- **Refactoring plans as CodeLens** above the symbols they target, with one click to copy the plan as a prompt for your agent.-- **Change risk before you push**: from the SCM title bar, score your change against its base and see what it touches - the files downstream of your edits, the files your history says usually change alongside them, changed files with no test, and who is best placed to review. Suggested reviewers copy to the clipboard in one click.-- **A quiet "did you forget a file?" hint**: when the files you are editing have a strong history of changing together with a file you have not touched, a subtle status-bar item offers to show you. It is advisory and dismissible, never a popup, and tunable or off from Settings.-- **Hovers and tree views** for ownership, hotspots, dead code, and architectural decisions, all lazy and refreshed only when the index moves.-- **Dashboards inside the editor**: health overview, C4 architecture, knowledge graph, refactoring plans, decision timeline, and a docs browser, rendered from the same visualizations the web app uses.+## Know before you push++Click **Analyze Change Risk** in the Source Control view and get the full picture of your uncommitted work in seconds:++- A risk score for the change, with the exact factors that move it.+- **The riskiest files in your change**, ranked, so you know where to focus your own review first.+- **What is downstream**: the files that depend on what you touched.+- **What you might have forgotten**: files that historically change together with yours but are untouched, and changed files with no associated test.+- **Who should review it**, from ownership and history, with one-click copy for your PR.++While you edit, a quiet status-bar hint appears if you are missing a file that usually travels with your change. It never pops up, never interrupts, and is one click to dismiss or turn off.++## See health as you work++- **Gutter heat** marks the lines with findings in the file you have open. Glanceable, not shouty.+- **Status bar scores** show the active file's health across defect risk, maintainability, and performance.+- **Explorer badges** flag only the files most worth your attention.+- **Hover any symbol** for instant context: how many things call it, who owns the file, and the architectural decisions that govern it.+- **Refactoring plans appear as a CodeLens** right above the code they target. Open the full plan, or copy it as a ready-to-paste prompt for your agent.+- Prefer the Problems panel? Turn it on in settings. It stays off by default because your problems list belongs to you.++## Explore the big picture++Full dashboards open right in an editor tab, no browser needed:++- **Health overview**: where the risk concentrates, at a glance.+- **Architecture map**: zoomable views of your system, from services down to components.+- **Knowledge graph**: how everything connects, with search and path finding.+- **Refactoring plans**: ranked, with the impact of each.+- **Decision timeline**: the "why" behind your codebase, mined from its history.+- **Docs browser**: always-current documentation for the file you are in.++## One install, two brains++VS Code agent mode sees the Repowise tools automatically after install: no config, no copy-pasting JSON. For other editors and MCP clients, one command writes the config for your workspace. The signal you see in the gutter and the context your agent reasons with come from the same index, so you are never debugging two different opinions about your code.++## Quiet by design++Nothing polls, nothing scans in the background, and nothing interrupts you. Data loads when you look at it and is cached until your index changes. Activation adds zero measurable startup time. Every surface is individually toggleable, either in VS Code settings or in the built-in Repowise settings panel.<!-- Screenshots / GIFs: drop captures under media/screenshots and link them here before the stable Marketplace release. -->## Getting started1. Install the CLI: `pip install repowise` (or `uv tool install repowise`).-2. Open your repository and run **Repowise: Set Up This Repository** to build the index, or follow the Get Started walkthrough.-3. The extension finds the running server automatically, or offers to start one when you need it.-4. Run **Repowise: Configure MCP for this Workspace** to expose the tools to MCP clients through `.vscode/mcp.json`. In VS Code itself, the MCP server is registered automatically.+2. Open your repository and run **Repowise: Set Up This Repository**, or follow the Get Started walkthrough.+3. That's it. The extension finds your local server automatically, or offers to start one when you first need it.## Commands| Command | What it does ||---|---|| Repowise: Set Up This Repository | Build the index for this workspace |-| Repowise: Start Server / Stop Server | Manage the local API server |-| Repowise: Configure MCP for this Workspace | Write `.vscode/mcp.json` for MCP clients |-| Repowise: Analyze Change Risk | Score your change and show what it touches, who should review it, and any missing co-changes or tests |-| Repowise: Update Index | Sync the index with your latest commits |+| Repowise: Analyze Change Risk | Score your change and see what it touches, what is missing, and who should review || Repowise: Show Health Dashboard | Open the health overview |-| Repowise: Show Architecture Map | Open the C4 architecture view |-| Repowise: Show Knowledge Graph | Open the dependency constellation |+| Repowise: Show Architecture Map | Open the architecture view |+| Repowise: Show Knowledge Graph | Open the dependency graph || Repowise: Show Decision Timeline | Browse mined architectural decisions || Repowise: Open Docs for This File | Open the generated docs for the active file |+| Repowise: Update Index | Sync the index with your latest commits |+| Repowise: Configure MCP for this Workspace | Write `.vscode/mcp.json` for MCP clients |+| Repowise: Start Server / Stop Server | Manage the local server |+| Repowise: Open Settings | Tune every surface from one panel || Repowise: Check Setup | Diagnose install, keys, and index state || Repowise: Show Log | Open the extension log |## Settings+The quickest way to tune Repowise is **Repowise: Open Settings**, a friendly panel covering every surface. The most useful knobs:+| Setting | Default | Purpose ||---|---|---|| `repowise.server.autoStart` | `ask` | Start the local server automatically, ask first, or never |-| `repowise.server.port` | discover | Override the server port instead of using lockfile discovery |-| `repowise.cliPath` | PATH | Absolute path to the `repowise` executable || `repowise.risk.baseBranch` | default branch | Base branch change risk is scored against |-| `repowise.changeIntel.cochangeNudge` | `true` | Show the quiet "usually change together" status-bar hint |-| `repowise.changeIntel.cochangeMinScore` | `4` | Minimum historical co-change count before a related file is surfaced |+| `repowise.hover.symbolDetail` | `true` | Callers, ownership, and decisions on symbol hover |+| `repowise.changeIntel.cochangeNudge` | `true` | The quiet "usually change together" status-bar hint |+| `repowise.changeIntel.cochangeMinScore` | `4` | How strong the history has to be before a related file is suggested |+| `repowise.diagnostics.enabled` | `false` | Also publish high-severity findings to the Problems panel |## Privacydiff --git a/packages/vscode/package.json b/packages/vscode/package.jsonindex b2b42b8e8..c54dbfa22 100644--- a/packages/vscode/package.json+++ b/packages/vscode/package.json@@ -1,7 +1,7 @@{"name": "repowise","displayName": "Repowise",- "description": "Code health, architecture, and git intelligence from one local index, in your editor and in your AI agent via MCP.",+ "description": "Know what your change breaks before you push. Health signals, architecture maps, and refactoring plans in your editor, and the same intelligence for your AI agent via MCP. Local and free.","version": "0.2.0","publisher": "repowise-dev","license": "AGPL-3.0-or-later",@@ -125,6 +125,11 @@"default": true,"description": "Show file health, ownership, and decision context on hover."},+ "repowise.hover.symbolDetail": {+ "type": "boolean",+ "default": true,+ "description": "Enrich symbol hovers with caller/callee counts, ownership, and governing decisions from the index. Fetched only when you hover, then cached."+ },"repowise.risk.baseBranch": {"type": "string","default": "",diff --git a/packages/vscode/src/core/api.ts b/packages/vscode/src/core/api.tsindex 0b6137687..3c54add3a 100644--- a/packages/vscode/src/core/api.ts+++ b/packages/vscode/src/core/api.ts@@ -36,6 +36,13 @@ export interface RepowiseApi {* `head_commit` (cache tag, staleness) and `default_branch` (risk base).*/resolveRepo(repoRoot: string): Promise<RepoResponse | null>;+ /**+ * Registers the single listener fired when a request fails at the network+ * level (refused, reset) while a base URL is set. HTTP error statuses do+ * not fire it. Lets the server manager notice a server that died without+ * touching its lockfile, instead of staying "connected" forever.+ */+ onConnectionFailure(listener: () => void): void;}const DEFAULT_HEALTH_TIMEOUT_MS = 800;@@ -55,10 +62,20 @@ function canonicalPath(p: string): string {export function createApi(log: Logger): RepowiseApi {let baseUrl: string | null = null;+ let connectionFailureListener: (() => void) | null = null;++ const guardedFetch: typeof fetch = async (input, init) => {+ try {+ return await fetch(input, init);+ } catch (err) {+ if (baseUrl) connectionFailureListener?.();+ throw err;+ }+ };function apply(): void {// The API client keeps global module state; keep it in sync with baseUrl.- configureApiClient({ baseUrl: baseUrl ?? "" });+ configureApiClient({ baseUrl: baseUrl ?? "", fetch: guardedFetch });}return {@@ -102,5 +119,9 @@ export function createApi(log: Logger): RepowiseApi {return null;}},++ onConnectionFailure(listener: () => void): void {+ connectionFailureListener = listener;+ },};}diff --git a/packages/vscode/src/core/lockfile.ts b/packages/vscode/src/core/lockfile.tsindex 4d579178e..b1f528e68 100644--- a/packages/vscode/src/core/lockfile.ts+++ b/packages/vscode/src/core/lockfile.ts@@ -31,9 +31,11 @@ function isServeLock(value: unknown): value is ServeLock {/*** Reads and validates the lockfile. Returns null when the file is missing,- * unreadable, or malformed. A present-but-stale file (dead server) still parses- * here; liveness is a separate health probe against `url`, because probing a- * pid cross-platform from Node is unreliable.+ * unreadable, or malformed. A present-but-stale file (dead server) still+ * parses here; callers must gate on `isPidAlive` before trusting it, then+ * health-probe `url`. Both checks matter: the pid filters out a dead writer+ * whose port an unrelated server re-bound (it would answer /health+ * convincingly), and the probe confirms the surviving pid still serves.*/export async function readLockfile(path: string): Promise<ServeLock | null> {try {@@ -44,3 +46,17 @@ export async function readLockfile(path: string): Promise<ServeLock | null> {return null;}}++/**+ * True when a process with this pid exists (signal-0 probe, no signal sent).+ * EPERM means alive but owned by someone else; ESRCH (or anything else) means+ * gone.+ */+export function isPidAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (err) {+ return (err as NodeJS.ErrnoException).code === "EPERM";+ }+}diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.tsindex 244bd2bc2..15b0bcc05 100644--- a/packages/vscode/src/core/webviewApi.ts+++ b/packages/vscode/src/core/webviewApi.ts@@ -59,6 +59,7 @@ const SETTING_DEFAULTS: SettingsValues = {"fileDecorations.maxScore": 4,"codeLens.enabled": true,"hover.enabled": true,+ "hover.symbolDetail": true,"server.autoStart": "ask","server.port": null,"cliPath": "",@@ -84,6 +85,7 @@ const SETTING_VALIDATORS: Record<SettingKey, (v: SettingValue) => SettingValue>"fileDecorations.maxScore": (v) => expectNumberInRange(v, 0, 10),"codeLens.enabled": expectBoolean,"hover.enabled": expectBoolean,+ "hover.symbolDetail": expectBoolean,"server.autoStart": (v) => expectEnum(v, ["ask", "always", "never"]),"server.port": expectNullablePort,"cliPath": expectString,diff --git a/packages/vscode/src/core/webviews.ts b/packages/vscode/src/core/webviews.tsindex b880eded5..0cf8482e5 100644--- a/packages/vscode/src/core/webviews.ts+++ b/packages/vscode/src/core/webviews.ts@@ -60,9 +60,34 @@ export function openViewPanel<V extends PanelViewId>(params?: ViewParams[V],): void {if (ctx.getExtensionState() !== "ready" || !ctx.repoId) {- void vscode.window.showWarningMessage(- "Connect to the Repowise server to open this view.",- );+ if (ctx.getExtensionState() === "server-down") {+ void vscode.window+ .showWarningMessage(+ "The local Repowise server is not running.",+ "Start Server",+ )+ .then((choice) => {+ if (choice === "Start Server") {+ void vscode.commands.executeCommand(Commands.startServer);+ }+ });+ } else if (ctx.getExtensionState() === "ready" && !ctx.repoId) {+ // Connected, but the server has no record of this folder.+ void vscode.window+ .showWarningMessage(+ "The connected Repowise server has no index for this folder.",+ "Check Setup",+ )+ .then((choice) => {+ if (choice === "Check Setup") {+ void vscode.commands.executeCommand(Commands.checkSetup);+ }+ });+ } else {+ void vscode.window.showWarningMessage(+ "Connect to the Repowise server to open this view.",+ );+ }return;}if (!manager) {diff --git a/packages/vscode/src/features/hovers.ts b/packages/vscode/src/features/hovers.tsindex 8c9c10f35..1e0bf4a0f 100644--- a/packages/vscode/src/features/hovers.ts+++ b/packages/vscode/src/features/hovers.ts@@ -2,7 +2,7 @@ import * as vscode from "vscode";import { CONFIG_SECTION, Commands } from "../constants";import { getHealthFileBreakdown } from "@repowise-dev/api-client/code-health";import { listDecisions } from "@repowise-dev/api-client/decisions";-import { listSymbols } from "@repowise-dev/api-client/symbols";+import { getSymbolDetail, listSymbols } from "@repowise-dev/api-client/symbols";import type { RepowiseContext } from "../core/context";import { getFileFindings, repoRelativePath } from "../core/fileSignals";import type {@@ -11,10 +11,14 @@ import type {} from "@repowise-dev/types/health";import type { DecisionRecordResponse } from "@repowise-dev/api-client/types";import type { SymbolResponse } from "@repowise-dev/api-client/types";+import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";/** Max governing decisions surfaced on a file hover. */const MAX_DECISIONS = 3;+/** Max governing decisions surfaced on a symbol hover. */+const MAX_SYMBOL_DECISIONS = 2;+/** Renders a score, or a dash when the dimension is absent from the payload. */function fmt(value: number | null | undefined): string {return value == null ? "-" : value.toFixed(1);@@ -31,8 +35,10 @@ function covers(finding: HealthFinding, line: number): boolean {/*** Provides health context on hover. Hovering line 0 of a file with health data* shows the three scores, its primary owner, and the decisions that govern it;- * hovering a symbol body shows the symbol name and a link to a matching finding.- * Every other position returns nothing, so hovering stays cheap.+ * hovering a symbol body shows the symbol name, optionally a compact detail+ * card (kind, caller/callee counts, owner, governing decisions), and a link to+ * a matching finding. Every other position returns nothing, so hovering stays+ * cheap.*/export function registerHovers(ctx: RepowiseContext): vscode.Disposable {const enabled = (): boolean =>@@ -40,6 +46,11 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {.getConfiguration(CONFIG_SECTION).get<boolean>("hover.enabled", true);+ const symbolDetailEnabled = (): boolean =>+ vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<boolean>("hover.symbolDetail", true);+/** Reads through the shared cache under the current head commit. */async function cached<T>(key: string,@@ -112,6 +123,7 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {async function symbolHover(relPath: string,position: vscode.Position,+ token: vscode.CancellationToken,): Promise<vscode.Hover | undefined> {const repoId = ctx.repoId;if (!repoId) return undefined;@@ -121,6 +133,7 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {() => listSymbols({ repo_id: repoId, file_path: relPath, limit: 1000 }),[],);+ if (token.isCancellationRequested) return undefined;const line1 = position.line + 1;// Innermost symbol covering the line: smallest span among those that match.let match: SymbolResponse | undefined;@@ -132,12 +145,57 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {}}if (!match) return undefined;+ const symbol = match;++ // One lazy detail fetch per hover, cached per symbol under the head+ // commit. Failures cache as null so a dead symbol id is asked once per+ // index version, and the hover degrades to the minimal name-only card.+ const detailPromise: Promise<SymbolDetailResponse | null> =+ symbolDetailEnabled()+ ? cached<SymbolDetailResponse | null>(+ `symbolDetail:${symbol.symbol_id}`,+ async () => {+ try {+ return await getSymbolDetail(repoId, symbol.symbol_id);+ } catch (err) {+ ctx.log.debug(`symbol detail ${symbol.symbol_id}: ${String(err)}`);+ return null;+ }+ },+ null,+ )+ : Promise.resolve(null);+ const [detail, findings] = await Promise.all([+ detailPromise,+ getFileFindings(ctx, relPath),+ ]);+ if (token.isCancellationRequested) return undefined;const md = new vscode.MarkdownString();- md.isTrusted = true;- md.appendMarkdown(`**${match.name}**\n\n`);+ // Trusted only for our own command link below; index-derived strings+ // (titles, owners) must not be able to smuggle arbitrary command URIs.+ md.isTrusted = { enabledCommands: [Commands.showFileHealth] };+ if (detail) {+ md.appendMarkdown(`**${match.name}** · ${detail.symbol.kind}\n\n`);+ const callers = detail.graph.in_degree;+ const callees = detail.graph.out_degree;+ md.appendMarkdown(`${callers} callers · ${callees} callees\n\n`);+ const owner = detail.file_context?.primary_owner;+ if (owner) {+ md.appendMarkdown(`Owner: ${owner}\n\n`);+ }+ const governing = detail.governing_decisions.slice(0, MAX_SYMBOL_DECISIONS);+ if (governing.length > 0) {+ md.appendMarkdown("Decisions:\n\n");+ for (const decision of governing) {+ md.appendMarkdown(`- ${decision.title}\n`);+ }+ md.appendMarkdown("\n");+ }+ } else {+ md.appendMarkdown(`**${match.name}**\n\n`);+ }- const findings = await getFileFindings(ctx, relPath);const finding = findings.find((f) => covers(f, position.line));if (finding) {md.appendMarkdown(@@ -150,7 +208,7 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {const provider = vscode.languages.registerHoverProvider({ scheme: "file" },{- provideHover: async (document, position) => {+ provideHover: async (document, position, token) => {if (!enabled() || ctx.getExtensionState() !== "ready" || !ctx.repoId) {return undefined;}@@ -158,7 +216,7 @@ export function registerHovers(ctx: RepowiseContext): vscode.Disposable {if (!rel) return undefined;return position.line === 0? fileHover(rel)- : symbolHover(rel, position);+ : symbolHover(rel, position, token);},},);diff --git a/packages/vscode/src/features/serverManager.ts b/packages/vscode/src/features/serverManager.tsindex c5cd3b85f..49fd21f0d 100644--- a/packages/vscode/src/features/serverManager.ts+++ b/packages/vscode/src/features/serverManager.ts@@ -2,7 +2,7 @@ import * as vscode from "vscode";import { spawn, type ChildProcess } from "node:child_process";import { Commands, MIN_SERVER_VERSION } from "../constants";import type { RepowiseContext } from "../core/context";-import { readLockfile } from "../core/lockfile";+import { isPidAlive, readLockfile } from "../core/lockfile";import type { HealthResult } from "../core/api";/**@@ -155,13 +155,17 @@ export function registerServerManager(ctx: RepowiseContext): vscode.Disposable {ensureWatcher();+ // The pid gate is not redundant with the probe: a dead writer's port can+ // be re-bound by an unrelated server that answers /health convincingly.const lock = await readLockfile(ws.lockfilePath);- if (lock) {+ if (lock && isPidAlive(lock.pid)) {const health = await ctx.api.checkHealth(lock.url);if (health) {await onConnected(ws.repoRoot, lock.url, health);return;}+ } else if (lock) {+ ctx.log.debug(`Ignoring stale lockfile (pid ${lock.pid} is gone).`);}// No lockfile, or a present-but-stale one whose server no longer answers.@@ -188,8 +192,10 @@ export function registerServerManager(ctx: RepowiseContext): vscode.Disposable {let delay = POLL_START_MS;while (Date.now() < deadline) {if (disposed || aborted()) return null;+ // Pid-gated so the poll cannot adopt a stale lockfile (and whatever+ // re-bound its port) in the window before our child overwrites it.const lock = await readLockfile(lockfilePath);- if (lock) {+ if (lock && isPidAlive(lock.pid)) {const health = await ctx.api.checkHealth(lock.url);if (health) return { url: lock.url, health };}@@ -238,9 +244,10 @@ export function registerServerManager(ctx: RepowiseContext): vscode.Disposable {}// A healthy server may already be up (started outside the editor, or by a- // prior session). Adopt it instead of spawning a second one.+ // prior session). Adopt it instead of spawning a second one. Pid-gated:+ // never adopt through a dead writer's lockfile.const existing = await readLockfile(ws.lockfilePath);- if (existing) {+ if (existing && isPidAlive(existing.pid)) {const health = await ctx.api.checkHealth(existing.url);if (health) {await onConnected(ws.repoRoot, existing.url, health);@@ -406,6 +413,35 @@ export function registerServerManager(ctx: RepowiseContext): vscode.Disposable {ctx.log.info("Stopped the local Repowise server.");}+ /** In-flight guard and cooldown for connection-failure rechecks. */+ let rechecking = false;+ let lastRecheckAt = 0;++ /**+ * A data request failed at the network level while we believed we were+ * connected. Re-probe once (cooldown-limited): a healthy probe means a+ * transient blip; a dead one re-runs discovery, which settles into+ * server-down and restores the Start Server affordances.+ */+ async function recheckConnection(): Promise<void> {+ if (disposed || rechecking || !isConnected()) return;+ const now = Date.now();+ if (now - lastRecheckAt < 5_000) return;+ rechecking = true;+ lastRecheckAt = now;+ try {+ const url = ctx.api.getBaseUrl();+ if (!url) return;+ const health = await ctx.api.checkHealth(url);+ if (health || disposed) return;+ ctx.log.info("Server stopped answering; re-running discovery.");+ await discover({ rescan: false });+ } finally {+ rechecking = false;+ }+ }+ ctx.api.onConnectionFailure(() => void recheckConnection());+const disposables: vscode.Disposable[] = [vscode.commands.registerCommand(Commands.startServer, () =>// An explicit invocation is its own consent, so never silent.diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.tsindex 3c3804b2e..3008329ca 100644--- a/packages/vscode/src/shared/webviewMessages.ts+++ b/packages/vscode/src/shared/webviewMessages.ts@@ -81,6 +81,7 @@ export const SETTING_KEYS = ["fileDecorations.maxScore","codeLens.enabled","hover.enabled",+ "hover.symbolDetail","server.autoStart","server.port","cliPath",diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex 3e8c2d854..cb90a98fa 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -47,7 +47,10 @@ const IMPACT: ChangeImpactReport = {workingCount: 1,scope: "branch",blast: {- direct_risks: [],+ direct_risks: [+ { path: "src/a.ts", risk_score: 0.3, temporal_hotspot: 0.1, centrality: 0.8 },+ { path: "src/b.ts", risk_score: 0.82, temporal_hotspot: 0.9, centrality: 0.1 },+ ],transitive_affected: [{ path: "src/consumer.ts", depth: 1 }],cochange_warnings: [{ changed: "src/a.ts", missing_partner: "src/a.test.ts", score: 8 },@@ -78,7 +81,11 @@ function makeHost(overrides: Partial<WebviewHost> = {},): WebviewHost {return {- api: { riskRange, changeImpact } as WebviewHost["api"],+ api: {+ riskRange,+ changeImpact,+ getSettings: vi.fn().mockResolvedValue({ "changeIntel.cochangeMinScore": 4 }),+ } as unknown as WebviewHost["api"],onInit: () => () => {},onRefresh: () => () => {},onUpdateDone: () => () => {},@@ -161,6 +168,58 @@ describe("risk App", () => {);});+ it("ranks the riskiest files with markers and opens a file on click", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ const changeImpact = vi.fn().mockResolvedValue(IMPACT);+ const openFile = vi.fn();+ render(+ <App+ host={makeHost(riskRange, changeImpact, { openFile })}+ repo={REPO}+ params={{}}+ refreshToken={0}+ />,+ );++ expect(await screen.findByText("Riskiest files in this change")).toBeTruthy();+ expect(screen.getByText("hotspot")).toBeTruthy();+ const bars = screen.getAllByTitle("Risk relative to the riskiest file in this change");+ expect(bars).toHaveLength(2);+ // Sorted riskiest first: b.ts (0.82) gets the full bar, a.ts a partial one.+ expect((bars[0]!.firstElementChild as HTMLElement).style.width).toBe("100%");++ // b.ts also appears in the test-gap card; the riskiest row renders first.+ fireEvent.click(screen.getAllByTitle("Open src/b.ts")[0]!);+ expect(openFile).toHaveBeenCalledWith("src/b.ts");+ });++ it("renders verdict chips that scroll to their sections", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ const changeImpact = vi.fn().mockResolvedValue(IMPACT);+ const scrollIntoView = vi.fn();+ Element.prototype.scrollIntoView = scrollIntoView;+ render(+ <App host={makeHost(riskRange, changeImpact)} repo={REPO} params={{}} refreshToken={0} />,+ );++ expect(await screen.findByText("may affect 1 downstream file")).toBeTruthy();+ expect(screen.getByText("1 co-change partner untouched")).toBeTruthy();+ expect(screen.getByText("1 changed file has no associated test")).toBeTruthy();++ fireEvent.click(screen.getByText("may affect 1 downstream file"));+ expect(scrollIntoView).toHaveBeenCalled();+ });++ it("renders no verdict chips on a clean tree", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);++ await screen.findByText("7.4");+ expect(screen.queryByText(/downstream file/)).toBeNull();+ expect(screen.queryByText(/untouched/)).toBeNull();+ expect(screen.queryByText(/associated test/)).toBeNull();+ });+it("shows a clean-tree empty state when nothing changed", async () => {const riskRange = vi.fn().mockResolvedValue(REPORT);render(<App host={makeHost(riskRange)} repo={REPO} params={{}} refreshToken={0} />);diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsxindex b0e1b6355..c19fcfdb8 100644--- a/packages/vscode/webview/src/views/risk/App.tsx+++ b/packages/vscode/webview/src/views/risk/App.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useState } from "react";import {Copy,+ Gauge,GitCompare,GitPullRequest,Network,@@ -17,6 +18,8 @@ import type {ChangeImpactReport,RiskRangeReport,} from "../../../../src/shared/webviewMessages";+import { selectMissingCochanges } from "../../../../src/shared/changeImpact";+import { selectDirectRisks, type RankedDirectRisk } from "./selectors";/** Human labels for the raw change features the endpoint returns, in report order. */const FEATURE_LABELS: ReadonlyArray<readonly [string, string]> = [@@ -44,6 +47,22 @@ const TONE_VAR: Record<Tone, string> = {high: "var(--color-risk-high)",};+/** Fallback co-change floor when settings cannot be read; mirrors the+ * changeIntel.cochangeMinScore default. */+const COCHANGE_MIN_SCORE = 4;++/** Anchors the verdict chips scroll to; each id sits on its impact card. */+const SECTION_IDS = {+ directRisks: "impact-direct-risks",+ downstream: "impact-downstream",+ cochanges: "impact-cochanges",+ testGaps: "impact-test-gaps",+} as const;++function scrollToSection(id: string) {+ document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });+}+/** Formats a contribution with an explicit sign (positive raises risk). */function signed(value: number): string {return `${value >= 0 ? "+" : "−"}${Math.abs(value).toFixed(2)}`;@@ -59,11 +78,20 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {const [error, setError] = useState<string | null>(null);const [loading, setLoading] = useState(true);const [impactLoading, setImpactLoading] = useState(true);+ const [cochangeFloor, setCochangeFloor] = useState(COCHANGE_MIN_SCORE);const load = useCallback(() => {setLoading(true);setImpactLoading(true);setError(null);+ // Keep the panel's co-change floor in step with the nudge's setting.+ host.api+ .getSettings()+ .then((s) => {+ const floor = s["changeIntel.cochangeMinScore"];+ if (typeof floor === "number") setCochangeFloor(floor);+ })+ .catch(() => undefined);host.api.riskRange().then((r) => setReport(r))@@ -120,7 +148,13 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {) : report ? (<><ScoreHero report={report} />- <ChangeImpact impact={impact} loading={impactLoading} host={host} />+ <VerdictStrip impact={impact} cochangeFloor={cochangeFloor} />+ <ChangeImpact+ impact={impact}+ loading={impactLoading}+ host={host}+ cochangeFloor={cochangeFloor}+ /><RiskBreakdown report={report} /></>) : null}@@ -224,6 +258,62 @@ function ScoreHero({ report }: { report: RiskRangeReport }) {);}+/** Quiet one-line summary of the blast data. Each chip anchors its section;+ * zero counts render no chip, and a clean tree renders nothing at all. */+function VerdictStrip({+ impact,+ cochangeFloor,+}: {+ impact: ChangeImpactReport | null;+ cochangeFloor: number;+}) {+ const blast = impact?.blast;+ if (!impact || !blast || impact.gitUnavailable) return null;++ const downstream = blast.transitive_affected.length;+ const cochanges = selectMissingCochanges(impact, cochangeFloor).length;+ const gaps = blast.test_gaps.length;++ const chips: Array<{ id: string; label: string }> = [];+ if (downstream > 0) {+ chips.push({+ id: SECTION_IDS.downstream,+ label: `may affect ${downstream} downstream file${downstream === 1 ? "" : "s"}`,+ });+ }+ if (cochanges > 0) {+ chips.push({+ id: SECTION_IDS.cochanges,+ label: `${cochanges} co-change partner${cochanges === 1 ? "" : "s"} untouched`,+ });+ }+ if (gaps > 0) {+ chips.push({+ id: SECTION_IDS.testGaps,+ label:+ gaps === 1+ ? "1 changed file has no associated test"+ : `${gaps} changed files have no associated test`,+ });+ }+ if (chips.length === 0) return null;++ return (+ <div className="flex flex-wrap gap-2">+ {chips.map((c) => (+ <button+ key={c.id}+ type="button"+ onClick={() => scrollToSection(c.id)}+ className="inline-flex items-center rounded-full border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] transition-colors hover:bg-[var(--color-bg-surface)]"+ >+ {c.label}+ </button>+ ))}+ </div>+ );+}+/** The statistical breakdown: what moves the score, and the raw change shape. */function RiskBreakdown({ report }: { report: RiskRangeReport }) {const r = report.result;@@ -301,53 +391,39 @@ function RiskBreakdown({ report }: { report: RiskRangeReport }) {// Change impact (blast radius + reviewers for the working change set)// ----------------------------------------------------------------------------/** One missing co-change partner, grouped from the per-pair warnings. */-interface GroupedCochange {- partner: string;- score: number;- withChanged: string;-}--function groupCochanges(- warnings: ReadonlyArray<{ changed: string; missing_partner: string; score: number }>,-): GroupedCochange[] {- const map = new Map<string, GroupedCochange>();- for (const w of warnings) {- const e = map.get(w.missing_partner);- if (e) {- if (w.score > e.score) {- e.score = w.score;- e.withChanged = w.changed;- }- } else {- map.set(w.missing_partner, {- partner: w.missing_partner,- score: w.score,- withChanged: w.changed,- });- }- }- return [...map.values()].sort((a, b) => b.score - a.score);-}-function ChangeImpact({impact,loading,host,+ cochangeFloor,}: {impact: ChangeImpactReport | null;loading: boolean;host: WebviewHost;+ cochangeFloor: number;}) {if (loading && !impact) {return (- <Card>- <CardContent className="space-y-3 py-5" aria-hidden>- <div className="h-4 w-40 animate-pulse rounded bg-[var(--color-bg-inset)]" />- <div className="h-3 w-full animate-pulse rounded bg-[var(--color-bg-inset)]" />- <div className="h-3 w-2/3 animate-pulse rounded bg-[var(--color-bg-inset)]" />- </CardContent>- </Card>+ <>+ <Card>+ <CardContent className="space-y-3 py-5" aria-hidden>+ <div className="h-4 w-40 animate-pulse rounded bg-[var(--color-bg-inset)]" />+ {Array.from({ length: 3 }).map((_, i) => (+ <div key={i} className="flex items-center gap-2">+ <div className="h-3 flex-1 animate-pulse rounded bg-[var(--color-bg-inset)]" />+ <div className="h-1.5 w-16 shrink-0 animate-pulse rounded-full bg-[var(--color-bg-inset)]" />+ </div>+ ))}+ </CardContent>+ </Card>+ <Card>+ <CardContent className="space-y-3 py-5" aria-hidden>+ <div className="h-4 w-40 animate-pulse rounded bg-[var(--color-bg-inset)]" />+ <div className="h-3 w-full animate-pulse rounded bg-[var(--color-bg-inset)]" />+ <div className="h-3 w-2/3 animate-pulse rounded bg-[var(--color-bg-inset)]" />+ </CardContent>+ </Card>+ </>);}if (!impact) return null;@@ -374,8 +450,9 @@ function ChangeImpact({}const blast = impact.blast;+ const directRisks = selectDirectRisks(impact);const downstream = blast?.transitive_affected ?? [];- const cochanges = groupCochanges(blast?.cochange_warnings ?? []);+ const cochanges = selectMissingCochanges(impact, cochangeFloor);const testGaps = blast?.test_gaps ?? [];const reviewers = impact.reviewers;const overall = blast?.overall_risk_score ?? null;@@ -402,8 +479,23 @@ function ChangeImpact({</span></div>+ {directRisks.length > 0 && (+ <ImpactCard+ id={SECTION_IDS.directRisks}+ icon={<Gauge className="h-4 w-4" />}+ title="Riskiest files in this change"+ hint="Per-file risk from history and structure. Start your review here."+ >+ {directRisks.slice(0, 10).map((f) => (+ <DirectRiskRow key={f.path} risk={f} onOpen={() => host.openFile(f.path)} />+ ))}+ <MoreRow count={directRisks.length - 10} />+ </ImpactCard>+ )}+{downstream.length > 0 && (<ImpactCard+ id={SECTION_IDS.downstream}icon={<Network className="h-4 w-4" />}title="Downstream of your changes"hint="These files depend on what you changed. Verify they still work."@@ -422,6 +514,7 @@ function ChangeImpact({{cochanges.length > 0 && (<ImpactCard+ id={SECTION_IDS.cochanges}icon={<GitPullRequest className="h-4 w-4" />}title="Usually changes together"hint="History suggests these often change with your edits. Advisory, not a rule."@@ -440,6 +533,7 @@ function ChangeImpact({{testGaps.length > 0 && (<ImpactCard+ id={SECTION_IDS.testGaps}icon={<TestTube className="h-4 w-4" />}title="Changed without a test"hint="These changed files have no associated test file."@@ -457,18 +551,21 @@ function ChangeImpact({}function ImpactCard({+ id,icon,title,hint,children,}: {+ /** Anchor for the verdict chips; omitted for cards without a chip. */+ id?: string;icon: React.ReactNode;title: string;hint: string;children: React.ReactNode;}) {return (- <Card>+ <Card id={id}><CardHeader className="pb-2"><CardTitle className="flex items-center gap-2 text-sm"><span className="text-[var(--color-text-tertiary)]">{icon}</span>@@ -512,6 +609,47 @@ function PathRow({);}+/** A clickable file row with a quiet relative risk bar and a hotspot marker. */+function DirectRiskRow({ risk, onOpen }: { risk: RankedDirectRisk; onOpen: () => void }) {+ const name = risk.path.split("/").pop() || risk.path;+ const dir = risk.path.slice(0, risk.path.length - name.length);+ const pct = Math.min(100, Math.max(0, risk.share * 100));+ return (+ <button+ type="button"+ onClick={onOpen}+ title={`Open ${risk.path}`}+ className="flex w-full items-center gap-2 rounded px-1.5 py-1 text-left text-sm transition-colors hover:bg-[var(--color-bg-surface)]"+ >+ <span className="min-w-0 flex-1 truncate">+ {dir && <span className="text-[var(--color-text-tertiary)]">{dir}</span>}+ <span className="text-[var(--color-text-primary)]">{name}</span>+ </span>+ {risk.hotspot && (+ <span+ className="shrink-0 text-xs text-[var(--color-text-tertiary)]"+ title="Changes often in recent history"+ >+ hotspot+ </span>+ )}+ <span+ className="h-1.5 w-16 shrink-0 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]"+ title="Risk relative to the riskiest file in this change"+ >+ <span+ className="block h-full rounded-full"+ style={{+ width: `${pct}%`,+ backgroundColor:+ "color-mix(in srgb, var(--color-text-secondary) 45%, transparent)",+ }}+ />+ </span>+ </button>+ );+}+function MoreRow({ count }: { count: number }) {if (count <= 0) return null;return (diff --git a/packages/vscode/webview/src/views/risk/selectors.test.ts b/packages/vscode/webview/src/views/risk/selectors.test.tsnew file mode 100644index 000000000..46c97454c--- /dev/null+++ b/packages/vscode/webview/src/views/risk/selectors.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from "vitest";+import { selectDirectRisks } from "./selectors";+import type { ChangeImpactReport } from "../../../../src/shared/webviewMessages";+import type { DirectRiskEntry } from "@repowise-dev/types/blast-radius";++function report(direct_risks: DirectRiskEntry[] = [], blast = true): ChangeImpactReport {+ return {+ changed: direct_risks.map((d) => d.path),+ stagedCount: 0,+ workingCount: 0,+ scope: "branch",+ reviewers: [],+ gitUnavailable: false,+ blast: blast+ ? {+ direct_risks,+ transitive_affected: [],+ cochange_warnings: [],+ recommended_reviewers: [],+ test_gaps: [],+ overall_risk_score: 0,+ }+ : null,+ };+}++describe("selectDirectRisks", () => {+ it("ranks riskiest first with shares relative to the set maximum", () => {+ const out = selectDirectRisks(+ report([+ { path: "a.ts", risk_score: 0.005, temporal_hotspot: 0, centrality: 0.005 },+ { path: "b.ts", risk_score: 0.02, temporal_hotspot: 0, centrality: 0.02 },+ ]),+ );+ expect(out.map((r) => r.path)).toEqual(["b.ts", "a.ts"]);+ expect(out[0]?.share).toBe(1);+ expect(out[1]?.share).toBeCloseTo(0.25);+ });++ it("flags hotspots only above the floor", () => {+ const out = selectDirectRisks(+ report([+ { path: "hot.ts", risk_score: 0.01, temporal_hotspot: 0.9, centrality: 0.005 },+ { path: "quiet.ts", risk_score: 0.01, temporal_hotspot: 0.2, centrality: 0.005 },+ ]),+ );+ expect(out.find((r) => r.path === "hot.ts")?.hotspot).toBe(true);+ expect(out.find((r) => r.path === "quiet.ts")?.hotspot).toBe(false);+ });++ it("serves zero shares when every risk score is zero", () => {+ const out = selectDirectRisks(+ report([{ path: "a.ts", risk_score: 0, temporal_hotspot: 0, centrality: 0 }]),+ );+ expect(out[0]?.share).toBe(0);+ });++ it("returns nothing when there is no blast payload", () => {+ expect(selectDirectRisks(report([], false))).toEqual([]);+ });+});diff --git a/packages/vscode/webview/src/views/risk/selectors.ts b/packages/vscode/webview/src/views/risk/selectors.tsnew file mode 100644index 000000000..e3c1842bf--- /dev/null+++ b/packages/vscode/webview/src/views/risk/selectors.ts@@ -0,0 +1,36 @@+/**+ * Pure selectors over the change-impact payload for the risk panel. Kept free+ * of React and the host runtime so they unit-test like src/shared/changeImpact.+ */++import type { ChangeImpactReport } from "../../../../src/shared/webviewMessages";++/**+ * Temporal-hotspot fraction above which a file earns the quiet hotspot marker.+ * The per-file risk score itself is centrality-weighted and unbounded, so rows+ * carry a share relative to the riskiest file instead of an absolute scale.+ */+export const HOTSPOT_FLOOR = 0.6;++/** One changed file ranked by its blast-radius risk. */+export interface RankedDirectRisk {+ /** Repo-relative path of the changed file. */+ path: string;+ /** Risk relative to the riskiest file in this change, 0 to 1. */+ share: number;+ /** True when git history marks the file as a temporal hotspot. */+ hotspot: boolean;+}++/** Ranks the blast response's per-file risks for display, riskiest first. */+export function selectDirectRisks(report: ChangeImpactReport): RankedDirectRisk[] {+ const risks = report.blast?.direct_risks ?? [];+ const max = risks.reduce((m, d) => Math.max(m, d.risk_score), 0);+ return risks+ .map((d) => ({+ path: d.path,+ share: max > 0 ? d.risk_score / max : 0,+ hotspot: d.temporal_hotspot >= HOTSPOT_FLOOR,+ }))+ .sort((a, b) => b.share - a.share);+}diff --git a/packages/vscode/webview/src/views/settings/App.test.tsx b/packages/vscode/webview/src/views/settings/App.test.tsxindex 0d57ffd9d..930d17c91 100644--- a/packages/vscode/webview/src/views/settings/App.test.tsx+++ b/packages/vscode/webview/src/views/settings/App.test.tsx@@ -18,6 +18,7 @@ const DEFAULTS: SettingsValues = {"fileDecorations.maxScore": 4,"codeLens.enabled": true,"hover.enabled": true,+ "hover.symbolDetail": true,"server.autoStart": "ask","server.port": null,"cliPath": "",@@ -94,4 +95,16 @@ describe("settings App", () => {const severity = (await screen.findByLabelText("Minimum severity")) as HTMLSelectElement;expect(severity.disabled).toBe(true);});++ it("renders the change intelligence group and gates symbol details under hover cards", async () => {+ const { host } = makeHost({ "hover.enabled": false });+ renderApp(host);++ expect(await screen.findByText("Change intelligence")).toBeTruthy();+ expect(screen.getByLabelText("Co-change nudge")).toBeTruthy();+ expect(screen.getByLabelText("Minimum co-change count")).toBeTruthy();++ const symbolDetail = screen.getByLabelText("Symbol details on hover") as HTMLButtonElement;+ expect(symbolDetail.disabled).toBe(true);+ });});diff --git a/packages/vscode/webview/src/views/settings/App.tsx b/packages/vscode/webview/src/views/settings/App.tsxindex f8769bd6d..a45952821 100644--- a/packages/vscode/webview/src/views/settings/App.tsx+++ b/packages/vscode/webview/src/views/settings/App.tsx@@ -111,6 +111,38 @@ const GROUPS: Group[] = [description: "Show file health, ownership, and decision context on hover.",kind: "toggle",},+ {+ key: "hover.symbolDetail",+ label: "Symbol details on hover",+ description:+ "Enrich symbol hovers with caller/callee counts, ownership, and governing decisions. Fetched only when you hover, then cached.",+ kind: "toggle",+ needs: "hover.enabled",+ },+ ],+ },+ {+ title: "Change intelligence",+ blurb: "Quiet hints drawn from how this repository's files change together.",+ rows: [+ {+ key: "changeIntel.cochangeNudge",+ label: "Co-change nudge",+ description:+ "Show a quiet status-bar hint when files you are editing usually change together with a file you have not touched. Advisory and dismissible; never interrupts.",+ kind: "toggle",+ },+ {+ key: "changeIntel.cochangeMinScore",+ label: "Minimum co-change count",+ description:+ "Minimum historical co-change count before a related file is surfaced by the nudge. Higher values mean fewer, stronger hints.",+ kind: "number",+ needs: "changeIntel.cochangeNudge",+ min: 0,+ max: 100,+ step: 1,+ },],},{