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): open one finding's evidence and hand it to an agent (#2378)
Raghav Chamadiyaacb30861bc0f
diff --git a/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx b/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsxindex 0f0ed654b..7a050d443 100644--- a/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx+++ b/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx@@ -23,6 +23,9 @@ vi.stubGlobal("ResizeObserver", RO);* pick one. jsdom applies no CSS, so a cell matches in both; scope by caption.*/const TABLE = { name: /Documentation assertions/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;const BASIS ="Covers only references this detector can resolve; uncheckable ones are neither counted nor reported.";@@ -39,7 +42,11 @@ const FINDINGS: DocDriftFinding[] = [reason: "No file matches this path.",raw: "src/auth.py",context: "The resolver lives in src/auth.py.",- evidence: [],+ evidence: [+ "docs/architecture.md:42 states `src/auth.py`",+ "resolution: no-candidate",+ "under: Architecture > Resolvers",+ ],},{id: "f2",@@ -313,17 +320,94 @@ describe("DocDriftView", () => {expect(await screen.findByText("Sign in to see this")).toBeTruthy();});- it("opens the document, not the file it names", async () => {+ it("opens the detail panel rather than navigating away", async () => {+ // The row used to jump to the document's file page, which for a markdown+ // file renders an empty shell: no symbols, no edges, none of the evidence.const navigate = vi.fn();renderView(<DocDriftView adapter={makeAdapter({ navigate })} />);const table = await screen.findByRole("table", TABLE);fireEvent.click(within(table).getByText(/docs\/architecture\.md/));+ expect(await screen.findByRole("dialog", { name: PANEL })).toBeTruthy();+ expect(navigate).not.toHaveBeenCalled();+ });++ 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/));++ // The line as written, the heading trail and the resolver's trace all+ // arrive with every finding and were previously discarded.+ expect(await screen.findByText(/The resolver lives in src\/auth\.py\./)).toBeTruthy();+ expect(screen.getByText("Architecture > Resolvers")).toBeTruthy();+ expect(screen.getByText(/resolution: no-candidate/)).toBeTruthy();+ });++ 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/));++ const panel = await screen.findByRole("dialog", { name: PANEL });+ expect(within(panel).getByText(new RegExp(BASIS.slice(0, 40)))).toBeTruthy();+ });++ it("reaches the document from the panel, not from the row", async () => {+ 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(await screen.findByRole("link", { name: /Open document/i }));await waitFor(() =>expect(navigate).toHaveBeenCalledWith("/repos/repo-1/files/docs/architecture.md#L42",),);});++ it("hands one finding to an agent from its row", async () => {+ renderView(<DocDriftView adapter={makeAdapter()} />);+ const table = await screen.findByRole("table", TABLE);++ fireEvent.click(+ within(table).getByRole("button", {+ name: /Fix docs\/architecture\.md:42 with an agent/i,+ }),+ );++ expect(await screen.findByRole("dialog", { name: PROMPT })).toBeTruthy();+ // Only one: the row button stops propagation, so the row's own click+ // handler never runs and the detail panel stays shut.+ expect(screen.getAllByRole("dialog")).toHaveLength(1);+ });++ it("builds a prompt naming the document as the thing to edit", async () => {+ renderView(<DocDriftView adapter={makeAdapter()} />);+ const table = await screen.findByRole("table", TABLE);+ fireEvent.click(+ within(table).getByRole("button", {+ name: /Fix docs\/architecture\.md:42 with an agent/i,+ }),+ );++ const prompt = (await screen.findByRole("dialog", { name: PROMPT })).textContent ?? "";+ // The direction of the claim is the one thing this prompt must not invert.+ expect(prompt).toContain("`docs/architecture.md:42` claims `src/auth.py` exists");+ expect(prompt).toContain("Edit the document, not the code.");+ // And it has to leave room for a deliberate example to be correct.+ expect(prompt).toContain("Some findings are correct as written.");+ });++ it("can hand the whole slice over at once", async () => {+ renderView(<DocDriftView adapter={makeAdapter()} />);+ await screen.findByRole("table", TABLE);++ fireEvent.click(screen.getByRole("button", { name: /Fix 2 with an agent/i }));+ const prompt = (await screen.findByRole("dialog", { name: PROMPT })).textContent ?? "";+ expect(prompt).toContain("docs/architecture.md:42");+ expect(prompt).toContain("docs/cli.md:7");+ });});diff --git a/packages/ui/src/doc-drift/doc-drift-adapter.ts b/packages/ui/src/doc-drift/doc-drift-adapter.tsindex 59afd0ff4..54efc79e2 100644--- a/packages/ui/src/doc-drift/doc-drift-adapter.ts+++ b/packages/ui/src/doc-drift/doc-drift-adapter.ts@@ -47,7 +47,10 @@ export interface DocDriftAdapter {*/listReferences?(target: string): Promise<DocDriftReferencesResponse>;- /** Navigate to an href (host wires this to its router). Optional: a host- * whose document links are plain anchors does not need it. */+ /**+ * Navigate to an href (host wires this to its router). Optional: the+ * document link is a real anchor either way, so a host without a router+ * still gets a working link, just a full page load.+ */navigate?(href: string): void;}diff --git a/packages/ui/src/doc-drift/doc-drift-detail-panel.tsx b/packages/ui/src/doc-drift/doc-drift-detail-panel.tsxnew file mode 100644index 000000000..f8ff077ed--- /dev/null+++ b/packages/ui/src/doc-drift/doc-drift-detail-panel.tsx@@ -0,0 +1,189 @@+"use client";++/**+ * One drifted assertion, in full.+ *+ * The table can only carry the document, the target and a tier. Everything+ * that makes a finding *actionable* is the detail the resolver already+ * recorded and the row has no room for: the line as the document actually+ * wrote it, where in the document it sits, and what the resolver checked to+ * conclude the claim no longer holds. All of it arrives on the wire with every+ * finding; before this panel existed the tab fetched it and dropped it.+ *+ * Built on {@link AdaptivePanel}, the same primitive the health and coupling+ * drawers use, so this reads as the product's one detail surface rather than a+ * second one invented for drift.+ */++import { ExternalLink } from "lucide-react";+import {+ docDriftConfidenceTier,+ docDriftKindLabel,+ type DocDriftFinding,+} from "@repowise-dev/types/doc-drift";++import { AdaptivePanel } from "../shared/adaptive-panel";+import { AiPromptButton } from "../health/ai-prompt-button";++/** The evidence line carrying the enclosing heading trail. */+const TRAIL_PREFIX = "under: ";++const TIER_LABEL: Record<string, string> = {+ high: "Near-certain",+ medium: "Medium",+ low: "Low",+};++export interface DocDriftDetailPanelProps {+ finding: DocDriftFinding | null;+ onOpenChange: (open: boolean) => void;+ /** Link to the document itself. */+ documentHref: (path: string, line?: number) => string;+ /** Hand this one finding to an agent. */+ onPrompt: (finding: DocDriftFinding) => void;+ /** Client-side routing for the document link, when the host has a router. */+ navigate?: ((href: string) => void) | undefined;+ /** What a finding does and does not claim, from the engine. */+ basis: string;+}++export function DocDriftDetailPanel({+ finding,+ onOpenChange,+ documentHref,+ onPrompt,+ navigate,+ basis,+}: DocDriftDetailPanelProps) {+ if (!finding) {+ // AdaptivePanel needs a title even while closed; rendering nothing until+ // there is a finding keeps the closed state from inventing one.+ return null;+ }++ const tier = docDriftConfidenceTier(finding.confidence);+ const trail = finding.evidence.find((line) => line.startsWith(TRAIL_PREFIX));+ const trace = finding.evidence.filter((line) => !line.startsWith(TRAIL_PREFIX));++ return (+ <AdaptivePanel+ open+ onOpenChange={onOpenChange}+ eyebrow="Drifted assertion"+ title={`${finding.file_path}:${finding.line_number}`}+ widthClassName="md:max-w-[620px]"+ >+ <div className="flex flex-col gap-6 px-4 py-4">+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">+ <span className="text-[var(--color-text-secondary)]">+ {docDriftKindLabel(finding.kind)}+ </span>+ <span className="text-[var(--color-text-tertiary)]">·</span>+ <span+ className={+ tier === "high"+ ? "text-[var(--color-warning)]"+ : "text-[var(--color-text-secondary)]"+ }+ >+ {TIER_LABEL[tier]}{" "}+ <span className="font-mono text-[var(--color-text-tertiary)]">+ {finding.confidence.toFixed(2)}+ </span>+ </span>+ </div>++ <Section title="What this document claims">+ <p className="font-mono text-xs break-all text-[var(--color-text-primary)]">+ {finding.target}+ </p>+ <p className="mt-2 text-xs leading-relaxed text-[var(--color-text-secondary)]">+ {finding.reason}+ </p>+ </Section>++ {finding.context && (+ <Section title="The line as written">+ <pre className="overflow-x-auto rounded-md bg-[var(--color-bg-inset)] p-3 text-[11px] leading-relaxed text-[var(--color-text-primary)]">+ <code className="font-mono whitespace-pre-wrap break-all">+ {finding.context}+ </code>+ </pre>+ {finding.raw && finding.raw !== finding.context && (+ <p className="mt-2 font-mono text-[11px] break-all text-[var(--color-text-tertiary)]">+ Reference: {finding.raw}+ </p>+ )}+ </Section>+ )}++ {trail && (+ <Section title="Where in the document">+ <p className="text-xs text-[var(--color-text-secondary)]">+ {trail.slice(TRAIL_PREFIX.length)}+ </p>+ </Section>+ )}++ {trace.length > 0 && (+ <Section title="What was checked">+ <ul className="flex flex-col gap-1">+ {trace.map((line) => (+ <li+ key={line}+ className="font-mono text-[11px] break-all text-[var(--color-text-tertiary)]"+ >+ {line}+ </li>+ ))}+ </ul>+ </Section>+ )}++ {/* Beside the actions, not in a footnote: this is where someone is+ about to edit a file on the strength of the finding. */}+ <p className="text-xs leading-relaxed text-[var(--color-text-tertiary)] [text-wrap:pretty]">+ {basis}+ </p>++ <div className="flex flex-wrap items-center gap-2">+ <AiPromptButton+ onClick={() => onPrompt(finding)}+ label="Fix with an agent"+ />+ <a+ href={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));+ }}+ 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>+ </div>+ </div>+ </AdaptivePanel>+ );+}++function Section({+ title,+ children,+}: {+ title: string;+ children: React.ReactNode;+}) {+ return (+ <section className="flex flex-col gap-1.5">+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">+ {title}+ </h3>+ {children}+ </section>+ );+}diff --git a/packages/ui/src/doc-drift/doc-drift-view.tsx b/packages/ui/src/doc-drift/doc-drift-view.tsxindex 953200379..538c0a599 100644--- a/packages/ui/src/doc-drift/doc-drift-view.tsx+++ b/packages/ui/src/doc-drift/doc-drift-view.tsx@@ -29,6 +29,7 @@ import { FileCheck2 } from "lucide-react";import {DOC_DRIFT_CONFIDENCE,docDriftKindLabel,+ type DocDriftFinding,type DocDriftResponse,} from "@repowise-dev/types/doc-drift";@@ -38,9 +39,14 @@ import { EmptyState } from "../shared/empty-state";import { OverviewSection } from "../overview/section";import { toFriendlyMessage } from "../lib/errors";+import { AiPromptButton } from "../health/ai-prompt-button";+import { AiPromptModal } from "../health/ai-prompt-modal";+import { buildDocDriftAiPrompt } from "../health/ai-prompt-builder";+import { DocDriftLede } from "./doc-drift-lede";import { DriftFindingsTable } from "./drift-findings-table";import { DocDriftUnavailableState } from "./doc-drift-unavailable";+import { DocDriftDetailPanel } from "./doc-drift-detail-panel";import type { DocDriftAdapter } from "./doc-drift-adapter";/**@@ -84,6 +90,12 @@ export function DocDriftView({DOC_DRIFT_CONFIDENCE.MEDIUM,);const [kind, setKind] = useState<string>("");+ /** 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. */+ const [promptFindings, setPromptFindings] = useState<DocDriftFinding[] | null>(+ null,+ );const { data, isLoading, error, mutate } = useSWR<DocDriftResponse>(`doc-drift:${adapter.cacheKey}:${minConfidence}:${kind}`,@@ -172,13 +184,21 @@ export function DocDriftView({title="Drifted assertions"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={- <Filters- minConfidence={minConfidence}- onMinConfidence={setMinConfidence}- kind={kind}- onKind={setKind}- kinds={kinds}- />+ <div className="flex flex-wrap items-center gap-2">+ {data.findings.length > 0 && (+ <AiPromptButton+ onClick={() => setPromptFindings(data.findings)}+ label={`Fix ${data.findings.length} with an agent`}+ />+ )}+ <Filters+ minConfidence={minConfidence}+ onMinConfidence={setMinConfidence}+ kind={kind}+ onKind={setKind}+ kinds={kinds}+ />+ </div>}>{error ? (@@ -199,11 +219,43 @@ export function DocDriftView({)}<DriftFindingsTablefindings={data.findings}- documentHref={adapter.documentHref}- navigate={adapter.navigate}+ onSelect={setSelected}+ onPrompt={(finding) => setPromptFindings([finding])}+ selectedId={selected?.id ?? null}/></OverviewSection>)}++ <DocDriftDetailPanel+ finding={selected}+ onOpenChange={(open) => !open && setSelected(null)}+ documentHref={adapter.documentHref}+ onPrompt={(finding) => setPromptFindings([finding])}+ navigate={adapter.navigate}+ basis={summary.findings_basis}+ />++ <AiPromptModal+ open={promptFindings !== null}+ onOpenChange={(open) => !open && setPromptFindings(null)}+ title="Documentation fix prompt"+ description="Hand the drifted assertion, its evidence and the constraints to an agent."+ filePath={+ promptFindings?.length === 1+ ? `${promptFindings[0]!.file_path}:${promptFindings[0]!.line_number}`+ : null+ }+ getPrompt={+ promptFindings+ ? (flavor) =>+ buildDocDriftAiPrompt({+ findings: promptFindings,+ flavor,+ basis: summary.findings_basis,+ })+ : null+ }+ /></div>);}diff --git a/packages/ui/src/doc-drift/drift-findings-table.tsx b/packages/ui/src/doc-drift/drift-findings-table.tsxindex 5f292f6cb..e7525549b 100644--- a/packages/ui/src/doc-drift/drift-findings-table.tsx+++ b/packages/ui/src/doc-drift/drift-findings-table.tsx@@ -8,6 +8,10 @@* think it does not. The document leads because it is the file the reader* opens; putting the target first would read as a list of broken code files,* which is the opposite of what a finding says.+ *+ * 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.*/import { FileText } from "lucide-react";@@ -22,12 +26,16 @@ import {type ResponsiveColumn,} from "../shared/responsive-table";import { EmptyState } from "../shared/empty-state";+import { AiPromptButton } from "../health/ai-prompt-button";export interface DriftFindingsTableProps {findings: DocDriftFinding[];- /** Where a document link goes; the row is clickable when given. */- documentHref: (path: string, line?: number) => string;- navigate?: ((href: string) => void) | undefined;+ /** Open one finding's detail. The row is clickable when given. */+ onSelect: (finding: DocDriftFinding) => void;+ /** Hand one finding to an agent, from the row itself. */+ onPrompt: (finding: DocDriftFinding) => void;+ /** Which row the open panel is describing. */+ selectedId?: string | null | undefined;}/**@@ -49,13 +57,10 @@ const TIER_LABEL: Record<string, string> = {export function DriftFindingsTable({findings,- documentHref,- navigate,+ onSelect,+ onPrompt,+ selectedId,}: DriftFindingsTableProps) {- const open = (finding: DocDriftFinding) => {- navigate?.(documentHref(finding.file_path, finding.line_number));- };-const columns: ResponsiveColumn<DocDriftFinding>[] = [{key: "document",@@ -127,6 +132,22 @@ export function DriftFindingsTable({);},},+ {+ key: "actions",+ header: "",+ align: "right",+ priority: 1,+ cellClassName: "whitespace-nowrap",+ // The button stops its own propagation, so it is safe inside a row that+ // also opens the panel.+ render: (f) => (+ <AiPromptButton+ variant="icon"+ onClick={() => onPrompt(f)}+ label={`Fix ${f.file_path}:${f.line_number} with an agent`}+ />+ ),+ },];return (@@ -136,12 +157,9 @@ export function DriftFindingsTable({rowKey={(f) => f.id}stacked="md"caption="Documentation assertions the repository no longer satisfies"- {...(navigate- ? {- onRowClick: open,- rowClassName: () => "cursor-pointer",- }- : {})}+ onRowClick={onSelect}+ rowClassName={() => "cursor-pointer"}+ selectedKey={selectedId ?? null}empty={<EmptyStateicon={<FileText className="h-6 w-6" />}diff --git a/packages/ui/src/doc-drift/index.ts b/packages/ui/src/doc-drift/index.tsindex 2344ab652..e20a3f860 100644--- a/packages/ui/src/doc-drift/index.ts+++ b/packages/ui/src/doc-drift/index.ts@@ -1,4 +1,5 @@export * from "./doc-drift-adapter";+export * from "./doc-drift-detail-panel";export * from "./doc-drift-lede";export * from "./doc-drift-unavailable";export * from "./doc-drift-view";diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.tsindex 45567bb82..e32ba6316 100644--- a/packages/ui/src/health/ai-prompt-builder.ts+++ b/packages/ui/src/health/ai-prompt-builder.ts@@ -730,6 +730,136 @@ export function buildDeadCodeAiPrompt({.join("\n");}+// ─────────────────────────────────────────────────────────────────────+// Documentation drift prompt (per finding, or a whole slice)+// ─────────────────────────────────────────────────────────────────────++export interface DocDriftPromptFinding {+ /** The DOCUMENT carrying the assertion. Never the file it names. */+ file_path: string;+ line_number: number;+ /** What the document claims exists. */+ target: string;+ kind?: string | null;+ confidence?: number | null;+ reason?: string | null;+ /** The source line as written, which is what the agent has to edit. */+ context?: string | null;+ /** The reference exactly as the document wrote it. */+ raw?: string | null;+ /** The resolver's trace, including the enclosing heading trail. */+ evidence?: string[] | null;+}++export interface BuildDocDriftPromptOptions {+ findings: DocDriftPromptFinding[];+ flavor?: AiPromptFlavor;+ repoName?: string;+ /** What the counts do and do not cover, from the engine. */+ basis?: string | null;+}++/** Cap the list so a large pile does not produce a giant prompt. */+const MAX_DOC_DRIFT_FINDINGS = 20;++/**+ * Ask an agent to repair documentation whose assertions no longer hold.+ *+ * The one thing this prompt must get right is the direction of the claim. A+ * drift finding is filed against the *document*, and the target is what that+ * document claims exists — an agent that reads it the other way round goes off+ * and "restores" a file the repository deliberately removed. Every section+ * here names the document as the thing to edit.+ *+ * It also has to leave room for the finding to be wrong. Some of them are+ * correct-by-design: a contributor guide teaching you to add a file names one+ * that was never meant to exist, and deleting that line would damage the guide.+ * The flavor preamble already says "leads, not ground truth"; the constraints+ * say what that means for prose specifically.+ */+export function buildDocDriftAiPrompt({+ findings,+ flavor = "generic",+ repoName,+ basis,+}: BuildDocDriftPromptOptions): string {+ const repoLine = repoName ? ` (\`${repoName}\`)` : "";+ const shown = findings.slice(0, MAX_DOC_DRIFT_FINDINGS);+ const hidden = findings.length - shown.length;+ const documents = new Set(findings.map((f) => f.file_path)).size;++ const findingBlock = shown+ .map((f) => {+ // The heading trail the resolver recorded, which is how a reader finds+ // the passage in a long document. Split out of the evidence lines so it+ // can be labelled rather than dumped as trace.+ const trail = (f.evidence ?? []).find((line) => line.startsWith("under: "));+ const trace = (f.evidence ?? []).filter((line) => !line.startsWith("under: "));+ return [+ `- \`${f.file_path}:${f.line_number}\` claims \`${f.target}\` exists`,+ f.reason ? ` - Why flagged: ${f.reason}` : null,+ f.context ? ` - The line as written: \`${f.context.trim()}\`` : null,+ f.raw && f.raw !== f.context ? ` - The reference itself: \`${f.raw}\`` : null,+ trail ? ` - Section: ${trail.slice("under: ".length)}` : null,+ trace.length ? ` - Checked: ${trace.join("; ")}` : null,+ f.confidence != null ? ` - Confidence: ${f.confidence.toFixed(2)}` : null,+ ]+ .filter(Boolean)+ .join("\n");+ })+ .join("\n");++ const hiddenLine =+ hidden > 0+ ? `…and ${hidden} more finding${hidden === 1 ? "" : "s"} in the same slice (open the Doc drift tab in repowise for the full list).`+ : null;++ const constraintList = [+ "**Edit the document, not the code.** Each entry names a document that makes a claim the repository no longer satisfies. The fix is almost always to correct the prose, the path or the link — not to recreate the file it names.",+ "**Find out what replaced the target before you touch the line.** A path that no longer resolves usually moved or was renamed; point the document at the new location rather than deleting the sentence around it.",+ "**Some findings are correct as written.** A guide that teaches the reader to add a file names one that was never meant to exist, and an example path inside a tutorial is not drift. If a line is doing its job, leave it and say so.",+ "**Do not touch a changelog or release note.** Those describe the repository as it was at a release; a reference that no longer resolves is the document doing its job.",+ "**Keep the surrounding prose true.** Fixing a link that sits inside a sentence about how something works means checking that the sentence is still accurate, not just that the path resolves.",+ ];++ const completionContract = [+ "1. The edits themselves, one document at a time.",+ "2. For each, what the target became and how you confirmed it (the file you found, the heading you matched).",+ "3. A list of any findings you left alone, with the reason the line is correct as written.",+ ];++ return [+ FLAVOR_PREAMBLE[flavor],+ "",+ `## Documentation drift${repoLine}`,+ "",+ bulletList([+ `Findings: **${findings.length}** across **${documents}** document${documents === 1 ? "" : "s"}`,+ "Each one is an assertion a document makes that the repository no longer satisfies.",+ basis ?? null,+ ]),+ "",+ "## Findings",+ "",+ findingBlock,+ hiddenLine ?? "",+ "",+ "## Hard constraints",+ "",+ bulletList(constraintList),+ "",+ "## What I expect back",+ "",+ completionContract.join("\n"),+ "",+ flavor === "claude-code-mcp"+ ? "For each target, call `get_context([\"<target>\"])` to find where it lives now — repowise already indexed the tree, so use it instead of globbing for a renamed path. `get_why(...)` on a target that is genuinely gone will often name the change that removed it, which is what the document should now say."+ : "For each target, search the repository for the file or heading it names before editing — most of these moved rather than disappeared, and the document should point at where they went.",+ ]+ .filter((s) => s !== "")+ .join("\n");+}+// ─────────────────────────────────────────────────────────────────────// Coupling decouple prompt (per co-change pair)// ─────────────────────────────────────────────────────────────────────