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

Lint persistence

hkalex3be0b34c0e35
diff --git a/src/App.tsx b/src/App.tsx
index 8f52d531..1ade5c93 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -3,10 +3,11 @@ import { open } from "@tauri-apps/plugin-dialog"
import i18n from "@/i18n"
import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
+import { useLintStore } from "@/stores/lint-store"
import { useChatStore } from "@/stores/chat-store"
import { listDirectory, openProject } from "@/commands/fs"
import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId, loadProxyConfig, loadScheduledImportConfig, saveScheduledImportConfig, loadSourceWatchConfig, loadApiConfig } from "@/lib/project-store"
-import { loadReviewItems, loadChatHistory } from "@/lib/persist"
+import { loadReviewItems, loadLintItems, loadChatHistory } from "@/lib/persist"
import { setupAutoSave } from "@/lib/auto-save"
import { startClipWatcher } from "@/lib/clip-watcher"
import { AppLayout } from "@/components/layout/app-layout"
@@ -372,6 +373,15 @@ function App() {
} catch {
// ignore, start fresh
}
+ // Load persisted lint items
+ try {
+ const savedLint = await loadLintItems(proj.path)
+ if (savedLint.length > 0) {
+ useLintStore.getState().setItems(savedLint)
+ }
+ } catch {
+ // ignore, start fresh
+ }
// Load persisted chat history
try {
const savedChat = await loadChatHistory(proj.path)
diff --git a/src/components/lint/lint-view.test.ts b/src/components/lint/lint-view.test.ts
index 47a3ab1f..40e5742c 100644
--- a/src/components/lint/lint-view.test.ts
+++ b/src/components/lint/lint-view.test.ts
@@ -1,37 +1,40 @@
import { describe, expect, it } from "vitest"
-import type { LintResult } from "@/lib/lint"
import { groupLintResultsForDisplay } from "./lint-view"
+import type { LintItem } from "@/stores/lint-store"
-function lintResult(
+function makeLintItem(
page: string,
- severity: LintResult["severity"],
-): LintResult {
+ severity: "warning" | "info",
+ index: number,
+): LintItem {
return {
+ id: `lint-${index}`,
type: severity === "warning" ? "broken-link" : "orphan",
severity,
page,
detail: `${page} detail`,
+ createdAt: Date.now(),
}
}
describe("groupLintResultsForDisplay", () => {
- it("keeps original result indices when warnings and infos are interleaved", () => {
- const results = [
- lintResult("info-a.md", "info"),
- lintResult("warning-b.md", "warning"),
- lintResult("info-c.md", "info"),
- lintResult("warning-d.md", "warning"),
+ it("groups warnings and infos separately", () => {
+ const items: LintItem[] = [
+ makeLintItem("info-a.md", "info", 0),
+ makeLintItem("warning-b.md", "warning", 1),
+ makeLintItem("info-c.md", "info", 2),
+ makeLintItem("warning-d.md", "warning", 3),
]
- const grouped = groupLintResultsForDisplay(results)
+ const grouped = groupLintResultsForDisplay(items)
- expect(grouped.warnings.map(({ index, result }) => [index, result.page])).toEqual([
- [1, "warning-b.md"],
- [3, "warning-d.md"],
+ expect(grouped.warnings.map((item) => item.page)).toEqual([
+ "warning-b.md",
+ "warning-d.md",
])
- expect(grouped.infos.map(({ index, result }) => [index, result.page])).toEqual([
- [0, "info-a.md"],
- [2, "info-c.md"],
+ expect(grouped.infos.map((item) => item.page)).toEqual([
+ "info-a.md",
+ "info-c.md",
])
})
})
diff --git a/src/components/lint/lint-view.tsx b/src/components/lint/lint-view.tsx
index fb52a9b1..e0e8f711 100644
--- a/src/components/lint/lint-view.tsx
+++ b/src/components/lint/lint-view.tsx
@@ -14,30 +14,25 @@ import {
import { Button } from "@/components/ui/button"
import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
-import { runStructuralLint, runSemanticLint, type LintResult } from "@/lib/lint"
+import { useLintStore, type LintItem } from "@/stores/lint-store"
+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 { useTranslation } from "react-i18next"
-interface IndexedLintResult {
- result: LintResult
- index: number
-}
-
-export function groupLintResultsForDisplay(results: readonly LintResult[]): {
- warnings: IndexedLintResult[]
- infos: IndexedLintResult[]
+export function groupLintResultsForDisplay(results: readonly LintItem[]): {
+ warnings: LintItem[]
+ infos: LintItem[]
} {
- const warnings: IndexedLintResult[] = []
- const infos: IndexedLintResult[] = []
+ const warnings: LintItem[] = []
+ const infos: LintItem[] = []
- results.forEach((result, index) => {
- const item = { result, index }
+ results.forEach((result) => {
if (result.severity === "warning") {
- warnings.push(item)
+ warnings.push(result)
} else {
- infos.push(item)
+ infos.push(result)
}
})
@@ -62,7 +57,10 @@ export function LintView() {
semantic: { icon: BrainCircuit, label: t("lint.typeLabels.semantic") },
}), [t])
- const [results, setResults] = useState<LintResult[]>([])
+ const items = useLintStore((s) => s.items)
+ const addLintItems = useLintStore((s) => s.addItems)
+ const clearLintItems = useLintStore((s) => s.clearItems)
+
const [running, setRunning] = useState(false)
const [hasRun, setHasRun] = useState(false)
const [runSemantic, setRunSemantic] = useState(false)
@@ -72,7 +70,7 @@ export function LintView() {
if (!project || running) return
const pp = normalizePath(project.path)
setRunning(true)
- setResults([])
+ clearLintItems()
try {
const structural = await runStructuralLint(pp)
let all = structural
@@ -82,14 +80,14 @@ export function LintView() {
all = [...structural, ...semantic]
}
- setResults(all)
+ addLintItems(all)
setHasRun(true)
} catch (err) {
console.error("Lint failed:", err)
} finally {
setRunning(false)
}
- }, [project, llmConfig, running, runSemantic])
+ }, [project, llmConfig, running, runSemantic, addLintItems, clearLintItems])
async function handleOpenPage(page: string) {
if (!project) return
@@ -113,46 +111,45 @@ export function LintView() {
setFileContent(`Unable to load: ${page}`)
}
- async function handleFix(result: LintResult, index: number) {
+ async function handleFix(item: LintItem) {
if (!project) return
const pp = normalizePath(project.path)
- const id = `${result.type}-${index}`
- setFixingId(id)
+ setFixingId(item.id)
try {
- switch (result.type) {
+ 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 = result.page.replace(".md", "").replace(/^.*\//, "")
+ const pageName = item.page.replace(".md", "").replace(/^.*\//, "")
const entry = `- [[${pageName}]]`
if (!indexContent.includes(entry)) {
indexContent = indexContent.trimEnd() + "\n" + entry + "\n"
await writeFile(indexPath, indexContent)
}
- // Remove from results
- setResults((prev) => prev.filter((_, i) => i !== index))
+ // 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/${result.page}`
+ const pagePath = `${pp}/wiki/${item.page}`
useReviewStore.getState().addItem({
type: "confirm",
- title: t("lint.fixBrokenLink", { page: result.page }),
- description: result.detail,
- affectedPages: [result.page],
+ title: t("lint.fixBrokenLink", { page: item.page }),
+ description: item.detail,
+ affectedPages: [item.page],
options: [
- { label: t("lint.openEdit"), action: `open:${result.page}` },
+ { label: t("lint.openEdit"), action: `open:${item.page}` },
{ label: t("lint.deletePage"), action: `delete:${pagePath}` },
{ label: t("lint.skip"), action: "Skip" },
],
})
- setResults((prev) => prev.filter((_, i) => i !== index))
+ useLintStore.getState().removeItem(item.id)
break
}
@@ -160,15 +157,15 @@ export function LintView() {
// Send to Review — user should add links manually
useReviewStore.getState().addItem({
type: "suggestion",
- title: t("lint.addCrossRefs", { page: result.page }),
+ title: t("lint.addCrossRefs", { page: item.page }),
description: t("lint.addCrossRefsDescription"),
- affectedPages: [result.page],
+ affectedPages: [item.page],
options: [
- { label: t("lint.openEdit"), action: `open:${result.page}` },
+ { label: t("lint.openEdit"), action: `open:${item.page}` },
{ label: t("lint.skip"), action: "Skip" },
],
})
- setResults((prev) => prev.filter((_, i) => i !== index))
+ useLintStore.getState().removeItem(item.id)
break
}
@@ -176,15 +173,15 @@ export function LintView() {
// Semantic issues → send to Review for manual resolution
useReviewStore.getState().addItem({
type: "confirm",
- title: result.detail.slice(0, 80),
- description: result.detail,
- affectedPages: result.affectedPages ?? [result.page],
+ title: item.detail.slice(0, 80),
+ description: item.detail,
+ affectedPages: item.affectedPages ?? [item.page],
options: [
- { label: t("lint.openEdit"), action: `open:${result.page}` },
+ { label: t("lint.openEdit"), action: `open:${item.page}` },
{ label: t("lint.skip"), action: "Skip" },
],
})
- setResults((prev) => prev.filter((_, i) => i !== index))
+ useLintStore.getState().removeItem(item.id)
break
}
}
@@ -200,11 +197,11 @@ export function LintView() {
}
}
- async function handleDeleteOrphan(result: LintResult, index: number) {
+ async function handleDeleteOrphan(item: LintItem) {
if (!project) return
const pp = normalizePath(project.path)
- const pagePath = `${pp}/wiki/${result.page}`
- const confirmed = window.confirm(t("lint.deleteOrphanConfirm", { page: result.page }))
+ const pagePath = `${pp}/wiki/${item.page}`
+ const confirmed = window.confirm(t("lint.deleteOrphanConfirm", { page: item.page }))
if (!confirmed) return
try {
@@ -218,7 +215,7 @@ export function LintView() {
"@/lib/wiki-page-delete"
)
await cascadeDeleteWikiPagesWithRefs(pp, [pagePath])
- setResults((prev) => prev.filter((_, i) => i !== index))
+ useLintStore.getState().removeItem(item.id)
const tree = await listDirectory(pp)
setFileTree(tree)
bumpDataVersion()
@@ -228,8 +225,8 @@ export function LintView() {
}
const { warnings, infos } = useMemo(
- () => groupLintResultsForDisplay(results),
- [results],
+ () => groupLintResultsForDisplay(items),
+ [items],
)
return (
@@ -237,9 +234,9 @@ export function LintView() {
<div className="shrink-0 flex items-center justify-between border-b px-4 py-3">
<div className="flex items-center gap-2">
<h2 className="text-sm font-semibold">{t("lint.title")}</h2>
- {hasRun && results.length > 0 && (
+ {hasRun && items.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 === 1 ? t("lint.issues", { count: results.length }) : t("lint.issues_plural", { count: results.length })}
+ {items.length === 1 ? t("lint.issues", { count: items.length }) : t("lint.issues_plural", { count: items.length })}
</span>
)}
</div>
@@ -271,7 +268,7 @@ export function LintView() {
<p>{t("lint.runLintHint")}</p>
<p className="text-xs">{t("lint.runLintDescription")}</p>
</div>
- ) : results.length === 0 ? (
+ ) : items.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">{t("lint.allClear")}</p>
@@ -282,15 +279,14 @@ export function LintView() {
{warnings.length > 0 && (
<SectionHeader icon={AlertTriangle} label={t("lint.warnings")} count={warnings.length} color="text-amber-500" t={t} />
)}
- {warnings.map(({ result, index }) => (
+ {warnings.map((item) => (
<LintCard
- key={`warn-${index}`}
- result={result}
- index={index}
- fixing={fixingId === `${result.type}-${index}`}
+ key={item.id}
+ item={item}
+ fixing={fixingId === item.id}
onOpenPage={handleOpenPage}
onFix={handleFix}
- onDelete={result.type === "orphan" ? handleDeleteOrphan : undefined}
+ onDelete={item.type === "orphan" ? handleDeleteOrphan : undefined}
typeConfig={typeConfig}
t={t}
/>
@@ -298,15 +294,14 @@ export function LintView() {
{infos.length > 0 && (
<SectionHeader icon={Info} label={t("lint.info")} count={infos.length} color="text-blue-500" t={t} />
)}
- {infos.map(({ result, index }) => (
+ {infos.map((item) => (
<LintCard
- key={`info-${index}`}
- result={result}
- index={index}
- fixing={fixingId === `${result.type}-${index}`}
+ key={item.id}
+ item={item}
+ fixing={fixingId === item.id}
onOpenPage={handleOpenPage}
onFix={handleFix}
- onDelete={result.type === "orphan" ? handleDeleteOrphan : undefined}
+ onDelete={item.type === "orphan" ? handleDeleteOrphan : undefined}
typeConfig={typeConfig}
t={t}
/>
@@ -340,8 +335,7 @@ function SectionHeader({
}
function LintCard({
- result,
- index,
+ item,
fixing,
onOpenPage,
onFix,
@@ -349,16 +343,15 @@ function LintCard({
typeConfig,
t,
}: {
- result: LintResult
- index: number
+ item: LintItem
fixing: boolean
onOpenPage: (page: string) => void
- onFix: (result: LintResult, index: number) => void
- onDelete?: (result: LintResult, index: number) => void
+ onFix: (item: LintItem) => void
+ onDelete?: (item: LintItem) => void
typeConfig: Record<string, { icon: typeof AlertTriangle; label: string }>
t: (key: string, opts?: Record<string, unknown>) => string
}) {
- const config = typeConfig[result.type] ?? typeConfig.semantic
+ const config = typeConfig[item.type] ?? typeConfig.semantic
const Icon = config.icon
return (
@@ -366,20 +359,20 @@ function LintCard({
<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"
+ item.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="font-medium truncate">{item.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>
+ <p className="mb-2 text-xs text-muted-foreground">{item.detail}</p>
- {result.affectedPages && result.affectedPages.length > 0 && (
+ {item.affectedPages && item.affectedPages.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1">
- {result.affectedPages.map((page) => (
+ {item.affectedPages.map((page) => (
<button
key={page}
type="button"
@@ -397,7 +390,7 @@ function LintCard({
variant="outline"
size="sm"
className="h-6 text-xs gap-1"
- onClick={() => onOpenPage(result.page)}
+ onClick={() => onOpenPage(item.page)}
>
{t("lint.open")}
</Button>
@@ -406,7 +399,7 @@ function LintCard({
size="sm"
className="h-6 text-xs gap-1"
disabled={fixing}
- onClick={() => onFix(result, index)}
+ onClick={() => onFix(item)}
>
<Wrench className="h-3 w-3" />
{fixing ? t("lint.fixing") : t("lint.fix")}
@@ -416,7 +409,7 @@ function LintCard({
variant="outline"
size="sm"
className="h-6 text-xs gap-1 text-destructive hover:text-destructive"
- onClick={() => onDelete(result, index)}
+ onClick={() => onDelete(item)}
>
<Trash2 className="h-3 w-3" />
{t("lint.delete")}
diff --git a/src/lib/auto-save.ts b/src/lib/auto-save.ts
index 6281cf52..9b110ea3 100644
--- a/src/lib/auto-save.ts
+++ b/src/lib/auto-save.ts
@@ -1,9 +1,11 @@
import { useReviewStore } from "@/stores/review-store"
+import { useLintStore } from "@/stores/lint-store"
import { useChatStore } from "@/stores/chat-store"
import { useWikiStore } from "@/stores/wiki-store"
-import { saveReviewItems, saveChatHistory } from "./persist"
+import { saveReviewItems, saveLintItems, saveChatHistory } from "./persist"
let reviewTimer: ReturnType<typeof setTimeout> | null = null
+let lintTimer: ReturnType<typeof setTimeout> | null = null
let chatTimer: ReturnType<typeof setTimeout> | null = null
export function setupAutoSave(): void {
@@ -18,6 +20,17 @@ export function setupAutoSave(): void {
}, 1000)
})
+ // Auto-save lint items (debounced 1s)
+ useLintStore.subscribe((state) => {
+ if (lintTimer) clearTimeout(lintTimer)
+ lintTimer = setTimeout(() => {
+ const project = useWikiStore.getState().project
+ if (project) {
+ saveLintItems(project.path, state.items).catch(() => {})
+ }
+ }, 1000)
+ })
+
// Auto-save chat conversations and messages (debounced 2s, skip during streaming)
useChatStore.subscribe((state) => {
if (state.isStreaming) return
diff --git a/src/lib/persist.integration.test.ts b/src/lib/persist.integration.test.ts
index f8db30fb..e5906540 100644
--- a/src/lib/persist.integration.test.ts
+++ b/src/lib/persist.integration.test.ts
@@ -10,6 +10,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"
import { realFs, createTempProject, readFileRaw, writeFileRaw, fileExists } from "@/test-helpers/fs-temp"
import type { ReviewItem } from "@/stores/review-store"
+import type { LintItem } from "@/stores/lint-store"
import type { Conversation, DisplayMessage } from "@/stores/chat-store"
vi.mock("@/commands/fs", () => realFs)
@@ -17,6 +18,8 @@ vi.mock("@/commands/fs", () => realFs)
import {
saveReviewItems,
loadReviewItems,
+ saveLintItems,
+ loadLintItems,
saveChatHistory,
loadChatHistory,
} from "./persist"
@@ -36,6 +39,18 @@ function makeReview(overrides: Partial<ReviewItem> = {}): ReviewItem {
}
}
+function makeLint(overrides: Partial<LintItem> = {}): LintItem {
+ return {
+ id: "lint-1",
+ type: "orphan",
+ severity: "info",
+ page: "test.md",
+ detail: "test detail",
+ createdAt: 0,
+ ...overrides,
+ }
+}
+
beforeEach(async () => {
tmp = await createTempProject("persist")
})
@@ -103,6 +118,68 @@ describe("review persistence — round-trip", () => {
})
})
+describe("lint persistence — round-trip", () => {
+ it("save then load returns identical items", async () => {
+ const items: LintItem[] = [
+ makeLint({ id: "lint-1", page: "page-a.md" }),
+ makeLint({ id: "lint-2", page: "page-b.md", type: "broken-link", severity: "warning" }),
+ ]
+ await saveLintItems(tmp.path, items)
+ const loaded = await loadLintItems(tmp.path)
+ expect(loaded).toEqual(items)
+ })
+
+ it("creates the .llm-wiki directory on first save", async () => {
+ expect(await fileExists(`${tmp.path}/.llm-wiki`)).toBe(false)
+ await saveLintItems(tmp.path, [makeLint()])
+ expect(await fileExists(`${tmp.path}/.llm-wiki/lint.json`)).toBe(true)
+ })
+
+ it("returns empty array when the file is absent", async () => {
+ const loaded = await loadLintItems(tmp.path)
+ expect(loaded).toEqual([])
+ })
+
+ it("returns empty array when the file is corrupted JSON", async () => {
+ await writeFileRaw(`${tmp.path}/.llm-wiki/lint.json`, "{not valid json")
+ const loaded = await loadLintItems(tmp.path)
+ expect(loaded).toEqual([])
+ })
+
+ it("preserves all LintItem fields through JSON round-trip including affectedPages", async () => {
+ const items: LintItem[] = [
+ {
+ id: "lint-semantic-1",
+ type: "semantic",
+ severity: "warning",
+ page: "entities/transformer.md",
+ detail: "contradiction: conflicting claims",
+ affectedPages: ["a.md", "b.md"],
+ createdAt: 1234567890,
+ },
+ ]
+ await saveLintItems(tmp.path, items)
+ const loaded = await loadLintItems(tmp.path)
+ expect(loaded).toEqual(items)
+ expect(loaded[0].affectedPages).toEqual(["a.md", "b.md"])
+ })
+
+ it("overwrites existing file on subsequent saves", async () => {
+ await saveLintItems(tmp.path, [makeLint({ id: "lint-old", page: "old.md" })])
+ await saveLintItems(tmp.path, [makeLint({ id: "lint-new", page: "new.md" })])
+ const loaded = await loadLintItems(tmp.path)
+ expect(loaded).toHaveLength(1)
+ expect(loaded[0].page).toBe("new.md")
+ })
+
+ it("normalizes Windows-style paths in projectPath", async () => {
+ const windowsy = tmp.path.replace(/\//g, "\\")
+ await saveLintItems(windowsy, [makeLint({ id: "lint-1" })])
+ const loaded = await loadLintItems(windowsy)
+ expect(loaded).toHaveLength(1)
+ })
+})
+
describe("chat persistence — round-trip (new format)", () => {
function makeConv(id: string, title: string = "conv"): Conversation {
return { id, title, createdAt: 0, updatedAt: 1 }
diff --git a/src/lib/persist.ts b/src/lib/persist.ts
index 443900de..1acbb371 100644
--- a/src/lib/persist.ts
+++ b/src/lib/persist.ts
@@ -1,5 +1,6 @@
import { writeFile, readFile, createDirectory } from "@/commands/fs"
import type { ReviewItem } from "@/stores/review-store"
+import type { LintItem } from "@/stores/lint-store"
import type { DisplayMessage, Conversation } from "@/stores/chat-store"
import { normalizePath } from "@/lib/path-utils"
@@ -24,6 +25,22 @@ export async function loadReviewItems(projectPath: string): Promise<ReviewItem[]
}
}
+export async function saveLintItems(projectPath: string, items: LintItem[]): Promise<void> {
+ const pp = normalizePath(projectPath)
+ await ensureDir(pp)
+ await writeFile(`${pp}/.llm-wiki/lint.json`, JSON.stringify(items, null, 2))
+}
+
+export async function loadLintItems(projectPath: string): Promise<LintItem[]> {
+ const pp = normalizePath(projectPath)
+ try {
+ const content = await readFile(`${pp}/.llm-wiki/lint.json`)
+ return JSON.parse(content) as LintItem[]
+ } catch {
+ return []
+ }
+}
+
interface PersistedChatData {
conversations: Conversation[]
messages: DisplayMessage[]
diff --git a/src/stores/lint-store.test.ts b/src/stores/lint-store.test.ts
new file mode 100644
index 00000000..74524d78
--- /dev/null
+++ b/src/stores/lint-store.test.ts
@@ -0,0 +1,112 @@
+import { describe, it, expect, beforeEach } from "vitest"
+import type { LintResult } from "@/lib/lint"
+import { useLintStore, type LintItem } from "./lint-store"
+
+function makeLintResult(overrides: Partial<Omit<LintResult, "type" | "severity" | "page" | "detail">> & { type?: LintResult["type"]; severity?: LintResult["severity"]; page?: string } = {}): LintResult {
+ return {
+ type: "orphan",
+ severity: "info",
+ page: "test-page.md",
+ detail: "test detail",
+ ...overrides,
+ }
+}
+
+beforeEach(() => {
+ useLintStore.setState({ items: [] })
+})
+
+describe("lint-store addItems", () => {
+ it("converts LintResult[] to LintItem[] with generated id and createdAt", () => {
+ const results = [makeLintResult({ page: "page-a.md" })]
+ useLintStore.getState().addItems(results)
+ const items = useLintStore.getState().items
+ expect(items).toHaveLength(1)
+ expect(items[0].id).toMatch(/^lint-\d+$/)
+ expect(items[0].createdAt).toBeTypeOf("number")
+ expect(items[0].page).toBe("page-a.md")
+ })
+
+ it("adds multiple LintResult items in one call", () => {
+ const results = [
+ makeLintResult({ page: "page-a.md", type: "orphan" }),
+ makeLintResult({ page: "page-b.md", type: "broken-link", severity: "warning" }),
+ makeLintResult({ page: "page-c.md", type: "no-outlinks" }),
+ ]
+ useLintStore.getState().addItems(results)
+ expect(useLintStore.getState().items).toHaveLength(3)
+ })
+
+ it("preserves type, severity, page, detail, affectedPages from LintResult", () => {
+ const results: LintResult[] = [
+ {
+ type: "semantic",
+ severity: "warning",
+ page: "entities/transformer.md",
+ detail: "contradiction: conflicting claims about model size",
+ affectedPages: ["a.md", "b.md"],
+ },
+ ]
+ useLintStore.getState().addItems(results)
+ const item = useLintStore.getState().items[0]
+ expect(item.type).toBe("semantic")
+ expect(item.severity).toBe("warning")
+ 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"])
+ })
+})
+
+describe("lint-store setItems", () => {
+ it("replaces all items with the given array", () => {
+ useLintStore.getState().addItems([makeLintResult({ page: "existing.md" })])
+ const incoming: LintItem[] = [
+ { id: "lint-100", type: "orphan", severity: "info", page: "new.md", detail: "d", createdAt: 999 },
+ ]
+ useLintStore.getState().setItems(incoming)
+ expect(useLintStore.getState().items).toHaveLength(1)
+ expect(useLintStore.getState().items[0].page).toBe("new.md")
+ })
+
+ it("can set empty array to clear items", () => {
+ useLintStore.getState().addItems([makeLintResult(), makeLintResult()])
+ useLintStore.getState().setItems([])
+ expect(useLintStore.getState().items).toHaveLength(0)
+ })
+})
+
+describe("lint-store removeItem", () => {
+ it("removes the item with the given id", () => {
+ useLintStore.getState().addItems([makeLintResult({ page: "to-remove.md" })])
+ const id = useLintStore.getState().items[0].id
+ useLintStore.getState().removeItem(id)
+ expect(useLintStore.getState().items).toHaveLength(0)
+ })
+
+ it("removing a non-existent id is a no-op", () => {
+ useLintStore.getState().addItems([makeLintResult()])
+ expect(() => useLintStore.getState().removeItem("nonexistent")).not.toThrow()
+ expect(useLintStore.getState().items).toHaveLength(1)
+ })
+
+ it("only removes the item with the matching id", () => {
+ useLintStore.getState().addItems([makeLintResult({ page: "keep.md" }), makeLintResult({ page: "remove.md" })])
+ const ids = useLintStore.getState().items.map((i) => i.id)
+ useLintStore.getState().removeItem(ids[1])
+ const remaining = useLintStore.getState().items
+ expect(remaining).toHaveLength(1)
+ expect(remaining[0].page).toBe("keep.md")
+ })
+})
+
+describe("lint-store clearItems", () => {
+ it("removes all items", () => {
+ useLintStore.getState().addItems([makeLintResult(), makeLintResult(), makeLintResult()])
+ useLintStore.getState().clearItems()
+ expect(useLintStore.getState().items).toHaveLength(0)
+ })
+
+ it("clearItems on already-empty store is safe", () => {
+ expect(() => useLintStore.getState().clearItems()).not.toThrow()
+ })
+})
\ No newline at end of file
diff --git a/src/stores/lint-store.ts b/src/stores/lint-store.ts
new file mode 100644
index 00000000..2cd3785f
--- /dev/null
+++ b/src/stores/lint-store.ts
@@ -0,0 +1,52 @@
+import { create } from "zustand"
+import type { LintResult } from "@/lib/lint"
+
+export interface LintItem {
+ id: string
+ type: LintResult["type"]
+ severity: LintResult["severity"]
+ page: string
+ detail: string
+ affectedPages?: string[]
+ createdAt: number
+}
+
+function lintResultToItem(result: LintResult): LintItem {
+ return {
+ type: result.type,
+ severity: result.severity,
+ page: result.page,
+ detail: result.detail,
+ affectedPages: result.affectedPages,
+ id: `lint-${++counter}`,
+ createdAt: Date.now(),
+ }
+}
+
+interface LintState {
+ items: LintItem[]
+ setItems: (items: LintItem[]) => void
+ addItems: (results: LintResult[]) => void
+ removeItem: (id: string) => void
+ clearItems: () => void
+}
+
+let counter = 0
+
+export const useLintStore = create<LintState>((set) => ({
+ items: [],
+
+ setItems: (items) => set({ items }),
+
+ addItems: (results) =>
+ set((state) => ({
+ items: [...state.items, ...results.map(lintResultToItem)],
+ })),
+
+ removeItem: (id) =>
+ set((state) => ({
+ items: state.items.filter((item) => item.id !== id),
+ })),
+
+ clearItems: () => set({ items: [] }),
+}))
\ No newline at end of file