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: maintenance section with duplicate detection + serial merge queue

nash_sua4ab180e557c
diff --git a/src/App.tsx b/src/App.tsx
index eb86f332..e4f63f5e 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -271,6 +271,12 @@ function App() {
console.error("Failed to restore ingest queue:", err)
)
})
+ // Same handshake for the dedup-merge queue.
+ import("@/lib/dedup-queue").then(({ restoreQueue }) => {
+ restoreQueue(proj.id, proj.path).catch((err) =>
+ console.error("Failed to restore dedup queue:", err)
+ )
+ })
// Notify local clip server of the current project + all recent projects
fetch("http://127.0.0.1:19827/project", {
method: "POST",
diff --git a/src/components/settings/sections/maintenance-section.tsx b/src/components/settings/sections/maintenance-section.tsx
new file mode 100644
index 00000000..dc7ccc5c
--- /dev/null
+++ b/src/components/settings/sections/maintenance-section.tsx
@@ -0,0 +1,616 @@
+import { useCallback, useEffect, useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import {
+ Wrench,
+ Loader2,
+ AlertTriangle,
+ CheckCircle2,
+ XCircle,
+ Trash2,
+ RotateCcw,
+ Clock,
+} from "lucide-react"
+import { Button } from "@/components/ui/button"
+import { Label } from "@/components/ui/label"
+import { useWikiStore } from "@/stores/wiki-store"
+import { hasUsableLlm } from "@/lib/has-usable-llm"
+import { runDuplicateDetection } from "@/lib/dedup-runner"
+import { addNotDuplicate } from "@/lib/dedup-storage"
+import {
+ enqueueMerge,
+ cancelTask,
+ retryTask,
+ getQueue,
+ groupKey,
+ type DedupTask,
+} from "@/lib/dedup-queue"
+import type { DuplicateGroup } from "@/lib/dedup"
+
+interface GroupUiEntry {
+ group: DuplicateGroup
+ canonicalSlug: string
+ /** Becomes true when the user marks the group as "not duplicates"
+ * in this session — the card transitions to skipped state. */
+ skipped: boolean
+}
+
+/** Match a card to its task in the queue (if any) by slug-set. */
+function findTaskForGroup(
+ tasks: readonly DedupTask[],
+ slugs: readonly string[],
+): DedupTask | undefined {
+ const key = groupKey(slugs)
+ return tasks.find((t) => groupKey(t.group.slugs) === key)
+}
+
+export function MaintenanceSection() {
+ const { t } = useTranslation()
+ const llmConfig = useWikiStore((s) => s.llmConfig)
+ const project = useWikiStore((s) => s.project)
+
+ const [scanning, setScanning] = useState(false)
+ const [scanError, setScanError] = useState<string | null>(null)
+ const [groups, setGroups] = useState<GroupUiEntry[]>([])
+ const [scanCompleted, setScanCompleted] = useState(false)
+
+ // Poll the queue at 1Hz so the UI reflects pending → processing →
+ // failed transitions and cross-window queue activity (e.g. a merge
+ // that completed while the user was on a different settings tab).
+ // Same pattern activity-panel uses for ingest-queue.
+ const [tasks, setTasks] = useState<readonly DedupTask[]>([])
+ useEffect(() => {
+ setTasks([...getQueue()])
+ const id = setInterval(() => setTasks([...getQueue()]), 1000)
+ return () => clearInterval(id)
+ }, [])
+
+ const llmReady = hasUsableLlm(llmConfig)
+ const projectReady = !!project
+
+ const handleScan = useCallback(async () => {
+ if (!project) return
+ setScanning(true)
+ setScanError(null)
+ setGroups([])
+ setScanCompleted(false)
+ try {
+ const detected = await runDuplicateDetection(project.path, llmConfig)
+ setGroups(
+ detected.map((g) => ({
+ group: g,
+ canonicalSlug: g.slugs[0],
+ skipped: false,
+ })),
+ )
+ setScanCompleted(true)
+ } catch (err) {
+ setScanError(err instanceof Error ? err.message : String(err))
+ } finally {
+ setScanning(false)
+ }
+ }, [project, llmConfig])
+
+ const handleCanonicalChange = useCallback(
+ (idx: number, slug: string) => {
+ setGroups((prev) =>
+ prev.map((g, i) => (i === idx ? { ...g, canonicalSlug: slug } : g)),
+ )
+ },
+ [],
+ )
+
+ const handleEnqueue = useCallback(
+ async (entry: GroupUiEntry) => {
+ if (!project) return
+ try {
+ await enqueueMerge(project.id, entry.group, entry.canonicalSlug)
+ // Refresh immediately so the card flips to "queued" without
+ // waiting for the next 1s poll tick.
+ setTasks([...getQueue()])
+ } catch (err) {
+ console.error("[Maintenance] enqueue failed:", err)
+ }
+ },
+ [project],
+ )
+
+ const handleCancel = useCallback(async (taskId: string) => {
+ await cancelTask(taskId)
+ setTasks([...getQueue()])
+ }, [])
+
+ const handleRetry = useCallback(async (taskId: string) => {
+ await retryTask(taskId)
+ setTasks([...getQueue()])
+ }, [])
+
+ const handleNotDuplicate = useCallback(
+ async (idx: number) => {
+ if (!project) return
+ const entry = groups[idx]
+ if (!entry) return
+ try {
+ await addNotDuplicate(project.path, entry.group.slugs)
+ setGroups((prev) =>
+ prev.map((g, i) => (i === idx ? { ...g, skipped: true } : g)),
+ )
+ } catch (err) {
+ console.error("[Maintenance] addNotDuplicate failed:", err)
+ }
+ },
+ [project, groups],
+ )
+
+ // Drive each card's status from the queue.
+ // - Card not in queue + not skipped → idle, can merge / dismiss
+ // - Task pending → "Queued (N ahead)"
+ // - Task processing → "Merging…"
+ // - Task gone (after success) → "Merged" (queue removes done tasks
+ // immediately, so we only know it succeeded if we observed it
+ // in-flight before. Track that with a session-local set.)
+ // - Task failed → show error + retry / delete.
+ const [recentlyMergedKeys, setRecentlyMergedKeys] = useState<Set<string>>(
+ () => new Set(),
+ )
+
+ useEffect(() => {
+ // Detect transitions out of the queue: a slug-set we saw last
+ // tick is now gone → it completed (cancelled paths also remove,
+ // but only with explicit user action that re-renders separately).
+ setRecentlyMergedKeys((prev) => {
+ const currentKeys = new Set(tasks.map((t) => groupKey(t.group.slugs)))
+ let changed = false
+ const next = new Set(prev)
+ for (const g of groups) {
+ const k = groupKey(g.group.slugs)
+ const wasInFlight = lastSeenTaskKeysRef.current.has(k)
+ if (wasInFlight && !currentKeys.has(k) && !next.has(k)) {
+ next.add(k)
+ changed = true
+ }
+ }
+ lastSeenTaskKeysRef.current = currentKeys
+ return changed ? next : prev
+ })
+ // We intentionally only re-run when tasks change — the closure
+ // over `groups` is fine because newly-scanned groups can't be
+ // "recently merged" until they've been observed in-flight first.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [tasks])
+ const lastSeenTaskKeysRef = useRefInit<Set<string>>(() => new Set())
+
+ // Pending position helper: "queued (N ahead)" — count pending tasks
+ // before this one in arrival order.
+ const pendingPositionByTaskId = useMemo(() => {
+ const positions = new Map<string, number>()
+ let position = 0
+ for (const t of tasks) {
+ if (t.status === "pending") {
+ positions.set(t.id, position)
+ position++
+ }
+ }
+ return positions
+ }, [tasks])
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">
+ {t("settings.sections.maintenance.title", { defaultValue: "Maintenance" })}
+ </h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t("settings.sections.maintenance.description", {
+ defaultValue:
+ "Tools for cleaning up the wiki — detect and merge duplicate entities/concepts that the LLM created under different names across re-ingests.",
+ })}
+ </p>
+ </div>
+
+ <div className="space-y-3 rounded-lg border border-border/60 bg-muted/20 p-4">
+ <div className="flex items-center gap-2">
+ <Wrench className="h-4 w-4 text-muted-foreground" />
+ <h3 className="text-sm font-semibold">
+ {t("settings.sections.maintenance.dedup.title", {
+ defaultValue: "Detect duplicate entities / concepts",
+ })}
+ </h3>
+ </div>
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ {t("settings.sections.maintenance.dedup.description", {
+ defaultValue:
+ "Asks the LLM to scan all entity / concept pages and group ones that likely refer to the same topic under different names (English vs Chinese, plural vs singular, abbreviation vs full form). You confirm each group before merging. Merges are queued and run one at a time so cross-references stay consistent.",
+ })}
+ </p>
+
+ {!projectReady && (
+ <p className="text-xs text-amber-700 dark:text-amber-400">
+ {t("settings.sections.maintenance.noProject", {
+ defaultValue: "Open a project first.",
+ })}
+ </p>
+ )}
+ {projectReady && !llmReady && (
+ <p className="text-xs text-amber-700 dark:text-amber-400">
+ {t("settings.sections.maintenance.noLlm", {
+ defaultValue: "Configure an LLM provider first.",
+ })}
+ </p>
+ )}
+
+ <Button
+ onClick={() => void handleScan()}
+ disabled={scanning || !projectReady || !llmReady}
+ >
+ {scanning ? (
+ <>
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t("settings.sections.maintenance.dedup.scanning", {
+ defaultValue: "Scanning…",
+ })}
+ </>
+ ) : (
+ t("settings.sections.maintenance.dedup.scanButton", {
+ defaultValue: "Scan for duplicates",
+ })
+ )}
+ </Button>
+
+ {scanError && (
+ <div className="flex items-start gap-1.5 rounded border border-rose-500/40 bg-rose-500/5 px-2 py-1.5 text-xs text-rose-700 dark:text-rose-400">
+ <XCircle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <div>{scanError}</div>
+ </div>
+ )}
+
+ {scanCompleted && groups.length === 0 && !scanError && (
+ <div className="flex items-start gap-1.5 rounded border border-emerald-500/40 bg-emerald-500/5 px-2 py-1.5 text-xs text-emerald-700 dark:text-emerald-400">
+ <CheckCircle2 className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <div>
+ {t("settings.sections.maintenance.dedup.noneFound", {
+ defaultValue: "No duplicate groups found. The wiki is clean.",
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+
+ <QueueOrphanList
+ tasks={tasks}
+ groups={groups}
+ onCancel={(id) => void handleCancel(id)}
+ onRetry={(id) => void handleRetry(id)}
+ pendingPositionByTaskId={pendingPositionByTaskId}
+ />
+
+ {groups.map((entry, idx) => {
+ const task = findTaskForGroup(tasks, entry.group.slugs)
+ const merged = recentlyMergedKeys.has(groupKey(entry.group.slugs))
+ return (
+ <DuplicateGroupCard
+ key={entry.group.slugs.join(",")}
+ entry={entry}
+ task={task}
+ merged={merged}
+ pendingPosition={
+ task && task.status === "pending"
+ ? pendingPositionByTaskId.get(task.id) ?? 0
+ : 0
+ }
+ onCanonicalChange={(slug) => handleCanonicalChange(idx, slug)}
+ onEnqueue={() => void handleEnqueue(entry)}
+ onCancel={() => task && void handleCancel(task.id)}
+ onRetry={() => task && void handleRetry(task.id)}
+ onNotDuplicate={() => void handleNotDuplicate(idx)}
+ />
+ )
+ })}
+ </div>
+ )
+}
+
+// --- helpers ---------------------------------------------------------------
+
+/** A useRef variant that initializes lazily — avoids constructing a new
+ * Set on every render. Kept inline since it's only used here. */
+function useRefInit<T>(init: () => T): { current: T } {
+ // `useState` returning a ref-shaped object lets us mutate `.current`
+ // without triggering re-renders, which is exactly the ref semantics
+ // we want for the "last seen task keys" tracking above.
+ // eslint-disable-next-line react-hooks/rules-of-hooks
+ const [ref] = useState<{ current: T }>(() => ({ current: init() }))
+ return ref
+}
+
+interface QueueOrphanListProps {
+ tasks: readonly DedupTask[]
+ groups: GroupUiEntry[]
+ onCancel: (taskId: string) => void
+ onRetry: (taskId: string) => void
+ pendingPositionByTaskId: Map<string, number>
+}
+
+/**
+ * Render queued tasks that don't have a matching card on screen. This
+ * happens after the user closes the Maintenance pane and re-opens it,
+ * or after an app restart with pending tasks: those tasks are real
+ * but the user hasn't re-scanned, so without this list they'd be
+ * invisible.
+ */
+function QueueOrphanList({
+ tasks,
+ groups,
+ onCancel,
+ onRetry,
+ pendingPositionByTaskId,
+}: QueueOrphanListProps) {
+ const { t } = useTranslation()
+ const groupKeys = new Set(groups.map((g) => groupKey(g.group.slugs)))
+ const orphans = tasks.filter((t) => !groupKeys.has(groupKey(t.group.slugs)))
+
+ if (orphans.length === 0) return null
+
+ return (
+ <div className="space-y-2 rounded-lg border border-border/60 bg-muted/10 p-4">
+ <div className="flex items-center gap-2">
+ <Clock className="h-4 w-4 text-muted-foreground" />
+ <h3 className="text-sm font-semibold">
+ {t("settings.sections.maintenance.dedup.queueTitle", {
+ defaultValue: "In-progress merges",
+ })}
+ </h3>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.maintenance.dedup.queueDescription", {
+ defaultValue:
+ "Tasks queued from a previous scan that haven't finished yet. Merges run one at a time.",
+ })}
+ </p>
+ {orphans.map((task) => (
+ <div
+ key={task.id}
+ className="flex flex-wrap items-center gap-2 rounded border border-border/40 bg-background px-3 py-2 text-xs"
+ >
+ <code className="font-mono">{task.group.slugs.join(" + ")}</code>
+ <span className="text-muted-foreground">
+ →{" "}
+ <code className="font-mono">{task.canonicalSlug}</code>
+ </span>
+ <span className="ml-auto inline-flex items-center gap-1">
+ <TaskStatusChip
+ task={task}
+ pendingPosition={pendingPositionByTaskId.get(task.id) ?? 0}
+ />
+ {task.status === "failed" && (
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => onRetry(task.id)}
+ >
+ <RotateCcw className="h-3.5 w-3.5" />
+ {t("settings.sections.maintenance.dedup.retry", {
+ defaultValue: "Retry",
+ })}
+ </Button>
+ )}
+ <Button size="sm" variant="ghost" onClick={() => onCancel(task.id)}>
+ <Trash2 className="h-3.5 w-3.5" />
+ {t("settings.sections.maintenance.dedup.delete", {
+ defaultValue: "Delete",
+ })}
+ </Button>
+ </span>
+ {task.error && task.status === "failed" && (
+ <div className="basis-full rounded border border-rose-500/40 bg-rose-500/5 px-2 py-1 text-rose-700 dark:text-rose-400">
+ {task.error}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+interface ChipProps {
+ task: DedupTask
+ pendingPosition: number
+}
+
+function TaskStatusChip({ task, pendingPosition }: ChipProps) {
+ const { t } = useTranslation()
+ if (task.status === "processing") {
+ return (
+ <span className="inline-flex items-center gap-1 rounded bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-amber-700 dark:text-amber-400">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ {t("settings.sections.maintenance.dedup.merging", {
+ defaultValue: "Merging…",
+ })}
+ </span>
+ )
+ }
+ if (task.status === "pending") {
+ if (pendingPosition === 0) {
+ return (
+ <span className="inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase text-muted-foreground">
+ {t("settings.sections.maintenance.dedup.queued", {
+ defaultValue: "Queued",
+ })}
+ </span>
+ )
+ }
+ return (
+ <span className="inline-flex items-center gap-1 rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase text-muted-foreground">
+ {t("settings.sections.maintenance.dedup.queuedAhead", {
+ defaultValue: "Queued ({{n}} ahead)",
+ n: pendingPosition,
+ })}
+ </span>
+ )
+ }
+ if (task.status === "failed") {
+ return (
+ <span className="inline-flex items-center gap-1 rounded bg-rose-500/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-rose-700 dark:text-rose-400">
+ <AlertTriangle className="h-3 w-3" />
+ {t("settings.sections.maintenance.dedup.failed", {
+ defaultValue: "Failed ({{retries}}/3)",
+ retries: task.retryCount,
+ })}
+ </span>
+ )
+ }
+ return null
+}
+
+interface CardProps {
+ entry: GroupUiEntry
+ task: DedupTask | undefined
+ merged: boolean
+ pendingPosition: number
+ onCanonicalChange: (slug: string) => void
+ onEnqueue: () => void
+ onCancel: () => void
+ onRetry: () => void
+ onNotDuplicate: () => void
+}
+
+function DuplicateGroupCard({
+ entry,
+ task,
+ merged,
+ pendingPosition,
+ onCanonicalChange,
+ onEnqueue,
+ onCancel,
+ onRetry,
+ onNotDuplicate,
+}: CardProps) {
+ const { t } = useTranslation()
+ const { group, canonicalSlug, skipped } = entry
+
+ const inFlight = !!task && (task.status === "pending" || task.status === "processing")
+ const failed = !!task && task.status === "failed"
+ const finished = merged || skipped
+
+ const confidenceClass =
+ group.confidence === "high"
+ ? "bg-emerald-500/15 text-emerald-700 dark:text-emerald-400"
+ : group.confidence === "medium"
+ ? "bg-amber-500/15 text-amber-700 dark:text-amber-400"
+ : "bg-muted text-muted-foreground"
+
+ return (
+ <div
+ className={`space-y-3 rounded-lg border px-4 py-3 ${
+ finished ? "border-border/40 bg-muted/10 opacity-60" : "border-border bg-background"
+ }`}
+ >
+ <div className="flex items-center gap-2">
+ <span className={`rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase ${confidenceClass}`}>
+ {group.confidence}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {t("settings.sections.maintenance.dedup.candidates", {
+ defaultValue: "{{n}} candidates",
+ n: group.slugs.length,
+ })}
+ </span>
+ {merged && (
+ <span className="ml-auto inline-flex items-center gap-1 text-xs text-emerald-700 dark:text-emerald-400">
+ <CheckCircle2 className="h-3.5 w-3.5" />
+ {t("settings.sections.maintenance.dedup.merged", { defaultValue: "Merged" })}
+ </span>
+ )}
+ {skipped && (
+ <span className="ml-auto inline-flex items-center gap-1 text-xs text-muted-foreground">
+ {t("settings.sections.maintenance.dedup.skipped", { defaultValue: "Marked not duplicates" })}
+ </span>
+ )}
+ {task && !finished && (
+ <span className="ml-auto">
+ <TaskStatusChip task={task} pendingPosition={pendingPosition} />
+ </span>
+ )}
+ </div>
+
+ {group.reason && (
+ <div className="text-xs italic leading-relaxed text-muted-foreground">{group.reason}</div>
+ )}
+
+ {!finished && (
+ <>
+ <div className="space-y-1.5">
+ <Label className="text-xs">
+ {t("settings.sections.maintenance.dedup.canonicalLabel", {
+ defaultValue: "Keep this slug as canonical:",
+ })}
+ </Label>
+ {group.slugs.map((slug) => (
+ <label
+ key={slug}
+ className="flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 text-sm hover:bg-accent"
+ >
+ <input
+ type="radio"
+ name={`canonical-${group.slugs.join(",")}`}
+ checked={canonicalSlug === slug}
+ onChange={() => onCanonicalChange(slug)}
+ disabled={inFlight}
+ />
+ <code className="font-mono text-xs">{slug}</code>
+ </label>
+ ))}
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ {!task && (
+ <>
+ <Button size="sm" onClick={onEnqueue}>
+ {t("settings.sections.maintenance.dedup.mergeButton", {
+ defaultValue: "Merge into {{slug}}",
+ slug: canonicalSlug,
+ })}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onNotDuplicate}>
+ {t("settings.sections.maintenance.dedup.notDuplicates", {
+ defaultValue: "Not duplicates",
+ })}
+ </Button>
+ </>
+ )}
+ {inFlight && (
+ <Button size="sm" variant="ghost" onClick={onCancel}>
+ <Trash2 className="h-3.5 w-3.5" />
+ {t("settings.sections.maintenance.dedup.cancel", {
+ defaultValue: "Cancel",
+ })}
+ </Button>
+ )}
+ {failed && (
+ <>
+ <Button size="sm" onClick={onRetry}>
+ <RotateCcw className="h-3.5 w-3.5" />
+ {t("settings.sections.maintenance.dedup.retry", {
+ defaultValue: "Retry",
+ })}
+ </Button>
+ <Button size="sm" variant="ghost" onClick={onCancel}>
+ <Trash2 className="h-3.5 w-3.5" />
+ {t("settings.sections.maintenance.dedup.delete", {
+ defaultValue: "Delete",
+ })}
+ </Button>
+ </>
+ )}
+ </div>
+ </>
+ )}
+
+ {failed && task?.error && (
+ <div className="flex items-start gap-1.5 rounded border border-rose-500/40 bg-rose-500/5 px-2 py-1.5 text-xs text-rose-700 dark:text-rose-400">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <div>{task.error}</div>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index 2a2b8b18..deb8689c 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -9,6 +9,7 @@ import {
Image as ImageIcon,
Network,
History,
+ Wrench,
} from "lucide-react"
import { useTranslation } from "react-i18next"
import { invoke } from "@tauri-apps/api/core"
@@ -27,6 +28,7 @@ import { OutputSection } from "./sections/output-section"
import { InterfaceSection } from "./sections/interface-section"
import { NetworkSection } from "./sections/network-section"
import { ChangelogSection } from "./sections/changelog-section"
+import { MaintenanceSection } from "./sections/maintenance-section"
import { AboutSection } from "./sections/about-section"
type CategoryId =
@@ -37,6 +39,7 @@ type CategoryId =
| "network"
| "output"
| "interface"
+ | "maintenance"
| "changelog"
| "about"
@@ -57,6 +60,7 @@ const CATEGORIES: Category[] = [
{ id: "network", labelKey: "settings.categories.network", icon: Network },
{ id: "output", labelKey: "settings.categories.output", icon: Languages },
{ id: "interface", labelKey: "settings.categories.interface", icon: Palette },
+ { id: "maintenance", labelKey: "settings.categories.maintenance", icon: Wrench },
{ id: "changelog", labelKey: "settings.categories.changelog", icon: History },
{ id: "about", labelKey: "settings.categories.about", icon: Info },
]
@@ -286,6 +290,8 @@ export function SettingsView() {
return <OutputSection draft={draft} setDraft={setDraft} />
case "interface":
return <InterfaceSection draft={draft} setDraft={setDraft} />
+ case "maintenance":
+ return <MaintenanceSection />
case "changelog":
return <ChangelogSection />
case "about":
@@ -352,8 +358,8 @@ export function SettingsView() {
{/* Global Save bar hidden for sections that persist inline:
- "llm" saves per-row on every edit (independent per-preset state)
- - "about" has no editable fields */}
- {active !== "about" && active !== "llm" && (
+ - "about" / "maintenance" have no draft-bound fields */}
+ {active !== "about" && active !== "llm" && active !== "maintenance" && (
<div className="shrink-0 border-t bg-background/80 backdrop-blur px-8 py-3">
<div className="mx-auto flex max-w-2xl items-center justify-between gap-4">
<p className="text-xs text-muted-foreground">
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 53dc4397..3d13c3cc 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -110,6 +110,7 @@
"network": "Network",
"output": "Output",
"interface": "Interface",
+ "maintenance": "Maintenance",
"changelog": "Changelog",
"about": "About"
},
@@ -210,6 +211,34 @@
"uiLanguage": "UI Language",
"uiLanguageHint": "Affects labels, buttons, and other UI strings only. The AI output language is set separately in Output Preferences."
},
+ "maintenance": {
+ "title": "Maintenance",
+ "description": "Tools for cleaning up the wiki — detect and merge duplicate entities/concepts that the LLM created under different names across re-ingests.",
+ "noProject": "Open a project first.",
+ "noLlm": "Configure an LLM provider first.",
+ "dedup": {
+ "title": "Detect duplicate entities / concepts",
+ "description": "Asks the LLM to scan all entity / concept pages and group ones that likely refer to the same topic under different names (English vs Chinese, plural vs singular, abbreviation vs full form). You confirm each group before merging. Merges are queued and run one at a time so cross-references stay consistent.",
+ "scanButton": "Scan for duplicates",
+ "scanning": "Scanning…",
+ "noneFound": "No duplicate groups found. The wiki is clean.",
+ "candidates": "{{n}} candidates",
+ "canonicalLabel": "Keep this slug as canonical:",
+ "mergeButton": "Merge into {{slug}}",
+ "merging": "Merging…",
+ "queued": "Queued",
+ "queuedAhead": "Queued ({{n}} ahead)",
+ "failed": "Failed ({{retries}}/3)",
+ "cancel": "Cancel",
+ "retry": "Retry",
+ "delete": "Delete",
+ "queueTitle": "In-progress merges",
+ "queueDescription": "Tasks queued from a previous scan that haven't finished yet. Merges run one at a time.",
+ "notDuplicates": "Not duplicates",
+ "merged": "Merged",
+ "skipped": "Marked not duplicates"
+ }
+ },
"changelog": {
"title": "Changelog",
"description": "Notable user-visible changes in each released version, newest first."
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 14f5a732..fd5b06f4 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -110,6 +110,7 @@
"network": "网络",
"output": "输出偏好",
"interface": "界面",
+ "maintenance": "维护",
"changelog": "更新日志",
"about": "关于"
},
@@ -210,6 +211,34 @@
"uiLanguage": "UI 语言",
"uiLanguageHint": "只影响按钮、标签这些 UI 文案,不影响 AI 输出语言(那个在\"输出偏好\"里单独设置)。"
},
+ "maintenance": {
+ "title": "维护",
+ "description": "清理 wiki 的工具 —— 检测并合并 LLM 在多次再导入时用不同名字创建的重复实体 / 概念。",
+ "noProject": "请先打开一个项目。",
+ "noLlm": "请先配置 LLM 服务。",
+ "dedup": {
+ "title": "检测重复实体 / 概念",
+ "description": "让 LLM 扫描全部 entity / concept 页面,把可能指向同一主题但用了不同名字的页面分组(中英对照、单复数、缩写与全称等)。每一组都需要你确认后才会合并。合并任务会进入串行队列依次执行,避免交叉引用被并发改写覆盖。",
+ "scanButton": "扫描重复项",
+ "scanning": "扫描中…",
+ "noneFound": "未发现重复分组,wiki 很干净。",
+ "candidates": "{{n}} 个候选",
+ "canonicalLabel": "保留以下 slug 作为主条目:",
+ "mergeButton": "合并到 {{slug}}",
+ "merging": "合并中…",
+ "queued": "排队中",
+ "queuedAhead": "排队中(前面还有 {{n}} 个)",
+ "failed": "失败({{retries}}/3)",
+ "cancel": "取消",
+ "retry": "重试",
+ "delete": "删除",
+ "queueTitle": "进行中的合并",
+ "queueDescription": "上次扫描后排进队列、还未跑完的合并任务。每次只跑一个。",
+ "notDuplicates": "不是重复",
+ "merged": "已合并",
+ "skipped": "已标记为不重复"
+ }
+ },
"changelog": {
"title": "更新日志",
"description": "每个版本对用户可见的功能改动,最新版本在最前面。"
diff --git a/src/lib/dedup-queue.test.ts b/src/lib/dedup-queue.test.ts
new file mode 100644
index 00000000..d02bb022
--- /dev/null
+++ b/src/lib/dedup-queue.test.ts
@@ -0,0 +1,329 @@
+import { describe, it, expect, beforeEach, vi } from "vitest"
+import { createDeferred, flushMicrotasks } from "@/test-helpers/deferred"
+
+vi.mock("./dedup-runner", () => ({
+ executeMerge: vi.fn(),
+}))
+
+vi.mock("@/commands/fs", () => ({
+ readFile: vi.fn(),
+ writeFile: vi.fn(),
+}))
+
+const TEST_ID = "test-project-uuid"
+const TEST_PATH = "/project"
+const TEST_ID_B = "test-project-uuid-b"
+const TEST_PATH_B = "/project-b"
+const idToPath: Record<string, string> = {
+ [TEST_ID]: TEST_PATH,
+ [TEST_ID_B]: TEST_PATH_B,
+}
+vi.mock("@/lib/project-identity", () => ({
+ ensureProjectId: vi.fn(),
+ upsertProjectInfo: vi.fn(),
+ getProjectPathById: vi.fn(async (id: string) => idToPath[id] ?? null),
+ getProjectIdByPath: vi.fn(),
+ loadRegistry: vi.fn(),
+}))
+
+import {
+ enqueueMerge,
+ cancelTask,
+ retryTask,
+ clearQueueState,
+ getQueue,
+ getQueueSummary,
+ pauseQueue,
+ restoreQueue,
+} from "./dedup-queue"
+import { executeMerge } from "./dedup-runner"
+import { readFile, writeFile } from "@/commands/fs"
+import { useWikiStore } from "@/stores/wiki-store"
+import type { DuplicateGroup } from "./dedup"
+
+const mockExecuteMerge = vi.mocked(executeMerge)
+const mockReadFile = vi.mocked(readFile)
+const mockWriteFile = vi.mocked(writeFile)
+
+function makeGroup(slugs: string[]): DuplicateGroup {
+ return { slugs, confidence: "high", reason: "test" }
+}
+
+async function activate(id: string = TEST_ID): Promise<void> {
+ await restoreQueue(id, idToPath[id])
+}
+
+beforeEach(async () => {
+ clearQueueState()
+ mockExecuteMerge.mockReset()
+ mockReadFile.mockReset()
+ mockWriteFile.mockReset()
+ mockReadFile.mockRejectedValue(new Error("ENOENT"))
+ mockWriteFile.mockResolvedValue(undefined as unknown as void)
+
+ useWikiStore.getState().setLlmConfig({
+ provider: "openai",
+ apiKey: "test-key",
+ model: "gpt-4",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ })
+
+ await activate()
+})
+
+describe("dedup-queue — basic enqueue + processing", () => {
+ it("processes a queued merge and removes the task on success", async () => {
+ mockExecuteMerge.mockResolvedValue({
+ canonicalContent: "x",
+ canonicalPath: "wiki/entities/a.md",
+ rewrites: [],
+ pagesToDelete: [],
+ backup: [],
+ })
+
+ const id = await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ expect(id).toMatch(/^dedup-/)
+
+ await flushMicrotasks(20)
+
+ expect(mockExecuteMerge).toHaveBeenCalledOnce()
+ expect(getQueue()).toHaveLength(0)
+ })
+
+ it("persists pending queue to disk", async () => {
+ mockExecuteMerge.mockImplementation(() => new Promise(() => {}))
+ await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ await flushMicrotasks(2)
+
+ expect(mockWriteFile).toHaveBeenCalled()
+ const call = mockWriteFile.mock.calls.find(
+ (c) => typeof c[0] === "string" && c[0].includes("dedup-queue.json"),
+ )
+ expect(call).toBeTruthy()
+ })
+
+ it("dedupes on slug-set: re-enqueueing the same group returns the same id", async () => {
+ mockExecuteMerge.mockImplementation(() => new Promise(() => {}))
+ const id1 = await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ const id2 = await enqueueMerge(TEST_ID, makeGroup(["b", "a"]), "b")
+ expect(id2).toBe(id1)
+ expect(getQueue()).toHaveLength(1)
+ })
+
+ it("processes serially: second task only starts after first completes", async () => {
+ const d1 = createDeferred<void>()
+ const d2 = createDeferred<void>()
+ let calls = 0
+ mockExecuteMerge.mockImplementation(async () => {
+ calls++
+ const which = calls
+ await (which === 1 ? d1.promise : d2.promise)
+ return {
+ canonicalContent: "",
+ canonicalPath: "",
+ rewrites: [],
+ pagesToDelete: [],
+ backup: [],
+ }
+ })
+
+ await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ await enqueueMerge(TEST_ID, makeGroup(["c", "d"]), "c")
+ await flushMicrotasks(5)
+
+ expect(mockExecuteMerge).toHaveBeenCalledTimes(1)
+
+ d1.resolve()
+ await flushMicrotasks(20)
+ expect(mockExecuteMerge).toHaveBeenCalledTimes(2)
+
+ d2.resolve()
+ await flushMicrotasks(20)
+ expect(getQueue()).toHaveLength(0)
+ })
+})
+
+describe("dedup-queue — retries", () => {
+ it("retries on failure up to MAX_RETRIES (3) before marking failed", async () => {
+ mockExecuteMerge.mockRejectedValue(new Error("LLM boom"))
+
+ await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ await flushMicrotasks(40)
+
+ expect(mockExecuteMerge).toHaveBeenCalledTimes(3)
+ const tasks = getQueue()
+ expect(tasks).toHaveLength(1)
+ expect(tasks[0].status).toBe("failed")
+ expect(tasks[0].retryCount).toBe(3)
+ expect(tasks[0].error).toContain("LLM boom")
+ })
+
+ it("succeeds after a transient failure within retry budget", async () => {
+ mockExecuteMerge
+ .mockRejectedValueOnce(new Error("flaky"))
+ .mockRejectedValueOnce(new Error("flaky"))
+ .mockResolvedValueOnce({
+ canonicalContent: "",
+ canonicalPath: "",
+ rewrites: [],
+ pagesToDelete: [],
+ backup: [],
+ })
+
+ await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ await flushMicrotasks(40)
+
+ expect(mockExecuteMerge).toHaveBeenCalledTimes(3)
+ expect(getQueue()).toHaveLength(0)
+ })
+
+ it("retryTask resets a failed task to pending and runs it again", async () => {
+ mockExecuteMerge.mockRejectedValue(new Error("boom"))
+
+ const id = await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ await flushMicrotasks(40)
+ expect(getQueue()[0].status).toBe("failed")
+ expect(mockExecuteMerge).toHaveBeenCalledTimes(3)
+
+ mockExecuteMerge.mockResolvedValueOnce({
+ canonicalContent: "",
+ canonicalPath: "",
+ rewrites: [],
+ pagesToDelete: [],
+ backup: [],
+ })
+
+ await retryTask(id)
+ await flushMicrotasks(20)
+
+ expect(mockExecuteMerge).toHaveBeenCalledTimes(4)
+ expect(getQueue()).toHaveLength(0)
+ })
+})
+
+describe("dedup-queue — cancel / delete", () => {
+ it("cancelTask removes a pending task before it runs", async () => {
+ const d = createDeferred<void>()
+ mockExecuteMerge.mockImplementation(async () => {
+ await d.promise
+ return {
+ canonicalContent: "",
+ canonicalPath: "",
+ rewrites: [],
+ pagesToDelete: [],
+ backup: [],
+ }
+ })
+
+ const firstId = await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ const secondId = await enqueueMerge(TEST_ID, makeGroup(["c", "d"]), "c")
+ await flushMicrotasks(5)
+
+ // First is processing, second is pending — cancel the pending one.
+ expect(getQueue().find((t) => t.id === secondId)?.status).toBe("pending")
+ await cancelTask(secondId)
+ expect(getQueue().find((t) => t.id === secondId)).toBeUndefined()
+
+ d.resolve()
+ await flushMicrotasks(10)
+ expect(getQueue().find((t) => t.id === firstId)).toBeUndefined()
+ void firstId
+ })
+
+ it("cancelTask aborts an in-flight processing task", async () => {
+ let receivedSignal: AbortSignal | undefined
+ const d = createDeferred<never>()
+ mockExecuteMerge.mockImplementation(async (_pp, _g, _slug, _llm, opts) => {
+ receivedSignal = opts?.signal
+ // Reject when aborted
+ opts?.signal?.addEventListener("abort", () => {
+ d.reject(new Error("aborted"))
+ })
+ return d.promise
+ })
+
+ const id = await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ await flushMicrotasks(5)
+ expect(receivedSignal).toBeDefined()
+ expect(receivedSignal?.aborted).toBe(false)
+
+ await cancelTask(id)
+ expect(receivedSignal?.aborted).toBe(true)
+ expect(getQueue().find((t) => t.id === id)).toBeUndefined()
+ })
+})
+
+describe("dedup-queue — pauseQueue / restoreQueue", () => {
+ it("pauseQueue persists state, restoreQueue brings it back", async () => {
+ let captured = ""
+ mockWriteFile.mockImplementation(async (path: string, content: string) => {
+ if (path.includes("dedup-queue.json") && path.startsWith(TEST_PATH)) {
+ captured = content
+ }
+ })
+ // Hold execution so the task stays pending across pause.
+ mockExecuteMerge.mockImplementation(() => new Promise(() => {}))
+
+ await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ await flushMicrotasks(5)
+
+ await pauseQueue()
+ expect(getQueue()).toHaveLength(0)
+ expect(captured).toContain("\"status\": \"pending\"")
+
+ // Restore: read returns the captured content.
+ mockReadFile.mockImplementation(async (path: string) => {
+ if (path.startsWith(TEST_PATH)) return captured
+ throw new Error("ENOENT")
+ })
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ const restored = getQueue()
+ expect(restored).toHaveLength(1)
+ expect(restored[0].group.slugs).toEqual(["a", "b"])
+ })
+
+ it("restoreQueue reverts processing tasks to pending so they re-run", async () => {
+ const persisted = JSON.stringify([
+ {
+ id: "dedup-old",
+ projectId: TEST_ID,
+ group: { slugs: ["a", "b"], confidence: "high", reason: "x" },
+ canonicalSlug: "a",
+ status: "processing",
+ addedAt: 1,
+ error: null,
+ retryCount: 0,
+ },
+ ])
+ mockReadFile.mockImplementation(async (path: string) =>
+ path.startsWith(TEST_PATH) ? persisted : Promise.reject(new Error("ENOENT")),
+ )
+ mockExecuteMerge.mockResolvedValue({
+ canonicalContent: "",
+ canonicalPath: "",
+ rewrites: [],
+ pagesToDelete: [],
+ backup: [],
+ })
+
+ await restoreQueue(TEST_ID, TEST_PATH)
+ await flushMicrotasks(20)
+
+ expect(mockExecuteMerge).toHaveBeenCalledOnce()
+ expect(getQueue()).toHaveLength(0)
+ })
+
+ it("does not leak tasks across project switch", async () => {
+ mockExecuteMerge.mockImplementation(() => new Promise(() => {}))
+
+ await enqueueMerge(TEST_ID, makeGroup(["a", "b"]), "a")
+ expect(getQueueSummary().total).toBe(1)
+
+ await pauseQueue()
+ await restoreQueue(TEST_ID_B, TEST_PATH_B)
+ expect(getQueueSummary().total).toBe(0)
+ })
+})
diff --git a/src/lib/dedup-queue.ts b/src/lib/dedup-queue.ts
new file mode 100644
index 00000000..77867f68
--- /dev/null
+++ b/src/lib/dedup-queue.ts
@@ -0,0 +1,367 @@
+/**
+ * Persistent serial queue for duplicate-merge operations.
+ *
+ * Why a queue (and not just kicking off `executeMerge` from the click
+ * handler):
+ * - Merges rewrite cross-references across the entire wiki. Two
+ * concurrent merges race on the same files, last write wins, and
+ * half the rewrites silently disappear.
+ * - LLM calls take seconds; the user wants to queue several merges
+ * and walk away. The queue must survive app close so an
+ * interrupted merge resumes on next launch.
+ *
+ * Mirrors `ingest-queue.ts` almost line-for-line: same lifecycle
+ * (pause / restore on project switch), same persistence file shape,
+ * same retry-up-to-3 policy, same registry-based path resolution so
+ * a relocated project still finds its tasks.
+ */
+import { readFile, writeFile } from "@/commands/fs"
+import { useWikiStore } from "@/stores/wiki-store"
+import { normalizePath } from "@/lib/path-utils"
+import { getProjectPathById } from "@/lib/project-identity"
+import { hasUsableLlm } from "@/lib/has-usable-llm"
+import { executeMerge } from "@/lib/dedup-runner"
+import type { DuplicateGroup } from "@/lib/dedup"
+
+// ── Types ─────────────────────────────────────────────────────────────────
+
+export interface DedupTask {
+ id: string
+ projectId: string
+ group: DuplicateGroup
+ canonicalSlug: string
+ status: "pending" | "processing" | "done" | "failed"
+ addedAt: number
+ error: string | null
+ retryCount: number
+}
+
+// ── State ─────────────────────────────────────────────────────────────────
+
+let queue: DedupTask[] = []
+let processing = false
+let currentProjectId = ""
+let currentProjectPath = ""
+let currentAbortController: AbortController | null = null
+
+// ── Persistence ───────────────────────────────────────────────────────────
+
+function queueFilePath(projectPath: string): string {
+ return `${normalizePath(projectPath)}/.llm-wiki/dedup-queue.json`
+}
+
+async function saveQueue(projectPath: string): Promise<void> {
+ try {
+ const toSave = queue.filter((t) => t.status !== "done")
+ await writeFile(queueFilePath(projectPath), JSON.stringify(toSave, null, 2))
+ } catch {
+ // non-critical
+ }
+}
+
+async function loadQueue(
+ projectPath: string,
+ projectId: string,
+): Promise<DedupTask[]> {
+ try {
+ const raw = await readFile(queueFilePath(projectPath))
+ const tasks = JSON.parse(raw) as DedupTask[]
+ return tasks.map((t) => ({
+ ...t,
+ projectId: t.projectId ?? projectId,
+ }))
+ } catch {
+ return []
+ }
+}
+
+// ── Queue Operations ──────────────────────────────────────────────────────
+
+function generateId(): string {
+ return `dedup-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
+}
+
+/**
+ * Stable key for matching a queued task to a UI card. Order-independent
+ * lowercase join — same shape used by dedup-storage's canonical key.
+ */
+export function groupKey(slugs: readonly string[]): string {
+ return [...slugs].map((s) => s.toLowerCase()).sort().join(",")
+}
+
+/**
+ * Add a merge to the queue. The project MUST be the currently-active
+ * project. Returns the new task's id. Idempotent on the same group:
+ * if there's already a pending/processing/failed task for the same
+ * slug-set, the existing id is returned instead of a duplicate.
+ */
+export async function enqueueMerge(
+ projectId: string,
+ group: DuplicateGroup,
+ canonicalSlug: string,
+): Promise<string> {
+ if (!currentProjectId || currentProjectId !== projectId) {
+ throw new Error(
+ `enqueueMerge: project ${projectId} is not the active project (current: ${currentProjectId || "<none>"})`,
+ )
+ }
+
+ const key = groupKey(group.slugs)
+ const existing = queue.find(
+ (t) =>
+ t.projectId === projectId &&
+ t.status !== "done" &&
+ groupKey(t.group.slugs) === key,
+ )
+ if (existing) return existing.id
+
+ const task: DedupTask = {
+ id: generateId(),
+ projectId,
+ group,
+ canonicalSlug,
+ status: "pending",
+ addedAt: Date.now(),
+ error: null,
+ retryCount: 0,
+ }
+
+ queue.push(task)
+ await saveQueue(currentProjectPath)
+ processNext(currentProjectId)
+ return task.id
+}
+
+/**
+ * Reset a failed task back to pending so it gets another shot. Clears
+ * the error and resets retryCount so the user gets the full 3
+ * attempts again.
+ */
+export async function retryTask(taskId: string): Promise<void> {
+ const task = queue.find((t) => t.id === taskId)
+ if (!task) return
+ if (task.projectId !== currentProjectId) return
+
+ task.status = "pending"
+ task.error = null
+ task.retryCount = 0
+ await saveQueue(currentProjectPath)
+ processNext(currentProjectId)
+}
+
+/**
+ * Cancel/delete a task. If it's currently running, abort the LLM call
+ * first — the merge writes will be left where they were when the
+ * abort fired. Backup snapshots already on disk are kept either way.
+ */
+export async function cancelTask(taskId: string): Promise<void> {
+ const task = queue.find((t) => t.id === taskId)
+ if (!task) return
+ if (task.projectId !== currentProjectId) return
+
+ if (task.status === "processing") {
+ if (currentAbortController) {
+ currentAbortController.abort()
+ currentAbortController = null
+ }
+ processing = false
+ }
+
+ queue = queue.filter((t) => t.id !== taskId)
+ await saveQueue(currentProjectPath)
+ processNext(currentProjectId)
+}
+
+export function getQueue(): readonly DedupTask[] {
+ return queue
+}
+
+export function getQueueSummary(): {
+ pending: number
+ processing: number
+ failed: number
+ total: number
+} {
+ return {
+ pending: queue.filter((t) => t.status === "pending").length,
+ processing: queue.filter((t) => t.status === "processing").length,
+ failed: queue.filter((t) => t.status === "failed").length,
+ total: queue.length,
+ }
+}
+
+/**
+ * Test-only: wipe in-memory state without touching disk. Production
+ * code should always use `pauseQueue()` so pending state lands in
+ * the right project's file before the slate is cleared.
+ */
+export function clearQueueState(): void {
+ if (currentAbortController) {
+ currentAbortController.abort()
+ }
+ queue = []
+ processing = false
+ currentProjectId = ""
+ currentProjectPath = ""
+ currentAbortController = null
+}
+
+/**
+ * Project-switch handshake: flush the active project's queue to disk
+ * (reverting any in-flight task to pending so it gets re-tried on
+ * resume), then clear in-memory state.
+ */
+export async function pauseQueue(): Promise<void> {
+ if (!currentProjectId || !currentProjectPath) return
+
+ const pausedProjectPath = currentProjectPath
+
+ if (currentAbortController) {
+ currentAbortController.abort()
+ currentAbortController = null
+ }
+ processing = false
+
+ for (const task of queue) {
+ if (task.status === "processing") {
+ task.status = "pending"
+ }
+ }
+
+ await saveQueue(pausedProjectPath)
+
+ queue = []
+ currentProjectId = ""
+ currentProjectPath = ""
+}
+
+/**
+ * Load a project's queue from disk and resume processing. Tasks left
+ * in "processing" by an abrupt exit get reverted to "pending" so they
+ * pick up on next process tick.
+ */
+export async function restoreQueue(
+ projectId: string,
+ projectPath: string,
+): Promise<void> {
+ const pp = normalizePath(projectPath)
+ queue = []
+ processing = false
+ currentAbortController = null
+ currentProjectId = projectId
+ currentProjectPath = pp
+
+ const saved = await loadQueue(pp, projectId)
+ if (saved.length === 0) return
+
+ const mine = saved.filter((t) => t.projectId === projectId)
+ if (mine.length !== saved.length) {
+ console.warn(
+ `[Dedup Queue] Dropped ${saved.length - mine.length} cross-project tasks during restore`,
+ )
+ }
+
+ let restored = 0
+ for (const task of mine) {
+ if (task.status === "processing") {
+ task.status = "pending"
+ restored++
+ }
+ }
+
+ queue = mine
+ await saveQueue(pp)
+
+ const pending = queue.filter((t) => t.status === "pending").length
+ const failed = queue.filter((t) => t.status === "failed").length
+ if (pending > 0 || restored > 0) {
+ console.log(
+ `[Dedup Queue] Restored: ${pending} pending, ${failed} failed, ${restored} resumed from interrupted`,
+ )
+ processNext(projectId)
+ }
+}
+
+// ── Processing ────────────────────────────────────────────────────────────
+
+const MAX_RETRIES = 3
+
+async function processNext(projectId: string): Promise<void> {
+ if (processing) return
+ if (currentProjectId !== projectId) return
+
+ const next = queue.find(
+ (t) => t.projectId === projectId && t.status === "pending",
+ )
+ if (!next) return
+
+ const registryPath = await getProjectPathById(projectId)
+ const pp = registryPath ? normalizePath(registryPath) : ""
+ if (currentProjectId !== projectId) return
+
+ if (!pp) {
+ next.status = "failed"
+ next.error = "Project not found in registry (was it deleted?)"
+ await saveQueue(currentProjectPath)
+ processNext(projectId)
+ return
+ }
+
+ processing = true
+ next.status = "processing"
+ await saveQueue(pp)
+ if (currentProjectId !== projectId) return
+
+ const llmConfig = useWikiStore.getState().llmConfig
+
+ if (!hasUsableLlm(llmConfig)) {
+ next.status = "failed"
+ next.error = "LLM not configured — set API key in Settings"
+ processing = false
+ await saveQueue(pp)
+ return
+ }
+
+ console.log(
+ `[Dedup Queue] Processing: merge ${next.group.slugs.join(",")} → ${next.canonicalSlug}`,
+ )
+
+ currentAbortController = new AbortController()
+
+ try {
+ await executeMerge(pp, next.group, next.canonicalSlug, llmConfig, {
+ signal: currentAbortController.signal,
+ })
+ if (currentProjectId !== projectId) return
+
+ currentAbortController = null
+ queue = queue.filter((t) => t.id !== next.id)
+ await saveQueue(pp)
+ // Tell the rest of the app the wiki tree changed.
+ useWikiStore.getState().bumpDataVersion()
+
+ console.log(`[Dedup Queue] Done: ${next.group.slugs.join(",")}`)
+ } catch (err) {
+ if (currentProjectId !== projectId) return
+ currentAbortController = null
+ const message = err instanceof Error ? err.message : String(err)
+ next.retryCount++
+ next.error = message
+
+ if (next.retryCount >= MAX_RETRIES) {
+ next.status = "failed"
+ console.log(
+ `[Dedup Queue] Failed (${next.retryCount}x): ${next.group.slugs.join(",")} — ${message}`,
+ )
+ } else {
+ next.status = "pending"
+ console.log(
+ `[Dedup Queue] Error (retry ${next.retryCount}/${MAX_RETRIES}): ${next.group.slugs.join(",")} — ${message}`,
+ )
+ }
+ await saveQueue(pp)
+ }
+
+ processing = false
+ processNext(projectId)
+}
diff --git a/src/lib/dedup-runner.ts b/src/lib/dedup-runner.ts
new file mode 100644
index 00000000..c81a055a
--- /dev/null
+++ b/src/lib/dedup-runner.ts
@@ -0,0 +1,254 @@
+/**
+ * I/O wrapper that connects the pure dedup algorithm in dedup.ts
+ * to the project's filesystem + LLM. The UI layer calls these
+ * functions; everything below is about read/write/spawn-llm so
+ * the algorithm core stays testable without mocks of all that.
+ */
+import { listDirectory, readFile, writeFile, deleteFile } from "@/commands/fs"
+import { streamChat } from "@/lib/llm-client"
+import { normalizePath } from "@/lib/path-utils"
+import type { LlmConfig } from "@/stores/wiki-store"
+import type { FileNode } from "@/types/wiki"
+import {
+ detectDuplicateGroups,
+ extractEntitySummary,
+ mergeDuplicateGroup,
+ rewriteIndexMd,
+ type DedupLlmCall,
+ type DuplicateGroup,
+ type EntitySummary,
+ type MergeResult,
+} from "./dedup"
+import { loadNotDuplicates } from "./dedup-storage"
+
+/**
+ * Wrap streamChat into the (system, user, signal) → string shape
+ * the dedup module expects. Same pattern page-merge uses — keeps
+ * the algorithm modules free of any LlmConfig knowledge.
+ */
+export function buildDedupLlmCall(llmConfig: LlmConfig): DedupLlmCall {
+ return async (systemPrompt, userMessage, signal) => {
+ let result = ""
+ let streamError: Error | null = null
+ await new Promise<void>((resolve) => {
+ streamChat(
+ llmConfig,
+ [
+ { role: "system", content: systemPrompt },
+ { role: "user", content: userMessage },
+ ],
+ {
+ onToken: (t) => {
+ result += t
+ },
+ onDone: () => resolve(),
+ onError: (err) => {
+ streamError = err
+ resolve()
+ },
+ },
+ signal,
+ { temperature: 0.1 },
+ ).catch((err) => {
+ streamError = err instanceof Error ? err : new Error(String(err))
+ resolve()
+ })
+ })
+ if (streamError) throw streamError
+ return result
+ }
+}
+
+/** Walk a FileNode tree, yielding every .md file under a given prefix. */
+function* walkMd(nodes: FileNode[], prefix: string): Generator<FileNode> {
+ for (const node of nodes) {
+ if (node.is_dir) {
+ if (node.children) yield* walkMd(node.children, prefix)
+ continue
+ }
+ if (node.name.endsWith(".md") && node.path.includes(`${prefix}/`)) {
+ yield node
+ }
+ }
+}
+
+/** Convert an absolute filesystem path to a wiki-relative one
+ * (`<project>/wiki/entities/foo.md` → `wiki/entities/foo.md`). */
+function toWikiRelative(projectPath: string, absPath: string): string {
+ const pp = normalizePath(projectPath)
+ const norm = normalizePath(absPath)
+ if (norm.startsWith(`${pp}/`)) return norm.slice(pp.length + 1)
+ return norm
+}
+
+/**
+ * Walk wiki/entities/ and wiki/concepts/, build summaries.
+ * Pages that fail to parse (no frontmatter, etc.) are skipped
+ * silently — they can't participate in dedup anyway.
+ */
+export async function loadAllEntitySummaries(
+ projectPath: string,
+): Promise<EntitySummary[]> {
+ const pp = normalizePath(projectPath)
+ const tree = await listDirectory(pp)
+ const out: EntitySummary[] = []
+ for (const prefix of ["wiki/entities", "wiki/concepts"]) {
+ for (const node of walkMd(tree, prefix)) {
+ try {
+ const content = await readFile(node.path)
+ const rel = toWikiRelative(pp, node.path)
+ const summary = extractEntitySummary(rel, content)
+ if (summary) out.push(summary)
+ } catch {
+ // best-effort — skip unreadable pages
+ }
+ }
+ }
+ return out
+}
+
+/** Read every .md under wiki/ as { path, content }. The path is
+ * the wiki-relative form callers downstream use. */
+export async function loadAllWikiPages(
+ projectPath: string,
+): Promise<{ path: string; content: string }[]> {
+ const pp = normalizePath(projectPath)
+ const tree = await listDirectory(pp)
+ const out: { path: string; content: string }[] = []
+ for (const node of walkMd(tree, "wiki")) {
+ try {
+ const content = await readFile(node.path)
+ out.push({ path: toWikiRelative(pp, node.path), content })
+ } catch {
+ // ignore
+ }
+ }
+ return out
+}
+
+/**
+ * Stage 1 + 2 from the user's perspective: scan the project for
+ * duplicate-candidate groups. Reads notDuplicates whitelist from
+ * disk so previously-confirmed false-positives don't reappear.
+ */
+export async function runDuplicateDetection(
+ projectPath: string,
+ llmConfig: LlmConfig,
+ options: { signal?: AbortSignal } = {},
+): Promise<DuplicateGroup[]> {
+ const summaries = await loadAllEntitySummaries(projectPath)
+ if (summaries.length < 2) return []
+ const notDup = await loadNotDuplicates(projectPath)
+ const llm = buildDedupLlmCall(llmConfig)
+ return detectDuplicateGroups(summaries, llm, {
+ signal: options.signal,
+ notDuplicates: notDup,
+ })
+}
+
+/**
+ * Stage 3 + persistence: execute one user-confirmed merge.
+ *
+ * Steps:
+ * 1. Load each group page's full content + every other wiki page
+ * 2. Run mergeDuplicateGroup (LLM body merge + frontmatter
+ * union + cross-reference rewrites)
+ * 3. Snapshot every touched file to .llm-wiki/page-history/
+ * dedup-<timestamp>/
+ * 4. Write canonical content
+ * 5. Apply cross-reference rewrites
+ * 6. Delete merged-away files
+ * 7. Apply index.md rewrite (separate pass — index isn't in
+ * otherWikiPages because removing references is a different
+ * operation than slug-rewriting them)
+ */
+export async function executeMerge(
+ projectPath: string,
+ group: DuplicateGroup,
+ canonicalSlug: string,
+ llmConfig: LlmConfig,
+ options: { signal?: AbortSignal } = {},
+): Promise<MergeResult> {
+ const pp = normalizePath(projectPath)
+
+ // 1. Resolve each group slug to its actual on-disk path + content
+ const allPages = await loadAllWikiPages(pp)
+ const pathBySlug = new Map<string, string>()
+ for (const p of allPages) {
+ const base = p.path.split("/").pop() ?? ""
+ if (base.endsWith(".md")) {
+ pathBySlug.set(base.slice(0, -3), p.path)
+ }
+ }
+ const groupPages: { slug: string; path: string; content: string }[] = []
+ for (const slug of group.slugs) {
+ const relPath = pathBySlug.get(slug)
+ if (!relPath) {
+ throw new Error(
+ `Slug "${slug}" not found on disk — was the page deleted between detection and merge?`,
+ )
+ }
+ const page = allPages.find((p) => p.path === relPath)
+ if (!page) {
+ throw new Error(`Internal: page lookup miss for ${relPath}`)
+ }
+ groupPages.push({ slug, path: relPath, content: page.content })
+ }
+
+ const groupPaths = new Set(groupPages.map((p) => p.path))
+ const otherPages = allPages.filter((p) => !groupPaths.has(p.path))
+
+ const llm = buildDedupLlmCall(llmConfig)
+ const result = await mergeDuplicateGroup(
+ {
+ group: groupPages,
+ canonicalSlug,
+ otherWikiPages: otherPages,
+ },
+ llm,
+ { signal: options.signal },
+ )
+
+ // 2. Snapshot backup before any writes. If a write fails partway
+ // through, the user has the pre-merge state intact in
+ // .llm-wiki/page-history/.
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-")
+ const backupDir = `${pp}/.llm-wiki/page-history/dedup-${stamp}`
+ for (const b of result.backup) {
+ const sanitized = b.path.replace(/[/\\]/g, "_")
+ await writeFile(`${backupDir}/${sanitized}`, b.content)
+ }
+
+ // 3. Write canonical
+ await writeFile(`${pp}/${result.canonicalPath}`, result.canonicalContent)
+
+ // 4. Apply rewrites
+ for (const r of result.rewrites) {
+ await writeFile(`${pp}/${r.path}`, r.newContent)
+ }
+
+ // 5. Delete merged-away pages
+ for (const dead of result.pagesToDelete) {
+ try {
+ await deleteFile(`${pp}/${dead}`)
+ } catch (err) {
+ // Surface as a warning — backup is still safe.
+ console.warn(`[dedup] failed to delete ${dead}: ${err}`)
+ }
+ }
+
+ // 6. Rewrite index.md to drop merged-away entries.
+ const indexPath = `${pp}/wiki/index.md`
+ const indexEntry = allPages.find((p) => p.path === "wiki/index.md")
+ if (indexEntry) {
+ const removed = new Set(
+ group.slugs.filter((s) => s !== canonicalSlug),
+ )
+ const rewritten = rewriteIndexMd(indexEntry.content, removed)
+ if (rewritten !== indexEntry.content) {
+ await writeFile(indexPath, rewritten)
+ }
+ }
+
+ return result
+}
diff --git a/src/lib/dedup-storage.ts b/src/lib/dedup-storage.ts
new file mode 100644
index 00000000..ac1906e6
--- /dev/null
+++ b/src/lib/dedup-storage.ts
@@ -0,0 +1,68 @@
+/**
+ * Persistence for the dedup tool's "not duplicates" whitelist.
+ *
+ * When the user reviews a candidate group and says "these are NOT
+ * the same thing", we record the group so the next detector run
+ * doesn't re-suggest it. Stored as a JSON array-of-arrays where
+ * each inner array is one whitelisted group of slugs (lowercased,
+ * sorted — see the canonical key logic in `dedup.ts`).
+ *
+ * Lives next to ingest-cache.json / image-caption-cache.json /
+ * lexical-graph.json (when added) — same `.llm-wiki/` directory,
+ * same JSON-on-disk pattern.
+ */
+import { readFile, writeFile, fileExists } from "@/commands/fs"
+import { normalizePath } from "@/lib/path-utils"
+
+const FILE_NAME = ".llm-wiki/dedup-not-duplicates.json"
+
+export async function loadNotDuplicates(projectPath: string): Promise<string[][]> {
+ const pp = normalizePath(projectPath)
+ const filePath = `${pp}/${FILE_NAME}`
+ try {
+ if (!(await fileExists(filePath))) return []
+ } catch {
+ return []
+ }
+ try {
+ const content = await readFile(filePath)
+ const parsed = JSON.parse(content)
+ if (!Array.isArray(parsed)) return []
+ return parsed.filter(
+ (g): g is string[] =>
+ Array.isArray(g) && g.every((s) => typeof s === "string"),
+ )
+ } catch {
+ return []
+ }
+}
+
+export async function saveNotDuplicates(
+ projectPath: string,
+ list: string[][],
+): Promise<void> {
+ const pp = normalizePath(projectPath)
+ await writeFile(`${pp}/${FILE_NAME}`, JSON.stringify(list, null, 2))
+}
+
+/**
+ * Add a group to the whitelist. Idempotent — if the same group
+ * (in any order, any casing) is already present, this is a no-op.
+ */
+export async function addNotDuplicate(
+ projectPath: string,
+ slugs: string[],
+): Promise<void> {
+ if (slugs.length < 2) return
+ const list = await loadNotDuplicates(projectPath)
+ const normNew = canonicalKey(slugs)
+ for (const existing of list) {
+ if (canonicalKey(existing) === normNew) return // already there
+ }
+ list.push([...slugs].sort())
+ await saveNotDuplicates(projectPath, list)
+}
+
+function canonicalKey(slugs: string[]): string {
+ return [...slugs].map((s) => s.toLowerCase()).sort().join(",")
+}
diff --git a/src/lib/dedup.test.ts b/src/lib/dedup.test.ts
new file mode 100644
index 00000000..56abb209
--- /dev/null
+++ b/src/lib/dedup.test.ts
@@ -0,0 +1,541 @@
+import { describe, it, expect, vi } from "vitest"
+import {
+ extractEntitySummary,
+ detectDuplicateGroups,
+ parseDetectorResponse,
+ mergeDuplicateGroup,
+ rewriteCrossReferences,
+ rewriteIndexMd,
+ type EntitySummary,
+} from "./dedup"
+import { parseFrontmatterArray } from "./sources-merge"
+
+const PAGE = (fm: string, body: string) => `---\n${fm}\n---\n\n${body}`
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 1: extractEntitySummary
+// ──────────────────────────────────────────────────────────────────
+
+describe("extractEntitySummary", () => {
+ it("returns null for content with no frontmatter", () => {
+ expect(extractEntitySummary("wiki/entities/foo.md", "# Just body")).toBeNull()
+ })
+
+ it("derives slug from filename", () => {
+ const s = extractEntitySummary(
+ "wiki/entities/accumulibacter.md",
+ PAGE("type: entity\ntitle: Accumulibacter", "body"),
+ )
+ expect(s?.slug).toBe("accumulibacter")
+ })
+
+ it("uses frontmatter description when present", () => {
+ const s = extractEntitySummary(
+ "wiki/entities/foo.md",
+ PAGE(
+ 'type: entity\ntitle: Foo\ndescription: "A short summary."\ntags: [a, b]',
+ "Body text",
+ ),
+ )
+ expect(s?.description).toBe("A short summary.")
+ expect(s?.tags).toEqual(["a", "b"])
+ })
+
+ it("falls back to first non-heading body paragraph for description", () => {
+ const s = extractEntitySummary(
+ "wiki/entities/foo.md",
+ PAGE("type: entity\ntitle: Foo", "# Foo\n\nFirst real paragraph here."),
+ )
+ expect(s?.description).toBe("First real paragraph here.")
+ })
+
+ it("truncates long descriptions to ~200 chars", () => {
+ const long = "x".repeat(400)
+ const s = extractEntitySummary(
+ "wiki/entities/foo.md",
+ PAGE(`type: entity\ntitle: Foo\ndescription: "${long}"`, "body"),
+ )
+ expect(s?.description?.length).toBeLessThanOrEqual(200)
+ expect(s?.description?.endsWith("…")).toBe(true)
+ })
+})
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 2: parseDetectorResponse
+// ──────────────────────────────────────────────────────────────────
+
+describe("parseDetectorResponse", () => {
+ it("parses a clean JSON response", () => {
+ const raw = JSON.stringify({
+ groups: [
+ { slugs: ["a", "b"], reason: "same thing", confidence: "high" },
+ ],
+ })
+ expect(parseDetectorResponse(raw)).toEqual([
+ { slugs: ["a", "b"], reason: "same thing", confidence: "high" },
+ ])
+ })
+
+ it("strips ```json code fences if the LLM wrapped its output", () => {
+ const raw = '```json\n{"groups": [{"slugs": ["a","b"], "reason": "x", "confidence": "high"}]}\n```'
+ const out = parseDetectorResponse(raw)
+ expect(out).toHaveLength(1)
+ expect(out[0].slugs).toEqual(["a", "b"])
+ })
+
+ it("strips conversational preamble before the JSON", () => {
+ const raw =
+ 'Sure, here are the duplicates I found:\n\n{"groups": [{"slugs": ["foo","bar"], "reason": "synonyms", "confidence": "medium"}]}\n\nLet me know if you need anything else.'
+ const out = parseDetectorResponse(raw)
+ expect(out[0].slugs).toEqual(["foo", "bar"])
+ expect(out[0].confidence).toBe("medium")
+ })
+
+ it("rejects groups with fewer than 2 slugs", () => {
+ const raw = '{"groups": [{"slugs": ["only-one"], "reason": "x", "confidence": "high"}]}'
+ expect(parseDetectorResponse(raw)).toEqual([])
+ })
+
+ it("defaults invalid confidence values to 'low'", () => {
+ const raw = '{"groups": [{"slugs": ["a","b"], "reason": "", "confidence": "extremely-high"}]}'
+ expect(parseDetectorResponse(raw)[0].confidence).toBe("low")
+ })
+
+ it("returns [] for malformed JSON", () => {
+ expect(parseDetectorResponse("not json at all")).toEqual([])
+ expect(parseDetectorResponse('{"groups": [unclosed')).toEqual([])
+ expect(parseDetectorResponse("")).toEqual([])
+ })
+
+ it("returns [] when the JSON object has no groups field", () => {
+ expect(parseDetectorResponse('{"other_field": []}')).toEqual([])
+ })
+
+ it("survives quoted braces inside reason strings", () => {
+ const raw =
+ '{"groups": [{"slugs": ["a","b"], "reason": "Same thing { really }", "confidence": "high"}]}'
+ const out = parseDetectorResponse(raw)
+ expect(out[0].reason).toBe("Same thing { really }")
+ })
+})
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 2: detectDuplicateGroups (full pipeline w/ mock LLM)
+// ──────────────────────────────────────────────────────────────────
+
+describe("detectDuplicateGroups", () => {
+ const summary = (slug: string, title: string, type = "entity"): EntitySummary => ({
+ slug,
+ path: `wiki/entities/${slug}.md`,
+ type,
+ title,
+ tags: [],
+ })
+
+ it("returns [] when fewer than 2 summaries are passed", async () => {
+ const llm = vi.fn()
+ expect(await detectDuplicateGroups([summary("foo", "Foo")], llm)).toEqual([])
+ expect(llm).not.toHaveBeenCalled()
+ })
+
+ it("filters out groups whose slugs aren't in the input list", async () => {
+ const llm = vi.fn().mockResolvedValue(
+ JSON.stringify({
+ groups: [
+ { slugs: ["real-a", "real-b"], reason: "x", confidence: "high" },
+ { slugs: ["fake", "real-a"], reason: "x", confidence: "high" },
+ ],
+ }),
+ )
+ const result = await detectDuplicateGroups(
+ [summary("real-a", "A"), summary("real-b", "B")],
+ llm,
+ )
+ expect(result).toHaveLength(1)
+ expect(result[0].slugs).toEqual(["real-a", "real-b"])
+ })
+
+ it("filters out groups already on the user's not-duplicates whitelist", async () => {
+ const llm = vi.fn().mockResolvedValue(
+ JSON.stringify({
+ groups: [
+ { slugs: ["foo", "bar"], reason: "x", confidence: "high" },
+ { slugs: ["x", "y"], reason: "x", confidence: "high" },
+ ],
+ }),
+ )
+ const result = await detectDuplicateGroups(
+ [
+ summary("foo", "Foo"),
+ summary("bar", "Bar"),
+ summary("x", "X"),
+ summary("y", "Y"),
+ ],
+ llm,
+ { notDuplicates: [["foo", "bar"]] },
+ )
+ expect(result.map((g) => g.slugs.sort())).toEqual([["x", "y"]])
+ })
+
+ it("treats whitelist entries case-insensitively and order-independently", async () => {
+ const llm = vi.fn().mockResolvedValue(
+ JSON.stringify({
+ groups: [{ slugs: ["foo", "bar"], reason: "", confidence: "high" }],
+ }),
+ )
+ // Whitelist stored with reversed casing/order — should still match.
+ const result = await detectDuplicateGroups(
+ [summary("foo", "Foo"), summary("bar", "Bar")],
+ llm,
+ { notDuplicates: [["BAR", "FOO"]] },
+ )
+ expect(result).toEqual([])
+ })
+
+ it("formats the user message with type / slug / title / tags / description", async () => {
+ const llm = vi.fn().mockResolvedValue('{"groups":[]}')
+ await detectDuplicateGroups(
+ [
+ {
+ slug: "foo",
+ path: "wiki/entities/foo.md",
+ type: "entity",
+ title: "Foo",
+ description: "Short desc.",
+ tags: ["t1", "t2"],
+ },
+ summary("bar", "Bar"),
+ ],
+ llm,
+ )
+ expect(llm).toHaveBeenCalledOnce()
+ const userMsg = llm.mock.calls[0][1]
+ expect(userMsg).toContain("type=entity")
+ expect(userMsg).toContain("slug=foo")
+ expect(userMsg).toContain('"Foo"')
+ expect(userMsg).toContain("[t1, t2]")
+ expect(userMsg).toContain("Short desc.")
+ })
+})
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 3: rewriteCrossReferences
+// ──────────────────────────────────────────────────────────────────
+
+describe("rewriteCrossReferences", () => {
+ it("rewrites bare wikilinks", () => {
+ const out = rewriteCrossReferences(
+ "See [[old-slug]] for context.",
+ new Map([["old-slug", "new-slug"]]),
+ )
+ expect(out).toBe("See [[new-slug]] for context.")
+ })
+
+ it("rewrites wikilinks with aliases, preserving the alias", () => {
+ const out = rewriteCrossReferences(
+ "See [[old-slug|the old display]] here.",
+ new Map([["old-slug", "new-slug"]]),
+ )
+ expect(out).toBe("See [[new-slug|the old display]] here.")
+ })
+
+ it("does not touch wikilinks pointing at unrelated slugs", () => {
+ const input = "Both [[paos]] and [[unrelated]] are mentioned."
+ const out = rewriteCrossReferences(input, new Map([["paos", "phosphorus-accumulating-organisms"]]))
+ expect(out).toContain("[[phosphorus-accumulating-organisms]]")
+ expect(out).toContain("[[unrelated]]")
+ })
+
+ it("rewrites the related field (inline form)", () => {
+ const input = PAGE(
+ "type: entity\ntitle: Foo\nrelated: [old-slug, kept]",
+ "body",
+ )
+ const out = rewriteCrossReferences(input, new Map([["old-slug", "new-slug"]]))
+ expect(parseFrontmatterArray(out, "related")).toEqual(["new-slug", "kept"])
+ })
+
+ it("rewrites the related field (block form)", () => {
+ const input = PAGE(
+ "type: entity\ntitle: Foo\nrelated:\n - old-slug\n - kept",
+ "body",
+ )
+ const out = rewriteCrossReferences(input, new Map([["old-slug", "new-slug"]]))
+ expect(parseFrontmatterArray(out, "related")).toEqual(["new-slug", "kept"])
+ })
+
+ it("dedupes related when canonical was already in the list", () => {
+ // Page already linked to BOTH the canonical AND the duplicate.
+ // After redirect, we'd have ["new-slug", "new-slug"] before dedup.
+ const input = PAGE(
+ "type: entity\nrelated: [old-slug, new-slug, kept]",
+ "body",
+ )
+ const out = rewriteCrossReferences(input, new Map([["old-slug", "new-slug"]]))
+ expect(parseFrontmatterArray(out, "related")).toEqual(["new-slug", "kept"])
+ })
+
+ it("returns content unchanged when no redirects apply", () => {
+ const input = PAGE("type: entity\nrelated: [a, b]", "[[c]] and [[d]] here.")
+ const out = rewriteCrossReferences(input, new Map([["nonexistent", "other"]]))
+ expect(out).toBe(input)
+ })
+
+ it("rewrites multiple slugs in one pass", () => {
+ const input = "[[old-a]] and [[old-b]] and [[keep-me]]."
+ const out = rewriteCrossReferences(
+ input,
+ new Map([
+ ["old-a", "canonical"],
+ ["old-b", "canonical"],
+ ]),
+ )
+ expect(out).toBe("[[canonical]] and [[canonical]] and [[keep-me]].")
+ })
+})
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 3: rewriteIndexMd
+// ──────────────────────────────────────────────────────────────────
+
+describe("rewriteIndexMd", () => {
+ it("removes lines linking to merged-away slugs (markdown link form)", () => {
+ const input = [
+ "## Entities",
+ "- [Accumulibacter](entities/accumulibacter.md)",
+ "- [DPAOs (deprecated)](entities/dpaos.md)",
+ "- [DPAO](entities/dpao.md)",
+ ].join("\n")
+ const out = rewriteIndexMd(input, new Set(["dpaos"]))
+ expect(out).not.toContain("dpaos")
+ expect(out).toContain("accumulibacter")
+ expect(out).toContain("[DPAO](entities/dpao.md)")
+ })
+
+ it("removes lines with wikilinks to merged-away slugs", () => {
+ const input = [
+ "## Concepts",
+ "- [[vfa]] — Volatile fatty acids",
+ "- [[volatile-fatty-acids]] — VFAs (long form)",
+ "- [[pha]] — PHA storage polymer",
+ ].join("\n")
+ const out = rewriteIndexMd(input, new Set(["volatile-fatty-acids"]))
+ expect(out).not.toContain("volatile-fatty-acids")
+ expect(out).toContain("[[vfa]]")
+ expect(out).toContain("[[pha]]")
+ })
+
+ it("preserves headings and prose between lists", () => {
+ const input = [
+ "# Wiki Index",
+ "",
+ "Generated overview.",
+ "",
+ "## Entities",
+ "- [DPAOs](entities/dpaos.md)",
+ "- [DPAO](entities/dpao.md)",
+ "",
+ "## Concepts",
+ "Some intro prose here, no slugs.",
+ ].join("\n")
+ const out = rewriteIndexMd(input, new Set(["dpaos"]))
+ expect(out).toContain("# Wiki Index")
+ expect(out).toContain("Generated overview.")
+ expect(out).toContain("## Entities")
+ expect(out).toContain("[DPAO](entities/dpao.md)")
+ expect(out).toContain("## Concepts")
+ expect(out).toContain("Some intro prose here")
+ expect(out).not.toContain("dpaos.md")
+ })
+
+ it("is a no-op when removedSlugs is empty", () => {
+ const input = "- [Foo](entities/foo.md)\n- [Bar](entities/bar.md)"
+ expect(rewriteIndexMd(input, new Set())).toBe(input)
+ })
+})
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 3: mergeDuplicateGroup (full integration with mock LLM)
+// ──────────────────────────────────────────────────────────────────
+
+describe("mergeDuplicateGroup", () => {
+ const FIXED_TODAY = () => "2026-04-30"
+
+ it("throws when canonicalSlug isn't in the group", async () => {
+ await expect(
+ mergeDuplicateGroup(
+ {
+ group: [
+ { slug: "a", path: "wiki/entities/a.md", content: PAGE("type: entity", "ax") },
+ { slug: "b", path: "wiki/entities/b.md", content: PAGE("type: entity", "bx") },
+ ],
+ canonicalSlug: "z",
+ otherWikiPages: [],
+ },
+ vi.fn(),
+ ),
+ ).rejects.toThrow(/canonicalSlug/)
+ })
+
+ it("throws when group has fewer than 2 pages", async () => {
+ await expect(
+ mergeDuplicateGroup(
+ {
+ group: [{ slug: "a", path: "wiki/entities/a.md", content: PAGE("type: entity", "x") }],
+ canonicalSlug: "a",
+ otherWikiPages: [],
+ },
+ vi.fn(),
+ ),
+ ).rejects.toThrow(/at least 2/)
+ })
+
+ it("merges bodies via LLM, unions sources/tags/related, stamps updated", async () => {
+ const pageA = PAGE(
+ 'type: entity\ntitle: Accumulibacter\ncreated: 2026-04-09\nupdated: 2026-04-09\ntags: [microbiology, ebpr]\nrelated: [dpao, vfa]\nsources: ["doc-A.pdf"]',
+ "## Anaerobic Phase\n\nDescription from page A.",
+ )
+ const pageB = PAGE(
+ 'type: entity\ntitle: 聚磷菌\ncreated: 2026-04-15\nupdated: 2026-04-15\ntags: [paos, propionate]\nrelated: [pha]\nsources: ["doc-B.pdf"]',
+ "## 厌氧阶段\n\n来自页面 B 的描述。",
+ )
+ const llmMerged = PAGE(
+ 'type: entity\ntitle: Accumulibacter\ncreated: 2026-04-09\nupdated: 2026-04-09\ntags: [microbiology, ebpr]\nrelated: [dpao, vfa]\nsources: ["doc-A.pdf"]',
+ "## Anaerobic Phase\n\nDescription from page A.\n\n## 厌氧阶段\n\n来自页面 B 的描述。",
+ )
+ const llm = vi.fn().mockResolvedValue(llmMerged)
+
+ const result = await mergeDuplicateGroup(
+ {
+ group: [
+ { slug: "accumulibacter", path: "wiki/entities/accumulibacter.md", content: pageA },
+ { slug: "聚磷菌", path: "wiki/entities/聚磷菌.md", content: pageB },
+ ],
+ canonicalSlug: "accumulibacter",
+ otherWikiPages: [],
+ },
+ llm,
+ { today: FIXED_TODAY },
+ )
+
+ // Canonical body has both versions' content
+ expect(result.canonicalContent).toContain("Anaerobic Phase")
+ expect(result.canonicalContent).toContain("厌氧阶段")
+
+ // Frontmatter unioned (set semantics — order not part of contract)
+ expect(parseFrontmatterArray(result.canonicalContent, "sources").sort()).toEqual(
+ ["doc-A.pdf", "doc-B.pdf"].sort(),
+ )
+ expect(parseFrontmatterArray(result.canonicalContent, "tags").sort()).toEqual(
+ ["ebpr", "microbiology", "paos", "propionate"].sort(),
+ )
+ expect(parseFrontmatterArray(result.canonicalContent, "related").sort()).toEqual(
+ ["dpao", "pha", "vfa"].sort(),
+ )
+
+ // Updated stamped to today
+ expect(result.canonicalContent).toContain("updated: 2026-04-30")
+
+ // Canonical path correct
+ expect(result.canonicalPath).toBe("wiki/entities/accumulibacter.md")
+
+ // The other group member's path is in pagesToDelete
+ expect(result.pagesToDelete).toEqual(["wiki/entities/聚磷菌.md"])
+
+ // Backup includes both pre-merge contents
+ expect(result.backup).toEqual([
+ { path: "wiki/entities/accumulibacter.md", content: pageA },
+ { path: "wiki/entities/聚磷菌.md", content: pageB },
+ ])
+ })
+
+ it("rewrites cross-references in other wiki pages", async () => {
+ const pageA = PAGE("type: entity\ntitle: A\nrelated: [bar]", "body a")
+ const pageB = PAGE("type: entity\ntitle: B\nrelated: [bar]", "body b")
+ const referencingPage = PAGE(
+ "type: concept\ntitle: Other\nrelated: [a, b, kept]",
+ "See [[a]] and [[b|the b]] and [[unrelated]].",
+ )
+ const llm = vi.fn().mockResolvedValue(PAGE("type: entity\ntitle: A\n", "merged body"))
+
+ const result = await mergeDuplicateGroup(
+ {
+ group: [
+ { slug: "a", path: "wiki/entities/a.md", content: pageA },
+ { slug: "b", path: "wiki/entities/b.md", content: pageB },
+ ],
+ canonicalSlug: "a",
+ otherWikiPages: [
+ { path: "wiki/concepts/other.md", content: referencingPage },
+ ],
+ },
+ llm,
+ { today: FIXED_TODAY },
+ )
+
+ expect(result.rewrites).toHaveLength(1)
+ const rewritten = result.rewrites[0].newContent
+ // wikilinks rewritten
+ expect(rewritten).toContain("[[a]]")
+ expect(rewritten).toContain("[[a|the b]]")
+ expect(rewritten).toContain("[[unrelated]]")
+ expect(rewritten).not.toMatch(/\[\[b(\|[^\]]*)?\]\]/)
+ // related field rewritten + deduped
+ expect(parseFrontmatterArray(rewritten, "related")).toEqual(["a", "kept"])
+ })
+
+ it("doesn't include unchanged pages in rewrites", async () => {
+ const llm = vi.fn().mockResolvedValue(PAGE("type: entity\ntitle: A\n", "merged"))
+ const irrelevant = PAGE(
+ "type: concept\nrelated: [unrelated-slug]",
+ "[[totally-different]] page.",
+ )
+
+ const result = await mergeDuplicateGroup(
+ {
+ group: [
+ { slug: "a", path: "wiki/entities/a.md", content: PAGE("type: entity", "x") },
+ { slug: "b", path: "wiki/entities/b.md", content: PAGE("type: entity", "y") },
+ ],
+ canonicalSlug: "a",
+ otherWikiPages: [{ path: "wiki/concepts/irrelevant.md", content: irrelevant }],
+ },
+ llm,
+ { today: FIXED_TODAY },
+ )
+ expect(result.rewrites).toEqual([])
+ // Backup also doesn't include unchanged pages
+ expect(result.backup.map((b) => b.path)).not.toContain("wiki/concepts/irrelevant.md")
+ })
+
+ it("backup snapshots the pre-merge state of every touched file", async () => {
+ const pageA = PAGE("type: entity\ntitle: A", "body a")
+ const pageB = PAGE("type: entity\ntitle: B", "body b")
+ const refOrig = PAGE("type: concept\nrelated: [b]", "[[b]]")
+ const llm = vi.fn().mockResolvedValue(PAGE("type: entity\ntitle: A", "merged"))
+
+ const result = await mergeDuplicateGroup(
+ {
+ group: [
+ { slug: "a", path: "wiki/entities/a.md", content: pageA },
+ { slug: "b", path: "wiki/entities/b.md", content: pageB },
+ ],
+ canonicalSlug: "a",
+ otherWikiPages: [{ path: "wiki/concepts/ref.md", content: refOrig }],
+ },
+ llm,
+ { today: FIXED_TODAY },
+ )
+
+ // Backup has all 3 pre-merge files; rewrites only has the changed cross-ref
+ const backupPaths = result.backup.map((b) => b.path).sort()
+ expect(backupPaths).toEqual([
+ "wiki/concepts/ref.md",
+ "wiki/entities/a.md",
+ "wiki/entities/b.md",
+ ])
+ // The backup content is the ORIGINAL, not the post-merge version
+ const refBackup = result.backup.find((b) => b.path === "wiki/concepts/ref.md")
+ expect(refBackup?.content).toBe(refOrig)
+ })
+})
diff --git a/src/lib/dedup.ts b/src/lib/dedup.ts
new file mode 100644
index 00000000..19be5c6a
--- /dev/null
+++ b/src/lib/dedup.ts
@@ -0,0 +1,559 @@
+/**
+ * Duplicate-entity / -concept detection and merge for wiki maintenance.
+ *
+ * Problem: across re-ingests, the LLM names the same underlying
+ * topic differently — `paos` vs `聚磷菌`, `dpao` vs `dpaos` (plural)
+ * vs `反硝化除磷菌`, `vfa` vs `volatile-fatty-acids`. Each becomes a
+ * separate page even though they're the same entity. The page-merge
+ * layer only catches *exact* slug collisions; this module catches
+ * the soft-collision case via an LLM-driven self-check.
+ *
+ * Three stages, each independently testable:
+ *
+ * 1. extractEntitySummaries: walk wiki/entities and wiki/concepts,
+ * pull (slug, title, description, tags) per page. Pure-data;
+ * no LLM.
+ * 2. detectDuplicateGroups: hand the summary list to an LLM, ask
+ * it to identify groups of slugs likely to refer to the same
+ * thing. Returns parsed JSON groups with reason + confidence.
+ * The LLM call is injected so unit tests don't hit a model.
+ * 3. mergeDuplicateGroup: given a confirmed group + chosen
+ * canonical slug, merge bodies (LLM call), union frontmatter
+ * array fields (deterministic), rewrite every wikilink /
+ * `related:` reference / index.md entry across the wiki, and
+ * package up a result the caller writes to disk + backs up.
+ *
+ * The caller (UI) is responsible for filesystem reads/writes and
+ * for showing the user the candidate groups. This module only
+ * transforms data.
+ */
+
+import { parseFrontmatter } from "./frontmatter"
+import {
+ parseFrontmatterArray,
+ mergeArrayFieldsIntoContent,
+ writeFrontmatterArray,
+} from "./sources-merge"
+
+// ──────────────────────────────────────────────────────────────────
+// Types
+// ──────────────────────────────────────────────────────────────────
+
+export interface EntitySummary {
+ /** kebab-case slug (basename without `.md`). */
+ slug: string
+ /** Path relative to project root, e.g. `wiki/entities/foo.md`. */
+ path: string
+ /** entity | concept | source | ... — frontmatter `type` field. */
+ type: string
+ title: string
+ /** Optional one-line description from frontmatter `description`,
+ * or the first non-empty body paragraph as a fallback. Truncated
+ * to ~200 chars to keep the detector prompt small. */
+ description?: string
+ tags: string[]
+}
+
+export interface DuplicateGroup {
+ /** Two or more slugs from the input list. */
+ slugs: string[]
+ /** Why the model believes these are duplicates. Short prose. */
+ reason: string
+ confidence: "high" | "medium" | "low"
+}
+
+export interface MergeRequest {
+ /** Pages in the duplicate group, with their full content loaded. */
+ group: { slug: string; path: string; content: string }[]
+ /** Slug to keep. Must be one of group[].slug. The other pages
+ * are deleted; their wikilinks/related entries get rewritten
+ * to point here. */
+ canonicalSlug: string
+ /** Every other .md under the project's wiki/ tree. Used to
+ * rewrite cross-references when the merge replaces multiple
+ * pages with one. */
+ otherWikiPages: { path: string; content: string }[]
+}
+
+export interface MergeResult {
+ /** Final content of the canonical page (frontmatter + body),
+ * after LLM body merge + deterministic frontmatter unification. */
+ canonicalContent: string
+ /** Path of the canonical page on disk (one of the group's). */
+ canonicalPath: string
+ /** Cross-reference rewrites in other wiki pages. Caller writes
+ * each (path → newContent) back to disk. */
+ rewrites: { path: string; newContent: string }[]
+ /** Paths to delete after canonical + rewrites are written.
+ * Excludes the canonical path. */
+ pagesToDelete: string[]
+ /** Snapshot of every file the merge touches BEFORE the merge
+ * was computed. Caller persists this to .llm-wiki/page-history/
+ * before writing changes so a bad merge can be rolled back. */
+ backup: { path: string; content: string }[]
+}
+
+/**
+ * Generic two-prompt LLM call. Both detector and merger use it.
+ * Production wraps `streamChat`; tests use mocks.
+ */
+export type DedupLlmCall = (
+ systemPrompt: string,
+ userMessage: string,
+ signal?: AbortSignal,
+) => Promise<string>
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 1: extract summaries (no LLM)
+// ──────────────────────────────────────────────────────────────────
+
+/**
+ * Build an EntitySummary from a single page's path + content.
+ * `pathRelativeToProject` should be the canonical wiki-relative
+ * form (`wiki/entities/foo.md`) so callers downstream can derive
+ * slugs consistently.
+ */
+export function extractEntitySummary(
+ pathRelativeToProject: string,
+ content: string,
+): EntitySummary | null {
+ const { frontmatter, body } = parseFrontmatter(content)
+ if (!frontmatter) return null
+ const type = stringField(frontmatter.type) ?? "unknown"
+ const title = stringField(frontmatter.title) ?? slugFromPath(pathRelativeToProject)
+ const description = stringField(frontmatter.description) ?? firstBodyParagraph(body)
+ const tags = arrayField(frontmatter.tags)
+ return {
+ slug: slugFromPath(pathRelativeToProject),
+ path: pathRelativeToProject,
+ type,
+ title,
+ description: description ? truncate(description, 200) : undefined,
+ tags,
+ }
+}
+
+function slugFromPath(path: string): string {
+ const base = path.split("/").pop() ?? path
+ return base.replace(/\.md$/, "")
+}
+
+function stringField(v: unknown): string | undefined {
+ if (typeof v === "string" && v.trim() !== "") return v.trim()
+ return undefined
+}
+
+function arrayField(v: unknown): string[] {
+ if (!Array.isArray(v)) return []
+ return v.filter((x): x is string => typeof x === "string" && x.trim() !== "")
+}
+
+function firstBodyParagraph(body: string): string | undefined {
+ const lines = body.split("\n").map((l) => l.trim()).filter(Boolean)
+ // Skip leading h1/h2 lines so the description isn't just the title again.
+ for (const line of lines) {
+ if (line.startsWith("#")) continue
+ if (line.startsWith("|")) continue // table — too noisy
+ return line
+ }
+ return undefined
+}
+
+function truncate(s: string, max: number): string {
+ if (s.length <= max) return s
+ return s.slice(0, max - 1) + "…"
+}
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 2: LLM-driven duplicate detection
+// ──────────────────────────────────────────────────────────────────
+
+const DETECTOR_SYSTEM_PROMPT = `You are a wiki maintenance assistant. You will receive a list of entity / concept pages from a wiki. Identify groups of slugs that likely refer to the same underlying topic under different names — for example:
+
+- Same name in two languages (English vs Chinese, etc.)
+- Plural vs singular form (e.g. "dpao" vs "dpaos")
+- Abbreviation vs full form (e.g. "vfa" vs "volatile-fatty-acids")
+- Synonyms in the same language
+- The same proper noun spelled differently
+
+Output ONLY valid JSON. No prose, no markdown fences, no explanation outside the JSON. The schema is:
+
+{
+ "groups": [
+ {
+ "slugs": ["slug-a", "slug-b"],
+ "reason": "Both refer to X; first is English, second is Chinese.",
+ "confidence": "high"
+ }
+ ]
+}
+
+Rules:
+- Only include groups of 2 or more slugs from the input list.
+- "high" = clearly the same entity, only naming differs.
+- "medium" = likely the same but context-dependent.
+- "low" = uncertain; user should review carefully.
+- Never invent slugs that aren't in the input.
+- If no duplicates exist, output {"groups": []}.
+- Pages of different \`type\` (e.g. an entity and a concept) usually should NOT be grouped — only group across types when they're unambiguously the same thing.`
+
+/**
+ * Run the LLM duplicate-detector. The caller hands in summaries
+ * (typically every entity + concept page in the wiki) and a
+ * function that wraps an LLM call. Returns parsed, validated
+ * groups — invalid entries (slugs not in the input, single-element
+ * groups) are filtered out so the caller never sees garbage.
+ *
+ * Already-confirmed-not-duplicate groups passed in `notDuplicates`
+ * are filtered out before returning so the same false positive
+ * doesn't keep appearing on every run.
+ */
+export async function detectDuplicateGroups(
+ summaries: EntitySummary[],
+ llmCall: DedupLlmCall,
+ options: { signal?: AbortSignal; notDuplicates?: string[][] } = {},
+): Promise<DuplicateGroup[]> {
+ if (summaries.length < 2) return []
+
+ const userMessage = buildDetectorUserMessage(summaries)
+ const response = await llmCall(DETECTOR_SYSTEM_PROMPT, userMessage, options.signal)
+ const parsed = parseDetectorResponse(response)
+
+ const validSlugs = new Set(summaries.map((s) => s.slug))
+ const notDupSet = new Set(
+ (options.notDuplicates ?? []).map((g) => normalizeGroupKey(g)),
+ )
+
+ return parsed
+ .map((g) => ({ ...g, slugs: g.slugs.filter((s) => validSlugs.has(s)) }))
+ .filter((g) => g.slugs.length >= 2)
+ .filter((g) => !notDupSet.has(normalizeGroupKey(g.slugs)))
+}
+
+function buildDetectorUserMessage(summaries: EntitySummary[]): string {
+ const lines = summaries.map((s) => {
+ const tagPart = s.tags.length > 0 ? ` [${s.tags.join(", ")}]` : ""
+ const descPart = s.description ? ` — ${s.description}` : ""
+ return `- type=${s.type}, slug=${s.slug}, title=${JSON.stringify(s.title)}${tagPart}${descPart}`
+ })
+ return `## Wiki pages to scan (${summaries.length} entries)\n\n${lines.join("\n")}\n\nReturn duplicate groups as JSON only.`
+}
+
+/**
+ * Tolerant JSON extraction. The LLM might wrap output in code
+ * fences (\`\`\`json), prepend "Sure, here you go:", or trail
+ * with a polite "Let me know if...". Pull the first {…} block
+ * with balanced braces and parse it. Returns [] for any failure
+ * — the caller treats "no duplicates found" identically to "LLM
+ * output garbled".
+ */
+export function parseDetectorResponse(raw: string): DuplicateGroup[] {
+ const jsonText = extractFirstJsonObject(raw)
+ if (!jsonText) return []
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(jsonText)
+ } catch {
+ return []
+ }
+ if (!parsed || typeof parsed !== "object") return []
+ const groupsRaw = (parsed as { groups?: unknown }).groups
+ if (!Array.isArray(groupsRaw)) return []
+
+ const out: DuplicateGroup[] = []
+ for (const g of groupsRaw) {
+ if (!g || typeof g !== "object") continue
+ const obj = g as Record<string, unknown>
+ const slugs = Array.isArray(obj.slugs)
+ ? obj.slugs.filter((s): s is string => typeof s === "string")
+ : []
+ if (slugs.length < 2) continue
+ const reason = typeof obj.reason === "string" ? obj.reason : ""
+ const confidence: DuplicateGroup["confidence"] =
+ obj.confidence === "high" || obj.confidence === "medium"
+ ? obj.confidence
+ : "low"
+ out.push({ slugs, reason, confidence })
+ }
+ return out
+}
+
+/** Extract the first balanced `{...}` substring from arbitrary text. */
+function extractFirstJsonObject(text: string): string | null {
+ const start = text.indexOf("{")
+ if (start < 0) return null
+ let depth = 0
+ let inString = false
+ let escape = false
+ for (let i = start; i < text.length; i++) {
+ const ch = text[i]
+ if (escape) {
+ escape = false
+ continue
+ }
+ if (ch === "\\") {
+ escape = true
+ continue
+ }
+ if (ch === '"') {
+ inString = !inString
+ continue
+ }
+ if (inString) continue
+ if (ch === "{") depth++
+ else if (ch === "}") {
+ depth--
+ if (depth === 0) return text.slice(start, i + 1)
+ }
+ }
+ return null
+}
+
+/** Canonical key for a group — lowercased, sorted, comma-joined. */
+function normalizeGroupKey(slugs: string[]): string {
+ return [...slugs].map((s) => s.toLowerCase()).sort().join(",")
+}
+
+// ──────────────────────────────────────────────────────────────────
+// Stage 3: merge a confirmed duplicate group
+// ──────────────────────────────────────────────────────────────────
+
+const MERGER_SYSTEM_PROMPT = `You are a wiki maintenance assistant. You will be given several wiki pages that all describe the same entity or concept under different names. Merge them into a single coherent wiki page.
+
+Output the COMPLETE merged file (frontmatter + body). The first character of your response MUST be "-" (the opening of "---"). No preamble, no explanation outside the file.
+
+Rules:
+- Preserve every distinct factual claim from every input page.
+- Eliminate redundancy (don't say the same thing twice across sections).
+- Reorganize sections so the structure is logical for the unified topic, not a concatenation of inputs.
+- Use [[wikilink]] syntax in the body where the inputs did.
+- Frontmatter: keep the standard fields (type, title, created, updated, tags, related, sources). The caller will overwrite sources / tags / related / updated with deterministic unions afterward — your job is to produce a sensible body and reasonable frontmatter shape.
+- Pick the most descriptive title. If the inputs use different languages, prefer the language that matches the majority of the body content.`
+
+const FIELDS_TO_UNION = ["sources", "tags", "related"] as const
+
+/**
+ * Compute everything needed to merge a confirmed duplicate group:
+ * - LLM call to produce the merged canonical body
+ * - Deterministic frontmatter union (sources, tags, related)
+ * - Canonical slug enforcement on title path
+ * - Cross-reference rewrites across every other wiki page
+ * - Backup snapshot of all touched files
+ *
+ * Returns a MergeResult; the CALLER is responsible for actually
+ * writing canonicalContent + each rewrite + deleting the merged-
+ * away files + storing the backup. Splitting compute from I/O
+ * keeps this testable.
+ */
+export async function mergeDuplicateGroup(
+ req: MergeRequest,
+ llmCall: DedupLlmCall,
+ options: { signal?: AbortSignal; today?: () => string } = {},
+): Promise<MergeResult> {
+ const canonical = req.group.find((p) => p.slug === req.canonicalSlug)
+ if (!canonical) {
+ throw new Error(
+ `canonicalSlug "${req.canonicalSlug}" is not in the group: ${req.group.map((p) => p.slug).join(", ")}`,
+ )
+ }
+ if (req.group.length < 2) {
+ throw new Error("mergeDuplicateGroup requires at least 2 pages in the group")
+ }
+
+ // 1. LLM body merge
+ const userMessage = buildMergerUserMessage(req.group)
+ const llmOutput = await llmCall(MERGER_SYSTEM_PROMPT, userMessage, options.signal)
+
+ // 2. Frontmatter union (deterministic post-processing of LLM output).
+ // For each unioned field, fold every input page's values into
+ // the LLM output via mergeArrayFieldsIntoContent.
+ let merged = llmOutput
+ for (const page of req.group) {
+ merged = mergeArrayFieldsIntoContent(merged, page.content, [...FIELDS_TO_UNION])
+ }
+
+ // 3. Stamp updated to today and force a sensible title.
+ const today = (options.today ?? defaultToday)()
+ merged = setFrontmatterScalar(merged, "updated", today)
+ // If LLM output's frontmatter parses cleanly we leave its title;
+ // if not, the application layer doesn't try to manufacture one.
+
+ // 4. Cross-reference rewrites: every other wiki page that mentions
+ // a non-canonical slug needs its wikilinks / related entries
+ // rewritten to the canonical.
+ const slugRedirects = new Map<string, string>()
+ for (const page of req.group) {
+ if (page.slug !== req.canonicalSlug) {
+ slugRedirects.set(page.slug, req.canonicalSlug)
+ }
+ }
+ const rewrites: MergeResult["rewrites"] = []
+ for (const page of req.otherWikiPages) {
+ const rewritten = rewriteCrossReferences(page.content, slugRedirects)
+ if (rewritten !== page.content) {
+ rewrites.push({ path: page.path, newContent: rewritten })
+ }
+ }
+
+ // 5. Backup: every touched file's PRE-merge content.
+ const backup: MergeResult["backup"] = []
+ for (const page of req.group) {
+ backup.push({ path: page.path, content: page.content })
+ }
+ for (const r of rewrites) {
+ const orig = req.otherWikiPages.find((p) => p.path === r.path)
+ if (orig) backup.push({ path: orig.path, content: orig.content })
+ }
+
+ // 6. Pages to delete: every group member except the canonical.
+ const pagesToDelete = req.group
+ .filter((p) => p.slug !== req.canonicalSlug)
+ .map((p) => p.path)
+
+ return {
+ canonicalContent: merged,
+ canonicalPath: canonical.path,
+ rewrites,
+ pagesToDelete,
+ backup,
+ }
+}
+
+function buildMergerUserMessage(
+ group: { slug: string; content: string }[],
+): string {
+ const sections = group.map((p, i) => {
+ return [
+ `## Page ${i + 1} (slug: ${p.slug})`,
+ "",
+ p.content,
+ "",
+ ].join("\n")
+ })
+ return [
+ `These ${group.length} wiki pages have been confirmed by the user to describe the same topic.`,
+ `Merge them into a single coherent page (the canonical slug will be "${group[0].slug}" or whichever the caller chose).`,
+ "",
+ sections.join("\n---\n\n"),
+ "",
+ "Now output the merged file. First character must be `-`.",
+ ].join("\n")
+}
+
+/**
+ * Rewrite cross-references to merged-away slugs throughout one
+ * page's content. Three forms get rewritten:
+ *
+ * 1. `[[old-slug]]` and `[[old-slug|alias]]` in the body
+ * — replace just the target portion, keep alias if present.
+ * 2. `related: [..., old-slug, ...]` (inline form) — substitute
+ * old-slug with canonical inside the array, then dedup.
+ * 3. `related:\n - old-slug` (block form) — same substitution.
+ *
+ * `wiki/index.md`-style listings of files are out of scope here —
+ * the caller handles index regeneration separately.
+ */
+export function rewriteCrossReferences(
+ content: string,
+ slugRedirects: Map<string, string>,
+): string {
+ let out = content
+
+ // 1. Wikilinks in the body — both [[slug]] and [[slug|alias]].
+ for (const [oldSlug, newSlug] of slugRedirects) {
+ const escaped = escapeRegex(oldSlug)
+ const re = new RegExp(`\\[\\[${escaped}(\\|[^\\]]+)?\\]\\]`, "g")
+ out = out.replace(re, (_match, alias) => `[[${newSlug}${alias ?? ""}]]`)
+ }
+
+ // 2. & 3. `related` field — re-parse and rewrite.
+ const existing = parseFrontmatterArray(out, "related")
+ if (existing.length > 0) {
+ const rewritten = existing.map((s) => slugRedirects.get(s) ?? s)
+ // Deduplicate (case-insensitive, first-seen casing wins)
+ const seen = new Set<string>()
+ const unique: string[] = []
+ for (const s of rewritten) {
+ const k = s.toLowerCase()
+ if (seen.has(k)) continue
+ seen.add(k)
+ unique.push(s)
+ }
+ if (
+ unique.length !== existing.length ||
+ unique.some((s, i) => s !== existing[i])
+ ) {
+ out = writeFrontmatterArray(out, "related", unique)
+ }
+ }
+
+ return out
+}
+
+function escapeRegex(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+}
+
+function setFrontmatterScalar(
+ content: string,
+ field: string,
+ value: string,
+): string {
+ const m = content.match(/^(---\n)([\s\S]*?)(\n---)/)
+ if (!m) return content
+ const [, open, body, close] = m
+ const escaped = field.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+ const newLine = `${field}: ${value}`
+ const lineRe = new RegExp(`^${escaped}:\\s*(?!\\[)([^\\n]*)`, "m")
+ if (lineRe.test(body)) {
+ const rewritten = body.replace(lineRe, newLine)
+ return `${open}${rewritten}${close}${content.slice(m[0].length)}`
+ }
+ return `${open}${body}\n${newLine}${close}${content.slice(m[0].length)}`
+}
+
+function defaultToday(): string {
+ return new Date().toISOString().slice(0, 10)
+}
+
+// ──────────────────────────────────────────────────────────────────
+// Index rewriter — wiki/index.md-specific
+// ──────────────────────────────────────────────────────────────────
+
+/**
+ * Remove entries for merged-away slugs from `wiki/index.md`.
+ * Index files are typically formatted as bullet / link lists
+ * grouped by section. This is a CONSERVATIVE rewriter:
+ * - Removes any whole line that contains a markdown link or
+ * wikilink to a merged-away slug.
+ * - Preserves all other content verbatim (other sections,
+ * intros, the canonical entry).
+ * The caller (UI) shows the user a diff before writing so any
+ * over-removal is visible.
+ */
+export function rewriteIndexMd(
+ content: string,
+ removedSlugs: Set<string>,
+): string {
+ if (removedSlugs.size === 0) return content
+ const lines = content.split("\n")
+ const out: string[] = []
+ for (const line of lines) {
+ if (lineRefersToSlug(line, removedSlugs)) continue
+ out.push(line)
+ }
+ return out.join("\n")
+}
+
+function lineRefersToSlug(line: string, slugs: Set<string>): boolean {
+ for (const slug of slugs) {
+ const escaped = escapeRegex(slug)
+ // Wikilink form: [[slug]] or [[slug|alias]]
+ if (new RegExp(`\\[\\[${escaped}(\\|[^\\]]*)?\\]\\]`).test(line)) return true
+ // Markdown link form: [...](slug.md) or [...](path/slug.md)
+ if (new RegExp(`\\(([^)]*\\/)?${escaped}\\.md\\)`).test(line)) return true
+ // Bare slug.md mention (rare but seen in raw lists)
+ if (new RegExp(`\\b${escaped}\\.md\\b`).test(line)) return true
+ }
+ return false
+}
diff --git a/src/lib/reset-project-state.ts b/src/lib/reset-project-state.ts
index a20b159a..0da2420b 100644
--- a/src/lib/reset-project-state.ts
+++ b/src/lib/reset-project-state.ts
@@ -40,8 +40,9 @@ export async function resetProjectState(): Promise<void> {
// Module-level caches — load in parallel and clear each, surfacing any
// failure instead of swallowing it.
- const [queueMod, graphMod] = await Promise.allSettled([
+ const [queueMod, dedupQueueMod, graphMod] = await Promise.allSettled([
import("@/lib/ingest-queue"),
+ import("@/lib/dedup-queue"),
import("@/lib/graph-relevance"),
])
@@ -59,6 +60,16 @@ export async function resetProjectState(): Promise<void> {
console.warn("[Reset Project State] Failed to load ingest-queue:", queueMod.reason)
}
+ if (dedupQueueMod.status === "fulfilled") {
+ try {
+ await dedupQueueMod.value.pauseQueue()
+ } catch (err) {
+ console.warn("[Reset Project State] dedup pauseQueue failed:", err)
+ }
+ } else {
+ console.warn("[Reset Project State] Failed to load dedup-queue:", dedupQueueMod.reason)
+ }
+
if (graphMod.status === "fulfilled") {
try {
graphMod.value.clearGraphCache()