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

fix: scale wiki link repair for large projects

nash_su6661b819f569
diff --git a/src/components/lint/lint-view.tsx b/src/components/lint/lint-view.tsx
index a238a421..918656ff 100644
--- a/src/components/lint/lint-view.tsx
+++ b/src/components/lint/lint-view.tsx
@@ -1,4 +1,4 @@
-import { useState, useCallback, useMemo } from "react"
+import { useState, useCallback, useEffect, useMemo, useRef } from "react"
import {
Link2Off,
Unlink,
@@ -70,35 +70,49 @@ export function LintView() {
const clearLintItems = useLintStore((s) => s.clearItems)
const [running, setRunning] = useState(false)
+ const [lintProgress, setLintProgress] = useState<{ completed: number; total: number } | null>(null)
const [hasRun, setHasRun] = useState(false)
const [runSemantic, setRunSemantic] = useState(false)
const [fixingId, setFixingId] = useState<string | null>(null)
const [batchFixing, setBatchFixing] = useState(false)
const [fixError, setFixError] = useState<string | null>(null)
const [selectedLintIds, setSelectedLintIds] = useState<Set<string>>(() => new Set())
+ const lintAbortRef = useRef<AbortController | null>(null)
+
+ useEffect(() => () => lintAbortRef.current?.abort(), [])
const handleRunLint = useCallback(async () => {
if (!project || running) return
const pp = normalizePath(project.path)
setRunning(true)
setFixError(null)
+ setLintProgress(null)
setSelectedLintIds(new Set())
clearLintItems()
+ const controller = new AbortController()
+ lintAbortRef.current = controller
try {
- const structural = await runStructuralLint(pp)
+ const structural = await runStructuralLint(pp, {
+ signal: controller.signal,
+ onProgress: (completed, total) => setLintProgress({ completed, total }),
+ })
let all = structural
if (runSemantic && hasUsableLlm(llmConfig)) {
- const semantic = await runSemanticLint(pp, llmConfig)
+ const semantic = await runSemanticLint(pp, llmConfig, controller.signal)
all = [...structural, ...semantic]
}
addLintItems(all)
setHasRun(true)
} catch (err) {
- console.error("Lint failed:", err)
+ if (!(err instanceof DOMException && err.name === "AbortError")) {
+ console.error("Lint failed:", err)
+ }
} finally {
+ lintAbortRef.current = null
setRunning(false)
+ setLintProgress(null)
}
}, [project, llmConfig, running, runSemantic, addLintItems, clearLintItems])
@@ -167,7 +181,7 @@ export function LintView() {
}
}, [project, t])
- async function handleFix(item: LintItem) {
+ async function handleFix(item: LintItem, refreshTree = true) {
if (!project) return
const pp = normalizePath(project.path)
setFixingId(item.id)
@@ -223,11 +237,12 @@ export function LintView() {
}
}
- // Refresh tree
- await refreshProjectFileTree(pp, {
- projectId: project.id,
- bumpDataVersion: true,
- })
+ if (refreshTree) {
+ await refreshProjectFileTree(pp, {
+ projectId: project.id,
+ bumpDataVersion: true,
+ })
+ }
} catch (err) {
console.error("Fix failed:", err)
setFixError(err instanceof Error ? err.message : String(err))
@@ -314,15 +329,62 @@ export function LintView() {
const handleBatchFix = useCallback(async () => {
if (!project || batchFixing || selectedLintItems.length === 0) return
setBatchFixing(true)
+ setFixError(null)
+ const pp = normalizePath(project.path)
+ let filesystemChanged = false
try {
+ const edits = new Map<string, Array<{ id: string; apply: (content: string) => string }>>()
+ const queueEdit = (path: string, id: string, apply: (content: string) => string) => {
+ const pending = edits.get(path) ?? []
+ pending.push({ id, apply })
+ edits.set(path, pending)
+ }
+
for (const item of selectedLintItems) {
- await handleFix(item)
+ if (item.type === "orphan" && item.suggestedSource) {
+ queueEdit(`${pp}/wiki/${item.suggestedSource}`, item.id, (content) => appendWikilink(content, item.page))
+ } else if (item.type === "no-outlinks" && item.suggestedTarget) {
+ queueEdit(`${pp}/wiki/${item.page}`, item.id, (content) => appendWikilink(content, item.suggestedTarget!))
+ } else if (item.type === "broken-link" && item.brokenTarget) {
+ const stub = item.suggestedTarget ? null : await ensureBrokenLinkStub(pp, item.brokenTarget)
+ if (stub) filesystemChanged = true
+ const target = item.suggestedTarget ?? stub!.relativePath
+ queueEdit(`${pp}/wiki/${item.page}`, item.id, (content) =>
+ rewriteWikilinkTarget(content, item.brokenTarget!, target))
+ } else {
+ addLintItemToReview(item)
+ removeLintItems([item.id])
+ }
+ }
+
+ // Multiple findings can target the same page. Apply their transforms in
+ // memory and write that page once, avoiding lost updates and N full reads.
+ for (const [path, pending] of edits) {
+ const original = await readFile(path)
+ const updated = pending.reduce((content, edit) => edit.apply(content), original)
+ if (updated !== original) {
+ await writeFile(path, updated)
+ filesystemChanged = true
+ }
+ removeLintItems(pending.map((edit) => edit.id))
}
setSelectedLintIds(new Set())
+ } catch (err) {
+ console.error("Batch fix failed:", err)
+ setFixError(err instanceof Error ? err.message : String(err))
} finally {
+ // Refresh even after a partial failure: earlier files or stubs may have
+ // been written successfully. The expensive recursive rebuild still runs
+ // at most once for the whole batch.
+ if (filesystemChanged) {
+ await refreshProjectFileTree(pp, {
+ projectId: project.id,
+ bumpDataVersion: true,
+ })
+ }
setBatchFixing(false)
}
- }, [batchFixing, project, selectedLintItems])
+ }, [addLintItemToReview, batchFixing, project, removeLintItems, selectedLintItems])
return (
<div className="flex h-full flex-col">
@@ -347,11 +409,16 @@ export function LintView() {
</label>
<Button
size="sm"
- onClick={handleRunLint}
- disabled={running || !project}
+ variant={running ? "outline" : "default"}
+ onClick={running ? () => lintAbortRef.current?.abort() : handleRunLint}
+ disabled={!project}
>
<RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${running ? "animate-spin" : ""}`} />
- {running ? t("lint.running") : t("lint.runLint")}
+ {running
+ ? lintProgress && lintProgress.total > 0
+ ? t("lint.cancelProgress", { completed: lintProgress.completed, total: lintProgress.total })
+ : t("lint.cancel")
+ : t("lint.runLint")}
</Button>
</div>
</div>
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 2b0259a0..a14e0c55 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -344,6 +344,8 @@
"title": "Wiki Lint",
"semantic": "Semantic (LLM)",
"running": "Running...",
+ "cancel": "Cancel check",
+ "cancelProgress": "Cancel {{completed}}/{{total}}",
"runLint": "Run Lint",
"runLintHint": "Run lint to check wiki health",
"runLintDescription": "Checks for orphan pages, broken links, and more",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index ad43189c..e35f9452 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -344,6 +344,8 @@
"title": "Wiki 检查",
"semantic": "语义检查 (LLM)",
"running": "检查中...",
+ "cancel": "取消检查",
+ "cancelProgress": "取消 {{completed}}/{{total}}",
"runLint": "开始检查",
"runLintHint": "运行检查以诊断 Wiki 健康状况",
"runLintDescription": "检查孤立页面、失效链接等问题",
diff --git a/src/lib/ingest-parse.test.ts b/src/lib/ingest-parse.test.ts
index 525b4d72..d14e0ae0 100644
--- a/src/lib/ingest-parse.test.ts
+++ b/src/lib/ingest-parse.test.ts
@@ -25,8 +25,7 @@ import {
stampGeneratedLogDate,
buildGenerationPrompt,
sourceSummaryMediaRefsForExternalMarkdown,
- aggregatePathsNeedingRepair,
- filterAggregateRepairOutput,
+ buildDeterministicIngestLog,
rewriteIngestPathFromTitleForTargetLanguage,
canonicalizeSourcesField,
isAppManagedAggregatePath,
@@ -112,43 +111,16 @@ describe("source summary media refs", () => {
})
})
-describe("aggregate repair targeting", () => {
- it("repairs only the append-only log and leaves deterministic aggregates to the app", () => {
- expect(aggregatePathsNeedingRepair(
- ["wiki/index.md", "wiki/log.md"],
- ['FILE block "wiki/overview.md" was not closed before end of stream — likely truncation.'],
- )).toEqual([])
-
- expect(aggregatePathsNeedingRepair(["wiki/index.md"], [])).toEqual(["wiki/log.md"])
-
- expect(aggregatePathsNeedingRepair(
- ["wiki/index.md", "wiki/overview.md", "wiki/log.md"],
- [],
- )).toEqual([])
+describe("deterministic ingest log", () => {
+ it("builds a deterministic append-only log entry without another LLM call", () => {
+ expect(buildDeterministicIngestLog("", "raw/sources/a.pdf", "2026-07-20")).toBe(
+ "# Wiki Log\n\n## [2026-07-20] ingest | raw/sources/a.pdf\n",
+ )
+ expect(buildDeterministicIngestLog("# Wiki Log\n", "raw/sources/b.pdf", "2026-07-20")).toBe(
+ "# Wiki Log\n\n## [2026-07-20] ingest | raw/sources/b.pdf\n",
+ )
})
- it("filters aggregate repair output to the requested aggregate paths only", () => {
- const raw = [
- "---FILE: wiki/overview.md---",
- "# Overview",
- "---END FILE---",
- "",
- "---FILE: wiki/sources/should-not-touch.md---",
- "# Stray Source Summary",
- "---END FILE---",
- "",
- "---FILE: wiki/entities/stray.md---",
- "# Stray Entity",
- "---END FILE---",
- ].join("\n")
-
- const filtered = filterAggregateRepairOutput(raw, ["wiki/overview.md"])
-
- expect(filtered.text).toContain("---FILE: wiki/overview.md---")
- expect(filtered.text).not.toContain("should-not-touch")
- expect(filtered.text).not.toContain("wiki/entities/stray.md")
- expect(filtered.warnings.join("\n")).toContain("Dropped 2 non-aggregate")
- })
})
// ── H1: CRLF normalization ─────────────────────────────────────────
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index ef42a4a4..0b16d25e 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -603,6 +603,17 @@ export function formatIngestWarningLogEntry(
].join("\n")
}
+export function buildDeterministicIngestLog(
+ existing: string,
+ sourceIdentity: string,
+ date = currentWikiDate(),
+): string {
+ const entry = `## [${date}] ingest | ${sourceIdentity}`
+ return existing.trim()
+ ? `${existing.trimEnd()}\n\n${entry}\n`
+ : `# Wiki Log\n\n${entry}\n`
+}
+
async function appendIngestWarningLog(
projectPath: string,
sourceIdentity: string,
@@ -1123,85 +1134,20 @@ async function autoIngestImpl(
)
}
- const aggregateRepairPaths = aggregatePathsNeedingRepair(writtenPaths, writeWarnings)
- const repairableAggregatePaths = aggregateRepairPaths.filter((path) =>
- isAggregateRepairSafe(path, index, overview, llmConfig.maxContextSize),
- )
- const skippedAggregatePaths = aggregateRepairPaths.filter((path) =>
- !repairableAggregatePaths.includes(path),
- )
- if (skippedAggregatePaths.length > 0) {
- writeWarnings.push(
- `Skipped aggregate repair for ${skippedAggregatePaths.join(", ")} because the existing file is too large to safely regenerate without truncating existing entries.`,
- )
- }
- if (repairableAggregatePaths.length > 0 && !signal?.aborted) {
- activity.updateItem(activityId, {
- detail: `Repairing aggregate wiki files: ${repairableAggregatePaths.join(", ")}`,
- })
- let aggregateRepairOutput = ""
+ // log.md is append-only structural metadata. If the model omitted its FILE
+ // block, write a deterministic entry instead of starting another LLM turn.
+ // This keeps multi-file imports at two generation stages per source and
+ // prevents a slow provider from making the queue appear stuck in "repair".
+ if (!writtenPaths.some((path) => normalizePath(path).toLowerCase() === "wiki/log.md") && !signal?.aborted) {
try {
- await streamChat(
- llmConfig,
- [
- {
- role: "system",
- content: buildAggregateRepairPrompt(
- repairableAggregatePaths,
- purpose,
- index,
- overview,
- sourceIdentity,
- analysis,
- sourceContext,
- generation,
- llmConfig.maxContextSize,
- ),
- },
- {
- role: "user",
- content: "Emit the requested aggregate FILE blocks now. Start immediately with `---FILE:`.",
- },
- ],
- {
- onToken: (token) => { aggregateRepairOutput += token },
- onDone: () => {},
- onError: (err) => {
- writeWarnings.push(`Aggregate repair failed: ${err.message}`)
- },
- },
- signal,
- {
- temperature: 0.1,
- reasoning: { mode: "off" },
- max_tokens: computeIngestReviewMaxTokens(llmConfig.maxContextSize),
- },
- )
- throwIfIngestAborted(signal, activityId)
- if (aggregateRepairOutput.trim()) {
- const filteredRepair = filterAggregateRepairOutput(
- aggregateRepairOutput,
- repairableAggregatePaths,
- )
- writeWarnings.push(...filteredRepair.warnings)
- const repairResult = await writeFileBlocks(
- pp,
- filteredRepair.text,
- llmConfig,
- sourceIdentity,
- sourceSummaryPath,
- signal,
- activityId,
- onFileWritten,
- )
- writtenPaths.push(...repairResult.writtenPaths)
- writeWarnings.push(...repairResult.warnings)
- hardFailures.push(...repairResult.hardFailures)
- }
+ const logPath = `${pp}/wiki/log.md`
+ const existingLog = await tryReadFile(logPath)
+ await writeFile(logPath, buildDeterministicIngestLog(existingLog, sourceIdentity))
+ writtenPaths.push("wiki/log.md")
+ onFileWritten?.("wiki/log.md")
} catch (err) {
- throwIfIngestAborted(signal, activityId)
writeWarnings.push(
- `Aggregate repair failed: ${err instanceof Error ? err.message : String(err)}`,
+ `Deterministic log update failed: ${err instanceof Error ? err.message : String(err)}`,
)
}
}
@@ -1420,16 +1366,6 @@ export function rewriteIngestPathFromTitleForTargetLanguage(
return isSafeIngestPath(nextPath) ? nextPath : relativePath
}
-export function aggregatePathsNeedingRepair(writtenPaths: string[], warnings: string[]): string[] {
- const written = new Set(writtenPaths.map((path) => normalizePath(path)))
- const warningText = warnings.join("\n")
- // index.md is maintained deterministically and overview.md is intentionally
- // bounded/stable. Only the append-only log still needs an LLM repair block.
- return AGGREGATE_WIKI_PATHS.filter((path) => path === "wiki/log.md").filter((path) =>
- !written.has(path) || warningText.includes(`"${path}"`),
- )
-}
-
async function updateWikiIndexDeterministically(
projectPath: string,
writtenPaths: string[],
@@ -1487,44 +1423,6 @@ export function updateBoundedRecentIndexSection(index: string, additions: string
return [...prefix, "", section, ...recent, ...(suffix.length ? ["", ...suffix] : []), ""].join("\n")
}
-export function filterAggregateRepairOutput(text: string, allowedPaths: string[]): {
- text: string
- warnings: string[]
-} {
- const allowed = new Set(allowedPaths.map((path) => normalizePath(path)))
- const { blocks, warnings } = parseFileBlocks(text)
- const kept = blocks.filter((block) => allowed.has(normalizePath(block.path)))
- const dropped = blocks.filter((block) => !allowed.has(normalizePath(block.path)))
- if (dropped.length > 0) {
- warnings.push(
- `Dropped ${dropped.length} non-aggregate block(s) from aggregate repair output: ${dropped.map((block) => block.path).join(", ")}`,
- )
- }
- return {
- text: kept
- .map((block) => `---FILE: ${block.path}---\n${block.content.trimEnd()}\n---END FILE---`)
- .join("\n\n"),
- warnings,
- }
-}
-
-function aggregateRepairSectionCap(maxContextSize: number | undefined): number {
- const { maxCtx } = computeContextBudget(maxContextSize)
- return Math.max(4_000, Math.floor(maxCtx * 0.12))
-}
-
-function isAggregateRepairSafe(
- path: string,
- index: string,
- overview: string,
- maxContextSize: number | undefined,
-): boolean {
- const cap = aggregateRepairSectionCap(maxContextSize)
- if (path === "wiki/index.md") return index.length <= cap
- if (path === "wiki/overview.md") return overview.length <= cap
- return true
-}
-
function isValidSourceReference(source: string, activeSourceIdentity: string): boolean {
const normalized = normalizePath(source).replace(/^(?:\.\/)+/, "")
const key = normalized.toLowerCase()
@@ -2333,62 +2231,6 @@ function buildReviewSuggestionPrompt(
].filter(Boolean).join("\n")
}
-function buildAggregateRepairPrompt(
- paths: string[],
- purpose: string,
- index: string,
- overview: string,
- sourceIdentity: string,
- analysis: string,
- sourceContext: string,
- generation: string,
- maxContextSize: number | undefined,
-): string {
- const sectionCap = aggregateRepairSectionCap(maxContextSize)
- const today = currentWikiDate()
- return [
- "You are repairing aggregate wiki files after an ingest generation.",
- "Do not output chain-of-thought, hidden reasoning, or explanatory preamble.",
- "",
- languageRule(sourceContext),
- "",
- "Generate ONLY the requested aggregate FILE blocks listed below.",
- "Do not generate entity, concept, source summary, query, comparison, or synthesis pages.",
- "",
- "Requested paths:",
- ...paths.map((path) => `- ${path}`),
- "",
- "Rules:",
- `- Use today's date ${today} for log entries and frontmatter dates.`,
- "- For wiki/index.md: output the complete updated index, preserving existing entries and adding the new source-derived entries.",
- "- For wiki/overview.md: output the complete updated overview, reflecting the full wiki plus this new source.",
- "- For wiki/log.md: output only the new log entry to append, format `## [YYYY-MM-DD] ingest | Title`.",
- "- Output only FILE blocks. Nothing else.",
- "",
- "FILE block template:",
- "```",
- "---FILE: wiki/path.md---",
- "(complete file content, or just the new log entry for wiki/log.md)",
- "---END FILE---",
- "```",
- "",
- purpose ? `## Wiki Purpose\n${trimLongText(purpose, Math.floor(sectionCap * 0.5))}` : "",
- index ? `## Current Wiki Index\n${trimLongText(index, sectionCap)}` : "",
- overview ? `## Current Overview\n${trimLongText(overview, sectionCap)}` : "",
- "",
- `## Source\n${sourceIdentity}`,
- "",
- "## Stage 1 Analysis",
- trimLongText(analysis, sectionCap),
- "",
- "## Source Context",
- trimLongText(sourceContext, sectionCap),
- "",
- "## First Generation Output",
- trimLongText(generation, sectionCap),
- ].filter(Boolean).join("\n")
-}
-
function getStore() {
return useChatStore.getState()
}
diff --git a/src/lib/lint-structural-core.test.ts b/src/lib/lint-structural-core.test.ts
new file mode 100644
index 00000000..8a9bd05a
--- /dev/null
+++ b/src/lib/lint-structural-core.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from "vitest"
+import { computeStructuralLint, type StructuralLintPage } from "./lint-structural-core"
+
+function page(index: number, total: number): StructuralLintPage {
+ return {
+ shortName: `entities/page-${index}.md`,
+ slug: `entities/page-${index}`,
+ title: `Page ${index}`,
+ outlinks: index + 1 < total ? [`entities/page-${index + 1}`] : ["entities/page-0"],
+ tokens: ["shared", `topic-${index}`],
+ }
+}
+
+describe("computeStructuralLint", () => {
+ it("finds typo candidates without scanning unrelated page names", () => {
+ const pages = [
+ { ...page(0, 2), shortName: "transformer.md", slug: "transformer", title: "Transformer", outlinks: [] },
+ { ...page(1, 2), shortName: "attention.md", slug: "attention", title: "Attention", outlinks: ["transfomer"] },
+ ]
+ const broken = computeStructuralLint(pages).find((finding) => finding.type === "broken-link")
+ expect(broken?.suggestedTarget).toBe("transformer.md")
+ })
+
+ it("handles 5,000 pages without quadratic candidate expansion", () => {
+ const pages = Array.from({ length: 5_000 }, (_, index) => page(index, 5_000))
+ const started = performance.now()
+ const findings = computeStructuralLint(pages)
+ const elapsed = performance.now() - started
+
+ expect(findings).toEqual([])
+ // A generous ceiling catches accidental restoration of the old all-pairs
+ // scan while remaining stable on slower CI runners.
+ expect(elapsed).toBeLessThan(5_000)
+ })
+})
diff --git a/src/lib/lint-structural-core.ts b/src/lib/lint-structural-core.ts
new file mode 100644
index 00000000..2a662b24
--- /dev/null
+++ b/src/lib/lint-structural-core.ts
@@ -0,0 +1,211 @@
+export interface StructuralLintPage {
+ shortName: string
+ slug: string
+ title: string
+ outlinks: string[]
+ tokens: string[]
+}
+
+export interface StructuralLintFinding {
+ type: "orphan" | "broken-link" | "no-outlinks"
+ severity: "warning" | "info"
+ page: string
+ detail: string
+ brokenTarget?: string
+ suggestedTarget?: string
+ suggestedSource?: string
+}
+
+interface IndexedPage extends StructuralLintPage {
+ tokenSet: Set<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 SAME_BASENAME_SCORE = 0.96
+const CONTAINS_TARGET_SCORE = 0.82
+const MAX_SUGGESTION_CANDIDATES = 64
+
+function fileName(path: string): string {
+ return path.replace(/\\/g, "/").split("/").pop() ?? path
+}
+
+function normalizeTarget(target: string): string {
+ return target.replace(/\\/g, "/")
+ .replace(/^wiki\//i, "")
+ .replace(/\.md$/i, "")
+ .trim()
+ .toLowerCase()
+}
+
+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 += 1) {
+ current[0] = i
+ for (let j = 1; j <= b.length; j += 1) {
+ 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 += 1) previous[j] = current[j]
+ }
+ return previous[b.length]
+}
+
+function stringSimilarity(a: string, b: string): number {
+ const left = normalizeTarget(a)
+ const right = normalizeTarget(b)
+ if (!left || !right) return 0
+ if (left === right) return 1
+ const leftBase = fileName(left)
+ const rightBase = fileName(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
+ return 1 - levenshtein(leftBase, rightBase) / Math.max(leftBase.length, rightBase.length)
+}
+
+function fragments(value: string): string[] {
+ const normalized = normalizeTarget(value).normalize("NFKC")
+ const chars = Array.from(normalized)
+ if (chars.length < 2) return normalized ? [normalized] : []
+ const result = new Set<string>()
+ for (let i = 0; i < chars.length - 1; i += 1) result.add(`${chars[i]}${chars[i + 1]}`)
+ return Array.from(result)
+}
+
+function addToIndex(index: Map<string, number[]>, key: string, pageIndex: number): void {
+ const values = index.get(key)
+ if (values) values.push(pageIndex)
+ else index.set(key, [pageIndex])
+}
+
+function topCandidates(scores: Map<number, number>, excluded: number): number[] {
+ return Array.from(scores.entries())
+ .filter(([index]) => index !== excluded)
+ .sort((left, right) => right[1] - left[1] || left[0] - right[0])
+ .slice(0, MAX_SUGGESTION_CANDIDATES)
+ .map(([index]) => index)
+}
+
+export function computeStructuralLint(
+ rawPages: StructuralLintPage[],
+ onProgress?: (completed: number, total: number) => void,
+): StructuralLintFinding[] {
+ const pages: IndexedPage[] = rawPages.map((page) => ({ ...page, tokenSet: new Set(page.tokens) }))
+ const slugMap = new Map<string, number>()
+ const tokenIndex = new Map<string, number[]>()
+ const fragmentIndex = new Map<string, number[]>()
+
+ pages.forEach((page, index) => {
+ const basename = fileName(page.shortName).replace(/\.md$/i, "")
+ slugMap.set(normalizeTarget(page.slug), index)
+ slugMap.set(normalizeTarget(basename), index)
+ for (const token of page.tokenSet) addToIndex(tokenIndex, token, index)
+ for (const value of [page.slug, page.shortName, page.title]) {
+ for (const fragment of fragments(value)) addToIndex(fragmentIndex, fragment, index)
+ }
+ })
+
+ const inboundCounts = new Map<number, number>()
+ for (const page of pages) {
+ for (const link of page.outlinks) {
+ const target = slugMap.get(normalizeTarget(link))
+ ?? slugMap.get(normalizeTarget(fileName(link).replace(/\.md$/i, "")))
+ if (target !== undefined) inboundCounts.set(target, (inboundCounts.get(target) ?? 0) + 1)
+ }
+ }
+
+ function relatedCandidate(pageIndex: number, direction: "source" | "target"): IndexedPage | undefined {
+ const page = pages[pageIndex]
+ const scores = new Map<number, number>()
+ for (const token of page.tokenSet) {
+ const matches = tokenIndex.get(token) ?? []
+ // Very common terms do not identify a useful related page and recreate
+ // the quadratic scan this index is intended to avoid.
+ if (matches.length > Math.max(20, Math.ceil(pages.length * 0.25))) continue
+ const weight = token.length > 1 ? 1 : SINGLE_CJK_TOKEN_WEIGHT
+ for (const candidate of matches) scores.set(candidate, (scores.get(candidate) ?? 0) + weight)
+ }
+ const existing = new Set(page.outlinks.map(normalizeTarget))
+ let best: { page: IndexedPage; score: number } | undefined
+ for (const candidateIndex of topCandidates(scores, pageIndex)) {
+ const candidate = pages[candidateIndex]
+ if (direction === "target") {
+ const keys = [candidate.slug, candidate.shortName, fileName(candidate.shortName).replace(/\.md$/i, "")]
+ .map(normalizeTarget)
+ if (keys.some((key) => existing.has(key))) continue
+ }
+ const overlap = scores.get(candidateIndex) ?? 0
+ const folderBonus = page.shortName.split("/")[0] === candidate.shortName.split("/")[0]
+ ? SAME_FOLDER_SCORE_BONUS
+ : 0
+ const score = overlap / Math.sqrt(Math.max(1, page.tokenSet.size) * Math.max(1, candidate.tokenSet.size)) + folderBonus
+ if (score > (best?.score ?? 0)) best = { page: candidate, score }
+ }
+ return best && best.score >= RELATED_PAGE_SUGGESTION_MIN_SCORE ? best.page : undefined
+ }
+
+ function brokenCandidate(target: string): IndexedPage | undefined {
+ const scores = new Map<number, number>()
+ for (const fragment of fragments(target)) {
+ for (const candidate of fragmentIndex.get(fragment) ?? []) {
+ scores.set(candidate, (scores.get(candidate) ?? 0) + 1)
+ }
+ }
+ let best: { page: IndexedPage; score: number } | undefined
+ for (const candidateIndex of topCandidates(scores, -1)) {
+ const candidate = pages[candidateIndex]
+ 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
+ }
+
+ const results: StructuralLintFinding[] = []
+ pages.forEach((page, pageIndex) => {
+ if (!inboundCounts.has(pageIndex)) {
+ results.push({
+ type: "orphan",
+ severity: "info",
+ page: page.shortName,
+ detail: "No other pages link to this page.",
+ suggestedSource: relatedCandidate(pageIndex, "source")?.shortName,
+ })
+ }
+ if (page.outlinks.length === 0) {
+ results.push({
+ type: "no-outlinks",
+ severity: "info",
+ page: page.shortName,
+ detail: "This page has no [[wikilink]] references to other pages.",
+ suggestedTarget: relatedCandidate(pageIndex, "target")?.shortName,
+ })
+ }
+ for (const link of page.outlinks) {
+ const basename = fileName(link).replace(/\.md$/i, "")
+ if (slugMap.has(normalizeTarget(link)) || slugMap.has(normalizeTarget(basename))) continue
+ results.push({
+ type: "broken-link",
+ severity: "warning",
+ page: page.shortName,
+ detail: `Broken link: [[${link}]] — target page not found.`,
+ brokenTarget: link,
+ suggestedTarget: brokenCandidate(link)?.shortName,
+ })
+ }
+ if (pageIndex % 25 === 0 || pageIndex === pages.length - 1) {
+ onProgress?.(pageIndex + 1, pages.length)
+ }
+ })
+ return results
+}
diff --git a/src/lib/lint-structural.worker.ts b/src/lib/lint-structural.worker.ts
new file mode 100644
index 00000000..fcb59e29
--- /dev/null
+++ b/src/lib/lint-structural.worker.ts
@@ -0,0 +1,12 @@
+import { computeStructuralLint, type StructuralLintPage } from "./lint-structural-core"
+
+interface WorkerRequest {
+ pages: StructuralLintPage[]
+}
+
+self.onmessage = (event: MessageEvent<WorkerRequest>) => {
+ const findings = computeStructuralLint(event.data.pages, (completed, total) => {
+ self.postMessage({ type: "progress", completed, total })
+ })
+ self.postMessage({ type: "done", findings })
+}
diff --git a/src/lib/lint.test.ts b/src/lib/lint.test.ts
index 139af7be..61f98a21 100644
--- a/src/lib/lint.test.ts
+++ b/src/lib/lint.test.ts
@@ -222,6 +222,18 @@ describe("runSemanticLint — activity & early returns", () => {
})
describe("runStructuralLint — link suggestions", () => {
+ it("stops before reading pages when cancellation is already requested", async () => {
+ const pages = [makeFileNode("a.md", "# A")]
+ mockListDirectory.mockResolvedValue(pages.map((entry) => entry.node))
+ const controller = new AbortController()
+ controller.abort()
+
+ await expect(runStructuralLint("/project", { signal: controller.signal })).rejects.toMatchObject({
+ name: "AbortError",
+ })
+ expect(mockReadFile).not.toHaveBeenCalled()
+ })
+
it("suggests the closest existing page for a broken wikilink", async () => {
const pages = [
makeFileNode("transformer.md", "---\ntitle: Transformer\n---\n# Transformer\nAttention model."),
diff --git a/src/lib/lint.ts b/src/lib/lint.ts
index a88fb947..d353cf17 100644
--- a/src/lib/lint.ts
+++ b/src/lib/lint.ts
@@ -6,6 +6,11 @@ import { useActivityStore } from "@/stores/activity-store"
import { getFileName, getRelativePath, normalizePath } from "@/lib/path-utils"
import { buildLanguageDirective } from "@/lib/output-language"
import { normalizeReviewTitle } from "@/lib/review-utils"
+import {
+ computeStructuralLint,
+ type StructuralLintFinding,
+ type StructuralLintPage,
+} from "@/lib/lint-structural-core"
export interface LintResult {
type: "orphan" | "broken-link" | "no-outlinks" | "semantic"
@@ -18,13 +23,7 @@ export interface LintResult {
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 ───────────────────────────────────────────────────────────────────
@@ -55,14 +54,6 @@ 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()
-}
-
/**
* Normalize a name for missing-page existence comparison. NFKC folds full-width
* and compatibility forms so CJK / full-width variants compare equal.
@@ -113,66 +104,58 @@ function tokenizeForSuggestion(text: string): Set<string> {
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]
-}
+// ── Structural lint ───────────────────────────────────────────────────────────
-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
+export interface StructuralLintOptions {
+ signal?: AbortSignal
+ onProgress?: (completed: number, total: number) => void
}
-/**
- * Build a slug → absolute path map from wiki files. Keys are lowercased
- * so [[Transformer]] matches transformer.md — wikilink matching should
- * be case-insensitive (matching typical wiki conventions). Callers must
- * also lowercase their lookup keys.
- */
-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 = getRelativePath(f.path, wikiRoot).replace(/\.md$/, "")
- map.set(rel.toLowerCase(), f.path)
- // also index by basename without extension
- map.set(f.name.replace(/\.md$/, "").toLowerCase(), f.path)
+function runStructuralWorker(
+ pages: StructuralLintPage[],
+ options: StructuralLintOptions,
+): Promise<StructuralLintFinding[]> {
+ if (typeof Worker === "undefined") {
+ return Promise.resolve(computeStructuralLint(pages, options.onProgress))
}
- return map
+ return new Promise((resolve, reject) => {
+ const worker = new Worker(new URL("./lint-structural.worker.ts", import.meta.url), { type: "module" })
+ const abort = () => {
+ worker.terminate()
+ reject(new DOMException("Structural lint cancelled", "AbortError"))
+ }
+ if (options.signal?.aborted) {
+ abort()
+ return
+ }
+ options.signal?.addEventListener("abort", abort, { once: true })
+ worker.onerror = (event) => {
+ options.signal?.removeEventListener("abort", abort)
+ worker.terminate()
+ reject(new Error(event.message || "Structural lint worker failed"))
+ }
+ worker.onmessage = (event: MessageEvent<{
+ type: "progress" | "done"
+ completed?: number
+ total?: number
+ findings?: StructuralLintFinding[]
+ }>) => {
+ if (event.data.type === "progress") {
+ options.onProgress?.(event.data.completed ?? 0, event.data.total ?? pages.length)
+ return
+ }
+ options.signal?.removeEventListener("abort", abort)
+ worker.terminate()
+ resolve(event.data.findings ?? [])
+ }
+ worker.postMessage({ pages })
+ })
}
-// ── Structural lint ───────────────────────────────────────────────────────────
-
-export async function runStructuralLint(projectPath: string): Promise<LintResult[]> {
+export async function runStructuralLint(
+ projectPath: string,
+ options: StructuralLintOptions = {},
+): Promise<LintResult[]> {
const wikiRoot = `${normalizePath(projectPath)}/wiki`
let tree: FileNode[]
try {
@@ -187,21 +170,11 @@ export async function runStructuralLint(projectPath: string): Promise<LintResult
(f) => f.name !== "index.md" && f.name !== "log.md"
)
- const slugMap = buildSlugMap(contentFiles, wikiRoot)
-
- // Read all content files
- type PageData = {
- path: string
- shortName: string
- slug: string
- title: string
- content: string
- outlinks: string[]
- tokens: Set<string>
- }
- const pages: PageData[] = []
+ const pages: StructuralLintPage[] = []
- for (const f of contentFiles) {
+ for (let index = 0; index < contentFiles.length; index += 1) {
+ if (options.signal?.aborted) throw new DOMException("Structural lint cancelled", "AbortError")
+ const f = contentFiles[index]
try {
const content = await readFile(f.path)
const shortName = getRelativePath(f.path, wikiRoot)
@@ -209,117 +182,17 @@ export async function runStructuralLint(projectPath: string): Promise<LintResult
const title = extractTitle(content, shortName)
const outlinks = extractWikilinks(content)
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 })
+ const tokens = Array.from(tokenizeForSuggestion(`${title}\n${slugName}\n${content.slice(0, SUGGESTION_TOKEN_WINDOW)}`))
+ pages.push({ shortName, slug, title, outlinks, tokens })
} catch {
// skip unreadable files
}
+ options.onProgress?.(index + 1, contentFiles.length * 2)
}
-
- 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>()
- for (const p of pages) {
- for (const link of p.outlinks) {
- const lookup = link.toLowerCase()
- const target = slugMap.has(lookup)
- ? relativeToSlug(getRelativePath(slugMap.get(lookup)!, wikiRoot)).toLowerCase()
- : lookup
- inboundCounts.set(target, (inboundCounts.get(target) ?? 0) + 1)
- }
- }
-
- const results: LintResult[] = []
-
- for (const p of pages) {
- 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,
- })
- }
-
- // Broken links — case-insensitive matching.
- for (const link of p.outlinks) {
- const lookup = link.toLowerCase()
- 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,
- })
- }
- }
- }
-
- return results
+ return runStructuralWorker(pages, {
+ ...options,
+ onProgress: (completed, total) => options.onProgress?.(contentFiles.length + completed, contentFiles.length + total),
+ })
}
// ── Semantic lint ─────────────────────────────────────────────────────────────
@@ -330,6 +203,7 @@ const LINT_BLOCK_REGEX =
export async function runSemanticLint(
projectPath: string,
llmConfig: LlmConfig,
+ signal?: AbortSignal,
): Promise<LintResult[]> {
const pp = normalizePath(projectPath)
const activity = useActivityStore.getState()
@@ -360,6 +234,7 @@ export async function runSemanticLint(
const summaries: string[] = []
const existingPageNames = new Set<string>()
for (const f of wikiFiles) {
+ if (signal?.aborted) throw new DOMException("Semantic lint cancelled", "AbortError")
const basename = f.name.replace(/\.md$/i, "")
if (basename) existingPageNames.add(normalizeForExistence(basename))
try {
@@ -432,8 +307,10 @@ export async function runSemanticLint(
})
},
},
+ signal,
)
+ if (signal?.aborted) throw new DOMException("Semantic lint cancelled", "AbortError")
if (hadError) return []
const results: LintResult[] = []