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
fix(vscode): relocate doc drift diagnostics on live document edits (#2668) (#2782)
Rishabh Mishrac01fec9fce3d
diff --git a/packages/vscode/src/features/docDriftDiagnostics.ts b/packages/vscode/src/features/docDriftDiagnostics.tsindex a90de7cf3..6e357f127 100644--- a/packages/vscode/src/features/docDriftDiagnostics.ts+++ b/packages/vscode/src/features/docDriftDiagnostics.ts@@ -7,26 +7,55 @@ import { registerEditorDiagnostics } from "./editorDiagnostics";const CONFIG_PREFIX = `${CONFIG_SECTION}.docDrift`;const MARKDOWN_EXT = /\.(md|mdx|markdown)$/i;+import {+ clearDocDriftLocations,+ lastKnownLines,+ locateReference,+ pruneDocDriftLocations,+ type LocatedReference,+} from "./locateReference";++export {+ clearDocDriftLocations,+ lastKnownLines,+ locateReference,+ pruneDocDriftLocations,+ type LocatedReference,+};function isMarkdown(doc: vscode.TextDocument): boolean {return doc.languageId === "markdown" || MARKDOWN_EXT.test(doc.uri.path);}-/** The finding's line, narrowed to the reference as written (else the target). */-function rangeFor(doc: vscode.TextDocument, f: DocDriftFinding): vscode.Range {- const line = Math.min(Math.max(0, f.line_number - 1), doc.lineCount - 1);- const text = doc.lineAt(line).text;- for (const needle of [f.raw, f.target]) {- const at = needle ? text.indexOf(needle) : -1;- if (at >= 0) return new vscode.Range(line, at, line, at + needle.length);++/** The finding's line, narrowed to the reference as written (else the target), relocated in live buffer. */+export function rangeFor(doc: vscode.TextDocument, f: DocDriftFinding): vscode.Range | null {+ if (doc.lineCount === 0) return null;+ const lines: string[] = [];+ for (let i = 0; i < doc.lineCount; i++) {+ lines.push(doc.lineAt(i).text);+ }+ const recordedLine = Math.max(0, f.line_number - 1);+ const key = `${doc.uri.toString()}::${f.id}`;+ const startLine = lastKnownLines.get(key) ?? recordedLine;+ let loc = locateReference(lines, f.raw, f.target, startLine);+ if (!loc && startLine !== recordedLine) {+ loc = locateReference(lines, f.raw, f.target, recordedLine);}- return new vscode.Range(line, 0, line, text.length);+ if (!loc) {+ lastKnownLines.delete(key);+ return null;+ }+ lastKnownLines.set(key, loc.line);+ return new vscode.Range(loc.line, loc.start, loc.line, loc.end);}-function toDiagnostic(doc: vscode.TextDocument, f: DocDriftFinding): vscode.Diagnostic {+export function toDiagnostic(doc: vscode.TextDocument, f: DocDriftFinding): vscode.Diagnostic | null {+ const range = rangeFor(doc, f);+ if (!range) return null;const message = f.suggestion ? `${f.reason} Likely now: ${f.suggestion}.` : f.reason;const diagnostic = new vscode.Diagnostic(- rangeFor(doc, f),+ range,message,f.confidence >= DOC_DRIFT_CONFIDENCE.HIGH? vscode.DiagnosticSeverity.Warning@@ -49,6 +78,7 @@ export function registerDocDriftDiagnostics(ctx: RepowiseContext): vscode.DisposconfigPrefix: CONFIG_PREFIX,enabled: () => cfg().get<boolean>("diagnostics.enabled", true),accept: isMarkdown,+ recomputeOnEdit: true,load: (c, rel) =>getDocDriftFindings(c,@@ -58,5 +88,8 @@ export function registerDocDriftDiagnostics(ctx: RepowiseContext): vscode.Dispos// Keyed on what the diagnostic renders from.signature: (f) => `${f.id}:${f.line_number}:${f.confidence}:${f.suggestion ?? ""}`,toDiagnostic,+ onPublish: (doc, items) => pruneDocDriftLocations(doc.uri, items),+ onDropDocument: (uri) => clearDocDriftLocations(uri),});}+diff --git a/packages/vscode/src/features/editorDiagnostics.ts b/packages/vscode/src/features/editorDiagnostics.tsindex 88572dfd1..979a305b0 100644--- a/packages/vscode/src/features/editorDiagnostics.ts+++ b/packages/vscode/src/features/editorDiagnostics.ts@@ -2,6 +2,8 @@ import * as vscode from "vscode";import type { RepowiseContext } from "../core/context";import { repoRelativePath } from "../core/fileSignals";+const EDIT_DEBOUNCE_MS = 300;+/** One Problems-panel feature, as a configuration of the shared lifecycle. */export interface EditorDiagnosticsSpec<T> {/** Diagnostic collection name. */@@ -15,7 +17,13 @@ export interface EditorDiagnosticsSpec<T> {load(ctx: RepowiseContext, rel: string): Promise<T[]>;/** Per-item key; a file is republished only when its sorted set changes. */signature(item: T): string;- toDiagnostic(doc: vscode.TextDocument, item: T): vscode.Diagnostic;+ toDiagnostic(doc: vscode.TextDocument, item: T): vscode.Diagnostic | null | undefined;+ /** When true, recomputes diagnostic ranges on document edits without refetching. */+ recomputeOnEdit?: boolean;+ /** Invoked when items are published for a document (e.g. to synchronize finding positions). */+ onPublish?(doc: vscode.TextDocument, items: T[]): void;+ /** Invoked when a document's diagnostics are dropped or cleared. */+ onDropDocument?(uri: vscode.Uri): void;}/**@@ -32,6 +40,10 @@ export function registerEditorDiagnostics<T>(/** Last published item-set signature per document URI, for diff-only set. */const signatures = new Map<string, string>();+ /** Cached items per document URI for recomputation on edit. */+ const cachedItems = new Map<string, T[]>();+ /** Active debounce timers per document URI. */+ const editTimers = new Map<string, ReturnType<typeof setTimeout>>();/** Lazily created freshness subscription, so activate() does no watching. */let watcherSub: vscode.Disposable | null = null;/** Bumped per refresh run; a run that sees a newer value stops publishing. */@@ -41,16 +53,48 @@ export function registerEditorDiagnostics<T>(spec.enabled() && ctx.getExtensionState() === "ready" && !!ctx.repoId;function clearAll(): void {+ if (spec.onDropDocument) {+ for (const uriKey of cachedItems.keys()) {+ try {+ spec.onDropDocument(vscode.Uri.parse(uriKey));+ } catch {+ // ignore+ }+ }+ }collection.clear();signatures.clear();+ cachedItems.clear();+ for (const timer of editTimers.values()) {+ clearTimeout(timer);+ }+ editTimers.clear();}- function publish(doc: vscode.TextDocument, items: T[]): void {- const signature = items.map(spec.signature).sort().join("|");+ function publish(doc: vscode.TextDocument, items: T[], force = false): void {const uriKey = doc.uri.toString();- if (signatures.get(uriKey) === signature) return;- signatures.set(uriKey, signature);- collection.set(doc.uri, items.map((item) => spec.toDiagnostic(doc, item)));+ if (!force) {+ const pendingTimer = editTimers.get(uriKey);+ if (pendingTimer) {+ clearTimeout(pendingTimer);+ editTimers.delete(uriKey);+ }+ }+ cachedItems.set(uriKey, items);++ if (!force) {+ const signature = items.map(spec.signature).sort().join("|");+ if (signatures.get(uriKey) === signature) return;+ signatures.set(uriKey, signature);+ }++ const diagnostics: vscode.Diagnostic[] = [];+ for (const item of items) {+ const d = spec.toDiagnostic(doc, item);+ if (d) diagnostics.push(d);+ }+ collection.set(doc.uri, diagnostics);+ spec.onPublish?.(doc, items);}async function refreshAll(): Promise<void> {@@ -75,10 +119,19 @@ export function registerEditorDiagnostics<T>(}// Drop entries for documents that are no longer visible.- for (const uriKey of [...signatures.keys()]) {+ const trackedKeys = new Set([...signatures.keys(), ...cachedItems.keys()]);+ for (const uriKey of trackedKeys) {if (!visible.has(uriKey)) {- collection.delete(vscode.Uri.parse(uriKey));+ const uri = vscode.Uri.parse(uriKey);+ collection.delete(uri);signatures.delete(uriKey);+ cachedItems.delete(uriKey);+ const timer = editTimers.get(uriKey);+ if (timer) {+ clearTimeout(timer);+ editTimers.delete(uriKey);+ }+ spec.onDropDocument?.(uri);}}}@@ -97,6 +150,35 @@ export function registerEditorDiagnostics<T>(disposables.push(watcherSub);}+ if (spec.recomputeOnEdit) {+ disposables.push(+ vscode.workspace.onDidChangeTextDocument((event) => {+ if (!active()) return;+ const doc = event.document;+ if (spec.accept && !spec.accept(doc)) return;+ const isVisible = vscode.window.visibleTextEditors.some(+ (e) => e.document.uri.toString() === doc.uri.toString(),+ );+ if (!isVisible) return;+ const uriKey = doc.uri.toString();+ if (!cachedItems.has(uriKey)) return;++ const existing = editTimers.get(uriKey);+ if (existing) clearTimeout(existing);++ const currentGen = generation;+ const timer = setTimeout(() => {+ editTimers.delete(uriKey);+ if (!active() || generation !== currentGen) return;+ const currentItems = cachedItems.get(uriKey);+ if (!currentItems) return;+ publish(doc, currentItems, true);+ }, EDIT_DEBOUNCE_MS);+ editTimers.set(uriKey, timer);+ }),+ );+ }+disposables.push(ctx.onDidChangeExtensionState((state) => {if (state === "ready") {@@ -118,5 +200,11 @@ export function registerEditorDiagnostics<T>(}// Reads the array at dispose time, so the lazily pushed watcher is included.- return new vscode.Disposable(() => disposables.forEach((d) => d.dispose()));+ return new vscode.Disposable(() => {+ for (const timer of editTimers.values()) {+ clearTimeout(timer);+ }+ editTimers.clear();+ disposables.forEach((d) => d.dispose());+ });}diff --git a/packages/vscode/src/features/locateReference.ts b/packages/vscode/src/features/locateReference.tsnew file mode 100644index 000000000..0fb2e5b66--- /dev/null+++ b/packages/vscode/src/features/locateReference.ts@@ -0,0 +1,88 @@+import * as vscode from "vscode";++const SEARCH_WINDOW_LINES = 20;++export interface LocatedReference {+ line: number;+ start: number;+ end: number;+}++export interface FindingWithId {+ id: string;+}++/** Tracks the last resolved 0-based line for findings across live document edits. */+export const lastKnownLines = new Map<string, number>();++/** Clears cached line locations for a document URI, or all documents if omitted. */+export function clearDocDriftLocations(uri?: vscode.Uri): void {+ if (!uri) {+ lastKnownLines.clear();+ return;+ }+ const prefix = `${uri.toString()}::`;+ for (const key of lastKnownLines.keys()) {+ if (key.startsWith(prefix)) {+ lastKnownLines.delete(key);+ }+ }+}++/** Prunes cached line locations for findings that no longer exist for the given document URI. */+export function pruneDocDriftLocations(+ uri: vscode.Uri,+ currentFindings: readonly FindingWithId[],+): void {+ const prefix = `${uri.toString()}::`;+ const validKeys = new Set(currentFindings.map((f) => `${prefix}${f.id}`));+ for (const key of lastKnownLines.keys()) {+ if (key.startsWith(prefix) && !validKeys.has(key)) {+ lastKnownLines.delete(key);+ }+ }+}++/**+ * Searches for `raw` (then `target`) on the recorded `line` (0-based) first, then on the+ * nearest line within ±20 lines, preferring the closest match and the line above on a tie.+ * Returns null if no match is found within the window.+ */+export function locateReference(+ lines: string[],+ raw: string | null | undefined,+ target: string | null | undefined,+ line: number,+): LocatedReference | null {+ if (lines.length === 0) return null;+ const clampedLine = Math.min(Math.max(0, line), lines.length - 1);+ const needles = [raw, target].filter((n): n is string => Boolean(n && n.length > 0));+ if (needles.length === 0) return null;++ function findOnLine(lineIdx: number): LocatedReference | null {+ if (lineIdx < 0 || lineIdx >= lines.length) return null;+ const text = lines[lineIdx];+ if (text == null) return null;+ for (const needle of needles) {+ const at = text.indexOf(needle);+ if (at >= 0) {+ return { line: lineIdx, start: at, end: at + needle.length };+ }+ }+ return null;+ }++ // 1. Check recorded line (distance 0)+ const exact = findOnLine(clampedLine);+ if (exact) return exact;++ // 2. Search outward up to ±20 lines: closest match, line above on a tie+ for (let d = 1; d <= SEARCH_WINDOW_LINES; d++) {+ const above = findOnLine(clampedLine - d);+ if (above) return above;+ const below = findOnLine(clampedLine + d);+ if (below) return below;+ }++ return null;+}diff --git a/packages/vscode/src/test/extension.test.ts b/packages/vscode/src/test/extension.test.tsindex 18040731e..09eb75c36 100644--- a/packages/vscode/src/test/extension.test.ts+++ b/packages/vscode/src/test/extension.test.ts@@ -1,6 +1,12 @@import * as assert from "node:assert";import * as vscode from "vscode";import { Commands, EXTENSION_ID } from "../constants";+import {+ clearDocDriftLocations,+ lastKnownLines,+ locateReference,+ pruneDocDriftLocations,+} from "../features/locateReference";/*** Fast, offline smoke suite. It runs inside a real VS Code process against an@@ -89,3 +95,160 @@ describe("Repowise extension", () => {await vscode.commands.executeCommand(Commands.showLog);});});++describe("locateReference", () => {+ it("finds reference on the recorded line", () => {+ const lines = ["# Intro", "See [guide](docs/guide.md) for details.", "End"];+ const res = locateReference(lines, "docs/guide.md", "docs/guide.md", 1);+ assert.deepStrictEqual(res, { line: 1, start: 12, end: 25 });+ });++ it("finds reference after lines were inserted above", () => {+ const lines = [+ "# Title",+ "Extra line 1",+ "Extra line 2",+ "See [guide](docs/guide.md).",+ ];+ // Recorded line 1 before insertion, now at line 3 (+2 lines shifted)+ const res = locateReference(lines, "docs/guide.md", "docs/guide.md", 1);+ assert.deepStrictEqual(res, { line: 3, start: 12, end: 25 });+ });++ it("finds reference after lines were deleted above", () => {+ const lines = ["See [guide](docs/guide.md).", "Next line"];+ // Recorded line 3 before deletion, now at line 0 (-3 lines shifted)+ const res = locateReference(lines, "docs/guide.md", "docs/guide.md", 3);+ assert.deepStrictEqual(res, { line: 0, start: 12, end: 25 });+ });++ it("prefers the nearest match when multiple matches exist", () => {+ // Match at line 3 (distance 2 from recorded line 5) vs match at line 6 (distance 1 from recorded line 5)+ const lines = [+ "line 0",+ "line 1",+ "line 2",+ "docs/guide.md far",+ "line 4",+ "recorded line 5",+ "docs/guide.md near",+ ];+ const res = locateReference(lines, "docs/guide.md", "docs/guide.md", 5);+ assert.strictEqual(res?.line, 6);+ });++ it("prefers the line above on a distance tie", () => {+ // Matches at line 4 (distance 1 above) and line 6 (distance 1 below)+ const lines = [+ "line 0",+ "line 1",+ "line 2",+ "line 3",+ "docs/guide.md above",+ "recorded line 5",+ "docs/guide.md below",+ ];+ const res = locateReference(lines, "docs/guide.md", "docs/guide.md", 5);+ assert.strictEqual(res?.line, 4);+ });++ it("returns null when not found within the search window", () => {+ // Missing completely+ assert.strictEqual(+ locateReference(["line 1", "line 2"], "docs/missing.md", "docs/missing.md", 0),+ null,+ );++ // Farther than ±20 lines away (e.g. at line 35 when recorded line is 5)+ const lines = new Array(50).fill("blank");+ lines[35] = "See docs/guide.md";+ assert.strictEqual(+ locateReference(lines, "docs/guide.md", "docs/guide.md", 5),+ null,+ );+ });++ it("falls back to target when raw is missing or not present", () => {+ const lines = ["Refer to docs/new_guide.md for info."];+ // raw does not match text, but target does+ const res = locateReference(+ lines,+ "docs/old_guide.md",+ "docs/new_guide.md",+ 0,+ );+ assert.deepStrictEqual(res, { line: 0, start: 9, end: 26 });++ // raw is empty string+ const resEmptyRaw = locateReference(lines, "", "docs/new_guide.md", 0);+ assert.deepStrictEqual(resEmptyRaw, { line: 0, start: 9, end: 26 });+ });++ it("tracks reference location when searching from updated position across large cumulative inserts", () => {+ // Initial state: recorded line 5+ const lines = new Array(50).fill("line");+ lines[5] = "See docs/guide.md";++ const initial = locateReference(lines, "docs/guide.md", "docs/guide.md", 5);+ assert.strictEqual(initial?.line, 5);++ // First edit: insert 15 lines above (shifted from 5 to 20)+ lines.splice(0, 0, ...new Array(15).fill("inserted line"));+ const firstShift = locateReference(lines, "docs/guide.md", "docs/guide.md", initial!.line);+ assert.strictEqual(firstShift?.line, 20);++ // Second edit: insert another 15 lines above (shifted from 20 to 35, cumulative shift +30 > 20)+ lines.splice(0, 0, ...new Array(15).fill("more lines"));+ // Searching from original recorded line 5 would return null:+ assert.strictEqual(locateReference(lines, "docs/guide.md", "docs/guide.md", 5), null);+ // But searching from the last known line (20) successfully relocates to line 35:+ const secondShift = locateReference(lines, "docs/guide.md", "docs/guide.md", firstShift!.line);+ assert.strictEqual(secondShift?.line, 35);+ });+});++describe("docDriftDiagnostics locations", () => {+ const uri1 = vscode.Uri.file("/workspace/doc1.md");+ const uri2 = vscode.Uri.file("/workspace/doc2.md");++ beforeEach(() => {+ lastKnownLines.clear();+ });++ it("clears document location entries on document drop or closure", () => {+ lastKnownLines.set(`${uri1.toString()}::f1`, 10);+ lastKnownLines.set(`${uri1.toString()}::f2`, 25);+ lastKnownLines.set(`${uri2.toString()}::f3`, 40);++ clearDocDriftLocations(uri1);++ assert.strictEqual(lastKnownLines.has(`${uri1.toString()}::f1`), false);+ assert.strictEqual(lastKnownLines.has(`${uri1.toString()}::f2`), false);+ assert.strictEqual(lastKnownLines.get(`${uri2.toString()}::f3`), 40);+ });++ it("clears all document locations when uri is omitted", () => {+ lastKnownLines.set(`${uri1.toString()}::f1`, 10);+ lastKnownLines.set(`${uri2.toString()}::f3`, 40);++ clearDocDriftLocations();+ assert.strictEqual(lastKnownLines.size, 0);+ });++ it("prunes location entries for findings that are removed", () => {+ lastKnownLines.set(`${uri1.toString()}::f1`, 10);+ lastKnownLines.set(`${uri1.toString()}::f2`, 25);+ lastKnownLines.set(`${uri2.toString()}::f3`, 40);++ // uri1 now only has finding f2+ pruneDocDriftLocations(uri1, [+ { id: "f2", line_number: 26, confidence: 0.9, kind: "drift", reason: "r", raw: "x", target: "y" } as any,+ ]);++ assert.strictEqual(lastKnownLines.has(`${uri1.toString()}::f1`), false);+ assert.strictEqual(lastKnownLines.get(`${uri1.toString()}::f2`), 25);+ assert.strictEqual(lastKnownLines.get(`${uri2.toString()}::f3`), 40);+ });+});++