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: hotspot → top symbols drill-down, writable decision linkage (#191)

Raghav Chamadiyadb07930d7311
diff --git a/packages/core/src/repowise/core/persistence/crud.py b/packages/core/src/repowise/core/persistence/crud.py
index fbba7fe34..22380ac40 100644
--- a/packages/core/src/repowise/core/persistence/crud.py
+++ b/packages/core/src/repowise/core/persistence/crud.py
@@ -1054,6 +1054,30 @@ async def list_decisions(
return list(result.scalars().all())
+async def update_decision_metadata(
+ session: AsyncSession,
+ decision_id: str,
+ *,
+ affected_modules: list[str] | None = None,
+ affected_files: list[str] | None = None,
+) -> DecisionRecord | None:
+ """Patch the module/file linkage on a decision record.
+
+ Each argument left as ``None`` is preserved. Pass an empty list to clear.
+ Returns the updated record, or ``None`` if the id was not found.
+ """
+ rec = await session.get(DecisionRecord, decision_id)
+ if rec is None:
+ return None
+ if affected_modules is not None:
+ rec.affected_modules_json = json.dumps(affected_modules)
+ if affected_files is not None:
+ rec.affected_files_json = json.dumps(affected_files)
+ rec.updated_at = _now_utc()
+ await session.flush()
+ return rec
+
+
async def update_decision_status(
session: AsyncSession,
decision_id: str,
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 2ad0ba5e9..97a09523a 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -124,18 +124,43 @@ async def patch_decision(
body: DecisionStatusUpdate,
session: AsyncSession = Depends(get_db_session), # noqa: B008
) -> DecisionRecordResponse:
- """Update the status of a decision record (confirm, deprecate, supersede)."""
- try:
- rec = await crud.update_decision_status(
+ """Update a decision record.
+
+ Accepts status transitions (confirm / deprecate / supersede) and / or
+ governance edits (``affected_modules``, ``affected_files``). Any field
+ left as ``None`` in the body is preserved.
+ """
+ rec = await crud.get_decision(session, decision_id)
+ if rec is None or rec.repository_id != repo_id:
+ raise HTTPException(status_code=404, detail="Decision not found")
+
+ if body.status is not None:
+ try:
+ rec = await crud.update_decision_status(
+ session,
+ decision_id,
+ body.status,
+ superseded_by=body.superseded_by,
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if rec is None:
+ raise HTTPException(status_code=404, detail="Decision not found")
+ elif body.superseded_by is not None:
+ raise HTTPException(
+ status_code=400,
+ detail="superseded_by requires status='superseded'",
+ )
+
+ if body.affected_modules is not None or body.affected_files is not None:
+ rec = await crud.update_decision_metadata(
session,
decision_id,
- body.status,
- superseded_by=body.superseded_by,
+ affected_modules=body.affected_modules,
+ affected_files=body.affected_files,
)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail=str(exc)) from exc
- if rec is None:
- raise HTTPException(status_code=404, detail="Decision not found")
- if rec.repository_id != repo_id:
- raise HTTPException(status_code=404, detail="Decision not found")
+ if rec is None:
+ raise HTTPException(status_code=404, detail="Decision not found")
+
+ assert rec is not None
return DecisionRecordResponse.from_orm(rec)
diff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.py
index 974ac4b87..30c12bd06 100644
--- a/packages/server/src/repowise/server/routers/symbols.py
+++ b/packages/server/src/repowise/server/routers/symbols.py
@@ -96,6 +96,9 @@ async def search_symbols(
kind: str | None = Query(None, description="Filter by symbol kind"),
language: str | None = Query(None, description="Filter by language"),
visibility: str | None = Query(None, description="Filter by visibility"),
+ file_path: str | None = Query(
+ None, description="Filter by exact source file path (for hotspot drill-down)"
+ ),
in_hot_files: bool = Query(False, description="Only symbols whose file is a hotspot"),
in_entry_points: bool = Query(False, description="Only symbols in entry-point files"),
sort: SortKey = Query("importance", description="Sort key"),
@@ -120,6 +123,8 @@ async def search_symbols(
base = base.where(WikiSymbol.language == language)
if visibility:
base = base.where(WikiSymbol.visibility == visibility)
+ if file_path:
+ base = base.where(WikiSymbol.file_path == file_path)
# Optional file-level filters require resolving file paths up front.
if in_hot_files or in_entry_points:
diff --git a/packages/server/src/repowise/server/schemas.py b/packages/server/src/repowise/server/schemas.py
index 619513b2e..5cd4a512e 100644
--- a/packages/server/src/repowise/server/schemas.py
+++ b/packages/server/src/repowise/server/schemas.py
@@ -941,8 +941,17 @@ class DecisionCreate(BaseModel):
class DecisionStatusUpdate(BaseModel):
- status: str
+ """PATCH body for /decisions/{id}.
+
+ All fields are optional — clients can update status alone (the historical
+ contract), the linked modules / files alone (governance editor), or both
+ in a single request. Fields left at ``None`` are preserved.
+ """
+
+ status: str | None = None
superseded_by: str | None = None
+ affected_modules: list[str] | None = None
+ affected_files: list[str] | None = None
# ---------------------------------------------------------------------------
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index a7dd16a1e..8caf0261d 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -56,9 +56,15 @@ export interface DecisionCreateInput {
tags?: string[];
}
+/**
+ * PATCH body for /api/repos/{id}/decisions/{decision_id}. All fields are
+ * optional — clients can update just the status, just the linkage, or both.
+ */
export interface DecisionStatusUpdate {
- status: DecisionStatus;
+ status?: DecisionStatus;
superseded_by?: string;
+ affected_modules?: string[];
+ affected_files?: string[];
}
export interface DecisionHealth {
diff --git a/packages/ui/src/decisions/index.ts b/packages/ui/src/decisions/index.ts
index 7e2a231b7..f787fc0b0 100644
--- a/packages/ui/src/decisions/index.ts
+++ b/packages/ui/src/decisions/index.ts
@@ -1,2 +1,3 @@
export * from "./decision-health-widget.js";
export * from "./decisions-table.js";
+export * from "./module-link-editor.js";
diff --git a/packages/ui/src/decisions/module-link-editor.tsx b/packages/ui/src/decisions/module-link-editor.tsx
new file mode 100644
index 000000000..2c1a30ab4
--- /dev/null
+++ b/packages/ui/src/decisions/module-link-editor.tsx
@@ -0,0 +1,270 @@
+"use client";
+
+import * as React from "react";
+import { Folder, FileText, Plus, X } from "lucide-react";
+import { Button } from "../ui/button";
+import { Input } from "../ui/input";
+import { cn } from "../lib/cn";
+
+/**
+ * Inline chip editor for the `affected_modules` + `affected_files` linkage
+ * on a decision. Presentational only — the parent owns persistence.
+ *
+ * The host wires `suggestions` (typically module_paths from
+ * /api/repos/{id}/modules/health) for inline autocomplete; users can also
+ * type any path freehand.
+ */
+interface ModuleLinkEditorProps {
+ modules: string[];
+ files: string[];
+ suggestions?: string[] | undefined;
+ /** True while the parent is persisting a save. */
+ saving?: boolean | undefined;
+ /** Disables interactivity (e.g. while loading the initial record). */
+ disabled?: boolean | undefined;
+ onSave: (next: { modules: string[]; files: string[] }) => Promise<void> | void;
+ className?: string | undefined;
+}
+
+export function ModuleLinkEditor({
+ modules,
+ files,
+ suggestions,
+ saving = false,
+ disabled = false,
+ onSave,
+ className,
+}: ModuleLinkEditorProps) {
+ const [localModules, setLocalModules] = React.useState(modules);
+ const [localFiles, setLocalFiles] = React.useState(files);
+ const [moduleDraft, setModuleDraft] = React.useState("");
+ const [fileDraft, setFileDraft] = React.useState("");
+
+ // Keep local state in sync if the parent reloads the decision.
+ React.useEffect(() => setLocalModules(modules), [modules]);
+ React.useEffect(() => setLocalFiles(files), [files]);
+
+ const dirty =
+ !arraysEqual(localModules, modules) || !arraysEqual(localFiles, files);
+
+ const filteredSuggestions = React.useMemo(() => {
+ if (!suggestions || moduleDraft.trim().length === 0) return [];
+ const q = moduleDraft.trim().toLowerCase();
+ return suggestions
+ .filter(
+ (s) =>
+ s.toLowerCase().includes(q) && !localModules.includes(s),
+ )
+ .slice(0, 6);
+ }, [suggestions, moduleDraft, localModules]);
+
+ const addModule = (value: string) => {
+ const v = value.trim();
+ if (!v) return;
+ if (localModules.includes(v)) return;
+ setLocalModules([...localModules, v]);
+ setModuleDraft("");
+ };
+
+ const addFile = (value: string) => {
+ const v = value.trim();
+ if (!v) return;
+ if (localFiles.includes(v)) return;
+ setLocalFiles([...localFiles, v]);
+ setFileDraft("");
+ };
+
+ const handleSave = async () => {
+ await onSave({ modules: localModules, files: localFiles });
+ };
+
+ const handleReset = () => {
+ setLocalModules(modules);
+ setLocalFiles(files);
+ setModuleDraft("");
+ setFileDraft("");
+ };
+
+ return (
+ <div
+ className={cn(
+ "rounded-lg border border-[var(--color-border-default)] p-4 space-y-4",
+ className,
+ )}
+ >
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium text-[var(--color-text-secondary)]">
+ Governance scope
+ </h3>
+ <p className="text-[11px] text-[var(--color-text-tertiary)]">
+ Link this decision to the modules and files it governs.
+ </p>
+ </div>
+
+ {/* Modules */}
+ <Field
+ icon={<Folder className="h-3.5 w-3.5" />}
+ label="Modules"
+ chips={localModules}
+ onRemove={(m) => setLocalModules(localModules.filter((x) => x !== m))}
+ disabled={disabled || saving}
+ >
+ <div className="relative">
+ <div className="flex gap-2">
+ <Input
+ value={moduleDraft}
+ onChange={(e) => setModuleDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ addModule(moduleDraft);
+ }
+ }}
+ placeholder="packages/server"
+ disabled={disabled || saving}
+ className="font-mono text-xs"
+ />
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => addModule(moduleDraft)}
+ disabled={disabled || saving || moduleDraft.trim().length === 0}
+ >
+ <Plus className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ {filteredSuggestions.length > 0 && (
+ <div className="absolute z-10 mt-1 w-full rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] shadow-lg">
+ {filteredSuggestions.map((s) => (
+ <button
+ key={s}
+ type="button"
+ onClick={() => addModule(s)}
+ className="block w-full px-3 py-1.5 text-left font-mono text-xs text-[var(--color-text-primary)] hover:bg-[var(--color-bg-hover)]"
+ >
+ {s}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ </Field>
+
+ {/* Files */}
+ <Field
+ icon={<FileText className="h-3.5 w-3.5" />}
+ label="Files"
+ chips={localFiles}
+ onRemove={(f) => setLocalFiles(localFiles.filter((x) => x !== f))}
+ disabled={disabled || saving}
+ >
+ <div className="flex gap-2">
+ <Input
+ value={fileDraft}
+ onChange={(e) => setFileDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ addFile(fileDraft);
+ }
+ }}
+ placeholder="src/server/app.py"
+ disabled={disabled || saving}
+ className="font-mono text-xs"
+ />
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={() => addFile(fileDraft)}
+ disabled={disabled || saving || fileDraft.trim().length === 0}
+ >
+ <Plus className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </Field>
+
+ {/* Footer actions */}
+ <div className="flex items-center justify-between gap-2 border-t border-[var(--color-border-default)] pt-3">
+ <p className="text-[11px] text-[var(--color-text-tertiary)]">
+ {dirty ? "Unsaved changes" : "All linkage saved."}
+ </p>
+ <div className="flex gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ onClick={handleReset}
+ disabled={!dirty || saving}
+ >
+ Reset
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ onClick={handleSave}
+ disabled={!dirty || saving}
+ >
+ {saving ? "Saving…" : "Save linkage"}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+interface FieldProps {
+ icon: React.ReactNode;
+ label: string;
+ chips: string[];
+ onRemove: (value: string) => void;
+ disabled?: boolean | undefined;
+ children: React.ReactNode;
+}
+
+function Field({ icon, label, chips, onRemove, disabled, children }: FieldProps) {
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-secondary)]">
+ {icon}
+ <span>{label}</span>
+ <span className="text-[var(--color-text-tertiary)] font-normal">
+ ({chips.length})
+ </span>
+ </div>
+ {chips.length > 0 && (
+ <div className="flex flex-wrap gap-1.5">
+ {chips.map((c) => (
+ <span
+ key={c}
+ className="inline-flex items-center gap-1 rounded-full border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-0.5 font-mono text-[11px] text-[var(--color-text-primary)]"
+ >
+ <span className="max-w-[260px] truncate" title={c}>
+ {c}
+ </span>
+ <button
+ type="button"
+ onClick={() => onRemove(c)}
+ disabled={disabled}
+ className="rounded-full p-0.5 hover:bg-[var(--color-bg-hover)] disabled:cursor-not-allowed disabled:opacity-50"
+ aria-label={`Remove ${c}`}
+ >
+ <X className="h-2.5 w-2.5" />
+ </button>
+ </span>
+ ))}
+ </div>
+ )}
+ {children}
+ </div>
+ );
+}
+
+function arraysEqual(a: string[], b: string[]): boolean {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) {
+ if (a[i] !== b[i]) return false;
+ }
+ return true;
+}
diff --git a/packages/ui/src/git/hotspot-table.tsx b/packages/ui/src/git/hotspot-table.tsx
index 92dcc87e3..9673ff649 100644
--- a/packages/ui/src/git/hotspot-table.tsx
+++ b/packages/ui/src/git/hotspot-table.tsx
@@ -1,7 +1,8 @@
"use client";
+import * as React from "react";
import { useState, useMemo } from "react";
-import { TrendingUp, TrendingDown, Search, Flame, ArrowUpDown, ArrowUp, ArrowDown, GitBranch, BookOpen, Radius } from "lucide-react";
+import { TrendingUp, TrendingDown, Search, Flame, ArrowUpDown, ArrowUp, ArrowDown, GitBranch, BookOpen, Radius, ChevronRight, ChevronDown } from "lucide-react";
import { Badge } from "../ui/badge";
import { Input } from "../ui/input";
import { EmptyState } from "../shared/empty-state";
@@ -33,6 +34,12 @@ interface HotspotTableProps {
hasMore?: boolean;
loadingMore?: boolean;
onLoadMore?: () => void;
+ /**
+ * When provided, each row shows a chevron toggle that expands an inline
+ * panel below it — used for hotspot → "top symbols in this file" drill-down.
+ * The host owns data-fetching and renders the panel body.
+ */
+ renderExpandedRow?: (hotspot: Hotspot) => React.ReactNode;
}
type Filter = "all" | "hot" | "risk" | "accelerating";
@@ -60,7 +67,18 @@ export function HotspotTable({
hasMore,
loadingMore,
onLoadMore,
+ renderExpandedRow,
}: HotspotTableProps) {
+ const expandable = !!renderExpandedRow;
+ const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
+ const toggleExpand = (filePath: string) => {
+ setExpanded((prev) => {
+ const next = new Set(prev);
+ if (next.has(filePath)) next.delete(filePath);
+ else next.add(filePath);
+ return next;
+ });
+ };
const prefix = linkPrefix ?? (repoId ? `/repos/${repoId}` : undefined);
const [search, setSearch] = useState("");
const [filter, setFilter] = useState<Filter>("all");
@@ -169,6 +187,7 @@ export function HotspotTable({
<table className="w-full min-w-[760px] text-sm">
<thead className="sticky top-0 z-10 bg-[var(--color-bg-elevated)]">
<tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-elevated)]">
+ {expandable && <th className="w-6 px-1" aria-hidden="true" />}
<th className="px-3 py-2.5 text-left text-xs font-medium text-[var(--color-text-tertiary)] uppercase tracking-wider w-8">
#
</th>
@@ -216,15 +235,39 @@ export function HotspotTable({
{filtered.map((h, i) => {
const accelerating = h.commit_count_30d * 3 > h.commit_count_90d;
const trendScore = h.temporal_hotspot_score;
+ const isExpanded = expanded.has(h.file_path);
return (
+ <React.Fragment key={h.file_path}>
<tr
- key={h.file_path}
onClick={onSelect ? () => onSelect(h) : undefined}
className={cn(
- "border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors last:border-0",
+ "border-b border-[var(--color-border-default)] hover:bg-[var(--color-bg-elevated)] transition-colors",
+ !isExpanded && "last:border-0",
onSelect && "cursor-pointer",
)}
>
+ {expandable && (
+ <td
+ className="px-1 py-2.5 align-middle"
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleExpand(h.file_path);
+ }}
+ >
+ <button
+ type="button"
+ aria-label={isExpanded ? "Collapse symbols" : "Expand symbols"}
+ aria-expanded={isExpanded}
+ className="flex h-5 w-5 items-center justify-center rounded text-[var(--color-text-tertiary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)]"
+ >
+ {isExpanded ? (
+ <ChevronDown className="h-3.5 w-3.5" />
+ ) : (
+ <ChevronRight className="h-3.5 w-3.5" />
+ )}
+ </button>
+ </td>
+ )}
<td className="px-3 py-2.5 text-[var(--color-text-tertiary)] tabular-nums text-xs">
{i + 1}
</td>
@@ -302,6 +345,15 @@ export function HotspotTable({
</div>
</td>
</tr>
+ {expandable && isExpanded && (
+ <tr className="border-b border-[var(--color-border-default)] bg-[var(--color-bg-subtle)] last:border-0">
+ <td className="px-1" />
+ <td colSpan={9} className="px-3 py-3">
+ {renderExpandedRow!(h)}
+ </td>
+ </tr>
+ )}
+ </React.Fragment>
);
})}
</tbody>
diff --git a/packages/ui/src/symbols/index.ts b/packages/ui/src/symbols/index.ts
index 77ea3673c..9385c008e 100644
--- a/packages/ui/src/symbols/index.ts
+++ b/packages/ui/src/symbols/index.ts
@@ -3,3 +3,4 @@ export * from "./symbol-drawer.js";
export * from "./symbol-graph-panel.js";
export * from "./symbol-git-panel.js";
export * from "./hot-symbols-board.js";
+export * from "./top-symbols-row.js";
diff --git a/packages/ui/src/symbols/top-symbols-row.tsx b/packages/ui/src/symbols/top-symbols-row.tsx
new file mode 100644
index 000000000..82d47e932
--- /dev/null
+++ b/packages/ui/src/symbols/top-symbols-row.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import * as React from "react";
+import { ChevronRight, AlertCircle } from "lucide-react";
+import { Skeleton } from "../ui/skeleton";
+import { Badge } from "../ui/badge";
+import { cn } from "../lib/cn";
+import type { CodeSymbol } from "@repowise-dev/types/symbols";
+
+interface TopSymbolsRowProps {
+ symbols: CodeSymbol[] | undefined;
+ loading?: boolean | undefined;
+ error?: string | undefined;
+ /** Optional click handler — typically opens the SymbolDrawer in the host. */
+ onSelect?: ((symbol: CodeSymbol) => void) | undefined;
+ /** Link to the full /symbols page filtered to this file, when host provides one. */
+ seeAllHref?: string | undefined;
+ className?: string | undefined;
+}
+
+const KIND_LABEL: Record<string, string> = {
+ function: "fn",
+ method: "m",
+ class: "class",
+ interface: "iface",
+ struct: "struct",
+ enum: "enum",
+ trait: "trait",
+ variable: "var",
+ type: "type",
+ module: "mod",
+};
+
+/**
+ * Inline panel shown when a hotspot row is expanded. Renders the
+ * importance-ranked top symbols for the underlying file. Presentational —
+ * the host owns fetching (typically a SWR call against `/api/symbols` with
+ * the `file_path` filter).
+ */
+export function TopSymbolsRow({
+ symbols,
+ loading,
+ error,
+ onSelect,
+ seeAllHref,
+ className,
+}: TopSymbolsRowProps) {
+ if (loading && (!symbols || symbols.length === 0)) {
+ return (
+ <div className={cn("space-y-2", className)}>
+ <div className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Top symbols
+ </div>
+ <div className="grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <Skeleton key={i} className="h-7 w-full" />
+ ))}
+ </div>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-2 text-xs text-[var(--color-text-secondary)]",
+ className,
+ )}
+ >
+ <AlertCircle className="h-3.5 w-3.5 text-red-400" />
+ Couldn&apos;t load symbols: {error}
+ </div>
+ );
+ }
+
+ if (!symbols || symbols.length === 0) {
+ return (
+ <div className={cn("text-xs text-[var(--color-text-tertiary)]", className)}>
+ No indexed symbols in this file yet.
+ </div>
+ );
+ }
+
+ return (
+ <div className={cn("space-y-2", className)}>
+ <div className="flex items-center justify-between">
+ <div className="text-[11px] font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Top symbols ({symbols.length})
+ </div>
+ {seeAllHref && (
+ <a
+ href={seeAllHref}
+ className="inline-flex items-center gap-0.5 text-[11px] text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ >
+ See all
+ <ChevronRight className="h-3 w-3" />
+ </a>
+ )}
+ </div>
+ <div className="grid gap-1.5 sm:grid-cols-2 lg:grid-cols-3">
+ {symbols.map((s) => {
+ const score = typeof s.importance_score === "number" ? s.importance_score : null;
+ const isPublic = s.visibility === "public";
+ return (
+ <button
+ key={s.id}
+ type="button"
+ onClick={onSelect ? () => onSelect(s) : undefined}
+ className={cn(
+ "group flex items-center gap-2 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-2 py-1.5 text-left transition-colors",
+ onSelect && "hover:border-[var(--color-accent-primary)] hover:bg-[var(--color-bg-hover)] cursor-pointer",
+ )}
+ title={s.qualified_name || s.name}
+ aria-label={`Open symbol ${s.name}`}
+ >
+ <Badge variant="outline" className="shrink-0 px-1.5 py-0 text-[10px] uppercase">
+ {KIND_LABEL[s.kind] ?? s.kind}
+ </Badge>
+ <span className="flex-1 truncate font-mono text-xs text-[var(--color-text-primary)]">
+ {s.name}
+ </span>
+ {!isPublic && s.visibility && (
+ <span className="shrink-0 text-[10px] text-[var(--color-text-tertiary)] uppercase">
+ {s.visibility}
+ </span>
+ )}
+ {score !== null && (
+ <span
+ className="shrink-0 tabular-nums text-[10px] text-[var(--color-text-tertiary)]"
+ title={`Importance score: ${score.toFixed(3)}`}
+ >
+ {score.toFixed(2)}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/web/src/components/decisions/decision-detail.tsx b/packages/web/src/components/decisions/decision-detail.tsx
index e5dbbe2ac..57fa05826 100644
--- a/packages/web/src/components/decisions/decision-detail.tsx
+++ b/packages/web/src/components/decisions/decision-detail.tsx
@@ -3,12 +3,15 @@
import * as React from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
+import useSWR from "swr";
import { toast } from "sonner";
import Link from "next/link";
import { ChevronLeft } from "lucide-react";
import { Badge } from "@repowise-dev/ui/ui/badge";
import { ConfirmDialog } from "@repowise-dev/ui/ui/confirm-dialog";
+import { ModuleLinkEditor } from "@repowise-dev/ui/decisions/module-link-editor";
import { patchDecision } from "@/lib/api/decisions";
+import { listModuleHealth } from "@/lib/api/modules";
import type { DecisionRecordResponse } from "@/lib/api/types";
const STATUS_VARIANT: Record<string, "default" | "fresh" | "stale" | "outdated" | "outline" | "accent"> = {
@@ -42,6 +45,63 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
const [status, setStatus] = React.useState(decision.status);
const [loading, setLoading] = React.useState(false);
const [pendingStatus, setPendingStatus] = React.useState<string | null>(null);
+ const [linkedModules, setLinkedModules] = React.useState(decision.affected_modules);
+ const [linkedFiles, setLinkedFiles] = React.useState(decision.affected_files);
+ const [linkageSaving, setLinkageSaving] = React.useState(false);
+
+ // Suggestions for the module autocomplete — top-level modules indexed for
+ // this repo. Loaded once; cheap to cache.
+ const { data: moduleHealth } = useSWR(
+ `module-health-suggestions:${repoId}`,
+ () => listModuleHealth(repoId, { sort: "file_count", limit: 500 }),
+ { revalidateOnFocus: false },
+ );
+ const moduleSuggestions = React.useMemo(
+ () => (moduleHealth?.items ?? []).map((m) => m.module_path),
+ [moduleHealth],
+ );
+
+ const saveLinkage = async (next: { modules: string[]; files: string[] }) => {
+ const previousModules = linkedModules;
+ const previousFiles = linkedFiles;
+ setLinkageSaving(true);
+ try {
+ await patchDecision(repoId, decision.id, {
+ affected_modules: next.modules,
+ affected_files: next.files,
+ });
+ setLinkedModules(next.modules);
+ setLinkedFiles(next.files);
+ toast.success("Decision linkage updated", {
+ action: {
+ label: "Undo",
+ onClick: async () => {
+ try {
+ await patchDecision(repoId, decision.id, {
+ affected_modules: previousModules,
+ affected_files: previousFiles,
+ });
+ setLinkedModules(previousModules);
+ setLinkedFiles(previousFiles);
+ } catch (err) {
+ toast.error(
+ err instanceof Error ? `Couldn't undo: ${err.message}` : "Couldn't undo",
+ );
+ }
+ },
+ },
+ duration: 6000,
+ });
+ } catch (err) {
+ toast.error(
+ err instanceof Error
+ ? `Couldn't save linkage: ${err.message}`
+ : "Couldn't save linkage",
+ );
+ } finally {
+ setLinkageSaving(false);
+ }
+ };
const applyStatusChange = async (newStatus: string) => {
const previous = status;
@@ -142,23 +202,15 @@ export function DecisionDetail({ decision, repoId }: DecisionDetailProps) {
)}
</div>
- {/* Metadata */}
+ {/* Governance linkage — writable editor + evidence card */}
<div className="grid gap-4 sm:grid-cols-2">
- {decision.affected_files.length > 0 && (
- <div className="rounded-lg border border-[var(--color-border-default)] p-4">
- <h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">
- Affected Files ({decision.affected_files.length})
- </h3>
- <ul className="space-y-1 text-sm text-[var(--color-text-tertiary)]">
- {decision.affected_files.slice(0, 10).map((f) => (
- <li key={f} className="truncate font-mono text-xs" title={f}>{f}</li>
- ))}
- {decision.affected_files.length > 10 && (
- <li className="text-xs">...and {decision.affected_files.length - 10} more</li>
- )}
- </ul>
- </div>
- )}
+ <ModuleLinkEditor
+ modules={linkedModules}
+ files={linkedFiles}
+ suggestions={moduleSuggestions}
+ saving={linkageSaving}
+ onSave={saveLinkage}
+ />
<div className="rounded-lg border border-[var(--color-border-default)] p-4">
<h3 className="mb-2 text-sm font-medium text-[var(--color-text-secondary)]">Evidence</h3>
diff --git a/packages/web/src/components/risk/hotspots-tab.tsx b/packages/web/src/components/risk/hotspots-tab.tsx
index 380545bba..66cf99634 100644
--- a/packages/web/src/components/risk/hotspots-tab.tsx
+++ b/packages/web/src/components/risk/hotspots-tab.tsx
@@ -3,7 +3,9 @@
import { useState } from "react";
import useSWR from "swr";
import { useFileCardHost } from "@/components/shared/file-card-host";
-import type { HotspotResponse as HotspotRowType, Paginated } from "@/lib/api/types";
+import { HotspotTopSymbolsHost } from "@/components/symbols/hotspot-top-symbols-host";
+import { SymbolDrawerWrapper } from "@/components/symbols/symbol-drawer-wrapper";
+import type { HotspotResponse as HotspotRowType, Paginated, SymbolResponse } from "@/lib/api/types";
import type { FileCardData } from "@repowise-dev/ui/shared/file-card";
import { HotspotTable } from "@repowise-dev/ui/git/hotspot-table";
import { ChurnHistogram } from "@repowise-dev/ui/git/churn-histogram";
@@ -36,6 +38,7 @@ function hotspotToFileCard(h: HotspotRowType): FileCardData {
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 {
data: hotspotsPage,
isLoading: loadingHotspots,
@@ -142,8 +145,20 @@ export function HotspotsTab({ repoId }: { repoId: string }) {
hasMore={hasMore}
loadingMore={validatingHotspots && !loadingHotspots}
onLoadMore={() => setPageLimit((n) => Math.min(n + PAGE_SIZE, 500))}
+ renderExpandedRow={(h) => (
+ <HotspotTopSymbolsHost
+ repoId={repoId}
+ filePath={h.file_path}
+ onSelectSymbol={setDrawerSymbol}
+ />
+ )}
/>
{dialog}
+ <SymbolDrawerWrapper
+ symbol={drawerSymbol}
+ repoId={repoId}
+ onClose={() => setDrawerSymbol(null)}
+ />
</div>
);
}
diff --git a/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx b/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx
new file mode 100644
index 000000000..f85e66986
--- /dev/null
+++ b/packages/web/src/components/symbols/hotspot-top-symbols-host.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import useSWR from "swr";
+import { TopSymbolsRow } from "@repowise-dev/ui/symbols/top-symbols-row";
+import { listSymbolsPage } from "@/lib/api/symbols";
+import type { SymbolResponse } from "@/lib/api/types";
+
+interface Props {
+ repoId: string;
+ filePath: string;
+ /** Opens the universal SymbolDrawer from the host page. */
+ onSelectSymbol: (symbol: SymbolResponse) => void;
+}
+
+/**
+ * SWR host for the hotspot-row → top-symbols inline expand. Pulls the top 10
+ * importance-ranked symbols in the given file, then defers rendering to the
+ * shared TopSymbolsRow.
+ */
+export function HotspotTopSymbolsHost({ repoId, filePath, onSelectSymbol }: Props) {
+ const { data, error, isLoading } = useSWR(
+ `top-symbols-in-file:${repoId}:${filePath}`,
+ () =>
+ listSymbolsPage({
+ repo_id: repoId,
+ file_path: filePath,
+ sort: "importance",
+ limit: 10,
+ }),
+ { revalidateOnFocus: false },
+ );
+
+ const seeAllHref = `/repos/${repoId}/symbols?q=${encodeURIComponent(filePath)}`;
+
+ return (
+ <TopSymbolsRow
+ symbols={data?.items}
+ loading={isLoading}
+ error={error instanceof Error ? error.message : error ? String(error) : undefined}
+ onSelect={onSelectSymbol}
+ seeAllHref={seeAllHref}
+ />
+ );
+}
diff --git a/packages/web/src/lib/api/symbols.ts b/packages/web/src/lib/api/symbols.ts
index e998f1d23..d061e128f 100644
--- a/packages/web/src/lib/api/symbols.ts
+++ b/packages/web/src/lib/api/symbols.ts
@@ -9,6 +9,7 @@ export interface SymbolListParams {
kind?: string;
language?: string;
visibility?: string;
+ file_path?: string;
in_hot_files?: boolean;
in_entry_points?: boolean;
sort?: SymbolSortKey;
diff --git a/packages/web/src/lib/api/types.ts b/packages/web/src/lib/api/types.ts
index 677cf4753..0d383a18d 100644
--- a/packages/web/src/lib/api/types.ts
+++ b/packages/web/src/lib/api/types.ts
@@ -592,8 +592,10 @@ export interface DecisionCreate {
}
export interface DecisionStatusUpdate {
- status: string;
+ status?: string;
superseded_by?: string;
+ affected_modules?: string[];
+ affected_files?: string[];
}
export interface DecisionHealthResponse {
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index 1f4415e9f..26451f7bd 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -29,6 +29,7 @@ def _create_test_app():
from fastapi import FastAPI
from repowise.server.routers import (
dead_code,
+ decisions,
git,
graph,
health,
@@ -74,6 +75,7 @@ def _create_test_app():
app.include_router(dead_code.router)
app.include_router(owners.router)
app.include_router(modules.router)
+ app.include_router(decisions.router)
return app
diff --git a/tests/unit/server/test_decisions_patch.py b/tests/unit/server/test_decisions_patch.py
new file mode 100644
index 000000000..a09bdca7d
--- /dev/null
+++ b/tests/unit/server/test_decisions_patch.py
@@ -0,0 +1,112 @@
+"""Tests for PATCH /api/repos/{id}/decisions/{decision_id}.
+
+Covers the expanded contract: clients may patch ``status`` alone, the
+``affected_modules`` / ``affected_files`` linkage alone, or both in a single
+request. Fields left as ``None`` must be preserved.
+"""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+
+async def _seed_decision(session_factory, repo_id: str) -> str:
+ async with get_session(session_factory) as session:
+ rec = await crud.upsert_decision(
+ session,
+ repository_id=repo_id,
+ title="Use SQLite for the dev DB",
+ status="active",
+ context="Local dev needs zero-config storage.",
+ decision="SQLite via aiosqlite for all unit tests and CLI runs.",
+ affected_modules=["packages/core"],
+ affected_files=["packages/core/src/repowise/core/persistence/database.py"],
+ source="cli",
+ )
+ return rec.id
+
+
+async def test_patch_decision_status_only(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ decision_id = await _seed_decision(app.state.session_factory, repo["id"])
+
+ resp = await client.patch(
+ f"/api/repos/{repo['id']}/decisions/{decision_id}",
+ json={"status": "deprecated"},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "deprecated"
+ # Linkage preserved.
+ assert body["affected_modules"] == ["packages/core"]
+ assert body["affected_files"] == [
+ "packages/core/src/repowise/core/persistence/database.py"
+ ]
+
+
+async def test_patch_decision_modules_only(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ decision_id = await _seed_decision(app.state.session_factory, repo["id"])
+
+ resp = await client.patch(
+ f"/api/repos/{repo['id']}/decisions/{decision_id}",
+ json={"affected_modules": ["packages/server", "packages/cli"]},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ # Status untouched.
+ assert body["status"] == "active"
+ assert body["affected_modules"] == ["packages/server", "packages/cli"]
+
+
+async def test_patch_decision_clear_files(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ decision_id = await _seed_decision(app.state.session_factory, repo["id"])
+
+ resp = await client.patch(
+ f"/api/repos/{repo['id']}/decisions/{decision_id}",
+ json={"affected_files": []},
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["affected_files"] == []
+ # Modules untouched (None means preserve).
+ assert body["affected_modules"] == ["packages/core"]
+
+
+async def test_patch_decision_status_and_modules(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ decision_id = await _seed_decision(app.state.session_factory, repo["id"])
+
+ resp = await client.patch(
+ f"/api/repos/{repo['id']}/decisions/{decision_id}",
+ json={
+ "status": "superseded",
+ "superseded_by": "abc123",
+ "affected_modules": ["packages/server"],
+ },
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert body["status"] == "superseded"
+ assert body["superseded_by"] == "abc123"
+ assert body["affected_modules"] == ["packages/server"]
+
+
+async def test_patch_decision_not_found(client: AsyncClient) -> None:
+ repo = await create_test_repo(client)
+ resp = await client.patch(
+ f"/api/repos/{repo['id']}/decisions/missing",
+ json={"status": "deprecated"},
+ )
+ assert resp.status_code == 404
diff --git a/tests/unit/server/test_symbols.py b/tests/unit/server/test_symbols.py
index c6ab73c65..8255753a0 100644
--- a/tests/unit/server/test_symbols.py
+++ b/tests/unit/server/test_symbols.py
@@ -82,6 +82,36 @@ async def test_search_symbols_by_kind(client: AsyncClient, app) -> None:
assert data[0]["kind"] == "class"
+async def test_search_symbols_by_file_path(client: AsyncClient, app) -> None:
+ """The ``file_path`` filter scopes results to a single source file —
+ powers the hotspot-row → top-symbols drill-down."""
+ repo = await create_test_repo(client)
+ await _insert_symbol(
+ app.state.session_factory,
+ repo["id"],
+ name="alpha",
+ symbol_id="src/a.py::alpha",
+ file_path="src/a.py",
+ )
+ await _insert_symbol(
+ app.state.session_factory,
+ repo["id"],
+ name="beta",
+ symbol_id="src/b.py::beta",
+ file_path="src/b.py",
+ )
+
+ resp = await client.get(
+ "/api/symbols",
+ params={"repo_id": repo["id"], "file_path": "src/a.py"},
+ )
+ assert resp.status_code == 200
+ payload = resp.json()
+ assert payload["total"] == 1
+ assert payload["items"][0]["name"] == "alpha"
+
+
@pytest.mark.asyncio
async def test_lookup_by_name_exact(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)