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 operation — structural and semantic wiki health check

nash_sub49ee46bd82a
diff --git a/src/components/layout/content-area.tsx b/src/components/layout/content-area.tsx
index 75a554a2..d7fe9cc5 100644
--- a/src/components/layout/content-area.tsx
+++ b/src/components/layout/content-area.tsx
@@ -3,6 +3,8 @@ import { ChatPanel } from "@/components/chat/chat-panel"
import { SettingsView } from "@/components/settings/settings-view"
import { SourcesView } from "@/components/sources/sources-view"
import { ReviewView } from "@/components/review/review-view"
+import { LintView } from "@/components/lint/lint-view"
+import { SearchView } from "@/components/search/search-view"
export function ContentArea() {
const activeView = useWikiStore((s) => s.activeView)
@@ -14,6 +16,10 @@ export function ContentArea() {
return <SourcesView />
case "review":
return <ReviewView />
+ case "lint":
+ return <LintView />
+ case "search":
+ return <SearchView />
default:
return <ChatPanel />
}
diff --git a/src/components/lint/lint-view.tsx b/src/components/lint/lint-view.tsx
new file mode 100644
index 00000000..55d027e4
--- /dev/null
+++ b/src/components/lint/lint-view.tsx
@@ -0,0 +1,220 @@
+import { useState, useCallback } from "react"
+import {
+ Link2Off,
+ Unlink,
+ ArrowUpRight,
+ AlertTriangle,
+ Info,
+ RefreshCw,
+ CheckCircle2,
+ BrainCircuit,
+} from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { ScrollArea } from "@/components/ui/scroll-area"
+import { useWikiStore } from "@/stores/wiki-store"
+import { runStructuralLint, runSemanticLint, type LintResult } from "@/lib/lint"
+import { readFile } from "@/commands/fs"
+
+const typeConfig: Record<string, { icon: typeof AlertTriangle; label: string }> = {
+ orphan: { icon: Unlink, label: "Orphan Page" },
+ "broken-link": { icon: Link2Off, label: "Broken Link" },
+ "no-outlinks": { icon: ArrowUpRight, label: "No Outbound Links" },
+ semantic: { icon: BrainCircuit, label: "Semantic Issue" },
+}
+
+export function LintView() {
+ const project = useWikiStore((s) => s.project)
+ const llmConfig = useWikiStore((s) => s.llmConfig)
+ const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
+ const setFileContent = useWikiStore((s) => s.setFileContent)
+ const setActiveView = useWikiStore((s) => s.setActiveView)
+
+ const [results, setResults] = useState<LintResult[]>([])
+ const [running, setRunning] = useState(false)
+ const [hasRun, setHasRun] = useState(false)
+ const [runSemantic, setRunSemantic] = useState(false)
+
+ const handleRunLint = useCallback(async () => {
+ if (!project || running) return
+ setRunning(true)
+ setResults([])
+ try {
+ const structural = await runStructuralLint(project.path)
+ let all = structural
+
+ if (runSemantic && (llmConfig.apiKey || llmConfig.provider === "ollama")) {
+ const semantic = await runSemanticLint(project.path, llmConfig)
+ all = [...structural, ...semantic]
+ }
+
+ setResults(all)
+ setHasRun(true)
+ } catch (err) {
+ console.error("Lint failed:", err)
+ } finally {
+ setRunning(false)
+ }
+ }, [project, llmConfig, running, runSemantic])
+
+ async function handleOpenPage(page: string) {
+ if (!project) return
+ const candidates = [
+ `${project.path}/wiki/${page}`,
+ `${project.path}/wiki/${page}.md`,
+ ]
+ setActiveView("wiki")
+ for (const path of candidates) {
+ try {
+ const content = await readFile(path)
+ setSelectedFile(path)
+ setFileContent(content)
+ return
+ } catch {
+ // try next
+ }
+ }
+ setSelectedFile(candidates[0])
+ setFileContent(`Unable to load: ${page}`)
+ }
+
+ const warnings = results.filter((r) => r.severity === "warning")
+ const infos = results.filter((r) => r.severity === "info")
+
+ return (
+ <div className="flex h-full flex-col">
+ <div className="flex items-center justify-between border-b px-4 py-3">
+ <div className="flex items-center gap-2">
+ <h2 className="text-sm font-semibold">Wiki Lint</h2>
+ {hasRun && results.length > 0 && (
+ <span className="rounded-full bg-amber-500/20 px-2 py-0.5 text-xs font-medium text-amber-600 dark:text-amber-400">
+ {results.length} issue{results.length !== 1 ? "s" : ""}
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-2">
+ <label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ className="h-3 w-3"
+ checked={runSemantic}
+ onChange={(e) => setRunSemantic(e.target.checked)}
+ />
+ Semantic (LLM)
+ </label>
+ <Button
+ size="sm"
+ onClick={handleRunLint}
+ disabled={running || !project}
+ >
+ <RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${running ? "animate-spin" : ""}`} />
+ {running ? "Running..." : "Run Lint"}
+ </Button>
+ </div>
+ </div>
+
+ <ScrollArea className="flex-1">
+ {!hasRun ? (
+ <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" />
+ <p>Run lint to check wiki health</p>
+ <p className="text-xs">Checks for orphan pages, broken links, and more</p>
+ </div>
+ ) : results.length === 0 ? (
+ <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-emerald-500/60" />
+ <p className="text-emerald-600 dark:text-emerald-400 font-medium">All clear!</p>
+ <p className="text-xs">No issues found.</p>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2 p-3">
+ {warnings.length > 0 && (
+ <SectionHeader icon={AlertTriangle} label="Warnings" count={warnings.length} color="text-amber-500" />
+ )}
+ {warnings.map((result, i) => (
+ <LintCard key={`warn-${i}`} result={result} onOpenPage={handleOpenPage} />
+ ))}
+ {infos.length > 0 && (
+ <SectionHeader icon={Info} label="Info" count={infos.length} color="text-blue-500" />
+ )}
+ {infos.map((result, i) => (
+ <LintCard key={`info-${i}`} result={result} onOpenPage={handleOpenPage} />
+ ))}
+ </div>
+ )}
+ </ScrollArea>
+ </div>
+ )
+}
+
+function SectionHeader({
+ icon: Icon,
+ label,
+ count,
+ color,
+}: {
+ icon: typeof AlertTriangle
+ label: string
+ count: number
+ color: string
+}) {
+ return (
+ <div className={`flex items-center gap-1.5 px-1 py-1 text-xs font-semibold ${color}`}>
+ <Icon className="h-3.5 w-3.5" />
+ {label} ({count})
+ </div>
+ )
+}
+
+function LintCard({
+ result,
+ onOpenPage,
+}: {
+ result: LintResult
+ onOpenPage: (page: string) => void
+}) {
+ const config = typeConfig[result.type] ?? typeConfig.semantic
+ const Icon = config.icon
+
+ return (
+ <div className="rounded-lg border p-3 text-sm">
+ <div className="mb-1.5 flex items-start gap-2">
+ <Icon
+ className={`mt-0.5 h-4 w-4 shrink-0 ${
+ result.severity === "warning" ? "text-amber-500" : "text-blue-500"
+ }`}
+ />
+ <div className="flex-1 min-w-0">
+ <div className="font-medium truncate">{result.page}</div>
+ <div className="text-[11px] text-muted-foreground">{config.label}</div>
+ </div>
+ </div>
+
+ <p className="mb-2 text-xs text-muted-foreground">{result.detail}</p>
+
+ {result.affectedPages && result.affectedPages.length > 0 && (
+ <div className="flex flex-wrap gap-1">
+ {result.affectedPages.map((page) => (
+ <button
+ key={page}
+ type="button"
+ onClick={() => onOpenPage(page)}
+ className="inline-flex items-center gap-0.5 rounded bg-accent/60 px-1.5 py-0.5 text-xs font-medium text-primary hover:bg-accent transition-colors"
+ >
+ {page}
+ </button>
+ ))}
+ </div>
+ )}
+
+ {!result.affectedPages && (
+ <button
+ type="button"
+ onClick={() => onOpenPage(result.page)}
+ className="inline-flex items-center gap-0.5 rounded bg-accent/60 px-1.5 py-0.5 text-xs font-medium text-primary hover:bg-accent transition-colors"
+ >
+ {result.page}
+ </button>
+ )}
+ </div>
+ )
+}
diff --git a/src/lib/lint.ts b/src/lib/lint.ts
new file mode 100644
index 00000000..dd9d3cc6
--- /dev/null
+++ b/src/lib/lint.ts
@@ -0,0 +1,281 @@
+import { readFile, listDirectory } from "@/commands/fs"
+import { streamChat } from "@/lib/llm-client"
+import type { LlmConfig } from "@/stores/wiki-store"
+import type { FileNode } from "@/types/wiki"
+import { useActivityStore } from "@/stores/activity-store"
+
+export interface LintResult {
+ type: "orphan" | "broken-link" | "no-outlinks" | "semantic"
+ severity: "warning" | "info"
+ page: string
+ detail: string
+ affectedPages?: string[]
+}
+
+// ── helpers ───────────────────────────────────────────────────────────────────
+
+function flattenMdFiles(nodes: FileNode[]): FileNode[] {
+ const files: FileNode[] = []
+ for (const node of nodes) {
+ if (node.is_dir && node.children) {
+ files.push(...flattenMdFiles(node.children))
+ } else if (!node.is_dir && node.name.endsWith(".md")) {
+ files.push(node)
+ }
+ }
+ return files
+}
+
+function extractWikilinks(content: string): string[] {
+ const links: string[] = []
+ const regex = /\[\[([^\]|]+?)(?:\|[^\]]+?)?\]\]/g
+ let match: RegExpExecArray | null
+ while ((match = regex.exec(content)) !== null) {
+ links.push(match[1].trim())
+ }
+ return links
+}
+
+function relativeToSlug(relativePath: string): string {
+ // relativePath relative to wiki/ dir, e.g. "entities/foo-bar" or "queries/my-page-2024-01-01"
+ return relativePath.replace(/\.md$/, "")
+}
+
+/** Build a slug → absolute path map from wiki files */
+function buildSlugMap(
+ wikiFiles: FileNode[],
+ wikiRoot: string,
+): Map<string, string> {
+ const map = new Map<string, string>()
+ for (const f of wikiFiles) {
+ // e.g. /path/to/project/wiki/entities/foo.md → entities/foo
+ const rel = f.path.replace(wikiRoot + "/", "").replace(/\.md$/, "")
+ map.set(rel, f.path)
+ // also index by basename without extension
+ map.set(f.name.replace(/\.md$/, ""), f.path)
+ }
+ return map
+}
+
+// ── Structural lint ───────────────────────────────────────────────────────────
+
+export async function runStructuralLint(projectPath: string): Promise<LintResult[]> {
+ const wikiRoot = `${projectPath}/wiki`
+ let tree: FileNode[]
+ try {
+ tree = await listDirectory(wikiRoot)
+ } catch {
+ return []
+ }
+
+ const wikiFiles = flattenMdFiles(tree)
+ // Exclude index.md and log.md from orphan checks
+ const contentFiles = wikiFiles.filter(
+ (f) => f.name !== "index.md" && f.name !== "log.md"
+ )
+
+ const slugMap = buildSlugMap(contentFiles, wikiRoot)
+
+ // Read all content files
+ type PageData = { path: string; slug: string; content: string; outlinks: string[] }
+ const pages: PageData[] = []
+
+ for (const f of contentFiles) {
+ try {
+ const content = await readFile(f.path)
+ const slug = relativeToSlug(f.path.replace(wikiRoot + "/", ""))
+ const outlinks = extractWikilinks(content)
+ pages.push({ path: f.path, slug, content, outlinks })
+ } catch {
+ // skip unreadable files
+ }
+ }
+
+ // Build inbound link count
+ const inboundCounts = new Map<string, number>()
+ for (const p of pages) {
+ for (const link of p.outlinks) {
+ const target = slugMap.has(link)
+ ? relativeToSlug(slugMap.get(link)!.replace(wikiRoot + "/", ""))
+ : link
+ inboundCounts.set(target, (inboundCounts.get(target) ?? 0) + 1)
+ }
+ }
+
+ const results: LintResult[] = []
+
+ for (const p of pages) {
+ const shortName = p.path.replace(wikiRoot + "/", "")
+
+ // Orphan: no inbound links
+ const inbound = inboundCounts.get(p.slug) ?? 0
+ if (inbound === 0) {
+ results.push({
+ type: "orphan",
+ severity: "info",
+ page: shortName,
+ detail: "No other pages link to this page.",
+ })
+ }
+
+ // No outbound links
+ if (p.outlinks.length === 0) {
+ results.push({
+ type: "no-outlinks",
+ severity: "info",
+ page: shortName,
+ detail: "This page has no [[wikilink]] references to other pages.",
+ })
+ }
+
+ // Broken links
+ for (const link of p.outlinks) {
+ const exists = slugMap.has(link) || slugMap.has(link.split("/").pop() ?? "")
+ if (!exists) {
+ results.push({
+ type: "broken-link",
+ severity: "warning",
+ page: shortName,
+ detail: `Broken link: [[${link}]] — target page not found.`,
+ })
+ }
+ }
+ }
+
+ return results
+}
+
+// ── Semantic lint ─────────────────────────────────────────────────────────────
+
+const LINT_BLOCK_REGEX =
+ /---LINT:\s*([^\n|]+?)\s*\|\s*([^\n|]+?)\s*\|\s*([^\n-]+?)\s*---\n([\s\S]*?)---END LINT---/g
+
+export async function runSemanticLint(
+ projectPath: string,
+ llmConfig: LlmConfig,
+): Promise<LintResult[]> {
+ const activity = useActivityStore.getState()
+ const activityId = activity.addItem({
+ type: "lint",
+ title: "Semantic wiki lint",
+ status: "running",
+ detail: "Reading wiki pages...",
+ filesWritten: [],
+ })
+
+ const wikiRoot = `${projectPath}/wiki`
+ let tree: FileNode[]
+ try {
+ tree = await listDirectory(wikiRoot)
+ } catch {
+ activity.updateItem(activityId, { status: "error", detail: "Failed to read wiki directory." })
+ return []
+ }
+
+ const wikiFiles = flattenMdFiles(tree).filter(
+ (f) => f.name !== "log.md"
+ )
+
+ // Build a compact summary of each page (frontmatter + first 500 chars)
+ const summaries: string[] = []
+ for (const f of wikiFiles) {
+ try {
+ const content = await readFile(f.path)
+ const preview = content.slice(0, 500) + (content.length > 500 ? "..." : "")
+ const shortPath = f.path.replace(wikiRoot + "/", "")
+ summaries.push(`### ${shortPath}\n${preview}`)
+ } catch {
+ // skip
+ }
+ }
+
+ if (summaries.length === 0) {
+ activity.updateItem(activityId, { status: "done", detail: "No wiki pages to lint." })
+ return []
+ }
+
+ activity.updateItem(activityId, { detail: "Running LLM semantic analysis..." })
+
+ const prompt = [
+ "You are a wiki quality analyst. Review the following wiki page summaries and identify issues.",
+ "",
+ "For each issue, output exactly this format:",
+ "",
+ "---LINT: type | severity | Short title---",
+ "Description of the issue.",
+ "PAGES: page1.md, page2.md",
+ "---END LINT---",
+ "",
+ "Types:",
+ "- contradiction: two or more pages make conflicting claims",
+ "- stale: information that appears outdated or superseded",
+ "- missing-page: an important concept is heavily referenced but has no dedicated page",
+ "- suggestion: a question or source worth adding to the wiki",
+ "",
+ "Severities:",
+ "- warning: should be addressed",
+ "- info: nice to have",
+ "",
+ "Only report genuine issues. Do not invent problems. Output ONLY the ---LINT--- blocks, no other text.",
+ "",
+ "## Wiki Pages",
+ "",
+ summaries.join("\n\n"),
+ ].join("\n")
+
+ let raw = ""
+ let hadError = false
+
+ await streamChat(
+ llmConfig,
+ [{ role: "user", content: prompt }],
+ {
+ onToken: (token) => { raw += token },
+ onDone: () => {},
+ onError: (err) => {
+ hadError = true
+ activity.updateItem(activityId, {
+ status: "error",
+ detail: `LLM error: ${err.message}`,
+ })
+ },
+ },
+ )
+
+ if (hadError) return []
+
+ const results: LintResult[] = []
+ const matches = raw.matchAll(LINT_BLOCK_REGEX)
+
+ for (const match of matches) {
+ const rawType = match[1].trim().toLowerCase()
+ const severity = match[2].trim().toLowerCase()
+ const title = match[3].trim()
+ const body = match[4].trim()
+
+ // semantic results always use type "semantic"
+ void rawType
+
+ const pagesMatch = body.match(/^PAGES:\s*(.+)$/m)
+ const affectedPages = pagesMatch
+ ? pagesMatch[1].split(",").map((p) => p.trim())
+ : undefined
+
+ const detail = body.replace(/^PAGES:.*$/m, "").trim()
+
+ results.push({
+ type: "semantic",
+ severity: (severity === "warning" ? "warning" : "info") as LintResult["severity"],
+ page: title,
+ detail: `[${rawType}] ${detail}`,
+ affectedPages,
+ })
+ }
+
+ activity.updateItem(activityId, {
+ status: "done",
+ detail: `Found ${results.length} semantic issue(s).`,
+ })
+
+ return results
+}