Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: add lint link repair suggestions

nash_su25df6628a79a
diff --git a/src/components/lint/lint-view.tsx b/src/components/lint/lint-view.tsx
index 5956e525..f2d04c33 100644
--- a/src/components/lint/lint-view.tsx
+++ b/src/components/lint/lint-view.tsx
@@ -10,6 +10,7 @@ import {
BrainCircuit,
Wrench,
Trash2,
+ Link,
} from "lucide-react"
import { Button } from "@/components/ui/button"
import { useWikiStore } from "@/stores/wiki-store"
@@ -19,6 +20,11 @@ import { runStructuralLint, runSemanticLint } from "@/lib/lint"
import { hasUsableLlm } from "@/lib/has-usable-llm"
import { readFile, writeFile, listDirectory } from "@/commands/fs"
import { normalizePath } from "@/lib/path-utils"
+import {
+ appendWikilink,
+ ensureBrokenLinkStub,
+ rewriteWikilinkTarget,
+} from "@/lib/lint-fixes"
import { useTranslation } from "react-i18next"
export function groupLintResultsForDisplay(results: readonly LintItem[]): {
@@ -69,11 +75,13 @@ export function LintView() {
const [hasRun, setHasRun] = useState(false)
const [runSemantic, setRunSemantic] = useState(false)
const [fixingId, setFixingId] = useState<string | null>(null)
+ const [fixError, setFixError] = useState<string | null>(null)
const handleRunLint = useCallback(async () => {
if (!project || running) return
const pp = normalizePath(project.path)
setRunning(true)
+ setFixError(null)
clearLintItems()
try {
const structural = await runStructuralLint(pp)
@@ -119,56 +127,74 @@ export function LintView() {
if (!project) return
const pp = normalizePath(project.path)
setFixingId(item.id)
+ setFixError(null)
try {
switch (item.type) {
case "orphan": {
- // Add a link to this page from index.md
- const indexPath = `${pp}/wiki/index.md`
- let indexContent = ""
- try { indexContent = await readFile(indexPath) } catch { indexContent = "# Wiki Index\n" }
-
- const pageName = item.page.replace(".md", "").replace(/^.*\//, "")
- const entry = `- [[${pageName}]]`
- if (!indexContent.includes(entry)) {
- indexContent = indexContent.trimEnd() + "\n" + entry + "\n"
- await writeFile(indexPath, indexContent)
+ if (item.suggestedSource) {
+ const sourcePath = `${pp}/wiki/${item.suggestedSource}`
+ const content = await readFile(sourcePath)
+ await writeFile(sourcePath, appendWikilink(content, item.page))
+ } else {
+ useReviewStore.getState().addItem({
+ type: "suggestion",
+ title: t("lint.addCrossRefs", { page: item.page }),
+ description: item.detail,
+ affectedPages: [item.page],
+ options: [
+ { label: t("lint.openEdit"), action: `open:${item.page}` },
+ { label: t("lint.skip"), action: "Skip" },
+ ],
+ })
}
- // Remove from store
useLintStore.getState().removeItem(item.id)
break
}
case "broken-link": {
- // Option: remove the broken link from the page, or send to Review for manual fix
const pagePath = `${pp}/wiki/${item.page}`
- useReviewStore.getState().addItem({
- type: "confirm",
- title: t("lint.fixBrokenLink", { page: item.page }),
- description: item.detail,
- affectedPages: [item.page],
- options: [
- { label: t("lint.openEdit"), action: `open:${item.page}` },
- { label: t("lint.deletePage"), action: `delete:${pagePath}` },
- { label: t("lint.skip"), action: "Skip" },
- ],
- })
+ if (item.brokenTarget && item.suggestedTarget) {
+ const content = await readFile(pagePath)
+ await writeFile(pagePath, rewriteWikilinkTarget(content, item.brokenTarget, item.suggestedTarget))
+ } else if (item.brokenTarget) {
+ const content = await readFile(pagePath)
+ const stub = await ensureBrokenLinkStub(pp, item.brokenTarget)
+ await writeFile(pagePath, rewriteWikilinkTarget(content, item.brokenTarget, stub.relativePath))
+ } else {
+ useReviewStore.getState().addItem({
+ type: "confirm",
+ title: t("lint.fixBrokenLink", { page: item.page }),
+ description: item.detail,
+ affectedPages: [item.page],
+ options: [
+ { label: t("lint.openEdit"), action: `open:${item.page}` },
+ { label: t("lint.deletePage"), action: `delete:${pagePath}` },
+ { label: t("lint.skip"), action: "Skip" },
+ ],
+ })
+ }
useLintStore.getState().removeItem(item.id)
break
}
case "no-outlinks": {
- // Send to Review — user should add links manually
- useReviewStore.getState().addItem({
- type: "suggestion",
- title: t("lint.addCrossRefs", { page: item.page }),
- description: t("lint.addCrossRefsDescription"),
- affectedPages: [item.page],
- options: [
- { label: t("lint.openEdit"), action: `open:${item.page}` },
- { label: t("lint.skip"), action: "Skip" },
- ],
- })
+ if (item.suggestedTarget) {
+ const pagePath = `${pp}/wiki/${item.page}`
+ const content = await readFile(pagePath)
+ await writeFile(pagePath, appendWikilink(content, item.suggestedTarget))
+ } else {
+ useReviewStore.getState().addItem({
+ type: "suggestion",
+ title: t("lint.addCrossRefs", { page: item.page }),
+ description: t("lint.addCrossRefsDescription"),
+ affectedPages: [item.page],
+ options: [
+ { label: t("lint.openEdit"), action: `open:${item.page}` },
+ { label: t("lint.skip"), action: "Skip" },
+ ],
+ })
+ }
useLintStore.getState().removeItem(item.id)
break
}
@@ -196,6 +222,7 @@ export function LintView() {
bumpDataVersion()
} catch (err) {
console.error("Fix failed:", err)
+ setFixError(err instanceof Error ? err.message : String(err))
} finally {
setFixingId(null)
}
@@ -267,6 +294,11 @@ export function LintView() {
</div>
<div className="flex-1 overflow-y-auto">
+ {fixError && (
+ <div className="mx-3 mt-3 rounded-md border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs text-destructive">
+ {t("lint.fixFailed", { error: fixError })}
+ </div>
+ )}
{!showResults ? (
<div className="flex flex-col items-center justify-center gap-2 p-8 text-center text-sm text-muted-foreground">
<CheckCircle2 className="h-8 w-8 text-muted-foreground/30" />
@@ -375,6 +407,21 @@ function LintCard({
<p className="mb-2 text-xs text-muted-foreground">{item.detail}</p>
+ {(item.suggestedTarget || item.suggestedSource) && (
+ <div className="mb-2 rounded-md border border-emerald-500/20 bg-emerald-500/5 px-2 py-1.5 text-xs text-emerald-700 dark:text-emerald-300">
+ <div className="flex items-start gap-1.5">
+ <Link className="mt-0.5 h-3 w-3 shrink-0" />
+ <div className="min-w-0">
+ <div className="font-medium">
+ {item.suggestedSource
+ ? t("lint.suggestedSource", { page: item.suggestedSource })
+ : t("lint.suggestedTarget", { page: item.suggestedTarget })}
+ </div>
+ </div>
+ </div>
+ </div>
+ )}
+
{item.affectedPages && item.affectedPages.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1">
{item.affectedPages.map((page) => (
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 77e4cebf..eacf6f51 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -170,6 +170,7 @@
"open": "Open",
"fixing": "Fixing...",
"fix": "Fix",
+ "fixFailed": "Fix failed: {{error}}",
"delete": "Delete",
"openEdit": "Open & Edit",
"skip": "Skip",
@@ -177,6 +178,8 @@
"fixBrokenLink": "Fix broken link in {{page}}",
"addCrossRefs": "Add cross-references to {{page}}",
"addCrossRefsDescription": "This page has no outbound [[wikilinks]]. Consider adding cross-references to related entities and concepts.",
+ "suggestedTarget": "Suggested target: {{page}}",
+ "suggestedSource": "Suggested source: {{page}}",
"deleteOrphanConfirm": "Delete orphan page \"{{page}}\"?",
"typeLabels": {
"orphan": "Orphan Page",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 898ef5f8..192628b7 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -170,6 +170,7 @@
"open": "打开",
"fixing": "修复中...",
"fix": "修复",
+ "fixFailed": "修复失败:{{error}}",
"delete": "删除",
"openEdit": "打开编辑",
"skip": "跳过",
@@ -177,6 +178,8 @@
"fixBrokenLink": "修复 {{page}} 中的失效链接",
"addCrossRefs": "为 {{page}} 添加交叉引用",
"addCrossRefsDescription": "此页面没有出站 [[wikilinks]]。建议添加与相关实体和概念的交叉引用。",
+ "suggestedTarget": "建议目标:{{page}}",
+ "suggestedSource": "建议来源:{{page}}",
"deleteOrphanConfirm": "删除孤立页面「{{page}}」?",
"typeLabels": {
"orphan": "孤立页面",
diff --git a/src/lib/lint-fixes.test.ts b/src/lib/lint-fixes.test.ts
new file mode 100644
index 00000000..e1785dd0
--- /dev/null
+++ b/src/lib/lint-fixes.test.ts
@@ -0,0 +1,94 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const fsMocks = vi.hoisted(() => ({
+ createDirectory: vi.fn(),
+ fileExists: vi.fn(),
+ writeFile: vi.fn(),
+}))
+
+vi.mock("@/commands/fs", () => fsMocks)
+
+import {
+ appendWikilink,
+ ensureBrokenLinkStub,
+ rewriteWikilinkTarget,
+ stubRelativePathFromBrokenTarget,
+} from "./lint-fixes"
+
+beforeEach(() => {
+ fsMocks.createDirectory.mockReset()
+ fsMocks.fileExists.mockReset()
+ fsMocks.writeFile.mockReset()
+})
+
+describe("rewriteWikilinkTarget", () => {
+ it("rewrites a matching wikilink and preserves aliases", () => {
+ const out = rewriteWikilinkTarget(
+ "See [[transfomer|the Transformer page]] and [[attention]].",
+ "transfomer",
+ "entities/transformer.md",
+ )
+
+ expect(out).toBe("See [[entities/transformer|the Transformer page]] and [[attention]].")
+ })
+
+ it("leaves non-matching wikilinks byte-identical", () => {
+ const input = "See [[attention|Attention]] only."
+ expect(rewriteWikilinkTarget(input, "transformer", "entities/transformer.md")).toBe(input)
+ })
+})
+
+describe("appendWikilink", () => {
+ it("does not duplicate an existing aliased wikilink", () => {
+ const input = "See [[entities/transformer|Transformer]]."
+ expect(appendWikilink(input, "entities/transformer.md")).toBe(input)
+ })
+
+ it("appends a related section when the target is absent", () => {
+ expect(appendWikilink("# Page\nBody", "entities/transformer.md")).toBe(
+ "# Page\nBody\n\n## Related\n- [[entities/transformer]]\n",
+ )
+ })
+
+ it("adds to an existing related section without duplicating the heading", () => {
+ const out = appendWikilink(
+ "# Page\n\n## Related\n- [[entities/attention]]\n",
+ "entities/transformer.md",
+ )
+
+ expect(out.match(/^## Related$/gm)).toHaveLength(1)
+ expect(out).toContain("## Related\n- [[entities/transformer]]\n- [[entities/attention]]")
+ })
+})
+
+describe("ensureBrokenLinkStub", () => {
+ it("reuses an existing slugified target instead of overwriting it", async () => {
+ fsMocks.fileExists.mockResolvedValue(true)
+
+ const result = await ensureBrokenLinkStub("/project", "Foo Bar")
+
+ expect(result).toEqual({
+ fullPath: "/project/wiki/queries/foo-bar.md",
+ relativePath: "queries/foo-bar.md",
+ created: false,
+ })
+ expect(fsMocks.writeFile).not.toHaveBeenCalled()
+ })
+
+ it("creates a safe stub path when no target exists", async () => {
+ fsMocks.fileExists.mockResolvedValue(false)
+
+ const result = await ensureBrokenLinkStub("/project", "Foo Bar")
+
+ expect(result.relativePath).toBe("queries/foo-bar.md")
+ expect(fsMocks.createDirectory).toHaveBeenCalledWith("/project/wiki/queries")
+ expect(fsMocks.writeFile).toHaveBeenCalledWith(
+ "/project/wiki/queries/foo-bar.md",
+ expect.stringContaining("title: \"Foo Bar\""),
+ )
+ })
+
+ it("keeps explicit wiki subdirectories when building stub paths", () => {
+ expect(stubRelativePathFromBrokenTarget("concepts/Foo Bar")).toBe("concepts/foo-bar.md")
+ })
+})
diff --git a/src/lib/lint-fixes.ts b/src/lib/lint-fixes.ts
new file mode 100644
index 00000000..f10228d6
--- /dev/null
+++ b/src/lib/lint-fixes.ts
@@ -0,0 +1,100 @@
+import { createDirectory, fileExists, writeFile } from "@/commands/fs"
+import { getFileName, normalizePath } from "@/lib/path-utils"
+import { makeQuerySlug } from "@/lib/wiki-filename"
+
+export function lintLinkTarget(target: string): string {
+ return normalizePath(target)
+ .replace(/^wiki\//i, "")
+ .replace(/\.md$/i, "")
+ .trim()
+}
+
+function normalizedLintLinkTarget(target: string): string {
+ return lintLinkTarget(target).toLowerCase()
+}
+
+function hasWikilinkToTarget(content: string, target: string): boolean {
+ const normalized = normalizedLintLinkTarget(target)
+ return Array.from(content.matchAll(/\[\[([^\]|]+?)(?:\|[^\]]+?)?\]\]/g))
+ .some((match) => normalizedLintLinkTarget(match[1]) === normalized)
+}
+
+export function appendWikilink(content: string, target: string): string {
+ const linkTarget = lintLinkTarget(target)
+ if (hasWikilinkToTarget(content, linkTarget)) return content
+ const linkLine = `- [[${linkTarget}]]`
+ const relatedHeading = /^##\s+Related\s*$/im.exec(content)
+ if (relatedHeading) {
+ const insertAt = relatedHeading.index + relatedHeading[0].length
+ return `${content.slice(0, insertAt)}\n${linkLine}${content.slice(insertAt)}`
+ }
+ return `${content.trimEnd()}\n\n## Related\n${linkLine}\n`
+}
+
+export function rewriteWikilinkTarget(
+ content: string,
+ brokenTarget: string,
+ suggestedTarget: string,
+): string {
+ const broken = normalizedLintLinkTarget(brokenTarget)
+ const replacement = lintLinkTarget(suggestedTarget)
+ return content.replace(
+ /\[\[([^\]|]+?)(\|[^\]]+?)?\]\]/g,
+ (match, rawTarget: string, rawAlias?: string) => {
+ if (normalizedLintLinkTarget(rawTarget) !== broken) return match
+ return `[[${replacement}${rawAlias ?? ""}]]`
+ },
+ )
+}
+
+export function stubRelativePathFromBrokenTarget(brokenTarget: string): string {
+ const normalized = lintLinkTarget(brokenTarget)
+ const parts = normalized
+ .split("/")
+ .map((part) => makeQuerySlug(part))
+ .filter(Boolean)
+ const rel = parts.length > 1
+ ? parts.join("/")
+ : `queries/${parts[0] ?? "missing-page"}`
+ return `${rel}.md`
+}
+
+function stubTitleFromBrokenTarget(brokenTarget: string): string {
+ return getFileName(lintLinkTarget(brokenTarget))
+ .replace(/[-_]+/g, " ")
+ .trim() || "Missing Page"
+}
+
+export async function ensureBrokenLinkStub(
+ projectPath: string,
+ brokenTarget: string,
+): Promise<{ fullPath: string; relativePath: string; created: boolean }> {
+ const relativePath = stubRelativePathFromBrokenTarget(brokenTarget)
+ const fullPath = `${projectPath}/wiki/${relativePath}`
+ if (await fileExists(fullPath)) {
+ return { fullPath, relativePath, created: false }
+ }
+
+ const parent = fullPath.split("/").slice(0, -1).join("/")
+ await createDirectory(parent)
+ const title = stubTitleFromBrokenTarget(brokenTarget)
+ const date = new Date().toISOString().slice(0, 10)
+ const content = [
+ "---",
+ "type: query",
+ `title: "${title.replace(/"/g, '\\"')}"`,
+ `created: ${date}`,
+ `updated: ${date}`,
+ "tags: [stub, lint]",
+ "related: []",
+ "sources: []",
+ "---",
+ "",
+ `# ${title}`,
+ "",
+ "Created by Wiki Lint as a placeholder for a missing wikilink target.",
+ "",
+ ].join("\n")
+ await writeFile(fullPath, content)
+ return { fullPath, relativePath, created: true }
+}
diff --git a/src/lib/lint.test.ts b/src/lib/lint.test.ts
index 9812fec9..8c6b03ff 100644
--- a/src/lib/lint.test.ts
+++ b/src/lib/lint.test.ts
@@ -13,7 +13,7 @@ vi.mock("@/commands/fs", () => ({
listDirectory: vi.fn(),
}))
-import { runSemanticLint } from "./lint"
+import { runSemanticLint, runStructuralLint } from "./lint"
import { streamChat } from "./llm-client"
import { readFile, listDirectory } from "@/commands/fs"
import { useWikiStore } from "@/stores/wiki-store"
@@ -152,3 +152,97 @@ describe("runSemanticLint — activity & early returns", () => {
expect(items[0].status).toBe("error")
})
})
+
+describe("runStructuralLint — link suggestions", () => {
+ it("suggests the closest existing page for a broken wikilink", async () => {
+ const pages = [
+ makeFileNode("transformer.md", "---\ntitle: Transformer\n---\n# Transformer\nAttention model."),
+ makeFileNode("attention.md", "# Attention\nSee [[transfomer]] for the architecture."),
+ ]
+ mockListDirectory.mockResolvedValue(pages.map((p) => p.node))
+ mockReadFile.mockImplementation(async (path) => {
+ const match = pages.find((p) => p.node.path === path)
+ return match?.content ?? ""
+ })
+
+ const results = await runStructuralLint("/project")
+ const broken = results.find((result) => result.type === "broken-link")
+
+ expect(broken).toMatchObject({
+ page: "attention.md",
+ brokenTarget: "transfomer",
+ suggestedTarget: "transformer.md",
+ })
+ })
+
+ it("suggests related pages for orphan and no-outlinks findings", async () => {
+ const pages = [
+ makeFileNode("rag.md", "# RAG\nRetrieval augmented generation uses vector search."),
+ makeFileNode("vector-search.md", "# Vector Search\nVector search retrieval finds related chunks."),
+ ]
+ mockListDirectory.mockResolvedValue(pages.map((p) => p.node))
+ mockReadFile.mockImplementation(async (path) => {
+ const match = pages.find((p) => p.node.path === path)
+ return match?.content ?? ""
+ })
+
+ const results = await runStructuralLint("/project")
+ const noOutlinks = results.find((result) => result.type === "no-outlinks" && result.page === "rag.md")
+ const orphan = results.find((result) => result.type === "orphan" && result.page === "rag.md")
+
+ expect(noOutlinks?.suggestedTarget).toBe("vector-search.md")
+ expect(orphan?.suggestedSource).toBe("vector-search.md")
+ })
+
+ it("does not attach self-referential suggestions when no related page exists", async () => {
+ const pages = [
+ makeFileNode("alpha.md", "# Alpha\nAardvark apricot."),
+ makeFileNode("beta.md", "# Beta\nZeppelin zircon."),
+ ]
+ mockListDirectory.mockResolvedValue(pages.map((p) => p.node))
+ mockReadFile.mockImplementation(async (path) => {
+ const match = pages.find((p) => p.node.path === path)
+ return match?.content ?? ""
+ })
+
+ const results = await runStructuralLint("/project")
+ const orphan = results.find((result) => result.type === "orphan" && result.page === "alpha.md")
+
+ expect(orphan?.suggestedSource).toBeUndefined()
+ expect(orphan?.suggestedTarget).toBeUndefined()
+ })
+
+ it("does not suggest same-folder pages without shared terms", async () => {
+ const pages = [
+ makeFileNode("concepts/alpha.md", "# Alpha\nAardvark apricot."),
+ makeFileNode("concepts/beta.md", "# Beta\nZeppelin zircon."),
+ ]
+ mockListDirectory.mockResolvedValue(pages.map((p) => p.node))
+ mockReadFile.mockImplementation(async (path) => {
+ const match = pages.find((p) => p.node.path === path)
+ return match?.content ?? ""
+ })
+
+ const results = await runStructuralLint("/project")
+ const orphan = results.find((result) => result.type === "orphan" && result.page === "concepts/alpha.md")
+
+ expect(orphan?.suggestedSource).toBeUndefined()
+ })
+
+ it("does not suggest short unrelated typo targets", async () => {
+ const pages = [
+ makeFileNode("bat.md", "# Bat\nFlying mammal."),
+ makeFileNode("note.md", "# Note\nSee [[cat]]."),
+ ]
+ mockListDirectory.mockResolvedValue(pages.map((p) => p.node))
+ mockReadFile.mockImplementation(async (path) => {
+ const match = pages.find((p) => p.node.path === path)
+ return match?.content ?? ""
+ })
+
+ const results = await runStructuralLint("/project")
+ const broken = results.find((result) => result.type === "broken-link" && result.brokenTarget === "cat")
+
+ expect(broken?.suggestedTarget).toBeUndefined()
+ })
+})
diff --git a/src/lib/lint.ts b/src/lib/lint.ts
index b20117d4..12b69402 100644
--- a/src/lib/lint.ts
+++ b/src/lib/lint.ts
@@ -12,8 +12,19 @@ export interface LintResult {
page: string
detail: string
affectedPages?: string[]
+ brokenTarget?: string
+ suggestedTarget?: string
+ suggestedSource?: string
}
+const BROKEN_LINK_SUGGESTION_MIN_SCORE = 0.74
+const RELATED_PAGE_SUGGESTION_MIN_SCORE = 0.08
+const SAME_FOLDER_SCORE_BONUS = 0.08
+const SINGLE_CJK_TOKEN_WEIGHT = 0.35
+const SUGGESTION_TOKEN_WINDOW = 4000
+const SAME_BASENAME_SCORE = 0.96
+const CONTAINS_TARGET_SCORE = 0.82
+
// ── helpers ───────────────────────────────────────────────────────────────────
function flattenMdFiles(nodes: FileNode[]): FileNode[] {
@@ -43,6 +54,76 @@ function relativeToSlug(relativePath: string): string {
return relativePath.replace(/\.md$/, "")
}
+function normalizeLinkTarget(target: string): string {
+ return normalizePath(target)
+ .replace(/^wiki\//i, "")
+ .replace(/\.md$/i, "")
+ .trim()
+ .toLowerCase()
+}
+
+function extractTitle(content: string, fallbackPath: string): string {
+ const frontmatter = content.match(/^---\s*\n([\s\S]*?)\n---/)
+ if (frontmatter) {
+ const title = frontmatter[1].match(/^title:\s*["']?(.+?)["']?\s*$/m)
+ if (title?.[1]?.trim()) return title[1].trim()
+ }
+ const heading = content.match(/^#\s+(.+)$/m)
+ if (heading?.[1]?.trim()) return heading[1].trim()
+ return getFileName(fallbackPath)
+ .replace(/\.md$/i, "")
+ .replace(/[-_]+/g, " ")
+}
+
+function tokenizeForSuggestion(text: string): Set<string> {
+ const tokens = new Set<string>()
+ const normalized = text.normalize("NFKC").toLowerCase()
+ for (const match of normalized.matchAll(/[\p{L}\p{N}]+/gu)) {
+ const token = match[0]
+ if (token.length >= 2) tokens.add(token)
+ if (/[\u3400-\u9fff]/u.test(token)) {
+ for (const char of Array.from(token)) tokens.add(char)
+ }
+ }
+ return tokens
+}
+
+function levenshtein(a: string, b: string): number {
+ if (a === b) return 0
+ if (!a) return b.length
+ if (!b) return a.length
+ const previous = Array.from({ length: b.length + 1 }, (_, i) => i)
+ const current = new Array<number>(b.length + 1)
+ for (let i = 1; i <= a.length; i++) {
+ current[0] = i
+ for (let j = 1; j <= b.length; j++) {
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1
+ current[j] = Math.min(
+ current[j - 1] + 1,
+ previous[j] + 1,
+ previous[j - 1] + cost,
+ )
+ }
+ for (let j = 0; j <= b.length; j++) previous[j] = current[j]
+ }
+ return previous[b.length]
+}
+
+function stringSimilarity(a: string, b: string): number {
+ const left = normalizeLinkTarget(a)
+ const right = normalizeLinkTarget(b)
+ if (!left || !right) return 0
+ if (left === right) return 1
+ const leftBase = getFileName(left)
+ const rightBase = getFileName(right)
+ if (leftBase === rightBase) return SAME_BASENAME_SCORE
+ if (right.includes(left) || left.includes(right)) return CONTAINS_TARGET_SCORE
+ if (leftBase.length < 5 || rightBase.length < 5) return 0
+ const maxLen = Math.max(leftBase.length, rightBase.length)
+ if (maxLen === 0) return 0
+ return 1 - levenshtein(leftBase, rightBase) / maxLen
+}
+
/**
* Build a slug → absolute path map from wiki files. Keys are lowercased
* so [[Transformer]] matches transformer.md — wikilink matching should
@@ -84,20 +165,73 @@ export async function runStructuralLint(projectPath: string): Promise<LintResult
const slugMap = buildSlugMap(contentFiles, wikiRoot)
// Read all content files
- type PageData = { path: string; slug: string; content: string; outlinks: string[] }
+ type PageData = {
+ path: string
+ shortName: string
+ slug: string
+ title: string
+ content: string
+ outlinks: string[]
+ tokens: Set<string>
+ }
const pages: PageData[] = []
for (const f of contentFiles) {
try {
const content = await readFile(f.path)
- const slug = relativeToSlug(getRelativePath(f.path, wikiRoot))
+ const shortName = getRelativePath(f.path, wikiRoot)
+ const slug = relativeToSlug(shortName)
+ const title = extractTitle(content, shortName)
const outlinks = extractWikilinks(content)
- pages.push({ path: f.path, slug, content, outlinks })
+ const slugName = getFileName(slug)
+ const tokens = tokenizeForSuggestion(`${title}\n${slugName}\n${content.slice(0, SUGGESTION_TOKEN_WINDOW)}`)
+ pages.push({ path: f.path, shortName, slug, title, content, outlinks, tokens })
} catch {
// skip unreadable files
}
}
+ function suggestBrokenTarget(target: string): PageData | undefined {
+ let best: { page: PageData; score: number } | undefined
+ for (const candidate of pages) {
+ const score = Math.max(
+ stringSimilarity(target, candidate.slug),
+ stringSimilarity(target, candidate.shortName),
+ stringSimilarity(target, candidate.title),
+ )
+ if (score > (best?.score ?? 0)) best = { page: candidate, score }
+ }
+ return best && best.score >= BROKEN_LINK_SUGGESTION_MIN_SCORE ? best.page : undefined
+ }
+
+ function suggestRelatedPage(page: PageData, direction: "source" | "target"): PageData | undefined {
+ const existingOutlinks = new Set(page.outlinks.map(normalizeLinkTarget))
+ let best: { page: PageData; score: number } | undefined
+ for (const candidate of pages) {
+ if (candidate.shortName === page.shortName) continue
+ if (direction === "target") {
+ const candidateKeys = [
+ normalizeLinkTarget(candidate.slug),
+ normalizeLinkTarget(candidate.shortName),
+ normalizeLinkTarget(getFileName(candidate.shortName).replace(/\.md$/i, "")),
+ ]
+ if (candidateKeys.some((key) => existingOutlinks.has(key))) continue
+ }
+ let overlap = 0
+ for (const token of page.tokens) {
+ if (candidate.tokens.has(token)) overlap += token.length > 1 ? 1 : SINGLE_CJK_TOKEN_WEIGHT
+ }
+ if (overlap === 0) continue
+ const folderBonus =
+ page.shortName.split("/")[0] === candidate.shortName.split("/")[0] ? SAME_FOLDER_SCORE_BONUS : 0
+ const score =
+ overlap / Math.sqrt(Math.max(1, page.tokens.size) * Math.max(1, candidate.tokens.size)) +
+ folderBonus
+ if (score > (best?.score ?? 0)) best = { page: candidate, score }
+ }
+ return best && best.score >= RELATED_PAGE_SUGGESTION_MIN_SCORE ? best.page : undefined
+ }
+
// Build inbound link count. Lookups are case-insensitive — [[Transformer]]
// should match transformer.md (slug "transformer").
const inboundCounts = new Map<string, number>()
@@ -114,26 +248,30 @@ export async function runStructuralLint(projectPath: string): Promise<LintResult
const results: LintResult[] = []
for (const p of pages) {
- const shortName = getRelativePath(p.path, wikiRoot)
+ const shortName = p.shortName
// Orphan: no inbound links (lowercased slug for case-insensitive match)
const inbound = inboundCounts.get(p.slug.toLowerCase()) ?? 0
if (inbound === 0) {
+ const suggestedSource = suggestRelatedPage(p, "source")
results.push({
type: "orphan",
severity: "info",
page: shortName,
detail: "No other pages link to this page.",
+ suggestedSource: suggestedSource?.shortName,
})
}
// No outbound links
if (p.outlinks.length === 0) {
+ const suggestedTarget = suggestRelatedPage(p, "target")
results.push({
type: "no-outlinks",
severity: "info",
page: shortName,
detail: "This page has no [[wikilink]] references to other pages.",
+ suggestedTarget: suggestedTarget?.shortName,
})
}
@@ -143,11 +281,14 @@ export async function runStructuralLint(projectPath: string): Promise<LintResult
const basename = getFileName(link).replace(/\.md$/, "").toLowerCase()
const exists = slugMap.has(lookup) || slugMap.has(basename)
if (!exists) {
+ const suggestedTarget = suggestBrokenTarget(link)
results.push({
type: "broken-link",
severity: "warning",
page: shortName,
detail: `Broken link: [[${link}]] — target page not found.`,
+ brokenTarget: link,
+ suggestedTarget: suggestedTarget?.shortName,
})
}
}
diff --git a/src/stores/lint-store.test.ts b/src/stores/lint-store.test.ts
index 11290071..ae00a912 100644
--- a/src/stores/lint-store.test.ts
+++ b/src/stores/lint-store.test.ts
@@ -45,6 +45,9 @@ describe("lint-store addItems", () => {
page: "entities/transformer.md",
detail: "contradiction: conflicting claims about model size",
affectedPages: ["a.md", "b.md"],
+ brokenTarget: "transfomer",
+ suggestedTarget: "entities/transformer.md",
+ suggestedSource: "concepts/attention.md",
},
]
useLintStore.getState().addItems(results)
@@ -54,6 +57,9 @@ describe("lint-store addItems", () => {
expect(item.page).toBe("entities/transformer.md")
expect(item.detail).toBe("contradiction: conflicting claims about model size")
expect(item.affectedPages).toEqual(["a.md", "b.md"])
+ expect(item.brokenTarget).toBe("transfomer")
+ expect(item.suggestedTarget).toBe("entities/transformer.md")
+ expect(item.suggestedSource).toBe("concepts/attention.md")
})
})
diff --git a/src/stores/lint-store.ts b/src/stores/lint-store.ts
index e1f4ed5c..9c1d0d3e 100644
--- a/src/stores/lint-store.ts
+++ b/src/stores/lint-store.ts
@@ -8,6 +8,9 @@ export interface LintItem {
page: string
detail: string
affectedPages?: string[]
+ brokenTarget?: string
+ suggestedTarget?: string
+ suggestedSource?: string
createdAt: number
}
@@ -18,6 +21,9 @@ function lintResultToItem(result: LintResult): LintItem {
page: result.page,
detail: result.detail,
affectedPages: result.affectedPages,
+ brokenTarget: result.brokenTarget,
+ suggestedTarget: result.suggestedTarget,
+ suggestedSource: result.suggestedSource,
id: `lint-${++counter}`,
createdAt: Date.now(),
}