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): editor-native signals - diagnostics, trees, branch risk, refactoring lens, docs (#644)
Raghav Chamadiya1c0786f6d3d8
diff --git a/package-lock.json b/package-lock.jsonindex 9ba8fb0e7..3ae9523ff 100644--- a/package-lock.json+++ b/package-lock.json@@ -19139,6 +19139,7 @@"devDependencies": {"@repowise-dev/api-client": "*","@repowise-dev/types": "*",+ "@repowise-dev/ui": "*","@types/mocha": "^10.0.0","@types/node": "^20","@types/vscode": "~1.101.0",diff --git a/packages/api-client/package.json b/packages/api-client/package.jsonindex ffc3905ed..b9b964a82 100644--- a/packages/api-client/package.json+++ b/packages/api-client/package.json@@ -34,6 +34,7 @@"./providers": "./src/providers.ts","./refactoring": "./src/refactoring.ts","./repos": "./src/repos.ts",+ "./risk": "./src/risk.ts","./search": "./src/search.ts","./security": "./src/security.ts","./stats": "./src/stats.ts",diff --git a/packages/api-client/src/refactoring.ts b/packages/api-client/src/refactoring.tsindex d24db8317..8e8c86aab 100644--- a/packages/api-client/src/refactoring.ts+++ b/packages/api-client/src/refactoring.ts@@ -20,6 +20,8 @@ export interface GenerateCodeOverrides {export interface RefactoringTargetsParams {refactoringType?: string;minConfidence?: string;+ /** Repo-relative path; narrows plans to one file (summary stays global). */+ filePath?: string;}export async function getRefactoringTargets(@@ -29,6 +31,7 @@ export async function getRefactoringTargets(return apiGet<RefactoringTargets>(`/api/repos/${repoId}/refactoring/targets`, {refactoring_type: params.refactoringType,min_confidence: params.minConfidence,+ file_path: params.filePath,});}diff --git a/packages/api-client/src/risk.ts b/packages/api-client/src/risk.tsnew file mode 100644index 000000000..f4f8e95d9--- /dev/null+++ b/packages/api-client/src/risk.ts@@ -0,0 +1,44 @@+/**+ * REST client for the change-risk endpoints.+ * Backend: packages/server/src/repowise/server/routers/git.py (risk/range)+ */++import { apiGet } from "./client";+import type { RiskDriverResponse } from "./types/git";++export interface RiskRangeParams {+ /** Base revision of the comparison (branch name, sha, or ref). */+ base: string;+ /** Head revision; the server defaults to HEAD when omitted. */+ head?: string;+ /**+ * How many recent commits to build the percentile baseline from. 0 skips+ * the percentile (risk_percentile and review_priority come back null).+ */+ baseline?: number;+}++export interface RiskRangeResponse {+ base: string;+ head: string;+ score: number;+ probability: number;+ level: string;+ risk_percentile: number | null;+ review_priority: string | null;+ is_fix: boolean;+ features: Record<string, number | null>;+ drivers: RiskDriverResponse[];+}++/** Scores the aggregate diff between two revisions (0-10, with drivers). */+export async function getRiskRange(+ repoId: string,+ params: RiskRangeParams,+): Promise<RiskRangeResponse> {+ return apiGet<RiskRangeResponse>(`/api/repos/${repoId}/risk/range`, {+ base: params.base,+ head: params.head,+ baseline: params.baseline,+ });+}diff --git a/packages/server/src/repowise/server/routers/refactoring.py b/packages/server/src/repowise/server/routers/refactoring.pyindex 662f09565..8e55c4a47 100644--- a/packages/server/src/repowise/server/routers/refactoring.py+++ b/packages/server/src/repowise/server/routers/refactoring.py@@ -167,14 +167,18 @@ async def get_refactoring_targets(description="Filter to one type: extract_class | extract_helper | move_method | break_cycle",),min_confidence: str | None = Query(None, description="low | medium | high"),+ file_path: str | None = Query(+ None, description="Filter plans to one repo-relative file path"+ ),session: AsyncSession = Depends(get_db_session),) -> RefactoringTargetsResponse:- """Ranked refactoring plans for the repo, filterable by type and confidence.+ """Ranked refactoring plans for the repo, filterable by type, confidence,+ and file.- The summary ignores the *type* filter (so the per-type chips always show- every type's total, even while one type is selected) but does honor- *min_confidence* — so the summary and the plan list stay consistent under a- confidence filter.+ The summary ignores the *type* and *file* filters (so the per-type chips+ always show every type's total, even while one type is selected) but does+ honor *min_confidence* — so the summary and the plan list stay consistent+ under a confidence filter."""centrality = await _centrality_map(session, repo_id)@@ -199,6 +203,8 @@ async def get_refactoring_targets(if refactoring_type is Noneelse [r for r in all_rows if r.refactoring_type == refactoring_type])+ if file_path is not None:+ rows = [r for r in rows if r.file_path == file_path]suggestions = [_row_to_suggestion(r) for r in rows]ranked = rank_suggestions(suggestions, centrality=centrality)return RefactoringTargetsResponse(diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 65b5ae3e9..8c95b6f73 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -32,6 +32,7 @@"./dead-code": "./src/dead-code/index.ts","./dead-code/*": "./src/dead-code/*.tsx","./health": "./src/health/index.ts",+ "./health/ai-prompt-builder": "./src/health/ai-prompt-builder.ts","./health/*": "./src/health/*.tsx","./coupling": "./src/coupling/index.ts","./coupling/*": "./src/coupling/*.tsx",@@ -70,6 +71,7 @@"./blast-radius": "./src/blast-radius/index.ts","./blast-radius/*": "./src/blast-radius/*.tsx","./refactoring": "./src/refactoring/index.ts",+ "./refactoring/types": "./src/refactoring/types.ts","./refactoring/*": "./src/refactoring/*.tsx","./c4": "./src/c4/index.ts","./c4/export": "./src/c4/export/index.ts",diff --git a/packages/vscode/esbuild.mjs b/packages/vscode/esbuild.mjsindex 67a629a71..2111f4cff 100644--- a/packages/vscode/esbuild.mjs+++ b/packages/vscode/esbuild.mjs@@ -22,6 +22,12 @@ const options = {format: "cjs",target: "node20",external: ["vscode"],+ // Prefer each dependency's ESM ("module") entry over its CommonJS one so+ // esbuild can tree-shake barrel packages. Without this, a package pulled in+ // for one helper (e.g. lucide-react, reached transitively through a shared+ // UI module) resolves to its non-tree-shakeable CJS bundle and drags its+ // entire icon set into the host bundle.+ mainFields: ["module", "main"],minify: production,sourcemap: !production,logLevel: "info",diff --git a/packages/vscode/package.json b/packages/vscode/package.jsonindex 59bd79d20..bf15e8e9b 100644--- a/packages/vscode/package.json+++ b/packages/vscode/package.json@@ -72,6 +72,58 @@"type": "string","default": "","description": "Absolute path to the repowise CLI executable. Leave empty to use 'repowise' from your PATH."+ },+ "repowise.diagnostics.enabled": {+ "type": "boolean",+ "default": true,+ "description": "Show health findings for visible files in the Problems panel."+ },+ "repowise.diagnostics.minSeverity": {+ "type": "string",+ "enum": ["critical", "high", "medium", "low"],+ "default": "high",+ "description": "Lowest finding severity surfaced in the Problems panel. Lower-severity findings stay visible in the gutter and tree views."+ },+ "repowise.diagnostics.dimensions": {+ "type": "array",+ "items": {+ "type": "string",+ "enum": ["defect", "maintainability", "performance"]+ },+ "default": ["defect", "maintainability", "performance"],+ "description": "Health dimensions included in the Problems panel."+ },+ "repowise.gutterHeat.enabled": {+ "type": "boolean",+ "default": true,+ "description": "Shade the gutter next to lines with health findings in visible editors."+ },+ "repowise.fileDecorations.enabled": {+ "type": "boolean",+ "default": true,+ "description": "Badge the worst-health files in the file explorer."+ },+ "repowise.fileDecorations.maxScore": {+ "type": "number",+ "default": 4,+ "minimum": 0,+ "maximum": 10,+ "description": "Badge files whose defect score is at or below this value."+ },+ "repowise.codeLens.enabled": {+ "type": "boolean",+ "default": true,+ "description": "Show refactoring plan lenses above symbols with a detected refactoring opportunity."+ },+ "repowise.hover.enabled": {+ "type": "boolean",+ "default": true,+ "description": "Show file health, ownership, and decision context on hover."+ },+ "repowise.risk.baseBranch": {+ "type": "string",+ "default": "",+ "description": "Base branch for branch risk scoring. Leave empty to use the repository's default branch."}}},@@ -105,8 +157,38 @@"command": "repowise.checkSetup","title": "Check Setup","category": "Repowise"+ },+ {+ "command": "repowise.checkBranchRisk",+ "title": "Check Branch Risk",+ "category": "Repowise",+ "icon": "$(pulse)"+ },+ {+ "command": "repowise.updateIndex",+ "title": "Update Index",+ "category": "Repowise"+ },+ {+ "command": "repowise.showFileHealth",+ "title": "Show File Health",+ "category": "Repowise"+ },+ {+ "command": "repowise.openDocs",+ "title": "Open Docs for This File",+ "category": "Repowise"}],+ "menus": {+ "scm/title": [+ {+ "command": "repowise.checkBranchRisk",+ "group": "navigation",+ "when": "scmProvider == git && repowise.state == 'ready'"+ }+ ]+ },"viewsContainers": {"activitybar": [{@@ -120,7 +202,33 @@"repowise": [{"id": "repowise.home",- "name": "Overview"+ "name": "Overview",+ "when": "repowise.state != 'ready'"+ },+ {+ "id": "repowise.healthView",+ "name": "Health",+ "when": "repowise.state == 'ready'"+ },+ {+ "id": "repowise.refactoringView",+ "name": "Refactoring",+ "when": "repowise.state == 'ready'"+ },+ {+ "id": "repowise.hotspotsView",+ "name": "Hotspots & Ownership",+ "when": "repowise.state == 'ready'"+ },+ {+ "id": "repowise.deadCodeView",+ "name": "Dead Code",+ "when": "repowise.state == 'ready'"+ },+ {+ "id": "repowise.decisionsView",+ "name": "Decisions",+ "when": "repowise.state == 'ready'"}]},@@ -208,6 +316,7 @@"devDependencies": {"@repowise-dev/api-client": "*","@repowise-dev/types": "*",+ "@repowise-dev/ui": "*","@types/mocha": "^10.0.0","@types/node": "^20","@types/vscode": "~1.101.0",diff --git a/packages/vscode/src/constants.ts b/packages/vscode/src/constants.tsindex 9347137f4..7faf3dade 100644--- a/packages/vscode/src/constants.ts+++ b/packages/vscode/src/constants.ts@@ -23,6 +23,30 @@ export const Commands = {configureMcp: "repowise.configureMcp",runInit: "repowise.runInit",checkSetup: "repowise.checkSetup",+ checkBranchRisk: "repowise.checkBranchRisk",+ updateIndex: "repowise.updateIndex",+ showFileHealth: "repowise.showFileHealth",+ openDocs: "repowise.openDocs",+} as const;++/**+ * Command ids registered at runtime but not surfaced in the palette (they+ * take arguments from a CodeLens or tree item). Not contributed in+ * package.json on purpose.+ */+export const InternalCommands = {+ copyRefactoringPrompt: "repowise.copyRefactoringPrompt",+ openRefactoringPlan: "repowise.openRefactoringPlan",+} as const;++/** Tree view ids, mirrored from package.json `contributes.views`. */+export const Views = {+ home: "repowise.home",+ health: "repowise.healthView",+ refactoring: "repowise.refactoringView",+ hotspots: "repowise.hotspotsView",+ deadCode: "repowise.deadCodeView",+ decisions: "repowise.decisionsView",} as const;/** Context key the welcome views gate on. */diff --git a/packages/vscode/src/core/api.ts b/packages/vscode/src/core/api.tsindex f9ceea881..0b6137687 100644--- a/packages/vscode/src/core/api.ts+++ b/packages/vscode/src/core/api.ts@@ -2,6 +2,7 @@ import * as path from "node:path";import { realpathSync } from "node:fs";import { configureApiClient } from "@repowise-dev/api-client";import { listRepos } from "@repowise-dev/api-client/repos";+import type { RepoResponse } from "@repowise-dev/api-client/types";import type { Logger } from "./log";/** Result of a successful `/health` probe. */@@ -28,11 +29,13 @@ export interface RepowiseApi {*/checkHealth(baseUrl: string, timeoutMs?: number): Promise<HealthResult | null>;/**- * Maps a workspace folder to its indexed repo id by matching `local_path`+ * Maps a workspace folder to its indexed repo by matching `local_path`* against the server's repo list. There is no path-lookup endpoint. Returns- * null when no repo matches or the server is unreachable.+ * null when no repo matches or the server is unreachable. The full repo+ * object is returned because features need more than the id: the indexed+ * `head_commit` (cache tag, staleness) and `default_branch` (risk base).*/- resolveRepoId(repoRoot: string): Promise<string | null>;+ resolveRepo(repoRoot: string): Promise<RepoResponse | null>;}const DEFAULT_HEALTH_TIMEOUT_MS = 800;@@ -85,7 +88,7 @@ export function createApi(log: Logger): RepowiseApi {}},- async resolveRepoId(repoRoot: string): Promise<string | null> {+ async resolveRepo(repoRoot: string): Promise<RepoResponse | null> {if (!baseUrl) return null;try {const target = canonicalPath(repoRoot);@@ -93,9 +96,9 @@ export function createApi(log: Logger): RepowiseApi {const match = repos.find((repo) => repo.local_path && canonicalPath(repo.local_path) === target,);- return match?.id ?? null;+ return match ?? null;} catch (err) {- log.debug(`resolveRepoId failed: ${String(err)}`);+ log.debug(`resolveRepo failed: ${String(err)}`);return null;}},diff --git a/packages/vscode/src/core/bulkHealth.ts b/packages/vscode/src/core/bulkHealth.tsnew file mode 100644index 000000000..c258dabd5--- /dev/null+++ b/packages/vscode/src/core/bulkHealth.ts@@ -0,0 +1,106 @@+import {+ listHealthFiles,+ type HealthFileMetric,+} from "@repowise-dev/api-client/code-health";+import type { RepowiseContext } from "./context";++/**+ * The per-file health scores both editor signals read. A lean projection of+ * `HealthFileMetric`: only the fields the decoration badge and status item+ * render, so callers never depend on the wider metric shape. Nullable score+ * fields stay nullable, since older index payloads predate the split.+ */+export interface FileScores {+ /** Overall surfaced score (equals `defect_score` until a blend decision). */+ score: number;+ defectScore: number | null;+ maintainabilityScore: number | null;+ performanceScore: number | null;+ nloc: number;+ module: string | null;+}++/** In-memory cache key for the bulk files payload; tag is the head commit. */+const CACHE_KEY = "health:files";++/** Server-enforced maximum page size for the files endpoint. */+const PAGE_LIMIT = 2000;++/**+ * In-flight fetches keyed by `repoId:tag`, so concurrent callers (both signals+ * reacting to the same ready/index event) share one request instead of racing+ * duplicate paginations. Cleared when the fetch settles.+ */+const inFlight = new Map<string, Promise<Map<string, FileScores> | null>>();++function toScores(metric: HealthFileMetric): FileScores {+ return {+ score: metric.score,+ defectScore: metric.defect_score ?? null,+ maintainabilityScore: metric.maintainability_score ?? null,+ performanceScore: metric.performance_score ?? null,+ nloc: metric.nloc,+ module: metric.module,+ };+}++/**+ * Pages the health files endpoint until every scored file is collected, keyed+ * by repo-relative forward-slash path. Returns null on any failure so callers+ * degrade quietly instead of throwing.+ */+async function fetchAll(+ ctx: RepowiseContext,+ repoId: string,+): Promise<Map<string, FileScores> | null> {+ try {+ const map = new Map<string, FileScores>();+ let offset = 0;+ for (;;) {+ const page = await listHealthFiles(repoId, { limit: PAGE_LIMIT, offset });+ for (const metric of page.files) {+ map.set(metric.file_path, toScores(metric));+ }+ offset += page.files.length;+ // Stop on an empty page (guards a mismatched total) or once the reported+ // total is covered.+ if (page.files.length === 0 || offset >= page.total) break;+ }+ return map;+ } catch (err) {+ ctx.log.debug(`bulk health fetch failed: ${String(err)}`);+ return null;+ }+}++/**+ * One bulk fetch of per-file scores, shared by the decoration and status+ * signals. Returns null (never throws) when not ready, no repo is resolved, or+ * the request fails. Served from the session cache when the head commit is+ * unchanged, and deduplicated while a fetch is in flight.+ */+export async function getBulkHealth(+ ctx: RepowiseContext,+): Promise<Map<string, FileScores> | null> {+ const repoId = ctx.repoId;+ if (ctx.getExtensionState() !== "ready" || !repoId) return null;++ const tag = ctx.repo?.head_commit ?? "";+ const cached = ctx.cache.get<Map<string, FileScores>>(repoId, CACHE_KEY, tag);+ if (cached) return cached;++ const dedupeKey = `${repoId}:${tag}`;+ const pending = inFlight.get(dedupeKey);+ if (pending) return pending;++ const request = fetchAll(ctx, repoId)+ .then((map) => {+ if (map) ctx.cache.set(repoId, CACHE_KEY, tag, map);+ return map;+ })+ .finally(() => {+ inFlight.delete(dedupeKey);+ });+ inFlight.set(dedupeKey, request);+ return request;+}diff --git a/packages/vscode/src/core/cliRunner.ts b/packages/vscode/src/core/cliRunner.tsindex 8a5d5bace..a4dba132b 100644--- a/packages/vscode/src/core/cliRunner.ts+++ b/packages/vscode/src/core/cliRunner.ts@@ -13,6 +13,20 @@ export interface RunOptions {cwd?: string;/** Kill the process after this many ms. */timeoutMs?: number;+ /**+ * Receives each complete stdout line as it arrives, for commands that+ * stream newline-delimited progress. The full stdout is still collected in+ * the result. Callback errors are swallowed so a bad consumer cannot kill+ * the run.+ */+ onStdoutLine?: (line: string) => void;+ /**+ * Runs immediately instead of waiting in the serialized queue. For+ * long-running streams (an index update can take many minutes) that would+ * otherwise make every queued short call appear frozen. The caller is+ * responsible for its own single-flight guard.+ */+ bypassQueue?: boolean;}/** Structured payload of `repowise doctor --format json`. */@@ -69,8 +83,27 @@ export function createCliRunner(reject(new Error(`CLI timed out after ${timeoutMs}ms`));}, timeoutMs);+ let lineBuffer = "";+ const emitLines = (text: string, flush: boolean): void => {+ const onLine = options.onStdoutLine;+ if (!onLine) return;+ lineBuffer += text;+ const lines = lineBuffer.split(/\r?\n/);+ lineBuffer = flush ? "" : (lines.pop() ?? "");+ for (const line of lines) {+ if (!line) continue;+ try {+ onLine(line);+ } catch (err) {+ log.debug(`stdout line handler failed: ${String(err)}`);+ }+ }+ };+child.stdout.on("data", (chunk: Buffer) => {- stdout += chunk.toString();+ const text = chunk.toString();+ stdout += text;+ emitLines(text, false);});child.stderr.on("data", (chunk: Buffer) => {stderr += chunk.toString();@@ -85,12 +118,15 @@ export function createCliRunner(if (settled) return;settled = true;clearTimeout(timer);+ // A final line without a trailing newline is still a line.+ emitLines("", true);resolve({ code, stdout, stderr });});});}function run(args: string[], options: RunOptions = {}): Promise<CliResult> {+ if (options.bypassQueue) return exec(args, options);// Chain onto the queue so only one child runs at a time. Failures do not// poison the queue: the next call runs regardless.const result = queue.then(diff --git a/packages/vscode/src/core/context.ts b/packages/vscode/src/core/context.tsindex e977223be..bb01aa62a 100644--- a/packages/vscode/src/core/context.ts+++ b/packages/vscode/src/core/context.ts@@ -4,8 +4,13 @@ import type { Logger } from "./log";import type { RepowiseApi } from "./api";import type { RepowiseCache } from "./cache";import type { CliRunner } from "./cliRunner";-import { createFreshnessWatcher, type FreshnessWatcher } from "./freshness";+import {+ createFreshnessWatcher,+ type FreshnessEventKind,+ type FreshnessWatcher,+} from "./freshness";import { detectWorkspace, type WorkspaceInfo } from "./workspace";+import type { RepoResponse } from "@repowise-dev/api-client/types";/*** States the activity-bar welcome content gates on. `ready` shows no special@@ -32,6 +37,15 @@ function createConfig(): RepowiseConfig {};}+/**+ * The subscription surface features receive from `events()`. Deliberately not+ * the watcher itself: the watcher is replaced on workspace rescans, while this+ * surface stays valid for the life of the context.+ */+export interface FreshnessEvents {+ readonly onDidChange: vscode.Event<FreshnessEventKind>;+}+/*** Optional presentation detail for a status-bar state. Only the `connected`* state uses it today, to show the live server version and url in the tooltip.@@ -60,6 +74,14 @@ export class RepowiseContext {readonly config: RepowiseConfig = createConfig();private extensionState: ExtensionState = "no-index";+ private currentRepo: RepoResponse | null = null;+ private readonly stateEmitter = new vscode.EventEmitter<ExtensionState>();+ /**+ * Fires after the extension state settles into a new value (deduplicated).+ * Data features key off `ready`: it guarantees a base URL and, when the+ * server knows this repo, a repo id.+ */+ readonly onDidChangeExtensionState = this.stateEmitter.event;private freshnessWatcher: FreshnessWatcher | null = null;private statusBarSink: (state: StatusBarState, detail?: StatusBarDetail) => void =() => {};@@ -92,36 +114,103 @@ export class RepowiseContext {}/**- * Freshness watchers for the primary repo, created on first use. Returns null- * when no repo root is known. Never call this during activate() to keep cold- * start free of filesystem watching.+ * Stable pipe from whichever filesystem watcher is current. A workspace+ * rescan replaces the watcher, but subscriptions made through `events()`+ * attach here and survive the swap; only the pipe below is rebound.*/- events(): FreshnessWatcher | null {+ private readonly freshnessEmitter = new vscode.EventEmitter<FreshnessEventKind>();+ private freshnessPipe: vscode.Disposable | null = null;+ private readonly freshnessFacade: FreshnessEvents = {+ onDidChange: this.freshnessEmitter.event,+ };++ /**+ * Freshness events for the primary repo; the underlying watcher is created+ * on first use. Returns null when no repo root is known. Never call this+ * during activate() to keep cold start free of filesystem watching.+ */+ events(): FreshnessEvents | null {if (!this.workspaceInfo.repoRoot) return null;if (!this.freshnessWatcher) {this.freshnessWatcher = createFreshnessWatcher(this.workspaceInfo.repoRoot,this.workspaceInfo.workspaceMode ? WORKSPACE_DIR : REPO_DIR,);+ this.freshnessPipe = this.freshnessWatcher.onDidChange((kind) =>+ this.freshnessEmitter.fire(kind),+ );}- return this.freshnessWatcher;+ return this.freshnessFacade;}private disposeFreshness(): void {+ this.freshnessPipe?.dispose();+ this.freshnessPipe = null;this.freshnessWatcher?.dispose();this.freshnessWatcher = null;}/** Updates the welcome-view context key. Cheap; safe to call often. */setExtensionState(next: ExtensionState): void {+ const changed = this.extensionState !== next;this.extensionState = next;+ // The resolved repo is only meaningful while connected; leaving `ready`+ // for any reason (server stop, version floor, workspace change)+ // invalidates it.+ if (next !== "ready") this.currentRepo = null;void vscode.commands.executeCommand("setContext", STATE_CONTEXT_KEY, next);+ if (changed) this.stateEmitter.fire(next);}getExtensionState(): ExtensionState {return this.extensionState;}+ /**+ * The server's record of the primary repo, resolved by the server manager+ * on connect (null while disconnected or when the server does not index+ * this workspace). Set before the state flips to `ready`, so a `ready`+ * listener can read it synchronously. Carries the indexed `head_commit`+ * (the cache/staleness tag) and `default_branch` (the risk base).+ */+ get repo(): RepoResponse | null {+ return this.currentRepo;+ }++ get repoId(): string | null {+ return this.currentRepo?.id ?? null;+ }++ setRepo(repo: RepoResponse | null): void {+ this.currentRepo = repo;+ }++ private repoRefresh: Promise<RepoResponse | null> | null = null;++ /**+ * Re-resolves the repo record from the server so `head_commit` reflects a+ * just-finished index update. Single-flight: concurrent callers (several+ * features reacting to the same freshness event) share one request. Keeps+ * the last known record when the server is unreachable mid-refresh.+ */+ refreshRepo(): Promise<RepoResponse | null> {+ if (this.repoRefresh) return this.repoRefresh;+ const root = this.workspaceInfo.repoRoot;+ if (!root || this.extensionState !== "ready") {+ return Promise.resolve(this.currentRepo);+ }+ this.repoRefresh = this.api+ .resolveRepo(root)+ .then((repo) => {+ if (repo) this.setRepo(repo);+ return this.currentRepo;+ })+ .finally(() => {+ this.repoRefresh = null;+ });+ return this.repoRefresh;+ }+/** Routes a state to the status bar feature, if it has registered a sink. */setStatusBarState(next: StatusBarState, detail?: StatusBarDetail): void {this.statusBarSink(next, detail);@@ -134,5 +223,7 @@ export class RepowiseContext {dispose(): void {this.disposeFreshness();+ this.freshnessEmitter.dispose();+ this.stateEmitter.dispose();}}diff --git a/packages/vscode/src/core/fileSignals.ts b/packages/vscode/src/core/fileSignals.tsnew file mode 100644index 000000000..c4e83fdd1Binary files /dev/null and b/packages/vscode/src/core/fileSignals.ts differdiff --git a/packages/vscode/src/core/freshness.ts b/packages/vscode/src/core/freshness.tsindex b27a1ffe2..b47d18bbe 100644--- a/packages/vscode/src/core/freshness.ts+++ b/packages/vscode/src/core/freshness.ts@@ -59,9 +59,19 @@ export function createFreshnessWatcher(new vscode.RelativePattern(repoRoot, `${markerDir}/**`),);const onIndexEvent = (uri: vscode.Uri): void => {- emitDebounced(- uri.path.endsWith(LOCKFILE_NAME) ? "lockfileChanged" : "indexChanged",- );+ const base = uri.path.slice(uri.path.lastIndexOf("/") + 1);+ if (base === LOCKFILE_NAME) {+ emitDebounced("lockfileChanged");+ return;+ }+ // Only deliberate update artifacts count as "the index changed". The+ // marker dir also churns on every served READ (SQLite WAL checkpoints+ // rewrite the db as request connections close), and treating that churn+ // as a change creates a feedback loop: fetch -> db write -> event ->+ // refetch, pinning the extension host.+ if (base === "state.json" || base === ".update.log") {+ emitDebounced("indexChanged");+ }};indexWatcher.onDidChange(onIndexEvent);indexWatcher.onDidCreate(onIndexEvent);diff --git a/packages/vscode/src/core/gitApi.ts b/packages/vscode/src/core/gitApi.tsnew file mode 100644index 000000000..6fe5077d6--- /dev/null+++ b/packages/vscode/src/core/gitApi.ts@@ -0,0 +1,124 @@+import * as vscode from "vscode";++/**+ * Guarded adapter over the built-in `vscode.git` extension. We deliberately do+ * NOT declare an extensionDependency on it, so every path here degrades to+ * null / a no-op when git is missing, disabled, or not yet initialized. Callers+ * fall back to reading `.git/HEAD` directly when this returns null.+ *+ * Only the members actually used are typed below; the full `git.d.ts` surface is+ * intentionally not vendored.+ */++/** `onDidChangeState` values reported by the git API. */+type APIState = "uninitialized" | "initialized";++interface Branch {+ readonly name?: string;+ readonly commit?: string;+}++interface RepositoryState {+ readonly HEAD?: Branch;+ readonly onDidChange: vscode.Event<void>;+}++interface Repository {+ readonly state: RepositoryState;+}++interface GitAPI {+ readonly state: APIState;+ readonly onDidChangeState: vscode.Event<APIState>;+ getRepository(uri: vscode.Uri): Repository | null;+}++interface GitExtension {+ readonly enabled: boolean;+ getAPI(version: 1): GitAPI;+}++/**+ * Resolves the git API, or null when unavailable. Checks `enabled` BEFORE+ * `getAPI(1)`, because `getAPI` throws "Git model not found" when+ * `git.enabled` is false. Waits for the API to reach `initialized` so an+ * early call does not read an empty repository set.+ */+async function getApi(): Promise<GitAPI | null> {+ try {+ const ext = vscode.extensions.getExtension<GitExtension>("vscode.git");+ if (!ext) return null;+ const exports = ext.isActive ? ext.exports : await ext.activate();+ if (!exports.enabled) return null;+ const api = exports.getAPI(1);+ if (api.state === "initialized") return api;+ return await waitForInitialized(api);+ } catch {+ return null;+ }+}++/** Resolves once the API reports `initialized`, or null after a short wait. */+function waitForInitialized(api: GitAPI): Promise<GitAPI | null> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ sub.dispose();+ resolve(null);+ }, 5_000);+ const sub = api.onDidChangeState((state) => {+ if (state !== "initialized") return;+ clearTimeout(timer);+ sub.dispose();+ resolve(api);+ });+ });+}++/** Resolves the repository for a root, or null when git cannot serve it. */+async function getRepository(repoRoot: string): Promise<Repository | null> {+ const api = await getApi();+ if (!api) return null;+ try {+ return api.getRepository(vscode.Uri.file(repoRoot));+ } catch {+ return null;+ }+}++/** Current branch name, or null when detached, unavailable, or git is off. */+export async function getCurrentBranchName(+ repoRoot: string,+): Promise<string | null> {+ const repo = await getRepository(repoRoot);+ return repo?.state.HEAD?.name ?? null;+}++/** Checked-out commit sha, or null when unavailable or git is off. */+export async function getHeadCommit(repoRoot: string): Promise<string | null> {+ const repo = await getRepository(repoRoot);+ return repo?.state.HEAD?.commit ?? null;+}++/**+ * Invokes `cb` when the repository's HEAD name or commit changes. Returns a+ * disposable, or a no-op disposable when git is unavailable. The underlying+ * `state.onDidChange` fires on any repository change, so we filter to HEAD+ * transitions to avoid waking callers on unrelated working-tree events.+ */+export async function onDidChangeHead(+ repoRoot: string,+ cb: () => void,+): Promise<vscode.Disposable> {+ const repo = await getRepository(repoRoot);+ if (!repo) return { dispose: () => {} };+ let lastName = repo.state.HEAD?.name;+ let lastCommit = repo.state.HEAD?.commit;+ return repo.state.onDidChange(() => {+ const name = repo.state.HEAD?.name;+ const commit = repo.state.HEAD?.commit;+ if (name === lastName && commit === lastCommit) return;+ lastName = name;+ lastCommit = commit;+ cb();+ });+}diff --git a/packages/vscode/src/core/plans.ts b/packages/vscode/src/core/plans.tsnew file mode 100644index 000000000..0d22c4ec1--- /dev/null+++ b/packages/vscode/src/core/plans.ts@@ -0,0 +1,54 @@+import { getRefactoringTargets } from "@repowise-dev/api-client/refactoring";+import type { RefactoringPlan } from "@repowise-dev/ui/refactoring/types";+import type { RepowiseContext } from "./context";++/**+ * Per-file refactoring-plan fetcher shared by the CodeLens provider and any+ * other feature that needs the deterministic plans for one file. Uses the+ * server-side `filePath` filter so the response is already scoped to the file;+ * caches under the head-commit tag and dedupes concurrent requests for the same+ * (repo, commit, file) so several editors opening the same file issue one call.+ */++const inFlight = new Map<string, Promise<RefactoringPlan[]>>();++/**+ * Plans for `relPath` (repo-relative, forward slashes). Returns [] when no repo+ * is resolved or the request fails; never throws, so a lens provider can await+ * it inline. Results are cached per head commit; a reindex changes the tag and+ * the stale entry is simply never read again.+ */+export async function getPlansForFile(+ ctx: RepowiseContext,+ relPath: string,+): Promise<RefactoringPlan[]> {+ const repoId = ctx.repoId;+ if (!repoId) return [];++ const tag = ctx.repo?.head_commit ?? "";+ const key = `plans:file:${relPath}`;++ const cached = ctx.cache.get<RefactoringPlan[]>(repoId, key, tag);+ if (cached) return cached;++ const dedupeKey = `${repoId} ${tag} ${key}`;+ const existing = inFlight.get(dedupeKey);+ if (existing) return existing;++ const request = getRefactoringTargets(repoId, { filePath: relPath })+ .then((targets) => {+ const plans = targets.plans ?? [];+ ctx.cache.set(repoId, key, tag, plans);+ return plans;+ })+ .catch((err) => {+ ctx.log.debug(`getPlansForFile(${relPath}) failed: ${String(err)}`);+ return [];+ })+ .finally(() => {+ inFlight.delete(dedupeKey);+ });++ inFlight.set(dedupeKey, request);+ return request;+}diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.tsindex 0c295c77c..78cab2d46 100644--- a/packages/vscode/src/extension.ts+++ b/packages/vscode/src/extension.ts@@ -11,6 +11,16 @@ import { registerStatusBar } from "./features/statusBar";import { registerOnboarding } from "./features/onboarding";import { registerServerManager } from "./features/serverManager";import { registerMcp } from "./features/mcp";+import { registerDiagnostics } from "./features/diagnostics";+import { registerGutterHeat } from "./features/gutterHeat";+import { registerHovers } from "./features/hovers";+import { registerFileDecorations } from "./features/fileDecorations";+import { registerFileScoreStatus } from "./features/fileScoreStatus";+import { registerTrees } from "./features/trees";+import { registerBranchRisk } from "./features/branchRisk";+import { registerStaleness } from "./features/staleness";+import { registerRefactoringLens } from "./features/refactoringLens";+import { registerDocs } from "./features/docs";let rootContext: RepowiseContext | undefined;@@ -61,12 +71,24 @@ export function activate(extCtx: vscode.ExtensionContext): void {vscode.commands.registerCommand(Commands.checkSetup, () => checkSetup(ctx)),);- // Features. Each returns a Disposable and owns its own commands.+ // Features. Each returns a Disposable and owns its own commands. All data+ // features are event-driven: registration only wires providers and+ // listeners; nothing fetches until a surface becomes visible while ready.extCtx.subscriptions.push(registerStatusBar(ctx),registerOnboarding(ctx),registerServerManager(ctx),registerMcp(ctx),+ registerDiagnostics(ctx),+ registerGutterHeat(ctx),+ registerHovers(ctx),+ registerFileDecorations(ctx),+ registerFileScoreStatus(ctx),+ registerTrees(ctx),+ registerBranchRisk(ctx),+ registerStaleness(ctx),+ registerRefactoringLens(ctx),+ registerDocs(ctx),);// Workspace-folder changes are handled by the server manager, which ownsdiff --git a/packages/vscode/src/features/branchRisk.ts b/packages/vscode/src/features/branchRisk.tsnew file mode 100644index 000000000..90d238eab--- /dev/null+++ b/packages/vscode/src/features/branchRisk.ts@@ -0,0 +1,169 @@+import * as vscode from "vscode";+import { ApiClientError } from "@repowise-dev/api-client";+import { getRiskRange } from "@repowise-dev/api-client/risk";+import type { RiskRangeResponse } from "@repowise-dev/api-client/risk";+import { CONFIG_SECTION, Commands } from "../constants";+import type { RepowiseContext } from "../core/context";+import { getCurrentBranchName } from "../core/gitApi";++/** Virtual-document scheme the rendered risk report is served on. */+const RISK_SCHEME = "repowise-risk";+/** Fixed virtual-document path; its basename becomes the preview title. */+const RISK_URI = vscode.Uri.parse(`${RISK_SCHEME}:/Branch Risk.md`);++/** Human-readable names for the raw change features the endpoint returns. */+const FEATURE_LABELS: ReadonlyArray<readonly [string, string]> = [+ ["la", "Lines added"],+ ["ld", "Lines deleted"],+ ["nf", "Files changed"],+ ["nd", "Directories changed"],+ ["ns", "Subsystems changed"],+ ["entropy", "Change entropy"],+ ["exp", "Author experience"],+];++/**+ * Scores the working branch against a base and renders the result as a markdown+ * preview. Bound to the palette command and the SCM title button (both call+ * `Commands.checkBranchRisk`). No caching: risk reflects the working HEAD, so+ * each invocation fetches fresh.+ */+export function registerBranchRisk(ctx: RepowiseContext): vscode.Disposable {+ let content = "";+ const changeEmitter = new vscode.EventEmitter<vscode.Uri>();++ const provider: vscode.TextDocumentContentProvider = {+ onDidChange: changeEmitter.event,+ provideTextDocumentContent: () => content,+ };++ async function run(): Promise<void> {+ if (ctx.getExtensionState() !== "ready") {+ void vscode.window.showWarningMessage(+ "Connect to the Repowise server before scoring branch risk.",+ );+ return;+ }+ const repoId = ctx.repoId;+ if (!repoId) {+ void vscode.window.showWarningMessage(+ "This repository is not indexed by the Repowise server.",+ );+ return;+ }++ // Base resolution: explicit setting, else the server's default branch,+ // else "main". An empty setting means "auto".+ const configured = vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<string>("risk.baseBranch", "")+ .trim();+ const base = configured || ctx.repo?.default_branch || "main";++ const result = await vscode.window.withProgress(+ {+ location: vscode.ProgressLocation.Notification,+ title: `Scoring branch risk against ${base}`,+ },+ async (): Promise<RiskRangeResponse | null> => {+ try {+ return await getRiskRange(repoId, { base, head: "HEAD" });+ } catch (err) {+ if (err instanceof ApiClientError) {+ // The server rev-parses inputs and returns 400 on an unknown rev.+ void vscode.window.showWarningMessage(+ `Could not score branch risk: ${err.detail}`,+ );+ return null;+ }+ ctx.log.error(`branch risk failed: ${String(err)}`);+ void vscode.window.showWarningMessage(+ "Could not score branch risk. See the Repowise log for details.",+ );+ return null;+ }+ },+ );+ if (!result) return;++ const branch = await getCurrentBranchName(ctx.workspace.repoRoot ?? "");+ content = renderReport(result, base, branch);+ changeEmitter.fire(RISK_URI);+ // Ensure the preview re-reads the updated content on a repeat invocation.+ await vscode.workspace.openTextDocument(RISK_URI);+ await vscode.commands.executeCommand("markdown.showPreview", RISK_URI);+ }++ const disposables: vscode.Disposable[] = [+ vscode.workspace.registerTextDocumentContentProvider(RISK_SCHEME, provider),+ vscode.commands.registerCommand(Commands.checkBranchRisk, () => void run()),+ changeEmitter,+ ];++ return {+ dispose(): void {+ for (const d of disposables) d.dispose();+ },+ };+}++/** Formats a contribution with an explicit sign (positive raises risk). */+function signed(value: number): string {+ return `${value >= 0 ? "+" : ""}${value.toFixed(2)}`;+}++/** Builds the markdown body for a scored range. */+function renderReport(+ r: RiskRangeResponse,+ base: string,+ branch: string | null,+): string {+ const lines: string[] = [];+ const head = branch ?? "HEAD";++ lines.push(`# Branch risk: ${r.score.toFixed(1)}/10 (${r.level})`);+ lines.push("");+ lines.push(`\`${head}\` vs \`${base}\``);+ lines.push("");+ lines.push(`- Defect probability: ${(r.probability * 100).toFixed(1)}%`);+ if (r.risk_percentile !== null) {+ // Served as 0-100 already, not a fraction.+ lines.push(`- Risk percentile: ${r.risk_percentile.toFixed(0)}%`);+ }+ if (r.review_priority !== null) {+ lines.push(`- Review priority: ${r.review_priority}`);+ }+ if (r.is_fix) {+ lines.push("- Classified as a fix change.");+ }++ if (r.drivers.length > 0) {+ lines.push("");+ lines.push("## Drivers");+ lines.push("");+ const ordered = [...r.drivers].sort(+ (a, b) => Math.abs(b.contribution) - Math.abs(a.contribution),+ );+ for (const d of ordered) {+ lines.push(`- ${d.label}: ${signed(d.contribution)}`);+ }+ }++ // A feature can be null (author experience on shallow history); skip those.+ const featureRows = FEATURE_LABELS.filter(+ ([key]) => key in r.features && r.features[key] != null,+ );+ if (featureRows.length > 0) {+ lines.push("");+ lines.push("## Features");+ lines.push("");+ lines.push("| Feature | Value |");+ lines.push("| --- | --- |");+ for (const [key, label] of featureRows) {+ lines.push(`| ${label} | ${r.features[key]} |`);+ }+ }++ lines.push("");+ return lines.join("\n");+}diff --git a/packages/vscode/src/features/diagnostics.ts b/packages/vscode/src/features/diagnostics.tsnew file mode 100644index 000000000..f11bd6c70--- /dev/null+++ b/packages/vscode/src/features/diagnostics.ts@@ -0,0 +1,164 @@+import * as vscode from "vscode";+import { CONFIG_SECTION } from "../constants";+import type { RepowiseContext } from "../core/context";+import { getFileFindings, repoRelativePath } from "../core/fileSignals";+import type { HealthDimension, HealthFinding, HealthSeverity } from "@repowise-dev/types/health";++/** Severity ordering, high number = more severe, for the minSeverity floor. */+const SEVERITY_RANK: Record<HealthSeverity, number> = {+ low: 0,+ medium: 1,+ high: 2,+ critical: 3,+};++const DEFAULT_DIMENSIONS: HealthDimension[] = [+ "defect",+ "maintainability",+ "performance",+];++/** Config keys this feature reacts to, for the configuration-change filter. */+const CONFIG_PREFIX = `${CONFIG_SECTION}.diagnostics`;++/** Maps a finding severity to a diagnostic severity, capped at Warning. */+function toDiagnosticSeverity(severity: HealthSeverity): vscode.DiagnosticSeverity {+ switch (severity) {+ case "critical":+ case "high":+ return vscode.DiagnosticSeverity.Warning;+ case "medium":+ return vscode.DiagnosticSeverity.Information;+ case "low":+ return vscode.DiagnosticSeverity.Hint;+ }+}++/** Line span (1-based, inclusive) to a 0-based range; null lines anchor at top. */+function rangeFor(finding: HealthFinding): vscode.Range {+ if (finding.line_start == null) return new vscode.Range(0, 0, 0, 0);+ const start = Math.max(0, finding.line_start - 1);+ const end = Math.max(start, (finding.line_end ?? finding.line_start) - 1);+ return new vscode.Range(start, 0, end, Number.MAX_SAFE_INTEGER);+}++/**+ * Publishes health findings for visible editors into the Problems panel. Only+ * findings at or above the configured severity floor and within the configured+ * dimensions surface; the deeper set stays in the gutter. Work is confined to+ * visible editors, and a file is only republished when its finding set changes.+ */+export function registerDiagnostics(ctx: RepowiseContext): vscode.Disposable {+ const collection = vscode.languages.createDiagnosticCollection("repowise");+ const disposables: vscode.Disposable[] = [collection];++ /** Last published finding-set signature per document URI, for diff-only set. */+ const signatures = new Map<string, string>();+ /** Lazily created freshness subscription, so activate() does no watching. */+ let watcherSub: vscode.Disposable | null = null;++ const cfg = () => vscode.workspace.getConfiguration(CONFIG_SECTION);+ const enabled = (): boolean => cfg().get<boolean>("diagnostics.enabled", true);+ const minSeverity = (): HealthSeverity =>+ cfg().get<HealthSeverity>("diagnostics.minSeverity", "high");+ const dimensions = (): Set<string> =>+ new Set(cfg().get<string[]>("diagnostics.dimensions", DEFAULT_DIMENSIONS));++ function clearAll(): void {+ collection.clear();+ signatures.clear();+ }++ /** Diff-only publish: skips the set when the file's finding set is unchanged. */+ function publish(doc: vscode.TextDocument, findings: HealthFinding[]): void {+ const floor = SEVERITY_RANK[minSeverity()];+ const dims = dimensions();+ const filtered = findings.filter(+ (f) =>+ SEVERITY_RANK[f.severity] >= floor && dims.has(f.dimension ?? "defect"),+ );++ const signature = filtered+ .map((f) => `${f.id}:${f.line_start}:${f.line_end}:${f.severity}`)+ .sort()+ .join("|");+ const uriKey = doc.uri.toString();+ if (signatures.get(uriKey) === signature) return;+ signatures.set(uriKey, signature);++ const diagnostics = filtered.map((f) => {+ const diagnostic = new vscode.Diagnostic(+ rangeFor(f),+ f.reason,+ toDiagnosticSeverity(f.severity),+ );+ diagnostic.source = "repowise";+ diagnostic.code = f.biomarker_type;+ return diagnostic;+ });+ collection.set(doc.uri, diagnostics);+ }++ async function refreshAll(): Promise<void> {+ if (!enabled() || ctx.getExtensionState() !== "ready" || !ctx.repoId) {+ clearAll();+ return;+ }++ const editors = vscode.window.visibleTextEditors;+ const visible = new Set<string>();+ for (const editor of editors) {+ const rel = repoRelativePath(ctx, editor.document.uri);+ if (!rel) continue;+ visible.add(editor.document.uri.toString());+ const findings = await getFileFindings(ctx, rel);+ // State or config may have changed across the await; re-check before set.+ if (!enabled() || ctx.getExtensionState() !== "ready") return;+ publish(editor.document, findings);+ }++ // Drop entries for documents that are no longer visible.+ for (const uriKey of [...signatures.keys()]) {+ if (!visible.has(uriKey)) {+ collection.delete(vscode.Uri.parse(uriKey));+ signatures.delete(uriKey);+ }+ }+ }++ /** Subscribe to index-change events for this repo, once, while ready. */+ function ensureWatcher(): void {+ if (watcherSub) return;+ const watcher = ctx.events();+ if (!watcher) return;+ watcherSub = watcher.onDidChange((kind) => {+ if (kind !== "indexChanged") return;+ // A finished index update re-stamps head_commit; re-resolve it so the+ // next fetch caches under the new tag, then recompute visible editors.+ void ctx.refreshRepo().then(() => refreshAll());+ });+ disposables.push(watcherSub);+ }++ disposables.push(+ ctx.onDidChangeExtensionState((state) => {+ if (state === "ready") {+ ensureWatcher();+ void refreshAll();+ } else {+ clearAll();+ }+ }),+ vscode.window.onDidChangeVisibleTextEditors(() => void refreshAll()),+ vscode.workspace.onDidChangeConfiguration((event) => {+ if (event.affectsConfiguration(CONFIG_PREFIX)) void refreshAll();+ }),+ );++ if (ctx.getExtensionState() === "ready") {+ ensureWatcher();+ void refreshAll();+ }++ return vscode.Disposable.from(...disposables);+}diff --git a/packages/vscode/src/features/docs.ts b/packages/vscode/src/features/docs.tsnew file mode 100644index 000000000..c346d1535--- /dev/null+++ b/packages/vscode/src/features/docs.ts@@ -0,0 +1,102 @@+import * as vscode from "vscode";+import { getFileDetail } from "@repowise-dev/api-client/files";+import { Commands } from "../constants";+import type { RepowiseContext } from "../core/context";+import { repoRelativePath } from "../core/fileSignals";++/** Virtual-document scheme for the rendered wiki page preview. */+const DOCS_SCHEME = "repowise-docs";++/**+ * Docs command: renders the wiki page for the active editor's file. The page+ * body ships inline on the file-detail aggregate, so one request maps a+ * repo-relative path to its content. The rendered markdown is cached per file+ * under the head-commit tag and shown as a markdown preview.+ */+export function registerDocs(ctx: RepowiseContext): vscode.Disposable {+ // Rendered page markdown, keyed by virtual-doc uri, for this session.+ const docContent = new Map<string, string>();+ const contentProvider: vscode.TextDocumentContentProvider = {+ provideTextDocumentContent: (uri) => docContent.get(uri.toString()) ?? "",+ };++ return vscode.Disposable.from(+ vscode.workspace.registerTextDocumentContentProvider(DOCS_SCHEME, contentProvider),+ vscode.commands.registerCommand(Commands.openDocs, () => openDocs(ctx, docContent)),+ );+}++async function openDocs(+ ctx: RepowiseContext,+ docContent: Map<string, string>,+): Promise<void> {+ const editor = vscode.window.activeTextEditor;+ if (!editor) {+ void vscode.window.showInformationMessage("Open a file to see its Repowise docs.");+ return;+ }++ const relPath = repoRelativePath(ctx, editor.document.uri);+ if (!relPath) {+ void vscode.window.showInformationMessage(+ "This file is not part of the indexed repository.",+ );+ return;+ }++ if (ctx.getExtensionState() !== "ready" || !ctx.repoId) {+ void vscode.window.showInformationMessage(+ "Start the Repowise server to load docs for this file.",+ );+ return;+ }++ const repoId = ctx.repoId;+ const tag = ctx.repo?.head_commit ?? "";+ const key = `docs:${relPath}`;++ let markdown = ctx.cache.get<string>(repoId, key, tag);+ if (markdown === undefined) {+ let rendered: string | null;+ try {+ const detail = await getFileDetail(repoId, relPath);+ rendered = detail.wiki_page ? renderPage(detail.wiki_page) : null;+ } catch (err) {+ ctx.log.error(`openDocs(${relPath}) failed: ${String(err)}`);+ void vscode.window.showErrorMessage(+ "Could not load docs for this file. See the Repowise log for details.",+ );+ return;+ }+ if (rendered === null) {+ void vscode.window.showInformationMessage("No docs indexed for this file.");+ return;+ }+ markdown = rendered;+ ctx.cache.set(repoId, key, tag, markdown);+ }++ // Tag the uri with the head commit so a reindex yields a fresh preview rather+ // than a stale cached render.+ const uri = vscode.Uri.from({+ scheme: DOCS_SCHEME,+ path: `/${relPath}.md`,+ query: tag,+ });+ docContent.set(uri.toString(), markdown);+ await vscode.commands.executeCommand("markdown.showPreview", uri);+}++/** Wiki page as markdown, with any human-curated note quoted above the body. */+function renderPage(page: {+ content: string;+ human_notes: string | null;+}): string {+ const notes = page.human_notes?.trim();+ if (!notes) return page.content;+ const quoted = notes+ .split("\n")+ .map((line) => `> ${line}`)+ .join("\n");+ return `${quoted}\n\n${page.content}`;+}diff --git a/packages/vscode/src/features/fileDecorations.ts b/packages/vscode/src/features/fileDecorations.tsnew file mode 100644index 000000000..aa5c93ba1--- /dev/null+++ b/packages/vscode/src/features/fileDecorations.ts@@ -0,0 +1,117 @@+import * as vscode from "vscode";+import { CONFIG_SECTION } from "../constants";+import { getBulkHealth, type FileScores } from "../core/bulkHealth";+import type { RepowiseContext } from "../core/context";+import { repoRelativePath } from "../core/fileSignals";++/** Single-glyph badge for worst-tier files (FileDecoration badge max is 2). */+const BADGE = "!";++/**+ * Badges the worst-health files in the explorer. Quiet by default: only files+ * at or below the configured defect-score threshold are decorated, and the+ * whole provider output is gated by a setting. Decoration lookups are+ * synchronous against an in-memory map; the bulk fetch is kicked lazily and the+ * decorations refresh when it lands.+ */+export function registerFileDecorations(ctx: RepowiseContext): vscode.Disposable {+ const emitter = new vscode.EventEmitter<undefined>();+ const errorColor = new vscode.ThemeColor("list.errorForeground");++ /** Loaded scores, keyed by repo-relative forward-slash path; null until fetched. */+ let scores: Map<string, FileScores> | null = null;+ /** Guards against overlapping background fetches. */+ let loading = false;+ /** Lazily created freshness subscription, so activate() does no watching. */+ let watcherSub: vscode.Disposable | null = null;++ const read = (): vscode.WorkspaceConfiguration =>+ vscode.workspace.getConfiguration(CONFIG_SECTION);+ const isEnabled = (): boolean => read().get<boolean>("fileDecorations.enabled", true);+ const maxScore = (): number => read().get<number>("fileDecorations.maxScore", 4);++ /** Starts the shared bulk fetch once while ready; refreshes decorations on land. */+ function kick(): void {+ if (loading || scores) return;+ if (ctx.getExtensionState() !== "ready" || !ctx.repoId) return;+ loading = true;+ void getBulkHealth(ctx).then((map) => {+ loading = false;+ if (map) {+ scores = map;+ emitter.fire(undefined);+ }+ });+ }++ const provider: vscode.FileDecorationProvider = {+ onDidChangeFileDecorations: emitter.event,+ provideFileDecoration(uri) {+ if (!isEnabled()) return undefined;+ if (!scores) {+ // First lookup while ready primes the map; nothing to show until it lands.+ kick();+ return undefined;+ }+ const rel = repoRelativePath(ctx, uri);+ if (!rel) return undefined;+ const entry = scores.get(rel);+ if (!entry) return undefined;+ const defect = entry.defectScore ?? entry.score;+ if (defect > maxScore()) return undefined;+ return {+ badge: BADGE,+ tooltip: `Repowise defect score ${defect.toFixed(1)}`,+ color: errorColor,+ propagate: false,+ };+ },+ };++ /** Subscribe to index-change events for this repo, once. */+ function ensureWatcher(): void {+ if (watcherSub) return;+ const watcher = ctx.events();+ if (!watcher) return;+ watcherSub = watcher.onDidChange((kind) => {+ if (kind !== "indexChanged") return;+ // A finished index update re-stamps head_commit; re-resolve it so the+ // next fetch caches under the new tag, then refetch and refresh.+ void ctx.refreshRepo().then(() => {+ scores = null;+ emitter.fire(undefined);+ kick();+ });+ });+ }++ const stateSub = ctx.onDidChangeExtensionState((state) => {+ if (state === "ready") {+ ensureWatcher();+ kick();+ } else {+ // Leaving ready invalidates the resolved repo; drop the map and clear.+ scores = null;+ loading = false;+ emitter.fire(undefined);+ }+ });++ const configSub = vscode.workspace.onDidChangeConfiguration((event) => {+ if (event.affectsConfiguration(`${CONFIG_SECTION}.fileDecorations`)) {+ emitter.fire(undefined);+ }+ });++ if (ctx.getExtensionState() === "ready") ensureWatcher();++ const providerSub = vscode.window.registerFileDecorationProvider(provider);++ return vscode.Disposable.from(+ providerSub,+ stateSub,+ configSub,+ { dispose: () => watcherSub?.dispose() },+ emitter,+ );+}diff --git a/packages/vscode/src/features/fileScoreStatus.ts b/packages/vscode/src/features/fileScoreStatus.tsnew file mode 100644index 000000000..606a55523--- /dev/null+++ b/packages/vscode/src/features/fileScoreStatus.ts@@ -0,0 +1,127 @@+import * as vscode from "vscode";+import { Commands, Views } from "../constants";+import { getBulkHealth, type FileScores } from "../core/bulkHealth";+import type { RepowiseContext } from "../core/context";+import { repoRelativePath } from "../core/fileSignals";++/** Renders a score, or a dash when the dimension is absent from the payload. */+function fmt(value: number | null): string {+ return value === null ? "-" : value.toFixed(1);+}++/**+ * A dedicated status-bar item showing the active editor's three health scores+ * (defect, maintainability, performance) compactly, with a tooltip that names+ * each dimension plus size and module. Data comes from the shared bulk fetch,+ * never a per-file request; the item hides whenever the active file has no+ * score or the extension is not ready. Clicking focuses the health view.+ */+export function registerFileScoreStatus(ctx: RepowiseContext): vscode.Disposable {+ const item = vscode.window.createStatusBarItem(+ vscode.StatusBarAlignment.Right,+ // Its own slot, lower priority than default source-control/language items.+ 50,+ );+ item.command = Commands.showFileHealth;++ /** Loaded scores, keyed by repo-relative forward-slash path; null until fetched. */+ let scores: Map<string, FileScores> | null = null;+ /** Guards against overlapping background fetches. */+ let loading = false;+ /** Lazily created freshness subscription, so activate() does no watching. */+ let watcherSub: vscode.Disposable | null = null;++ function render(): void {+ const editor = vscode.window.activeTextEditor;+ if (ctx.getExtensionState() !== "ready" || !scores || !editor) {+ item.hide();+ return;+ }+ const rel = repoRelativePath(ctx, editor.document.uri);+ const entry = rel ? scores.get(rel) : undefined;+ if (!entry) {+ item.hide();+ return;+ }+ const defect = entry.defectScore ?? entry.score;+ item.text = `$(heart) ${fmt(defect)} · ${fmt(entry.maintainabilityScore)} · ${fmt(+ entry.performanceScore,+ )}`;+ const tooltip = new vscode.MarkdownString();+ tooltip.appendMarkdown("**Repowise health**\n\n");+ tooltip.appendMarkdown(+ `Defect ${fmt(defect)} · Maintainability ${fmt(+ entry.maintainabilityScore,+ )} · Performance ${fmt(entry.performanceScore)}\n\n`,+ );+ tooltip.appendMarkdown(+ `${entry.nloc} lines${entry.module ? ` · ${entry.module}` : ""}`,+ );+ item.tooltip = tooltip;+ item.show();+ }++ /** Starts the shared bulk fetch once while ready; re-renders when it lands. */+ function kick(): void {+ if (loading || scores) return;+ if (ctx.getExtensionState() !== "ready" || !ctx.repoId) return;+ loading = true;+ void getBulkHealth(ctx).then((map) => {+ loading = false;+ if (map) {+ scores = map;+ render();+ }+ });+ }++ /** Subscribe to index-change events for this repo, once. */+ function ensureWatcher(): void {+ if (watcherSub) return;+ const watcher = ctx.events();+ if (!watcher) return;+ watcherSub = watcher.onDidChange((kind) => {+ if (kind !== "indexChanged") return;+ // A finished index update re-stamps head_commit; re-resolve it so the+ // next fetch caches under the new tag, then refetch and refresh.+ void ctx.refreshRepo().then(() => {+ scores = null;+ render();+ kick();+ });+ });+ }++ const editorSub = vscode.window.onDidChangeActiveTextEditor(() => {+ kick();+ render();+ });++ const stateSub = ctx.onDidChangeExtensionState((state) => {+ if (state === "ready") {+ ensureWatcher();+ kick();+ render();+ } else {+ scores = null;+ loading = false;+ item.hide();+ }+ });++ // The health tree view auto-generates a `<viewId>.focus` command; reuse it so+ // clicking the score reveals the fuller breakdown.+ const commandSub = vscode.commands.registerCommand(Commands.showFileHealth, () => {+ void vscode.commands.executeCommand(`${Views.health}.focus`);+ });++ if (ctx.getExtensionState() === "ready") {+ ensureWatcher();+ kick();+ render();+ }++ return vscode.Disposable.from(item, editorSub, stateSub, commandSub, {+ dispose: () => watcherSub?.dispose(),+ });+}diff --git a/packages/vscode/src/features/gutterHeat.ts b/packages/vscode/src/features/gutterHeat.tsnew file mode 100644index 000000000..0139583c3--- /dev/null+++ b/packages/vscode/src/features/gutterHeat.ts@@ -0,0 +1,153 @@+import * as vscode from "vscode";+import { CONFIG_SECTION } from "../constants";+import type { RepowiseContext } from "../core/context";+import { getFileFindings, repoRelativePath } from "../core/fileSignals";+import type { HealthFinding, HealthSeverity } from "@repowise-dev/types/health";++/** Gutter/overview-ruler color per severity tier. */+const TIER_COLOR: Record<HealthSeverity, string> = {+ critical: "#f14c4c",+ high: "#ff8800",+ medium: "#ffcc00",+ low: "#75beff",+};++const TIERS: HealthSeverity[] = ["critical", "high", "medium", "low"];++/** A 2px gutter strip in the tier color, as a data-URI SVG for gutterIconPath. */+function stripIcon(color: string): vscode.Uri {+ const svg =+ `<svg xmlns="http://www.w3.org/2000/svg" width="6" height="18">` ++ `<rect x="0" y="0" width="2" height="18" fill="${color}" fill-opacity="0.85"/>` ++ `</svg>`;+ return vscode.Uri.parse(+ `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`,+ );+}++/** Line span (1-based, inclusive) to a 0-based range; null lines anchor at top. */+function rangeFor(finding: HealthFinding): vscode.Range {+ if (finding.line_start == null) return new vscode.Range(0, 0, 0, 0);+ const start = Math.max(0, finding.line_start - 1);+ const end = Math.max(start, (finding.line_end ?? finding.line_start) - 1);+ return new vscode.Range(start, 0, end, 0);+}++/**+ * Shades the gutter beside every line with a health finding in visible editors,+ * one color per severity tier. This is the deep layer under the quiet Problems+ * floor: it paints all findings regardless of the diagnostics severity setting.+ * Decoration types are created once and reused; each paint only swaps ranges.+ */+export function registerGutterHeat(ctx: RepowiseContext): vscode.Disposable {+ const disposables: vscode.Disposable[] = [];++ /** Decoration types per tier, created lazily on first paint and reused. */+ let decorations: Record<HealthSeverity, vscode.TextEditorDecorationType> | null =+ null;+ /** Lazily created freshness subscription, so activate() does no watching. */+ let watcherSub: vscode.Disposable | null = null;++ const enabled = (): boolean =>+ vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<boolean>("gutterHeat.enabled", true);++ function ensureDecorations(): Record<+ HealthSeverity,+ vscode.TextEditorDecorationType+ > {+ if (decorations) return decorations;+ const build = (severity: HealthSeverity): vscode.TextEditorDecorationType => {+ const color = TIER_COLOR[severity];+ const type = vscode.window.createTextEditorDecorationType({+ gutterIconPath: stripIcon(color),+ gutterIconSize: "contain",+ overviewRulerColor: color,+ overviewRulerLane: vscode.OverviewRulerLane.Left,+ });+ disposables.push(type);+ return type;+ };+ decorations = {+ critical: build("critical"),+ high: build("high"),+ medium: build("medium"),+ low: build("low"),+ };+ return decorations;+ }++ /** Clears every tier's decorations from all visible editors. */+ function clearAll(): void {+ if (!decorations) return;+ for (const editor of vscode.window.visibleTextEditors) {+ for (const tier of TIERS) editor.setDecorations(decorations[tier], []);+ }+ }++ function paint(+ editor: vscode.TextEditor,+ findings: HealthFinding[],+ ): void {+ const types = ensureDecorations();+ const byTier: Record<HealthSeverity, vscode.Range[]> = {+ critical: [],+ high: [],+ medium: [],+ low: [],+ };+ for (const finding of findings) byTier[finding.severity].push(rangeFor(finding));+ for (const tier of TIERS) editor.setDecorations(types[tier], byTier[tier]);+ }++ async function refreshAll(): Promise<void> {+ if (!enabled() || ctx.getExtensionState() !== "ready" || !ctx.repoId) {+ clearAll();+ return;+ }+ for (const editor of vscode.window.visibleTextEditors) {+ const rel = repoRelativePath(ctx, editor.document.uri);+ if (!rel) continue;+ const findings = await getFileFindings(ctx, rel);+ if (!enabled() || ctx.getExtensionState() !== "ready") return;+ paint(editor, findings);+ }+ }++ /** Subscribe to index-change events for this repo, once, while ready. */+ function ensureWatcher(): void {+ if (watcherSub) return;+ const watcher = ctx.events();+ if (!watcher) return;+ watcherSub = watcher.onDidChange((kind) => {+ if (kind !== "indexChanged") return;+ void ctx.refreshRepo().then(() => refreshAll());+ });+ disposables.push(watcherSub);+ }++ disposables.push(+ ctx.onDidChangeExtensionState((state) => {+ if (state === "ready") {+ ensureWatcher();+ void refreshAll();+ } else {+ clearAll();+ }+ }),+ vscode.window.onDidChangeVisibleTextEditors(() => void refreshAll()),+ vscode.workspace.onDidChangeConfiguration((event) => {+ if (event.affectsConfiguration(`${CONFIG_SECTION}.gutterHeat.enabled`)) {+ void refreshAll();+ }+ }),+ );++ if (ctx.getExtensionState() === "ready") {+ ensureWatcher();+ void refreshAll();+ }++ return vscode.Disposable.from(...disposables);+}diff --git a/packages/vscode/src/features/hovers.ts b/packages/vscode/src/features/hovers.tsnew file mode 100644index 000000000..8c9c10f35--- /dev/null+++ b/packages/vscode/src/features/hovers.ts@@ -0,0 +1,167 @@+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 type { RepowiseContext } from "../core/context";+import { getFileFindings, repoRelativePath } from "../core/fileSignals";+import type {+ HealthFileBreakdownResponse,+ HealthFinding,+} from "@repowise-dev/types/health";+import type { DecisionRecordResponse } from "@repowise-dev/api-client/types";+import type { SymbolResponse } from "@repowise-dev/api-client/types";++/** Max governing decisions surfaced on a file hover. */+const MAX_DECISIONS = 3;++/** 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);+}++/** True when a finding's 1-based line span covers the given 0-based line. */+function covers(finding: HealthFinding, line: number): boolean {+ if (finding.line_start == null) return false;+ const start = finding.line_start - 1;+ const end = (finding.line_end ?? finding.line_start) - 1;+ return line >= start && line <= end;+}++/**+ * 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.+ */+export function registerHovers(ctx: RepowiseContext): vscode.Disposable {+ const enabled = (): boolean =>+ vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<boolean>("hover.enabled", true);++ /** Reads through the shared cache under the current head commit. */+ async function cached<T>(+ key: string,+ fetcher: () => Promise<T>,+ fallback: T,+ ): Promise<T> {+ const repoId = ctx.repoId;+ if (!repoId) return fallback;+ const tag = ctx.repo?.head_commit ?? "";+ const hit = ctx.cache.get<T>(repoId, key, tag);+ if (hit !== undefined) return hit;+ try {+ const value = await fetcher();+ ctx.cache.set(repoId, key, tag, value);+ return value;+ } catch (err) {+ ctx.log.debug(`hover fetch ${key} failed: ${String(err)}`);+ return fallback;+ }+ }++ async function fileHover(+ relPath: string,+ ): Promise<vscode.Hover | undefined> {+ const repoId = ctx.repoId;+ if (!repoId) return undefined;++ const breakdown = await cached<HealthFileBreakdownResponse | null>(+ `breakdown:${relPath}`,+ () => getHealthFileBreakdown(repoId, relPath),+ null,+ );+ const metric = breakdown?.metric;+ if (!metric) return undefined;++ const decisions = await cached<DecisionRecordResponse[]>(+ "decisions:all",+ () => listDecisions(repoId, { limit: 500 }),+ [],+ );+ const governing = decisions+ .filter((d) => d.affected_files.includes(relPath))+ .slice(0, MAX_DECISIONS);++ const md = new vscode.MarkdownString();+ md.appendMarkdown("**Repowise health**\n\n");+ md.appendMarkdown(+ `Defect ${fmt(metric.defect_score ?? metric.score)} · Maintainability ${fmt(+ metric.maintainability_score,+ )} · Performance ${fmt(metric.performance_score)}\n\n`,+ );++ const owner = breakdown?.signals?.primary_owner_name;+ if (owner) {+ const pct = breakdown?.signals?.primary_owner_commit_pct;+ md.appendMarkdown(+ `Owner: ${owner}${pct == null ? "" : ` (${Math.round(pct)}%)`}\n\n`,+ );+ }++ if (governing.length > 0) {+ md.appendMarkdown("Decisions:\n\n");+ for (const decision of governing) {+ md.appendMarkdown(`- ${decision.title}\n`);+ }+ }+ return new vscode.Hover(md);+ }++ async function symbolHover(+ relPath: string,+ position: vscode.Position,+ ): Promise<vscode.Hover | undefined> {+ const repoId = ctx.repoId;+ if (!repoId) return undefined;++ const symbols = await cached<SymbolResponse[]>(+ `symbols:${relPath}`,+ () => listSymbols({ repo_id: repoId, file_path: relPath, limit: 1000 }),+ [],+ );+ const line1 = position.line + 1;+ // Innermost symbol covering the line: smallest span among those that match.+ let match: SymbolResponse | undefined;+ for (const symbol of symbols) {+ if (symbol.start_line <= line1 && line1 <= symbol.end_line) {+ if (!match || symbol.end_line - symbol.start_line < match.end_line - match.start_line) {+ match = symbol;+ }+ }+ }+ if (!match) return undefined;++ const md = new vscode.MarkdownString();+ md.isTrusted = true;+ 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(+ `[${finding.reason}](command:${Commands.showFileHealth})\n`,+ );+ }+ return new vscode.Hover(md);+ }++ const provider = vscode.languages.registerHoverProvider(+ { scheme: "file" },+ {+ provideHover: async (document, position) => {+ if (!enabled() || ctx.getExtensionState() !== "ready" || !ctx.repoId) {+ return undefined;+ }+ const rel = repoRelativePath(ctx, document.uri);+ if (!rel) return undefined;+ return position.line === 0+ ? fileHover(rel)+ : symbolHover(rel, position);+ },+ },+ );++ return provider;+}diff --git a/packages/vscode/src/features/refactoringLens.ts b/packages/vscode/src/features/refactoringLens.tsnew file mode 100644index 000000000..ba86861a8--- /dev/null+++ b/packages/vscode/src/features/refactoringLens.ts@@ -0,0 +1,244 @@+import * as vscode from "vscode";+import * as path from "node:path";+import { buildRefactoringPlanPrompt, type AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";+import { typeMeta } from "@repowise-dev/ui/refactoring/meta";+import {+ blastCount,+ blastFiles,+ evidenceRows,+ planSynopsis,+ planWins,+ type RefactoringPlan,+} from "@repowise-dev/ui/refactoring/types";+import { CONFIG_SECTION, InternalCommands } from "../constants";+import type { RepowiseContext } from "../core/context";+import { repoRelativePath } from "../core/fileSignals";+import { getPlansForFile } from "../core/plans";++/** Virtual-document scheme for the rendered refactoring plan preview. */+const PLAN_SCHEME = "repowise-plan";++/** The four agent prompt flavors, in QuickPick order (first is the default). */+const FLAVOR_ITEMS: { label: string; flavor: AiPromptFlavor }[] = [+ { label: "Generic agent", flavor: "generic" },+ { label: "Claude Code", flavor: "claude-code" },+ { label: "Claude Code (with Repowise MCP)", flavor: "claude-code-mcp" },+ { label: "Cursor", flavor: "cursor" },+];++/**+ * Refactoring CodeLens: renders one lens per detected refactoring plan above the+ * plan's start line, gated on the `repowise.codeLens.enabled` setting and the+ * `ready` state. Owns the two internal commands the lens fans out to: opening a+ * rendered plan preview and copying a ready-to-paste agent prompt.+ */+export function registerRefactoringLens(ctx: RepowiseContext): vscode.Disposable {+ const onDidChangeCodeLenses = new vscode.EventEmitter<void>();++ const provider = createProvider(ctx, onDidChangeCodeLenses.event);++ // Rendered plan markdown, keyed by virtual-doc uri. Kept for the session so a+ // reopened preview does not need to re-render.+ const planDocs = new Map<string, string>();+ const planContentProvider: vscode.TextDocumentContentProvider = {+ provideTextDocumentContent: (uri) => planDocs.get(uri.toString()) ?? "",+ };++ let watcherSub: vscode.Disposable | undefined;+ /** Subscribe to index-change events once, lazily (never during activate). */+ function ensureWatcher(): void {+ if (watcherSub) return;+ const watcher = ctx.events();+ if (!watcher) return;+ watcherSub = watcher.onDidChange((kind) => {+ if (kind !== "indexChanged") return;+ // A finished index update re-stamps head_commit; re-resolve it so the+ // next fetch caches under the new tag, then refire so lenses refetch.+ void ctx.refreshRepo().then(() => onDidChangeCodeLenses.fire());+ });+ }++ const stateSub = ctx.onDidChangeExtensionState((state) => {+ if (state === "ready") ensureWatcher();+ onDidChangeCodeLenses.fire();+ });++ const configSub = vscode.workspace.onDidChangeConfiguration((event) => {+ if (event.affectsConfiguration(`${CONFIG_SECTION}.codeLens`)) {+ onDidChangeCodeLenses.fire();+ }+ });++ if (ctx.getExtensionState() === "ready") ensureWatcher();++ return vscode.Disposable.from(+ vscode.languages.registerCodeLensProvider({ scheme: "file" }, provider),+ vscode.workspace.registerTextDocumentContentProvider(PLAN_SCHEME, planContentProvider),+ vscode.commands.registerCommand(InternalCommands.openRefactoringPlan, (plan: RefactoringPlan) =>+ openRefactoringPlan(planDocs, plan),+ ),+ vscode.commands.registerCommand(InternalCommands.copyRefactoringPrompt, (plan: RefactoringPlan) =>+ copyRefactoringPrompt(plan),+ ),+ stateSub,+ configSub,+ onDidChangeCodeLenses,+ { dispose: () => watcherSub?.dispose() },+ );+}++function createProvider(+ ctx: RepowiseContext,+ onDidChangeCodeLenses: vscode.Event<void>,+): vscode.CodeLensProvider {+ return {+ onDidChangeCodeLenses,+ async provideCodeLenses(document): Promise<vscode.CodeLens[]> {+ const enabled = vscode.workspace+ .getConfiguration(CONFIG_SECTION)+ .get<boolean>("codeLens.enabled", true);+ if (!enabled || ctx.getExtensionState() !== "ready") return [];++ const relPath = repoRelativePath(ctx, document.uri);+ if (!relPath) return [];++ const plans = await getPlansForFile(ctx, relPath);+ const lenses: vscode.CodeLens[] = [];+ for (const plan of plans) {+ if (plan.line_start == null) continue;+ // Server line numbers are 1-based; editor ranges are 0-based.+ const line = Math.max(0, plan.line_start - 1);+ const range = new vscode.Range(line, 0, line, 0);+ lenses.push(+ new vscode.CodeLens(range, {+ title: lensTitle(plan),+ command: InternalCommands.openRefactoringPlan,+ arguments: [plan],+ }),+ );+ }+ return lenses;+ },+ // Lens commands are resolved eagerly above; this satisfies the interface.+ resolveCodeLens: (lens) => lens,+ };+}++/** "Repowise: Extract Class (impact 1.20, M)". */+function lensTitle(plan: RefactoringPlan): string {+ return `Repowise: ${typeMeta(plan.refactoring_type).label} (impact ${plan.impact_delta.toFixed(+ 2,+ )}, ${plan.effort_bucket})`;+}++/** `path:start-end` (or `path:start`, or `path`) for the plan's target. */+function planLocation(plan: RefactoringPlan): string {+ if (plan.line_start == null) return plan.file_path;+ if (plan.line_end != null && plan.line_end !== plan.line_start) {+ return `${plan.file_path}:${plan.line_start}-${plan.line_end}`;+ }+ return `${plan.file_path}:${plan.line_start}`;+}++/** Human-readable plan preview (distinct from the agent prompt). */+function renderPlanMarkdown(plan: RefactoringPlan): string {+ const meta = typeMeta(plan.refactoring_type);+ const affected = blastFiles(plan).filter((f) => f !== plan.file_path);+ const count = blastCount(plan);+ const wins = planWins(plan);+ const evidence = evidenceRows(plan);++ const lines: string[] = [+ `# ${meta.label}`,+ "",+ planSynopsis(plan) || meta.blurb,+ "",+ "## Target",+ "",+ `- Location: \`${planLocation(plan)}\``,+ ...(plan.target_symbol ? [`- Symbol: \`${plan.target_symbol}\``] : []),+ `- Confidence: ${plan.confidence}`,+ `- Effort: ${plan.effort_bucket}`,+ `- Impact: ${plan.impact_delta.toFixed(2)} health points`,+ "",+ ];++ if (wins.length > 0) {+ lines.push("## What you gain", "");+ for (const win of wins) lines.push(`- ${win.label}`);+ lines.push("");+ }++ if (evidence.length > 0) {+ lines.push("## Evidence", "");+ for (const row of evidence) lines.push(`- ${row.label}: ${row.value}`);+ lines.push("");+ }++ lines.push("## Blast radius", "");+ if (affected.length > 0) {+ lines.push(`${count} file${count === 1 ? "" : "s"} to keep consistent:`, "");+ for (const file of affected.slice(0, 20)) lines.push(`- \`${file}\``);+ if (affected.length > 20) lines.push(`- ...and ${affected.length - 20} more`);+ } else {+ lines.push(+ count > 0+ ? `${count} dependent${count === 1 ? "" : "s"} affected.`+ : "No dependent files recorded.",+ );+ }+ lines.push("");++ lines.push(+ "---",+ "",+ 'Run "Repowise: Copy plan for agent" (the action on this preview) to copy a ready-to-paste prompt for an AI coding agent.',+ );++ return lines.join("\n");+}++/** Render the plan into a virtual markdown doc and open its preview. */+async function openRefactoringPlan(+ planDocs: Map<string, string>,+ plan: RefactoringPlan,+): Promise<void> {+ if (!plan) return;+ const meta = typeMeta(plan.refactoring_type);+ const base = path.basename(plan.file_path) || "file";+ // Unique per plan id so distinct plans get distinct previews; readable path so+ // the preview tab shows the refactoring type.+ const uri = vscode.Uri.from({+ scheme: PLAN_SCHEME,+ path: `/${meta.label} - ${base}.md`,+ query: plan.id,+ });+ planDocs.set(uri.toString(), renderPlanMarkdown(plan));++ await vscode.commands.executeCommand("markdown.showPreview", uri);++ const choice = await vscode.window.showInformationMessage(+ `Repowise refactoring plan: ${meta.label}`,+ "Copy plan for agent",+ );+ if (choice === "Copy plan for agent") {+ await vscode.commands.executeCommand(InternalCommands.copyRefactoringPrompt, plan);+ }+}++/** Pick a prompt flavor and copy the shared agent prompt for this plan. */+async function copyRefactoringPrompt(plan: RefactoringPlan): Promise<void> {+ if (!plan) return;+ const picked = await vscode.window.showQuickPick(+ FLAVOR_ITEMS.map((item) => item.label),+ { placeHolder: "Copy refactoring plan as a prompt for..." },+ );+ if (!picked) return;+ const flavor = FLAVOR_ITEMS.find((item) => item.label === picked)?.flavor ?? "generic";++ const prompt = buildRefactoringPlanPrompt({ plan, flavor });+ await vscode.env.clipboard.writeText(prompt);+ void vscode.window.showInformationMessage(+ `Copied refactoring prompt (${prompt.length} characters) to the clipboard.`,+ );+}diff --git a/packages/vscode/src/features/serverManager.ts b/packages/vscode/src/features/serverManager.tsindex 77ddff25a..c5cd3b85f 100644--- a/packages/vscode/src/features/serverManager.ts+++ b/packages/vscode/src/features/serverManager.ts@@ -111,12 +111,14 @@ export function registerServerManager(ctx: RepowiseContext): vscode.Disposable {return;}- // A missing repo id is not fatal: staying connected still serves the- // workspace, so log it and carry on.- const repoId = await ctx.api.resolveRepoId(repoRoot);- if (!repoId) {+ // A missing repo record is not fatal: staying connected still serves the+ // workspace, so log it and carry on. Set before the ready flip so state+ // listeners read a settled repo.+ const repo = await ctx.api.resolveRepo(repoRoot);+ if (!repo) {ctx.log.warn(`Could not resolve a repo id for ${repoRoot}; staying connected.`);}+ ctx.setRepo(repo);ctx.setExtensionState("ready");ctx.setStatusBarState("connected", { version: health.version, url });}diff --git a/packages/vscode/src/features/staleness.ts b/packages/vscode/src/features/staleness.tsnew file mode 100644index 000000000..3e91a3f29--- /dev/null+++ b/packages/vscode/src/features/staleness.ts@@ -0,0 +1,269 @@+import * as vscode from "vscode";+import { readFile } from "node:fs/promises";+import * as path from "node:path";+import { Commands } from "../constants";+import type { RepowiseContext } from "../core/context";+import { getHeadCommit } from "../core/gitApi";++/** Update runs can be long on a large repo; well above the default timeout. */+const UPDATE_TIMEOUT_MS = 30 * 60_000;++/** One newline-delimited progress event from `repowise update --progress json`. */+interface UpdateEvent {+ event: string;+ name?: string;+ total?: number;+ completed?: number;+ ok?: boolean;+ message?: string;+}++/**+ * Surfaces "index behind the working tree" state in its own status-bar item and+ * owns `Commands.updateIndex`. Stale means the server's indexed `head_commit`+ * differs from the live checked-out commit. The badge is visible only while+ * stale; a click runs an incremental index update that clears it.+ */+export function registerStaleness(ctx: RepowiseContext): vscode.Disposable {+ const item = vscode.window.createStatusBarItem(+ vscode.StatusBarAlignment.Right,+ 0,+ );+ item.text = "$(sync-ignored) Repowise: index behind";+ item.tooltip =+ "The Repowise index is behind the checked-out commit. Click to run an index update.";+ item.command = Commands.updateIndex;+ item.backgroundColor = new vscode.ThemeColor("statusBarItem.warningBackground");++ let watcherSub: vscode.Disposable | null = null;+ /** True while an update is in flight, to enforce single-flight. */+ let updating = false;++ /** Live checked-out commit, preferring the git extension over disk reads. */+ async function liveHead(root: string): Promise<string | null> {+ const viaGit = await getHeadCommit(root);+ if (viaGit) return viaGit;+ return readHeadFromDisk(root);+ }++ async function evaluate(): Promise<void> {+ const indexed = ctx.repo?.head_commit;+ const root = ctx.workspace.repoRoot;+ // Only flag when both sides are known: an unresolved repo or an+ // undeterminable HEAD is not evidence of staleness.+ if (!indexed || !root) {+ item.hide();+ return;+ }+ const live = await liveHead(root);+ if (!live) {+ item.hide();+ return;+ }+ if (commitsMatch(indexed, live)) item.hide();+ else item.show();+ }++ /** Subscribe to freshness events lazily (never during activate()). */+ function ensureWatcher(): void {+ if (watcherSub) return;+ const watcher = ctx.events();+ if (!watcher) return;+ watcherSub = watcher.onDidChange((kind) => {+ if (kind === "headChanged") {+ void evaluate();+ } else if (kind === "indexChanged") {+ // An index rebuild re-stamps head_commit; re-resolve before comparing.+ void ctx.refreshRepo().then(() => evaluate());+ }+ });+ }++ async function updateIndex(): Promise<void> {+ if (updating) {+ void vscode.window.showInformationMessage(+ "A Repowise index update is already running.",+ );+ return;+ }+ const root = ctx.workspace.repoRoot;+ if (!root) {+ void vscode.window.showWarningMessage(+ "No Repowise index found in this workspace.",+ );+ return;+ }++ updating = true;+ try {+ const { ok, detail } = await runUpdate(root);+ if (ok) {+ await ctx.refreshRepo();+ await evaluate();+ void vscode.window.showInformationMessage("Repowise index updated.");+ } else {+ const choice = await vscode.window.showErrorMessage(+ detail ?? "The Repowise index update failed.",+ "Show Log",+ );+ if (choice === "Show Log") ctx.log.show();+ }+ } finally {+ updating = false;+ }+ }++ /**+ * Runs the CLI update, streaming NDJSON progress into a notification. A `done`+ * event with `ok: false`, an `error` event, or a nonzero exit code all count+ * as failure. Non-JSON lines are ignored silently.+ */+ async function runUpdate(+ root: string,+ ): Promise<{ ok: boolean; detail: string | null }> {+ return vscode.window.withProgress(+ {+ location: vscode.ProgressLocation.Notification,+ title: "Updating Repowise index",+ cancellable: false,+ },+ async (progress) => {+ let total: number | null = null;+ let lastPct = 0;+ let failed = false;+ let errorMessage: string | null = null;++ const onStdoutLine = (line: string): void => {+ let evt: UpdateEvent;+ try {+ evt = JSON.parse(line) as UpdateEvent;+ } catch {+ return;+ }+ switch (evt.event) {+ case "start":+ progress.report({ message: "Scanning changes" });+ break;+ case "stage":+ if (evt.name) progress.report({ message: humanize(evt.name) });+ break;+ case "total_known":+ total = typeof evt.total === "number" ? evt.total : null;+ break;+ case "page_done": {+ const completed = evt.completed ?? 0;+ const message = total+ ? `Generating pages ${completed}/${total}`+ : `Generating pages (${completed})`;+ if (total && total > 0) {+ const pct = Math.min(100, (completed / total) * 100);+ progress.report({ increment: pct - lastPct, message });+ lastPct = pct;+ } else {+ progress.report({ message });+ }+ break;+ }+ case "done":+ if (evt.ok === false) failed = true;+ break;+ case "error":+ failed = true;+ errorMessage = evt.message ?? errorMessage;+ break;+ default:+ break;+ }+ };++ try {+ // Bypass the serialized queue: a minutes-long update would make+ // every queued short call (doctor, version probes) appear frozen.+ // The `updating` flag above is the single-flight guard.+ const result = await ctx.cli.run(["update", "--progress", "json"], {+ cwd: root,+ timeoutMs: UPDATE_TIMEOUT_MS,+ onStdoutLine,+ bypassQueue: true,+ });+ const ok = result.code === 0 && !failed;+ const detail = ok+ ? null+ : errorMessage ??+ `The Repowise index update failed (exit code ${result.code ?? "unknown"}).`;+ return { ok, detail };+ } catch (err) {+ ctx.log.error(`index update failed: ${String(err)}`);+ return { ok: false, detail: "The Repowise index update failed." };+ }+ },+ );+ }++ const disposables: vscode.Disposable[] = [+ item,+ vscode.commands.registerCommand(Commands.updateIndex, () => void updateIndex()),+ ctx.onDidChangeExtensionState((state) => {+ if (state === "ready") {+ ensureWatcher();+ void evaluate();+ } else {+ item.hide();+ }+ }),+ ];++ // If the extension is already ready when this registers (unusual: discovery+ // runs post-activation), evaluate once off the hot path.+ if (ctx.getExtensionState() === "ready") {+ const timer = setTimeout(() => {+ ensureWatcher();+ void evaluate();+ }, 0);+ disposables.push({ dispose: () => clearTimeout(timer) });+ }++ return {+ dispose(): void {+ watcherSub?.dispose();+ watcherSub = null;+ for (const d of disposables) d.dispose();+ },+ };+}++/** True when two commit ids refer to the same commit (tolerates short shas). */+function commitsMatch(a: string, b: string): boolean {+ if (a === b) return true;+ const shorter = a.length < b.length ? a : b;+ const longer = a.length < b.length ? b : a;+ return shorter.length > 0 && longer.startsWith(shorter);+}++/**+ * Reads the checked-out commit from `.git` when the git extension is+ * unavailable. Resolves a symbolic ref to its loose ref file. Packed refs are+ * not read here; that path degrades to null (no false staleness) and the git+ * extension covers it when enabled.+ */+async function readHeadFromDisk(root: string): Promise<string | null> {+ try {+ const raw = (await readFile(path.join(root, ".git", "HEAD"), "utf8")).trim();+ if (raw.startsWith("ref:")) {+ const ref = raw.slice(4).trim();+ const refPath = path.join(root, ".git", ...ref.split("/"));+ const sha = (await readFile(refPath, "utf8")).trim();+ return sha || null;+ }+ // Detached HEAD: the file holds the commit id directly.+ return raw || null;+ } catch {+ return null;+ }+}++/** Turns a snake_case stage name into a readable progress message. */+function humanize(name: string): string {+ const spaced = name.replace(/_/g, " ");+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);+}diff --git a/packages/vscode/src/features/trees.ts b/packages/vscode/src/features/trees.tsnew file mode 100644index 000000000..887af5615--- /dev/null+++ b/packages/vscode/src/features/trees.ts@@ -0,0 +1,23 @@+import * as vscode from "vscode";+import type { RepowiseContext } from "../core/context";+import { registerDeadCodeTree } from "./trees/deadCode";+import { registerDecisionsTree } from "./trees/decisions";+import { registerHealthTree } from "./trees/health";+import { registerHotspotsTree } from "./trees/hotspots";+import { registerRefactoringTree } from "./trees/refactoring";++/**+ * Instantiates the five activity-bar tree views (Health, Refactoring, Hotspots+ * & Ownership, Dead Code, Decisions) and bundles their disposables into one.+ * Registration is cheap: each provider defers its first fetch until VS Code+ * asks for children, which only happens once the view is visible.+ */+export function registerTrees(ctx: RepowiseContext): vscode.Disposable {+ return vscode.Disposable.from(+ registerHealthTree(ctx),+ registerRefactoringTree(ctx),+ registerHotspotsTree(ctx),+ registerDeadCodeTree(ctx),+ registerDecisionsTree(ctx),+ );+}diff --git a/packages/vscode/src/features/trees/deadCode.ts b/packages/vscode/src/features/trees/deadCode.tsnew file mode 100644index 000000000..d1275f1fe--- /dev/null+++ b/packages/vscode/src/features/trees/deadCode.ts@@ -0,0 +1,95 @@+import * as vscode from "vscode";+import { getDeadCodeSummary, listDeadCode } from "@repowise-dev/api-client/dead-code";+import type { DeadCodeFindingResponse } from "@repowise-dev/api-client/types";+import { Views } from "../../constants";+import type { RepowiseContext } from "../../core/context";+import {+ baseName,+ mountView,+ openFileCommand,+ RepowiseTreeProvider,+ type RepoTreeNode,+} from "./shared";++const FINDINGS_KEY = "deadcode:findings";+const SUMMARY_KEY = "deadcode:summary";++/** Confidence tiers, most-confident first, with their inclusive lower bounds. */+const TIERS: Array<{ key: string; label: string; min: number }> = [+ { key: "high", label: "High", min: 0.75 },+ { key: "medium", label: "Medium", min: 0.5 },+ { key: "low", label: "Low", min: 0 },+];++/**+ * Dead Code view: findings grouped into High / Medium / Low confidence tiers.+ * Empty tiers are dropped. Findings use `start_line`/`end_line` (distinct from+ * the health findings' `line_start`/`line_end`); a click jumps to `start_line`+ * when present. The badge is the summary's total finding count.+ */+class DeadCodeTreeProvider extends RepowiseTreeProvider {+ protected readonly name = "Dead Code";++ protected async loadRoots(repoId: string): Promise<RepoTreeNode[]> {+ const findings = await this.cached(FINDINGS_KEY, () =>+ listDeadCode(repoId, { limit: 500 }),+ );+ void this.loadBadge(repoId);++ if (findings.length === 0) return [this.messageNode("No dead code")];++ const roots: RepoTreeNode[] = [];+ for (const tier of TIERS) {+ const rows = findings.filter((f) => tierOf(f.confidence) === tier.key);+ if (rows.length === 0) continue;+ roots.push({+ key: `tier:${tier.key}`,+ label: tier.label,+ description: `${rows.length}`,+ collapsibleState: vscode.TreeItemCollapsibleState.Expanded,+ children: rows.map((row) => this.findingNode(row)),+ });+ }+ return roots;+ }++ private findingNode(row: DeadCodeFindingResponse): RepoTreeNode {+ const tooltip = new vscode.MarkdownString();+ tooltip.appendMarkdown(`\`${row.file_path}\`\n\n`);+ tooltip.appendMarkdown(`- Kind: ${row.kind}\n`);+ tooltip.appendMarkdown(`- Confidence: ${row.confidence.toFixed(2)}\n`);+ tooltip.appendMarkdown(`- ${row.reason}\n`);+ return {+ key: `dead:${row.id}`,+ label: row.symbol_name ?? baseName(row.file_path),+ description: `${row.kind} · ${row.lines} lines`,+ tooltip,+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ command: openFileCommand(this.ctx, row.file_path, row.start_line),+ };+ }++ private async loadBadge(repoId: string): Promise<void> {+ try {+ const summary = await this.cached(SUMMARY_KEY, () =>+ getDeadCodeSummary(repoId),+ );+ this.setBadge(summary.total_findings, `${summary.total_findings} dead-code findings`);+ } catch (err) {+ this.ctx.log.debug(`Dead Code badge load failed: ${String(err)}`);+ }+ }+}++/** Maps a 0-1 confidence to its tier key. */+function tierOf(confidence: number): string {+ for (const tier of TIERS) {+ if (confidence >= tier.min) return tier.key;+ }+ return "low";+}++/** Registers the Dead Code tree view. */+export function registerDeadCodeTree(ctx: RepowiseContext): vscode.Disposable {+ return mountView(ctx, Views.deadCode, new DeadCodeTreeProvider(ctx));+}diff --git a/packages/vscode/src/features/trees/decisions.ts b/packages/vscode/src/features/trees/decisions.tsnew file mode 100644index 000000000..f3e03de5b--- /dev/null+++ b/packages/vscode/src/features/trees/decisions.ts@@ -0,0 +1,96 @@+import * as vscode from "vscode";+import { listDecisions } from "@repowise-dev/api-client/decisions";+import type { DecisionRecordResponse } from "@repowise-dev/api-client/types";+import { Views } from "../../constants";+import type { RepowiseContext } from "../../core/context";+import {+ mountView,+ openFileCommand,+ RepowiseTreeProvider,+ truncate,+ type RepoTreeNode,+} from "./shared";++const DECISIONS_KEY = "decisions:all";++/** Status display order: accepted/active first, retired states last, else A-Z. */+const STATUS_RANK: Record<string, number> = {+ accepted: 0,+ active: 1,+ proposed: 2,+ deprecated: 4,+ superseded: 5,+};++/**+ * Decisions view: architectural decision records grouped by status, accepted+ * first. A record with a backing `evidence_file` opens it on click (at+ * `evidence_line`, 1-based, when present); records without evidence are not+ * clickable. No badge.+ */+class DecisionsTreeProvider extends RepowiseTreeProvider {+ protected readonly name = "Decisions";++ protected async loadRoots(repoId: string): Promise<RepoTreeNode[]> {+ // Same key and limit as the hover feature's decision lookup, so whichever+ // fetches first serves both.+ const decisions = await this.cached(DECISIONS_KEY, () =>+ listDecisions(repoId, { limit: 500 }),+ );+ if (decisions.length === 0) return [this.messageNode("No decisions")];++ const byStatus = new Map<string, DecisionRecordResponse[]>();+ for (const record of decisions) {+ const bucket = byStatus.get(record.status);+ if (bucket) bucket.push(record);+ else byStatus.set(record.status, [record]);+ }++ return Array.from(byStatus.keys())+ .sort(compareStatus)+ .map((status) => {+ const rows = byStatus.get(status) ?? [];+ return {+ key: `status:${status}`,+ label: capitalize(status),+ description: `${rows.length}`,+ collapsibleState: vscode.TreeItemCollapsibleState.Expanded,+ children: rows.map((row) => this.decisionNode(row)),+ };+ });+ }++ private decisionNode(row: DecisionRecordResponse): RepoTreeNode {+ const tooltip = new vscode.MarkdownString();+ tooltip.appendMarkdown(`**Decision:** ${row.decision}\n\n`);+ tooltip.appendMarkdown(`**Rationale:** ${row.rationale}\n`);+ return {+ key: `decision:${row.id}`,+ label: truncate(row.title),+ description: row.source,+ tooltip,+ icon: new vscode.ThemeIcon("law"),+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ command: row.evidence_file+ ? openFileCommand(this.ctx, row.evidence_file, row.evidence_line)+ : undefined,+ };+ }+}++/** Orders two status keys by preferred rank, falling back to alphabetical. */+function compareStatus(a: string, b: string): number {+ const ra = STATUS_RANK[a] ?? 3;+ const rb = STATUS_RANK[b] ?? 3;+ return ra === rb ? a.localeCompare(b) : ra - rb;+}++/** Upper-cases the first letter for a status label. */+function capitalize(text: string): string {+ return text.length === 0 ? text : text.charAt(0).toUpperCase() + text.slice(1);+}++/** Registers the Decisions tree view. */+export function registerDecisionsTree(ctx: RepowiseContext): vscode.Disposable {+ return mountView(ctx, Views.decisions, new DecisionsTreeProvider(ctx));+}diff --git a/packages/vscode/src/features/trees/health.ts b/packages/vscode/src/features/trees/health.tsnew file mode 100644index 000000000..e7130bca6--- /dev/null+++ b/packages/vscode/src/features/trees/health.ts@@ -0,0 +1,89 @@+import * as vscode from "vscode";+import { listHealthFiles } from "@repowise-dev/api-client/code-health";+import type { HealthFileMetric } from "@repowise-dev/api-client/code-health";+import { Views } from "../../constants";+import type { RepowiseContext } from "../../core/context";+import {+ baseName,+ mountView,+ openFileCommand,+ RepowiseTreeProvider,+ type RepoTreeNode,+} from "./shared";++// Distinct from the bulk per-file score map cached under "health:files": this+// entry holds the worst-100 response object, not the full-repo score map.+const FILES_KEY = "health:worst";+const FAILING_KEY = "health:failing";++/** Formats a 0-10 health score, or a dash when the score is absent. */+function score(value: number | null | undefined): string {+ return value == null ? "-" : value.toFixed(1);+}++/**+ * Health view: the 100 lowest-scoring files, grouped by module with worst-first+ * children. The list arrives sorted ascending by score, so iterating it in+ * order yields both worst-first files and worst-first modules for free. The+ * badge counts failing files (a separate one-row query for its `total`).+ */+class HealthTreeProvider extends RepowiseTreeProvider {+ protected readonly name = "Health";++ protected async loadRoots(repoId: string): Promise<RepoTreeNode[]> {+ const files = await this.cached(FILES_KEY, () =>+ listHealthFiles(repoId, { sort: "score", order: "asc", limit: 100 }),+ );+ void this.loadBadge(repoId);++ if (files.files.length === 0) return [this.messageNode("No health data")];++ const byModule = new Map<string, HealthFileMetric[]>();+ for (const file of files.files) {+ const module = file.module ?? "(no module)";+ const bucket = byModule.get(module);+ if (bucket) bucket.push(file);+ else byModule.set(module, [file]);+ }++ return Array.from(byModule, ([module, rows]) => ({+ key: `mod:${module}`,+ label: module,+ description: `${rows.length} ${rows.length === 1 ? "file" : "files"}`,+ collapsibleState: vscode.TreeItemCollapsibleState.Collapsed,+ children: rows.map((row) => this.fileNode(row)),+ }));+ }++ private fileNode(row: HealthFileMetric): RepoTreeNode {+ const tooltip = new vscode.MarkdownString();+ tooltip.appendMarkdown(`\`${row.file_path}\`\n\n`);+ tooltip.appendMarkdown(`- Defect risk: ${score(row.defect_score ?? row.score)}\n`);+ tooltip.appendMarkdown(`- Maintainability: ${score(row.maintainability_score)}\n`);+ tooltip.appendMarkdown(`- Performance: ${score(row.performance_score)}\n`);+ return {+ key: `file:${row.file_path}`,+ label: baseName(row.file_path),+ description: score(row.defect_score ?? row.score),+ tooltip,+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ command: openFileCommand(this.ctx, row.file_path),+ };+ }++ private async loadBadge(repoId: string): Promise<void> {+ try {+ const failing = await this.cached(FAILING_KEY, () =>+ listHealthFiles(repoId, { only_failing: true, limit: 1 }),+ );+ this.setBadge(failing.total, `${failing.total} failing files`);+ } catch (err) {+ this.ctx.log.debug(`Health badge load failed: ${String(err)}`);+ }+ }+}++/** Registers the Health tree view. */+export function registerHealthTree(ctx: RepowiseContext): vscode.Disposable {+ return mountView(ctx, Views.health, new HealthTreeProvider(ctx));+}diff --git a/packages/vscode/src/features/trees/hotspots.ts b/packages/vscode/src/features/trees/hotspots.tsnew file mode 100644index 000000000..9da2d65bf--- /dev/null+++ b/packages/vscode/src/features/trees/hotspots.ts@@ -0,0 +1,96 @@+import * as vscode from "vscode";+import { getHotspotsPage, getOwnershipPage } from "@repowise-dev/api-client/git";+import type {+ HotspotResponse,+ OwnershipEntry,+} from "@repowise-dev/api-client/types";+import { Views } from "../../constants";+import type { RepowiseContext } from "../../core/context";+import {+ baseName,+ mountView,+ openFileCommand,+ RepowiseTreeProvider,+ type RepoTreeNode,+} from "./shared";++const HOTSPOTS_KEY = "hotspots:page";+const OWNERSHIP_KEY = "ownership:page";++/**+ * Hotspots & Ownership view: two section roots, each fetched lazily when its+ * section expands (so opening the view fetches neither until its section is+ * shown). Hotspots are the highest-churn files; Ownership rolls up who owns+ * each module and flags single-owner silos.+ */+class HotspotsTreeProvider extends RepowiseTreeProvider {+ protected readonly name = "Hotspots";++ protected loadRoots(): Promise<RepoTreeNode[]> {+ return Promise.resolve([+ this.section("hotspots", "Hotspots", () => this.loadHotspots()),+ this.section("ownership", "Ownership", () => this.loadOwnership()),+ ]);+ }++ private async loadHotspots(): Promise<RepoTreeNode[]> {+ const repoId = this.ctx.repoId;+ if (!repoId) return [];+ const page = await this.cached(HOTSPOTS_KEY, () =>+ getHotspotsPage(repoId, { limit: 50 }),+ );+ if (page.items.length === 0) return [this.messageNode("No hotspots")];+ return page.items.map((row) => this.hotspotNode(row));+ }++ private hotspotNode(row: HotspotResponse): RepoTreeNode {+ const owner = row.primary_owner ?? "unknown";+ const tooltip = new vscode.MarkdownString();+ tooltip.appendMarkdown(`\`${row.file_path}\`\n\n`);+ tooltip.appendMarkdown(`- Churn percentile: ${Math.round(row.churn_percentile)}\n`);+ tooltip.appendMarkdown(`- Bus factor: ${row.bus_factor}\n`);+ tooltip.appendMarkdown(`- Contributors: ${row.contributor_count}\n`);+ return {+ key: `hotspot:${row.file_path}`,+ label: baseName(row.file_path),+ description: `${row.commit_count_90d} commits · ${owner}`,+ tooltip,+ icon: new vscode.ThemeIcon("flame"),+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ command: openFileCommand(this.ctx, row.file_path),+ };+ }++ private async loadOwnership(): Promise<RepoTreeNode[]> {+ const repoId = this.ctx.repoId;+ if (!repoId) return [];+ const page = await this.cached(OWNERSHIP_KEY, () =>+ getOwnershipPage(repoId, "module", { limit: 200 }),+ );+ if (page.items.length === 0) return [this.messageNode("No ownership data")];+ return page.items.map((row) => this.ownershipNode(row));+ }++ private ownershipNode(row: OwnershipEntry): RepoTreeNode {+ const owner = row.primary_owner ?? "unknown";+ const pct = row.owner_pct == null ? "-" : `${Math.round(row.owner_pct)}%`;+ const tooltip = new vscode.MarkdownString();+ tooltip.appendMarkdown(`\`${row.module_path}\`\n\n`);+ tooltip.appendMarkdown(`- Primary owner: ${owner} (${pct})\n`);+ tooltip.appendMarkdown(`- Files: ${row.file_count}\n`);+ if (row.is_silo) tooltip.appendMarkdown(`- Single-owner silo\n`);+ return {+ key: `owner:${row.module_path}`,+ label: row.module_path,+ description: `${owner} ${pct}`,+ tooltip,+ icon: row.is_silo ? new vscode.ThemeIcon("warning") : undefined,+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ };+ }+}++/** Registers the Hotspots & Ownership tree view. */+export function registerHotspotsTree(ctx: RepowiseContext): vscode.Disposable {+ return mountView(ctx, Views.hotspots, new HotspotsTreeProvider(ctx));+}diff --git a/packages/vscode/src/features/trees/refactoring.ts b/packages/vscode/src/features/trees/refactoring.tsnew file mode 100644index 000000000..87e652505--- /dev/null+++ b/packages/vscode/src/features/trees/refactoring.ts@@ -0,0 +1,81 @@+import * as vscode from "vscode";+import { getRefactoringTargets } from "@repowise-dev/api-client/refactoring";+import { InternalCommands, Views } from "../../constants";+import type { RepowiseContext } from "../../core/context";+import {+ baseName,+ humanizeType,+ mountView,+ RepowiseTreeProvider,+ type RepoTreeNode,+} from "./shared";++/** Response and plan shapes derived from the client so no extra import is needed. */+type RefactoringTargets = Awaited<ReturnType<typeof getRefactoringTargets>>;+type RefactoringPlan = RefactoringTargets["plans"][number];++const PLANS_KEY = "plans:all";+const MAX_PLANS = 100;++/** Reads the first present dependent/file/caller count from an open blast dict. */+function blastCount(blast: Record<string, unknown>): number | null {+ for (const key of ["dependents_count", "file_count", "callers"]) {+ const value = blast[key];+ if (typeof value === "number") return value;+ if (Array.isArray(value)) return value.length;+ }+ return null;+}++/**+ * Refactoring view: server-ranked plans shown as a flat, top-N list (plans+ * arrive already ordered by rank). The item command hands the full plan object+ * to a runtime command registered elsewhere; this module only references it by+ * id. The badge is the server's total count, read from the same response.+ */+class RefactoringTreeProvider extends RepowiseTreeProvider {+ protected readonly name = "Refactoring";++ protected async loadRoots(repoId: string): Promise<RepoTreeNode[]> {+ const targets = await this.cached(PLANS_KEY, () =>+ getRefactoringTargets(repoId, { minConfidence: "medium" }),+ );+ this.setBadge(targets.summary.total, `${targets.summary.total} refactoring targets`);++ if (targets.plans.length === 0) {+ return [this.messageNode("No refactoring targets")];+ }+ return targets.plans.slice(0, MAX_PLANS).map((plan) => this.planNode(plan));+ }++ private planNode(plan: RefactoringPlan): RepoTreeNode {+ const tooltip = new vscode.MarkdownString();+ tooltip.appendMarkdown(`**${humanizeType(plan.refactoring_type)}**\n\n`);+ tooltip.appendMarkdown(`\`${plan.file_path}\`\n\n`);+ tooltip.appendMarkdown(`- Impact: ${plan.impact_delta.toFixed(2)}\n`);+ tooltip.appendMarkdown(`- Effort: ${plan.effort_bucket}\n`);+ tooltip.appendMarkdown(`- Confidence: ${plan.confidence}\n`);+ const blast = blastCount(plan.blast_radius);+ if (blast != null) tooltip.appendMarkdown(`- Blast radius: ${blast}\n`);+ return {+ key: `plan:${plan.id}`,+ label: `${humanizeType(plan.refactoring_type)} ${+ plan.target_symbol ?? baseName(plan.file_path)+ }`,+ description: `impact ${plan.impact_delta.toFixed(2)} · ${plan.effort_bucket}`,+ tooltip,+ icon: new vscode.ThemeIcon("wrench"),+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ command: {+ command: InternalCommands.openRefactoringPlan,+ title: "Open Refactoring Plan",+ arguments: [plan],+ },+ };+ }+}++/** Registers the Refactoring tree view. */+export function registerRefactoringTree(ctx: RepowiseContext): vscode.Disposable {+ return mountView(ctx, Views.refactoring, new RefactoringTreeProvider(ctx));+}diff --git a/packages/vscode/src/features/trees/shared.ts b/packages/vscode/src/features/trees/shared.tsnew file mode 100644index 000000000..e72b67af9--- /dev/null+++ b/packages/vscode/src/features/trees/shared.ts@@ -0,0 +1,247 @@+import * as vscode from "vscode";+import * as path from "node:path";+import type { RepowiseContext } from "../../core/context";++/**+ * One node in a Repowise activity-bar tree. Providers build a plain node tree+ * and the base turns each into a `TreeItem`. Optional fields carry `| undefined`+ * so nodes compose cleanly under `exactOptionalPropertyTypes`. Group nodes+ * either hold their children inline (`children`) or resolve them on expansion+ * (`loadChildren`); leaves carry neither.+ */+export interface RepoTreeNode {+ key: string;+ label: string;+ description?: string | undefined;+ tooltip?: string | vscode.MarkdownString | undefined;+ icon?: vscode.ThemeIcon | undefined;+ collapsibleState: vscode.TreeItemCollapsibleState;+ command?: vscode.Command | undefined;+ children?: RepoTreeNode[] | undefined;+ loadChildren?: (() => Promise<RepoTreeNode[]>) | undefined;+}++/**+ * Base for the five data-backed tree views. Handles the shared lifecycle so+ * each subclass only supplies `loadRoots`: lazy root fetch on first ask (VS+ * Code calls `getChildren` only when the view is visible), an in-memory root+ * cache cleared on refresh, per-provider index-change watching wired lazily+ * (never during activate), and a view badge surfaced through an event because+ * badges live on the `TreeView`, not on items.+ */+export abstract class RepowiseTreeProvider+ implements vscode.TreeDataProvider<RepoTreeNode>, vscode.Disposable+{+ private readonly changeEmitter = new vscode.EventEmitter<void>();+ readonly onDidChangeTreeData = this.changeEmitter.event;++ private readonly badgeEmitter = new vscode.EventEmitter<+ vscode.ViewBadge | undefined+ >();+ /** Fires the badge to set on the owning `TreeView` (undefined clears it). */+ readonly onDidChangeBadge = this.badgeEmitter.event;++ private rootsPromise: Promise<RepoTreeNode[]> | null = null;+ private freshnessSub: vscode.Disposable | null = null;++ /** Human label used only in debug log lines. */+ protected abstract readonly name: string;++ constructor(protected readonly ctx: RepowiseContext) {}++ /** Builds the root nodes for a resolved repo. Throws are caught upstream. */+ protected abstract loadRoots(repoId: string): Promise<RepoTreeNode[]>;++ getTreeItem(node: RepoTreeNode): vscode.TreeItem {+ const item = new vscode.TreeItem(node.label, node.collapsibleState);+ if (node.description !== undefined) item.description = node.description;+ if (node.tooltip !== undefined) item.tooltip = node.tooltip;+ if (node.icon !== undefined) item.iconPath = node.icon;+ if (node.command !== undefined) item.command = node.command;+ return item;+ }++ async getChildren(node?: RepoTreeNode): Promise<RepoTreeNode[]> {+ if (node) {+ if (node.children) return node.children;+ if (node.loadChildren) {+ node.children = await this.guard(node.loadChildren);+ return node.children;+ }+ return [];+ }+ if (!this.rootsPromise) this.rootsPromise = this.computeRoots();+ return this.rootsPromise;+ }++ /** Drops the cached roots and re-asks the tree; data refetches on next ask. */+ refresh(): void {+ this.rootsPromise = null;+ this.changeEmitter.fire();+ }++ private async computeRoots(): Promise<RepoTreeNode[]> {+ this.ensureWatching();+ const repoId = this.ctx.repoId;+ // Views are gated to the `ready` state, but a state flip can race a pending+ // ask; render empty rather than hitting a null repo.+ if (!repoId) return [];+ return this.guard(() => this.loadRoots(repoId));+ }++ /** Runs a loader, turning any failure into a single "could not load" node. */+ private async guard(+ loader: () => Promise<RepoTreeNode[]>,+ ): Promise<RepoTreeNode[]> {+ try {+ return await loader();+ } catch (err) {+ this.ctx.log.debug(`${this.name} tree load failed: ${String(err)}`);+ return [errorNode()];+ }+ }++ /**+ * Subscribes to index changes on first data ask (not at registration, so a+ * cold start does no filesystem watching). An index rebuild re-resolves the+ * repo record (fresh `head_commit` => fresh cache tag) then refreshes.+ */+ private ensureWatching(): void {+ if (this.freshnessSub) return;+ const watcher = this.ctx.events();+ if (!watcher) return;+ this.freshnessSub = watcher.onDidChange(async (kind) => {+ if (kind !== "indexChanged") return;+ await this.ctx.refreshRepo();+ this.refresh();+ });+ }++ /** Fires a badge with the given count, or clears it when the count is zero. */+ protected setBadge(value: number, tooltip: string): void {+ this.badgeEmitter.fire(value > 0 ? { value, tooltip } : undefined);+ }++ /**+ * Reads a value from the shared cache keyed by (repoId, key, head_commit),+ * fetching and storing on a miss. The head commit is the freshness tag: an+ * index rebuild changes it and the old entry is simply never read again.+ */+ protected async cached<T>(key: string, loader: () => Promise<T>): Promise<T> {+ const repoId = this.ctx.repoId;+ if (!repoId) return loader();+ const tag = this.ctx.repo?.head_commit ?? "";+ const hit = this.ctx.cache.get<T>(repoId, key, tag);+ if (hit !== undefined) return hit;+ const value = await loader();+ this.ctx.cache.set(repoId, key, tag, value);+ return value;+ }++ /** Section root whose children resolve lazily when the section expands. */+ protected section(+ key: string,+ label: string,+ loader: () => Promise<RepoTreeNode[]>,+ ): RepoTreeNode {+ return {+ key,+ label,+ collapsibleState: vscode.TreeItemCollapsibleState.Expanded,+ loadChildren: loader,+ };+ }++ /** A friendly single leaf for empty results ("No findings", etc). */+ protected messageNode(label: string, icon = "info"): RepoTreeNode {+ return {+ key: `msg:${label}`,+ label,+ icon: new vscode.ThemeIcon(icon),+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ };+ }++ dispose(): void {+ this.freshnessSub?.dispose();+ this.changeEmitter.dispose();+ this.badgeEmitter.dispose();+ }+}++/** The single node rendered when a root or section fetch fails. */+export function errorNode(): RepoTreeNode {+ return {+ key: "error",+ label: "Could not load (see log)",+ icon: new vscode.ThemeIcon("warning"),+ collapsibleState: vscode.TreeItemCollapsibleState.None,+ };+}++/**+ * Creates the `TreeView`, wires the badge onto it, and refreshes the provider+ * whenever the extension state settles (entering `ready` loads, leaving it+ * clears). Returns a disposable owning the view and the provider.+ */+export function mountView(+ ctx: RepowiseContext,+ viewId: string,+ provider: RepowiseTreeProvider,+): vscode.Disposable {+ const treeView = vscode.window.createTreeView(viewId, {+ treeDataProvider: provider,+ });+ const subs: vscode.Disposable[] = [+ treeView,+ provider,+ provider.onDidChangeBadge((badge) => {+ treeView.badge = badge;+ }),+ ctx.onDidChangeExtensionState(() => provider.refresh()),+ ];+ return vscode.Disposable.from(...subs);+}++/** Last path segment of a repo-relative, forward-slash server path. */+export function baseName(relPath: string): string {+ return path.posix.basename(relPath);+}++/**+ * A `vscode.open` command for a repo-relative path, selecting `line` (1-based)+ * when known. Server paths are forward-slash and repo-relative, so they join+ * onto the local repo root.+ */+export function openFileCommand(+ ctx: RepowiseContext,+ relPath: string,+ line?: number | null,+): vscode.Command {+ const uri = vscode.Uri.file(+ path.join(ctx.workspace.repoRoot ?? "", relPath),+ );+ const args: unknown[] = [uri];+ if (line != null) {+ const zero = Math.max(0, line - 1);+ const options: vscode.TextDocumentShowOptions = {+ selection: new vscode.Range(zero, 0, zero, 0),+ };+ args.push(options);+ }+ return { command: "vscode.open", title: "Open File", arguments: args };+}++/** Title-cases a snake_case type label, e.g. `extract_method` => `Extract Method`. */+export function humanizeType(type: string): string {+ return type+ .split("_")+ .filter((w) => w.length > 0)+ .map((w) => w.charAt(0).toUpperCase() + w.slice(1))+ .join(" ");+}++/** Truncates to `max` characters, appending an ellipsis when cut. */+export function truncate(text: string, max = 80): string {+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;+}diff --git a/packages/vscode/src/test/extension.test.ts b/packages/vscode/src/test/extension.test.tsindex c42c264ff..c279a5106 100644--- a/packages/vscode/src/test/extension.test.ts+++ b/packages/vscode/src/test/extension.test.ts@@ -28,6 +28,8 @@ describe("Repowise extension", () => {const start = Date.now();await ext.activate();const elapsed = Date.now() - start;+ // Surfaced in the test output so perf runs can read the measured value.+ console.log(`activation: ${elapsed}ms`);assert.strictEqual(ext.isActive, true);assert.ok(elapsed < 2000,diff --git a/packages/vscode/tsconfig.json b/packages/vscode/tsconfig.jsonindex 24309765f..b7ba285c4 100644--- a/packages/vscode/tsconfig.json+++ b/packages/vscode/tsconfig.json@@ -4,6 +4,7 @@"module": "ESNext","moduleResolution": "Bundler","lib": ["ES2022", "DOM"],+ "jsx": "react-jsx","strict": true,"noUncheckedIndexedAccess": true,"exactOptionalPropertyTypes": true,diff --git a/tests/unit/server/test_refactoring.py b/tests/unit/server/test_refactoring.pyindex 05a239b16..063e9a615 100644--- a/tests/unit/server/test_refactoring.py+++ b/tests/unit/server/test_refactoring.py@@ -222,6 +222,30 @@ async def test_type_filter_narrows_plans_but_keeps_summary(client: AsyncClient,assert body["summary"]["total"] == 4+async def test_file_path_filter_narrows_plans_but_keeps_summary(+ client: AsyncClient, app+) -> None:+ repo_id = await _seed(client, app)+ resp = await client.get(+ f"/api/repos/{repo_id}/refactoring/targets",+ params={"file_path": "pkg/a.py"},+ )+ assert resp.status_code == 200+ body = resp.json()+ assert {p["refactoring_type"] for p in body["plans"]} == {"move_method", "break_cycle"}+ assert all(p["file_path"] == "pkg/a.py" for p in body["plans"])+ # Summary stays global, matching the type filter's semantics.+ assert body["summary"]["total"] == 4++ # An unknown path filters everything out rather than erroring.+ empty = await client.get(+ f"/api/repos/{repo_id}/refactoring/targets",+ params={"file_path": "pkg/nope.py"},+ )+ assert empty.status_code == 200+ assert empty.json()["plans"] == []++async def test_plan_detail_by_id(client: AsyncClient, app) -> None:repo_id = await _seed(client, app)listed = (await client.get(f"/api/repos/{repo_id}/refactoring/targets")).json()["plans"]