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(health): roll AI prompt actions across the dashboard (#547)

Raghav Chamadiyad93c300d8d98
diff --git a/packages/ui/src/coupling/coupling-table.tsx b/packages/ui/src/coupling/coupling-table.tsx
index b62b00d88..381ac701a 100644
--- a/packages/ui/src/coupling/coupling-table.tsx
+++ b/packages/ui/src/coupling/coupling-table.tsx
@@ -5,6 +5,7 @@ import {
ResponsiveTable,
type ResponsiveColumn,
} from "../shared/responsive-table";
+import { AiPromptButton } from "../health/ai-prompt-button";
import type { CouplingEdge } from "@repowise-dev/types/coupling";
interface CouplingTableProps {
@@ -12,6 +13,8 @@ interface CouplingTableProps {
/** Focused file (emphasizes rows incident to it; synced with the diagram). */
focusedPath?: string | null;
onFocusChange?: (path: string | null) => void;
+ /** When set, each row shows an "AI decouple prompt" action. */
+ onGeneratePrompt?: (edge: CouplingEdge) => void;
}
function basename(path: string): string {
@@ -23,7 +26,7 @@ function basename(path: string): string {
* coupling, strongest first. Clicking a row focuses that file in the ring;
* rows touching the focused file are emphasized.
*/
-export function CouplingTable({ edges, focusedPath, onFocusChange }: CouplingTableProps) {
+export function CouplingTable({ edges, focusedPath, onFocusChange, onGeneratePrompt }: CouplingTableProps) {
const maxStrength = Math.max(...edges.map((e) => e.strength), 1);
const incident = (e: CouplingEdge) =>
focusedPath != null && (e.source === focusedPath || e.target === focusedPath);
@@ -95,6 +98,23 @@ export function CouplingTable({ edges, focusedPath, onFocusChange }: CouplingTab
</span>
),
},
+ ...(onGeneratePrompt
+ ? [
+ {
+ key: "ai",
+ header: "",
+ priority: 3,
+ headerClassName: "w-10",
+ render: (e: CouplingEdge) => (
+ <AiPromptButton
+ variant="icon"
+ label="AI decouple prompt"
+ onClick={() => onGeneratePrompt(e)}
+ />
+ ),
+ } as ResponsiveColumn<CouplingEdge>,
+ ]
+ : []),
];
return (
diff --git a/packages/ui/src/dashboard/attention-panel.tsx b/packages/ui/src/dashboard/attention-panel.tsx
index 4b867179c..5af459697 100644
--- a/packages/ui/src/dashboard/attention-panel.tsx
+++ b/packages/ui/src/dashboard/attention-panel.tsx
@@ -12,6 +12,9 @@ import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { stripMarkdown } from "../lib/format";
import { fileEntityPath } from "../shared/entity/routes";
+import { AiPromptButton } from "../health/ai-prompt-button";
+import { AiPromptModal } from "../health/ai-prompt-modal";
+import { buildWorkQueueAiPrompt } from "../health/ai-prompt-builder";
export type AttentionItemType =
| "stale_decision"
@@ -60,6 +63,8 @@ interface AttentionPanelProps {
linkPrefix?: string;
/** Initial preview window; expanding the panel reveals all items. */
previewCount?: number;
+ /** Shown next to the title of the generated work-queue prompt. */
+ repoName?: string;
}
function getDefaultHref(item: AttentionItem, prefix: string): string {
@@ -92,9 +97,11 @@ export function AttentionPanel({
repoId,
linkPrefix,
previewCount = 8,
+ repoName,
}: AttentionPanelProps) {
const prefix = linkPrefix ?? `/repos/${repoId}`;
const [expanded, setExpanded] = useState(false);
+ const [promptOpen, setPromptOpen] = useState(false);
const visible = expanded ? items : items.slice(0, previewCount);
if (items.length === 0) {
return (
@@ -109,16 +116,23 @@ export function AttentionPanel({
}
return (
+ <>
<Card>
<CardHeader className="pb-2">
- <CardTitle className="text-sm flex items-center justify-between">
+ <CardTitle className="text-sm flex items-center justify-between gap-2">
<span className="flex items-center gap-2">
<AlertTriangle className="h-4 w-4 text-[var(--color-warning)]" />
Attention Needed
</span>
- <Badge variant="outline" className="text-[10px] h-5 tabular-nums">
- {items.length}
- </Badge>
+ <span className="flex items-center gap-2">
+ <AiPromptButton
+ label="Hand queue to AI"
+ onClick={() => setPromptOpen(true)}
+ />
+ <Badge variant="outline" className="text-[10px] h-5 tabular-nums">
+ {items.length}
+ </Badge>
+ </span>
</CardTitle>
</CardHeader>
<CardContent className="pt-0">
@@ -165,5 +179,25 @@ export function AttentionPanel({
</div>
</CardContent>
</Card>
+ <AiPromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ getPrompt={(flavor) =>
+ buildWorkQueueAiPrompt({
+ items: items.map((it) => ({
+ type: it.type,
+ title: it.title,
+ description: it.description,
+ severity: it.severity,
+ target_id: it.target_id ?? null,
+ })),
+ flavor,
+ ...(repoName ? { repoName } : {}),
+ })
+ }
+ title="AI work queue"
+ description="A ready-to-paste prompt that hands your AI agent this repo's Attention Needed backlog as a prioritized worklist."
+ />
+ </>
);
}
diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsx
index 281ebbe30..ff67573ae 100644
--- a/packages/ui/src/git/hotspot-table.tsx
+++ b/packages/ui/src/git/hotspot-table.tsx
@@ -8,6 +8,7 @@ import { Input } from "../ui/input";
import { EmptyState } from "../shared/empty-state";
import { ResultsFooter } from "../shared/results-footer";
import { RowActions } from "../shared/row-actions";
+import { AiPromptButton } from "../health/ai-prompt-button";
import { ChurnBar } from "./churn-bar";
import { formatLOC } from "../lib/format";
import { cn } from "../lib/cn";
@@ -40,6 +41,8 @@ interface HotspotTableProps {
* The host owns data-fetching and renders the panel body.
*/
renderExpandedRow?: (hotspot: Hotspot) => React.ReactNode;
+ /** When set, each row shows an "AI stabilize" action that calls this. */
+ onGeneratePrompt?: (hotspot: Hotspot) => void;
}
type Filter = "all" | "hot" | "risk" | "accelerating";
@@ -68,6 +71,7 @@ export function HotspotTable({
loadingMore,
onLoadMore,
renderExpandedRow,
+ onGeneratePrompt,
}: HotspotTableProps) {
const expandable = !!renderExpandedRow;
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
@@ -333,6 +337,13 @@ export function HotspotTable({
<div className="flex items-center gap-1">
{h.is_hotspot && <Badge variant="outdated">Hot</Badge>}
{h.is_stable && <Badge variant="fresh">Stable</Badge>}
+ {onGeneratePrompt && (
+ <AiPromptButton
+ variant="icon"
+ label="AI stabilization prompt"
+ onClick={() => onGeneratePrompt(h)}
+ />
+ )}
{prefix && (
<RowActions
actions={[
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index 4f1723d41..46ec486e1 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -37,24 +37,63 @@ const FLAVOR_PREAMBLE: Record<AiPromptFlavor, string> = {
* to the repowise tools it already has instead of repeating the exploration
* repowise did at index time; every other flavor keeps the read-first wording.
*/
+type CloserKind = "refactor" | "coverage" | "security" | "hotspot";
+
+const CLOSER_CONFIG: Record<
+ CloserKind,
+ { mcpSecond: (f: string) => string; mcpInto: string; verb: string; readFirst: string }
+> = {
+ refactor: {
+ mcpSecond: (f) =>
+ `\`get_risk(['${f}'])\` for the blast radius, co-change partners, and test gaps`,
+ mcpInto: "functions below",
+ verb: "propose a fix",
+ readFirst:
+ "Start by reading the file end-to-end, then explore its callers, tests, and any related helpers. The findings below describe symptoms — the actual root cause may live elsewhere. Don't propose a fix until you've grounded each one in the real code.",
+ },
+ coverage: {
+ mcpSecond: (f) =>
+ `\`get_context(['${f}'], include=['callers'])\` to see who exercises it`,
+ mcpInto: "functions you'll test",
+ verb: "write a test",
+ readFirst:
+ "Start by reading the file end-to-end, then explore its callers, the existing tests directory, and any sibling files that test similar code. The coverage numbers below come from a static report — verify them by looking at the real test files and the real source. Don't write a test before you've seen the code it's exercising and the project's existing test conventions.",
+ },
+ security: {
+ mcpSecond: (f) =>
+ `\`get_risk(['${f}'])\` to see who depends on this code before you touch it`,
+ mcpInto: "flagged lines",
+ verb: "change anything",
+ readFirst:
+ "Start by reading the file and the exact lines flagged, then trace how the value flows in and out. The scanner matches patterns — confirm this is actually exploitable in context before you change anything. If it's a false positive (test fixture, sample data, already-sanitized), say so and stop.",
+ },
+ hotspot: {
+ mcpSecond: (f) =>
+ `\`get_risk(['${f}'])\` for the co-change partners and test gaps that make this file risky to touch`,
+ mcpInto: "most-churned functions",
+ verb: "propose changes",
+ readFirst:
+ "Start by reading the file end-to-end, then look at what it co-changes with and how well it's tested. High churn is a symptom — the goal is to make this file safer and cheaper to change, not to rewrite it. Don't propose changes until you understand why it churns.",
+ },
+};
+
+/**
+ * Closing instruction, tailored per surface. The MCP flavor steers the agent to
+ * the repowise tools it already has instead of repeating the exploration
+ * repowise did at index time; every other flavor keeps the read-first wording.
+ */
function explorationCloser(
flavor: AiPromptFlavor,
filePath: string,
- kind: "refactor" | "coverage",
+ kind: CloserKind,
): string {
+ const cfg = CLOSER_CONFIG[kind];
if (flavor === "claude-code-mcp") {
- const second =
- kind === "coverage"
- ? `\`get_context(['${filePath}'], include=['callers'])\` to see who exercises it`
- : `\`get_risk(['${filePath}'])\` for the blast radius, co-change partners, and test gaps`;
- const verb = kind === "coverage" ? "write a test" : "propose a fix";
- const into = kind === "coverage" ? "functions you'll test" : "functions below";
- return `Start with \`get_context(['${filePath}'])\` for the skeleton and ${second}, then \`get_symbol\` into the specific ${into}. repowise already indexed this repo — lean on it before falling back to Read/Grep. The findings describe symptoms; the real root cause may live in a caller or a co-change partner. Don't ${verb} until you've grounded each one in the actual code.`;
- }
- if (kind === "coverage") {
- return "Start by reading the file end-to-end, then explore its callers, the existing tests directory, and any sibling files that test similar code. The coverage numbers below come from a static report — verify them by looking at the real test files and the real source. Don't write a test before you've seen the code it's exercising and the project's existing test conventions.";
+ return `Start with \`get_context(['${filePath}'])\` for the skeleton and ${cfg.mcpSecond(
+ filePath,
+ )}, then \`get_symbol\` into the specific ${cfg.mcpInto}. repowise already indexed this repo — lean on it before falling back to Read/Grep. Don't ${cfg.verb} until you've grounded each finding in the actual code.`;
}
- return "Start by reading the file end-to-end, then explore its callers, tests, and any related helpers. The findings below describe symptoms — the actual root cause may live elsewhere. Don't propose a fix until you've grounded each one in the real code.";
+ return cfg.readFirst;
}
function bulletList(items: (string | null | undefined | false)[]): string {
@@ -397,3 +436,776 @@ export function buildCoverageAiPrompt({
.filter((s) => s !== "")
.join("\n");
}
+
+// ─────────────────────────────────────────────────────────────────────
+// Work-queue prompt (repo-level — the Attention Needed backlog)
+// ─────────────────────────────────────────────────────────────────────
+
+const WORK_QUEUE_PREAMBLE: Record<AiPromptFlavor, string> = {
+ generic:
+ "You are a senior engineer triaging a backlog of issues repowise flagged across this repository. Work through them in priority order, one focused change at a time. Each item is a lead from static + git analysis — verify it against the real code before acting, and skip anything that turns out to be a false positive (say why).",
+ "claude-code":
+ "You are Claude Code clearing a backlog of issues repowise flagged across this repository. Use TodoWrite to track the queue, and Read / Grep / Glob to investigate each item before editing. Work in priority order, one focused, independently-revertible change at a time. Verify each item against the real code; flag false positives instead of forcing a change.",
+ "claude-code-mcp":
+ "You are Claude Code clearing a backlog of issues repowise flagged across this repository, which is indexed by repowise and exposes its MCP tools. Use TodoWrite to track the queue. For each item, pull the context repowise already computed — `get_context([target])` for the skeleton, `get_risk([target])` before editing, `get_why(...)` for decision items, `get_health([target])` for code-health items — instead of re-exploring by hand. Work in priority order, one focused, independently-revertible change at a time. Verify each item; flag false positives.",
+ cursor:
+ "You are clearing a backlog of issues repowise flagged across this repository. Work through them in priority order, one focused change at a time. Use @file and @codebase to investigate each item before editing. Verify each against the real code and skip false positives, saying why.",
+};
+
+const WORK_QUEUE_GUIDANCE: Record<string, string> = {
+ stale_decision:
+ "Re-check this architectural decision against the current code; update it, or supersede it if the code has moved on.",
+ proposed_decision:
+ "Review this auto-proposed decision: confirm it reflects reality and accept it, or reject it with a reason.",
+ knowledge_silo:
+ "One person holds the knowledge for this area (low bus factor). Add tests and docs that make it legible to others.",
+ ungoverned_hotspot:
+ "A high-churn file with no governing decision. Stabilize it (tests, clearer seams) and/or capture the decision behind it.",
+ dead_code:
+ "Verify with a repo-wide search (including dynamic references), then remove it in a small, revertible commit.",
+};
+
+export interface WorkQueueItem {
+ type: string;
+ title: string;
+ description: string;
+ severity: "high" | "medium" | "low";
+ target_id?: string | null;
+}
+
+export interface BuildWorkQueuePromptOptions {
+ items: WorkQueueItem[];
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+const MAX_WORK_QUEUE_ITEMS = 15;
+const SEVERITY_ORDER: Record<string, number> = { high: 0, medium: 1, low: 2 };
+
+export function buildWorkQueueAiPrompt({
+ items,
+ flavor = "generic",
+ repoName,
+}: BuildWorkQueuePromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const ranked = items
+ .slice()
+ .sort((a, b) => (SEVERITY_ORDER[a.severity] ?? 3) - (SEVERITY_ORDER[b.severity] ?? 3));
+ const shown = ranked.slice(0, MAX_WORK_QUEUE_ITEMS);
+ const hidden = ranked.length - shown.length;
+
+ const itemsBlock = shown
+ .map((it, i) => {
+ const guidance = WORK_QUEUE_GUIDANCE[it.type];
+ return [
+ `${i + 1}. [${it.severity.toUpperCase()}] **${it.title}**`,
+ it.description ? ` - Detail: ${it.description}` : null,
+ it.target_id ? ` - Target: \`${it.target_id}\`` : null,
+ guidance ? ` - How to approach: ${guidance}` : null,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ })
+ .join("\n\n");
+
+ const constraintList = [
+ "Work top-down by severity. Finish (or consciously defer) one item before starting the next.",
+ "One focused, independently-revertible change per item — don't bundle unrelated fixes into a single commit.",
+ "Verify each item against the real code first. If it's a false positive, skip it and record why instead of forcing a change.",
+ "Preserve behavior. Add or update tests for anything whose logic you touch.",
+ "If an item is too large for one pass, propose a phased plan for it and move on rather than half-finishing.",
+ ];
+
+ const completionContract = [
+ "1. A triaged plan: the order you'll take these in and why.",
+ "2. For each item you action: the change, scoped and verified, with the tests that cover it.",
+ "3. For each item you skip: a one-line reason (false positive, needs product input, too large — with a proposed follow-up).",
+ "4. A short summary of what's left in the queue at the end.",
+ ];
+
+ return [
+ WORK_QUEUE_PREAMBLE[flavor],
+ "",
+ `## Repository backlog${repoLine}`,
+ "",
+ bulletList([
+ `Items in this queue: **${ranked.length}**`,
+ "Source: repowise's Attention Needed panel (decisions, hotspots, knowledge silos, dead code).",
+ ]),
+ "",
+ "## Issues to work through (highest severity first)",
+ "",
+ itemsBlock,
+ hidden > 0
+ ? `\n…and ${hidden} more lower-priority item${hidden === 1 ? "" : "s"} in the panel — handle these after the above.`
+ : "",
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ flavor === "claude-code-mcp"
+ ? "Start by calling `get_overview()` to orient, then take the queue top-down — `get_context` / `get_risk` / `get_why` per item before you touch anything. repowise already did the exploration; lean on it."
+ : "Start with the highest-severity items and ground each one in the real code before acting. The list describes symptoms; confirm the root cause before you change anything.",
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+// ─────────────────────────────────────────────────────────────────────
+// Dead-code cleanup prompt (bulk — the safe-to-delete pile)
+// ─────────────────────────────────────────────────────────────────────
+
+export interface DeadCodePromptFinding {
+ file_path: string;
+ symbol_name?: string | null;
+ kind?: string | null;
+ reason?: string | null;
+ lines?: number | null;
+ confidence?: number | null;
+ risk_factors?: string[] | null;
+}
+
+export interface BuildDeadCodePromptOptions {
+ findings: DeadCodePromptFinding[];
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+// Cap the file list so a big cleanup pile doesn't produce a giant prompt; the
+// tail is summarized so the agent still knows the full scope.
+const MAX_DEAD_CODE_FILES = 20;
+
+export function buildDeadCodeAiPrompt({
+ findings,
+ flavor = "generic",
+ repoName,
+}: BuildDeadCodePromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+
+ const byFile = new Map<string, DeadCodePromptFinding[]>();
+ for (const f of findings) {
+ byFile.set(f.file_path, [...(byFile.get(f.file_path) ?? []), f]);
+ }
+ const files = Array.from(byFile.entries()).sort(
+ (a, b) =>
+ b[1].reduce((s, f) => s + (f.lines ?? 0), 0) -
+ a[1].reduce((s, f) => s + (f.lines ?? 0), 0),
+ );
+ const shown = files.slice(0, MAX_DEAD_CODE_FILES);
+ const hidden = files.slice(MAX_DEAD_CODE_FILES);
+ const totalLines = findings.reduce((s, f) => s + (f.lines ?? 0), 0);
+
+ const fileBlock = shown
+ .map(([path, fs]) => {
+ const symbols = fs.map((f) => f.symbol_name).filter(Boolean).join(", ");
+ const kinds = Array.from(new Set(fs.map((f) => f.kind).filter(Boolean)));
+ const reason = fs.map((f) => f.reason).filter(Boolean)[0];
+ const risk = Array.from(
+ new Set(fs.flatMap((f) => f.risk_factors ?? [])),
+ );
+ return [
+ `- \`${path}\`${symbols ? ` — ${symbols}` : ""}`,
+ kinds.length ? ` - Kind: ${kinds.join(", ")}` : null,
+ reason ? ` - Why flagged: ${reason}` : null,
+ risk.length ? ` - Runtime-load risk to rule out first: ${risk.join(", ")}` : null,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ })
+ .join("\n");
+
+ const hiddenLine =
+ hidden.length > 0
+ ? `…and ${hidden.length} more file${hidden.length === 1 ? "" : "s"} in the same pile (open the dead-code report in repowise for the full list).`
+ : null;
+
+ const constraintList = [
+ "**Verify before deleting.** Each entry was flagged by static analysis, not proven dead. Search the whole repo (including config, DI containers, string-based imports, templates, and tests) for every symbol before removing it.",
+ "Watch for dynamic access: reflection, `getattr`/`importlib`, dependency-injection registries, plugin discovery, serialization, and public-API re-exports can use code that looks unreferenced.",
+ "Delete in small, reviewable commits grouped by area — not one giant sweep. Keep each commit independently revertible.",
+ "Run the full test suite (and a build/type-check) after each group. If anything fails, the symbol wasn't dead — restore it and note why.",
+ "Remove now-orphaned imports, fixtures, and tests that only existed for the deleted code.",
+ "If a finding turns out to be reachable, mark it as a false positive in your summary instead of forcing the deletion.",
+ ];
+
+ const completionContract = [
+ "1. A short plan grouping the deletions into safe, independently-revertible commits.",
+ "2. The deletions themselves, with the cross-repo search you ran to confirm each one is unused.",
+ "3. The test/build result after each group.",
+ "4. A list of any findings you skipped as false positives, with the reference that kept them alive.",
+ ];
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Dead-code cleanup${repoLine}`,
+ "",
+ bulletList([
+ `Files in this pile: **${files.length}**`,
+ `Estimated reclaimable lines: **${totalLines.toLocaleString()}**`,
+ "Source: repowise dead-code analysis (high-confidence, safe-to-delete tier).",
+ ]),
+ "",
+ "## Files to clean up (largest first)",
+ "",
+ fileBlock,
+ hiddenLine ?? "",
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ flavor === "claude-code-mcp"
+ ? "For each file, call `get_risk([...])` to see who still imports it and `get_context([...])` for its exported surface before deleting — repowise already mapped the dependency graph, so use it instead of grepping blind. A file with live dependents is not dead; surface that and skip it."
+ : "Start with the largest files. For each, run a repo-wide search for its name and every exported symbol before you delete anything — the analyzer can't see dynamic or string-based references. A file with live dependents is not dead; skip it and say so.",
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+// ─────────────────────────────────────────────────────────────────────
+// Coupling decouple prompt (per co-change pair)
+// ─────────────────────────────────────────────────────────────────────
+
+export interface CouplingPromptEdge {
+ source: string;
+ target: string;
+ strength?: number | null;
+ last_co_change?: string | null;
+}
+
+export interface BuildCouplingPromptOptions {
+ edge: CouplingPromptEdge;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+export function buildCouplingAiPrompt({
+ edge,
+ flavor = "generic",
+ repoName,
+}: BuildCouplingPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const last = edge.last_co_change
+ ? new Date(edge.last_co_change).toISOString().slice(0, 10)
+ : null;
+
+ const constraintList = [
+ "**Diagnose before decoupling.** Read both files and the commits that touched them together. The coupling may be legitimate (two halves of one feature) or accidental (a leaky abstraction, a shared constant, copy-paste). Name which it is before acting.",
+ "If it's accidental, fix the cause: extract the shared concept into one owner, invert the dependency, or introduce a stable interface — don't just move code around.",
+ "If it's legitimate and unavoidable, say so and stop. Forcing a split that the domain doesn't support makes things worse.",
+ "Preserve behavior. This is a structural change, not a feature change.",
+ "Add or update tests so the new boundary is exercised and the old hidden contract can't silently regress.",
+ ];
+
+ const completionContract = [
+ "1. A verdict: is this coupling accidental or legitimate, and what's the underlying shared concern?",
+ "2. If accidental — a concrete decoupling plan (extract / invert / interface), smallest-risk first.",
+ "3. The first change, scoped and behavior-preserving, with its tests.",
+ "4. If legitimate — the reason to leave it, and any lighter-touch improvement (docs, a shared module) worth doing instead.",
+ ];
+
+ const closer =
+ flavor === "claude-code-mcp"
+ ? `Call \`get_risk(['${edge.source}'])\` and \`get_context(['${edge.source}', '${edge.target}'])\` to see what else each file pulls in before you plan the split — repowise already mapped the dependency graph and the co-change history. Don't restructure until you know why they move together.`
+ : "Start by reading both files and `git log` for the commits that changed them together. The co-change count is a symptom; find the shared concern driving it before you restructure anything.";
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Hidden coupling to untangle${repoLine}`,
+ "",
+ bulletList([
+ `File A: \`${edge.source}\``,
+ `File B: \`${edge.target}\``,
+ edge.strength != null
+ ? `Coupling strength: **${edge.strength}** (recency-weighted count of commits that changed both — not a verified dependency)`
+ : null,
+ last ? `Last changed together: ${last}` : null,
+ "Source: repowise co-change analysis (git history — treat as a lead).",
+ ]),
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ closer,
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+// ─────────────────────────────────────────────────────────────────────
+// Conformance prompt (bulk — architecture rule violations)
+// ─────────────────────────────────────────────────────────────────────
+
+export interface ConformancePromptViolation {
+ source: string;
+ target: string;
+ source_name?: string | null;
+ target_name?: string | null;
+ edge_kind?: string | null;
+ rule_source?: string | null;
+ rule_target?: string | null;
+ rule_description?: string | null;
+}
+
+export interface BuildConformancePromptOptions {
+ violations: ConformancePromptViolation[];
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+const MAX_CONFORMANCE_VIOLATIONS = 20;
+
+export function buildConformanceAiPrompt({
+ violations,
+ flavor = "generic",
+ repoName,
+}: BuildConformancePromptOptions): string {
+ const wsLine = repoName ? ` (\`${repoName}\`)` : "";
+ const shown = violations.slice(0, MAX_CONFORMANCE_VIOLATIONS);
+ const hidden = violations.length - shown.length;
+
+ const block = shown
+ .map((v, i) => {
+ const src = v.source_name || v.source;
+ const tgt = v.target_name || v.target;
+ const rule =
+ v.rule_source && v.rule_target
+ ? `${v.rule_source} !-> ${v.rule_target}`
+ : null;
+ return [
+ `${i + 1}. **${src} → ${tgt}**${v.edge_kind ? ` (${v.edge_kind})` : ""}`,
+ rule ? ` - Breaks rule: \`${rule}\`` : null,
+ v.rule_description ? ` - Rule intent: ${v.rule_description}` : null,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ })
+ .join("\n\n");
+
+ const constraintList = [
+ "**Fix the architecture, not the rule.** The goal is to remove the disallowed dependency, not to relax the declared rule (unless the rule is genuinely wrong — if so, say so and stop).",
+ "For each violation, find the actual import/call/event that creates the edge, then choose the right fix: invert the dependency, introduce a shared interface/contract module, move the shared code to an allowed layer, or route through an allowed intermediary.",
+ "Preserve behavior. These are structural changes across service boundaries — keep the public contract stable.",
+ "Tackle one violation (or one tightly-related cluster) per change so each is reviewable and revertible.",
+ "Update or add tests that would catch the boundary regressing again.",
+ ];
+
+ const completionContract = [
+ "1. For each violation: the exact code that creates the disallowed edge (file + symbol).",
+ "2. The chosen fix and why it's the right one (invert / interface / move / intermediary).",
+ "3. The change itself, scoped per violation, with tests.",
+ "4. Any violation you believe reflects a wrong rule rather than wrong code, with your reasoning.",
+ ];
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Architecture conformance violations${wsLine}`,
+ "",
+ bulletList([
+ `Violations: **${violations.length}** dependencies that break a declared rule.`,
+ "Source: repowise workspace conformance check (live dependency graph vs declared rules).",
+ ]),
+ "",
+ "## Violations to resolve",
+ "",
+ block,
+ hidden > 0
+ ? `\n…and ${hidden} more violation${hidden === 1 ? "" : "s"} — resolve these after the above.`
+ : "",
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ flavor === "claude-code-mcp"
+ ? "For each violation, use `get_blast_radius` / `get_context` on the two services to find the exact edge and what else rides on it before you cut it — repowise already resolved the cross-repo graph. Don't restructure blind."
+ : "For each violation, locate the real import/call/event that creates the edge before proposing a fix. The rule names the boundary; the code is where you'll actually sever it.",
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+// ─────────────────────────────────────────────────────────────────────
+// Security remediation prompt (per finding)
+// ─────────────────────────────────────────────────────────────────────
+
+export interface SecurityPromptFinding {
+ file_path: string;
+ kind: string;
+ severity: string;
+ snippet?: string | null;
+}
+
+export interface BuildSecurityPromptOptions {
+ finding: SecurityPromptFinding;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+export function buildSecurityAiPrompt({
+ finding,
+ flavor = "generic",
+ repoName,
+}: BuildSecurityPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const isSecret = /secret|key|token|credential|password/i.test(finding.kind);
+
+ const constraintList = [
+ "**Confirm it's real first.** Reproduce the issue or trace the data flow before editing. Pattern scanners over-flag — test fixtures, sample data, and already-sanitized paths are common false positives. If this is one, say so and stop.",
+ isSecret
+ ? "If this is a live secret, the fix is two-part: (1) remove it from the code and load it from a secret manager / env var, and (2) call out that the secret must be **rotated** — it is compromised the moment it lands in git history."
+ : "Fix the root cause, not the symptom — validate/escape/parameterize at the boundary rather than blocking one known-bad input.",
+ "Preserve behavior for legitimate inputs. Don't break the feature to silence the scanner.",
+ "Add or update a test that fails on the vulnerable behavior and passes after the fix, where the project's setup allows it.",
+ "Don't introduce a new dependency for this unless there's no safe stdlib/first-party option; if you do, justify it.",
+ ];
+
+ const completionContract = [
+ "1. A one-line verdict: is this exploitable, and how (or why it's a false positive)?",
+ "2. The fix, scoped to the smallest change that closes the issue.",
+ "3. The test that now covers it, if one was feasible.",
+ isSecret ? "4. An explicit rotation/remediation note for the exposed secret." : "4. Any related spots in the codebase with the same pattern that should get the same fix.",
+ ];
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Security finding${repoLine}`,
+ "",
+ bulletList([
+ `File: \`${finding.file_path}\``,
+ `Type: **${finding.kind}**`,
+ `Severity: **${finding.severity.toUpperCase()}**`,
+ "Source: repowise local security scan (pattern-based — treat as a lead).",
+ ]),
+ "",
+ finding.snippet
+ ? ["## Flagged code", "", "```", finding.snippet, "```", ""].join("\n")
+ : "",
+ "## Your task",
+ "",
+ `Investigate and remediate this ${finding.kind} finding in \`${finding.file_path}\`.`,
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ explorationCloser(flavor, finding.file_path, "security"),
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+// ─────────────────────────────────────────────────────────────────────
+// Hotspot stabilization prompt (per file)
+// ─────────────────────────────────────────────────────────────────────
+
+export interface HotspotPromptInput {
+ file_path: string;
+ churn_percentile?: number | null;
+ commit_count_90d?: number | null;
+ commit_count_30d?: number | null;
+ bus_factor?: number | null;
+ contributor_count?: number | null;
+ primary_owner?: string | null;
+ lines_added_90d?: number | null;
+ lines_deleted_90d?: number | null;
+ temporal_hotspot_score?: number | null;
+ change_entropy_pct?: number | null;
+ prior_defect_count?: number | null;
+ module?: string | null;
+}
+
+export interface BuildHotspotPromptOptions {
+ hotspot: HotspotPromptInput;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+export function buildHotspotAiPrompt({
+ hotspot: h,
+ flavor = "generic",
+ repoName,
+}: BuildHotspotPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const soleOwner = h.bus_factor != null && h.bus_factor <= 1;
+
+ const constraintList = [
+ "**Understand the churn before touching it.** A hotspot is a file that keeps changing — find out why (a god module, mixed responsibilities, a leaky abstraction, missing tests) before proposing structure changes.",
+ "Make it safer to change, don't just rewrite it. Behavior-preserving refactors, better seams, and tests beat a from-scratch rewrite.",
+ soleOwner
+ ? "This file has a low bus factor (one person holds the knowledge). Favor changes that make it more legible to others — clear names, docs on the non-obvious parts, tests that document intent."
+ : "Keep the change reviewable — a single coherent improvement, not a sprawling rewrite.",
+ "Because this file changes often, raise its test coverage as part of the work — that's what makes future changes cheap.",
+ "Check its co-change partners: if it always changes alongside another file, the coupling itself may be the thing to fix.",
+ ];
+
+ const completionContract = [
+ "1. A diagnosis: why does this file churn so much? (2–4 bullets, grounded in the actual code and its history.)",
+ "2. A prioritized plan to reduce its change-cost — structural seams, extractions, or decoupling, smallest-risk first.",
+ "3. The change you'd make first, scoped and behavior-preserving, with the tests that protect it.",
+ "4. What you'd leave for later and why.",
+ ];
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Hotspot to stabilize${repoLine}`,
+ "",
+ `\`${h.file_path}\``,
+ "",
+ "## Why it's flagged",
+ "",
+ bulletList([
+ h.churn_percentile != null
+ ? `Churn: **${Math.round(h.churn_percentile)}th percentile** in this repo (it changes more than most files)`
+ : null,
+ h.commit_count_90d != null
+ ? `Commits: **${h.commit_count_90d} in 90 days**${h.commit_count_30d != null ? ` (${h.commit_count_30d} in the last 30)` : ""}`
+ : null,
+ h.bus_factor != null
+ ? `Bus factor: **${h.bus_factor}**${soleOwner ? " — knowledge concentrated in one person" : ""}`
+ : null,
+ h.contributor_count != null ? `Contributors: ${h.contributor_count}` : null,
+ h.primary_owner ? `Primary owner: ${h.primary_owner}` : null,
+ h.lines_added_90d != null || h.lines_deleted_90d != null
+ ? `Lines churned (90d): +${h.lines_added_90d ?? 0} / −${h.lines_deleted_90d ?? 0}`
+ : null,
+ h.change_entropy_pct != null
+ ? `Change entropy: ${Math.round(h.change_entropy_pct)}th percentile (how scattered the edits are)`
+ : null,
+ h.prior_defect_count != null && h.prior_defect_count > 0
+ ? `Prior bug-fix commits here: ${h.prior_defect_count}`
+ : null,
+ h.module ? `Module: \`${h.module}\`` : null,
+ ]),
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ explorationCloser(flavor, h.file_path, "hotspot"),
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+// ─────────────────────────────────────────────────────────────────────
+// Decision verification prompt (per architectural decision)
+// ─────────────────────────────────────────────────────────────────────
+
+export interface DecisionPromptInput {
+ title: string;
+ status: string;
+ context?: string | null;
+ decision?: string | null;
+ rationale?: string | null;
+ alternatives?: string[];
+ consequences?: string[];
+ affected_modules?: string[];
+ affected_files?: string[];
+ staleness_score?: number | null;
+ confidence?: number | null;
+}
+
+export interface BuildDecisionPromptOptions {
+ decision: DecisionPromptInput;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+export function buildDecisionAiPrompt({
+ decision: d,
+ flavor = "generic",
+ repoName,
+}: BuildDecisionPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const isProposed = d.status === "proposed";
+ const isStale = (d.staleness_score ?? 0) > 0.5;
+ const scope = [...(d.affected_modules ?? []), ...(d.affected_files ?? [])];
+
+ const task = isProposed
+ ? "repowise auto-proposed this architectural decision from the code and history. Verify it: does the codebase actually reflect this decision today? Then recommend whether to **confirm** it (it's real and current) or **reject** it (it's wrong, speculative, or already superseded)."
+ : isStale
+ ? "This recorded decision is flagged stale — the code it governs has changed since it was written. Re-verify it against the current code and recommend whether to **keep**, **update**, or **deprecate** it."
+ : "Verify this recorded decision against the current code: is it still honored in the implementation? Recommend whether to keep, update, or deprecate it.";
+
+ const constraintList = [
+ "Ground every claim in the actual code, not the decision text. The decision describes intent; the code is the truth. Where they disagree, the code wins and the decision is stale.",
+ scope.length > 0
+ ? "Start from the affected modules/files listed below, then follow the dependency graph to anything that should obey this decision but doesn't."
+ : "Identify which parts of the codebase this decision governs, then check them for conformance.",
+ "Cite specific files/symbols as evidence for your verdict — don't assert without a reference.",
+ "Distinguish 'the decision is wrong' from 'the code drifted from a still-good decision' — they lead to opposite actions (reject/deprecate vs. fix the code).",
+ "Do not change code as part of this task unless asked — this is a verification, not an implementation.",
+ ];
+
+ const completionContract = [
+ `1. A verdict: ${isProposed ? "**confirm** or **reject**" : "**keep**, **update**, or **deprecate**"}, in one line.`,
+ "2. The evidence: the files/symbols you checked and whether each conforms.",
+ "3. Any conformance gaps — places that violate the decision — as a short list.",
+ "4. If you'd update the decision text, the exact wording you'd change.",
+ ];
+
+ const closer =
+ flavor === "claude-code-mcp"
+ ? `Use \`get_why('${d.title.replace(/'/g, "")}')\` for the recorded rationale and \`get_context([${scope.slice(0, 3).map((s) => `'${s}'`).join(", ")}])\` for the governed code — repowise links decisions to graph nodes, so verify against that instead of guessing. Then check conformance file by file.`
+ : "Read the decision below, then open the code it governs and check it line up. The decision is a claim about the code — your job is to confirm or refute it with evidence.";
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Architectural decision to verify${repoLine}`,
+ "",
+ bulletList([
+ `Title: **${d.title}**`,
+ `Status: ${d.status}`,
+ d.confidence != null ? `Recorded confidence: ${Math.round(d.confidence * 100)}%` : null,
+ isStale ? `Staleness: ${(d.staleness_score ?? 0).toFixed(2)} — flagged stale` : null,
+ scope.length > 0 ? `Governs: ${scope.slice(0, 8).map((s) => `\`${s}\``).join(", ")}${scope.length > 8 ? `, +${scope.length - 8} more` : ""}` : null,
+ ]),
+ "",
+ d.context ? ["## Context", "", d.context, ""].join("\n") : "",
+ d.decision ? ["## Decision", "", d.decision, ""].join("\n") : "",
+ d.rationale ? ["## Rationale", "", d.rationale, ""].join("\n") : "",
+ d.alternatives && d.alternatives.length > 0
+ ? ["## Alternatives rejected", "", bulletList(d.alternatives), ""].join("\n")
+ : "",
+ d.consequences && d.consequences.length > 0
+ ? ["## Consequences", "", bulletList(d.consequences), ""].join("\n")
+ : "",
+ "## Your task",
+ "",
+ task,
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ closer,
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
+
+// ─────────────────────────────────────────────────────────────────────
+// Commit review prompt (per commit)
+// ─────────────────────────────────────────────────────────────────────
+
+export interface CommitPromptInput {
+ sha: string;
+ subject: string;
+ review_priority?: string | null;
+ risk_percentile?: number | null;
+ change_risk_score?: number | null;
+ is_fix?: boolean;
+ files_changed?: number | null;
+ lines_added?: number | null;
+ lines_deleted?: number | null;
+ entropy?: number | null;
+ top_drivers?: string[];
+ author_name?: string | null;
+}
+
+export interface BuildCommitPromptOptions {
+ commit: CommitPromptInput;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+export function buildCommitAiPrompt({
+ commit: c,
+ flavor = "generic",
+ repoName,
+}: BuildCommitPromptOptions): string {
+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";
+ const short = c.sha.slice(0, 10);
+
+ const constraintList = [
+ "Read the diff first. The risk score is a prior, not a verdict — a high score on a mechanical rename is fine; a low score hiding a logic change is not.",
+ "Focus on what the change-risk drivers flag: scattered edits, missing tests, a hotspot touch, a new-to-the-area author. Confirm each against the actual diff.",
+ "Check the blast radius: what depends on the changed files, and is anything that usually changes with them missing from this commit?",
+ "Call out missing or weak test coverage for the behavior this commit changes.",
+ "Be specific — reference files and lines. A review that says 'looks risky' is useless.",
+ ];
+
+ const completionContract = [
+ "1. A one-paragraph risk read: is this commit actually risky, and where?",
+ "2. The specific things a reviewer should scrutinize, as a checklist tied to files.",
+ "3. Suggested reviewers — who owns or recently changed the affected code.",
+ "4. Any missing tests or co-change partners that should have been in this commit.",
+ ];
+
+ const closer =
+ flavor === "claude-code-mcp"
+ ? `Call \`get_risk(changed_files=[...])\` for this commit's files to get the blast radius, co-change partners, missing-test directive, and owners in one shot — repowise computes all of that. Then read the diff and ground each flag.`
+ : `Start with \`git show ${short}\` to read the diff, then check who owns and recently touched the changed files. Ground every risk call in the actual change.`;
+
+ return [
+ FLAVOR_PREAMBLE[flavor],
+ "",
+ `## Commit to review${repoLine}`,
+ "",
+ bulletList([
+ `Commit: \`${short}\` — ${c.subject || "(no subject)"}`,
+ c.author_name ? `Author: ${c.author_name}` : null,
+ c.is_fix ? "Tagged as a bug-fix commit." : null,
+ c.review_priority ? `Review priority (repo-relative): **${c.review_priority}**` : null,
+ c.risk_percentile != null ? `Risk percentile in this repo: ${Math.round(c.risk_percentile)}th` : null,
+ c.change_risk_score != null ? `Raw change-risk score: ${c.change_risk_score.toFixed(1)}/10` : null,
+ c.files_changed != null ? `Files changed: ${c.files_changed}` : null,
+ c.lines_added != null || c.lines_deleted != null
+ ? `Lines: +${c.lines_added ?? 0} / −${c.lines_deleted ?? 0}`
+ : null,
+ c.entropy != null ? `Change entropy: ${c.entropy.toFixed(2)} (how scattered the edits are)` : null,
+ c.top_drivers && c.top_drivers.length > 0
+ ? `Top risk drivers: ${c.top_drivers.slice(0, 3).join(", ")}`
+ : null,
+ ]),
+ "",
+ "## Hard constraints",
+ "",
+ bulletList(constraintList),
+ "",
+ "## What I expect back",
+ "",
+ completionContract.join("\n"),
+ "",
+ closer,
+ ]
+ .filter((s) => s !== "")
+ .join("\n");
+}
diff --git a/packages/ui/src/health/ai-prompt-button.tsx b/packages/ui/src/health/ai-prompt-button.tsx
new file mode 100644
index 000000000..6680b7b5f
--- /dev/null
+++ b/packages/ui/src/health/ai-prompt-button.tsx
@@ -0,0 +1,63 @@
+"use client";
+
+import { Sparkles } from "lucide-react";
+import { cn } from "../lib/cn";
+
+export interface AiPromptButtonProps {
+ onClick: () => void;
+ /** Visible label for the default variant; also used as the title/aria-label. */
+ label?: string;
+ /**
+ * `default` shows the green sparkles pill with a label (cards, headers).
+ * `icon` is a compact icon-only button for dense table rows; the label
+ * still rides along as the tooltip / accessible name.
+ */
+ variant?: "default" | "icon";
+ className?: string;
+}
+
+/**
+ * Canonical "hand this to an AI agent" affordance. One button, used everywhere
+ * an AI prompt can be generated (refactor, coverage, dead code, security,
+ * hotspots) so the action reads the same on every screen. The host owns the
+ * click — typically opening the shared AiPromptModal.
+ */
+export function AiPromptButton({
+ onClick,
+ label = "AI fix prompt",
+ variant = "default",
+ className,
+}: AiPromptButtonProps) {
+ const base =
+ "group/ai inline-flex items-center gap-1.5 rounded-md border border-[var(--color-success)]/40 bg-[var(--color-success)]/10 font-semibold text-[var(--color-success)] transition-colors hover:bg-[var(--color-success)]/20 hover:border-[var(--color-success)]/60";
+ if (variant === "icon") {
+ return (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onClick();
+ }}
+ title={label}
+ aria-label={label}
+ className={cn(base, "h-6 w-6 justify-center p-0", className)}
+ >
+ <Sparkles className="h-3.5 w-3.5 transition-transform group-hover/ai:rotate-12" />
+ </button>
+ );
+ }
+ return (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ onClick();
+ }}
+ title={label}
+ className={cn(base, "px-2.5 py-1 text-xs", className)}
+ >
+ <Sparkles className="h-3.5 w-3.5 transition-transform group-hover/ai:rotate-12" />
+ {label}
+ </button>
+ );
+}
diff --git a/packages/ui/src/health/index.ts b/packages/ui/src/health/index.ts
index d0f746e90..394673a92 100644
--- a/packages/ui/src/health/index.ts
+++ b/packages/ui/src/health/index.ts
@@ -31,6 +31,7 @@ export * from "./churn-complexity-quadrant";
export * from "./health-file-drawer";
export * from "./ai-prompt-builder";
export * from "./ai-prompt-modal";
+export * from "./ai-prompt-button";
export * from "./hot-functions-panel";
export * from "./hidden-coupling-list";
export * from "./recalibration-banner";
diff --git a/packages/ui/src/security/findings-table.tsx b/packages/ui/src/security/findings-table.tsx
index 7a9b06b93..810b18386 100644
--- a/packages/ui/src/security/findings-table.tsx
+++ b/packages/ui/src/security/findings-table.tsx
@@ -5,6 +5,7 @@ import { Search } from "lucide-react";
import { Badge } from "../ui/badge";
import { Input } from "../ui/input";
import { EmptyState } from "../shared/empty-state";
+import { AiPromptButton } from "../health/ai-prompt-button";
export interface SecurityFinding {
id: number;
@@ -24,9 +25,11 @@ const SEVERITY_VARIANT: Record<string, "outdated" | "stale" | "outline"> = {
export interface SecurityFindingsTableProps {
findings: SecurityFinding[];
onSelect?: (finding: SecurityFinding) => void;
+ /** When set, each row shows an "AI fix prompt" action that calls this. */
+ onGeneratePrompt?: (finding: SecurityFinding) => void;
}
-export function SecurityFindingsTable({ findings, onSelect }: SecurityFindingsTableProps) {
+export function SecurityFindingsTable({ findings, onSelect, onGeneratePrompt }: SecurityFindingsTableProps) {
const [q, setQ] = useState("");
const [sev, setSev] = useState<"all" | "high" | "med" | "low">("all");
@@ -108,6 +111,7 @@ export function SecurityFindingsTable({ findings, onSelect }: SecurityFindingsTa
<th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-28">
Detected
</th>
+ {onGeneratePrompt && <th className="px-3 py-2.5 w-10" />}
</tr>
</thead>
<tbody>
@@ -137,6 +141,15 @@ export function SecurityFindingsTable({ findings, onSelect }: SecurityFindingsTa
<td className="px-3 py-2 text-xs text-[var(--color-text-tertiary)] tabular-nums">
{new Date(f.detected_at).toLocaleDateString()}
</td>
+ {onGeneratePrompt && (
+ <td className="px-3 py-2" onClick={(e) => e.stopPropagation()}>
+ <AiPromptButton
+ variant="icon"
+ label="AI fix prompt"
+ onClick={() => onGeneratePrompt(f)}
+ />
+ </td>
+ )}
</tr>
))}
</tbody>
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index e0ae7a8ad..351eb8aa5 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -151,7 +151,7 @@ export default async function OverviewPage({ params }: Props) {
rail={
<>
<SavingsMini data={summary.savings} repoId={id} />
- <AttentionPanel items={attentionItems} repoId={id} previewCount={5} />
+ <AttentionPanel items={attentionItems} repoId={id} previewCount={5} repoName={repo.name} />
</>
}
/>
diff --git a/packages/web/src/app/workspace/conformance/page.tsx b/packages/web/src/app/workspace/conformance/page.tsx
index f222b9f99..9b48ce2e9 100644
--- a/packages/web/src/app/workspace/conformance/page.tsx
+++ b/packages/web/src/app/workspace/conformance/page.tsx
@@ -1,9 +1,10 @@
"use client";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { ShieldCheck, ShieldAlert, RefreshCw, Waypoints, ListChecks, Gauge } from "lucide-react";
import { buildDsm, DsmMatrixView } from "@repowise-dev/ui/workspace/dsm";
+import { AiPromptButton, AiPromptModal, buildConformanceAiPrompt } from "@repowise-dev/ui/health";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { StatCard } from "@repowise-dev/ui/shared/stat-card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
@@ -15,6 +16,7 @@ import {
export default function ConformancePage() {
const router = useRouter();
+ const [promptOpen, setPromptOpen] = useState(false);
const { data: graph, isLoading: graphLoading } = useWorkspaceSystemGraph();
const { data: report, isLoading: reportLoading } = useWorkspaceConformance();
const { data: metrics } = useWorkspaceArchitecture();
@@ -105,11 +107,17 @@ export default function ConformancePage() {
{/* Governance findings */}
<div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Card>
- <CardHeader className="pb-2">
+ <CardHeader className="pb-2 flex-row items-center justify-between gap-2">
<CardTitle className="text-sm font-medium inline-flex items-center gap-2">
<ShieldAlert className="h-4 w-4 text-[var(--color-risk-high)]" />
Rule violations ({violations.length})
</CardTitle>
+ {violations.length > 0 && (
+ <AiPromptButton
+ label="Fix violations with AI"
+ onClick={() => setPromptOpen(true)}
+ />
+ )}
</CardHeader>
<CardContent className="pt-0 space-y-3">
{isLoading ? (
@@ -187,6 +195,28 @@ export default function ConformancePage() {
</CardContent>
</Card>
</div>
+
+ <AiPromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ getPrompt={(flavor) =>
+ buildConformanceAiPrompt({
+ violations: violations.map((v) => ({
+ source: v.source,
+ target: v.target,
+ source_name: v.source_name,
+ target_name: v.target_name,
+ edge_kind: v.edge_kind,
+ rule_source: v.rule_source,
+ rule_target: v.rule_target,
+ rule_description: v.rule_description,
+ })),
+ flavor,
+ })
+ }
+ title="AI conformance fix"
+ description="A ready-to-paste prompt that has your AI agent resolve these architecture rule violations by removing the disallowed dependencies."
+ />
</div>
);
}
diff --git a/packages/web/src/components/commits/commits-explorer.tsx b/packages/web/src/components/commits/commits-explorer.tsx
index 7656833ec..94efd987a 100644
--- a/packages/web/src/components/commits/commits-explorer.tsx
+++ b/packages/web/src/components/commits/commits-explorer.tsx
@@ -18,6 +18,7 @@ import {
type CommitSort,
} from "@repowise-dev/ui/commits/commit-table";
import { CommitDetailCard } from "@repowise-dev/ui/commits/commit-detail-card";
+import { AiPromptButton, AiPromptModal, buildCommitAiPrompt } from "@repowise-dev/ui/health";
import { CredibilityStrip } from "@repowise-dev/ui/commits/credibility-strip";
import { AgentTrendStrip } from "@repowise-dev/ui/commits/agent-trend-strip";
import { RiskDistributionChart } from "@repowise-dev/ui/git/risk-distribution-chart";
@@ -33,6 +34,7 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
// ?commit= deep link — entity links from Overview/file pages land here with
// the detail sheet already open, and the sheet state survives refresh.
const [selectedSha, setSelectedSha] = useQueryState("commit");
+ const [promptOpen, setPromptOpen] = useState(false);
const { data, isLoading, isValidating, error } = useSWR<Paginated<CommitResponse>>(
`commits:${repoId}:${sort}:${authorship}:${limit}`,
@@ -164,11 +166,51 @@ export function CommitsExplorer({ repoId }: { repoId: string }) {
<Skeleton className="h-40 w-full" />
</div>
) : (
- <CommitDetailCard commit={detail} />
+ <>
+ <div className="flex justify-end pt-1 pb-3">
+ <AiPromptButton
+ label="AI review prompt"
+ onClick={() => setPromptOpen(true)}
+ />
+ </div>
+ <CommitDetailCard commit={detail} />
+ </>
)}
</div>
</SheetContent>
</Sheet>
+
+ <AiPromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ getPrompt={
+ detail
+ ? (flavor) =>
+ buildCommitAiPrompt({
+ commit: {
+ sha: detail.sha,
+ subject: detail.subject,
+ review_priority: detail.review_priority,
+ risk_percentile: detail.risk_percentile,
+ change_risk_score: detail.change_risk_score,
+ is_fix: detail.is_fix,
+ files_changed: detail.files_changed,
+ lines_added: detail.lines_added,
+ lines_deleted: detail.lines_deleted,
+ entropy: detail.entropy,
+ top_drivers: detail.drivers
+ .filter((d) => d.contribution > 0)
+ .map((d) => d.label),
+ author_name: detail.author_name,
+ },
+ flavor,
+ })
+ : null
+ }
+ filePath={detail ? detail.short_sha : null}
+ title="AI commit review"
+ description="A ready-to-paste prompt that has your AI agent review this commit's change-risk, flag what to scrutinize, and suggest reviewers."
+ />
</div>
);
}
diff --git a/packages/web/src/components/coupling/coupling-view.tsx b/packages/web/src/components/coupling/coupling-view.tsx
index bb0cb7be1..e082eefde 100644
--- a/packages/web/src/components/coupling/coupling-view.tsx
+++ b/packages/web/src/components/coupling/coupling-view.tsx
@@ -3,7 +3,8 @@
import { useState } from "react";
import { CouplingGraph, CouplingTable } from "@repowise-dev/ui/coupling";
import { GraphCanvasShell } from "@repowise-dev/ui/graph/graph-canvas-shell";
-import type { CouplingGraphResponse } from "@repowise-dev/types/coupling";
+import { AiPromptModal, buildCouplingAiPrompt } from "@repowise-dev/ui/health";
+import type { CouplingEdge, CouplingGraphResponse } from "@repowise-dev/types/coupling";
interface CouplingViewProps {
data: CouplingGraphResponse;
@@ -20,6 +21,7 @@ interface CouplingViewProps {
*/
export function CouplingView({ data }: CouplingViewProps) {
const [focusedPath, setFocusedPath] = useState<string | null>(null);
+ const [promptEdge, setPromptEdge] = useState<CouplingEdge | null>(null);
return (
<div className="space-y-5">
@@ -40,8 +42,22 @@ export function CouplingView({ data }: CouplingViewProps) {
edges={data.edges}
focusedPath={focusedPath}
onFocusChange={setFocusedPath}
+ onGeneratePrompt={setPromptEdge}
/>
</div>
+
+ <AiPromptModal
+ open={promptEdge !== null}
+ onOpenChange={(o) => !o && setPromptEdge(null)}
+ getPrompt={
+ promptEdge
+ ? (flavor) => buildCouplingAiPrompt({ edge: promptEdge, flavor })
+ : null
+ }
+ filePath={promptEdge ? `${promptEdge.source} ↔ ${promptEdge.target}` : null}
+ title="AI decouple prompt"
+ description="A ready-to-paste prompt that has your AI agent diagnose why these two files change together and propose how to decouple them."
+ />
</div>
);
}
diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsx
index e9504b7b9..727b1702c 100644
--- a/packages/web/src/components/decisions/decision-detail.tsx
+++ b/packages/web/src/components/decisions/decision-detail.tsx
@@ -14,6 +14,7 @@ import { ModuleLinkEditor } from "@repowise-dev/ui/decisions/module-link-editor"
import { VerificationBadge } from "@repowise-dev/ui/decisions/verification-badge";
import { DecisionEvidenceDrawer } from "@repowise-dev/ui/decisions/decision-evidence-drawer";
import { DecisionLineage } from "@repowise-dev/ui/decisions/decision-lineage";
+import { AiPromptButton, AiPromptModal, buildDecisionAiPrompt } from "@repowise-dev/ui/health";
import {
getDecisionEvidence,
getDecisionLineage,
@@ -58,6 +59,7 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
const [linkedFiles, setLinkedFiles] = React.useState(decision.affected_files);
const [linkageSaving, setLinkageSaving] = React.useState(false);
const [evidenceOpen, setEvidenceOpen] = React.useState(false);
+ const [promptOpen, setPromptOpen] = React.useState(false);
// Lineage: cheap, load eagerly so the Evolution timeline renders when present.
const { data: lineage } = useSWR(
@@ -225,10 +227,15 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
{decision.verification && (
<VerificationBadge verification={decision.verification} />
)}
+ <AiPromptButton
+ label={status === "proposed" ? "Verify & confirm with AI" : "Verify with AI"}
+ onClick={() => setPromptOpen(true)}
+ className="ml-auto"
+ />
<button
type="button"
onClick={() => setEvidenceOpen(true)}
- className="ml-auto inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)]"
>
<FileSearch className="h-3.5 w-3.5" />
Evidence
@@ -401,6 +408,32 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
error={evidenceError}
decisionTitle={decision.title}
/>
+
+ <AiPromptModal
+ open={promptOpen}
+ onOpenChange={setPromptOpen}
+ getPrompt={(flavor) =>
+ buildDecisionAiPrompt({
+ decision: {
+ title: decision.title,
+ status,
+ context: decision.context,
+ decision: decision.decision,
+ rationale: decision.rationale,
+ alternatives: decision.alternatives,
+ consequences: decision.consequences,
+ affected_modules: linkedModules,
+ affected_files: linkedFiles,
+ staleness_score: decision.staleness_score,
+ confidence: decision.confidence,
+ },
+ flavor,
+ })
+ }
+ filePath={stripMarkdown(decision.title)}
+ title="AI decision verification"
+ description="A ready-to-paste prompt that has your AI agent check this decision against the current code and recommend whether to keep, update, or retire it."
+ />
</div>
);
}
diff --git a/packages/web/src/components/risk/dead-code-tab.tsx b/packages/web/src/components/risk/dead-code-tab.tsx
index 178eb3d1d..991a08950 100644
--- a/packages/web/src/components/risk/dead-code-tab.tsx
+++ b/packages/web/src/components/risk/dead-code-tab.tsx
@@ -13,6 +13,7 @@ import { SafeToDeletePile } from "@repowise-dev/ui/dead-code/safe-to-delete-pile
import { OwnerLeaderboard } from "@repowise-dev/ui/dead-code/owner-leaderboard";
import { FindingsBreakdownGrid } from "@repowise-dev/ui/dead-code/findings-breakdown-grid";
import { FindingsTable } from "@repowise-dev/ui/dead-code/findings-table";
+import { AiPromptModal, buildDeadCodeAiPrompt } from "@repowise-dev/ui/health";
import { getDeadCodeSummary, listDeadCode, analyzeDeadCode, patchDeadCodeFinding } from "@/lib/api/dead-code";
import type { DeadCodeFindingResponse, DeadCodeSummaryResponse } from "@/lib/api/types";
import type { DeadCodeStatus } from "@repowise-dev/types/dead-code";
@@ -20,6 +21,7 @@ import type { DeadCodeStatus } from "@repowise-dev/types/dead-code";
export function DeadCodeTab({ repoId }: { repoId: string }) {
const router = useRouter();
const [analyzing, setAnalyzing] = useState(false);
+ const [promptIds, setPromptIds] = useState<string[] | null>(null);
const { data: summary, isLoading: loadingSummary, error: summaryError, mutate: mutateSummary } =
useSWR<DeadCodeSummaryResponse>(
@@ -39,40 +41,14 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {
const findingsList = findings ?? [];
const safeFindings = findingsList.filter((f) => f.safe_to_delete);
- // "Propose cleanup" builds an agent-ready brief from the safe pile and
- // copies it — the cheapest path from finding to action until a server-side
- // cleanup-PR flow exists.
- const handlePropose = async (findingIds: string[]) => {
- const selected = safeFindings.filter((f) => findingIds.includes(f.id));
- const byFile = new Map<string, typeof selected>();
- for (const f of selected) {
- byFile.set(f.file_path, [...(byFile.get(f.file_path) ?? []), f]);
- }
- const lines = [...byFile.entries()].map(([path, fs]) => {
- const symbols = fs
- .map((f) => f.symbol_name)
- .filter(Boolean)
- .join(", ");
- return `- ${path}${symbols ? ` (${symbols})` : ""} — ${fs
- .map((f) => f.reason)
- .filter(Boolean)
- .slice(0, 1)
- .join("")}`;
- });
- const brief = [
- "Remove the following dead code. Each entry was flagged high-confidence",
- "safe-to-delete by repowise's dead-code analysis. Verify with a project",
- "search before deleting, then run the test suite.",
- "",
- ...lines,
- ].join("\n");
- try {
- await navigator.clipboard.writeText(brief);
- toast.success(`Cleanup brief for ${byFile.size} files copied — paste it to your agent`);
- } catch {
- toast.error("Couldn't copy to clipboard");
- }
- };
+ // "Propose cleanup" opens the shared AI-prompt modal seeded with the safe
+ // pile — same agent-flavor picker (incl. repowise MCP) and copy affordance as
+ // every other AI action in the dashboard.
+ const handlePropose = (findingIds: string[]) => setPromptIds(findingIds);
+
+ const promptFindings = promptIds
+ ? safeFindings.filter((f) => promptIds.includes(f.id))
+ : [];
const handleAnalyze = async () => {
setAnalyzing(true);
@@ -204,6 +180,30 @@ export function DeadCodeTab({ repoId }: { repoId: string }) {
isLoading={loadingFindings}
/>
</CollapsibleSection>
+
+ <AiPromptModal
+ open={promptIds !== null}
+ onOpenChange={(o) => !o && setPromptIds(null)}
+ getPrompt={
+ promptFindings.length > 0
+ ? (flavor) =>
+ buildDeadCodeAiPrompt({
+ findings: promptFindings.map((f) => ({
+ file_path: f.file_path,
+ symbol_name: f.symbol_name,
+ kind: f.kind,
+ reason: f.reason,
+ lines: f.lines,
+ confidence: f.confidence,
+ risk_factors: f.risk_factors,
+ })),
+ flavor,
+ })
+ : null
+ }
+ title="AI cleanup prompt"
+ description="A ready-to-paste prompt that has your AI agent verify and remove this dead-code pile safely, in reviewable commits."
+ />
</div>
);
}
diff --git a/packages/web/src/components/risk/hotspots-tab.tsx b/packages/web/src/components/risk/hotspots-tab.tsx
index 794256bff..7f4ab1b2b 100644
--- a/packages/web/src/components/risk/hotspots-tab.tsx
+++ b/packages/web/src/components/risk/hotspots-tab.tsx
@@ -17,6 +17,8 @@ import {
CodeHealthMap,
type CodeHealthOverlay,
} from "@repowise-dev/ui/health/code-health-map";
+import { AiPromptModal, buildHotspotAiPrompt } from "@repowise-dev/ui/health";
+import type { Hotspot } from "@repowise-dev/types/git";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { Skeleton } from "@repowise-dev/ui/ui/skeleton";
import { getHotspotsPage } from "@/lib/api/git";
@@ -30,6 +32,7 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
const { showFile, dialog } = useFileCardHost(repoId);
const [pageLimit, setPageLimit] = useState(PAGE_SIZE);
const [drawerSymbol, setDrawerSymbol] = useState<SymbolResponse | null>(null);
+ const [promptHotspot, setPromptHotspot] = useState<Hotspot | null>(null);
// The galaxy map opens on the churn lens here — this is the hotspots surface,
// so "what changes most" is the first read; the switcher still offers
// health/coverage for cross-reference.
@@ -217,6 +220,7 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
hotspots={list}
repoId={repoId}
onSelect={(h) => showFile(hotspotToFileCard(h))}
+ onGeneratePrompt={setPromptHotspot}
total={total}
hasMore={hasMore}
loadingMore={validatingHotspots && !loadingHotspots}
@@ -235,6 +239,35 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
repoId={repoId}
onClose={() => setDrawerSymbol(null)}
/>
+ <AiPromptModal
+ open={promptHotspot !== null}
+ onOpenChange={(o) => !o && setPromptHotspot(null)}
+ getPrompt={
+ promptHotspot
+ ? (flavor) =>
+ buildHotspotAiPrompt({
+ hotspot: {
+ file_path: promptHotspot.file_path,
+ churn_percentile: promptHotspot.churn_percentile,
+ commit_count_90d: promptHotspot.commit_count_90d,
+ commit_count_30d: promptHotspot.commit_count_30d,
+ bus_factor: promptHotspot.bus_factor,
+ contributor_count: promptHotspot.contributor_count,
+ primary_owner: promptHotspot.primary_owner,
+ lines_added_90d: promptHotspot.lines_added_90d,
+ lines_deleted_90d: promptHotspot.lines_deleted_90d,
+ temporal_hotspot_score: promptHotspot.temporal_hotspot_score,
+ change_entropy_pct: promptHotspot.change_entropy_pct,
+ prior_defect_count: promptHotspot.prior_defect_count,
+ },
+ flavor,
+ })
+ : null
+ }
+ filePath={promptHotspot?.file_path}
+ title="AI stabilization prompt"
+ description="A ready-to-paste prompt that has your AI agent diagnose why this file churns and propose changes that make it cheaper to maintain."
+ />
</div>
);
}
diff --git a/packages/web/src/components/risk/security-tab.tsx b/packages/web/src/components/risk/security-tab.tsx
index 34c69284c..18c61b58b 100644
--- a/packages/web/src/components/risk/security-tab.tsx
+++ b/packages/web/src/components/risk/security-tab.tsx
@@ -6,6 +6,7 @@ import { RotateCw } from "lucide-react";
import { toast } from "sonner";
import { SecurityFindingsTable } from "@repowise-dev/ui/security/findings-table";
import { SeverityDirectoryMatrix } from "@repowise-dev/ui/security/severity-directory-matrix";
+import { AiPromptModal, buildSecurityAiPrompt } from "@repowise-dev/ui/health";
import { Button } from "@repowise-dev/ui/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@repowise-dev/ui/ui/card";
import { CollapsibleSection } from "@repowise-dev/ui/shared/collapsible-section";
@@ -22,6 +23,7 @@ export function SecurityTab({ repoId }: { repoId: string }) {
{ revalidateOnFocus: false },
);
const [rescanning, setRescanning] = useState(false);
+ const [promptFinding, setPromptFinding] = useState<SecurityFinding | null>(null);
const handleRescan = async () => {
setRescanning(true);
@@ -85,11 +87,28 @@ export function SecurityTab({ repoId }: { repoId: string }) {
hint={`${(findings ?? []).length} findings`}
defaultOpen={false}
>
- <SecurityFindingsTable findings={findings ?? []} onSelect={handleSelect} />
+ <SecurityFindingsTable
+ findings={findings ?? []}
+ onSelect={handleSelect}
+ onGeneratePrompt={setPromptFinding}
+ />
</CollapsibleSection>
</>
)}
+ <AiPromptModal
+ open={promptFinding !== null}
+ onOpenChange={(o) => !o && setPromptFinding(null)}
+ getPrompt={
+ promptFinding
+ ? (flavor) => buildSecurityAiPrompt({ finding: promptFinding, flavor })
+ : null
+ }
+ filePath={promptFinding?.file_path}
+ title="AI fix prompt"
+ description="A ready-to-paste prompt that walks your AI agent through confirming and remediating this security finding."
+ />
+
{dialog}
</div>
);