Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(doc-drift): group findings by document and show which documents name a file (#2647)
Raghav Chamadiya902c0bcbe835
diff --git a/packages/ui/__tests__/dashboard/attention-href.test.ts b/packages/ui/__tests__/dashboard/attention-href.test.tsnew file mode 100644index 000000000..188f6ed22--- /dev/null+++ b/packages/ui/__tests__/dashboard/attention-href.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";+import { docDriftHref, getDefaultHref, type AttentionItem } from "../../src/dashboard/attention-href";++function drift(target_id?: string): AttentionItem {+ return {+ id: "drift-7",+ type: "doc_drift",+ title: "docs/a b.md",+ description: "No file matches this path.",+ severity: "medium",+ ...(target_id ? { target_id } : {}),+ };+}++describe("getDefaultHref: doc_drift", () => {+ it("lands on the drift tab filtered to the document", () => {+ expect(getDefaultHref(drift("docs/a b.md"), "/repos/r1")).toBe(+ "/repos/r1/code-health?tab=doc-drift&document=docs%2Fa%20b.md",+ );+ });++ it("falls back to the unfiltered tab without a document", () => {+ expect(getDefaultHref(drift(), "/repos/r1")).toBe("/repos/r1/code-health?tab=doc-drift");+ });+});++describe("docDriftHref", () => {+ it("encodes the document and omits it when absent", () => {+ expect(docDriftHref("/repos/r1", "docs/a&b.md")).toBe(+ "/repos/r1/code-health?tab=doc-drift&document=docs%2Fa%26b.md",+ );+ expect(docDriftHref("/repos/r1")).toBe("/repos/r1/code-health?tab=doc-drift");+ });+});diff --git a/packages/ui/__tests__/doc-drift/doc-drift-references.test.tsx b/packages/ui/__tests__/doc-drift/doc-drift-references.test.tsxnew file mode 100644index 000000000..3e4c91a37--- /dev/null+++ b/packages/ui/__tests__/doc-drift/doc-drift-references.test.tsx@@ -0,0 +1,128 @@+import { describe, it, expect, vi } from "vitest";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";+import { SWRConfig } from "swr";+import type { ReactElement } from "react";++import { DocDriftReferences } from "../../src/doc-drift/doc-drift-references.js";+import type { DocDriftReferencesResponse } from "@repowise-dev/types/doc-drift";++const BASIS = "A reference names a file; it is not a description of it.";++function response(over: Partial<DocDriftReferencesResponse> = {}): DocDriftReferencesResponse {+ return {+ target_path: "src/auth.py",+ references: [+ { document: "docs/guide.md", line: 30, kind: "path", section: "Setup > Auth" },+ { document: "README.md", line: 4, kind: "path" },+ { document: "docs/guide.md", line: 12, kind: "path" },+ ],+ references_emitted: 3,+ references_total: 3,+ documents: 2,+ documents_with_drift: [{ document: "docs/guide.md", findings: 2 }],+ references_basis: BASIS,+ unavailable: null,+ ...over,+ };+}++type Adapter = React.ComponentProps<typeof DocDriftReferences>["adapter"];++function renderPanel(+ listReferences: Adapter["listReferences"],+ extra: { driftHref?: (document: string) => string; navigate?: (href: string) => void } = {},+): ReturnType<typeof render> {+ const { driftHref, navigate } = extra;+ const adapter: Adapter = {+ cacheKey: "repo-1",+ ...(listReferences ? { listReferences } : {}),+ documentHref: (path, line) => `/files/${path}${line ? `#L${line}` : ""}`,+ ...(navigate ? { navigate } : {}),+ };+ const node: ReactElement = (+ <DocDriftReferences target="src/auth.py" adapter={adapter} driftHref={driftHref} />+ );+ return render(+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>{node}</SWRConfig>,+ );+}++describe("DocDriftReferences", () => {+ it("lists each naming document once, with its lines and section", async () => {+ const load = vi.fn(async () => response());+ renderPanel(load);++ expect(await screen.findByText("docs/guide.md")).toBeTruthy();+ expect(load).toHaveBeenCalledWith("src/auth.py");+ expect(screen.getByText("README.md")).toBeTruthy();+ const lines = screen.getAllByText(/^line \d+$/).map((el) => el.textContent);+ expect(lines).toEqual(["line 12", "line 30", "line 4"]);+ expect(screen.getByText("Setup > Auth")).toBeTruthy();+ expect(screen.getByText(new RegExp(BASIS.slice(0, 30)))).toBeTruthy();+ // A reference is weaker than a description; the panel never claims more.+ expect(document.body.textContent).not.toMatch(/describes/i);+ });++ it("marks the documents that carry drift and links to their findings", async () => {+ const navigate = vi.fn();+ renderPanel(async () => response(), {+ driftHref: (d) => `/drift?document=${d}`,+ navigate,+ });++ fireEvent.click(await screen.findByText("2 drifted assertions in this document"));+ await waitFor(() => expect(navigate).toHaveBeenCalledWith("/drift?document=docs/guide.md"));+ expect(screen.getAllByText(/drifted assertion/)).toHaveLength(1);+ });++ it("says plainly when no document names the file, with the basis", async () => {+ renderPanel(async () =>+ response({+ references: [],+ references_emitted: 0,+ references_total: 0,+ documents: 0,+ documents_with_drift: [],+ }),+ );+ expect(await screen.findByText(/No document names this file\./)).toBeTruthy();+ expect(screen.getByText(new RegExp(BASIS.slice(0, 30)))).toBeTruthy();+ });++ it("names the refusal rather than reading as no references", async () => {+ renderPanel(async () =>+ response({ references: [], documents: 0, unavailable: "not_computed" }),+ );+ expect(await screen.findByText(/has not been checked yet/i)).toBeTruthy();+ expect(screen.queryByText(/No document names this file/)).toBeNull();+ });++ it("renders nothing on a failed read", async () => {+ const load = vi.fn(async () => {+ throw new Error("boom");+ });+ const { container } = renderPanel(load);+ await waitFor(() => expect(load).toHaveBeenCalled());+ await waitFor(() => expect(container.textContent).toBe(""));+ });++ it("renders nothing when the host cannot list references", () => {+ const { container } = renderPanel(undefined);+ expect(container.textContent).toBe("");+ });++ it("leaves a modified or non-primary click to the browser", async () => {+ const navigate = vi.fn();+ renderPanel(async () => response(), { navigate });+ const link = await screen.findByText("README.md");+ // Runs after React's handler; stops jsdom attempting the real navigation.+ const block = (e: Event) => e.preventDefault();+ document.addEventListener("click", block);+ fireEvent.click(link, { button: 1 });+ fireEvent.click(link, { ctrlKey: true });+ expect(navigate).not.toHaveBeenCalled();+ fireEvent.click(link);+ expect(navigate).toHaveBeenCalledWith("/files/README.md");+ document.removeEventListener("click", block);+ });+});diff --git a/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx b/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsxindex 732efaff3..5a0f0a369 100644--- a/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx+++ b/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx@@ -21,8 +21,10 @@ vi.stubGlobal("ResizeObserver", RO);/*** The findings table stacks into a card list beside the real table and lets CSS* pick one. jsdom applies no CSS, so a cell matches in both; scope by caption.+ * One table per document, so the caption names which.*/-const TABLE = { name: /Documentation assertions/i };+const TABLE = { name: /Documentation assertions in docs\/architecture\.md/i };+const CLI_TABLE = { name: /Documentation assertions in docs\/cli\.md/i };/** The detail panel and the prompt modal are both dialogs; name tells them apart. */const PANEL = /docs\/architecture\.md:42/;const PROMPT = /Documentation fix prompt/i;@@ -132,7 +134,7 @@ describe("DocDriftView", () => {renderView(<DocDriftView adapter={makeAdapter()} />);const table = await screen.findByRole("table", TABLE);- expect(within(table).getByText(/docs\/architecture\.md/)).toBeTruthy();+ expect(screen.getByRole("heading", { name: "docs/architecture.md" })).toBeTruthy();expect(within(table).getByText("src/auth.py")).toBeTruthy();});@@ -346,7 +348,7 @@ describe("DocDriftView", () => {renderView(<DocDriftView adapter={makeAdapter({ navigate })} />);const table = await screen.findByRole("table", TABLE);- fireEvent.click(within(table).getByText(/docs\/architecture\.md/));+ fireEvent.click(within(table).getByText("src/auth.py"));expect(await screen.findByRole("dialog", { name: PANEL })).toBeTruthy();expect(navigate).not.toHaveBeenCalled();@@ -355,7 +357,7 @@ describe("DocDriftView", () => {it("shows the evidence the row has no room for", async () => {renderView(<DocDriftView adapter={makeAdapter()} />);const table = await screen.findByRole("table", TABLE);- fireEvent.click(within(table).getByText(/docs\/architecture\.md/));+ fireEvent.click(within(table).getByText("src/auth.py"));// The line as written, the heading trail and the resolver's trace all// arrive with every finding and were previously discarded.@@ -367,15 +369,15 @@ describe("DocDriftView", () => {it("shows the likely replacement only when the engine found one", async () => {renderView(<DocDriftView adapter={makeAdapter()} />);const table = await screen.findByRole("table", TABLE);- fireEvent.click(within(table).getByText(/docs\/architecture\.md/));+ const cliTable = screen.getByRole("table", CLI_TABLE);+ fireEvent.click(within(table).getByText("src/auth.py"));const panel = await screen.findByRole("dialog", { name: PANEL });expect(within(panel).getByText("Likely now")).toBeTruthy();expect(within(panel).getByText("src/auth/")).toBeTruthy();expect(within(panel).getByText("Became a package")).toBeTruthy();- // The document and its own-anchor target both match; either cell opens the row.- fireEvent.click(within(table).getAllByText(/docs\/cli\.md/)[0]!);+ fireEvent.click(within(cliTable).getByText("docs/cli.md#usage"));const other = await screen.findByRole("dialog", { name: /docs\/cli\.md:7/ });expect(within(other).queryByText("Likely now")).toBeNull();});@@ -383,7 +385,7 @@ describe("DocDriftView", () => {it("repeats what a finding does and does not claim where the action is", async () => {renderView(<DocDriftView adapter={makeAdapter()} />);const table = await screen.findByRole("table", TABLE);- fireEvent.click(within(table).getByText(/docs\/architecture\.md/));+ fireEvent.click(within(table).getByText("src/auth.py"));const panel = await screen.findByRole("dialog", { name: PANEL });expect(within(panel).getByText(new RegExp(BASIS.slice(0, 40)))).toBeTruthy();@@ -393,7 +395,7 @@ describe("DocDriftView", () => {const navigate = vi.fn();renderView(<DocDriftView adapter={makeAdapter({ navigate })} />);const table = await screen.findByRole("table", TABLE);- fireEvent.click(within(table).getByText(/docs\/architecture\.md/));+ fireEvent.click(within(table).getByText("src/auth.py"));fireEvent.click(await screen.findByRole("link", { name: /Open document/i }));await waitFor(() =>@@ -446,4 +448,99 @@ describe("DocDriftView", () => {expect(prompt).toContain("docs/architecture.md:42");expect(prompt).toContain("docs/cli.md:7");});++ it("groups rows under their document, in reading order", async () => {+ const early: DocDriftFinding = { ...FINDINGS[0]!, id: "f0", line_number: 3, target: "src/old.py" };+ const adapter = makeAdapter({+ listFindings: vi.fn(async () =>+ response({ findings: [FINDINGS[1]!, FINDINGS[0]!, early], findings_emitted: 3 }),+ ),+ });+ renderView(<DocDriftView adapter={adapter} />);++ const table = await screen.findByRole("table", TABLE);+ const headings = screen+ .getAllByRole("heading", { level: 3 })+ .map((h) => h.textContent);+ expect(headings).toEqual(["docs/architecture.md", "docs/cli.md"]);+ expect(screen.getByText("2 findings")).toBeTruthy();+ expect(screen.getByText("1 finding")).toBeTruthy();++ const rows = within(table).getAllByRole("row").slice(1);+ expect(rows.map((r) => within(r).getByText(/^line /).textContent)).toEqual([+ "line 3",+ "line 42",+ ]);+ });++ it("narrows to one document on the server when one is picked", async () => {+ const listFindings = vi.fn(async () => response());+ renderView(<DocDriftView adapter={makeAdapter({ listFindings })} />);+ await screen.findByRole("table", TABLE);++ fireEvent.change(screen.getByLabelText(/^Document$/), {+ target: { value: "docs/cli.md" },+ });++ await waitFor(() =>+ expect(listFindings).toHaveBeenCalledWith(+ expect.objectContaining({ document: "docs/cli.md" }),+ ),+ );+ });++ it("opens narrowed to a deep-linked document", async () => {+ const listFindings = vi.fn(async () => response());+ renderView(+ <DocDriftView+ adapter={makeAdapter({ listFindings })}+ initialDocument="docs/cli.md"+ />,+ );++ await screen.findByRole("table", CLI_TABLE);+ expect(listFindings).toHaveBeenCalledWith(+ expect.objectContaining({ document: "docs/cli.md" }),+ );+ // Rows follow the selection even when a host's server ignores the filter.+ expect(screen.queryByRole("table", TABLE)).toBeNull();+ });++ it("keeps the previous document's rows while the next one loads", async () => {+ let release: (r: DocDriftResponse) => void = () => {};+ const listFindings = vi.fn(async (opts?: { document?: string }) => {+ if (opts?.document === "docs/cli.md") {+ return new Promise<DocDriftResponse>((resolve) => (release = resolve));+ }+ const findings = FINDINGS.filter(+ (f) => !opts?.document || f.file_path === opts.document,+ );+ return response({ findings, findings_emitted: findings.length });+ });+ renderView(+ <DocDriftView+ adapter={makeAdapter({ listFindings })}+ initialDocument="docs/architecture.md"+ />,+ );+ await screen.findByRole("table", TABLE);+ await screen.findByRole("option", { name: "docs/cli.md" });++ fireEvent.change(screen.getByLabelText(/^Document$/), {+ target: { value: "docs/cli.md" },+ });++ // Filtering A's rows to B client-side would flash the empty state.+ await waitFor(() =>+ expect(listFindings).toHaveBeenCalledWith(+ expect.objectContaining({ document: "docs/cli.md" }),+ ),+ );+ expect(screen.queryByText("No findings in this slice")).toBeNull();+ expect(screen.getByRole("table", TABLE)).toBeTruthy();++ release(response({ findings: [FINDINGS[1]!], findings_emitted: 1 }));+ expect(await screen.findByRole("table", CLI_TABLE)).toBeTruthy();+ expect(screen.queryByRole("table", TABLE)).toBeNull();+ });});diff --git a/packages/ui/src/dashboard/attention-href.ts b/packages/ui/src/dashboard/attention-href.tsindex 4cc7f8f22..4664c3c7e 100644--- a/packages/ui/src/dashboard/attention-href.ts+++ b/packages/ui/src/dashboard/attention-href.ts@@ -117,6 +117,12 @@ export function attentionSourceHref(source: string, prefix: string): string {}}+/** The doc drift tab, narrowed to one document when given. */+export function docDriftHref(prefix: string, document?: string): string {+ const base = attentionSourceHref("doc_drift", prefix);+ return document ? `${base}&document=${encodeURIComponent(document)}` : base;+}+/** Area keys are not item types, so they get their own names. */const AREA_LABEL: Record<string, string> = {security: "Security",@@ -188,10 +194,9 @@ export function getDefaultHref(item: AttentionItem, prefix: string): string {// agent.return attentionSourceHref(item.type, prefix);case "doc_drift":- // Also the category. `target_id` here is the *document* making the false- // claim rather than the code it is wrong about, so a file page would- // open the wrong subject.- return attentionSourceHref(item.type, prefix);+ // The drift tab filtered to the *document* making the false claim+ // (`target_id`); a file page would open the code, the wrong subject.+ return docDriftHref(prefix, target);case "dead_code":// The row names one symbol, so the category list is the wrong landing:// the dead-code tab has no per-file filter, and arriving at a fewdiff --git a/packages/ui/src/doc-drift/doc-drift-adapter.ts b/packages/ui/src/doc-drift/doc-drift-adapter.tsindex 54efc79e2..bbed088dc 100644--- a/packages/ui/src/doc-drift/doc-drift-adapter.ts+++ b/packages/ui/src/doc-drift/doc-drift-adapter.ts@@ -34,6 +34,8 @@ export interface DocDriftAdapter {listFindings(opts?: {min_confidence?: number;kind?: string;+ /** One document's findings. Optional: a host may ignore it. */+ document?: string;limit?: number;}): Promise<DocDriftResponse>;diff --git a/packages/ui/src/doc-drift/doc-drift-detail-panel.tsx b/packages/ui/src/doc-drift/doc-drift-detail-panel.tsxindex 8b4d22888..3ed57f76a 100644--- a/packages/ui/src/doc-drift/doc-drift-detail-panel.tsx+++ b/packages/ui/src/doc-drift/doc-drift-detail-panel.tsx@@ -25,6 +25,7 @@ import {import { AdaptivePanel } from "../shared/adaptive-panel";import { AiPromptButton } from "../health/ai-prompt-button";+import { RouterAnchor } from "./router-anchor";/** The evidence line carrying the enclosing heading trail. */const TRAIL_PREFIX = "under: ";@@ -166,20 +167,14 @@ export function DocDriftDetailPanel({onClick={() => onPrompt(finding)}label="Fix with an agent"/>- <a+ <RouterAnchorhref={documentHref(finding.file_path, finding.line_number)}- // Stays a real anchor so it can be opened in a new tab; the router- // only takes over a plain left click.- onClick={(event) => {- if (!navigate || event.metaKey || event.ctrlKey || event.shiftKey) return;- event.preventDefault();- navigate(documentHref(finding.file_path, finding.line_number));- }}+ navigate={navigate}className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1 text-xs font-medium text-[var(--color-text-secondary)] transition-colors hover:border-[var(--color-border-hover)] hover:text-[var(--color-text-primary)]"><ExternalLink className="h-3.5 w-3.5" />Open document- </a>+ </RouterAnchor></div></div></AdaptivePanel>diff --git a/packages/ui/src/doc-drift/doc-drift-references.tsx b/packages/ui/src/doc-drift/doc-drift-references.tsxnew file mode 100644index 000000000..ddfc2b835--- /dev/null+++ b/packages/ui/src/doc-drift/doc-drift-references.tsx@@ -0,0 +1,165 @@+"use client";++/**+ * The reverse view of doc drift, for a file page: which documents name this+ * file, at which lines, and which of those documents carry drift somewhere.+ *+ * A reference is weaker than a description. It says a document names the file,+ * not that it explains it, so every word here stays at "names". Drift on a+ * listed document is a fact about the document: a drifted reference resolves+ * to nothing, so it can never mean the passage about this file is wrong.+ */++import useSWR from "swr";+import type { DocDriftReferencesResponse } from "@repowise-dev/types/doc-drift";++import { Skeleton } from "../ui/skeleton";+import type { DocDriftAdapter } from "./doc-drift-adapter";+import { docDriftUnavailableCopy } from "./doc-drift-unavailable";+import { groupByDocument } from "./group-by-document";+import { RouterAnchor } from "./router-anchor";++export interface DocDriftReferencesProps {+ /** Repo-relative path of the file the page is about. */+ target: string;+ /** Without `listReferences` the panel renders nothing. */+ adapter: Pick<DocDriftAdapter, "cacheKey" | "listReferences" | "documentHref" | "navigate">;+ /** Link to a document's drift findings. Omitted, the drift mark is plain text. */+ driftHref?: ((document: string) => string) | undefined;+}++export function DocDriftReferences({ target, adapter, driftHref }: DocDriftReferencesProps) {+ const { documentHref, navigate } = adapter;+ const { data, isLoading } = useSWR<DocDriftReferencesResponse | null>(+ adapter.listReferences ? `doc-drift-references:${adapter.cacheKey}:${target}` : null,+ // A failed read renders nothing: this panel is a side note on a file page,+ // and an error card here would outshout the page it sits on.+ () => adapter.listReferences!(target).catch(() => null),+ { revalidateOnFocus: false },+ );++ if (isLoading) return <Skeleton className="h-16 w-full max-w-[52ch] rounded-md" />;+ if (!data) return null;++ if (data.unavailable) {+ const copy = docDriftUnavailableCopy(data.unavailable);+ return (+ <Frame>+ <Prose>{copy.title}. {copy.description}</Prose>+ </Frame>+ );+ }++ if (data.references.length === 0) {+ return (+ <Frame>+ <Prose>No document names this file. {data.references_basis}</Prose>+ </Frame>+ );+ }++ const drift = new Map(data.documents_with_drift.map((d) => [d.document, d.findings]));+ const groups = groupByDocument(data.references, (r) => r.document, (r) => r.line);++ return (+ <Frame>+ <Prose>+ <strong className="font-semibold text-[var(--color-text-primary)]">+ {data.documents} {data.documents === 1 ? "document names" : "documents name"}+ </strong>{" "}+ this file, in {data.references_total}{" "}+ {data.references_total === 1 ? "place" : "places"}. {data.references_basis}+ </Prose>+ <ul className="flex flex-col">+ {groups.map((group) => {+ const findings = drift.get(group.document);+ return (+ <li+ key={group.document}+ className="flex flex-col gap-1 border-t border-[var(--color-border-default)] py-2"+ >+ <div className="flex min-w-0 flex-wrap items-baseline justify-between gap-x-3 gap-y-0.5">+ <RouterAnchor+ href={documentHref(group.document)}+ navigate={navigate}+ title={group.document}+ className="min-w-0 truncate font-mono text-xs text-[var(--color-text-primary)] transition-colors hover:text-[var(--color-accent-primary)]"+ >+ {group.document}+ </RouterAnchor>+ {findings ? (+ driftHref ? (+ <RouterAnchor+ href={driftHref(group.document)}+ navigate={navigate}+ className="shrink-0 text-xs text-[var(--color-warning)] hover:underline"+ >+ {driftLabel(findings)}+ </RouterAnchor>+ ) : (+ <span className="shrink-0 text-xs text-[var(--color-warning)]">+ {driftLabel(findings)}+ </span>+ )+ ) : null}+ </div>+ <ul className="flex flex-col gap-0.5">+ {group.items.map((r) => (+ <li+ key={`${r.line}:${r.kind}`}+ className="flex min-w-0 items-baseline gap-2 text-xs"+ >+ <RouterAnchor+ href={documentHref(group.document, r.line)}+ navigate={navigate}+ className="shrink-0 font-mono tabular-nums text-[var(--color-text-secondary)] hover:text-[var(--color-accent-primary)]"+ >+ line {r.line}+ </RouterAnchor>+ {r.section ? (+ <span+ className="min-w-0 truncate text-[var(--color-text-tertiary)]"+ title={r.section}+ >+ {r.section}+ </span>+ ) : null}+ </li>+ ))}+ </ul>+ </li>+ );+ })}+ </ul>+ {data.references_emitted < data.references_total && (+ <p className="border-t border-[var(--color-border-default)] pt-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ listing {data.references_emitted} of {data.references_total} references+ </p>+ )}+ </Frame>+ );+}++/** Drift is the document's, counted over the whole document. */+function driftLabel(findings: number): string {+ return `${findings} drifted ${findings === 1 ? "assertion" : "assertions"} in this document`;+}++function Frame({ children }: { children: React.ReactNode }) {+ return (+ <section className="flex flex-col gap-2">+ <h3 className="text-[13px] font-semibold text-[var(--color-text-primary)]">+ Documents naming this file+ </h3>+ {children}+ </section>+ );+}++function Prose({ children }: { children: React.ReactNode }) {+ return (+ <p className="max-w-[62ch] text-[13px] leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">+ {children}+ </p>+ );+}diff --git a/packages/ui/src/doc-drift/doc-drift-unavailable.tsx b/packages/ui/src/doc-drift/doc-drift-unavailable.tsxindex c01586a57..509e96f22 100644--- a/packages/ui/src/doc-drift/doc-drift-unavailable.tsx+++ b/packages/ui/src/doc-drift/doc-drift-unavailable.tsx@@ -18,6 +18,7 @@ import { EmptyState } from "../shared/empty-state";* separate cause and not folded into the stale-index one.*/type Copy = { title: string; description: string; retryable: boolean };+export type DocDriftUnavailableCopy = Copy;const COPY: Record<DocDriftUnavailable, Copy> = {not_computed: {@@ -53,6 +54,13 @@ const UNKNOWN: Copy = {retryable: true,};+/** The copy for one refusal, for a surface too small for the full state. */+export function docDriftUnavailableCopy(+ reason: DocDriftUnavailable,+): DocDriftUnavailableCopy {+ return COPY[reason] ?? UNKNOWN;+}+export function DocDriftUnavailableState({reason,titleAs,@@ -63,7 +71,7 @@ export function DocDriftUnavailableState({/** Offered only where retrying could change the answer. */onRetry?: (() => void) | undefined;}) {- const copy = COPY[reason] ?? UNKNOWN;+ const copy = docDriftUnavailableCopy(reason);return (<EmptyStateicon={<FileQuestion className="h-6 w-6" />}diff --git a/packages/ui/src/doc-drift/doc-drift-view.tsx b/packages/ui/src/doc-drift/doc-drift-view.tsxindex a1c2382e9..7f2dfd43d 100644--- a/packages/ui/src/doc-drift/doc-drift-view.tsx+++ b/packages/ui/src/doc-drift/doc-drift-view.tsx@@ -24,7 +24,7 @@*/import { useState } from "react";-import useSWR from "swr";+import useSWR, { useSWRConfig } from "swr";import { FileCheck2 } from "lucide-react";import {DOC_DRIFT_CONFIDENCE,@@ -74,12 +74,29 @@ function filterKinds(return [...keys].sort();}+/**+ * Documents for the filter, read off the same unfiltered response as the+ * kinds. Ceiling: that response is capped at {@link FINDINGS_LIMIT}, so a+ * document whose findings all fall past the cap is not offered.+ */+function filterDocuments(+ distribution: DocDriftResponse | undefined,+ selected: string,+): string[] {+ const keys = new Set((distribution?.findings ?? []).map((f) => f.file_path));+ if (selected) keys.add(selected);+ return [...keys].sort();+}+export function DocDriftView({adapter,renderError,renderLoading,+ initialDocument,}: {adapter: DocDriftAdapter;+ /** Open narrowed to one document, e.g. from a `?document=` deep link. */+ initialDocument?: string | undefined;/** Host-specific failure card — an auth toast, a permissions notice. */renderError?: (error: unknown, retry: () => void) => React.ReactNode;/** Host-specific skeleton, for a shell that has its own loading language. */@@ -91,6 +108,7 @@ export function DocDriftView({DOC_DRIFT_CONFIDENCE.MEDIUM,);const [kind, setKind] = useState<string>("");+ const [document, setDocument] = useState<string>(initialDocument ?? "");/** The finding the detail panel is describing. */const [selected, setSelected] = useState<DocDriftFinding | null>(null);/** The findings handed to the prompt modal; null when it is closed. */@@ -98,22 +116,28 @@ export function DocDriftView({null,);+ // The document suffix only when set, so the unfiltered key stays the one+ // a page-level fetch and the distribution below share.+ const key = `doc-drift:${adapter.cacheKey}:${minConfidence}:${kind}${document ? `:${document}` : ""}`;+ const { cache } = useSWRConfig();const { data, isLoading, error, mutate } = useSWR<DocDriftResponse>(- `doc-drift:${adapter.cacheKey}:${minConfidence}:${kind}`,+ key,() =>adapter.listFindings({min_confidence: minConfidence,limit: FINDINGS_LIMIT,...(kind ? { kind } : {}),+ ...(document ? { document } : {}),}),{ revalidateOnFocus: false, keepPreviousData: true },);- // The kind options come from the same query without the kind filter. When- // nothing is selected that is the key above, so SWR serves both from one- // request; only a narrowed view pays for a second.+ // The kind and document options come from the same query without either+ // filter. When nothing is selected that is the key above, so SWR serves both+ // from one request; only a narrowed view pays for a second.+ const narrowed = kind !== "" || document !== "";const { data: distribution } = useSWR<DocDriftResponse>(- kind ? `doc-drift:${adapter.cacheKey}:${minConfidence}:` : null,+ narrowed ? `doc-drift:${adapter.cacheKey}:${minConfidence}:` : null,() =>adapter.listFindings({min_confidence: minConfidence,@@ -163,8 +187,18 @@ export function DocDriftView({if (!summary) return null;const truncated = data.findings_emitted < summary.findings_total;- const kinds = filterKinds(kind ? (distribution ?? data) : data, kind);- const filtered = minConfidence !== DOC_DRIFT_CONFIDENCE.MEDIUM || kind !== "";+ const unfiltered = narrowed ? (distribution ?? data) : data;+ const kinds = filterKinds(unfiltered, kind);+ const documents = filterDocuments(unfiltered, document);+ const filtered = minConfidence !== DOC_DRIFT_CONFIDENCE.MEDIUM || narrowed;+ // Also narrowed here, for a host whose server ignores `document`: its rows+ // still match the selection even though its summary stays repo-wide. Not+ // while `data` is the previous key's (keepPreviousData): filtering another+ // document's rows to this one would flash an empty table.+ const current = cache.get(key)?.data !== undefined;+ const findings = document && current+ ? data.findings.filter((f) => f.file_path === document)+ : data.findings;return (<div className="flex flex-col gap-8">@@ -189,10 +223,10 @@ export function DocDriftView({description="Each row names the document to edit and the line to edit it on. It does not claim the document describes the file it names, only that the file is no longer there."action={<div className="flex flex-wrap items-center gap-2">- {data.findings.length > 0 && (+ {findings.length > 0 && (<AiPromptButton- onClick={() => setPromptFindings(data.findings)}- label={`Fix ${data.findings.length} with an agent`}+ onClick={() => setPromptFindings(findings)}+ label={`Fix ${findings.length} with an agent`}/>)}<Filters@@ -201,6 +235,9 @@ export function DocDriftView({kind={kind}onKind={setKind}kinds={kinds}+ document={document}+ onDocument={setDocument}+ documents={documents}/></div>}@@ -222,7 +259,7 @@ export function DocDriftView({</p>)}<DriftFindingsTable- findings={data.findings}+ findings={findings}onSelect={setSelected}onPrompt={(finding) => setPromptFindings([finding])}selectedId={selected?.id ?? null}@@ -268,8 +305,9 @@ const SELECT_CLS ="h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-xs text-[var(--color-text-secondary)]";/**- * Two filters, each on its own axis: how sure the finding is, and how it was- * found. Both go to the server so the lede's figures narrow with the rows.+ * Three filters, each on its own axis: how sure the finding is, how it was+ * found, and which document it is in. All go to the server so the lede's+ * figures narrow with the rows.*/function Filters({minConfidence,@@ -277,12 +315,18 @@ function Filters({kind,onKind,kinds,+ document,+ onDocument,+ documents,}: {minConfidence: number;onMinConfidence: (value: number) => void;kind: string;onKind: (value: string) => void;kinds: string[];+ document: string;+ onDocument: (value: string) => void;+ documents: string[];}) {return (<div className="flex flex-wrap items-center gap-2">@@ -321,6 +365,27 @@ function Filters({</select></>)}++ {(documents.length > 1 || document !== "") && (+ <>+ <label className="sr-only" htmlFor="doc-drift-document">+ Document+ </label>+ <select+ id="doc-drift-document"+ className={`${SELECT_CLS} max-w-[28ch] truncate`}+ value={document}+ onChange={(e) => onDocument(e.target.value)}+ >+ <option value="">All documents</option>+ {documents.map((d) => (+ <option key={d} value={d}>+ {d}+ </option>+ ))}+ </select>+ </>+ )}</div>);}diff --git a/packages/ui/src/doc-drift/drift-findings-table.tsx b/packages/ui/src/doc-drift/drift-findings-table.tsxindex 9f9a9218c..e33c9eb26 100644--- a/packages/ui/src/doc-drift/drift-findings-table.tsx+++ b/packages/ui/src/doc-drift/drift-findings-table.tsx@@ -12,6 +12,10 @@* A row opens the detail panel rather than navigating. The evidence that makes* a finding actionable does not fit in a row, and the document's own file page* cannot show it either.+ *+ * Rows are grouped by document, one section each, headed by the path and its+ * count, so the document still leads and each row only adds the line. One+ * table per section because the shared table has no group-header rows.*/import { FileText } from "lucide-react";@@ -28,6 +32,7 @@ import {} from "../shared/responsive-table";import { EmptyState } from "../shared/empty-state";import { AiPromptButton } from "../health/ai-prompt-button";+import { groupByDocument } from "./group-by-document";export interface DriftFindingsTableProps {findings: DocDriftFinding[];@@ -64,13 +69,11 @@ export function DriftFindingsTable({}: DriftFindingsTableProps) {const columns: ResponsiveColumn<DocDriftFinding>[] = [{- key: "document",- header: "Document",+ key: "line",+ header: "Line",priority: 1,- // Widths are capped per cell, not left to the table: a repo-relative- // path and a heading slug are both long and unbreakable, and an- // auto-laid-out table gives them the room by pushing the confidence- // column off the side, which is the one column a reader triages on.+ // Capped per cell so long slugs and reasons cannot push the confidence+ // column, the one a reader triages on, off the side.cellClassName: "max-w-[34ch]",render: (f) => (<div className="flex min-w-0 flex-col gap-0.5">@@ -78,8 +81,7 @@ export function DriftFindingsTable({className="truncate font-mono text-xs text-[var(--color-text-primary)]"title={`${f.file_path}:${f.line_number}`}>- {f.file_path}- <span className="text-[var(--color-text-tertiary)]">:{f.line_number}</span>+ line {f.line_number}{f.is_new ? (<Badge variant="accent" className="ml-1.5 h-4 px-1 text-[10px]">new@@ -156,23 +158,52 @@ export function DriftFindingsTable({},];+ if (findings.length === 0) {+ return (+ <EmptyState+ icon={<FileText className="h-6 w-6" />}+ title="No findings in this slice"+ description="Widen the confidence floor or clear the reference filter to see the rest."+ />+ );+ }++ // Sections by path, rows by line: the order the document is read in.+ const groups = groupByDocument(+ findings,+ (f) => f.file_path,+ (f) => f.line_number,+ ).sort((a, b) => a.document.localeCompare(b.document));+return (- <ResponsiveTable- columns={columns}- rows={findings}- rowKey={(f) => f.id}- stacked="md"- caption="Documentation assertions the repository no longer satisfies"- onRowClick={onSelect}- rowClassName={() => "cursor-pointer"}- selectedKey={selectedId ?? null}- empty={- <EmptyState- icon={<FileText className="h-6 w-6" />}- title="No findings in this slice"- description="Widen the confidence floor or clear the reference filter to see the rest."- />- }- />+ <div className="flex flex-col divide-y divide-[var(--color-border-default)] overflow-hidden border border-[var(--color-border-default)]">+ {groups.map((group) => (+ <section key={group.document} aria-label={group.document}>+ <header className="flex min-w-0 items-baseline justify-between gap-3 bg-[var(--color-bg-elevated)] px-3 py-2">+ <h3+ className="min-w-0 truncate font-mono text-xs font-medium text-[var(--color-text-primary)]"+ title={group.document}+ >+ {group.document}+ </h3>+ <span className="shrink-0 text-xs tabular-nums text-[var(--color-text-tertiary)]">+ {group.items.length}{" "}+ {group.items.length === 1 ? "finding" : "findings"}+ </span>+ </header>+ <ResponsiveTable+ bare+ columns={columns}+ rows={group.items}+ rowKey={(f) => f.id}+ stacked="md"+ caption={`Documentation assertions in ${group.document} the repository no longer satisfies`}+ onRowClick={onSelect}+ rowClassName={() => "cursor-pointer"}+ selectedKey={selectedId ?? null}+ />+ </section>+ ))}+ </div>);}diff --git a/packages/ui/src/doc-drift/group-by-document.ts b/packages/ui/src/doc-drift/group-by-document.tsnew file mode 100644index 000000000..1fecaced5--- /dev/null+++ b/packages/ui/src/doc-drift/group-by-document.ts@@ -0,0 +1,23 @@+export interface DocumentGroup<T> {+ document: string;+ items: T[];+}++/** One group per document in first-seen order, lines ascending within. */+export function groupByDocument<T>(+ items: readonly T[],+ documentOf: (item: T) => string,+ lineOf: (item: T) => number,+): DocumentGroup<T>[] {+ const groups = new Map<string, T[]>();+ for (const item of items) {+ const key = documentOf(item);+ const list = groups.get(key);+ if (list) list.push(item);+ else groups.set(key, [item]);+ }+ return [...groups].map(([document, list]) => ({+ document,+ items: list.sort((a, b) => lineOf(a) - lineOf(b)),+ }));+}diff --git a/packages/ui/src/doc-drift/index.ts b/packages/ui/src/doc-drift/index.tsindex e20a3f860..3ee5e2c8c 100644--- a/packages/ui/src/doc-drift/index.ts+++ b/packages/ui/src/doc-drift/index.ts@@ -1,6 +1,7 @@export * from "./doc-drift-adapter";export * from "./doc-drift-detail-panel";export * from "./doc-drift-lede";+export * from "./doc-drift-references";export * from "./doc-drift-unavailable";export * from "./doc-drift-view";export * from "./drift-findings-table";diff --git a/packages/ui/src/doc-drift/router-anchor.tsx b/packages/ui/src/doc-drift/router-anchor.tsxnew file mode 100644index 000000000..5b313a0ac--- /dev/null+++ b/packages/ui/src/doc-drift/router-anchor.tsx@@ -0,0 +1,44 @@+"use client";++/**+ * A real anchor the host router takes over on a plain left click only, so a+ * middle click or a modifier still opens a new tab.+ */+export function RouterAnchor({+ href,+ navigate,+ className,+ title,+ children,+}: {+ href: string;+ navigate?: ((href: string) => void) | undefined;+ className?: string | undefined;+ title?: string | undefined;+ children: React.ReactNode;+}) {+ return (+ <a+ href={href}+ title={title}+ className={className}+ onClick={(event) => {+ if (+ !navigate ||+ event.defaultPrevented ||+ event.button !== 0 ||+ event.metaKey ||+ event.ctrlKey ||+ event.shiftKey ||+ event.altKey+ ) {+ return;+ }+ event.preventDefault();+ navigate(href);+ }}+ >+ {children}+ </a>+ );+}diff --git a/packages/ui/src/files/file-doc-tab.tsx b/packages/ui/src/files/file-doc-tab.tsxindex 085071c92..70a43fb80 100644--- a/packages/ui/src/files/file-doc-tab.tsx+++ b/packages/ui/src/files/file-doc-tab.tsx@@ -8,17 +8,22 @@ interface FileDocTabProps {wikiPage: FileWikiPageRef | null;/** Server-rendered wiki content (the host renders markdown its own way). */docSlot?: ReactNode | undefined;+ /** The repository's own documents naming this file, rendered below the page. */+ referencesPanel?: ReactNode | undefined;}-export function FileDocTab({ wikiPage, docSlot }: FileDocTabProps) {+export function FileDocTab({ wikiPage, docSlot, referencesPanel }: FileDocTabProps) {if (!wikiPage) {return (- <EmptyState- titleAs="h2"- icon={<BookOpen className="h-8 w-8" />}- title="No documentation page for this file"- description="Repowise writes pages for the files that carry a repository's shape. Re-run the index with a wider page budget to bring this one in."- />+ <div className="space-y-6">+ <EmptyState+ titleAs="h2"+ icon={<BookOpen className="h-8 w-8" />}+ title="No documentation page for this file"+ description="Repowise writes pages for the files that carry a repository's shape. Re-run the index with a wider page budget to bring this one in."+ />+ {referencesPanel}+ </div>);}@@ -62,6 +67,8 @@ export function FileDocTab({ wikiPage, docSlot }: FileDocTabProps) {<article data-chat-selection="" className="max-w-none overflow-hidden">{docSlot}</article>++ {referencesPanel}</div>);}diff --git a/packages/ui/src/files/file-page-panels.tsx b/packages/ui/src/files/file-page-panels.tsxindex 9e174e86e..27dbfc996 100644--- a/packages/ui/src/files/file-page-panels.tsx+++ b/packages/ui/src/files/file-page-panels.tsx@@ -32,6 +32,11 @@ export interface BuildFilePanelsOptions {* a fetcher function cannot cross the server boundary as a prop.*/testsPanel?: ReactNode;+ /**+ * Which of the repository's documents name this file, for the Doc tab.+ * Host-wrapped for the same reason as `testsPanel`.+ */+ docReferencesPanel?: ReactNode;/*** Router link, forwarded to every tab body that renders one.*@@ -69,6 +74,7 @@ export function buildFilePanels({coverageCodeHtml,healthPanel,testsPanel,+ docReferencesPanel,LinkComponent,}: BuildFilePanelsOptions): Partial<Record<FilePageTab, ReactNode>> {const link = LinkComponent ? { LinkComponent } : {};@@ -81,7 +87,13 @@ export function buildFilePanels({{...link}/>),- doc: <FileDocTab wikiPage={data.wiki_page} docSlot={docSlot} />,+ doc: (+ <FileDocTab+ wikiPage={data.wiki_page}+ docSlot={docSlot}+ referencesPanel={docReferencesPanel}+ />+ ),health: healthPanel,history: (<FileHistoryTabdiff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsxindex 252ebb40b..d5d9e6f4a 100644--- a/packages/web/src/app/repos/[id]/code-health/page.tsx+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx@@ -440,6 +440,8 @@ export default function CodeHealthPage() {const sp = new URLSearchParams(searchParams.toString());if (next === "triage") sp.delete("tab");else sp.set("tab", next);+ // The document filter belongs to the drift tab; it must not ride along.+ if (next !== "doc-drift") sp.delete("document");const qs = sp.toString();router.replace(qs ? `?${qs}` : "?", { scroll: false });},@@ -600,7 +602,12 @@ export default function CodeHealthPage() {{activeTab === "performance" && <PerformanceTab repoId={repoId} />}{activeTab === "coverage" && <CoverageTab repoId={repoId} />}{activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}- {activeTab === "doc-drift" && <DocDriftTab repoId={repoId} />}+ {activeTab === "doc-drift" && (+ <DocDriftTab+ repoId={repoId}+ initialDocument={searchParams.get("document") ?? undefined}+ />+ )}{activeTab === "security" && <SecurityTab repoId={repoId} />}{activeTab === "impact" && <ImpactTab repoId={repoId} />}</ViewTabs>diff --git a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx b/packages/web/src/app/repos/[id]/files/[...path]/page.tsxindex 05dc5c4fc..f7d36b0eb 100644--- a/packages/web/src/app/repos/[id]/files/[...path]/page.tsx+++ b/packages/web/src/app/repos/[id]/files/[...path]/page.tsx@@ -20,6 +20,7 @@ import {import { FilePageHost } from "@/components/files/file-page-host";import { FileTestsPanel } from "@/components/files/file-tests-panel";import { FileHealthPanel } from "@/components/files/file-health-panel";+import { FileDocReferencesPanel } from "@/components/files/file-doc-references-panel";import type { FileDetailResponse } from "@repowise-dev/types/files";/** Matches the sibling routes (`decisions`, the repo root, the four workspace@@ -192,6 +193,9 @@ export default async function FileEntityPage({ params, searchParams }: Props) {/>),testsPanel: <FileTestsPanel repoId={id} filePath={detail.file_path} />,+ docReferencesPanel: (+ <FileDocReferencesPanel repoId={id} filePath={detail.file_path} />+ ),LinkComponent: Link,});diff --git a/packages/web/src/components/files/file-doc-references-panel.tsx b/packages/web/src/components/files/file-doc-references-panel.tsxnew file mode 100644index 000000000..ab73119d0--- /dev/null+++ b/packages/web/src/components/files/file-doc-references-panel.tsx@@ -0,0 +1,30 @@+"use client";++/**+ * The Doc tab's "Documents naming this file" list, bound to web's `/api`+ * client and `/repos/:id` routing.+ *+ * Client-side for the same reason as `FileTestsPanel`: the shared list fetches,+ * and a fetcher cannot be handed to a server-rendered tab body as a prop.+ */++import { DocDriftReferences } from "@repowise-dev/ui/doc-drift";+import { docDriftHref } from "@repowise-dev/ui/dashboard/attention-href";+import { useDocDriftAdapter } from "@/components/risk/doc-drift-tab";++export function FileDocReferencesPanel({+ repoId,+ filePath,+}: {+ repoId: string;+ filePath: string;+}) {+ const adapter = useDocDriftAdapter(repoId);+ return (+ <DocDriftReferences+ target={filePath}+ adapter={adapter}+ driftHref={(document) => docDriftHref(`/repos/${repoId}`, document)}+ />+ );+}diff --git a/packages/web/src/components/risk/doc-drift-tab.tsx b/packages/web/src/components/risk/doc-drift-tab.tsxindex 857c9a34c..62207d187 100644--- a/packages/web/src/components/risk/doc-drift-tab.tsx+++ b/packages/web/src/components/risk/doc-drift-tab.tsx@@ -8,25 +8,45 @@* pieces, so web and hosted render the same view.*/+import { useMemo } from "react";import { useRouter } from "next/navigation";import { DocDriftView, type DocDriftAdapter } from "@repowise-dev/ui/doc-drift";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";import { getDocDrift, getDocDriftReferences } from "@/lib/api/doc-drift";-export function DocDriftTab({ repoId }: { repoId: string }) {+/** Web's adapter, shared by the drift tab and the file page's references list. */+export function useDocDriftAdapter(repoId: string): DocDriftAdapter {const router = useRouter();- const prefix = `/repos/${repoId}`;-- const adapter: DocDriftAdapter = {- cacheKey: repoId,- listFindings: (opts) => getDocDrift(repoId, opts),- listReferences: (target) => getDocDriftReferences(repoId, target),- // The line is dropped rather than appended: no file view renders `#L<n>`- // anchors yet, and a fragment that resolves nowhere teaches the reader- // that the link goes somewhere it does not.- documentHref: (path) => fileEntityPath(prefix, path),- navigate: (href) => router.push(href),- };+ return useMemo(() => {+ const prefix = `/repos/${repoId}`;+ return {+ cacheKey: repoId,+ listFindings: (opts) => getDocDrift(repoId, opts),+ listReferences: (target) => getDocDriftReferences(repoId, target),+ // The line is dropped rather than appended: no file view renders `#L<n>`+ // anchors yet, and a fragment that resolves nowhere teaches the reader+ // that the link goes somewhere it does not.+ documentHref: (path) => fileEntityPath(prefix, path),+ navigate: (href) => router.push(href),+ };+ }, [repoId, router]);+}- return <DocDriftView adapter={adapter} />;+export function DocDriftTab({+ repoId,+ initialDocument,+}: {+ repoId: string;+ /** From `?document=` on the code-health page. */+ initialDocument?: string | undefined;+}) {+ const adapter = useDocDriftAdapter(repoId);+ return (+ <DocDriftView+ // Remount on a new deep link: the view reads it once, as initial state.+ key={initialDocument ?? ""}+ adapter={adapter}+ initialDocument={initialDocument}+ />+ );}