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: resume interrupted ingest generation
nash_sucbd1717bae91
diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.tsindex 6cb5a124..c1e09f90 100644--- a/src/lib/ingest-source-path-collision.test.ts+++ b/src/lib/ingest-source-path-collision.test.ts@@ -19,6 +19,7 @@ let truncatedRepairResponse = ""let abortDuringReview: AbortController | null = nulllet interactiveGenerationOverride = ""let mergeRequestCount = 0+let truncateGenerationOnce = falsevi.mock("./llm-client", () => ({streamChat: vi.fn(async (_cfg, messages, cb) => {@@ -120,7 +121,12 @@ vi.mock("./llm-client", () => ({"---END FILE---",generationSuffix,].join("\n"))- cb.onDone()+ if (truncateGenerationOnce) {+ truncateGenerationOnce = false+ cb.onDone({ finishReason: "length", truncated: true })+ } else {+ cb.onDone({ finishReason: "stop", truncated: false })+ }}),}))@@ -153,6 +159,7 @@ describe("autoIngest source summary paths", () => {abortDuringReview = nullinteractiveGenerationOverride = ""mergeRequestCount = 0+ truncateGenerationOnce = falsemockStreamChat.mockClear()mockParseWithMineru.mockReset()tmp = await createTempProject("same-basename-sources")@@ -690,6 +697,72 @@ describe("autoIngest source summary paths", () => {).toBe(true)})+ it("auto-routes a generated typed page into its schema directory", async () => {+ if (!tmp) throw new Error("missing temp project")+ sourceMarkers = ["project-a config"]+ generationSuffix = [+ "",+ "---FILE: wiki/concepts/outcome.md---",+ "---",+ "type: goal",+ 'title: "Outcome"',+ 'sources: ["project-a/config.yaml"]',+ "---",+ "# Outcome",+ "---END FILE---",+ ].join("\n")++ const written = await autoIngest(+ tmp.path,+ `${tmp.path}/raw/sources/project-a/config.yaml`,+ useWikiStore.getState().llmConfig,+ )++ expect(written).toContain("wiki/goals/outcome.md")+ expect(written).not.toContain("wiki/concepts/outcome.md")+ await expect(fs.readFile(`${tmp.path}/wiki/goals/outcome.md`, "utf8"))+ .resolves.toContain("# Outcome")+ })++ it("persists completed files and resumes after a truncated generation", async () => {+ if (!tmp) throw new Error("missing temp project")+ const sourcePath = `${tmp.path}/raw/sources/project-a/config.yaml`+ sourceMarkers = ["first attempt", "resumed attempt"]+ generationSuffix = [+ "",+ "---FILE: wiki/goals/preserved.md---",+ "---",+ "type: goal",+ 'title: "Preserved"',+ 'sources: ["project-a/config.yaml"]',+ "---",+ "# Preserved",+ "---END FILE---",+ ].join("\n")+ truncateGenerationOnce = true++ await expect(autoIngest(+ tmp.path,+ sourcePath,+ useWikiStore.getState().llmConfig,+ )).rejects.toThrow("generation reached its output limit")+ await expect(fs.readFile(`${tmp.path}/wiki/goals/preserved.md`, "utf8"))+ .resolves.toContain("# Preserved")++ generationSuffix = ""+ await autoIngest(tmp.path, sourcePath, useWikiStore.getState().llmConfig)++ const generationCalls = mockStreamChat.mock.calls.filter(([, messages]) =>+ String(messages[0]?.content ?? "").includes("## What to generate"),+ )+ const resumedPrompt = String(generationCalls[generationCalls.length - 1]?.[1]?.[1]?.content ?? "")+ expect(resumedPrompt)+ .toContain("## Resume checkpoint")+ expect(resumedPrompt).toContain("wiki/goals/preserved.md")+ const checkpointFiles = await fs.readdir(`${tmp.path}/.llm-wiki/ingest-generation`)+ expect(checkpointFiles).toHaveLength(0)+ })+it("rejects an ingest when a truncated FILE block cannot be repaired", async () => {if (!tmp) throw new Error("missing temp project")sourceMarkers = ["project-a config"]diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 5e2d33aa..ca759f8a 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -338,6 +338,14 @@ interface LongSourceCheckpoint {updatedAt: number}+interface GenerationCheckpoint {+ version: 1+ sourceIdentity: string+ sourceFingerprint: string+ completedPaths: string[]+ updatedAt: number+}+/*** Resolve the LLM config that the caption pipeline should use.* `null` = captioning is OFF, caller should skip the pipeline@@ -375,6 +383,7 @@ import { buildLanguageDirective, getOutputLanguage } from "@/lib/output-languageimport { detectLanguage } from "@/lib/detect-language"import { getLanguagePromptName, sameScriptFamily } from "@/lib/language-metadata"import {+ correctWikiPageRouting,loadProjectWikiSchemaRouting,validateWikiPageRouting,} from "@/lib/wiki-schema"@@ -1112,60 +1121,90 @@ async function autoIngestImpl(// LLM takes the analysis as context and produces wiki files + review itemsactivity.updateItem(activityId, { detail: "Step 2/2: Generating wiki pages..." })+ const generationFingerprint = await sourceGenerationFingerprint(sp, sourceContent)+ const generationProgressPath = generationCheckpointPath(+ pp,+ sourceSummarySlug,+ generationFingerprint,+ )+ const generationCheckpoint = await loadGenerationCheckpoint(+ generationProgressPath,+ sourceIdentity,+ generationFingerprint,+ pp,+ )+ const previouslyCompletedPaths = generationCheckpoint?.completedPaths ?? []let generation = ""+ let generationError: string | null = null+ let generationTruncated = false- await streamChat(- llmConfig,- [- { role: "system", content: buildGenerationPrompt(schema, purpose, index, sourceIdentity, overview, sourceContext, sourceSummaryPath) },+ try {+ await streamChat(+ llmConfig,+ [+ { role: "system", content: buildGenerationPrompt(schema, purpose, index, sourceIdentity, overview, sourceContext, sourceSummaryPath) },+ {+ role: "user",+ content: [+ `Source document to process: **${sourceIdentity}**`,+ "",+ "The Stage 1 analysis below is CONTEXT to inform your output. Do NOT echo",+ "its tables, bullet points, or prose. Your output must be FILE/REVIEW",+ "blocks as specified in the system prompt — nothing else.",+ previouslyCompletedPaths.length > 0+ ? [+ "",+ "## Resume checkpoint",+ "The following FILE paths were already written successfully in an earlier attempt.",+ "Do not emit them again. Emit only the remaining pages required by the analysis:",+ ...previouslyCompletedPaths.map((path) => `- ${path}`),+ ].join("\n")+ : "",+ "",+ "## Stage 1 Analysis (context only — do not repeat)",+ "",+ analysis,+ "",+ "## Source Context",+ "",+ sourceContext,+ "",+ "---",+ "",+ `Now emit the FILE blocks for the wiki files derived from **${sourceIdentity}**.`,+ "Your response MUST begin with `---FILE:` as the very first characters.",+ "No preamble. No analysis prose. Start immediately.",+ ].filter(Boolean).join("\n"),+ },+ ],{- role: "user",- content: [- `Source document to process: **${sourceIdentity}**`,- "",- "The Stage 1 analysis below is CONTEXT to inform your output. Do NOT echo",- "its tables, bullet points, or prose. Your output must be FILE/REVIEW",- "blocks as specified in the system prompt — nothing else.",- "",- "## Stage 1 Analysis (context only — do not repeat)",- "",- analysis,- "",- "## Source Context",- "",- sourceContext,- "",- "---",- "",- `Now emit the FILE blocks for the wiki files derived from **${sourceIdentity}**.`,- "Your response MUST begin with `---FILE:` as the very first characters.",- "No preamble. No analysis prose. Start immediately.",- ].join("\n"),+ onToken: (token) => { generation += token },+ onDone: (completion) => { generationTruncated = completion?.truncated === true },+ onError: (err) => { generationError = err.message },},- ],- {- onToken: (token) => { generation += token },- onDone: () => {},- onError: (err) => {- activity.updateItem(activityId, { status: "error", detail: `Generation failed: ${err.message}` })+ signal,+ {+ temperature: 0.1,+ reasoning: resolveIngestReasoning(llmConfig),+ max_tokens: computeIngestGenerationMaxTokens(llmConfig.maxContextSize),},- },- signal,- {- temperature: 0.1,- reasoning: resolveIngestReasoning(llmConfig),- max_tokens: computeIngestGenerationMaxTokens(llmConfig.maxContextSize),- },- )+ )+ } catch (err) {+ throwIfIngestAborted(signal, activityId)+ generationError = err instanceof Error ? err.message : String(err)+ }- const generationActivity = useActivityStore.getState().items.find((i) => i.id === activityId)- if (generationActivity?.status === "error") {- throw new Error(generationActivity.detail || "Generation stream failed")+ if ((generationError || generationTruncated) && parseFileBlocks(generation).blocks.length === 0) {+ const message = generationError+ ? `Generation failed before any complete wiki file was produced: ${generationError}`+ : "Generation was truncated before any complete wiki file was produced."+ activity.updateItem(activityId, { status: "error", detail: message })+ throw new Error(message)}throwIfIngestAborted(signal, activityId)let reviewSuggestionOutput = ""- if (!signal?.aborted && shouldRunDedicatedReviewStage(generation)) {+ if (!generationError && !generationTruncated && !signal?.aborted && shouldRunDedicatedReviewStage(generation)) {let reviewStageHadError = falsetry {await streamChat(@@ -1227,7 +1266,10 @@ async function autoIngestImpl(onFileWritten,)throwIfIngestAborted(signal, activityId)- const writtenPaths = writeResult.writtenPaths+ const writtenPaths = uniqueNormalizedPaths([+ ...previouslyCompletedPaths,+ ...writeResult.writtenPaths,+ ])const writeWarnings = writeResult.warningsconst hardFailures = writeResult.hardFailureslet unrecoveredTruncatedPaths = uniqueNormalizedPaths(@@ -1428,8 +1470,27 @@ async function autoIngestImpl(// incomplete result. Throwing here keeps the queue task visible as// pending/failed instead of removing it as "done" while Sources reports the// same file as not ingested.- if (hardFailures.length > 0 || unrecoveredTruncatedPaths.length > 0) {+ const generationIncomplete = Boolean(generationError) || generationTruncated+ if (generationIncomplete && writtenPaths.length > 0) {+ try {+ await saveGenerationCheckpoint(generationProgressPath, {+ version: 1,+ sourceIdentity,+ sourceFingerprint: generationFingerprint,+ completedPaths: writtenPaths.filter((path) => !isAppManagedAggregatePath(path)),+ updatedAt: Date.now(),+ })+ } catch (err) {+ hardFailures.push(+ `Generation checkpoint write failed: ${err instanceof Error ? err.message : String(err)}`,+ )+ }+ }++ if (hardFailures.length > 0 || unrecoveredTruncatedPaths.length > 0 || generationIncomplete) {const reasons = [+ generationError ? `generation stream failed: ${generationError}` : "",+ generationTruncated ? "generation reached its output limit" : "",hardFailures.length > 0? `${hardFailures.length} wiki file write failure(s)`: "",@@ -1469,6 +1530,7 @@ async function autoIngestImpl(unrecoveredTruncatedPaths.length === 0) {await saveIngestCache(pp, sourceIdentity, sourceContent, writtenPaths)+ await clearGenerationCheckpoint(generationProgressPath)if (longSourceCheckpointPath) {await clearLongSourceCheckpoint(longSourceCheckpointPath)}@@ -2009,11 +2071,23 @@ async function writeFileBlocks(!isLogPath(relativePath) &&!isListingPath(relativePath)) {- const routingIssue = validateWikiPageRouting(+ const correction = correctWikiPageRouting(relativePath,content,projectSchemaRouting,)+ if (correction.message) {+ if (!isSafeIngestPath(correction.path)) {+ const msg = `Dropped "${relativePath}" — corrected schema path was unsafe.`+ console.warn(`[ingest] ${msg}`)+ warnings.push(msg)+ continue+ }+ console.info(`[ingest] ${correction.message}`)+ warnings.push(correction.message)+ relativePath = correction.path+ }+ const routingIssue = validateWikiPageRouting(relativePath, content, projectSchemaRouting)if (routingIssue) {const msg = `Dropped "${relativePath}" — ${routingIssue.message}`console.warn(`[ingest] ${msg}`)@@ -2830,6 +2904,65 @@ function longSourceCheckpointPath(return `${normalizePath(projectPath)}/.llm-wiki/ingest-progress/${sourceSummarySlug}-${sourceHash}.json`}+function generationCheckpointPath(+ projectPath: string,+ sourceSummarySlug: string,+ sourceFingerprint: string,+): string {+ return `${normalizePath(projectPath)}/.llm-wiki/ingest-generation/${sourceSummarySlug}-${sourceFingerprint}.json`+}++async function sourceGenerationFingerprint(sourcePath: string, sourceContent: string): Promise<string> {+ const [modified, size] = await Promise.all([+ getFileModifiedTime(sourcePath).catch(() => 0),+ getFileSize(sourcePath).catch(() => 0),+ ])+ return hashTextHex(`${sourceContent}\0${modified}\0${size}`)+}++async function loadGenerationCheckpoint(+ checkpointPath: string,+ sourceIdentity: string,+ sourceFingerprint: string,+ projectPath: string,+): Promise<GenerationCheckpoint | null> {+ try {+ const parsed = JSON.parse(await readFile(checkpointPath)) as GenerationCheckpoint+ if (+ parsed.version !== 1 ||+ parsed.sourceIdentity !== sourceIdentity ||+ parsed.sourceFingerprint !== sourceFingerprint ||+ !Array.isArray(parsed.completedPaths)+ ) return null+ const completedPaths: string[] = []+ for (const path of uniqueNormalizedPaths(parsed.completedPaths)) {+ if (isSafeIngestPath(path) && await fileExists(`${projectPath}/${path}`)) {+ completedPaths.push(path)+ }+ }+ return { ...parsed, completedPaths }+ } catch {+ return null+ }+}++async function saveGenerationCheckpoint(+ checkpointPath: string,+ checkpoint: GenerationCheckpoint,+): Promise<void> {+ await createDirectory(checkpointPath.split("/").slice(0, -1).join("/"))+ await writeFile(checkpointPath, JSON.stringify(checkpoint, null, 2))+}++async function clearGenerationCheckpoint(checkpointPath: string): Promise<void> {+ try {+ if (await fileExists(checkpointPath)) await deleteFile(checkpointPath)+ } catch {+ // Best-effort cleanup; a completed checkpoint is harmless because the+ // ingest cache short-circuits subsequent unchanged-source runs.+ }+}+function isCompatibleLongSourceCheckpoint(checkpoint: LongSourceCheckpoint,params: {diff --git a/src/lib/wiki-schema.test.ts b/src/lib/wiki-schema.test.tsindex 1f291b52..4f5bf07c 100644--- a/src/lib/wiki-schema.test.ts+++ b/src/lib/wiki-schema.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest"import {+ correctWikiPageRouting,parseWikiSchemaRouting,validateWikiPageRouting,} from "./wiki-schema"@@ -53,6 +54,47 @@ describe("parseWikiSchemaRouting", () => {concept: "wiki/concepts",})})++ it("rejects schema directories that escape or are invalid on Windows", () => {+ const routing = parseWikiSchemaRouting([+ "## Page Types",+ "| Type | Directory |",+ "| --- | --- |",+ "| escape | wiki/../outside/ |",+ "| windows | wiki/bad:name/ |",+ "| safe | wiki/安全/ |",+ ].join("\n"))++ expect(routing.typeDirs).toEqual({ safe: "wiki/安全" })+ })+})++describe("correctWikiPageRouting", () => {+ const routing = parseWikiSchemaRouting(SCHEMA)++ it("moves a typed page to its schema directory while preserving its filename", () => {+ expect(correctWikiPageRouting(+ "wiki/concepts/retrieval.md",+ "---\ntype: method\ntitle: Retrieval\n---\n# Retrieval",+ routing,+ )).toEqual({+ path: "wiki/methods/retrieval.md",+ message: 'Auto-routed page type "method" from "wiki/concepts/" to "wiki/methods/".',+ })+ })++ it("leaves unknown and already-correct routes unchanged", () => {+ expect(correctWikiPageRouting(+ "wiki/methods/retrieval.md",+ "---\ntype: method\n---",+ routing,+ ).message).toBeNull()+ expect(correctWikiPageRouting(+ "wiki/custom/item.md",+ "---\ntype: custom\n---",+ routing,+ ).path).toBe("wiki/custom/item.md")+ })})describe("validateWikiPageRouting", () => {diff --git a/src/lib/wiki-schema.ts b/src/lib/wiki-schema.tsindex efe30c6b..a7a67b0d 100644--- a/src/lib/wiki-schema.ts+++ b/src/lib/wiki-schema.ts@@ -9,6 +9,11 @@ export interface WikiSchemaRoutingIssue {message: string}+export interface WikiSchemaRouteCorrection {+ path: string+ message: string | null+}+export async function loadProjectWikiSchemaRouting(projectPath: string,): Promise<WikiSchemaRouting | null> {@@ -36,7 +41,7 @@ export function parseWikiSchemaRouting(markdown: string): WikiSchemaRouting {const [type, dir] = cellsif (!/^[a-z][a-z0-9_-]*$/i.test(type)) continue- if (dir !== "wiki" && !dir.startsWith("wiki/")) continue+ if (!isSafeWikiDirectory(dir)) continuetypeDirs[type] = stripTrailingSlash(dir)}@@ -91,6 +96,31 @@ export function validateWikiPageRouting(return null}+export function correctWikiPageRouting(+ relativePath: string,+ content: string,+ routing: WikiSchemaRouting,+): WikiSchemaRouteCorrection {+ const parsed = parseFrontmatter(content)+ const type = parsed.frontmatter?.type+ const normalizedPath = normalizeRelativePath(relativePath)+ if (typeof type !== "string" || !type.trim()) {+ return { path: normalizedPath, message: null }+ }++ const expectedDir = routing.typeDirs[type]+ const actualDir = dirname(normalizedPath)+ if (!expectedDir || actualDir === expectedDir) {+ return { path: normalizedPath, message: null }+ }++ const fileName = normalizedPath.slice(normalizedPath.lastIndexOf("/") + 1)+ return {+ path: `${expectedDir}/${fileName}`,+ message: `Auto-routed page type "${type}" from "${actualDir}/" to "${expectedDir}/".`,+ }+}+function inferTypeFromSchemaPath(relativePath: string,routing: WikiSchemaRouting,@@ -115,3 +145,13 @@ function dirname(relativePath: string): string {function stripTrailingSlash(value: string): string {return value.replace(/\/+$/, "")}++function isSafeWikiDirectory(value: string): boolean {+ const withoutTrailingSlash = stripTrailingSlash(value)+ const normalized = normalizeRelativePath(withoutTrailingSlash)+ if (normalized !== withoutTrailingSlash) return false+ if (normalized !== "wiki" && !normalized.startsWith("wiki/")) return false+ return normalized.split("/").every((segment) => (+ segment.length > 0 && segment !== "." && segment !== ".." && !/[<>:"|?*\\]/.test(segment)+ ))+}diff --git a/src/test-helpers/fs-temp.ts b/src/test-helpers/fs-temp.tsindex 09e68c98..d969176c 100644--- a/src/test-helpers/fs-temp.ts+++ b/src/test-helpers/fs-temp.ts@@ -75,6 +75,12 @@ export const realFs = {() => false,)},+ getFileModifiedTime: async (p: string): Promise<number> => {+ return (await fs.stat(p)).mtimeMs+ },+ getFileSize: async (p: string): Promise<number> => {+ return (await fs.stat(p)).size+ },findRelatedWikiPages: async (): Promise<string[]> => {return []},