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: source-delete guards against deleting pages whose sole source is unrelated

nash_su1b7b6c4a2986
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 4f1fbf48..59b9a5aa 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -18,6 +18,8 @@ import {
extractFrontmatterTitle,
type DeletedPageInfo,
} from "@/lib/wiki-cleanup"
+import { parseSources, writeSources } from "@/lib/sources-merge"
+import { decidePageFate } from "@/lib/source-delete-decision"
export function SourcesView() {
const { t } = useTranslation()
@@ -223,43 +225,46 @@ export function SourcesView() {
// cache file may not exist
}
- // Step 4: Delete or update related wiki pages.
- // - Multi-source pages: just remove this source from the `sources[]`
- // frontmatter list, keep the page on disk.
- // - Single-source (or no-sources) pages: actually delete, and
- // capture { slug, title } so downstream cleanup can wipe every
- // stale reference — both the slug form (`[[kv-cache]]`) and the
- // title form (`[[KV Cache]]`) that the LLM emits interchangeably.
+ // Step 4: For each page that findRelatedWikiPages surfaced,
+ // consult decidePageFate to pick one of three actions:
+ //
+ // keep — page has OTHER sources too; just drop this one from
+ // its sources[] list and rewrite.
+ // delete — this was the page's sole source; remove the page
+ // and record { slug, title } so downstream cleanup
+ // can wipe every stale reference to it.
+ // skip — the page's sources[] doesn't actually include the
+ // file being deleted. Must have been surfaced by the
+ // Rust findRelatedWikiPages loose-match path (fs.rs
+ // Strategy 3 — substring of title / description /
+ // elsewhere in the frontmatter). Leaving the page
+ // alone prevents silent data loss when a filename
+ // happens to appear in an unrelated page's metadata.
const actuallyDeleted: string[] = []
const deletedInfos: DeletedPageInfo[] = []
for (const pagePath of relatedPages) {
try {
const content = await readFile(pagePath)
- // Parse sources from frontmatter
- const sourcesMatch = content.match(/^sources:\s*\[([^\]]*)\]/m)
- if (sourcesMatch) {
- const sourcesList = sourcesMatch[1]
- .split(",")
- .map((s) => s.trim().replace(/["']/g, ""))
- .filter((s) => s.length > 0)
-
- if (sourcesList.length > 1) {
- // Multiple sources — just remove this file from the list, keep the page
- const updatedSources = sourcesList.filter(
- (s) => s.toLowerCase() !== fileName.toLowerCase()
- )
- const updatedContent = content.replace(
- /^sources:\s*\[([^\]]*)\]/m,
- `sources: [${updatedSources.map((s) => `"${s}"`).join(", ")}]`
- )
- await writeFile(pagePath, updatedContent)
- continue // Don't delete this page
- }
+ const sourcesList = parseSources(content)
+ const decision = decidePageFate(sourcesList, fileName)
+
+ if (decision.action === "skip") {
+ // Nothing to do — page isn't really derived from this source.
+ continue
+ }
+
+ if (decision.action === "keep") {
+ // Multi-source page — rewrite sources with the deleted one
+ // filtered out. writeSources preserves every other
+ // frontmatter field and position.
+ const updated = writeSources(content, decision.updatedSources)
+ await writeFile(pagePath, updated)
+ continue
}
- // Single source or no sources field — delete the page and
- // record both its slug and its frontmatter title so index /
- // overview / other pages can be cleaned of stale references.
+ // action === "delete": the page's sole source was this file.
+ // Capture slug + title before deletion so stale references
+ // can be cleaned from index / overview / sibling pages.
const slug = getFileName(pagePath).replace(/\.md$/, "")
const title = extractFrontmatterTitle(content)
deletedInfos.push({ slug, title })
diff --git a/src/lib/source-delete-decision.test.ts b/src/lib/source-delete-decision.test.ts
new file mode 100644
index 00000000..1971e57a
--- /dev/null
+++ b/src/lib/source-delete-decision.test.ts
@@ -0,0 +1,123 @@
+/**
+ * Regression suite for decidePageFate — the three-way branch that
+ * decides whether a wiki page survives, loses a source reference, or
+ * gets deleted when the user removes a source document.
+ *
+ * The key case is the one that used to silently lose data:
+ *
+ * `frontmatterSources` = ["other.md"]
+ * `deletingSource` = "test.md"
+ * → must return { action: "skip" }, NOT { action: "delete" }
+ *
+ * Before the extraction, this branch in sources-view.tsx didn't check
+ * whether the sole source was the one being deleted — it just saw
+ * length === 1 and fell through to delete. findRelatedWikiPages'
+ * over-eager matching (see fs.rs Strategy 3) could surface pages whose
+ * sources list didn't actually contain the target, and those would
+ * then be wiped.
+ */
+import { describe, it, expect } from "vitest"
+import { decidePageFate } from "./source-delete-decision"
+
+describe("decidePageFate — single-source page", () => {
+ it("deletes when the sole source is the one being removed", () => {
+ expect(decidePageFate(["test.md"], "test.md")).toEqual({ action: "delete" })
+ })
+
+ it("SKIPS when the sole source is NOT the one being removed (Bug #1 fix)", () => {
+ // The user-reported / review-surfaced data-loss path: page shows up
+ // in findRelatedWikiPages via a loose match, but its actual single
+ // source is unrelated. Must NOT be deleted.
+ const decision = decidePageFate(["other.md"], "test.md")
+ expect(decision.action).toBe("skip")
+ })
+
+ it("matches case-insensitively when deciding to delete", () => {
+ expect(decidePageFate(["Test.md"], "test.md")).toEqual({ action: "delete" })
+ expect(decidePageFate(["test.md"], "TEST.MD")).toEqual({ action: "delete" })
+ })
+})
+
+describe("decidePageFate — multi-source page", () => {
+ it("keeps and drops the deleted source from the list", () => {
+ expect(decidePageFate(["a.md", "b.md"], "a.md")).toEqual({
+ action: "keep",
+ updatedSources: ["b.md"],
+ })
+ })
+
+ it("preserves the order of surviving sources", () => {
+ expect(decidePageFate(["a.md", "b.md", "c.md"], "b.md")).toEqual({
+ action: "keep",
+ updatedSources: ["a.md", "c.md"],
+ })
+ })
+
+ it("SKIPS when the deleted source is not in the multi-source list", () => {
+ // Again the false-positive-from-loose-match scenario, but the page
+ // has multiple genuine sources, none of which is the deleted one.
+ const decision = decidePageFate(["a.md", "b.md"], "c.md")
+ expect(decision.action).toBe("skip")
+ })
+
+ it("matches case-insensitively AND strips all case variants on keep", () => {
+ // If a page somehow has both "Test.md" and "test.md" in its sources
+ // list (rare but possible via manual editing or ingest glitch), a
+ // single deletion request should remove every case variant so
+ // residual duplicates don't linger.
+ const decision = decidePageFate(
+ ["Test.md", "Other.md", "test.md"],
+ "test.md",
+ )
+ expect(decision).toEqual({
+ action: "keep",
+ updatedSources: ["Other.md"],
+ })
+ })
+})
+
+describe("decidePageFate — empty / edge inputs", () => {
+ it("skips a page with an empty sources list (no claim on this deletion)", () => {
+ // Pre-0.3.x pages without a sources field, or pages manually edited
+ // to an empty list. They shouldn't be deleted just because
+ // findRelatedWikiPages happened to return them via the file-path
+ // heuristic.
+ const decision = decidePageFate([], "test.md")
+ expect(decision.action).toBe("skip")
+ })
+
+ it("skips when the deleting source is itself empty", () => {
+ // Defensive: an empty deleting source never matches anything.
+ const decision = decidePageFate(["a.md"], "")
+ expect(decision.action).toBe("skip")
+ })
+
+ it("handles a single-source list where the source is some other casing", () => {
+ expect(
+ decidePageFate(["SomeFile.Md"], "somefile.md"),
+ ).toEqual({ action: "delete" })
+ })
+})
+
+describe("decidePageFate — the full lifecycle of a shared page", () => {
+ it("walks from multi-source → multi-source → single-source → deleted across source deletions", () => {
+ // Page starts with three sources.
+ let sources = ["a.md", "b.md", "c.md"]
+
+ // Delete a.md first → keep, drop a.
+ let d = decidePageFate(sources, "a.md")
+ expect(d.action).toBe("keep")
+ sources = (d as { action: "keep"; updatedSources: string[] }).updatedSources
+ expect(sources).toEqual(["b.md", "c.md"])
+
+ // Delete c.md → keep, drop c.
+ d = decidePageFate(sources, "c.md")
+ expect(d.action).toBe("keep")
+ sources = (d as { action: "keep"; updatedSources: string[] }).updatedSources
+ expect(sources).toEqual(["b.md"])
+
+ // Delete b.md (now the sole source) → delete the page.
+ d = decidePageFate(sources, "b.md")
+ expect(d.action).toBe("delete")
+ })
+})
diff --git a/src/lib/source-delete-decision.ts b/src/lib/source-delete-decision.ts
new file mode 100644
index 00000000..6b858aab
--- /dev/null
+++ b/src/lib/source-delete-decision.ts
@@ -0,0 +1,58 @@
+/**
+ * Decide what to do with a wiki page when the user deletes a source
+ * document. This is a pure function so the branching is unit-testable
+ * in isolation — the previous inline version in sources-view.tsx was
+ * entangled with React and silently harboured a data-loss bug (pages
+ * whose sole source was NOT the one being deleted got wiped anyway,
+ * because findRelatedWikiPages had returned them via a loose
+ * substring match).
+ */
+
+export type DeleteDecision =
+ /** Keep the page on disk; rewrite its sources to the returned list. */
+ | { action: "keep"; updatedSources: string[] }
+ /** Delete the page — the deleting source was its sole contributor. */
+ | { action: "delete" }
+ /** Leave the page alone entirely — it ended up in findRelatedWikiPages'
+ * results by accident (loose frontmatter substring match) but its
+ * sources list doesn't actually include the deleting source. */
+ | { action: "skip"; reason: string }
+
+/**
+ * Decide whether a page should be kept, deleted, or skipped in response
+ * to the user removing `deletingSource`. Case-insensitive throughout so
+ * "Test.md" and "test.md" are treated as the same source.
+ *
+ * - If `deletingSource` is NOT in `frontmatterSources` → skip.
+ * Guards against findRelatedWikiPages' loose match taking out
+ * innocent pages.
+ * - If it IS and there are OTHER sources too → keep, return the
+ * filtered list so caller can rewrite the frontmatter.
+ * - If it IS and it's the ONLY source → delete.
+ */
+export function decidePageFate(
+ frontmatterSources: readonly string[],
+ deletingSource: string,
+): DeleteDecision {
+ const targetLower = deletingSource.toLowerCase()
+
+ const inList = frontmatterSources.some(
+ (s) => s.toLowerCase() === targetLower,
+ )
+ if (!inList) {
+ return {
+ action: "skip",
+ reason: `page sources do not include "${deletingSource}"`,
+ }
+ }
+
+ const survivors = frontmatterSources.filter(
+ (s) => s.toLowerCase() !== targetLower,
+ )
+
+ if (survivors.length > 0) {
+ return { action: "keep", updatedSources: survivors }
+ }
+
+ return { action: "delete" }
+}