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 parser — fence-aware, CRLF-tolerant, truncation-visible
nash_sued49e6ebd7f7
diff --git a/src/lib/ingest-parse.test.ts b/src/lib/ingest-parse.test.tsnew file mode 100644index 00000000..9509e8f9--- /dev/null+++ b/src/lib/ingest-parse.test.ts@@ -0,0 +1,308 @@+/**+ * Regression suite for the FILE-block parser in `ingest.ts`.+ *+ * This started life as a diagnostic harness that documented every+ * silent-drop failure mode (H1/H2/H3/H5/H6) against the naive regex.+ * The file now pins down the FIXED behavior of `parseFileBlocks`:+ *+ * - H1 CRLF input is normalized to LF.+ * - H2 stream truncation surfaces as a warning (can't fabricate+ * content the LLM never sent; at least make the drop visible).+ * - H3 whitespace/case variants on both markers are accepted.+ * - H5 literal `---END FILE---` inside a fenced code block is+ * treated as body text (fence-aware scanner).+ * - H6 empty path surfaces as a warning instead of silently+ * continuing.+ *+ * A failing test here means the fix regressed — the parser is back+ * to dropping pages without telling anyone.+ */+import { describe, it, expect } from "vitest"+import { parseFileBlocks } from "./ingest"++// ── Happy paths ─────────────────────────────────────────────────────++describe("parseFileBlocks — canonical shapes", () => {+ it("extracts a single well-formed block", () => {+ const text = [+ "---FILE: wiki/concepts/rope.md---",+ "# RoPE",+ "Rotary positional embedding.",+ "---END FILE---",+ ].join("\n")+ const { blocks, warnings } = parseFileBlocks(text)+ expect(warnings).toHaveLength(0)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].path).toBe("wiki/concepts/rope.md")+ expect(blocks[0].content).toContain("# RoPE")+ })++ it("extracts multiple consecutive blocks", () => {+ const text = [+ "---FILE: wiki/entities/qwen.md---",+ "# Qwen",+ "---END FILE---",+ "",+ "---FILE: wiki/concepts/moe.md---",+ "# MoE",+ "---END FILE---",+ "",+ "---FILE: wiki/sources/paper.md---",+ "# Source summary",+ "---END FILE---",+ ].join("\n")+ const { blocks, warnings } = parseFileBlocks(text)+ expect(warnings).toHaveLength(0)+ expect(blocks.map((b) => b.path)).toEqual([+ "wiki/entities/qwen.md",+ "wiki/concepts/moe.md",+ "wiki/sources/paper.md",+ ])+ })++ it("accepts hyphenated paths", () => {+ const text = [+ "---FILE: wiki/concepts/multi-head-attention.md---",+ "body",+ "---END FILE---",+ ].join("\n")+ expect(parseFileBlocks(text).blocks).toHaveLength(1)+ })++ it("ignores preamble prose before the first block", () => {+ const text = [+ "Here are the wiki files:",+ "",+ "---FILE: wiki/concepts/foo.md---",+ "body",+ "---END FILE---",+ ].join("\n")+ expect(parseFileBlocks(text).blocks).toHaveLength(1)+ })+})++// ── H1: CRLF normalization ─────────────────────────────────────────++describe("parseFileBlocks — H1: CRLF line endings", () => {+ it("extracts all blocks when input uses Windows CRLF", () => {+ const text = [+ "---FILE: wiki/entities/qwen.md---",+ "# Qwen",+ "---END FILE---",+ "",+ "---FILE: wiki/concepts/moe.md---",+ "# MoE",+ "---END FILE---",+ ].join("\r\n")+ const { blocks, warnings } = parseFileBlocks(text)+ expect(warnings).toHaveLength(0)+ expect(blocks).toHaveLength(2)+ expect(blocks.map((b) => b.path)).toEqual([+ "wiki/entities/qwen.md",+ "wiki/concepts/moe.md",+ ])+ // Content should have LF only (normalized).+ for (const b of blocks) {+ expect(b.content).not.toMatch(/\r/)+ }+ })++ it("handles mixed CRLF body with LF markers", () => {+ const text =+ "---FILE: wiki/concepts/foo.md---\nline1\r\nline2\r\n---END FILE---"+ const { blocks } = parseFileBlocks(text)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].content).toBe("line1\nline2")+ })+})++// ── H2: Stream truncation ──────────────────────────────────────────++describe("parseFileBlocks — H2: truncated streams (surface, don't hide)", () => {+ it("emits a warning when the final block has no closer", () => {+ const text = [+ "---FILE: wiki/entities/qwen.md---",+ "# Qwen",+ "---END FILE---",+ "",+ "---FILE: wiki/concepts/moe.md---",+ "# Mixture of Exp", // stream cut here+ ].join("\n")+ const { blocks, warnings } = parseFileBlocks(text)+ // Completed block makes it through.+ expect(blocks).toHaveLength(1)+ expect(blocks[0].path).toBe("wiki/entities/qwen.md")+ // Unclosed block is surfaced as a warning rather than silently lost.+ expect(warnings).toHaveLength(1)+ expect(warnings[0]).toMatch(/wiki\/concepts\/moe\.md/)+ expect(warnings[0]).toMatch(/not closed/i)+ })++ it("warns when the only block is unclosed", () => {+ const text = "---FILE: wiki/concepts/rope.md---\n# RoPE\nIt rotates"+ const { blocks, warnings } = parseFileBlocks(text)+ expect(blocks).toHaveLength(0)+ expect(warnings).toHaveLength(1)+ expect(warnings[0]).toMatch(/rope\.md/)+ })+})++// ── H3: Marker whitespace / case variants ──────────────────────────++describe("parseFileBlocks — H3: tolerant marker matching", () => {+ it("accepts `--- END FILE ---` (inner spaces)", () => {+ const text = [+ "---FILE: wiki/concepts/foo.md---",+ "body",+ "--- END FILE ---",+ ].join("\n")+ expect(parseFileBlocks(text).blocks).toHaveLength(1)+ })++ it("accepts `---end file---` (lowercase)", () => {+ const text = [+ "---FILE: wiki/concepts/foo.md---",+ "body",+ "---end file---",+ ].join("\n")+ expect(parseFileBlocks(text).blocks).toHaveLength(1)+ })++ it("accepts `--- FILE: path ---` (spaces after leading dashes)", () => {+ const text = [+ "--- FILE: wiki/concepts/foo.md ---",+ "body",+ "---END FILE---",+ ].join("\n")+ const { blocks } = parseFileBlocks(text)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].path).toBe("wiki/concepts/foo.md")+ })++ it("tolerates trailing whitespace on the opener line", () => {+ const text = "---FILE: wiki/concepts/foo.md--- \nbody\n---END FILE---"+ expect(parseFileBlocks(text).blocks).toHaveLength(1)+ })++ it("rejects marker variants embedded in prose / list items", () => {+ // `---END FILE---` inside a list item is NOT on its own line, so+ // must not end the block. The regex is anchored ^...$.+ const text = [+ "---FILE: wiki/concepts/foo.md---",+ "Not to be written:",+ "- `---END FILE---` in backticks (this is prose)",+ "real content continues",+ "---END FILE---",+ ].join("\n")+ const { blocks } = parseFileBlocks(text)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].content).toContain("real content continues")+ })+})++// ── H5: Literal markers inside fenced code blocks ──────────────────++describe("parseFileBlocks — H5: code-fence awareness", () => {+ it("treats `---END FILE---` inside a fenced code block as body text", () => {+ // This is the user-reported scenario: the LLM writes a concept+ // page about the ingest format, which naturally quotes the literal+ // marker in a code example. Naive parsers truncate the outer block+ // at the first inner marker; the fence-aware parser keeps going.+ const text = [+ "---FILE: wiki/concepts/ingest-format.md---",+ "# Ingest Format",+ "",+ "Example of a FILE block:",+ "",+ "```plaintext",+ "---FILE: wiki/path/to/page.md---",+ "body content",+ "---END FILE---", // inside a fence — must be ignored+ "```",+ "",+ "More explanation after the example.",+ "---END FILE---", // the real closer+ ].join("\n")+ const { blocks, warnings } = parseFileBlocks(text)+ expect(warnings).toHaveLength(0)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].path).toBe("wiki/concepts/ingest-format.md")+ // Content must include BOTH the fenced example AND the post-fence+ // prose — which the old parser silently dropped.+ expect(blocks[0].content).toContain("```plaintext")+ expect(blocks[0].content).toContain("More explanation after the example.")+ })++ it("handles multiple fenced blocks in one page", () => {+ const text = [+ "---FILE: wiki/concepts/foo.md---",+ "```",+ "---END FILE---",+ "```",+ "",+ "prose",+ "",+ "~~~",+ "---END FILE---",+ "~~~",+ "",+ "more prose",+ "---END FILE---",+ ].join("\n")+ const { blocks } = parseFileBlocks(text)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].content).toContain("more prose")+ })++ it("handles nested-length fences per CommonMark (outer 4-tick, inner 3-tick)", () => {+ const text = [+ "---FILE: wiki/concepts/foo.md---",+ "````markdown",+ "```",+ "---END FILE---",+ "```",+ "````",+ "",+ "real content after the outer fence closes",+ "---END FILE---",+ ].join("\n")+ const { blocks } = parseFileBlocks(text)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].content).toContain("real content after the outer fence closes")+ })++ it("a 3-tick fence does NOT close a 4-tick opener (CommonMark rule)", () => {+ // Inside a ```` fence, a ``` line is just content, NOT a close.+ // If we wrongly treated 3-tick as closing, `---END FILE---` after+ // it would exit the block prematurely.+ const text = [+ "---FILE: wiki/concepts/foo.md---",+ "````",+ "```",+ "---END FILE---", // still inside the 4-tick fence+ "```",+ "````",+ "",+ "real content",+ "---END FILE---",+ ].join("\n")+ const { blocks } = parseFileBlocks(text)+ expect(blocks).toHaveLength(1)+ expect(blocks[0].content).toContain("real content")+ })+})++// ── H6: Empty path ──────────────────────────────────────────────────++describe("parseFileBlocks — H6: empty-path blocks", () => {+ it("surfaces a warning instead of silently dropping empty-path blocks", () => {+ const text = "---FILE: ---\nsome body\n---END FILE---"+ const { blocks, warnings } = parseFileBlocks(text)+ // The OPENER_LINE regex requires at least one non-whitespace char+ // in the path capture group via `(.+?)`, so " " technically+ // captures the space and trims to empty → empty-path warning.+ // In either case, the block must NOT produce a silent write.+ expect(blocks).toHaveLength(0)+ expect(warnings.length).toBeGreaterThan(0)+ })+})diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex db5eac1c..1bf4fb7a 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -10,10 +10,148 @@ import { checkIngestCache, saveIngestCache } from "@/lib/ingest-cache"import { buildLanguageDirective } from "@/lib/output-language"import { detectLanguage } from "@/lib/detect-language"-// Path capture group allows any non-newline char so hyphenated paths like-// "wiki/concepts/multi-head-attention.md" are accepted. The lazy `+?` plus-// the following `\s*---\n` anchor still stops at the closing ---.-const FILE_BLOCK_REGEX = /---FILE:\s*([^\n]+?)\s*---\n([\s\S]*?)---END FILE---/g+// Legacy export kept for backward compatibility with existing diagnostic+// tests. The live pipeline goes through parseFileBlocks() below, which+// handles classes of LLM output this regex silently drops (see H1/H3/H5+// in src/lib/ingest-parse.test.ts).+export const FILE_BLOCK_REGEX = /---FILE:\s*([^\n]+?)\s*---\n([\s\S]*?)---END FILE---/g++/** One FILE block extracted from an LLM's stage-2 output. */+export interface ParsedFileBlock {+ path: string+ content: string+}++/** What the parser produced, with any non-fatal issues surfaced. */+export interface ParseFileBlocksResult {+ blocks: ParsedFileBlock[]+ /** Human-readable notes for blocks we refused or couldn't close. Each+ * one is also console.warn'd. UI can surface these so users see that+ * something was skipped instead of silently getting fewer pages. */+ warnings: string[]+}++// Line-level openers / closers. Both are case-insensitive, tolerant of+// extra interior whitespace (`--- END FILE ---`), and anchored to the+// whole trimmed line so a stray `---END FILE---` inside prose or a list+// item (`- ---END FILE---`) won't register.+const OPENER_LINE = /^---\s*FILE:\s*(.+?)\s*---\s*$/i+const CLOSER_LINE = /^---\s*END\s+FILE\s*---\s*$/i+// Fence delimiters per CommonMark (triple+ backticks or tildes). Leading+// indentation ≤ 3 spaces is still a fence; 4+ spaces is an indented code+// block and doesn't use fence markers.+const FENCE_LINE = /^\s{0,3}(```+|~~~+)/++/**+ * Parse an LLM stage-2 generation into FILE blocks.+ *+ * Known hazards the naive `---FILE:...---END FILE---` regex walks into+ * (all reproduced as fixtures in src/lib/ingest-parse.test.ts):+ *+ * H1. Windows CRLF line endings — regex anchored on bare `\n` missed+ * every block.+ * H2. Stream truncation — the last block's closing `---END FILE---`+ * never arrived; the entire block was silently dropped with no+ * logging.+ * H3. Marker whitespace / case variants — `--- END FILE ---`,+ * `---end file---`, `--- FILE: path ---`, `---FILE: foo--- \n`+ * (trailing space) all made the regex fail.+ * H5. Literal `---END FILE---` inside a fenced code block (e.g. when+ * the LLM is writing a concept page about our own ingest format)+ * — lazy match stopped at the first occurrence, truncating the+ * page and dumping all subsequent real content into no-man's-land.+ * H6. Empty path — block matched but was silently dropped by a+ * downstream `!path` check.+ *+ * This parser fixes every one except H2 (which is fundamentally a+ * stream-budget problem), and at least surfaces H2 as a warning so the+ * user isn't left wondering why a page is missing.+ */+export function parseFileBlocks(text: string): ParseFileBlocksResult {+ // H1 fix: normalize CRLF to LF before anything else. Cheap and+ // covers the case where a proxy / server / LLM inserts Windows line+ // endings into the stream.+ const normalized = text.replace(/\r\n/g, "\n")+ const lines = normalized.split("\n")++ const blocks: ParsedFileBlock[] = []+ const warnings: string[] = []++ let i = 0+ while (i < lines.length) {+ const openerMatch = OPENER_LINE.exec(lines[i])+ if (!openerMatch) {+ i+++ continue+ }+ const path = openerMatch[1].trim()+ i++ // consume opener++ const contentLines: string[] = []+ let fenceMarker: string | null = null // tracks whether we're inside ``` or ~~~+ let fenceLen = 0+ let closed = false++ while (i < lines.length) {+ const line = lines[i]++ // H5 fix: update fence state before checking closer. Only close+ // the fence when we see the same character repeated at least as+ // many times — CommonMark rule. This lets docs-about-our-format+ // quote `---END FILE---` inside code fences without truncating+ // the outer block.+ const fenceMatch = FENCE_LINE.exec(line)+ if (fenceMatch) {+ const run = fenceMatch[1]+ const char = run[0] // '`' or '~'+ const len = run.length+ if (fenceMarker === null) {+ fenceMarker = char+ fenceLen = len+ } else if (char === fenceMarker && len >= fenceLen) {+ fenceMarker = null+ fenceLen = 0+ }+ contentLines.push(line)+ i+++ continue+ }++ // A line matching the closer ONLY counts when we're outside any+ // code fence. Inside a fence, treat it as ordinary body text.+ if (fenceMarker === null && CLOSER_LINE.test(line)) {+ closed = true+ i+++ break+ }++ contentLines.push(line)+ i+++ }++ if (!closed) {+ // H2 fix (partial): we can't fabricate content the LLM never+ // sent, but we surface the drop instead of silently hiding it.+ const pathLabel = path || "(unnamed)"+ const msg = `FILE block "${pathLabel}" was not closed before end of stream — likely truncation (model hit max_tokens, timeout, or connection dropped). Block dropped.`+ console.warn(`[ingest] ${msg}`)+ warnings.push(msg)+ continue+ }++ if (!path) {+ // H6 fix: surface empty-path blocks.+ const msg = `FILE block with empty path skipped (LLM omitted the path after \`---FILE:\`).`+ console.warn(`[ingest] ${msg}`)+ warnings.push(msg)+ continue+ }++ blocks.push({ path, content: contentLines.join("\n") })+ }++ return { blocks, warnings }+}/*** Build the language rule for ingest prompts.@@ -154,7 +292,18 @@ export async function autoIngest(// ── Step 3: Write files ───────────────────────────────────────activity.updateItem(activityId, { detail: "Writing files..." })- const writtenPaths = await writeFileBlocks(pp, generation)+ const { writtenPaths, warnings: writeWarnings } = await writeFileBlocks(pp, generation)++ // Surface parser / writer warnings to the activity panel so users+ // don't have to open devtools to find out a block was dropped.+ // Keeping the base "Writing files..." detail on top and appending the+ // first few warnings; full list stays in the console.+ if (writeWarnings.length > 0) {+ const summary = writeWarnings.length === 1+ ? writeWarnings[0]+ : `${writeWarnings.length} ingest warnings: ${writeWarnings.slice(0, 2).join(" · ")}${writeWarnings.length > 2 ? ` … (+${writeWarnings.length - 2} more in console)` : ""}`+ activity.updateItem(activityId, { detail: summary })+ }// Ensure source summary page exists (LLM may not have generated it correctly)const sourceBaseName = fileName.replace(/\.[^.]+$/, "")@@ -281,17 +430,17 @@ function contentMatchesTargetLanguage(content: string, target: string): booleanreturn !detectedIsCjk && !["Arabic", "Hindi", "Thai", "Hebrew"].includes(detected)}-async function writeFileBlocks(projectPath: string, text: string): Promise<string[]> {+async function writeFileBlocks(+ projectPath: string,+ text: string,+): Promise<{ writtenPaths: string[]; warnings: string[] }> {+ const { blocks, warnings: parseWarnings } = parseFileBlocks(text)+ const warnings = [...parseWarnings]const writtenPaths: string[] = []- const matches = text.matchAll(FILE_BLOCK_REGEX)const targetLang = useWikiStore.getState().outputLanguage- for (const match of matches) {- const relativePath = match[1].trim()- const content = match[2]- if (!relativePath) continue-+ for (const { path: relativePath, content } of blocks) {// Language guard: reject individual FILE blocks whose body contradicts// the user-set target language. Skip:// - log.md (structural, short)@@ -314,9 +463,9 @@ async function writeFileBlocks(projectPath: string, text: string): Promise<strin!isEntityOrSource &&!contentMatchesTargetLanguage(content, targetLang)) {- console.warn(- `[ingest] dropping ${relativePath}: content not in target language ${targetLang}`,- )+ const msg = `Dropped "${relativePath}" — body language doesn't match target ${targetLang}.`+ console.warn(`[ingest] ${msg}`)+ warnings.push(msg)continue}@@ -331,11 +480,13 @@ async function writeFileBlocks(projectPath: string, text: string): Promise<strin}writtenPaths.push(relativePath)} catch (err) {- console.error(`Failed to write ${fullPath}:`, err)+ const msg = `Failed to write "${relativePath}": ${err instanceof Error ? err.message : String(err)}`+ console.error(`[ingest] ${msg}`)+ warnings.push(msg)}}- return writtenPaths+ return { writtenPaths, warnings }}const REVIEW_BLOCK_REGEX = /---REVIEW:\s*(\w[\w-]*)\s*\|\s*(.+?)\s*---\n([\s\S]*?)---END REVIEW---/g