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: LLM review sweep + multi-language + robustness fixes

nash_su6a2d226d28ab
diff --git a/src/App.tsx b/src/App.tsx
index 1e095e40..14a5966b 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -162,11 +162,11 @@ function App() {
}
}
- function handleSwitchProject() {
- // Clear all per-project state so the welcome screen doesn't leak old data
- import("@/lib/reset-project-state").then(({ resetProjectState }) => {
- resetProjectState()
- })
+ async function handleSwitchProject() {
+ // Clear all per-project state BEFORE flipping back to the welcome screen
+ // so old data cannot leak in via any async render pass.
+ const { resetProjectState } = await import("@/lib/reset-project-state")
+ resetProjectState()
setProject(null)
setFileTree([])
setSelectedFile(null)
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsx
index 2604cf80..1202507c 100644
--- a/src/components/chat/chat-panel.tsx
+++ b/src/components/chat/chat-panel.tsx
@@ -168,6 +168,7 @@ export function ChatPanel() {
// Build system prompt with wiki context using graph-enhanced retrieval
const systemMessages: LLMMessage[] = []
let queryRefs: { title: string; path: string }[] = []
+ let langReminder: string | undefined
if (project) {
const pp = normalizePath(project.path)
const dataVersion = useWikiStore.getState().dataVersion
@@ -317,9 +318,9 @@ export function ChatPanel() {
].filter(Boolean).join("\n"),
})
- // Stash language reminder to inject right before the user's current message
- const langReminder = buildLanguageReminder(text)
- ;(systemMessages as unknown as { __langReminder?: string }).__langReminder = langReminder
+ // Reminder injected later, right before the user's current message
+ // (after history so it's the last system instruction the LLM sees).
+ langReminder = buildLanguageReminder(text)
lastQueryPages = relevantPages.map((p) => ({ title: p.title, path: p.path }))
queryRefs = [...lastQueryPages]
@@ -332,7 +333,6 @@ export function ChatPanel() {
.slice(-maxHistoryMessages)
// Inject language reminder as system message between history and final user query
- const langReminder = (systemMessages as unknown as { __langReminder?: string }).__langReminder
const historyMessages = chatMessagesToLLM(activeConvMessages)
const llmMessages = langReminder && historyMessages.length > 0
? [
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index 829c50d0..a384bcef 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -122,6 +122,45 @@ export function SettingsView() {
<p className="text-xs text-muted-foreground">{t("settings.languageHint")}</p>
</div>
+ {/* Target Language section */}
+ <div className="space-y-4 rounded-lg border p-4">
+ <h3 className="font-semibold">AI Target Language</h3>
+ <p className="text-xs text-muted-foreground">
+ Force all AI-generated content (chat responses, wiki pages, research results, lint reports) to use the selected target language.
+ Choose "Auto" to match the user's input or source document language.
+ </p>
+ <div className="space-y-2">
+ <Label>Language</Label>
+ <select
+ value={localOutputLang}
+ onChange={(e) => setLocalOutputLang(e.target.value as typeof localOutputLang)}
+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
+ >
+ <option value="auto">Auto (detect from input/source)</option>
+ <option value="English">English</option>
+ <option value="Chinese">简体中文 (Simplified Chinese)</option>
+ <option value="Traditional Chinese">繁體中文 (Traditional Chinese)</option>
+ <option value="Japanese">日本語 (Japanese)</option>
+ <option value="Korean">한국어 (Korean)</option>
+ <option value="Vietnamese">Tiếng Việt (Vietnamese)</option>
+ <option value="French">Français (French)</option>
+ <option value="German">Deutsch (German)</option>
+ <option value="Spanish">Español (Spanish)</option>
+ <option value="Portuguese">Português (Portuguese)</option>
+ <option value="Italian">Italiano (Italian)</option>
+ <option value="Russian">Русский (Russian)</option>
+ <option value="Arabic">العربية (Arabic)</option>
+ <option value="Hindi">हिन्दी (Hindi)</option>
+ <option value="Turkish">Türkçe (Turkish)</option>
+ <option value="Dutch">Nederlands (Dutch)</option>
+ <option value="Polish">Polski (Polish)</option>
+ <option value="Swedish">Svenska (Swedish)</option>
+ <option value="Indonesian">Bahasa Indonesia (Indonesian)</option>
+ <option value="Thai">ไทย (Thai)</option>
+ </select>
+ </div>
+ </div>
+
{/* LLM Provider section */}
<div className="space-y-4 rounded-lg border p-4">
<h3 className="font-semibold">{t("settings.llmProvider")}</h3>
@@ -283,45 +322,6 @@ export function SettingsView() {
)}
</div>
- {/* Target Language section */}
- <div className="space-y-4 rounded-lg border p-4">
- <h3 className="font-semibold">AI Target Language</h3>
- <p className="text-xs text-muted-foreground">
- Force all AI-generated content (chat responses, wiki pages, research results, lint reports) to use the selected target language.
- Choose "Auto" to match the user's input or source document language.
- </p>
- <div className="space-y-2">
- <Label>Language</Label>
- <select
- value={localOutputLang}
- onChange={(e) => setLocalOutputLang(e.target.value as typeof localOutputLang)}
- className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
- >
- <option value="auto">Auto (detect from input/source)</option>
- <option value="English">English</option>
- <option value="Chinese">简体中文 (Simplified Chinese)</option>
- <option value="Traditional Chinese">繁體中文 (Traditional Chinese)</option>
- <option value="Japanese">日本語 (Japanese)</option>
- <option value="Korean">한국어 (Korean)</option>
- <option value="Vietnamese">Tiếng Việt (Vietnamese)</option>
- <option value="French">Français (French)</option>
- <option value="German">Deutsch (German)</option>
- <option value="Spanish">Español (Spanish)</option>
- <option value="Portuguese">Português (Portuguese)</option>
- <option value="Italian">Italiano (Italian)</option>
- <option value="Russian">Русский (Russian)</option>
- <option value="Arabic">العربية (Arabic)</option>
- <option value="Hindi">हिन्दी (Hindi)</option>
- <option value="Turkish">Türkçe (Turkish)</option>
- <option value="Dutch">Nederlands (Dutch)</option>
- <option value="Polish">Polski (Polish)</option>
- <option value="Swedish">Svenska (Swedish)</option>
- <option value="Indonesian">Bahasa Indonesia (Indonesian)</option>
- <option value="Thai">ไทย (Thai)</option>
- </select>
- </div>
- </div>
-
{/* Embedding Search section */}
<div className="space-y-4 rounded-lg border p-4">
<div className="flex items-center justify-between">
diff --git a/src/lib/enrich-wikilinks.ts b/src/lib/enrich-wikilinks.ts
index a6d71b6b..20b43b73 100644
--- a/src/lib/enrich-wikilinks.ts
+++ b/src/lib/enrich-wikilinks.ts
@@ -1,7 +1,7 @@
import { readFile, writeFile } from "@/commands/fs"
import { streamChat } from "./llm-client"
import { useWikiStore, type LlmConfig } from "@/stores/wiki-store"
-import { LANGUAGE_RULE } from "./ingest"
+import { buildLanguageDirective } from "./output-language"
import { normalizePath } from "@/lib/path-utils"
/**
@@ -34,7 +34,7 @@ export async function enrichWithWikilinks(
"You are a wiki cross-referencing assistant.",
"Your ONLY job: add [[wikilinks]] to the text where entities or concepts from the wiki index are mentioned.",
"",
- LANGUAGE_RULE,
+ buildLanguageDirective(content),
"",
"Rules:",
"- Return the COMPLETE text with [[wikilinks]] added.",
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index 829af72f..1a4e41af 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -25,6 +25,9 @@ let lastWrittenFiles: string[] = [] // track files written by current ingest fo
// Track whether any task has been processed since the last drain.
// Prevents the sweep from running on every idle/no-op call.
let processedSinceDrain = false
+// Abort controller for the review-sweep LLM call so switching projects
+// cancels a long-running judgment instead of burning tokens.
+let sweepAbortController: AbortController | null = null
// ── Persistence ───────────────────────────────────────────────────────────
@@ -209,10 +212,15 @@ export function clearQueueState(): void {
if (currentAbortController) {
currentAbortController.abort()
}
+ // Abort any in-progress review sweep LLM call
+ if (sweepAbortController) {
+ sweepAbortController.abort()
+ }
queue = []
processing = false
currentProjectPath = ""
currentAbortController = null
+ sweepAbortController = null
lastWrittenFiles = []
processedSinceDrain = false
}
@@ -265,11 +273,18 @@ async function onQueueDrained(projectPath: string): Promise<void> {
if (!processedSinceDrain) return
processedSinceDrain = false
+ sweepAbortController = new AbortController()
+ const signal = sweepAbortController.signal
+
try {
const { sweepResolvedReviews } = await import("@/lib/sweep-reviews")
- await sweepResolvedReviews(projectPath)
+ await sweepResolvedReviews(projectPath, signal)
} catch (err) {
console.error("[Ingest Queue] Failed to load sweep-reviews:", err)
+ } finally {
+ if (sweepAbortController && sweepAbortController.signal === signal) {
+ sweepAbortController = null
+ }
}
}
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index d8cbc0aa..416a2556 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -7,7 +7,7 @@ import { useActivityStore } from "@/stores/activity-store"
import { useReviewStore, type ReviewItem } from "@/stores/review-store"
import { getFileName, normalizePath } from "@/lib/path-utils"
import { checkIngestCache, saveIngestCache } from "@/lib/ingest-cache"
-import { buildLanguageDirective, getOutputLanguage } from "@/lib/output-language"
+import { buildLanguageDirective } from "@/lib/output-language"
const FILE_BLOCK_REGEX = /---FILE:\s*([^\n-]+?)\s*---\n([\s\S]*?)---END FILE---/g
@@ -19,9 +19,6 @@ export function languageRule(sourceContent: string = ""): string {
return buildLanguageDirective(sourceContent)
}
-/** @deprecated Use languageRule() instead — kept for backwards compat with enrich-wikilinks */
-export const LANGUAGE_RULE = buildLanguageDirective("")
-
/**
* Auto-ingest: reads source → LLM analyzes → LLM writes wiki pages, all in one go.
* Used when importing new files.
@@ -601,10 +598,18 @@ export async function executeIngestWrites(
let accumulated = ""
+ // In auto mode, fall back to detecting language from the chat history
+ // (user's discussion messages) rather than the empty string, which would
+ // default to English regardless of the source content.
+ const historyText = conversationHistory
+ .map((m) => m.content)
+ .join("\n")
+ .slice(0, 2000)
+
const systemPrompt = [
"You are a wiki generation assistant. Your task is to produce structured wiki file contents.",
"",
- languageRule(""),
+ languageRule(historyText),
schema ? `## Wiki Schema\n${schema}` : "",
]
.filter(Boolean)
diff --git a/src/lib/lint.ts b/src/lib/lint.ts
index eb90b6fe..d443663f 100644
--- a/src/lib/lint.ts
+++ b/src/lib/lint.ts
@@ -199,10 +199,14 @@ export async function runSemanticLint(
activity.updateItem(activityId, { detail: "Running LLM semantic analysis..." })
+ // For auto-mode language detection, sample the concatenated summaries
+ // so non-English wikis get a matching language directive.
+ const summarySample = summaries.join("\n").slice(0, 2000)
+
const prompt = [
"You are a wiki quality analyst. Review the following wiki page summaries and identify issues.",
"",
- buildLanguageDirective(""),
+ buildLanguageDirective(summarySample),
"",
"For each issue, output exactly this format:",
"",
diff --git a/src/lib/optimize-research-topic.ts b/src/lib/optimize-research-topic.ts
index 287ba985..09feb437 100644
--- a/src/lib/optimize-research-topic.ts
+++ b/src/lib/optimize-research-topic.ts
@@ -1,5 +1,6 @@
import { streamChat } from "./llm-client"
import type { LlmConfig } from "@/stores/wiki-store"
+import { buildLanguageDirective } from "./output-language"
export interface OptimizedTopic {
topic: string
@@ -21,6 +22,8 @@ export async function optimizeResearchTopic(
const prompt = [
"You are a research assistant. Given a knowledge gap found in a personal wiki, generate a precise research topic and search queries.",
"",
+ buildLanguageDirective(`${gapTitle} ${gapDescription} ${purpose} ${overview}`),
+ "",
"## Wiki Context",
purpose ? `### Purpose\n${purpose}` : "",
overview ? `### Current Overview\n${overview}` : "",
@@ -37,8 +40,8 @@ export async function optimizeResearchTopic(
"",
"## Output Format (STRICT — follow exactly, no other text)",
"Respond with EXACTLY 4 lines, no more:",
- "TOPIC: <one sentence>",
- "QUERY: <query 1>",
+ "TOPIC: <one sentence — MUST be in the mandatory output language declared above>",
+ "QUERY: <query 1 — may use English keywords if they better match search engines>",
"QUERY: <query 2>",
"QUERY: <query 3>",
].filter(Boolean).join("\n")
diff --git a/src/lib/reset-project-state.ts b/src/lib/reset-project-state.ts
index 8591cab6..fe12689d 100644
--- a/src/lib/reset-project-state.ts
+++ b/src/lib/reset-project-state.ts
@@ -38,10 +38,14 @@ export function resetProjectState() {
// Ingest queue
import("@/lib/ingest-queue").then(({ clearQueueState }) => {
clearQueueState()
- }).catch(() => {})
+ }).catch((err) => {
+ console.warn("[Reset Project State] Failed to clear ingest queue:", err)
+ })
// Graph relevance cache
import("@/lib/graph-relevance").then(({ clearGraphCache }) => {
clearGraphCache()
- }).catch(() => {})
+ }).catch((err) => {
+ console.warn("[Reset Project State] Failed to clear graph cache:", err)
+ })
}
diff --git a/src/lib/review-utils.ts b/src/lib/review-utils.ts
new file mode 100644
index 00000000..29e56760
--- /dev/null
+++ b/src/lib/review-utils.ts
@@ -0,0 +1,27 @@
+/**
+ * Shared helpers for reasoning about review items.
+ * Kept dependency-free so both the Zustand store and sweep logic can import
+ * it without creating cycles or pulling heavy LLM modules into the store.
+ */
+
+// Common prefixes LLM may prepend in English or Chinese review titles.
+// Kept in one place so dedupe and sweep agree on what "the same concept" means.
+const REVIEW_TITLE_PREFIX_RE =
+ /^(missing[\s-]?page[::]\s*|duplicate[\s-]?page[::]\s*|possible[\s-]?duplicate[::]\s*|缺失页面[::]\s*|缺少页面[::]\s*|重复页面[::]\s*|疑似重复[::]\s*)/i
+
+/**
+ * Normalize a review title for equality comparison:
+ * - strip leading "Missing page:" / "缺失页面:" / etc.
+ * - collapse whitespace
+ * - lowercase
+ *
+ * Two review items with the same (type, normalized title) are considered
+ * the same concept and should be merged rather than duplicated.
+ */
+export function normalizeReviewTitle(title: string): string {
+ return title
+ .replace(REVIEW_TITLE_PREFIX_RE, "")
+ .replace(/\s+/g, " ")
+ .trim()
+ .toLowerCase()
+}
diff --git a/src/lib/sweep-reviews.ts b/src/lib/sweep-reviews.ts
index f2b94fa8..8b3122e2 100644
--- a/src/lib/sweep-reviews.ts
+++ b/src/lib/sweep-reviews.ts
@@ -2,16 +2,35 @@
* Sweep pending review items and auto-resolve those whose underlying
* condition has been addressed by subsequent ingests.
*
- * Triggered when the ingest queue drains.
- * Conservative: only auto-resolves high-certainty cases. Preserves
- * contradiction / suggestion / confirm types that need human judgment.
+ * Triggered when the ingest queue drains. Two stages:
+ * 1. Rule-based matching (filename / frontmatter title / affectedPages)
+ * 2. LLM semantic judgment for remaining pending items
+ *
+ * Conservative: preserves contradiction / suggestion / confirm types
+ * that need human judgment.
*/
import { listDirectory, readFile } from "@/commands/fs"
import { useReviewStore, type ReviewItem } from "@/stores/review-store"
import { useActivityStore } from "@/stores/activity-store"
+import { useWikiStore } from "@/stores/wiki-store"
+import { streamChat } from "@/lib/llm-client"
import type { FileNode } from "@/types/wiki"
import { normalizePath } from "@/lib/path-utils"
+import { normalizeReviewTitle } from "@/lib/review-utils"
+
+// ── Types ─────────────────────────────────────────────────────────────────
+
+interface WikiPageSummary {
+ id: string // filename without .md
+ title: string | null // from frontmatter
+}
+
+interface WikiIndex {
+ byId: Set<string>
+ byTitle: Set<string>
+ pages: WikiPageSummary[]
+}
// ── Helpers ────────────────────────────────────────────────────────────────
@@ -28,13 +47,11 @@ function flattenMdFiles(nodes: FileNode[]): FileNode[] {
}
/** Build an index of wiki pages: id (filename without .md) + title → normalized */
-async function buildWikiIndex(projectPath: string): Promise<{
- byId: Set<string>
- byTitle: Set<string>
-}> {
+async function buildWikiIndex(projectPath: string): Promise<WikiIndex> {
const pp = normalizePath(projectPath)
const byId = new Set<string>()
const byTitle = new Set<string>()
+ const pages: WikiPageSummary[] = []
try {
const tree = await listDirectory(`${pp}/wiki`)
@@ -44,22 +61,25 @@ async function buildWikiIndex(projectPath: string): Promise<{
const id = file.name.replace(/\.md$/, "").toLowerCase()
byId.add(id)
- // Also capture frontmatter title for fuzzy matching
+ let title: string | null = null
try {
const content = await readFile(file.path)
const match = content.match(/^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m)
if (match) {
- byTitle.add(match[1].trim().toLowerCase())
+ title = match[1].trim()
+ byTitle.add(title.toLowerCase())
}
} catch {
// skip unreadable files
}
+
+ pages.push({ id, title })
}
} catch {
// no wiki directory yet
}
- return { byId, byTitle }
+ return { byId, byTitle, pages }
}
/**
@@ -71,12 +91,9 @@ function extractCandidateNames(item: ReviewItem): string[] {
// The review title itself is often the missing page name
// e.g. "Missing page: 注意力机制" or "注意力机制"
- const cleaned = item.title
- .replace(/^(missing[\s-]?page[::]\s*|缺失页面[::]\s*|缺少页面[::]\s*)/i, "")
- .trim()
-
+ const cleaned = normalizeReviewTitle(item.title)
if (cleaned && cleaned.length <= 100) {
- names.add(cleaned.toLowerCase())
+ names.add(cleaned)
}
// Also check affectedPages — these reference files directly
@@ -89,7 +106,7 @@ function extractCandidateNames(item: ReviewItem): string[] {
}
/** Check if a candidate name matches an existing wiki page */
-function pageExists(name: string, index: { byId: Set<string>; byTitle: Set<string> }): boolean {
+function pageExists(name: string, index: WikiIndex): boolean {
const normalized = name.trim().toLowerCase()
if (!normalized) return false
@@ -103,13 +120,209 @@ function pageExists(name: string, index: { byId: Set<string>; byTitle: Set<strin
return false
}
+/**
+ * Extract a JSON object from an LLM response.
+ *
+ * Handles:
+ * - Bare JSON: `{...}`
+ * - Fenced: ` ```json\n{...}\n``` ` or single-line ` ```{...}``` `
+ * - Wrapped in prose: find the first balanced `{...}` object via brace depth
+ *
+ * Returns empty string if no balanced object is found.
+ */
+function extractJsonObject(raw: string): string {
+ let text = raw.trim()
+
+ // Strip an opening ```json or ``` fence (with or without newline)
+ text = text.replace(/^```(?:json)?\s*/i, "")
+ // Strip a trailing ``` fence
+ text = text.replace(/\s*```\s*$/i, "")
+ text = text.trim()
+
+ // Walk brace depth to find the first complete {...}, respecting strings/escapes
+ const start = text.indexOf("{")
+ if (start === -1) return ""
+
+ 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 === "\\" && inString) {
+ 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 ""
+}
+
+const JUDGE_BATCH_SIZE = 40
+const MAX_JUDGE_BATCHES = 5
+const MAX_PAGES_IN_PROMPT = 300
+
+/**
+ * Ask the LLM to judge a single batch of pending reviews. Returns the set of
+ * resolved review IDs (subset of the batch's IDs).
+ *
+ * Conservative: returns empty set on any error (network, parse, config missing,
+ * aborted).
+ */
+async function judgeBatch(
+ batch: ReviewItem[],
+ index: WikiIndex,
+ signal?: AbortSignal,
+): Promise<Set<string>> {
+ if (batch.length === 0 || signal?.aborted) return new Set()
+
+ const llmConfig = useWikiStore.getState().llmConfig
+ const hasConfig =
+ !!llmConfig.apiKey || llmConfig.provider === "ollama" || llmConfig.provider === "custom"
+ if (!hasConfig) return new Set()
+
+ const pages = index.pages.slice(0, MAX_PAGES_IN_PROMPT)
+
+ const pageList = pages
+ .map((p) => (p.title ? `- ${p.id} (title: ${p.title})` : `- ${p.id}`))
+ .join("\n")
+
+ const reviewList = batch
+ .map((r) => {
+ const affected = r.affectedPages?.length ? ` | affected: ${r.affectedPages.join(", ")}` : ""
+ const desc = r.description ? ` — ${r.description.slice(0, 200)}` : ""
+ return `- id=${r.id} [${r.type}] "${r.title}"${desc}${affected}`
+ })
+ .join("\n")
+
+ const prompt = [
+ "You are cleaning up a stale review queue for a personal wiki.",
+ "After recent ingests, some review items may no longer be valid because the missing page now exists, the duplicate was resolved, or the referenced concept has been added.",
+ "",
+ "Current wiki pages (filename, optional title):",
+ pageList || "(no pages yet)",
+ "",
+ "Pending review items to judge:",
+ reviewList,
+ "",
+ "For each review item, decide whether the underlying condition has been RESOLVED by the current wiki state.",
+ "Be conservative: only mark as resolved if you are confident the concern no longer applies.",
+ "For contradictions, confirmations, or human-judgment items, default to keeping them pending.",
+ "",
+ 'Respond with ONLY a JSON object in this exact shape: {"resolved": ["id1", "id2"]}',
+ 'If none of the items are resolved, return exactly: {"resolved": []}',
+ "Do not wrap in markdown fences. Do not add commentary.",
+ ].join("\n")
+
+ let raw = ""
+ let hadError = false
+
+ try {
+ await streamChat(
+ llmConfig,
+ [{ role: "user", content: prompt }],
+ {
+ onToken: (token) => {
+ raw += token
+ },
+ onDone: () => {},
+ onError: (err) => {
+ hadError = true
+ console.warn("[Sweep Reviews] LLM error:", err.message)
+ },
+ },
+ signal,
+ )
+ } catch (err) {
+ console.warn("[Sweep Reviews] LLM call failed:", err)
+ return new Set()
+ }
+
+ if (hadError || signal?.aborted || !raw.trim()) return new Set()
+
+ try {
+ const cleaned = extractJsonObject(raw)
+ if (!cleaned) {
+ console.warn("[Sweep Reviews] No JSON object in response:", raw.slice(0, 300))
+ return new Set()
+ }
+ const parsed = JSON.parse(cleaned) as { resolved?: unknown }
+ if (!parsed || !Array.isArray(parsed.resolved)) return new Set()
+
+ const validIds = new Set(batch.map((i) => i.id))
+ const resolved = new Set<string>()
+ for (const id of parsed.resolved) {
+ if (typeof id === "string" && validIds.has(id)) {
+ resolved.add(id)
+ }
+ }
+ return resolved
+ } catch (err) {
+ console.warn("[Sweep Reviews] Failed to parse LLM response:", err, raw.slice(0, 300))
+ return new Set()
+ }
+}
+
+/**
+ * Judge all remaining pending reviews by processing them in batches.
+ *
+ * - Caps at MAX_JUDGE_BATCHES to avoid unbounded LLM calls per drain.
+ * - Breaks early if a batch resolves nothing (likely nothing else will either).
+ * - Stops immediately on abort.
+ */
+async function llmJudgeReviews(
+ pending: ReviewItem[],
+ index: WikiIndex,
+ signal?: AbortSignal,
+): Promise<Set<string>> {
+ const resolved = new Set<string>()
+ if (pending.length === 0) return resolved
+
+ const remaining = [...pending]
+ let batches = 0
+
+ while (remaining.length > 0 && batches < MAX_JUDGE_BATCHES) {
+ if (signal?.aborted) break
+ const batch = remaining.splice(0, JUDGE_BATCH_SIZE)
+ const batchResolved = await judgeBatch(batch, index, signal)
+ batches++
+
+ if (batchResolved.size === 0) {
+ // Nothing resolved in this batch — further batches likely same result.
+ break
+ }
+ for (const id of batchResolved) resolved.add(id)
+ }
+
+ return resolved
+}
+
// ── Main ──────────────────────────────────────────────────────────────────
/**
* Scan pending review items and auto-resolve those whose condition
* no longer holds. Called when the ingest queue drains.
*/
-export async function sweepResolvedReviews(projectPath: string): Promise<number> {
+export async function sweepResolvedReviews(
+ projectPath: string,
+ signal?: AbortSignal,
+): Promise<number> {
const store = useReviewStore.getState()
const pending = store.items.filter((i) => !i.resolved)
@@ -117,15 +330,19 @@ export async function sweepResolvedReviews(projectPath: string): Promise<number>
const index = await buildWikiIndex(projectPath)
- let resolvedCount = 0
+ let ruleResolved = 0
+ const stillPending: ReviewItem[] = []
+ // Stage 1: rule-based matching
for (const item of pending) {
- // Only auto-resolve types where we can make a high-certainty judgment
+ let resolvedByRule = false
+
if (item.type === "missing-page") {
const names = extractCandidateNames(item)
if (names.length > 0 && names.some((n) => pageExists(n, index))) {
store.resolveItem(item.id, "auto-resolved")
- resolvedCount++
+ ruleResolved++
+ resolvedByRule = true
}
} else if (item.type === "duplicate") {
// If any affected page no longer exists, the duplicate situation changed —
@@ -138,24 +355,75 @@ export async function sweepResolvedReviews(projectPath: string): Promise<number>
})
if (!allStillExist) {
store.resolveItem(item.id, "auto-resolved")
- resolvedCount++
+ ruleResolved++
+ resolvedByRule = true
+ }
+ }
+ }
+
+ if (!resolvedByRule) {
+ stillPending.push(item)
+ }
+ }
+
+ // Stage 2: LLM semantic judgment on what's left
+ let llmResolved = 0
+ const activity = useActivityStore.getState()
+ let activityId: string | null = null
+
+ if (stillPending.length > 0 && !signal?.aborted) {
+ // Surface a running indicator so a multi-second LLM judgment doesn't
+ // feel like the app froze.
+ activityId = activity.addItem({
+ type: "query",
+ title: "Review cleanup",
+ status: "running",
+ detail: `Judging ${stillPending.length} pending review${stillPending.length > 1 ? "s" : ""}…`,
+ filesWritten: [],
+ })
+
+ try {
+ const resolvedIds = await llmJudgeReviews(stillPending, index, signal)
+ if (!signal?.aborted) {
+ for (const id of resolvedIds) {
+ store.resolveItem(id, "llm-judged")
+ llmResolved++
}
}
+ } catch (err) {
+ activity.updateItem(activityId, {
+ status: "error",
+ detail: `Review cleanup failed: ${err instanceof Error ? err.message : String(err)}`,
+ })
+ activityId = null
}
- // contradiction / suggestion / confirm → keep, need human judgment
}
- if (resolvedCount > 0) {
- // Log to activity panel so user sees it happened
- useActivityStore.getState().addItem({
+ const total = ruleResolved + llmResolved
+ const parts: string[] = []
+ if (ruleResolved > 0) parts.push(`${ruleResolved} by rules`)
+ if (llmResolved > 0) parts.push(`${llmResolved} by LLM`)
+ const detail = total > 0
+ ? `Auto-resolved ${total} stale review item${total > 1 ? "s" : ""} (${parts.join(", ")})`
+ : "No stale review items to clean up"
+
+ if (activityId !== null) {
+ activity.updateItem(activityId, {
+ status: signal?.aborted ? "error" : "done",
+ detail: signal?.aborted ? "Review cleanup cancelled" : detail,
+ })
+ } else if (total > 0) {
+ // Rule-only path: no in-progress indicator was shown, add a done item.
+ activity.addItem({
type: "query",
title: "Review cleanup",
status: "done",
- detail: `Auto-resolved ${resolvedCount} stale review item${resolvedCount > 1 ? "s" : ""}`,
+ detail,
filesWritten: [],
})
- console.log(`[Sweep Reviews] Auto-resolved ${resolvedCount} review items`)
}
- return resolvedCount
+ if (total > 0) console.log(`[Sweep Reviews] ${detail}`)
+
+ return total
}
diff --git a/src/stores/review-store.ts b/src/stores/review-store.ts
index fa7e266b..33ed2e8c 100644
--- a/src/stores/review-store.ts
+++ b/src/stores/review-store.ts
@@ -1,4 +1,5 @@
import { create } from "zustand"
+import { normalizeReviewTitle } from "@/lib/review-utils"
export interface ReviewOption {
label: string
@@ -49,24 +50,24 @@ export const useReviewStore = create<ReviewState>((set) => ({
addItems: (items) =>
set((state) => {
- // De-dupe against pending items with same type + normalized title
- // Merge affectedPages / searchQueries / sourcePath instead of creating duplicates
+ // De-dupe against pending items with same type + normalized title (all
+ // 5 types — bulk ingest can re-surface the same contradiction/confirm
+ // from multiple files).
+ // Merge affectedPages / searchQueries / sourcePath instead of duplicating.
const result = [...state.items]
- const keyFor = (t: string, title: string) => `${t}::${title.trim().toLowerCase()}`
+ const keyFor = (t: string, title: string) => `${t}::${normalizeReviewTitle(title)}`
// Build index of existing pending items for fast lookup
const pendingIndex = new Map<string, number>()
result.forEach((it, idx) => {
- if (!it.resolved && (it.type === "missing-page" || it.type === "duplicate" || it.type === "suggestion")) {
+ if (!it.resolved) {
pendingIndex.set(keyFor(it.type, it.title), idx)
}
})
for (const incoming of items) {
const k = keyFor(incoming.type, incoming.title)
- const existingIdx = (incoming.type === "missing-page" || incoming.type === "duplicate" || incoming.type === "suggestion")
- ? pendingIndex.get(k)
- : undefined
+ const existingIdx = pendingIndex.get(k)
if (existingIdx !== undefined) {
// Merge into existing
@@ -88,9 +89,7 @@ export const useReviewStore = create<ReviewState>((set) => ({
createdAt: Date.now(),
}
result.push(newItem)
- if (incoming.type === "missing-page" || incoming.type === "duplicate" || incoming.type === "suggestion") {
- pendingIndex.set(k, result.length - 1)
- }
+ pendingIndex.set(k, result.length - 1)
}
}