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): change intelligence in the SCM view (#664)
Raghav Chamadiya3f8679529eab
diff --git a/README.md b/README.mdindex 94c253007..9e6fd4321 100644--- a/README.md+++ b/README.md@@ -312,7 +312,8 @@ pattern scan) · **Costs** · **Workspace**The **Repowise** extension puts the index where code gets written: inline healthdiagnostics and gutter heat on the files you open, refactoring plans as CodeLens,-branch risk before you push, and the same dashboards (health, architecture,+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,knowledge graph, decisions, docs) inside the editor. One install also registersthe Repowise MCP server with VS Code, so the same local index serves both you andyour AI agent.diff --git a/docs/VSCODE.md b/docs/VSCODE.mdindex 9bb0b7c21..1be789d57 100644--- a/docs/VSCODE.md+++ b/docs/VSCODE.md@@ -34,8 +34,17 @@ under `.repowise/`, or offers to start one when you first need data.**Copy plan for agent** (the same payload the web Refactoring tab produces).- **Hovers** with file health, hotspot flag, primary owner, and governingdecisions.-- **Branch risk** from the SCM title bar: score the current branch against its- base, with the drivers behind the score.+- **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@@ -71,7 +80,9 @@ for this Workspace** to write `.vscode/mcp.json`.| `repowise.fileDecorations.enabled` | `true` | Badge the worst-health files in the explorer || `repowise.codeLens.enabled` | `true` | Show refactoring plan lenses || `repowise.hover.enabled` | `true` | Show file health context on hover |-| `repowise.risk.baseBranch` | default branch | Base branch for branch risk scoring |+| `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 |## Privacydiff --git a/packages/vscode/README.md b/packages/vscode/README.mdindex aca97ec44..7894dd4bf 100644--- a/packages/vscode/README.md+++ b/packages/vscode/README.md@@ -11,7 +11,8 @@ This extension brings that index into VS Code, for both halves of how code gets- **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.-- **Branch risk before you push**: score a branch against its base from the SCM title bar, with the drivers behind the score.+- **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.@@ -31,7 +32,7 @@ This extension brings that index into VS Code, for both halves of how code gets| 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: Check Branch Risk | Score the current branch against its base |+| 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: Show Health Dashboard | Open the health overview || Repowise: Show Architecture Map | Open the C4 architecture view |@@ -48,6 +49,9 @@ This extension brings that index into VS Code, for both halves of how code gets| `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 |## Privacydiff --git a/packages/vscode/package.json b/packages/vscode/package.jsonindex 4a074b915..b2b42b8e8 100644--- a/packages/vscode/package.json+++ b/packages/vscode/package.json@@ -128,7 +128,19 @@"repowise.risk.baseBranch": {"type": "string","default": "",- "description": "Base branch for branch risk scoring. Leave empty to use the repository's default branch."+ "description": "Base branch for change risk scoring. Leave empty to use the repository's default branch."+ },+ "repowise.changeIntel.cochangeNudge": {+ "type": "boolean",+ "default": true,+ "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."+ },+ "repowise.changeIntel.cochangeMinScore": {+ "type": "number",+ "default": 4,+ "minimum": 0,+ "maximum": 100,+ "description": "Minimum historical co-change count before a related file is surfaced by the nudge. Higher values mean fewer, stronger hints."}}},@@ -165,7 +177,7 @@},{"command": "repowise.checkBranchRisk",- "title": "Check Branch Risk",+ "title": "Analyze Change Risk","category": "Repowise","icon": "$(pulse)"},diff --git a/packages/vscode/src/constants.ts b/packages/vscode/src/constants.tsindex 78025c51c..83591d2d3 100644--- a/packages/vscode/src/constants.ts+++ b/packages/vscode/src/constants.ts@@ -42,6 +42,8 @@ export const Commands = {export const InternalCommands = {copyRefactoringPrompt: "repowise.copyRefactoringPrompt",openRefactoringPlan: "repowise.openRefactoringPlan",+ /** Opens the co-change nudge QuickPick; bound to the status-bar item only. */+ reviewCochanges: "repowise.reviewCochanges",} as const;/** Sidebar view ids, mirrored from package.json `contributes.views`. */diff --git a/packages/vscode/src/core/changeAnalysis.ts b/packages/vscode/src/core/changeAnalysis.tsnew file mode 100644index 000000000..26eb2829b--- /dev/null+++ b/packages/vscode/src/core/changeAnalysis.ts@@ -0,0 +1,159 @@+import { analyzeBlastRadius } from "@repowise-dev/api-client/blast-radius";+import { getReviewerSuggestions } from "@repowise-dev/api-client/git";+import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";+import type { ReviewerSuggestion } from "@repowise-dev/api-client/types";+import { CONFIG_SECTION } from "../constants";+import { changeSignature } from "../shared/changeImpact";+import type { ChangeImpactReport } from "../shared/webviewMessages";+import type { RepowiseContext } from "./context";+import { getBranchChangedFiles, getChangedFiles } from "./gitApi";+import * as vscode from "vscode";++/**+ * The one place the extension turns "what changed" into "what it touches". Both+ * the Change Risk panel and the ambient co-change nudge call this, so the blast+ * and reviewer analysis is computed once, cached, and shared.+ *+ * The network result depends only on the CHANGED FILE SET and the indexed+ * commit, never on file contents (blast radius is graph-derived). So it is+ * cached under a signature of the sorted path set, tagged by the indexed head+ * commit. Editing lines in an already-changed file leaves the set unchanged and+ * hits the cache; adding or removing a file from the set triggers one fetch.+ */++export type ChangeScope = ChangeImpactReport["scope"];++/** Upper bound on paths sent to the server; a sprawling set is capped, not refused. */+const MAX_CHANGED_FILES = 400;++/** The cached half: the two network results keyed by the change-set signature. */+interface ImpactData {+ blast: BlastRadiusResponse | null;+ reviewers: ReviewerSuggestion[];+ /** True only when both endpoints succeeded; a degraded result is not cached. */+ complete: boolean;+}++/** Shared across callers so two surfaces analyzing the same set fetch once. */+const inFlight = new Map<string, Promise<ImpactData>>();++/** Resolves the base ref for branch-scope diffing (matches the risk panel). */+function resolveBase(ctx: RepowiseContext): string {+ const configured = vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<string>("risk.baseBranch", "")+ .trim();+ return configured || ctx.repo?.default_branch || "main";+}++function emptyReport(+ scope: ChangeScope,+ gitUnavailable: boolean,+): ChangeImpactReport {+ return {+ changed: [],+ stagedCount: 0,+ workingCount: 0,+ scope,+ blast: null,+ reviewers: [],+ gitUnavailable,+ };+}++/**+ * Analyzes the current change set. Returns a clean (empty) report when the tree+ * has nothing to analyze, and a `gitUnavailable` report when git cannot be read+ * (callers distinguish the two: clean means "nothing to say", unavailable means+ * "cannot say"). Never throws: a failing endpoint degrades its own section.+ */+export async function analyzeChange(+ ctx: RepowiseContext,+ scope: ChangeScope,+): Promise<ChangeImpactReport> {+ const id = ctx.repoId;+ const root = ctx.workspace.repoRoot;+ if (!id || !root || ctx.getExtensionState() !== "ready") {+ return emptyReport(scope, false);+ }++ const files = await getChangedFiles(root);+ if (!files) return emptyReport(scope, true);++ const working = dedupeSorted([...files.staged, ...files.workingTree]);+ let changed = working;+ if (scope === "branch") {+ const branchFiles = await getBranchChangedFiles(root, resolveBase(ctx));+ if (branchFiles) changed = dedupeSorted([...branchFiles, ...working]);+ }+ changed = changed.slice(0, MAX_CHANGED_FILES);++ if (changed.length === 0) {+ const clean = emptyReport(scope, false);+ clean.stagedCount = files.staged.length;+ clean.workingCount = files.workingTree.length;+ return clean;+ }++ const data = await loadImpact(ctx, id, changed);+ return {+ changed,+ stagedCount: files.staged.length,+ workingCount: files.workingTree.length,+ scope,+ blast: data.blast,+ reviewers: data.reviewers,+ gitUnavailable: false,+ };+}++/** Serves the blast+reviewer pair from the tagged cache; misses share a request. */+function loadImpact(+ ctx: RepowiseContext,+ id: string,+ changed: string[],+): Promise<ImpactData> {+ const sig = changeSignature(changed);+ const tag = ctx.repo?.head_commit ?? "";+ const key = `changeIntel:${sig}`;+ const hit = ctx.cache.get<ImpactData>(id, key, tag);+ if (hit !== undefined) return Promise.resolve(hit);++ const flightKey = `${id}|${tag}|${sig}`;+ const pending = inFlight.get(flightKey);+ if (pending) return pending;++ const request = fetchImpact(id, changed)+ .then((data) => {+ // Only persist a complete result. Caching a transient failure would pin+ // the degraded value until the file set or the index moved, with no+ // retry; instead we return it once and re-fetch on the next call.+ if (data.complete) ctx.cache.set(id, key, tag, data);+ return data;+ })+ .finally(() => {+ inFlight.delete(flightKey);+ });+ inFlight.set(flightKey, request);+ return request;+}++/** Runs both endpoints in parallel; either failing degrades to its empty shape. */+async function fetchImpact(+ id: string,+ changed: string[],+): Promise<ImpactData> {+ const [blast, reviewers] = await Promise.allSettled([+ analyzeBlastRadius(id, { changed_files: changed }),+ getReviewerSuggestions(id, changed),+ ]);+ return {+ blast: blast.status === "fulfilled" ? blast.value : null,+ reviewers: reviewers.status === "fulfilled" ? reviewers.value.suggestions : [],+ complete: blast.status === "fulfilled" && reviewers.status === "fulfilled",+ };+}++function dedupeSorted(paths: string[]): string[] {+ return [...new Set(paths)].sort();+}diff --git a/packages/vscode/src/core/gitApi.ts b/packages/vscode/src/core/gitApi.tsindex 8c7e275df..b0144a31d 100644--- a/packages/vscode/src/core/gitApi.ts+++ b/packages/vscode/src/core/gitApi.ts@@ -20,13 +20,28 @@ interface Branch {readonly commit?: string;}+/** One changed path as reported by the git extension. */+interface Change {+ readonly uri: vscode.Uri;+ readonly originalUri: vscode.Uri;+ /** Numeric git status; not interpreted here, every change counts as touched. */+ readonly status: number;+}+interface RepositoryState {readonly HEAD?: Branch;+ /** Staged changes (the index). */+ readonly indexChanges: readonly Change[];+ /** Unstaged working-tree changes. */+ readonly workingTreeChanges: readonly Change[];readonly onDidChange: vscode.Event<void>;}interface Repository {+ readonly rootUri: vscode.Uri;readonly state: RepositoryState;+ /** `git diff ref1 ref2`, name+status list. Absent on older git extensions. */+ diffBetween?(ref1: string, ref2: string): Promise<Change[]>;}interface GitAPI {@@ -164,3 +179,84 @@ export async function onDidChangeHead(cb();});}++/** Uncommitted changes split by staging state; paths are repo-relative POSIX. */+export interface ChangedFiles {+ /** Staged (index) paths. */+ staged: string[];+ /** Unstaged working-tree paths. */+ workingTree: string[];+}++/**+ * Converts a changed-file URI to a repo-relative POSIX path (the shape the+ * server addresses files by), or null when it resolves outside the root. The+ * git extension only ever reports paths inside the repo, so the guard is+ * defensive, not expected to fire.+ */+function toRepoRelative(root: string, uri: vscode.Uri): string | null {+ const rel = path.relative(root, uri.fsPath);+ if (rel === "" || rel.startsWith("..") || path.isAbsolute(rel)) return null;+ return rel.split(path.sep).join("/");+}++/** De-dupes and sorts a path list so a change-set has a stable signature. */+function normalizePaths(root: string, changes: readonly Change[]): string[] {+ const out = new Set<string>();+ for (const change of changes) {+ const rel = toRepoRelative(root, change.uri);+ if (rel) out.add(rel);+ }+ return [...out].sort();+}++/**+ * Uncommitted changes (staged and working tree), or null when git cannot serve+ * the repository. An empty repo with a clean tree returns empty arrays, which is+ * distinct from the null "git unavailable" case callers must not treat as clean.+ */+export async function getChangedFiles(+ repoRoot: string,+): Promise<ChangedFiles | null> {+ const repo = await getRepository(repoRoot);+ if (!repo) return null;+ return {+ staged: normalizePaths(repoRoot, repo.state.indexChanges),+ workingTree: normalizePaths(repoRoot, repo.state.workingTreeChanges),+ };+}++/**+ * Files that differ between `base` and the checked-out HEAD (the committed work+ * a push would carry), as repo-relative POSIX paths. Null when git is+ * unavailable, the git extension is too old to expose `diffBetween`, or `base`+ * cannot be resolved (e.g. never fetched); callers fall back to the working-tree+ * set. Never throws.+ */+export async function getBranchChangedFiles(+ repoRoot: string,+ base: string,+): Promise<string[] | null> {+ const repo = await getRepository(repoRoot);+ if (!repo?.diffBetween) return null;+ try {+ const changes = await repo.diffBetween(base, "HEAD");+ return normalizePaths(repoRoot, changes);+ } catch {+ return null;+ }+}++/**+ * Invokes `cb` on any repository state change (staging, working-tree edits, HEAD+ * moves). Unlike {@link onDidChangeHead} this does not filter, so callers must+ * debounce. Returns a no-op disposable when git is unavailable.+ */+export async function onDidChangeRepoState(+ repoRoot: string,+ cb: () => void,+): Promise<vscode.Disposable> {+ const repo = await getRepository(repoRoot);+ if (!repo) return { dispose: () => {} };+ return repo.state.onDidChange(() => cb());+}diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.tsindex 253959c04..244bd2bc2 100644--- a/packages/vscode/src/core/webviewApi.ts+++ b/packages/vscode/src/core/webviewApi.ts@@ -39,6 +39,7 @@ import {type SettingValue,} from "../shared/webviewMessages";import type { RepowiseContext } from "./context";+import { analyzeChange } from "./changeAnalysis";import { commitsMatch, getCurrentBranchName, resolveLiveHead } from "./gitApi";/** Thrown by the dispatcher when a request arrives while disconnected. */@@ -62,6 +63,8 @@ const SETTING_DEFAULTS: SettingsValues = {"server.port": null,"cliPath": "","risk.baseBranch": "",+ "changeIntel.cochangeNudge": true,+ "changeIntel.cochangeMinScore": 4,};const SEVERITIES = ["critical", "high", "medium", "low"];@@ -85,6 +88,8 @@ const SETTING_VALIDATORS: Record<SettingKey, (v: SettingValue) => SettingValue>"server.port": expectNullablePort,"cliPath": expectString,"risk.baseBranch": expectString,+ "changeIntel.cochangeNudge": expectBoolean,+ "changeIntel.cochangeMinScore": (v) => expectNumberInRange(v, 0, 100),};function expectBoolean(v: SettingValue): boolean {@@ -305,6 +310,11 @@ export function createHostApi(ctx: RepowiseContext, epoch: () => number): HostApreturn { base, branch, result };},+ // Change impact: reads the working tree, so it tracks the live change set+ // rather than the indexed commit. analyzeChange owns caching by change-set+ // signature, so this never re-fetches for an unchanged file set.+ changeImpact: () => analyzeChange(ctx, "branch"),+// Sidebar homehomeSummary,diff --git a/packages/vscode/src/core/webviews.ts b/packages/vscode/src/core/webviews.tsindex ac0bc69cb..b880eded5 100644--- a/packages/vscode/src/core/webviews.ts+++ b/packages/vscode/src/core/webviews.ts@@ -37,7 +37,7 @@ const VIEW_META: Record<PanelViewId, ViewMeta> = {refactoring: { title: "Repowise Refactoring Plan", retainContextWhenHidden: false },decisions: { title: "Repowise Decisions", retainContextWhenHidden: false },docs: { title: "Repowise Docs", retainContextWhenHidden: false },- risk: { title: "Repowise Branch Risk", retainContextWhenHidden: false },+ risk: { title: "Repowise Change Risk", retainContextWhenHidden: false },settings: { title: "Repowise Settings", retainContextWhenHidden: false },};diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.tsindex a7cd11ecb..1078a67df 100644--- a/packages/vscode/src/extension.ts+++ b/packages/vscode/src/extension.ts@@ -18,6 +18,7 @@ import { registerFileDecorations } from "./features/fileDecorations";import { registerFileScoreStatus } from "./features/fileScoreStatus";import { registerTrees } from "./features/trees";import { registerBranchRisk } from "./features/branchRisk";+import { registerChangeIntel } from "./features/changeIntel";import { registerStaleness } from "./features/staleness";import { registerRefactoringLens } from "./features/refactoringLens";import { registerDocs } from "./features/docs";@@ -88,6 +89,7 @@ export function activate(extCtx: vscode.ExtensionContext): void {registerFileScoreStatus(ctx),registerTrees(ctx),registerBranchRisk(ctx),+ registerChangeIntel(ctx),registerStaleness(ctx),registerRefactoringLens(ctx),registerDocs(ctx),diff --git a/packages/vscode/src/features/branchRisk.ts b/packages/vscode/src/features/branchRisk.tsindex 1dd3d49fb..ea8ad3ff9 100644--- a/packages/vscode/src/features/branchRisk.ts+++ b/packages/vscode/src/features/branchRisk.ts@@ -4,11 +4,12 @@ import type { RepowiseContext } from "../core/context";import { openViewPanel } from "../core/webviews";/**- * Opens the branch-risk webview, which scores the working branch against a base- * and renders the result. Bound to the palette command and the SCM title button- * (both call `Commands.checkBranchRisk`). The webview owns fetching, so this- * only opens the panel; openViewPanel guards the ready state and warns when the- * server is not connected or the repository is not indexed.+ * Opens the change-risk webview, which scores the working branch against a base+ * and shows what the change touches (downstream files, usual co-changes,+ * missing tests, and suggested reviewers). Bound to the palette command and the+ * SCM title button (both call `Commands.checkBranchRisk`). The webview owns+ * fetching, so this only opens the panel; openViewPanel guards the ready state+ * and warns when the server is not connected or the repository is not indexed.*/export function registerBranchRisk(ctx: RepowiseContext): vscode.Disposable {return vscode.commands.registerCommand(Commands.checkBranchRisk, () =>diff --git a/packages/vscode/src/features/changeIntel.ts b/packages/vscode/src/features/changeIntel.tsnew file mode 100644index 000000000..f1175b494--- /dev/null+++ b/packages/vscode/src/features/changeIntel.ts@@ -0,0 +1,237 @@+import * as vscode from "vscode";+import { CONFIG_SECTION, Commands, InternalCommands } from "../constants";+import { analyzeChange } from "../core/changeAnalysis";+import type { RepowiseContext } from "../core/context";+import { onDidChangeRepoState } from "../core/gitApi";+import {+ changeSignature,+ selectMissingCochanges,+ type MissingCochange,+} from "../shared/changeImpact";+import type { ChangeImpactReport } from "../shared/webviewMessages";++/**+ * Ambient "you may have forgotten a file" nudge. When the files you are editing+ * have a strong history of changing together with a file you have NOT touched,+ * a quiet status-bar item appears. It is deliberately restrained: no toast, no+ * modal, no colour alarm; it shows only above a configurable strength floor,+ * and it can be dismissed for the current change set. Co-changes are advisory+ * (plenty of edits legitimately touch only part of a cluster), so this must+ * inform without nagging.+ */++/** Git fires state changes on every save; coalesce a burst into one analysis. */+const DEBOUNCE_MS = 2_000;++/** How many partners the tooltip lists before collapsing to "+N more". */+const TOOLTIP_LIMIT = 5;++/** Workspace-state key holding the change-set signature the user dismissed. */+const DISMISS_KEY = "repowise.changeIntel.dismissedSignature";++function baseName(p: string): string {+ return p.split("/").pop() || p;+}++export function registerChangeIntel(ctx: RepowiseContext): vscode.Disposable {+ const item = vscode.window.createStatusBarItem(+ vscode.StatusBarAlignment.Right,+ 1,+ );+ item.command = InternalCommands.reviewCochanges;++ let repoStateSub: vscode.Disposable | null = null;+ /** Guards the async subscribe so a ready/not-ready flap cannot double-arm it. */+ let subscribing = false;+ let debounce: NodeJS.Timeout | null = null;+ /** The partners behind the currently shown item, for the QuickPick. */+ let current: MissingCochange[] = [];+ /** Signature of the change set the item currently reflects. */+ let currentSignature = "";++ function enabled(): boolean {+ return vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<boolean>("changeIntel.cochangeNudge", true);+ }++ function minScore(): number {+ return vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<number>("changeIntel.cochangeMinScore", 4);+ }++ function hide(): void {+ current = [];+ item.hide();+ }++ async function evaluate(): Promise<void> {+ if (!enabled() || ctx.getExtensionState() !== "ready") {+ hide();+ return;+ }+ let report: ChangeImpactReport;+ try {+ report = await analyzeChange(ctx, "working");+ } catch (err) {+ ctx.log.debug(`co-change nudge analysis failed: ${String(err)}`);+ hide();+ return;+ }+ const partners = selectMissingCochanges(report, minScore());+ currentSignature = changeSignature(report.changed);+ if (partners.length === 0) {+ hide();+ return;+ }+ // Respect a dismissal until the change set itself moves on.+ if (ctx.state.get<string>(DISMISS_KEY) === currentSignature) {+ hide();+ return;+ }+ current = partners;+ render(partners);+ }++ function render(partners: MissingCochange[]): void {+ const n = partners.length;+ item.text = `$(git-pull-request) ${n} related`;+ const md = new vscode.MarkdownString();+ md.appendMarkdown(+ `**Files that usually change with your edits**\n\nYou have not touched ${+ n === 1 ? "this file" : "these files"+ }:\n`,+ );+ for (const p of partners.slice(0, TOOLTIP_LIMIT)) {+ md.appendMarkdown(`\n- \`${p.partner}\``);+ }+ if (n > TOOLTIP_LIMIT) md.appendMarkdown(`\n- +${n - TOOLTIP_LIMIT} more`);+ md.appendMarkdown("\n\nClick to review. This is advisory, not a rule.");+ item.tooltip = md;+ item.show();+ }++ /** Opens a light QuickPick to review, jump to, or dismiss the related files. */+ async function reviewCochanges(): Promise<void> {+ if (current.length === 0) {+ void vscode.window.showInformationMessage(+ "No related files to review for the current change set.",+ );+ return;+ }+ // Snapshot the signature: a debounced re-evaluate may reassign+ // currentSignature while the QuickPick is open, and a dismiss must apply to+ // the set the user is actually looking at.+ const signatureAtOpen = currentSignature;+ type Item = vscode.QuickPickItem & {+ action: "open" | "panel" | "dismiss";+ partner?: string;+ };+ const fileItems: Item[] = current.map((p) => ({+ label: `$(file) ${baseName(p.partner)}`,+ description: `co-changed ${p.score}×`,+ detail: `${p.partner} — usually changes with ${p.withChanged}`,+ action: "open",+ partner: p.partner,+ }));+ const actions: Item[] = [+ {+ label: "$(pulse) Open Change Risk",+ detail: "See the full impact of this change set",+ action: "panel",+ },+ {+ label: "$(bell-slash) Dismiss for this change",+ detail: "Hide until the set of changed files changes",+ action: "dismiss",+ },+ ];+ const picked = await vscode.window.showQuickPick<Item>(+ [+ ...fileItems,+ { label: "", kind: vscode.QuickPickItemKind.Separator, action: "open" },+ ...actions,+ ],+ {+ placeHolder: "Files your history says usually change together with this one",+ matchOnDetail: true,+ },+ );+ if (!picked) return;+ if (picked.action === "open" && picked.partner) {+ const root = ctx.workspace.repoRoot;+ if (!root) return;+ const abs = vscode.Uri.joinPath(vscode.Uri.file(root), ...picked.partner.split("/"));+ try {+ await vscode.window.showTextDocument(abs, { preview: true });+ } catch {+ void vscode.window.showWarningMessage(`Could not open ${picked.partner}.`);+ }+ } else if (picked.action === "panel") {+ await vscode.commands.executeCommand(Commands.checkBranchRisk);+ } else if (picked.action === "dismiss") {+ await ctx.state.update(DISMISS_KEY, signatureAtOpen);+ hide();+ }+ }++ function scheduleEval(): void {+ if (debounce) clearTimeout(debounce);+ debounce = setTimeout(() => void evaluate(), DEBOUNCE_MS);+ }++ /** Subscribe to git state lazily (never during activate). */+ function ensureWatcher(): void {+ // The subscribe is async (git can take seconds to init); a second call+ // before it resolves would otherwise slip past a `repoStateSub`-only guard+ // and orphan a duplicate listener on a ready/not-ready flap.+ if (repoStateSub || subscribing) return;+ const root = ctx.workspace.repoRoot;+ if (!root) return;+ subscribing = true;+ void onDidChangeRepoState(root, scheduleEval).then((sub) => {+ subscribing = false;+ // The extension may have torn down before git resolved; drop the sub.+ if (disposed) sub.dispose();+ else repoStateSub = sub;+ });+ }++ let disposed = false;+ const disposables: vscode.Disposable[] = [+ item,+ vscode.commands.registerCommand(InternalCommands.reviewCochanges, () =>+ reviewCochanges(),+ ),+ ctx.onDidChangeExtensionState((state) => {+ if (state === "ready") {+ ensureWatcher();+ void evaluate();+ } else {+ hide();+ }+ }),+ vscode.workspace.onDidChangeConfiguration((e) => {+ if (e.affectsConfiguration(`${CONFIG_SECTION}.changeIntel`)) void evaluate();+ }),+ ];++ if (ctx.getExtensionState() === "ready") {+ const timer = setTimeout(() => {+ ensureWatcher();+ void evaluate();+ }, 0);+ disposables.push({ dispose: () => clearTimeout(timer) });+ }++ return {+ dispose(): void {+ disposed = true;+ if (debounce) clearTimeout(debounce);+ repoStateSub?.dispose();+ repoStateSub = null;+ for (const d of disposables) d.dispose();+ },+ };+}diff --git a/packages/vscode/src/shared/changeImpact.ts b/packages/vscode/src/shared/changeImpact.tsnew file mode 100644index 000000000..87d12aed6--- /dev/null+++ b/packages/vscode/src/shared/changeImpact.ts@@ -0,0 +1,57 @@+/**+ * Pure change-impact helpers, free of `vscode` and the api-client so they can be+ * shared by the extension host (analysis service, nudge feature) and unit-tested+ * in the webview vitest environment without a VS Code host. Runtime-dependency+ * free by design; only a type import from the message contract.+ */++import type { ChangeImpactReport } from "./webviewMessages";++/** Stable signature of a change set; identical sets share a cache entry. */+export function changeSignature(paths: string[]): string {+ return paths.join("\n");+}++/** A file not in the change set that historically changes with a changed file. */+export interface MissingCochange {+ /** Repo-relative path the user has not touched. */+ partner: string;+ /** Strongest co-change count among the changed files pointing at it. */+ score: number;+ /** An example changed file it partners with (for the "why"). */+ withChanged: string;+ /** How many changed files point at this partner. */+ count: number;+}++/**+ * Reduces the blast response's per-pair co-change warnings to one ranked entry+ * per missing partner, dropping anything below `minScore` or already in the+ * change set. Ranked by strength, strongest first.+ */+export function selectMissingCochanges(+ report: ChangeImpactReport,+ minScore: number,+): MissingCochange[] {+ const changed = new Set(report.changed);+ const byPartner = new Map<string, MissingCochange>();+ for (const w of report.blast?.cochange_warnings ?? []) {+ if (w.score < minScore || changed.has(w.missing_partner)) continue;+ const existing = byPartner.get(w.missing_partner);+ if (existing) {+ existing.count += 1;+ if (w.score > existing.score) {+ existing.score = w.score;+ existing.withChanged = w.changed;+ }+ } else {+ byPartner.set(w.missing_partner, {+ partner: w.missing_partner,+ score: w.score,+ withChanged: w.changed,+ count: 1,+ });+ }+ }+ return [...byPartner.values()].sort((a, b) => b.score - a.score);+}diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.tsindex d27b1b678..3c3804b2e 100644--- a/packages/vscode/src/shared/webviewMessages.ts+++ b/packages/vscode/src/shared/webviewMessages.ts@@ -32,6 +32,8 @@ import type {PageResponse,} from "@repowise-dev/api-client/types";import type { RiskRangeResponse } from "@repowise-dev/api-client/risk";+import type { ReviewerSuggestion } from "@repowise-dev/api-client/types";+import type { BlastRadiusResponse } from "@repowise-dev/types/blast-radius";import type { ArchitectureView } from "@repowise-dev/ui/c4";import type { RefactoringPlan, RefactoringTargets } from "@repowise-dev/ui/refactoring/types";import type { AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";@@ -83,6 +85,8 @@ export const SETTING_KEYS = ["server.port","cliPath","risk.baseBranch",+ "changeIntel.cochangeNudge",+ "changeIntel.cochangeMinScore",] as const;export type SettingKey = (typeof SETTING_KEYS)[number];@@ -147,8 +151,10 @@ export interface HostApi {pagesList(): Promise<PageResponse[]>;pageById(pageId: string): Promise<PageResponse>;fileDetail(relPath: string): Promise<FileDetailResponse>;- // Branch risk+ // Change riskriskRange(): Promise<RiskRangeReport>;+ /** Impact of the current change set (uncommitted + unpushed). */+ changeImpact(): Promise<ChangeImpactReport>;// Sidebar homehomeSummary(): Promise<HomeSummary>;// Settings panel@@ -198,6 +204,31 @@ export interface RiskRangeReport {result: RiskRangeResponse;}+/**+ * Impact of the working change set, assembled host-side from the blast-radius+ * and reviewer-suggestion endpoints. Shared verbatim by the Change Risk panel+ * and the ambient co-change nudge so there is one analysis, not two.+ */+export interface ChangeImpactReport {+ /** Repo-relative paths analyzed, sorted (the change-set signature source). */+ changed: string[];+ /** How many of the changed paths are staged / unstaged (working tree). */+ stagedCount: number;+ workingCount: number;+ /**+ * "branch" includes committed-but-unpushed changes (base..HEAD); "working"+ * is the uncommitted tree only. The panel asks for branch scope; the nudge+ * asks for working scope so it speaks to the file being edited right now.+ */+ scope: "branch" | "working";+ /** Blast analysis, or null when git is unavailable or nothing changed. */+ blast: BlastRadiusResponse | null;+ /** Reviewer suggestions for the changed set (names + reasons). */+ reviewers: ReviewerSuggestion[];+ /** True when git could not be read at all (distinct from a clean tree). */+ gitUnavailable: boolean;+}+export type HostApiMethod = keyof HostApi;// ---------------------------------------------------------------------------diff --git a/packages/vscode/webview/src/changeImpact.test.ts b/packages/vscode/webview/src/changeImpact.test.tsnew file mode 100644index 000000000..aa52bcd88--- /dev/null+++ b/packages/vscode/webview/src/changeImpact.test.ts@@ -0,0 +1,81 @@+import { describe, it, expect } from "vitest";+import {+ changeSignature,+ selectMissingCochanges,+} from "../../src/shared/changeImpact";+import type { ChangeImpactReport } from "../../src/shared/webviewMessages";++function report(+ overrides: Partial<ChangeImpactReport> & {+ cochange_warnings?: Array<{+ changed: string;+ missing_partner: string;+ score: number;+ }>;+ } = {},+): ChangeImpactReport {+ const { cochange_warnings = [], ...rest } = overrides;+ return {+ changed: [],+ stagedCount: 0,+ workingCount: 0,+ scope: "working",+ reviewers: [],+ gitUnavailable: false,+ blast: {+ direct_risks: [],+ transitive_affected: [],+ cochange_warnings,+ recommended_reviewers: [],+ test_gaps: [],+ overall_risk_score: 0,+ },+ ...rest,+ };+}++describe("selectMissingCochanges", () => {+ it("groups by partner and keeps the strongest score", () => {+ const out = selectMissingCochanges(+ report({+ changed: ["a.ts"],+ cochange_warnings: [+ { changed: "a.ts", missing_partner: "b.ts", score: 5 },+ { changed: "a.ts", missing_partner: "b.ts", score: 9 },+ { changed: "a.ts", missing_partner: "c.ts", score: 6 },+ ],+ }),+ 4,+ );+ expect(out).toHaveLength(2);+ // Sorted by score desc; b.ts keeps the max (9) and counts both pairs.+ expect(out[0]).toMatchObject({ partner: "b.ts", score: 9, count: 2 });+ expect(out[1]?.partner).toBe("c.ts");+ });++ it("drops partners below the floor and any already in the change set", () => {+ const out = selectMissingCochanges(+ report({+ changed: ["a.ts", "d.ts"],+ cochange_warnings: [+ { changed: "a.ts", missing_partner: "b.ts", score: 2 }, // below floor+ { changed: "a.ts", missing_partner: "d.ts", score: 9 }, // already changed+ { changed: "a.ts", missing_partner: "e.ts", score: 7 }, // kept+ ],+ }),+ 4,+ );+ expect(out.map((c) => c.partner)).toEqual(["e.ts"]);+ });++ it("returns nothing when there is no blast payload", () => {+ expect(selectMissingCochanges(report({ blast: null }), 4)).toEqual([]);+ });+});++describe("changeSignature", () => {+ it("is stable for the same set and distinct across sets", () => {+ expect(changeSignature(["a.ts", "b.ts"])).toBe(changeSignature(["a.ts", "b.ts"]));+ expect(changeSignature(["a.ts"])).not.toBe(changeSignature(["a.ts", "b.ts"]));+ });+});diff --git a/packages/vscode/webview/src/runtime/chrome.tsx b/packages/vscode/webview/src/runtime/chrome.tsxindex 68db52956..472d3ec6d 100644--- a/packages/vscode/webview/src/runtime/chrome.tsx+++ b/packages/vscode/webview/src/runtime/chrome.tsx@@ -34,7 +34,7 @@ const NAV: NavItem[] = [{ view: "refactoring", title: "Refactoring", icon: Wrench },{ view: "decisions", title: "Decisions", icon: Scale },{ view: "docs", title: "Docs", icon: BookOpen },- { view: "risk", title: "Branch Risk", icon: GitBranch },+ { view: "risk", title: "Change Risk", icon: GitBranch },];export function PanelChrome({ view, host }: { view: PanelViewId; host: WebviewHost }) {diff --git a/packages/vscode/webview/src/views/risk/App.test.tsx b/packages/vscode/webview/src/views/risk/App.test.tsxindex b9a1bd8fe..3e8c2d854 100644--- a/packages/vscode/webview/src/views/risk/App.test.tsx+++ b/packages/vscode/webview/src/views/risk/App.test.tsx@@ -2,8 +2,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";import { render, screen, fireEvent, waitFor, cleanup } from "@testing-library/react";import { App } from "./App";import type { WebviewHost } from "../../runtime/rpc";-import type { RepoInit } from "../../../../src/shared/webviewMessages";-import type { RiskRangeReport } from "../../../../src/shared/webviewMessages";+import type {+ ChangeImpactReport,+ RepoInit,+ RiskRangeReport,+} from "../../../../src/shared/webviewMessages";const REPORT: RiskRangeReport = {base: "main",@@ -27,9 +30,55 @@ const REPORT: RiskRangeReport = {const REPO: RepoInit = { id: "r1", name: "repo", headCommit: null, defaultBranch: "main" };-function makeHost(riskRange: WebviewHost["api"]["riskRange"]): WebviewHost {+/** A clean tree: nothing changed, so no impact sections render. */+const CLEAN_IMPACT: ChangeImpactReport = {+ changed: [],+ stagedCount: 0,+ workingCount: 0,+ scope: "branch",+ blast: null,+ reviewers: [],+ gitUnavailable: false,+};++const IMPACT: ChangeImpactReport = {+ changed: ["src/a.ts", "src/b.ts"],+ stagedCount: 1,+ workingCount: 1,+ scope: "branch",+ blast: {+ direct_risks: [],+ transitive_affected: [{ path: "src/consumer.ts", depth: 1 }],+ cochange_warnings: [+ { changed: "src/a.ts", missing_partner: "src/a.test.ts", score: 8 },+ ],+ recommended_reviewers: [],+ test_gaps: ["src/b.ts"],+ overall_risk_score: 5.6,+ },+ reviewers: [+ {+ name: "Ada Lovelace",+ email: "[email protected]",+ score: 0.9,+ recent_commits: 4,+ owned_paths: ["src/a.ts"],+ co_change_paths: [],+ reasons: ["owns src/a.ts"],+ },+ ],+ gitUnavailable: false,+};++function makeHost(+ riskRange: WebviewHost["api"]["riskRange"],+ changeImpact: WebviewHost["api"]["changeImpact"] = vi+ .fn()+ .mockResolvedValue(CLEAN_IMPACT),+ overrides: Partial<WebviewHost> = {},+): WebviewHost {return {- api: { riskRange } as WebviewHost["api"],+ api: { riskRange, changeImpact } as WebviewHost["api"],onInit: () => () => {},onRefresh: () => () => {},onUpdateDone: () => () => {},@@ -43,6 +92,7 @@ function makeHost(riskRange: WebviewHost["api"]["riskRange"]): WebviewHost {openNativeSettings: () => {},updateIndex: () => {},setTheme: () => {},+ ...overrides,};}@@ -73,4 +123,48 @@ describe("risk App", () => {fireEvent.click(screen.getByRole("button", { name: /run again/i }));await waitFor(() => expect(riskRange).toHaveBeenCalledTimes(2));});++ it("renders change-impact sections from the blast payload", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ const changeImpact = vi.fn().mockResolvedValue(IMPACT);+ render(+ <App host={makeHost(riskRange, changeImpact)} repo={REPO} params={{}} refreshToken={0} />,+ );++ expect(await screen.findByText("Downstream of your changes")).toBeTruthy();+ // Paths render as split dir/name spans, so match on the file name.+ expect(screen.getByText("consumer.ts")).toBeTruthy();+ expect(screen.getByText("Usually changes together")).toBeTruthy();+ expect(screen.getByText("a.test.ts")).toBeTruthy();+ expect(screen.getByText("Changed without a test")).toBeTruthy();+ expect(screen.getByText("Ada Lovelace")).toBeTruthy();+ });++ it("copies suggested reviewers to the clipboard", async () => {+ const riskRange = vi.fn().mockResolvedValue(REPORT);+ const changeImpact = vi.fn().mockResolvedValue(IMPACT);+ const copyText = vi.fn();+ render(+ <App+ host={makeHost(riskRange, changeImpact, { copyText })}+ repo={REPO}+ params={{}}+ refreshToken={0}+ />,+ );++ await screen.findByText("Ada Lovelace");+ fireEvent.click(screen.getByRole("button", { name: /copy/i }));+ expect(copyText).toHaveBeenCalledWith(+ "Suggested reviewers: Ada Lovelace <[email protected]>",+ expect.any(String),+ );+ });++ 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} />);++ expect(await screen.findByText("No pending changes")).toBeTruthy();+ });});diff --git a/packages/vscode/webview/src/views/risk/App.tsx b/packages/vscode/webview/src/views/risk/App.tsxindex 133e70d0b..b0e1b6355 100644--- a/packages/vscode/webview/src/views/risk/App.tsx+++ b/packages/vscode/webview/src/views/risk/App.tsx@@ -1,9 +1,22 @@import { useCallback, useEffect, useState } from "react";-import { GitCompare, RotateCw, ShieldCheck } from "lucide-react";+import {+ Copy,+ GitCompare,+ GitPullRequest,+ Network,+ RotateCw,+ ShieldCheck,+ TestTube,+ Users,+} from "lucide-react";import { Badge, Button, Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui";import { EmptyState } from "@repowise-dev/ui/shared";import type { ViewProps } from "../../runtime/mount";-import type { RiskRangeReport } from "../../../../src/shared/webviewMessages";+import type { WebviewHost } from "../../runtime/rpc";+import type {+ ChangeImpactReport,+ RiskRangeReport,+} from "../../../../src/shared/webviewMessages";/** Human labels for the raw change features the endpoint returns, in report order. */const FEATURE_LABELS: ReadonlyArray<readonly [string, string]> = [@@ -42,26 +55,32 @@ function formatFeatureValue(value: number): string {export function App({ host, repo, refreshToken }: ViewProps<"risk">) {const [report, setReport] = useState<RiskRangeReport | null>(null);+ const [impact, setImpact] = useState<ChangeImpactReport | null>(null);const [error, setError] = useState<string | null>(null);const [loading, setLoading] = useState(true);+ const [impactLoading, setImpactLoading] = useState(true);const load = useCallback(() => {setLoading(true);+ setImpactLoading(true);setError(null);host.api.riskRange()- .then((r) => {- setReport(r);- setLoading(false);- })- .catch((err: unknown) => {- setError(err instanceof Error ? err.message : "Could not score branch risk.");- setLoading(false);- });+ .then((r) => setReport(r))+ .catch((err: unknown) =>+ setError(err instanceof Error ? err.message : "Could not score change risk."),+ )+ .finally(() => setLoading(false));+ // Impact is independent: a git-less workspace still shows the risk score.+ host.api+ .changeImpact()+ .then((r) => setImpact(r))+ .catch(() => setImpact(null))+ .finally(() => setImpactLoading(false));}, [host]);- // Refetch on mount and whenever the index moves under the panel. Risk- // reflects the working HEAD, so there is no cache to reuse.+ // Refetch on mount and whenever the index moves under the panel. Both scopes+ // reflect the working tree, so there is no cache to reuse here.useEffect(() => {load();}, [load, refreshToken]);@@ -73,7 +92,7 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {<div className="mx-auto max-w-3xl space-y-5 p-6"><header className="flex items-start justify-between gap-4"><div className="min-w-0">- <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">Branch risk</h1>+ <h1 className="text-lg font-semibold text-[var(--color-text-primary)]">Change risk</h1><p className="mt-1 flex items-center gap-2 text-sm text-[var(--color-text-secondary)]"><GitCompare className="h-4 w-4 shrink-0" /><span className="truncate">@@ -94,12 +113,16 @@ export function App({ host, repo, refreshToken }: ViewProps<"risk">) {) : error ? (<EmptyStateicon={<ShieldCheck className="h-8 w-8" />}- title="Could not score branch risk"+ title="Could not score change risk"description={error}action={{ label: "Try again", onClick: load }}/>) : report ? (- <Report report={report} />+ <>+ <ScoreHero report={report} />+ <ChangeImpact impact={impact} loading={impactLoading} host={host} />+ <RiskBreakdown report={report} />+ </>) : null}</div>);@@ -145,77 +168,75 @@ function RiskSkeleton({ base }: { base: string }) {);}-function Report({ report }: { report: RiskRangeReport }) {+/** The Kamei diff-shape risk score for the committed range (base..HEAD). */+function ScoreHero({ report }: { report: RiskRangeReport }) {const r = report.result;const tone = scoreTone(r.score);const color = TONE_VAR[tone];+ return (+ <Card>+ <CardContent className="flex flex-wrap items-center gap-6 py-6">+ <div+ className="flex h-24 w-24 shrink-0 flex-col items-center justify-center rounded-2xl border"+ style={{+ borderColor: `color-mix(in srgb, ${color} 45%, transparent)`,+ backgroundColor: `color-mix(in srgb, ${color} 12%, transparent)`,+ }}+ >+ <span className="text-3xl font-bold leading-none" style={{ color }}>+ {r.score.toFixed(1)}+ </span>+ <span className="mt-1 text-[11px] text-[var(--color-text-tertiary)]">out of 10</span>+ </div>+ <div className="min-w-0 flex-1 space-y-2">+ <div className="flex flex-wrap items-center gap-2">+ <span+ className="inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium capitalize"+ style={{ color, borderColor: `color-mix(in srgb, ${color} 40%, transparent)` }}+ >+ {r.level} risk+ </span>+ {r.is_fix && (+ <Badge variant="outline" title="Classified as a fix change">+ fix+ </Badge>+ )}+ </div>+ <p className="text-sm text-[var(--color-text-secondary)]">+ Estimated defect probability{" "}+ <span className="font-semibold text-[var(--color-text-primary)]">+ {(r.probability * 100).toFixed(1)}%+ </span>+ </p>+ <div className="flex flex-wrap gap-2 pt-1">+ {r.risk_percentile != null && (+ <Badge variant="default">{r.risk_percentile.toFixed(0)}th percentile</Badge>+ )}+ {r.review_priority && (+ <Badge variant="accent" className="capitalize">+ {r.review_priority} review priority+ </Badge>+ )}+ </div>+ </div>+ </CardContent>+ </Card>+ );+}+/** The statistical breakdown: what moves the score, and the raw change shape. */+function RiskBreakdown({ report }: { report: RiskRangeReport }) {+ const r = report.result;const drivers = [...r.drivers].sort((a, b) => Math.abs(b.contribution) - Math.abs(a.contribution),);const maxDriver = drivers.reduce((m, d) => Math.max(m, Math.abs(d.contribution)), 0);-const featureRows = FEATURE_LABELS.filter(([key]) => r.features[key] != null,) as ReadonlyArray<readonly [string, string]>;return (- <div className="space-y-5">- {/* Score hero */}- <Card>- <CardContent className="flex flex-wrap items-center gap-6 py-6">- <div- className="flex h-24 w-24 shrink-0 flex-col items-center justify-center rounded-2xl border"- style={{- borderColor: `color-mix(in srgb, ${color} 45%, transparent)`,- backgroundColor: `color-mix(in srgb, ${color} 12%, transparent)`,- }}- >- <span className="text-3xl font-bold leading-none" style={{ color }}>- {r.score.toFixed(1)}- </span>- <span className="mt-1 text-[11px] text-[var(--color-text-tertiary)]">out of 10</span>- </div>- <div className="min-w-0 flex-1 space-y-2">- <div className="flex flex-wrap items-center gap-2">- <span- className="inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium capitalize"- style={{- color,- borderColor: `color-mix(in srgb, ${color} 40%, transparent)`,- }}- >- {r.level} risk- </span>- {r.is_fix && (- <Badge variant="outline" title="Classified as a fix change">- fix- </Badge>- )}- </div>- <p className="text-sm text-[var(--color-text-secondary)]">- Estimated defect probability{" "}- <span className="font-semibold text-[var(--color-text-primary)]">- {(r.probability * 100).toFixed(1)}%- </span>- </p>- <div className="flex flex-wrap gap-2 pt-1">- {r.risk_percentile != null && (- <Badge variant="default">- {r.risk_percentile.toFixed(0)}th percentile- </Badge>- )}- {r.review_priority && (- <Badge variant="accent" className="capitalize">- {r.review_priority} review priority- </Badge>- )}- </div>- </div>- </CardContent>- </Card>-- {/* Drivers */}+ <>{drivers.length > 0 && (<Card><CardHeader className="pb-3">@@ -250,7 +271,6 @@ function Report({ report }: { report: RiskRangeReport }) {</Card>)}- {/* Change features */}{featureRows.length > 0 && (<Card><CardHeader className="pb-3">@@ -273,6 +293,295 @@ function Report({ report }: { report: RiskRangeReport }) {</CardContent></Card>)}+ </>+ );+}++// ---------------------------------------------------------------------------+// 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,+}: {+ impact: ChangeImpactReport | null;+ loading: boolean;+ host: WebviewHost;+}) {+ 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>+ );+ }+ if (!impact) return null;++ if (impact.gitUnavailable) {+ return (+ <Card>+ <CardContent className="py-4 text-sm text-[var(--color-text-tertiary)]">+ Enable Git for this workspace to see what your change touches, who+ usually changes it with you, and who could review it.+ </CardContent>+ </Card>+ );+ }++ if (impact.changed.length === 0) {+ return (+ <EmptyState+ icon={<Network className="h-8 w-8" />}+ title="No pending changes"+ description="There are no uncommitted or unpushed changes to analyze. Impact appears here as soon as you edit or commit."+ />+ );+ }++ const blast = impact.blast;+ const downstream = blast?.transitive_affected ?? [];+ const cochanges = groupCochanges(blast?.cochange_warnings ?? []);+ const testGaps = blast?.test_gaps ?? [];+ const reviewers = impact.reviewers;+ const overall = blast?.overall_risk_score ?? null;++ const scopeLabel =+ impact.scope === "branch" ? "uncommitted and unpushed" : "uncommitted";++ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h2 className="text-sm font-semibold text-[var(--color-text-primary)]">+ What this change touches+ </h2>+ <span className="text-xs text-[var(--color-text-tertiary)]">+ {impact.changed.length} {scopeLabel} file{impact.changed.length === 1 ? "" : "s"}+ {overall != null && (+ <>+ {" · "}+ <span className="font-medium text-[var(--color-text-secondary)]">+ impact {overall.toFixed(1)}/10+ </span>+ </>+ )}+ </span>+ </div>++ {downstream.length > 0 && (+ <ImpactCard+ icon={<Network className="h-4 w-4" />}+ title="Downstream of your changes"+ hint="These files depend on what you changed. Verify they still work."+ >+ {downstream.slice(0, 10).map((t) => (+ <PathRow+ key={t.path}+ path={t.path}+ trailing={`depth ${t.depth}`}+ onOpen={() => host.openFile(t.path)}+ />+ ))}+ <MoreRow count={downstream.length - 10} />+ </ImpactCard>+ )}++ {cochanges.length > 0 && (+ <ImpactCard+ icon={<GitPullRequest className="h-4 w-4" />}+ title="Usually changes together"+ hint="History suggests these often change with your edits. Advisory, not a rule."+ >+ {cochanges.slice(0, 8).map((c) => (+ <PathRow+ key={c.partner}+ path={c.partner}+ trailing={`${c.score}×`}+ onOpen={() => host.openFile(c.partner)}+ />+ ))}+ <MoreRow count={cochanges.length - 8} />+ </ImpactCard>+ )}++ {testGaps.length > 0 && (+ <ImpactCard+ icon={<TestTube className="h-4 w-4" />}+ title="Changed without a test"+ hint="These changed files have no associated test file."+ >+ {testGaps.slice(0, 8).map((p) => (+ <PathRow key={p} path={p} onOpen={() => host.openFile(p)} />+ ))}+ <MoreRow count={testGaps.length - 8} />+ </ImpactCard>+ )}++ {reviewers.length > 0 && <Reviewers reviewers={reviewers} host={host} />}</div>);}++function ImpactCard({+ icon,+ title,+ hint,+ children,+}: {+ icon: React.ReactNode;+ title: string;+ hint: string;+ children: React.ReactNode;+}) {+ return (+ <Card>+ <CardHeader className="pb-2">+ <CardTitle className="flex items-center gap-2 text-sm">+ <span className="text-[var(--color-text-tertiary)]">{icon}</span>+ {title}+ </CardTitle>+ <p className="text-xs text-[var(--color-text-tertiary)]">{hint}</p>+ </CardHeader>+ <CardContent className="space-y-0.5">{children}</CardContent>+ </Card>+ );+}++function PathRow({+ path,+ trailing,+ onOpen,+}: {+ path: string;+ trailing?: string;+ onOpen: () => void;+}) {+ const name = path.split("/").pop() || path;+ const dir = path.slice(0, path.length - name.length);+ return (+ <button+ type="button"+ onClick={onOpen}+ title={`Open ${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>+ {trailing && (+ <span className="shrink-0 text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {trailing}+ </span>+ )}+ </button>+ );+}++function MoreRow({ count }: { count: number }) {+ if (count <= 0) return null;+ return (+ <p className="px-1.5 pt-1 text-xs text-[var(--color-text-tertiary)]">+{count} more</p>+ );+}++function Reviewers({+ reviewers,+ host,+}: {+ reviewers: ChangeImpactReport["reviewers"];+ host: WebviewHost;+}) {+ const top = reviewers.slice(0, 5);+ const copy = () => {+ const text = top+ .map((r) => (r.email ? `${r.name} <${r.email}>` : r.name))+ .join(", ");+ host.copyText(`Suggested reviewers: ${text}`, "Reviewers copied to clipboard.");+ };+ const maxScore = top.reduce((m, r) => Math.max(m, r.score), 0);++ return (+ <Card>+ <CardHeader className="flex flex-row items-center justify-between gap-2 pb-2">+ <div>+ <CardTitle className="flex items-center gap-2 text-sm">+ <span className="text-[var(--color-text-tertiary)]">+ <Users className="h-4 w-4" />+ </span>+ Suggested reviewers+ </CardTitle>+ <p className="text-xs text-[var(--color-text-tertiary)]">+ Ranked by ownership and co-change history of the changed files.+ </p>+ </div>+ <Button variant="outline" size="sm" onClick={copy}>+ <Copy className="h-3.5 w-3.5" />+ Copy+ </Button>+ </CardHeader>+ <CardContent className="space-y-2.5">+ {top.map((r) => {+ const pct = maxScore > 0 ? (r.score / maxScore) * 100 : 0;+ return (+ <div key={r.email ?? r.name} className="space-y-1">+ <div className="flex items-center justify-between gap-3 text-sm">+ <span className="min-w-0 truncate font-medium text-[var(--color-text-primary)]">+ {r.name}+ </span>+ <span className="shrink-0 text-xs text-[var(--color-text-tertiary)]">+ {r.recent_commits} recent commit{r.recent_commits === 1 ? "" : "s"}+ </span>+ </div>+ <div className="h-1.5 overflow-hidden rounded-full bg-[var(--color-bg-elevated)]">+ <div+ className="h-full rounded-full bg-[var(--color-accent-primary)]"+ style={{ width: `${pct}%` }}+ />+ </div>+ {r.reasons.length > 0 && (+ <p className="truncate text-xs text-[var(--color-text-tertiary)]">+ {r.reasons.join(" · ")}+ </p>+ )}+ </div>+ );+ })}+ </CardContent>+ </Card>+ );+}diff --git a/packages/vscode/webview/src/views/settings/App.test.tsx b/packages/vscode/webview/src/views/settings/App.test.tsxindex 0dde0a0f1..0d57ffd9d 100644--- a/packages/vscode/webview/src/views/settings/App.test.tsx+++ b/packages/vscode/webview/src/views/settings/App.test.tsx@@ -22,6 +22,8 @@ const DEFAULTS: SettingsValues = {"server.port": null,"cliPath": "","risk.baseBranch": "",+ "changeIntel.cochangeNudge": true,+ "changeIntel.cochangeMinScore": 4,};/** Host whose updateSetting echoes the merged map back, like the real one. */