Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix(ingest): prevent extra source blocks from overwriting summaries

xinyuan0801b03508fcad7d
diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.ts
index 48e4c111..884df571 100644
--- a/src/lib/ingest-source-path-collision.test.ts
+++ b/src/lib/ingest-source-path-collision.test.ts
@@ -14,6 +14,7 @@ vi.mock("@/commands/fs", () => realFs)
let sourceMarkers: string[] = []
let failLongChunksOnce = new Set<number>()
let extraReviewResponse = ""
+let generationPrefix = ""
let generationSuffix = ""
let truncatedRepairResponse = ""
let abortDuringReview: AbortController | null = null
@@ -43,7 +44,7 @@ vi.mock("./llm-client", () => ({
return
}
cb.onToken([
- "---FILE: wiki/sources/config.md---",
+ `---FILE: ${String(messages.at(-1)?.content).match(/exact path: \*\*([^*]+)\*\*/)?.[1] ?? "wiki/sources/config.md"}---`,
"---",
'type: "source"',
'title: "Source: config.yaml"',
@@ -123,6 +124,7 @@ vi.mock("./llm-client", () => ({
const sourceIdentity =
systemPrompt.match(/original source file is:\s*\*\*([^*]+)\*\*/i)?.[1] ?? "config.yaml"
cb.onToken([
+ generationPrefix,
`---FILE: ${targetPath}---`,
"---",
`title: "Source: ${sourceIdentity}"`,
@@ -168,6 +170,7 @@ describe("autoIngest source summary paths", () => {
sourceMarkers = []
failLongChunksOnce = new Set()
extraReviewResponse = ""
+ generationPrefix = ""
generationSuffix = ""
truncatedRepairResponse = ""
abortDuringReview = null
@@ -261,6 +264,108 @@ describe("autoIngest source summary paths", () => {
expect(content).toContain("-end")
})
+ it.each(["before", "after"])("preserves the exact summary when a cited work appears %s it", async (order) => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["correct source summary"]
+ const citationPath = "wiki/sources/the-bitter-lesson.md"
+ const existingCitation = "# Existing cited work\n\nKeep this page unchanged."
+ await writeFileRaw(`${tmp.path}/${citationPath}`, existingCitation)
+ const citationBlock = `---FILE: ${citationPath}---\n# Wrong cited-work summary\n---END FILE---`
+ if (order === "before") generationPrefix = citationBlock
+ else generationSuffix = citationBlock
+
+ const written = await autoIngest(tmp.path, `${tmp.path}/raw/sources/project-a/config.yaml`, useWikiStore.getState().llmConfig)
+ const summaryPath = `wiki/sources/${sourceSummarySlugFromIdentity("project-a/config.yaml")}.md`
+ const content = await fs.readFile(`${tmp.path}/${summaryPath}`, "utf8")
+
+ expect(content).toContain("correct source summary")
+ expect(content).not.toContain("Wrong cited-work summary")
+ expect(written.filter((p) => p === summaryPath)).toHaveLength(1)
+ expect(await fs.readFile(`${tmp.path}/${citationPath}`, "utf8")).toBe(existingCitation)
+ expect(await fs.readFile(`${tmp.path}/.llm-wiki/ingest-warnings.log`, "utf8")).toContain(`Ignored unexpected source summary "${citationPath}"`)
+ })
+
+ it("preserves the first successful summary when its exact path is emitted twice", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["first correct summary"]
+ const summaryPath = `wiki/sources/${sourceSummarySlugFromIdentity("project-a/config.yaml")}.md`
+ generationSuffix = `---FILE: ${summaryPath}---\n# Later incorrect replacement\n---END FILE---`
+
+ await autoIngest(tmp.path, `${tmp.path}/raw/sources/project-a/config.yaml`, useWikiStore.getState().llmConfig)
+
+ const content = await fs.readFile(`${tmp.path}/${summaryPath}`, "utf8")
+ expect(content).toContain("first correct summary")
+ expect(content).not.toContain("Later incorrect replacement")
+ expect(await fs.readFile(`${tmp.path}/.llm-wiki/ingest-warnings.log`, "utf8")).toContain("Ignored duplicate source summary")
+ })
+
+ it("prevents schema routing from overwriting an already-written source summary", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["correct source summary"]
+ await writeFileRaw(`${tmp.path}/schema.md`, "## Page Types\n| source | wiki/sources/ | Source summaries |")
+ const slug = sourceSummarySlugFromIdentity("project-a/config.yaml")
+ generationSuffix = `---FILE: wiki/concepts/${slug}.md---\n---\ntype: source\n---\n# Wrong routed replacement\n---END FILE---`
+
+ await autoIngest(tmp.path, `${tmp.path}/raw/sources/project-a/config.yaml`, useWikiStore.getState().llmConfig)
+
+ expect(await fs.readFile(`${tmp.path}/wiki/sources/${slug}.md`, "utf8")).toContain("correct source summary")
+ expect(await fs.readFile(`${tmp.path}/.llm-wiki/ingest-warnings.log`, "utf8")).toContain("Ignored duplicate source summary")
+ })
+
+ it("does not repair an unexpected truncated source summary onto the current source", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["correct source summary"]
+ generationSuffix = "---FILE: wiki/sources/cited-work.md---\n# Incomplete cited work"
+ truncatedRepairResponse = "---FILE: wiki/sources/cited-work.md---\n# Wrong repair\n---END FILE---"
+
+ await autoIngest(tmp.path, `${tmp.path}/raw/sources/project-a/config.yaml`, useWikiStore.getState().llmConfig)
+
+ const summaryPath = `wiki/sources/${sourceSummarySlugFromIdentity("project-a/config.yaml")}.md`
+ expect(await fs.readFile(`${tmp.path}/${summaryPath}`, "utf8")).toContain("correct source summary")
+ await expect(fs.access(`${tmp.path}/wiki/sources/cited-work.md`)).rejects.toThrow()
+ expect(mockStreamChat.mock.calls.some(([, messages]) => String(messages[0]?.content).startsWith("You are repairing truncated wiki FILE blocks"))).toBe(false)
+ })
+
+ it("protects the source summary while repairing a different truncated page", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["correct source summary"]
+ const summaryPath = `wiki/sources/${sourceSummarySlugFromIdentity("project-a/config.yaml")}.md`
+ generationSuffix = "---FILE: wiki/concepts/recovered.md---\n# Incomplete concept"
+ truncatedRepairResponse = [
+ "---FILE: wiki/concepts/recovered.md---\n# Recovered concept\n---END FILE---",
+ `---FILE: ${summaryPath}---\n# Wrong replacement\n---END FILE---`,
+ "---FILE: wiki/sources/cited-work.md---\n# Wrong cited work\n---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/concepts/recovered.md")
+ expect(await fs.readFile(`${tmp.path}/${summaryPath}`, "utf8")).toContain("correct source summary")
+ await expect(fs.access(`${tmp.path}/wiki/sources/cited-work.md`)).rejects.toThrow()
+ })
+
+ it("rejects additional and duplicate source summaries during interactive writes", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ useChatStore.getState().createConversation()
+ const summaryPath = `wiki/sources/${sourceSummarySlugFromIdentity("project-a/config.yaml")}.md`
+ interactiveGenerationOverride = [
+ "---FILE: wiki/sources/cited-work.md---\n# Wrong cited work\n---END FILE---",
+ `---FILE: ${summaryPath}---\n# Correct interactive summary\n---END FILE---`,
+ `---FILE: ${summaryPath}---\n# Wrong duplicate\n---END FILE---`,
+ ].join("\n")
+ useChatStore.setState({ ingestSource: `${tmp.path}/raw/sources/project-a/config.yaml` })
+
+ const written = await executeIngestWrites(tmp.path, useWikiStore.getState().llmConfig)
+
+ expect(written).toEqual([`${tmp.path}/${summaryPath}`])
+ expect(await fs.readFile(written[0], "utf8")).toContain("Correct interactive summary")
+ await expect(fs.access(`${tmp.path}/wiki/sources/cited-work.md`)).rejects.toThrow()
+ const warnings = await fs.readFile(`${tmp.path}/.llm-wiki/ingest-warnings.log`, "utf8")
+ expect(warnings).toContain("Ignored unexpected source summary")
+ expect(warnings).toContain("Ignored duplicate source summary")
+ expect(useChatStore.getState().messages.some((m) => m.role === "system" && m.content.includes("Ingest warnings:"))).toBe(true)
+ })
+
it("keeps distinct source summaries for same-basename files in different source subdirectories", async () => {
if (!tmp) throw new Error("missing temp project")
sourceMarkers = ["project-a config", "project-b config"]
@@ -785,6 +890,22 @@ describe("autoIngest source summary paths", () => {
expect(checkpointFiles).toHaveLength(0)
})
+ it("preserves a completed source summary when a resumed generation emits it again", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ sourceMarkers = ["first complete summary", "wrong resumed replacement"]
+ truncateGenerationOnce = true
+ const sourcePath = `${tmp.path}/raw/sources/project-a/config.yaml`
+ await expect(autoIngest(tmp.path, sourcePath, useWikiStore.getState().llmConfig)).rejects.toThrow("generation reached its output limit")
+
+ generationSuffix = "---FILE: wiki/concepts/remaining.md---\n# Remaining concept\n---END FILE---"
+ await autoIngest(tmp.path, sourcePath, useWikiStore.getState().llmConfig)
+
+ const summaryPath = `wiki/sources/${sourceSummarySlugFromIdentity("project-a/config.yaml")}.md`
+ const content = await fs.readFile(`${tmp.path}/${summaryPath}`, "utf8")
+ expect(content).toContain("first complete summary")
+ expect(content).not.toContain("wrong resumed replacement")
+ })
+
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"]
@@ -925,7 +1046,7 @@ describe("autoIngest source summary paths", () => {
).toBe(false)
})
- it("canonicalizes interactive source summary paths and sources frontmatter", async () => {
+ it("canonicalizes interactive source frontmatter at the requested summary path", async () => {
if (!tmp) throw new Error("missing temp project")
const conversationId = "conv-interactive-source"
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index ad283e3e..d820797f 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -1277,6 +1277,7 @@ async function autoIngestImpl(
signal,
activityId,
onFileWritten,
+ previouslyCompletedPaths.includes(sourceSummaryPath),
)
throwIfIngestAborted(signal, activityId)
const writtenPaths = uniqueNormalizedPaths([
@@ -1355,6 +1356,7 @@ async function autoIngestImpl(
signal,
activityId,
onFileWritten,
+ writtenPaths.includes(sourceSummaryPath),
)
// Match successful writes against the paths requested from the model,
// not the final on-disk paths. writeFileBlocks may legitimately rewrite
@@ -2013,6 +2015,22 @@ function setOrAppendFrontmatterDate(payload: string, key: "created" | "updated",
return `${payload.trimEnd()}\n${key}: ${date}`
}
+function sourceSummaryBlockWarning(
+ path: string,
+ sourceSummaryPath: string | undefined,
+ summaryWritten: boolean,
+): string | null {
+ const normalized = normalizePath(path)
+ if (!sourceSummaryPath || !normalized.toLowerCase().startsWith("wiki/sources/")) return null
+ if (normalized !== sourceSummaryPath) {
+ return `Ignored unexpected source summary "${path}"; only "${sourceSummaryPath}" may describe the current source.`
+ }
+ if (summaryWritten) {
+ return `Ignored duplicate source summary "${path}"; the first successful summary was preserved.`
+ }
+ return null
+}
+
async function writeFileBlocks(
projectPath: string,
text: string,
@@ -2022,6 +2040,7 @@ async function writeFileBlocks(
signal?: AbortSignal,
activityId?: string,
onFileWritten?: (relativePath: string) => void,
+ summaryAlreadyWritten = false,
): Promise<{
writtenPaths: string[]
completedInputPaths: string[]
@@ -2032,6 +2051,7 @@ async function writeFileBlocks(
const { blocks, warnings: parseWarnings, truncatedPaths } = parseFileBlocks(text)
const warnings = [...parseWarnings]
const writtenPaths: string[] = []
+ let summaryWritten = summaryAlreadyWritten
// Keep the model-requested path separate from the final path. Path
// canonicalization may rename the file after parsing, but callers that
// repair a specific FILE block still need to know that request succeeded.
@@ -2052,9 +2072,11 @@ async function writeFileBlocks(
for (const { path: rawRelativePath, content: rawContent } of blocks) {
throwIfIngestAborted(signal, activityId)
- let relativePath = rawRelativePath
- if (sourceSummaryPath && relativePath.startsWith("wiki/sources/")) {
- relativePath = sourceSummaryPath
+ let relativePath = normalizePath(rawRelativePath)
+ const summaryWarning = sourceSummaryBlockWarning(relativePath, sourceSummaryPath, summaryWritten)
+ if (summaryWarning) {
+ warnings.push(summaryWarning)
+ continue
}
if (isAppManagedAggregatePath(relativePath)) {
warnings.push(
@@ -2115,6 +2137,14 @@ async function writeFileBlocks(
}
}
+ // Schema routing can move another typed page into wiki/sources/, so
+ // enforce the same boundary again on its final destination.
+ const routedSummaryWarning = sourceSummaryBlockWarning(relativePath, sourceSummaryPath, summaryWritten)
+ if (routedSummaryWarning) {
+ warnings.push(routedSummaryWarning)
+ continue
+ }
+
// Language guard: reject individual FILE blocks whose body contradicts
// the user-set target language. Skip:
// - log.md (structural, short)
@@ -2198,6 +2228,7 @@ async function writeFileBlocks(
await writeFile(fullPath, toWrite)
}
writtenPaths.push(relativePath)
+ if (relativePath === sourceSummaryPath) summaryWritten = true
completedInputPaths.push(rawRelativePath)
onFileWritten?.(relativePath)
} catch (err) {
@@ -2208,12 +2239,17 @@ async function writeFileBlocks(
}
}
+ const repairableTruncatedPaths = truncatedPaths.filter((path) => {
+ const warning = sourceSummaryBlockWarning(path, sourceSummaryPath, summaryWritten)
+ if (warning) warnings.push(warning)
+ return !warning
+ })
return {
writtenPaths,
completedInputPaths,
warnings,
hardFailures,
- truncatedPaths,
+ truncatedPaths: repairableTruncatedPaths,
}
}
@@ -2428,6 +2464,7 @@ export function buildGenerationPrompt(
"## What to generate",
"",
`1. A source summary page at **${summaryPath}** (MUST use this exact path)`,
+ "Emit exactly one source summary FILE block. Do not create additional wiki/sources/ pages for works merely cited by the source; keep those citations in the summary or link to existing pages.",
"2. Entity or schema-defined typed pages for key named things identified in the analysis. Prefer schema-defined directories when present; otherwise use wiki/entities/.",
"3. Concept or schema-defined typed pages for key ideas, methods, techniques, and abstractions. Prefer schema-defined directories when present; otherwise use wiki/concepts/.",
"4. A log entry for wiki/log.md (just the new entry to append, format: ## [YYYY-MM-DD] ingest | Title)",
@@ -3642,6 +3679,7 @@ async function executeIngestWritesImpl(
`## Source File`,
`The original source file is: **${activeSourceIdentity}**`,
`If you generate a source summary page, it MUST use this exact path: **${activeSourceSummaryPath}**.`,
+ "Emit at most one source summary FILE block. Do not generate other wiki/sources/ pages for cited works.",
`Every page generated from this source MUST include "${activeSourceIdentity}" in its frontmatter \`sources\` field.`,
].join("\n")
: "",
@@ -3704,18 +3742,19 @@ async function executeIngestWritesImpl(
)
const writtenPaths: string[] = []
+ const summaryWarnings: string[] = []
+ let summaryWritten = false
const matches = accumulated.matchAll(FILE_BLOCK_REGEX)
for (const match of matches) {
- let relativePath = match[1].trim()
+ const relativePath = normalizePath(match[1].trim())
let content = match[2]
if (!relativePath) continue
- if (
- activeSourceSummaryPath &&
- relativePath.startsWith("wiki/sources/")
- ) {
- relativePath = activeSourceSummaryPath
+ const summaryWarning = sourceSummaryBlockWarning(relativePath, activeSourceSummaryPath ?? undefined, summaryWritten)
+ if (summaryWarning) {
+ summaryWarnings.push(summaryWarning)
+ continue
}
if (!isSafeIngestPath(relativePath) || isAppManagedAggregatePath(relativePath)) {
@@ -3746,11 +3785,17 @@ async function executeIngestWritesImpl(
await writeFile(fullPath, content)
}
writtenPaths.push(fullPath)
+ if (relativePath === activeSourceSummaryPath) summaryWritten = true
} catch (err) {
console.error(`Failed to write ${fullPath}:`, err)
}
}
+ if (summaryWarnings.length > 0) {
+ await appendIngestWarningLog(pp, activeSourceIdentity ?? "", summaryWarnings)
+ getStore().addMessage("system", `Ingest warnings:\n${summaryWarnings.map((warning) => `- ${warning}`).join("\n")}`)
+ }
+
if (writtenPaths.length > 0) {
const fileList = writtenPaths.map((p) => `- ${p}`).join("\n")
getStore().addMessage("system", `Files written to wiki:\n${fileList}`)