Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(vscode): hand refactoring plans to AI agents and expose native chat tools (#694)

Raghav Chamadiya6f2aba35ee4e
diff --git a/packages/vscode/package.json b/packages/vscode/package.json
index c54dbfa22..199834378 100644
--- a/packages/vscode/package.json
+++ b/packages/vscode/package.json
@@ -146,6 +146,16 @@
"minimum": 0,
"maximum": 100,
"description": "Minimum historical co-change count before a related file is surfaced by the nudge. Higher values mean fewer, stronger hints."
+ },
+ "repowise.agentHandoff.enabled": {
+ "type": "boolean",
+ "default": true,
+ "description": "Offer lightbulb code actions that hand a detected refactoring plan to your AI agent, alongside the copy-to-clipboard action."
+ },
+ "repowise.agentTools.enabled": {
+ "type": "boolean",
+ "default": true,
+ "description": "Expose Repowise index lookups (search, health, plans, risk, symbols, docs) as native tools your editor's AI chat can call."
}
}
},
@@ -317,6 +327,141 @@
"label": "Repowise"
}
],
+ "languageModelTools": [
+ {
+ "name": "repowise_searchCodebase",
+ "displayName": "Repowise: Search Codebase",
+ "toolReferenceName": "repowiseSearch",
+ "canBeReferencedInPrompt": true,
+ "icon": "$(search)",
+ "tags": ["repowise"],
+ "when": "repowise.agentToolsEnabled",
+ "modelDescription": "Search the Repowise index of this repository: semantic search over documentation pages, files, and symbols. Returns ranked matches with titles, target paths, scores, and snippets. Use it to locate where a concept, feature, or identifier lives before reading files.",
+ "userDescription": "Search the Repowise index of this repository.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "Search query: an identifier, file path, or natural language description."
+ },
+ "limit": {
+ "type": "number",
+ "description": "Maximum number of results (1 to 20, default 5)."
+ }
+ },
+ "required": ["query"]
+ }
+ },
+ {
+ "name": "repowise_getFileHealth",
+ "displayName": "Repowise: File Health",
+ "toolReferenceName": "repowiseFileHealth",
+ "canBeReferencedInPrompt": true,
+ "icon": "$(heart)",
+ "tags": ["repowise"],
+ "when": "repowise.agentToolsEnabled",
+ "modelDescription": "Get code health for one file in this repository: defect, maintainability, and performance scores (0 to 10, higher is healthier) plus line-anchored findings with severity and biomarker type. Use it before editing a file to know what is already flagged, or to check whether a change should also fix nearby findings.",
+ "userDescription": "Health scores and findings for one file.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "filePath": {
+ "type": "string",
+ "description": "Repository-relative path of the file, forward slashes."
+ }
+ },
+ "required": ["filePath"]
+ }
+ },
+ {
+ "name": "repowise_getRefactoringPlans",
+ "displayName": "Repowise: Refactoring Plans",
+ "toolReferenceName": "repowisePlans",
+ "canBeReferencedInPrompt": true,
+ "icon": "$(tools)",
+ "tags": ["repowise"],
+ "when": "repowise.agentToolsEnabled",
+ "modelDescription": "Get the deterministic refactoring plans Repowise computed for one file: refactoring type, target symbol with line range, step-by-step plan, evidence, impact estimate, and blast radius (affected callers and co-change partners). These plans are precomputed from static analysis and git history, not generated on the fly. Follow the plan's steps and constraints when refactoring.",
+ "userDescription": "Precomputed refactoring plans for one file.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "filePath": {
+ "type": "string",
+ "description": "Repository-relative path of the file, forward slashes."
+ }
+ },
+ "required": ["filePath"]
+ }
+ },
+ {
+ "name": "repowise_getBranchRisk",
+ "displayName": "Repowise: Branch Risk",
+ "toolReferenceName": "repowiseBranchRisk",
+ "canBeReferencedInPrompt": true,
+ "icon": "$(pulse)",
+ "tags": ["repowise"],
+ "when": "repowise.agentToolsEnabled",
+ "modelDescription": "Score the defect risk of the current branch's changes against a base branch (0 to 10, higher is riskier), with the drivers behind the score. Use it after making changes to judge whether the change set needs extra review or tests before pushing.",
+ "userDescription": "Defect risk score for the current branch.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "base": {
+ "type": "string",
+ "description": "Base branch or revision to compare against. Omit to use the repository's default branch."
+ }
+ }
+ }
+ },
+ {
+ "name": "repowise_getSymbolInfo",
+ "displayName": "Repowise: Symbol Info",
+ "toolReferenceName": "repowiseSymbol",
+ "canBeReferencedInPrompt": true,
+ "icon": "$(symbol-method)",
+ "tags": ["repowise"],
+ "when": "repowise.agentToolsEnabled",
+ "modelDescription": "Look up a symbol (function, class, method) in one file of this repository: kind, line bounds, callers and callees, ownership, and governing architectural decisions. Use it to judge the blast radius of editing a symbol or to find who depends on it. Omit symbolName to list the file's symbols.",
+ "userDescription": "Callers, callees, and ownership for a symbol.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "filePath": {
+ "type": "string",
+ "description": "Repository-relative path of the file, forward slashes."
+ },
+ "symbolName": {
+ "type": "string",
+ "description": "Name of the symbol to look up. Omit to list all symbols in the file."
+ }
+ },
+ "required": ["filePath"]
+ }
+ },
+ {
+ "name": "repowise_getFileDocs",
+ "displayName": "Repowise: File Docs",
+ "toolReferenceName": "repowiseDocs",
+ "canBeReferencedInPrompt": true,
+ "icon": "$(book)",
+ "tags": ["repowise"],
+ "when": "repowise.agentToolsEnabled",
+ "modelDescription": "Get the generated documentation page for one file in this repository: what the file does, its role in the architecture, key symbols, and relationships. Use it to orient in an unfamiliar file before reading the source.",
+ "userDescription": "Generated documentation for one file.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "filePath": {
+ "type": "string",
+ "description": "Repository-relative path of the file, forward slashes."
+ }
+ },
+ "required": ["filePath"]
+ }
+ }
+ ],
"walkthroughs": [
{
"id": "repowise.gettingStarted",
diff --git a/packages/vscode/src/constants.ts b/packages/vscode/src/constants.ts
index 83591d2d3..fa22dd90e 100644
--- a/packages/vscode/src/constants.ts
+++ b/packages/vscode/src/constants.ts
@@ -44,8 +44,29 @@ export const InternalCommands = {
openRefactoringPlan: "repowise.openRefactoringPlan",
/** Opens the co-change nudge QuickPick; bound to the status-bar item only. */
reviewCochanges: "repowise.reviewCochanges",
+ /** Hand a refactoring plan to Copilot agent mode; bound to code actions. */
+ handPlanToCopilot: "repowise.handPlanToCopilot",
+ /** Hand a refactoring plan to Claude Code; bound to code actions. */
+ handPlanToClaudeCode: "repowise.handPlanToClaudeCode",
} as const;
+/**
+ * Language model tool names, mirrored from the `languageModelTools`
+ * contribution in package.json. The runtime registration in features/lmTools
+ * must cover exactly this set or VS Code drops the missing tools.
+ */
+export const LmToolNames = {
+ searchCodebase: "repowise_searchCodebase",
+ getFileHealth: "repowise_getFileHealth",
+ getRefactoringPlans: "repowise_getRefactoringPlans",
+ getBranchRisk: "repowise_getBranchRisk",
+ getSymbolInfo: "repowise_getSymbolInfo",
+ getFileDocs: "repowise_getFileDocs",
+} as const;
+
+/** Context key gating the language model tools (mirrors agentTools.enabled). */
+export const AGENT_TOOLS_CONTEXT_KEY = "repowise.agentToolsEnabled";
+
/** Sidebar view ids, mirrored from package.json `contributes.views`. */
export const Views = {
/** Welcome/onboarding tree shown until the server is ready. */
diff --git a/packages/vscode/src/core/webviewApi.ts b/packages/vscode/src/core/webviewApi.ts
index 15b0bcc05..638274ce9 100644
--- a/packages/vscode/src/core/webviewApi.ts
+++ b/packages/vscode/src/core/webviewApi.ts
@@ -66,6 +66,8 @@ const SETTING_DEFAULTS: SettingsValues = {
"risk.baseBranch": "",
"changeIntel.cochangeNudge": true,
"changeIntel.cochangeMinScore": 4,
+ "agentHandoff.enabled": true,
+ "agentTools.enabled": true,
};
const SEVERITIES = ["critical", "high", "medium", "low"];
@@ -92,6 +94,8 @@ const SETTING_VALIDATORS: Record<SettingKey, (v: SettingValue) => SettingValue>
"risk.baseBranch": expectString,
"changeIntel.cochangeNudge": expectBoolean,
"changeIntel.cochangeMinScore": (v) => expectNumberInRange(v, 0, 100),
+ "agentHandoff.enabled": expectBoolean,
+ "agentTools.enabled": expectBoolean,
};
function expectBoolean(v: SettingValue): boolean {
diff --git a/packages/vscode/src/extension.ts b/packages/vscode/src/extension.ts
index 1078a67df..650929dcb 100644
--- a/packages/vscode/src/extension.ts
+++ b/packages/vscode/src/extension.ts
@@ -21,6 +21,8 @@ import { registerBranchRisk } from "./features/branchRisk";
import { registerChangeIntel } from "./features/changeIntel";
import { registerStaleness } from "./features/staleness";
import { registerRefactoringLens } from "./features/refactoringLens";
+import { registerAgentHandoff } from "./features/agentHandoff";
+import { registerLmTools } from "./features/lmTools";
import { registerDocs } from "./features/docs";
import { registerWebviews } from "./core/webviews";
import { registerDashboards } from "./features/dashboards";
@@ -92,6 +94,8 @@ export function activate(extCtx: vscode.ExtensionContext): void {
registerChangeIntel(ctx),
registerStaleness(ctx),
registerRefactoringLens(ctx),
+ registerAgentHandoff(ctx),
+ registerLmTools(ctx),
registerDocs(ctx),
registerWebviews(ctx, extCtx.extensionUri),
registerDashboards(ctx),
diff --git a/packages/vscode/src/features/agentHandoff.ts b/packages/vscode/src/features/agentHandoff.ts
new file mode 100644
index 000000000..9e981b772
--- /dev/null
+++ b/packages/vscode/src/features/agentHandoff.ts
@@ -0,0 +1,173 @@
+import { existsSync } from "node:fs";
+import * as path from "node:path";
+import * as vscode from "vscode";
+import { buildRefactoringPlanPrompt, type AiPromptFlavor } from "@repowise-dev/ui/health/ai-prompt-builder";
+import { typeMeta } from "@repowise-dev/ui/refactoring/meta";
+import 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";
+
+/** The Refactor sub-kinds this provider can emit, declared up front so VS Code
+ * only asks us when a Refactor-family action could be shown. */
+const PROVIDED_KINDS = [
+ vscode.CodeActionKind.RefactorExtract,
+ vscode.CodeActionKind.RefactorMove,
+ vscode.CodeActionKind.RefactorRewrite,
+];
+
+/**
+ * Lightbulb code actions that hand a detected refactoring plan to the user's
+ * AI agent: Copilot agent mode, Claude Code, or the clipboard. Gated on the
+ * `repowise.agentHandoff.enabled` setting and the `ready` state; reuses the
+ * per-file plan cache the CodeLens already populates, so showing the lightbulb
+ * costs no extra fetch. The copy action reuses the command the CodeLens owns.
+ */
+export function registerAgentHandoff(ctx: RepowiseContext): vscode.Disposable {
+ return vscode.Disposable.from(
+ vscode.languages.registerCodeActionsProvider(
+ { scheme: "file" },
+ createProvider(ctx),
+ { providedCodeActionKinds: PROVIDED_KINDS },
+ ),
+ vscode.commands.registerCommand(InternalCommands.handPlanToCopilot, (plan: RefactoringPlan) =>
+ handPlanToCopilot(ctx, plan),
+ ),
+ vscode.commands.registerCommand(InternalCommands.handPlanToClaudeCode, (plan: RefactoringPlan) =>
+ handPlanToClaudeCode(ctx, plan),
+ ),
+ );
+}
+
+function createProvider(ctx: RepowiseContext): vscode.CodeActionProvider {
+ return {
+ async provideCodeActions(
+ document: vscode.TextDocument,
+ range: vscode.Range | vscode.Selection,
+ context: vscode.CodeActionContext,
+ token: vscode.CancellationToken,
+ ): Promise<vscode.CodeAction[]> {
+ const enabled = vscode.workspace
+ .getConfiguration(CONFIG_SECTION)
+ .get<boolean>("agentHandoff.enabled", true);
+ if (!enabled || ctx.getExtensionState() !== "ready") return [];
+
+ // Only show up when the editor is asking for Refactor-family actions.
+ if (context.only && !context.only.intersects(vscode.CodeActionKind.Refactor)) {
+ return [];
+ }
+
+ const relPath = repoRelativePath(ctx, document.uri);
+ if (!relPath) return [];
+
+ const plans = await getPlansForFile(ctx, relPath);
+ if (token.isCancellationRequested) return [];
+
+ const actions: vscode.CodeAction[] = [];
+ for (const plan of plans) {
+ if (plan.line_start == null) continue;
+ // Server line numbers are 1-based; editor ranges are 0-based. A plan
+ // without an explicit end covers its start line only.
+ const start = Math.max(0, plan.line_start - 1);
+ const end = Math.max(start, (plan.line_end ?? plan.line_start) - 1);
+ const planRange = new vscode.Range(start, 0, end, Number.MAX_SAFE_INTEGER);
+ if (!planRange.intersection(range)) continue;
+
+ actions.push(...planActions(plan));
+ }
+ return actions;
+ },
+ };
+}
+
+/** Map a plan's type onto the Refactor sub-kind the editor filters on. */
+function planKind(plan: RefactoringPlan): vscode.CodeActionKind {
+ const type = plan.refactoring_type;
+ if (type.includes("extract")) return vscode.CodeActionKind.RefactorExtract;
+ if (type.includes("move")) return vscode.CodeActionKind.RefactorMove;
+ return vscode.CodeActionKind.RefactorRewrite;
+}
+
+/** The three handoff actions for one plan, all under the plan's kind. */
+function planActions(plan: RefactoringPlan): vscode.CodeAction[] {
+ const label = typeMeta(plan.refactoring_type).label;
+ const kind = planKind(plan);
+
+ const make = (title: string, command: string): vscode.CodeAction => {
+ const action = new vscode.CodeAction(title, kind);
+ action.command = { title, command, arguments: [plan] };
+ return action;
+ };
+
+ return [
+ make(`Repowise: Hand ${label} plan to Copilot agent mode`, InternalCommands.handPlanToCopilot),
+ make(`Repowise: Hand ${label} plan to Claude Code`, InternalCommands.handPlanToClaudeCode),
+ make(`Repowise: Copy ${label} plan for agent`, InternalCommands.copyRefactoringPrompt),
+ ];
+}
+
+/**
+ * Open Copilot chat in agent mode seeded with the plan prompt. The chat-open
+ * command is stringly typed and its argument shape is not a stable API, so any
+ * rejection falls back to the clipboard with one confirmation message.
+ */
+async function handPlanToCopilot(ctx: RepowiseContext, plan: RefactoringPlan): Promise<void> {
+ if (!plan) return;
+ const prompt = buildRefactoringPlanPrompt({
+ plan,
+ flavor: "generic",
+ ...(ctx.repo?.name ? { repoName: ctx.repo.name } : {}),
+ });
+ // The chat-open command exists even without a chat provider configured; it
+ // would open the setup view and silently drop the query. Only hand off when
+ // Copilot Chat is actually installed, otherwise the clipboard is the payload.
+ if (vscode.extensions.getExtension("github.copilot-chat")) {
+ try {
+ await vscode.commands.executeCommand("workbench.action.chat.open", {
+ query: prompt,
+ mode: "agent",
+ });
+ return;
+ } catch (err) {
+ ctx.log.debug(`Copilot chat handoff failed, falling back to clipboard: ${String(err)}`);
+ }
+ }
+ await vscode.env.clipboard.writeText(prompt);
+ void vscode.window.showInformationMessage(
+ "Couldn't open Copilot agent mode; the plan prompt was copied to the clipboard. Paste it into your agent chat.",
+ );
+}
+
+/**
+ * Hand the plan to Claude Code. The extension has no prompt-injection command,
+ * so the clipboard is the payload channel: copy the prompt (MCP-aware flavor
+ * when the workspace is configured for the Repowise MCP server), focus the
+ * Claude Code panel when the extension is installed, and confirm once.
+ */
+async function handPlanToClaudeCode(ctx: RepowiseContext, plan: RefactoringPlan): Promise<void> {
+ if (!plan) return;
+ const root = ctx.workspace.repoRoot;
+ const hasMcp =
+ !!root &&
+ (existsSync(path.join(root, ".mcp.json")) || existsSync(path.join(root, ".vscode", "mcp.json")));
+ const flavor: AiPromptFlavor = hasMcp ? "claude-code-mcp" : "claude-code";
+
+ const prompt = buildRefactoringPlanPrompt({
+ plan,
+ flavor,
+ ...(ctx.repo?.name ? { repoName: ctx.repo.name } : {}),
+ });
+ await vscode.env.clipboard.writeText(prompt);
+
+ if (vscode.extensions.getExtension("anthropic.claude-code")) {
+ try {
+ await vscode.commands.executeCommand("claude-vscode.focus");
+ } catch (err) {
+ ctx.log.debug(`Claude Code focus failed: ${String(err)}`);
+ }
+ }
+ void vscode.window.showInformationMessage(
+ "Plan copied for Claude Code. Paste it into the conversation.",
+ );
+}
diff --git a/packages/vscode/src/features/lmTools.ts b/packages/vscode/src/features/lmTools.ts
new file mode 100644
index 000000000..eb59eb83d
--- /dev/null
+++ b/packages/vscode/src/features/lmTools.ts
@@ -0,0 +1,379 @@
+import * as vscode from "vscode";
+import { getHealthFileBreakdown } from "@repowise-dev/api-client/code-health";
+import { getFileDetail } from "@repowise-dev/api-client/files";
+import { getRiskRange } from "@repowise-dev/api-client/risk";
+import { search } from "@repowise-dev/api-client/search";
+import { getSymbolDetail, listSymbols } from "@repowise-dev/api-client/symbols";
+import type { SymbolResponse } from "@repowise-dev/api-client/types";
+import type { HealthFileBreakdownResponse } from "@repowise-dev/types/health";
+import type { SymbolDetailResponse } from "@repowise-dev/types/symbols";
+import { AGENT_TOOLS_CONTEXT_KEY, CONFIG_SECTION, LmToolNames } from "../constants";
+import type { RepowiseContext } from "../core/context";
+import { getFileFindings } from "../core/fileSignals";
+import { getPlansForFile } from "../core/plans";
+
+/**
+ * Native language model tools over the Repowise index, mirroring the
+ * `languageModelTools` contribution in package.json. All six tools are
+ * read-only lookups against the local server; chat invokes them, so every
+ * outcome (including "disabled" and "not connected") flows back as a tool
+ * result rather than a toast.
+ */
+
+/** Hard ceiling on any tool result; the model gets a truncation note, not an error. */
+const MAX_RESULT_CHARS = 30000;
+
+/** Caps mirroring the manifest contract: bounded payloads, never firehoses. */
+const MAX_SEARCH_RESULTS = 20;
+const DEFAULT_SEARCH_RESULTS = 5;
+const MAX_FINDINGS = 50;
+const MAX_PLANS = 10;
+const MAX_SYMBOLS = 100;
+const MAX_SYMBOL_CANDIDATES = 5;
+
+/** Input shapes mirrored from the package.json inputSchema declarations. */
+interface SearchInput {
+ query: string;
+ limit?: number;
+}
+interface FileInput {
+ filePath: string;
+}
+interface BranchRiskInput {
+ base?: string;
+}
+interface SymbolInput {
+ filePath: string;
+ symbolName?: string;
+}
+
+function textResult(text: string): vscode.LanguageModelToolResult {
+ const bounded =
+ text.length > MAX_RESULT_CHARS
+ ? `${text.slice(0, MAX_RESULT_CHARS)}\n[truncated]`
+ : text;
+ return new vscode.LanguageModelToolResult([
+ new vscode.LanguageModelTextPart(bounded),
+ ]);
+}
+
+function jsonResult(payload: unknown): vscode.LanguageModelToolResult {
+ return textResult(JSON.stringify(payload));
+}
+
+/**
+ * Normalizes a repo-relative path from the model: forward slashes, no leading
+ * "./". Returns null for absolute paths or ".." segments; the caller answers
+ * with a polite refusal instead of letting the path reach the server.
+ */
+function normalizeRelPath(input: string): string | null {
+ let rel = input.replace(/\\/g, "/").trim();
+ if (rel.startsWith("./")) rel = rel.slice(2);
+ if (!rel) return null;
+ if (rel.startsWith("/") || /^[A-Za-z]:/.test(rel)) return null;
+ if (rel.split("/").some((segment) => segment === "..")) return null;
+ return rel;
+}
+
+function agentToolsEnabled(): boolean {
+ return vscode.workspace
+ .getConfiguration(CONFIG_SECTION)
+ .get<boolean>("agentTools.enabled", true);
+}
+
+export function registerLmTools(ctx: RepowiseContext): vscode.Disposable {
+ // The manifest `when` clauses hide the tools from pickers via this context
+ // key; the per-invoke guard below is the backstop for calls already in
+ // flight or hosts that ignore the clause.
+ const syncContextKey = (): void => {
+ void vscode.commands.executeCommand(
+ "setContext",
+ AGENT_TOOLS_CONTEXT_KEY,
+ agentToolsEnabled(),
+ );
+ };
+ syncContextKey();
+ const configListener = vscode.workspace.onDidChangeConfiguration((event) => {
+ if (event.affectsConfiguration(`${CONFIG_SECTION}.agentTools.enabled`)) {
+ syncContextKey();
+ }
+ });
+
+ /**
+ * Reads through the shared cache under the current head commit, mirroring
+ * plans.ts. Fetch failures propagate to the per-tool catch, which turns
+ * them into a text result.
+ */
+ async function cached<T>(key: string, fetcher: (repoId: string) => Promise<T>): Promise<T> {
+ const repoId = ctx.repoId;
+ if (!repoId) throw new Error("No repository resolved.");
+ const tag = ctx.repo?.head_commit ?? "";
+ const hit = ctx.cache.get<T>(repoId, key, tag);
+ if (hit !== undefined) return hit;
+ const value = await fetcher(repoId);
+ ctx.cache.set(repoId, key, tag, value);
+ return value;
+ }
+
+ /**
+ * Wraps a tool body with the shared guards: setting toggle, server
+ * readiness, and a catch that reports failures as tool text. Tools never
+ * throw for expected states and never surface UI notifications.
+ */
+ function makeTool<T>(
+ invocationMessage: string,
+ run: (input: T, token: vscode.CancellationToken) => Promise<vscode.LanguageModelToolResult>,
+ ): vscode.LanguageModelTool<T> {
+ return {
+ prepareInvocation: () => ({ invocationMessage }),
+ invoke: async (options, token) => {
+ if (!agentToolsEnabled()) {
+ return textResult(
+ "The Repowise tools are disabled in settings (repowise.agentTools.enabled).",
+ );
+ }
+ if (ctx.getExtensionState() !== "ready" || !ctx.repoId) {
+ return textResult(
+ "The local Repowise server is not connected. The user can start it from the Repowise status bar or the \"Repowise: Start Server\" command.",
+ );
+ }
+ try {
+ return await run(options.input, token);
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ ctx.log.error(`Language model tool failed: ${String(err)}`);
+ return textResult(`Repowise lookup failed: ${message}`);
+ }
+ },
+ };
+ }
+
+ /** Path-taking tools share the normalization refusal. */
+ function badPathResult(raw: string): vscode.LanguageModelToolResult {
+ return textResult(
+ `The path "${raw}" is not a valid repository-relative path. Use forward slashes, relative to the repository root, without ".." segments.`,
+ );
+ }
+
+ const searchTool = makeTool<SearchInput>(
+ "Searching the Repowise index",
+ async (input) => {
+ const repoId = ctx.repoId ?? "";
+ const raw = typeof input.limit === "number" ? Math.floor(input.limit) : DEFAULT_SEARCH_RESULTS;
+ const limit = Math.min(Math.max(raw, 1), MAX_SEARCH_RESULTS);
+ // Queries form an unbounded space, so results are never cached.
+ const results = await search(input.query, { limit, repo_id: repoId });
+ const payload = results.map((r) => ({
+ title: r.title,
+ page_type: r.page_type,
+ target_path: r.target_path,
+ score: r.score,
+ snippet: r.snippet,
+ }));
+ return jsonResult(payload);
+ },
+ );
+
+ const fileHealthTool = makeTool<FileInput>(
+ "Reading file health from Repowise",
+ async (input) => {
+ const rel = normalizeRelPath(input.filePath);
+ if (!rel) return badPathResult(input.filePath);
+ // Same cache key the hover uses, so a hovered file costs the tool nothing.
+ const breakdown = await cached<HealthFileBreakdownResponse>(
+ `breakdown:${rel}`,
+ (repoId) => getHealthFileBreakdown(repoId, rel),
+ );
+ const metric = breakdown.metric;
+ if (!metric) {
+ return textResult(`Repowise has no health data for ${rel}.`);
+ }
+ const findings = await getFileFindings(ctx, rel);
+ return jsonResult({
+ scores: {
+ defect: metric.defect_score ?? metric.score,
+ maintainability: metric.maintainability_score ?? null,
+ performance: metric.performance_score ?? null,
+ },
+ findings: findings.slice(0, MAX_FINDINGS).map((f) => ({
+ severity: f.severity,
+ dimension: f.dimension ?? "defect",
+ biomarker: f.biomarker_type,
+ line_start: f.line_start,
+ line_end: f.line_end,
+ message: f.reason,
+ })),
+ });
+ },
+ );
+
+ const plansTool = makeTool<FileInput>(
+ "Fetching Repowise refactoring plans",
+ async (input) => {
+ const rel = normalizeRelPath(input.filePath);
+ if (!rel) return badPathResult(input.filePath);
+ const plans = await getPlansForFile(ctx, rel);
+ if (plans.length === 0) {
+ return textResult(`Repowise has no refactoring plans for ${rel}.`);
+ }
+ const payload = plans.slice(0, MAX_PLANS).map((p) => ({
+ id: p.id,
+ refactoring_type: p.refactoring_type,
+ target_symbol: p.target_symbol,
+ line_start: p.line_start,
+ line_end: p.line_end,
+ impact_delta: p.impact_delta,
+ effort_bucket: p.effort_bucket,
+ confidence: p.confidence,
+ plan: p.plan,
+ evidence: p.evidence,
+ blast_radius: p.blast_radius,
+ }));
+ return jsonResult(payload);
+ },
+ );
+
+ const branchRiskTool = makeTool<BranchRiskInput>(
+ "Scoring branch risk with Repowise",
+ async (input) => {
+ const repoId = ctx.repoId ?? "";
+ const configured = vscode.workspace
+ .getConfiguration(CONFIG_SECTION)
+ .get<string>("risk.baseBranch", "")
+ .trim();
+ const base =
+ input.base?.trim() || configured || ctx.repo?.default_branch || "main";
+ // Scores the working HEAD, which moves independently of the index, so
+ // this always fetches fresh.
+ const result = await getRiskRange(repoId, { base, head: "HEAD" });
+ return jsonResult({
+ base,
+ score: result.score,
+ level: result.level,
+ probability: result.probability,
+ risk_percentile: result.risk_percentile,
+ review_priority: result.review_priority,
+ drivers: result.drivers,
+ features: result.features,
+ });
+ },
+ );
+
+ const symbolInfoTool = makeTool<SymbolInput>(
+ "Looking up symbol info in Repowise",
+ async (input) => {
+ const rel = normalizeRelPath(input.filePath);
+ if (!rel) return badPathResult(input.filePath);
+ // Same cache key the hover uses, so both features share one fetch.
+ const symbols = await cached<SymbolResponse[]>(`symbols:${rel}`, (repoId) =>
+ listSymbols({ repo_id: repoId, file_path: rel, limit: 1000 }),
+ );
+ if (symbols.length === 0) {
+ return textResult(`Repowise has no indexed symbols for ${rel}.`);
+ }
+
+ const name = input.symbolName?.trim();
+ if (!name) {
+ const payload = symbols.slice(0, MAX_SYMBOLS).map((s) => ({
+ name: s.name,
+ kind: s.kind,
+ line_start: s.start_line,
+ line_end: s.end_line,
+ }));
+ return jsonResult(payload);
+ }
+
+ const match =
+ symbols.find((s) => s.name === name) ??
+ symbols.find((s) => s.name.toLowerCase() === name.toLowerCase());
+ if (!match) {
+ const lower = name.toLowerCase();
+ const near = symbols.filter((s) => s.name.toLowerCase().includes(lower));
+ const candidates = (near.length > 0 ? near : symbols)
+ .slice(0, MAX_SYMBOL_CANDIDATES)
+ .map((s) => s.name);
+ return textResult(
+ `No symbol named "${name}" in ${rel}. Close candidates: ${candidates.join(", ")}.`,
+ );
+ }
+
+ // Shares the hover's cache key and its convention: a failed fetch caches
+ // as null so a dead symbol id is asked once per index version.
+ const detail = await cached<SymbolDetailResponse | null>(
+ `symbolDetail:${match.symbol_id}`,
+ async (repoId) => {
+ try {
+ return await getSymbolDetail(repoId, match.symbol_id);
+ } catch (err) {
+ ctx.log.debug(`symbol detail ${match.symbol_id}: ${String(err)}`);
+ return null;
+ }
+ },
+ );
+ if (!detail) {
+ return jsonResult({
+ name: match.name,
+ kind: match.kind,
+ lines: { start: match.start_line, end: match.end_line },
+ note: "Detail lookup unavailable for this symbol.",
+ });
+ }
+ return jsonResult({
+ name: match.name,
+ kind: detail.symbol.kind,
+ lines: { start: match.start_line, end: match.end_line },
+ owner: detail.file_context?.primary_owner ?? null,
+ callers: detail.graph.callers.map((c) => ({
+ name: c.name,
+ kind: c.kind,
+ file: c.file,
+ line: c.start_line,
+ })),
+ callees: detail.graph.callees.map((c) => ({
+ name: c.name,
+ kind: c.kind,
+ file: c.file,
+ line: c.start_line,
+ })),
+ decisions: detail.governing_decisions.map((d) => d.title),
+ });
+ },
+ );
+
+ const fileDocsTool = makeTool<FileInput>(
+ "Reading Repowise docs",
+ async (input) => {
+ const rel = normalizeRelPath(input.filePath);
+ if (!rel) return badPathResult(input.filePath);
+ // The file-detail aggregate carries the wiki page content inline, the
+ // same fetch the docs panel resolves a file through.
+ const detail = await cached(`lm:docs:${rel}`, (repoId) =>
+ getFileDetail(repoId, rel),
+ );
+ const page = detail.wiki_page;
+ if (!page) {
+ return textResult(`Repowise has no documentation page for ${rel}.`);
+ }
+ const header = JSON.stringify({ title: page.title, path: rel });
+ return textResult(`${header}\n\n# ${page.title}\n\n${page.content}`);
+ },
+ );
+
+ const registrations: vscode.Disposable[] = [configListener];
+ // Fail soft per tool: a host that rejects one registration (an older
+ // proposal surface, a name collision) should not take down the rest.
+ function safeRegister<T>(toolName: string, tool: vscode.LanguageModelTool<T>): void {
+ try {
+ registrations.push(vscode.lm.registerTool(toolName, tool));
+ } catch (err) {
+ ctx.log.warn(`Could not register language model tool ${toolName}: ${String(err)}`);
+ }
+ }
+ safeRegister(LmToolNames.searchCodebase, searchTool);
+ safeRegister(LmToolNames.getFileHealth, fileHealthTool);
+ safeRegister(LmToolNames.getRefactoringPlans, plansTool);
+ safeRegister(LmToolNames.getBranchRisk, branchRiskTool);
+ safeRegister(LmToolNames.getSymbolInfo, symbolInfoTool);
+ safeRegister(LmToolNames.getFileDocs, fileDocsTool);
+ return vscode.Disposable.from(...registrations);
+}
diff --git a/packages/vscode/src/shared/webviewMessages.ts b/packages/vscode/src/shared/webviewMessages.ts
index 3008329ca..73a9808cb 100644
--- a/packages/vscode/src/shared/webviewMessages.ts
+++ b/packages/vscode/src/shared/webviewMessages.ts
@@ -88,6 +88,8 @@ export const SETTING_KEYS = [
"risk.baseBranch",
"changeIntel.cochangeNudge",
"changeIntel.cochangeMinScore",
+ "agentHandoff.enabled",
+ "agentTools.enabled",
] as const;
export type SettingKey = (typeof SETTING_KEYS)[number];
diff --git a/packages/vscode/webview/src/views/settings/App.test.tsx b/packages/vscode/webview/src/views/settings/App.test.tsx
index 930d17c91..781b706cb 100644
--- a/packages/vscode/webview/src/views/settings/App.test.tsx
+++ b/packages/vscode/webview/src/views/settings/App.test.tsx
@@ -25,6 +25,8 @@ const DEFAULTS: SettingsValues = {
"risk.baseBranch": "",
"changeIntel.cochangeNudge": true,
"changeIntel.cochangeMinScore": 4,
+ "agentHandoff.enabled": true,
+ "agentTools.enabled": true,
};
/** Host whose updateSetting echoes the merged map back, like the real one. */
diff --git a/packages/vscode/webview/src/views/settings/App.tsx b/packages/vscode/webview/src/views/settings/App.tsx
index a45952821..25fd4b036 100644
--- a/packages/vscode/webview/src/views/settings/App.tsx
+++ b/packages/vscode/webview/src/views/settings/App.tsx
@@ -145,6 +145,26 @@ const GROUPS: Group[] = [
},
],
},
+ {
+ title: "Agent integration",
+ blurb: "How Repowise shares its index and plans with your AI agent.",
+ rows: [
+ {
+ key: "agentHandoff.enabled",
+ label: "Agent handoff actions",
+ description:
+ "Offer lightbulb code actions that hand a detected refactoring plan to your AI agent, alongside the copy-to-clipboard action.",
+ kind: "toggle",
+ },
+ {
+ key: "agentTools.enabled",
+ label: "Chat tools",
+ description:
+ "Expose Repowise index lookups (search, health, plans, risk, symbols, docs) as native tools your editor's AI chat can call.",
+ kind: "toggle",
+ },
+ ],
+ },
{
title: "Server",
blurb: "How the extension connects to the local Repowise server.",