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: LLM-merge wiki pages on re-ingest instead of clobbering body

nash_su6f4b7f0b316e
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index d7154ede..06e8471f 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -8,6 +8,7 @@ import { useReviewStore, type ReviewItem } from "@/stores/review-store"
import { getFileName, normalizePath } from "@/lib/path-utils"
import { checkIngestCache, saveIngestCache } from "@/lib/ingest-cache"
import { sanitizeIngestedFileContent } from "@/lib/ingest-sanitize"
+import { mergePageContent, type MergeFn } from "@/lib/page-merge"
import { withProjectLock } from "@/lib/project-mutex"
import {
extractAndSaveSourceImages,
@@ -593,7 +594,13 @@ async function autoIngestImpl(
// ── Step 3: Write files ───────────────────────────────────────
activity.updateItem(activityId, { detail: "Writing files..." })
- const { writtenPaths, warnings: writeWarnings, hardFailures } = await writeFileBlocks(pp, generation)
+ const { writtenPaths, warnings: writeWarnings, hardFailures } = await writeFileBlocks(
+ pp,
+ generation,
+ llmConfig,
+ fileName,
+ signal,
+ )
// Surface parser / writer warnings to the activity panel so users
// don't have to open devtools to find out a block was dropped.
@@ -755,6 +762,9 @@ function contentMatchesTargetLanguage(content: string, target: string): boolean
async function writeFileBlocks(
projectPath: string,
text: string,
+ llmConfig: LlmConfig,
+ sourceFileName: string,
+ signal?: AbortSignal,
): Promise<{ writtenPaths: string[]; warnings: string[]; hardFailures: string[] }> {
const { blocks, warnings: parseWarnings } = parseFileBlocks(text)
const warnings = [...parseWarnings]
@@ -829,19 +839,32 @@ async function writeFileBlocks(
await writeFile(fullPath, content)
} else {
// Content pages (entities / concepts / queries / synthesis /
- // comparisons / sources summaries): MERGE the sources field
- // with what's already on disk before overwriting, so pages
- // that multiple source documents contribute to retain the
- // full `sources: [...]` history. Without this, every
- // re-ingest clobbers sources to a single entry and the
- // source-delete flow would later treat the page as single-
- // sourced and delete it outright — silent data loss.
- //
- // See src/lib/sources-merge.ts for the merge semantics
- // (case-insensitive dedup, preserves existing order).
- const { mergeSourcesIntoContent } = await import("./sources-merge")
+ // comparisons / sources summaries): if a page with this
+ // path already exists on disk, merge old + new instead of
+ // clobbering. The merge has three layers:
+ // 1. Frontmatter array fields (sources, tags, related)
+ // are union-merged at the application layer.
+ // 2. If body content differs, an LLM call produces a
+ // coherent merged body — preserves contributions from
+ // every source document.
+ // 3. Locked frontmatter fields (type, title, created)
+ // are forced back to the existing values; updated is
+ // stamped today.
+ // LLM failure / sanity rejection falls back to "incoming
+ // body + array-field union" with a best-effort backup.
+ // See page-merge.ts.
const existing = await tryReadFile(fullPath)
- const toWrite = mergeSourcesIntoContent(content, existing)
+ const toWrite = await mergePageContent(
+ content,
+ existing || null,
+ buildPageMerger(llmConfig),
+ {
+ sourceFileName,
+ pagePath: relativePath,
+ signal,
+ backup: (oldContent) => backupExistingPage(projectPath, relativePath, oldContent),
+ },
+ )
await writeFile(fullPath, toWrite)
}
writtenPaths.push(relativePath)
@@ -1129,6 +1152,101 @@ async function tryReadFile(path: string): Promise<string> {
}
}
+/**
+ * Build a MergeFn for a given LLM config. The returned function asks
+ * the model to merge two versions of the same wiki page into one.
+ * Page-merge.ts handles all the sanity-checking and fallback paths;
+ * this is just the "stream the LLM" wrapper.
+ */
+function buildPageMerger(llmConfig: LlmConfig): MergeFn {
+ return async (existingContent, incomingContent, sourceFileName, signal) => {
+ const systemPrompt = [
+ "You are merging two versions of the same wiki page into one coherent document.",
+ "Both versions describe the same entity / concept; one is already on disk,",
+ "the other was just generated from a different source document.",
+ "",
+ "Output ONE merged version that:",
+ "- Preserves every factual claim from both versions (do not drop content)",
+ "- Eliminates redundancy when both versions state the same fact",
+ "- Reorganizes sections so the structure is logical for the merged topic,",
+ " not just a concatenation of the two inputs",
+ "- Uses consistent markdown structure (headings, tables, lists, callouts)",
+ "- Keeps `[[wikilink]]` references intact",
+ "",
+ "Output requirements:",
+ "- The FIRST character of your response MUST be `-` (the opening of `---`)",
+ "- Output the COMPLETE file: YAML frontmatter + body",
+ "- No preamble (no \"Here is the merged version:\"), no analysis prose",
+ "- The caller will overwrite `sources`/`tags`/`related`/`updated` with",
+ " deterministic values — your job is the body and any other fields",
+ ].join("\n")
+
+ const userMessage = [
+ `## Existing version on disk`,
+ "",
+ existingContent,
+ "",
+ "---",
+ "",
+ `## Newly generated version (from ${sourceFileName})`,
+ "",
+ incomingContent,
+ "",
+ "---",
+ "",
+ "Now output the merged file. Start with `---` on the first line.",
+ ].join("\n")
+
+ let result = ""
+ let streamError: Error | null = null
+ await new Promise<void>((resolve) => {
+ streamChat(
+ llmConfig,
+ [
+ { role: "system", content: systemPrompt },
+ { role: "user", content: userMessage },
+ ],
+ {
+ onToken: (token) => {
+ result += token
+ },
+ onDone: () => resolve(),
+ onError: (err) => {
+ streamError = err
+ resolve()
+ },
+ },
+ signal,
+ { temperature: 0.1 },
+ ).catch((err) => {
+ // Defensive: streamChat returns a Promise<void>; if it rejects
+ // (instead of going through onError), surface that too.
+ streamError = err instanceof Error ? err : new Error(String(err))
+ resolve()
+ })
+ })
+ if (streamError) throw streamError
+ return result
+ }
+}
+
+/**
+ * Best-effort snapshot of a page before a fallback merge overwrites
+ * it. Saved to `.llm-wiki/page-history/<sanitized-path>-<timestamp>.md`
+ * so a user who later notices content lost in a merge can recover it.
+ * Errors are swallowed by the caller (page-merge's tryBackup).
+ */
+async function backupExistingPage(
+ projectPath: string,
+ relativePath: string,
+ existingContent: string,
+): Promise<void> {
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-")
+ const sanitized = relativePath.replace(/[/\\]/g, "_")
+ const backupPath = `${projectPath}/.llm-wiki/page-history/${sanitized}-${stamp}`
+ await writeFile(backupPath, existingContent)
+}
+
/**
* Append (or replace) the embedded-images section on the source-
* summary page. Idempotent — paired marker comments bracket our
diff --git a/src/lib/page-merge.test.ts b/src/lib/page-merge.test.ts
new file mode 100644
index 00000000..478a321d
--- /dev/null
+++ b/src/lib/page-merge.test.ts
@@ -0,0 +1,224 @@
+/**
+ * Tests for the page-merge layer that decides what content to write
+ * when an ingest produces a wiki page that already exists on disk.
+ *
+ * The merger function (LLM call) is injected so these tests run
+ * deterministically without hitting any model. A separate real-llm
+ * test suite exercises the wired-up production path against the
+ * actual generation model.
+ */
+import { describe, it, expect, vi } from "vitest"
+import { mergePageContent } from "./page-merge"
+
+const PAGE = (fm: string, body: string) => `---\n${fm}\n---\n\n${body}`
+
+const FIXED_TODAY = () => "2026-04-30"
+const baseOpts = {
+ sourceFileName: "doc-B.pdf",
+ pagePath: "wiki/entities/foo.md",
+ today: FIXED_TODAY,
+}
+
+// ──────────────────────────────────────────────────────────────────
+// Fast paths — no LLM call should happen
+// ──────────────────────────────────────────────────────────────────
+
+describe("mergePageContent — fast paths", () => {
+ it("returns newContent when existingContent is null (new page)", async () => {
+ const merger = vi.fn()
+ const out = await mergePageContent(
+ PAGE('type: entity\ntitle: Foo\nsources: ["doc.pdf"]', "body"),
+ null,
+ merger,
+ baseOpts,
+ )
+ expect(out).toContain('sources: ["doc.pdf"]')
+ expect(merger).not.toHaveBeenCalled()
+ })
+
+ it("returns existingContent when both contents are byte-identical", async () => {
+ const merger = vi.fn()
+ const c = PAGE("type: entity\ntitle: Foo", "body")
+ const out = await mergePageContent(c, c, merger, baseOpts)
+ expect(out).toBe(c)
+ expect(merger).not.toHaveBeenCalled()
+ })
+
+ it("skips LLM when bodies are identical (only sources differ)", async () => {
+ // Re-ingest of the same file from a different source just adds
+ // its source filename — body is byte-identical. Don't waste an
+ // LLM call on this.
+ const merger = vi.fn()
+ const existing = PAGE(
+ 'type: entity\ntitle: Foo\nsources: ["a.pdf"]',
+ "same body",
+ )
+ const incoming = PAGE(
+ 'type: entity\ntitle: Foo\nsources: ["b.pdf"]',
+ "same body",
+ )
+ const out = await mergePageContent(incoming, existing, merger, baseOpts)
+ expect(out).toContain('sources: ["a.pdf", "b.pdf"]')
+ expect(out).toContain("same body")
+ expect(merger).not.toHaveBeenCalled()
+ })
+})
+
+// ──────────────────────────────────────────────────────────────────
+// LLM merge happy path
+// ──────────────────────────────────────────────────────────────────
+
+describe("mergePageContent — LLM merge", () => {
+ it("calls the merger when bodies differ and uses the merged output", async () => {
+ const existing = PAGE(
+ 'type: entity\ntitle: Accumulibacter\ncreated: 2026-04-09\ntags: [microbiology, ebpr]\nrelated: [dpao, vfa]\nsources: ["doc-A.pdf"]',
+ "## Anaerobic Phase\n\nDescription from doc A.\n\n## Denitrification\n\nMore from doc A.",
+ )
+ const incoming = PAGE(
+ 'type: entity\ntitle: Accumulibacter\ncreated: 2026-04-30\ntags: [paos, propionate]\nrelated: [pha]\nsources: ["doc-B.pdf"]',
+ "## Carbon Source Preferences\n\nDescription from doc B.\n\n## Acetate vs Propionate\n\nMore from doc B.",
+ )
+ const mergedBody = "## Anaerobic Phase\n\nDescription from doc A.\n\n## Denitrification\n\nMore from doc A.\n\n## Carbon Source Preferences\n\nDescription from doc B.\n\n## Acetate vs Propionate\n\nMore from doc B."
+ const merger = vi.fn().mockResolvedValue(
+ PAGE(
+ // LLM might also output frontmatter — we'll override locked fields.
+ 'type: entity\ntitle: Accumulibacter\ncreated: 2026-04-09\ntags: [paos, propionate]\nrelated: [pha]\nsources: ["doc-B.pdf"]',
+ mergedBody,
+ ),
+ )
+ const out = await mergePageContent(incoming, existing, merger, baseOpts)
+
+ expect(merger).toHaveBeenCalledOnce()
+
+ // Body uses LLM-merged version
+ expect(out).toContain("Anaerobic Phase")
+ expect(out).toContain("Carbon Source Preferences")
+
+ // Locked fields preserved from existing
+ expect(out).toContain("title: Accumulibacter")
+ expect(out).toContain("created: 2026-04-09")
+ expect(out).toContain("type: entity")
+
+ // updated forced to today
+ expect(out).toContain("updated: 2026-04-30")
+
+ // Array fields are unions
+ expect(out).toMatch(/sources:\s*\[\s*"doc-A.pdf",\s*"doc-B.pdf"\s*\]/)
+ expect(out).toMatch(/tags:\s*\[\s*"microbiology",\s*"ebpr",\s*"paos",\s*"propionate"\s*\]/)
+ expect(out).toMatch(/related:\s*\[\s*"dpao",\s*"vfa",\s*"pha"\s*\]/)
+ })
+
+ it("preserves locked title even if LLM rewrote it", async () => {
+ // Title changes break wikilinks — never accept LLM-rewritten title.
+ const existing = PAGE("type: entity\ntitle: Accumulibacter", "old body content here")
+ const incoming = PAGE("type: entity\ntitle: Accumulibacter", "very different new body here")
+ const merger = vi.fn().mockResolvedValue(
+ PAGE("type: entity\ntitle: ACCUMULIBACTER (renamed)", "merged body that is reasonably long enough to pass the threshold check"),
+ )
+ const out = await mergePageContent(incoming, existing, merger, baseOpts)
+ expect(out).toContain("title: Accumulibacter")
+ expect(out).not.toContain("ACCUMULIBACTER (renamed)")
+ })
+
+ it("preserves locked type even if LLM changed it", async () => {
+ const existing = PAGE("type: entity\ntitle: Foo", "original body content")
+ const incoming = PAGE("type: entity\ntitle: Foo", "new content from another source")
+ const merger = vi.fn().mockResolvedValue(
+ PAGE("type: concept\ntitle: Foo", "merged body that is long enough to clear the seventy percent threshold"),
+ )
+ const out = await mergePageContent(incoming, existing, merger, baseOpts)
+ expect(out).toContain("type: entity")
+ expect(out).not.toContain("type: concept")
+ })
+})
+
+// ──────────────────────────────────────────────────────────────────
+// LLM failure / sanity rejection — always falls back safely
+// ──────────────────────────────────────────────────────────────────
+
+describe("mergePageContent — LLM failure fallback", () => {
+ it("falls back to array-merged incoming when LLM throws", async () => {
+ const existing = PAGE(
+ 'type: entity\ntitle: Foo\ntags: [old]\nsources: ["a.pdf"]',
+ "old body content",
+ )
+ const incoming = PAGE(
+ 'type: entity\ntitle: Foo\ntags: [new]\nsources: ["b.pdf"]',
+ "new body content",
+ )
+ const merger = vi.fn().mockRejectedValue(new Error("LLM rate limited"))
+ const out = await mergePageContent(incoming, existing, merger, baseOpts)
+
+ // Array fields are still merged (no LLM needed for that)
+ expect(out).toMatch(/tags:\s*\[\s*"old",\s*"new"\s*\]/)
+ expect(out).toMatch(/sources:\s*\[\s*"a.pdf",\s*"b.pdf"\s*\]/)
+ // Body is the new (incoming) one — old body is lost; this is the
+ // pre-LLM-merge behavior, the documented fallback contract.
+ expect(out).toContain("new body content")
+ })
+
+ it("rejects LLM output that shrinks body below 70% of max(old, new)", async () => {
+ const longBody = "long body content ".repeat(200) // ~3600 chars
+ const existing = PAGE("type: entity\ntitle: Foo", longBody)
+ const incoming = PAGE("type: entity\ntitle: Foo", "incoming body that is also pretty long " + longBody)
+ const merger = vi.fn().mockResolvedValue(
+ PAGE("type: entity\ntitle: Foo", "tiny merged body"),
+ )
+ const out = await mergePageContent(incoming, existing, merger, baseOpts)
+ // Should fall back to incoming (array-merged) — not the tiny LLM output
+ expect(out).not.toContain("tiny merged body")
+ expect(out).toContain("incoming body that is also pretty long")
+ })
+
+ it("rejects LLM output that has no frontmatter at all", async () => {
+ const existing = PAGE("type: entity\ntitle: Foo", "old body content here")
+ const incoming = PAGE("type: entity\ntitle: Foo", "new body content here")
+ const merger = vi.fn().mockResolvedValue(
+ "raw markdown with no frontmatter at all and definitely no opening triple-dash",
+ )
+ const out = await mergePageContent(incoming, existing, merger, baseOpts)
+ // Falls back to incoming — never writes frontmatter-less output to disk
+ expect(out.startsWith("---")).toBe(true)
+ expect(out).toContain("new body content here")
+ })
+
+ it("calls the optional backup callback when falling back", async () => {
+ const existing = PAGE("type: entity\ntitle: Foo", "old body")
+ const incoming = PAGE("type: entity\ntitle: Foo", "new body")
+ const backup = vi.fn().mockResolvedValue(undefined)
+ const merger = vi.fn().mockRejectedValue(new Error("network error"))
+ await mergePageContent(incoming, existing, merger, {
+ ...baseOpts,
+ backup,
+ })
+ expect(backup).toHaveBeenCalledWith(existing)
+ })
+
+ it("does not call backup when LLM merge succeeds", async () => {
+ const existing = PAGE("type: entity\ntitle: Foo", "old body")
+ const incoming = PAGE("type: entity\ntitle: Foo", "new body content")
+ const backup = vi.fn().mockResolvedValue(undefined)
+ const merger = vi.fn().mockResolvedValue(
+ PAGE("type: entity\ntitle: Foo", "merged body that is long enough to clear the threshold check"),
+ )
+ await mergePageContent(incoming, existing, merger, {
+ ...baseOpts,
+ backup,
+ })
+ expect(backup).not.toHaveBeenCalled()
+ })
+
+ it("backup failure is swallowed (best-effort, never blocks the write)", async () => {
+ const existing = PAGE("type: entity\ntitle: Foo", "old body")
+ const incoming = PAGE("type: entity\ntitle: Foo", "new body content")
+ const backup = vi.fn().mockRejectedValue(new Error("disk full"))
+ const merger = vi.fn().mockRejectedValue(new Error("network error"))
+
+ // Should still resolve — backup error must not propagate
+ const out = await mergePageContent(incoming, existing, merger, {
+ ...baseOpts,
+ backup,
+ })
+ expect(out).toContain("new body content")
+ })
+})
diff --git a/src/lib/page-merge.ts b/src/lib/page-merge.ts
new file mode 100644
index 00000000..05448b82
--- /dev/null
+++ b/src/lib/page-merge.ts
@@ -0,0 +1,237 @@
+/**
+ * Merge a wiki page that the LLM just generated with whatever's
+ * already on disk. Solves silent data loss across re-ingests where
+ * a second source contributes content to the same entity / concept
+ * page.
+ *
+ * Architecture: pure logic, LLM call injected as a parameter.
+ * Production wires this up against `streamChat`; tests use mocks.
+ *
+ * Three layers of protection:
+ * 1. Frontmatter array fields (sources / tags / related) — always
+ * union-merged at the application layer regardless of whether
+ * the LLM is involved. Zero-cost, deterministic.
+ * 2. Body — if old and new bodies differ, ask the LLM to produce
+ * a coherent merge. Sanity-checked on length and structure
+ * before accepting.
+ * 3. Locked frontmatter fields (type / title / created) — even if
+ * the LLM rewrote them, the existing values are forced back.
+ * type/title shifting breaks wikilinks; created is a one-time
+ * stamp.
+ *
+ * Fallback: any LLM failure or sanity-check rejection falls back to
+ * the previous (Array-merged-frontmatter + new body) behavior, with
+ * an optional backup of the existing content for user recovery.
+ */
+import { parseFrontmatter } from "./frontmatter"
+import { mergeArrayFieldsIntoContent } from "./sources-merge"
+
+/** Frontmatter array fields unioned across re-ingests. */
+const UNION_FIELDS = ["sources", "tags", "related"] as const
+
+/**
+ * Frontmatter scalar fields whose existing value MUST survive an
+ * ingest, even if the LLM emits a different value:
+ * - type: changing it would re-categorize the page across folders;
+ * the wiki schema isn't designed for that.
+ * - title: every wikilink that resolves to this page goes through
+ * `[[slug]]` keyed off the slug, but the displayed title is the
+ * `title` field — silently rewriting it would break user mental
+ * maps and any prose that references the title verbatim.
+ * - created: a one-time stamp; an "updated" stamp is computed
+ * separately.
+ */
+const LOCKED_FIELDS = ["type", "title", "created"] as const
+
+/**
+ * Body length safety threshold. If the LLM's merged body is shorter
+ * than 70% of the longer of (existing body, incoming body), reject
+ * the merge — the LLM almost certainly stripped content rather than
+ * legitimately deduplicating. 0.7 allows for ~30% legitimate dedup
+ * compression while catching obvious truncation / lazy summaries.
+ */
+const BODY_SHRINK_THRESHOLD = 0.7
+
+export interface MergeFn {
+ /**
+ * Implements the LLM-call portion of the merge. Receives the
+ * existing on-disk content and the incoming new content (already
+ * array-field-merged); returns the LLM's full proposed merged
+ * file (frontmatter + body) as a string.
+ */
+ (
+ existingContent: string,
+ incomingContent: string,
+ sourceFileName: string,
+ signal?: AbortSignal,
+ ): Promise<string>
+}
+
+export interface MergePageOptions {
+ /** Source filename being ingested — passed through to the merger
+ * and used in fallback log messages. */
+ sourceFileName: string
+ /** Wiki-relative page path (e.g. wiki/entities/foo.md). Used only
+ * for log messages today; the file write itself is the caller's
+ * responsibility. */
+ pagePath: string
+ /** Abort signal forwarded to the merger. */
+ signal?: AbortSignal
+ /** Best-effort hook to back up the existing content before any
+ * fallback write. Errors are swallowed — backup must never
+ * block the merge. */
+ backup?: (existingContent: string) => Promise<void>
+ /** Date provider for the `updated` field. Injectable for
+ * deterministic tests. Defaults to today's UTC date. */
+ today?: () => string
+}
+
+export async function mergePageContent(
+ newContent: string,
+ existingContent: string | null,
+ merger: MergeFn,
+ opts: MergePageOptions,
+): Promise<string> {
+ // Fast path 1: brand-new page.
+ if (!existingContent) return newContent
+
+ // Fast path 2: byte-identical — re-ingest of the same source file
+ // with no actual change. Stable reference helps callers.
+ if (newContent === existingContent) return existingContent
+
+ // Step 1 — always-on: union the array frontmatter fields.
+ const arrayMerged = mergeArrayFieldsIntoContent(
+ newContent,
+ existingContent,
+ [...UNION_FIELDS],
+ )
+
+ // Fast path 3: bodies are identical (only frontmatter array-fields
+ // differed). The array merge has already produced the right output;
+ // skip the LLM.
+ const oldParsed = parseFrontmatter(existingContent)
+ const arrayMergedParsed = parseFrontmatter(arrayMerged)
+ if (oldParsed.body.trim() === arrayMergedParsed.body.trim()) {
+ return arrayMerged
+ }
+
+ // Step 2 — ask the merger to produce a unified body. Failures fall
+ // through to the array-merged-only path with a best-effort backup.
+ let llmOutput: string
+ try {
+ llmOutput = await merger(
+ existingContent,
+ arrayMerged,
+ opts.sourceFileName,
+ opts.signal,
+ )
+ } catch (err) {
+ console.warn(
+ `[page-merge] LLM merge failed for ${opts.pagePath}, falling back to incoming + array-field union: ${err instanceof Error ? err.message : err}`,
+ )
+ await tryBackup(opts, existingContent)
+ return arrayMerged
+ }
+
+ // Sanity 1: LLM output must parse as a frontmatter-bearing wiki
+ // page. No-frontmatter output would silently corrupt the page.
+ const llmParsed = parseFrontmatter(llmOutput)
+ if (llmParsed.frontmatter === null) {
+ console.warn(
+ `[page-merge] LLM output for ${opts.pagePath} has no frontmatter — rejecting, falling back`,
+ )
+ await tryBackup(opts, existingContent)
+ return arrayMerged
+ }
+
+ // Sanity 2: body length. Reject obvious truncation / lazy summary.
+ const oldBodyLen = oldParsed.body.length
+ const newBodyLen = arrayMergedParsed.body.length
+ const llmBodyLen = llmParsed.body.length
+ const minThreshold = Math.max(oldBodyLen, newBodyLen) * BODY_SHRINK_THRESHOLD
+ if (llmBodyLen < minThreshold) {
+ console.warn(
+ `[page-merge] LLM merge for ${opts.pagePath} produced body ${llmBodyLen} chars, below threshold ${minThreshold.toFixed(0)} (max input was ${Math.max(oldBodyLen, newBodyLen)}) — rejecting, falling back`,
+ )
+ await tryBackup(opts, existingContent)
+ return arrayMerged
+ }
+
+ // Step 3 — apply deterministic post-processing: lock fields back
+ // to existing values, force array fields to the union, set
+ // updated to today.
+ let final = llmOutput
+ for (const field of LOCKED_FIELDS) {
+ const existingValue = oldParsed.frontmatter?.[field]
+ if (typeof existingValue === "string" && existingValue !== "") {
+ final = setFrontmatterScalar(final, field, existingValue)
+ }
+ }
+ // Re-apply union merges on top of the LLM's frontmatter using
+ // arrayMerged (which is already existing+incoming union) as the
+ // reference. The LLM may have output a subset of array values —
+ // defensively re-union against BOTH sides so neither contributor
+ // is dropped, regardless of which side the LLM chose to echo.
+ final = mergeArrayFieldsIntoContent(final, arrayMerged, [...UNION_FIELDS])
+ // Updated is always today on a successful merge.
+ const todayFn = opts.today ?? defaultToday
+ final = setFrontmatterScalar(final, "updated", todayFn())
+
+ return final
+}
+
+async function tryBackup(
+ opts: MergePageOptions,
+ existingContent: string,
+): Promise<void> {
+ if (!opts.backup) return
+ try {
+ await opts.backup(existingContent)
+ } catch (err) {
+ console.warn(
+ `[page-merge] backup failed for ${opts.pagePath}: ${err instanceof Error ? err.message : err}`,
+ )
+ }
+}
+
+function defaultToday(): string {
+ return new Date().toISOString().slice(0, 10)
+}
+
+/**
+ * Set a scalar frontmatter field to `value` in the inline form
+ * `field: value`. If the field already exists in the frontmatter,
+ * the line is replaced in place. If it doesn't, the field is
+ * appended at the end of the frontmatter block.
+ *
+ * Keeps the rest of the document unchanged. Returns content
+ * unchanged if it has no frontmatter at all.
+ *
+ * Quoting: the value is written verbatim; the caller is
+ * responsible for quoting if the value contains characters that
+ * would otherwise break YAML parsing (`:` etc). Today's callers
+ * pass plain identifiers and ISO dates so this hasn't been an
+ * issue.
+ */
+function setFrontmatterScalar(
+ content: string,
+ fieldName: string,
+ value: string,
+): string {
+ const fmMatch = content.match(/^(---\n)([\s\S]*?)(\n---)/)
+ if (!fmMatch) return content
+ const [, openDelim, fmBody, closeDelim] = fmMatch
+ const escapedName = fieldName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+ const newLine = `${fieldName}: ${value}`
+
+ // Only match scalar form (no `[`, no `\n -`). Array-form fields
+ // are handled by sources-merge.
+ const lineRe = new RegExp(`^${escapedName}:\\s*(?!\\[)([^\\n]*)`, "m")
+ if (lineRe.test(fmBody)) {
+ const rewritten = fmBody.replace(lineRe, newLine)
+ return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`
+ }
+ // Field absent — append.
+ const rewritten = `${fmBody}\n${newLine}`
+ return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`
+}
diff --git a/src/lib/sources-merge.test.ts b/src/lib/sources-merge.test.ts
index c9a37cbf..0dcb4d92 100644
--- a/src/lib/sources-merge.test.ts
+++ b/src/lib/sources-merge.test.ts
@@ -17,6 +17,8 @@ import {
writeSources,
mergeSourcesLists,
mergeSourcesIntoContent,
+ mergeArrayFieldsIntoContent,
+ parseFrontmatterArray,
} from "./sources-merge"
const WRAP = (fm: string, body = "body\n") => `---\n${fm}\n---\n${body}`
@@ -310,3 +312,120 @@ describe("Regression: the data-loss path in the user's diagnosis", () => {
expect(page).not.toContain("body v2")
})
})
+
+// ── parseFrontmatterArray (generalized parser) ────────────────────
+
+describe("parseFrontmatterArray", () => {
+ it("parses an inline-form array for any field name", () => {
+ expect(parseFrontmatterArray(WRAP("tags: [a, b, c]"), "tags")).toEqual([
+ "a", "b", "c",
+ ])
+ })
+
+ it("parses block-form array (key: + - item lines) for any field", () => {
+ const fm = `related:\n - foo\n - bar`
+ expect(parseFrontmatterArray(WRAP(fm), "related")).toEqual(["foo", "bar"])
+ })
+
+ it("strips quotes around items", () => {
+ expect(
+ parseFrontmatterArray(WRAP('tags: ["a", "b"]'), "tags"),
+ ).toEqual(["a", "b"])
+ })
+
+ it("returns [] when the field doesn't exist", () => {
+ expect(parseFrontmatterArray(WRAP("title: X"), "tags")).toEqual([])
+ })
+
+ it("returns [] when content has no frontmatter", () => {
+ expect(parseFrontmatterArray("# plain markdown", "tags")).toEqual([])
+ })
+
+ it("doesn't mistake one field for another with similar prefix", () => {
+ // `related:` shouldn't accidentally match when we ask for `relate`.
+ const c = WRAP("related: [a, b]")
+ expect(parseFrontmatterArray(c, "relate")).toEqual([])
+ expect(parseFrontmatterArray(c, "related")).toEqual(["a", "b"])
+ })
+})
+
+// ── mergeArrayFieldsIntoContent (multi-field union merge) ─────────
+
+describe("mergeArrayFieldsIntoContent", () => {
+ it("merges sources / tags / related as a union of old and new", () => {
+ const existing = WRAP(
+ 'sources: ["a.md"]\ntags: [old-tag]\nrelated: [old-rel]',
+ )
+ const incoming = WRAP(
+ 'sources: ["b.md"]\ntags: [new-tag]\nrelated: [new-rel]',
+ "new body",
+ )
+ const merged = mergeArrayFieldsIntoContent(incoming, existing, [
+ "sources",
+ "tags",
+ "related",
+ ])
+ expect(parseFrontmatterArray(merged, "sources")).toEqual(["a.md", "b.md"])
+ expect(parseFrontmatterArray(merged, "tags")).toEqual(["old-tag", "new-tag"])
+ expect(parseFrontmatterArray(merged, "related")).toEqual([
+ "old-rel",
+ "new-rel",
+ ])
+ // Body always comes from incoming (no body merge here — that's
+ // page-merge.ts's job).
+ expect(merged).toContain("new body")
+ })
+
+ it("dedupes case-insensitively across all fields", () => {
+ const existing = WRAP("tags: [Foo, BAR]")
+ const incoming = WRAP("tags: [foo, bar, baz]")
+ const merged = mergeArrayFieldsIntoContent(incoming, existing, ["tags"])
+ // First-seen casing wins ("Foo" / "BAR"), but new entry "baz" is added.
+ expect(parseFrontmatterArray(merged, "tags")).toEqual(["Foo", "BAR", "baz"])
+ })
+
+ it("preserves a field that exists in old but is missing from new", () => {
+ // LLM forgot to emit `tags` in this ingest; existing tags must
+ // survive — analogous to the existing sources-protection guarantee.
+ const existing = WRAP("tags: [persistent]")
+ const incoming = WRAP("title: X")
+ const merged = mergeArrayFieldsIntoContent(incoming, existing, ["tags"])
+ expect(parseFrontmatterArray(merged, "tags")).toEqual(["persistent"])
+ })
+
+ it("is a no-op when neither old nor new have any of the requested fields", () => {
+ const existing = WRAP("title: X")
+ const incoming = WRAP("title: Y")
+ expect(
+ mergeArrayFieldsIntoContent(incoming, existing, ["sources", "tags"]),
+ ).toBe(incoming)
+ })
+
+ it("returns newContent unchanged when existingContent is null (new page)", () => {
+ const incoming = WRAP("tags: [a]\nrelated: [b]")
+ expect(mergeArrayFieldsIntoContent(incoming, null, ["tags", "related"])).toBe(
+ incoming,
+ )
+ })
+
+ it("merges only the fields the caller asked for", () => {
+ const existing = WRAP("sources: [a.md]\ntags: [old]")
+ const incoming = WRAP("sources: [b.md]\ntags: [new]")
+ // Asking only for sources — tags is left as the new content's value.
+ const merged = mergeArrayFieldsIntoContent(incoming, existing, ["sources"])
+ expect(parseFrontmatterArray(merged, "sources")).toEqual(["a.md", "b.md"])
+ expect(parseFrontmatterArray(merged, "tags")).toEqual(["new"])
+ })
+
+ it("preserves source-merge backward compatibility when called for `sources` only", () => {
+ // Verifies the new function reproduces mergeSourcesIntoContent's
+ // exact behavior for a sources-only call. If this drifts, the
+ // older callers (sources-view etc.) would silently be affected.
+ const existing = WRAP('sources: ["a.md"]')
+ const incoming = WRAP('sources: ["b.md"]', "new body")
+ const a = mergeSourcesIntoContent(incoming, existing)
+ const b = mergeArrayFieldsIntoContent(incoming, existing, ["sources"])
+ expect(parseSources(b)).toEqual(parseSources(a))
+ expect(b).toContain("new body")
+ })
+})
diff --git a/src/lib/sources-merge.ts b/src/lib/sources-merge.ts
index e8b6b86c..01484fa9 100644
--- a/src/lib/sources-merge.ts
+++ b/src/lib/sources-merge.ts
@@ -1,46 +1,61 @@
/**
- * Merge a page's YAML frontmatter `sources:` array with what the LLM
- * just emitted, so re-ingesting a page that already has a history from
- * another source doesn't silently clobber that history.
+ * Frontmatter array-field merging during ingest.
*
- * Why this exists: the stage-2 prompt instructs the LLM to emit
- * `sources: ["${sourceFileName}"]` — with JUST the current source — on
- * every FILE block. The stage-2 prompt also doesn't feed existing page
- * bodies into the context, so the LLM can't see the old sources. If
- * the ingest write were naive, each re-ingest would overwrite the
- * sources array with a single-element list, and the downstream
- * source-delete logic would later treat the page as single-sourced and
- * delete it — losing content contributed by the earlier source.
+ * Originally written for the `sources:` field alone — re-ingesting a
+ * page from a second source would clobber `sources: [...]` to a
+ * single entry, and the source-delete flow would later treat the page
+ * as single-sourced and delete it (silent data loss). The fix unions
+ * old and new sources before writing.
*
- * The fix: before writing, read the existing file (if any), parse its
- * sources, union with the freshly emitted sources, rewrite the frontmatter.
+ * Generalized to handle any frontmatter array field (`sources`,
+ * `tags`, `related`, …): the same loss-on-clobber pattern applied to
+ * `tags` and `related` too — old contributing tags / wikilinks
+ * disappeared every time a different source brought new ones. The
+ * generic API merges any subset of fields the caller names.
+ *
+ * Two callers today:
+ * - sources-view.tsx — uses `parseSources` / `writeSources` for
+ * the source-delete flow (operates on the single sources field)
+ * - ingest.ts — uses `mergeArrayFieldsIntoContent` to union
+ * sources + tags + related when writing a content page that
+ * already exists on disk
*/
+// ─── Generic helpers (the implementation core) ────────────────────
+
/**
- * Extract `sources: [...]` from the YAML frontmatter of a wiki page.
- * Returns `[]` when no sources line is found or parsing fails.
+ * Extract a frontmatter array field by name. Handles both:
+ * inline form: `name: ["a", "b"]` or `name: [a, b]`
+ * block form: `name:\n - a\n - b`
+ * Strips quotes (single or double) from items. Returns `[]` for
+ * missing field, malformed parse, or content with no frontmatter.
*
- * Handles both single-line form (`sources: ["a.md", "b.md"]`) and the
- * multi-line YAML list form (`sources:\n - a.md\n - b.md`). Single
- * and double quotes on items are stripped; bare items are accepted.
+ * The field name is matched as a whole word at line start, so
+ * `parseFrontmatterArray(c, "rel")` won't match `related: [...]`.
*/
-export function parseSources(content: string): string[] {
+export function parseFrontmatterArray(content: string, fieldName: string): string[] {
const fmMatch = content.match(/^---\n([\s\S]*?)\n---/)
- const fm = fmMatch ? fmMatch[1] : content
-
- // Multi-line YAML list form: `sources:\n - "a.md"\n - "b.md"`
- const multi = fm.match(/^sources:\s*\n((?:[ \t]+-\s+.+\n?)+)/m)
- if (multi) {
+ if (!fmMatch) return []
+ const fm = fmMatch[1]
+ // Anchor to start of line + exact field name + colon. The negative
+ // lookahead-style check is done by requiring `:` immediately after.
+ const escapedName = fieldName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+ const blockRe = new RegExp(
+ `^${escapedName}:\\s*\\n((?:[ \\t]+-\\s+.+\\n?)+)`,
+ "m",
+ )
+ const block = fm.match(blockRe)
+ if (block) {
const out: string[] = []
- for (const line of multi[1].split("\n")) {
+ for (const line of block[1].split("\n")) {
const m = line.match(/^\s+-\s+["']?(.+?)["']?\s*$/)
if (m && m[1]) out.push(m[1].trim())
}
return out
}
- // Inline form: `sources: ["a.md", "b.md"]` or `sources: []`.
- const inline = fm.match(/^sources:\s*\[([^\]]*)\]/m)
+ const inlineRe = new RegExp(`^${escapedName}:\\s*\\[([^\\]]*)\\]`, "m")
+ const inline = fm.match(inlineRe)
if (!inline) return []
const body = inline[1].trim()
if (body === "") return []
@@ -51,56 +66,57 @@ export function parseSources(content: string): string[] {
}
/**
- * Rewrite the `sources:` field of a markdown page's frontmatter to the
- * provided array. Preserves every other frontmatter line. If no
- * `sources:` line exists (LLM forgot it), one is inserted just before
- * the closing `---`. If no frontmatter exists at all, returns the
- * content unchanged — we don't manufacture frontmatter for pages the
- * LLM didn't frontmatter-prefix, since that almost certainly means
- * the emission was already malformed and the caller should surface it.
+ * Rewrite (or insert) a frontmatter array field. Preserves all other
+ * frontmatter lines and order. Returns content unchanged if the
+ * input has no frontmatter at all (don't manufacture frontmatter for
+ * unconventional pages — almost certainly malformed emission worth
+ * surfacing rather than silently fixing).
+ *
+ * Always emits the inline form `name: ["a", "b"]` so downstream
+ * parsers see a consistent shape regardless of the original input
+ * shape.
*/
-export function writeSources(content: string, sources: string[]): string {
+export function writeFrontmatterArray(
+ content: string,
+ fieldName: string,
+ values: string[],
+): string {
const fmMatch = content.match(/^(---\n)([\s\S]*?)(\n---)/)
if (!fmMatch) return content
const [, openDelim, fmBody, closeDelim] = fmMatch
- const serialized = sources.map((s) => `"${s}"`).join(", ")
- const newLine = `sources: [${serialized}]`
-
- // Prefer replacing an existing inline `sources:` line in-place so
- // field ordering within the frontmatter stays the same as the LLM
- // emitted it — users don't see fields shuffle around on every
- // re-ingest.
- if (/^sources:\s*\[[^\]]*\]/m.test(fmBody)) {
- const rewritten = fmBody.replace(/^sources:\s*\[[^\]]*\]/m, newLine)
+ const escapedName = fieldName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
+ const serialized = values.map((s) => `"${s}"`).join(", ")
+ const newLine = `${fieldName}: [${serialized}]`
+
+ // Replace inline form in place — preserves field ordering.
+ const inlineRe = new RegExp(`^${escapedName}:\\s*\\[[^\\]]*\\]`, "m")
+ if (inlineRe.test(fmBody)) {
+ const rewritten = fmBody.replace(inlineRe, newLine)
return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`
}
- // Replace a multi-line YAML list form with an inline form too —
- // consistent shape across pages makes downstream parsing simpler.
- if (/^sources:\s*\n((?:[ \t]+-\s+.+\n?)+)/m.test(fmBody)) {
- const rewritten = fmBody.replace(
- /^sources:\s*\n((?:[ \t]+-\s+.+\n?)+)/m,
- newLine,
- )
+ // Replace block form in place, normalized to inline form.
+ const blockRe = new RegExp(
+ `^${escapedName}:\\s*\\n((?:[ \\t]+-\\s+.+\\n?)+)`,
+ "m",
+ )
+ if (blockRe.test(fmBody)) {
+ const rewritten = fmBody.replace(blockRe, newLine)
return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`
}
- // No sources field at all — append one at the end of the frontmatter.
+ // Field absent — append at end of frontmatter.
const rewritten = `${fmBody}\n${newLine}`
return `${openDelim}${rewritten}${closeDelim}${content.slice(fmMatch[0].length)}`
}
/**
- * Merge two source lists, case-insensitively deduped. Order of existing
- * entries is preserved; new entries not already present are appended
- * in the order they appear in `incoming`.
- *
- * Case handling: if both lists contain the same name but with different
- * casing (e.g. "Test.md" and "test.md"), the first-seen form wins.
- * This keeps the user's original filename casing stable on disk.
+ * Union-merge two array values. Case-insensitive dedup. First-seen
+ * casing wins (matches sources-merge's historical contract — keeps
+ * users' original filename casing stable across re-ingests).
*/
-export function mergeSourcesLists(
+function mergeLists(
existing: readonly string[],
incoming: readonly string[],
): string[] {
@@ -116,33 +132,87 @@ export function mergeSourcesLists(
}
/**
- * The main entry point used from ingest: given the content the LLM
- * just emitted for a page (`newContent`), and whatever is currently on
- * disk at that path (`existingContent`, or null if the page is new),
- * return content whose `sources:` field is the union of both.
+ * Multi-field merge entry point. For each requested field, union the
+ * existing-on-disk value with the LLM-emitted new value, and rewrite
+ * the new content's frontmatter with the merged values.
*
- * For new pages: returns newContent unchanged.
- * For existing pages with no frontmatter: returns newContent unchanged
- * (don't corrupt unconventional files).
- * For existing pages with frontmatter: merges sources, rewrites.
+ * Fast-paths:
+ * - existingContent null/empty → return newContent verbatim
+ * - existing has no frontmatter at all → return newContent verbatim
+ * - no field actually changes → return newContent verbatim (stable
+ * reference, callers can rely on this for cache-key invariance)
*/
-export function mergeSourcesIntoContent(
+export function mergeArrayFieldsIntoContent(
newContent: string,
existingContent: string | null,
+ fields: readonly string[],
): string {
if (!existingContent) return newContent
- const oldSources = parseSources(existingContent)
- if (oldSources.length === 0) return newContent
- const newSources = parseSources(newContent)
- const merged = mergeSourcesLists(oldSources, newSources)
- // Avoid writing a no-op change: if nothing actually needs merging,
- // hand back the original newContent verbatim so hashes / caches stay
- // stable.
- if (
- merged.length === newSources.length &&
- merged.every((s, i) => s === newSources[i])
- ) {
- return newContent
+ if (!/^---\n/.test(existingContent)) return newContent
+
+ let result = newContent
+ let changed = false
+ for (const field of fields) {
+ const oldValues = parseFrontmatterArray(existingContent, field)
+ if (oldValues.length === 0) continue // field absent in existing → nothing to preserve
+ const newValues = parseFrontmatterArray(result, field)
+ const merged = mergeLists(oldValues, newValues)
+ if (
+ merged.length === newValues.length &&
+ merged.every((s, i) => s === newValues[i])
+ ) {
+ continue // no-op for this field
+ }
+ result = writeFrontmatterArray(result, field, merged)
+ changed = true
}
- return writeSources(newContent, merged)
+ return changed ? result : newContent
+}
+
+// ─── Backward-compatible single-field exports ─────────────────────
+
+/**
+ * Extract `sources: [...]` from a wiki page's frontmatter.
+ * Handles inline and block forms; strips quotes; returns [] when
+ * absent. Thin wrapper around the generic parser, kept stable for
+ * sources-view.tsx (source-delete flow).
+ */
+export function parseSources(content: string): string[] {
+ return parseFrontmatterArray(content, "sources")
+}
+
+/**
+ * Rewrite the `sources:` field. Thin wrapper around the generic
+ * writer, kept stable for sources-view.tsx (writes the post-delete
+ * sources list back).
+ */
+export function writeSources(content: string, sources: string[]): string {
+ return writeFrontmatterArray(content, "sources", sources)
+}
+
+/**
+ * Merge two source lists into one (case-insensitive dedup, first-
+ * seen casing wins). Exported for tests and sources-view consumers
+ * that prefer to call the merge directly without going through the
+ * content-rewrite path.
+ */
+export function mergeSourcesLists(
+ existing: readonly string[],
+ incoming: readonly string[],
+): string[] {
+ return mergeLists(existing, incoming)
+}
+
+/**
+ * Sources-only convenience wrapper — equivalent to
+ * `mergeArrayFieldsIntoContent(newContent, existingContent, ["sources"])`.
+ * Kept for ingest-flow callers that pre-date the multi-field
+ * generalization; new code should prefer the generic version which
+ * also unions tags / related.
+ */
+export function mergeSourcesIntoContent(
+ newContent: string,
+ existingContent: string | null,
+): string {
+ return mergeArrayFieldsIntoContent(newContent, existingContent, ["sources"])
}