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: use parseFrontmatter instead of an unbounded title: regex in 4 more places

Andrew Chen6984e55fa1a4
diff --git a/src/lib/embedding.test.ts b/src/lib/embedding.test.ts
index 9544eac1..da078c10 100644
--- a/src/lib/embedding.test.ts
+++ b/src/lib/embedding.test.ts
@@ -38,6 +38,7 @@ import {
getEmbeddingCount,
removePageEmbedding,
resetEmbeddingOptimizeAccountingForTests,
+ extractEmbeddingTitle,
type PageSearchResult,
} from "./embedding"
@@ -1966,3 +1967,19 @@ describe("legacyVectorRowCount / dropLegacyVectorTable / getEmbeddingCount / rem
await expect(removePageEmbedding("/proj", "rope")).resolves.toBeUndefined()
})
})
+
+describe("extractEmbeddingTitle", () => {
+ it("does not read a body prose line starting with title: as the frontmatter title", () => {
+ const content = "---\ntype: entity\n---\n# Real Heading\n\nSome text.\ntitle: not-frontmatter-at-all\n"
+ expect(extractEmbeddingTitle(content, "mypage")).toBe("mypage")
+ })
+
+ it("still uses a genuine frontmatter title", () => {
+ const content = "---\ntitle: Real Title\n---\n# Real Title\n"
+ expect(extractEmbeddingTitle(content, "mypage")).toBe("Real Title")
+ })
+
+ it("falls back to fallbackId when there is no frontmatter at all", () => {
+ expect(extractEmbeddingTitle("# Just a heading\n\nBody text.", "mypage")).toBe("mypage")
+ })
+})
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
index f1dc384c..8c7fdf5d 100644
--- a/src/lib/embedding.ts
+++ b/src/lib/embedding.ts
@@ -27,6 +27,7 @@ import type { EmbeddingConfig } from "@/stores/wiki-store"
import type { FileNode } from "@/types/wiki"
import { normalizePath } from "@/lib/path-utils"
import { chunkMarkdown, type Chunk } from "@/lib/text-chunker"
+import { parseFrontmatter } from "@/lib/frontmatter"
// ── Error surfacing ──────────────────────────────────────────────────────
@@ -259,9 +260,10 @@ type PageEmbeddingPreparation =
| { status: "empty" }
| { status: "failed"; reason: string }
-function extractEmbeddingTitle(content: string, fallbackId: string): string {
- const titleMatch = content.match(/^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m)
- return titleMatch ? titleMatch[1].trim() : fallbackId
+/** @internal Exported for unit tests only. */
+export function extractEmbeddingTitle(content: string, fallbackId: string): string {
+ const title = parseFrontmatter(content).frontmatter?.title
+ return typeof title === "string" && title.trim() ? title.trim() : fallbackId
}
async function preparePageEmbeddingRows(
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 1a5c50a0..61030bd2 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -1297,8 +1297,8 @@ async function autoIngestImpl(
if (!pageId || ["index", "log", "overview"].includes(pageId)) continue
try {
const content = await readFile(`${pp}/${wpath}`)
- const titleMatch = content.match(/^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m)
- const title = titleMatch ? titleMatch[1].trim() : pageId
+ const fmTitle = parseFrontmatter(content).frontmatter?.title
+ const title = typeof fmTitle === "string" && fmTitle.trim() ? fmTitle.trim() : pageId
await embedPage(pp, pageId, title, content, embCfg)
} catch {
// non-critical
@@ -3058,10 +3058,8 @@ async function reembedSourceSummary(
const sourceSummaryFullPath = `${pp}/wiki/sources/${sourceSummarySlug}.md`
try {
const content = await readFile(sourceSummaryFullPath)
- const titleMatch = content.match(
- /^---\n[\s\S]*?^title:\s*["']?(.+?)["']?\s*$/m,
- )
- const title = titleMatch ? titleMatch[1].trim() : sourceIdentity
+ const fmTitle = parseFrontmatter(content).frontmatter?.title
+ const title = typeof fmTitle === "string" && fmTitle.trim() ? fmTitle.trim() : sourceIdentity
const { embedPage } = await import("@/lib/embedding")
await embedPage(pp, sourceSummarySlug, title, content, embCfg)
console.log(`[ingest:caption] re-embedded ${sourceSummarySlug} with captioned alt text`)
diff --git a/src/lib/sweep-reviews-build-wiki-index.test.ts b/src/lib/sweep-reviews-build-wiki-index.test.ts
new file mode 100644
index 00000000..c6adcbe6
--- /dev/null
+++ b/src/lib/sweep-reviews-build-wiki-index.test.ts
@@ -0,0 +1,56 @@
+/**
+ * Regression test for buildWikiIndex's title extraction.
+ *
+ * buildWikiIndex previously matched `title:` with a regex anchored only at
+ * the opening `---`, never required to stop at the closing `---`. A page
+ * whose frontmatter has no title — but whose body happens to contain a
+ * later line starting with `title:` (plain prose, not YAML) — got that
+ * body line misread as the page's title and added to `byTitle`. Since
+ * `pageExists()` checks `byTitle` to decide whether a "missing page" review
+ * should auto-resolve, this could falsely mark a still-missing page as
+ * resolved.
+ */
+import { describe, it, expect, vi } from "vitest"
+import type { FileNode } from "@/types/wiki"
+
+const mockListDirectory = vi.fn()
+const mockReadFile = vi.fn()
+
+vi.mock("@/commands/fs", () => ({
+ listDirectory: (...args: unknown[]) => mockListDirectory(...args),
+ readFile: (...args: unknown[]) => mockReadFile(...args),
+}))
+
+async function loadBuildWikiIndex() {
+ const mod = await import("./sweep-reviews")
+ return mod.buildWikiIndex
+}
+
+function mdFile(name: string): FileNode {
+ return { name, path: `/project/wiki/${name}`, is_dir: false }
+}
+
+describe("buildWikiIndex", () => {
+ it("does not add a body prose line starting with title: to byTitle", async () => {
+ const buildWikiIndex = await loadBuildWikiIndex()
+ mockListDirectory.mockResolvedValue([mdFile("other.md")])
+ mockReadFile.mockResolvedValue(
+ "---\ntype: entity\n---\n# Real Heading\n\nSome text.\ntitle: Attention Mechanism\n",
+ )
+
+ const index = await buildWikiIndex("/project")
+
+ expect(index.byTitle.has("attention mechanism")).toBe(false)
+ expect(index.pages[0].title).toBeNull()
+ })
+
+ it("still indexes a genuine frontmatter title", async () => {
+ const buildWikiIndex = await loadBuildWikiIndex()
+ mockListDirectory.mockResolvedValue([mdFile("real.md")])
+ mockReadFile.mockResolvedValue("---\ntitle: Real Title\n---\n# Real Title\n")
+
+ const index = await buildWikiIndex("/project")
+
+ expect(index.byTitle.has("real title")).toBe(true)
+ })
+})
diff --git a/src/lib/sweep-reviews.ts b/src/lib/sweep-reviews.ts
index 2a0506df..2f92238c 100644
--- a/src/lib/sweep-reviews.ts
+++ b/src/lib/sweep-reviews.ts
@@ -19,6 +19,7 @@ import type { FileNode } from "@/types/wiki"
import { normalizePath } from "@/lib/path-utils"
import { normalizeReviewTitle } from "@/lib/review-utils"
import { hasUsableLlm } from "@/lib/has-usable-llm"
+import { parseFrontmatter } from "@/lib/frontmatter"
// ── Types ─────────────────────────────────────────────────────────────────
@@ -48,7 +49,7 @@ function flattenMdFiles(nodes: FileNode[]): FileNode[] {
}
/** Build an index of wiki pages: id (filename without .md) + title → normalized */
-async function buildWikiIndex(projectPath: string): Promise<WikiIndex> {
+export async function buildWikiIndex(projectPath: string): Promise<WikiIndex> {
const pp = normalizePath(projectPath)
const byId = new Set<string>()
const byTitle = new Set<string>()
@@ -65,9 +66,9 @@ async function buildWikiIndex(projectPath: string): Promise<WikiIndex> {
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) {
- title = match[1].trim()
+ const fmTitle = parseFrontmatter(content).frontmatter?.title
+ if (typeof fmTitle === "string" && fmTitle.trim()) {
+ title = fmTitle.trim()
byTitle.add(title.toLowerCase())
}
} catch {