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

feat: delete entity / concept pages from the Knowledge tree with full ref cleanup

nash_su65c1b4fb7eb3
diff --git a/src/components/layout/knowledge-tree.tsx b/src/components/layout/knowledge-tree.tsx
index 44be8a68..54fc694f 100644
--- a/src/components/layout/knowledge-tree.tsx
+++ b/src/components/layout/knowledge-tree.tsx
@@ -1,12 +1,14 @@
import { useState, useEffect, useCallback } from "react"
import {
- FileText, Users, Lightbulb, BookOpen, HelpCircle, GitMerge, BarChart3, ChevronRight, ChevronDown, Layout, Globe,
+ FileText, Users, Lightbulb, BookOpen, HelpCircle, GitMerge, BarChart3, ChevronRight, ChevronDown, Layout, Globe, Trash2,
} from "lucide-react"
import { ScrollArea } from "@/components/ui/scroll-area"
+import { Button } from "@/components/ui/button"
import { useWikiStore } from "@/stores/wiki-store"
import { readFile, listDirectory } from "@/commands/fs"
import type { FileNode } from "@/types/wiki"
import { normalizePath } from "@/lib/path-utils"
+import { cascadeDeleteWikiPagesWithRefs } from "@/lib/wiki-page-delete"
interface WikiPageInfo {
path: string
@@ -33,8 +35,14 @@ export function KnowledgeTree() {
const selectedFile = useWikiStore((s) => s.selectedFile)
const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
const fileTree = useWikiStore((s) => s.fileTree)
+ const setFileTree = useWikiStore((s) => s.setFileTree)
+ const bumpDataVersion = useWikiStore((s) => s.bumpDataVersion)
const [pages, setPages] = useState<WikiPageInfo[]>([])
const [expandedTypes, setExpandedTypes] = useState<Set<string>>(new Set(["overview", "entity", "concept", "source"]))
+ // Two-stage delete: first click arms the row, second click executes.
+ // Only one row armed at a time (clicking another row replaces).
+ const [armedPath, setArmedPath] = useState<string | null>(null)
+ const [deletingPath, setDeletingPath] = useState<string | null>(null)
const loadPages = useCallback(async () => {
if (!project) return
@@ -72,6 +80,39 @@ export function KnowledgeTree() {
loadPages()
}, [loadPages, fileTree])
+ const handleDeleteClick = useCallback(
+ async (pagePath: string) => {
+ if (!project) return
+ // First click: arm. Second click on the same row: execute.
+ if (armedPath !== pagePath) {
+ setArmedPath(pagePath)
+ return
+ }
+ setArmedPath(null)
+ setDeletingPath(pagePath)
+ try {
+ const pp = normalizePath(project.path)
+ await cascadeDeleteWikiPagesWithRefs(pp, [pagePath])
+ // Refresh: page list, file tree, any data-version subscribers.
+ await loadPages()
+ try {
+ const tree = await listDirectory(pp)
+ setFileTree(tree)
+ } catch {
+ // non-critical
+ }
+ bumpDataVersion()
+ if (selectedFile === pagePath) setSelectedFile(null)
+ } catch (err) {
+ console.error("[KnowledgeTree] delete failed:", err)
+ window.alert(`Failed to delete: ${err}`)
+ } finally {
+ setDeletingPath(null)
+ }
+ },
+ [project, armedPath, loadPages, selectedFile, setSelectedFile, setFileTree, bumpDataVersion],
+ )
+
if (!project) {
return (
<div className="flex h-full items-center justify-center p-4 text-sm text-muted-foreground">
@@ -142,20 +183,42 @@ export function KnowledgeTree() {
<div className="ml-3">
{items.map((page) => {
const isSelected = selectedFile === page.path
+ const isArmed = armedPath === page.path
+ const isDeleting = deletingPath === page.path
return (
- <button
+ <div
key={page.path}
- onClick={() => setSelectedFile(page.path)}
- className={`flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-sm ${
- isSelected
- ? "bg-accent text-accent-foreground"
- : "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"
+ className={`group flex items-center gap-1 rounded-md ${
+ isSelected ? "bg-accent text-accent-foreground" : "hover:bg-accent/50"
}`}
- title={page.path}
>
- {page.origin === "web-clip" && <Globe className="h-3 w-3 shrink-0 text-blue-400" />}
- <span className="truncate">{page.title}</span>
- </button>
+ <button
+ onClick={() => setSelectedFile(page.path)}
+ className={`flex flex-1 items-center gap-1.5 px-2 py-1 text-left text-sm min-w-0 ${
+ isSelected
+ ? "text-accent-foreground"
+ : "text-muted-foreground group-hover:text-accent-foreground"
+ }`}
+ title={page.path}
+ >
+ {page.origin === "web-clip" && <Globe className="h-3 w-3 shrink-0 text-blue-400" />}
+ <span className="truncate">{page.title}</span>
+ </button>
+ <DeleteButton
+ armed={isArmed}
+ deleting={isDeleting}
+ // Visible on hover, when this row is armed,
+ // or while deleting. Other rows fade out so
+ // accidental clicks on a sibling don't pile up.
+ className={`mr-1 transition-opacity ${
+ isArmed || isDeleting
+ ? "opacity-100"
+ : "opacity-0 group-hover:opacity-100"
+ }`}
+ onClick={() => void handleDeleteClick(page.path)}
+ name={page.title}
+ />
+ </div>
)
})}
</div>
@@ -272,6 +335,74 @@ function parsePageInfo(path: string, fileName: string, content: string): WikiPag
return { path, title, type, tags, origin }
}
+/**
+ * Two-stage delete affordance for a single page row. Default state =
+ * subtle ghost trash icon. Armed state = solid red Confirm pill so a
+ * second click can't be accidental. Same visual contract as the
+ * sources-view DeleteButton — kept inline here rather than shared
+ * because the parent owns the armed/deleting/visibility state and
+ * extracting would mean lifting four props to a shared module for one
+ * extra caller.
+ */
+function DeleteButton({
+ armed,
+ deleting,
+ onClick,
+ name,
+ className = "",
+}: {
+ armed: boolean
+ deleting: boolean
+ onClick: () => void
+ name: string
+ className?: string
+}) {
+ if (deleting) {
+ return (
+ <Button
+ variant="ghost"
+ size="icon"
+ className={`h-6 w-6 shrink-0 cursor-default ${className}`}
+ disabled
+ title={`Deleting ${name}…`}
+ >
+ <Trash2 className="h-3 w-3 animate-pulse text-destructive" />
+ </Button>
+ )
+ }
+ if (armed) {
+ return (
+ <Button
+ variant="destructive"
+ size="sm"
+ className={`h-6 shrink-0 px-1.5 text-[10px] font-semibold animate-pulse ${className}`}
+ onClick={(e) => {
+ e.stopPropagation()
+ onClick()
+ }}
+ title={`Click again to delete ${name} and clean up references`}
+ >
+ <Trash2 className="mr-0.5 h-3 w-3" />
+ Confirm
+ </Button>
+ )
+ }
+ return (
+ <Button
+ variant="ghost"
+ size="icon"
+ className={`h-6 w-6 shrink-0 text-muted-foreground hover:text-destructive ${className}`}
+ onClick={(e) => {
+ e.stopPropagation()
+ onClick()
+ }}
+ title={`Delete ${name} (and clean up references)`}
+ >
+ <Trash2 className="h-3 w-3" />
+ </Button>
+ )
+}
+
function flattenMdFiles(nodes: FileNode[]): FileNode[] {
const files: FileNode[] = []
for (const node of nodes) {
diff --git a/src/lib/wiki-page-delete.test.ts b/src/lib/wiki-page-delete.test.ts
index f1bbfe33..acfed16a 100644
--- a/src/lib/wiki-page-delete.test.ts
+++ b/src/lib/wiki-page-delete.test.ts
@@ -8,15 +8,15 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
const mockDeleteFile = vi.fn<(path: string) => Promise<void>>()
const mockRemovePageEmbedding = vi.fn<(projectPath: string, slug: string) => Promise<void>>()
+const mockReadFile = vi.fn<(path: string) => Promise<string>>()
+const mockWriteFile = vi.fn<(path: string, content: string) => Promise<void>>()
+const mockListDirectory = vi.fn<(path: string) => Promise<unknown>>()
vi.mock("@/commands/fs", () => ({
deleteFile: (path: string) => mockDeleteFile(path),
- // The other fs functions aren't called by this helper, but the
- // mock factory has to declare them so dynamic imports elsewhere
- // in transitive deps don't break.
- readFile: vi.fn(),
- writeFile: vi.fn(),
- listDirectory: vi.fn(),
+ readFile: (path: string) => mockReadFile(path),
+ writeFile: (path: string, content: string) => mockWriteFile(path, content),
+ listDirectory: (path: string) => mockListDirectory(path),
}))
vi.mock("@/lib/embedding", () => ({
@@ -24,14 +24,19 @@ vi.mock("@/lib/embedding", () => ({
mockRemovePageEmbedding(projectPath, slug),
}))
-import { cascadeDeleteWikiPage } from "./wiki-page-delete"
+import { cascadeDeleteWikiPage, cascadeDeleteWikiPagesWithRefs } from "./wiki-page-delete"
+import type { FileNode } from "@/types/wiki"
beforeEach(() => {
mockDeleteFile.mockReset()
mockRemovePageEmbedding.mockReset()
+ mockReadFile.mockReset()
+ mockWriteFile.mockReset()
+ mockListDirectory.mockReset()
// Default: both succeed silently.
mockDeleteFile.mockResolvedValue(undefined)
mockRemovePageEmbedding.mockResolvedValue(undefined)
+ mockWriteFile.mockResolvedValue(undefined)
})
describe("cascadeDeleteWikiPage", () => {
@@ -210,3 +215,232 @@ describe("cascadeDeleteWikiPage", () => {
expect(mockDeleteFile).toHaveBeenCalledWith("/proj/wiki/sources/.hidden.md")
})
})
+
+// ── cascadeDeleteWikiPagesWithRefs (new) ─────────────────────────────────
+//
+// User-driven "delete this entity" wants more than the file-level
+// helper above: it must also strip every reference to the deleted
+// page so we don't leave dangling links / phantom related entries
+// across the wiki. Pin every cleanup pathway here.
+
+const PROJECT = "/test/project"
+
+function fileNode(rel: string): FileNode {
+ const segs = rel.split("/")
+ return {
+ name: segs[segs.length - 1] ?? "",
+ path: `${PROJECT}/${rel}`,
+ is_dir: false,
+ }
+}
+
+function dirNode(rel: string, children: FileNode[]): FileNode {
+ const segs = rel.split("/")
+ return {
+ name: segs[segs.length - 1] ?? "",
+ path: `${PROJECT}/${rel}`,
+ is_dir: true,
+ children,
+ }
+}
+
+describe("cascadeDeleteWikiPagesWithRefs", () => {
+ it("deletes the file, drops embeddings, and reports the path", async () => {
+ const target = `${PROJECT}/wiki/entities/alice-chen.md`
+ mockReadFile.mockImplementationOnce(async () =>
+ `---\ntype: entity\ntitle: "Alice Chen"\n---\n\n# Alice`,
+ )
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ dirNode("wiki/entities", [fileNode("wiki/entities/alice-chen.md")]),
+ ]),
+ ])
+
+ const result = await cascadeDeleteWikiPagesWithRefs(PROJECT, [target])
+ expect(result.deletedPaths).toEqual([target])
+ expect(mockDeleteFile).toHaveBeenCalledWith(target)
+ expect(mockRemovePageEmbedding).toHaveBeenCalledWith(PROJECT, "alice-chen")
+ })
+
+ it("strips [[deleted]] body wikilinks from sibling pages", async () => {
+ const target = `${PROJECT}/wiki/entities/alice-chen.md`
+ mockReadFile.mockImplementation(async (p: string) => {
+ if (p === target) return `---\ntitle: "Alice Chen"\n---\n\n# Alice`
+ if (p === `${PROJECT}/wiki/entities/bob.md`) {
+ return `---\ntitle: Bob\n---\n\nBob worked with [[alice-chen]] on the migration.`
+ }
+ throw new Error(`unexpected read ${p}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ dirNode("wiki/entities", [
+ fileNode("wiki/entities/alice-chen.md"),
+ fileNode("wiki/entities/bob.md"),
+ ]),
+ ]),
+ ])
+
+ await cascadeDeleteWikiPagesWithRefs(PROJECT, [target])
+
+ const writeCall = mockWriteFile.mock.calls.find(
+ (c) => c[0] === `${PROJECT}/wiki/entities/bob.md`,
+ )
+ expect(writeCall).toBeTruthy()
+ const written = writeCall![1]
+ expect(written).not.toContain("[[alice-chen]]")
+ expect(written).toContain("Bob worked with alice-chen on the migration.")
+ })
+
+ it("strips title-form [[Alice Chen]] wikilinks too", async () => {
+ const target = `${PROJECT}/wiki/entities/alice-chen.md`
+ mockReadFile.mockImplementation(async (p: string) => {
+ if (p === target) return `---\ntitle: "Alice Chen"\n---\nbody`
+ if (p === `${PROJECT}/wiki/entities/bob.md`) {
+ return `---\ntitle: Bob\n---\n\nBob and [[Alice Chen]] led the project.`
+ }
+ throw new Error(`unexpected read ${p}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ dirNode("wiki/entities", [
+ fileNode("wiki/entities/alice-chen.md"),
+ fileNode("wiki/entities/bob.md"),
+ ]),
+ ]),
+ ])
+
+ await cascadeDeleteWikiPagesWithRefs(PROJECT, [target])
+ const written = mockWriteFile.mock.calls.find(
+ (c) => c[0] === `${PROJECT}/wiki/entities/bob.md`,
+ )![1]
+ expect(written).not.toContain("[[Alice Chen]]")
+ })
+
+ it("removes the deleted page's listing line from index.md", async () => {
+ const target = `${PROJECT}/wiki/entities/alice-chen.md`
+ mockReadFile.mockImplementation(async (p: string) => {
+ if (p === target) return `---\ntitle: "Alice Chen"\n---\nbody`
+ if (p === `${PROJECT}/wiki/index.md`) {
+ return [
+ "# Wiki Index",
+ "",
+ "## Entities",
+ "- [[alice-chen]] — engineering lead",
+ "- [[bob]] — designer",
+ ].join("\n")
+ }
+ throw new Error(`unexpected read ${p}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ fileNode("wiki/index.md"),
+ dirNode("wiki/entities", [fileNode("wiki/entities/alice-chen.md")]),
+ ]),
+ ])
+
+ await cascadeDeleteWikiPagesWithRefs(PROJECT, [target])
+
+ const indexWrite = mockWriteFile.mock.calls.find(
+ (c) => c[0] === `${PROJECT}/wiki/index.md`,
+ )!
+ const written = indexWrite[1]
+ expect(written).not.toContain("[[alice-chen]]")
+ expect(written).toContain("[[bob]]")
+ })
+
+ it("drops the deleted slug from `related:` frontmatter arrays", async () => {
+ const target = `${PROJECT}/wiki/entities/alice-chen.md`
+ mockReadFile.mockImplementation(async (p: string) => {
+ if (p === target) return `---\ntitle: "Alice Chen"\n---\nbody`
+ if (p === `${PROJECT}/wiki/projects/migration.md`) {
+ return [
+ "---",
+ "type: project",
+ "title: Migration",
+ "related: [alice-chen, bob, carol]",
+ "---",
+ "",
+ "Project body.",
+ ].join("\n")
+ }
+ throw new Error(`unexpected read ${p}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ dirNode("wiki/entities", [fileNode("wiki/entities/alice-chen.md")]),
+ dirNode("wiki/projects", [fileNode("wiki/projects/migration.md")]),
+ ]),
+ ])
+
+ await cascadeDeleteWikiPagesWithRefs(PROJECT, [target])
+
+ const projWrite = mockWriteFile.mock.calls.find(
+ (c) => c[0] === `${PROJECT}/wiki/projects/migration.md`,
+ )!
+ const written = projWrite[1]
+ // alice-chen filtered out; bob & carol kept.
+ expect(written).not.toMatch(/\balice-chen\b/)
+ expect(written).toContain("bob")
+ expect(written).toContain("carol")
+ })
+
+ it("does NOT touch a sibling whose slug merely contains the deleted slug as a substring", async () => {
+ // Deleting "ai" must not corrupt [[OpenAI]] / [[AI Safety]] —
+ // the bug class wiki-cleanup was originally written to prevent.
+ const target = `${PROJECT}/wiki/concepts/ai.md`
+ mockReadFile.mockImplementation(async (p: string) => {
+ if (p === target) return `---\ntitle: AI\n---\nbody`
+ if (p === `${PROJECT}/wiki/entities/openai.md`) {
+ return `---\ntitle: "OpenAI"\n---\n\nFounded as [[ai]] safety lab. Now also see [[OpenAI]] product line.`
+ }
+ throw new Error(`unexpected read ${p}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ dirNode("wiki/concepts", [fileNode("wiki/concepts/ai.md")]),
+ dirNode("wiki/entities", [fileNode("wiki/entities/openai.md")]),
+ ]),
+ ])
+
+ await cascadeDeleteWikiPagesWithRefs(PROJECT, [target])
+ const written = mockWriteFile.mock.calls.find(
+ (c) => c[0] === `${PROJECT}/wiki/entities/openai.md`,
+ )?.[1]
+ if (written) {
+ expect(written).toContain("[[OpenAI]]")
+ expect(written).not.toContain("[[ai]]")
+ }
+ })
+
+ it("handles batch deletes (multiple targets) with one cleanup sweep", async () => {
+ const t1 = `${PROJECT}/wiki/entities/alice-chen.md`
+ const t2 = `${PROJECT}/wiki/entities/alice-chen-1.md`
+ mockReadFile.mockImplementation(async (p: string) => {
+ if (p === t1) return `---\ntitle: "Alice Chen"\n---\nbody`
+ if (p === t2) return `---\ntitle: "Alice Chen"\n---\nbody`
+ if (p === `${PROJECT}/wiki/entities/bob.md`) {
+ return `---\ntitle: Bob\n---\n\nWorked with [[alice-chen]] and [[alice-chen-1]] both.`
+ }
+ throw new Error(`unexpected read ${p}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ dirNode("wiki/entities", [
+ fileNode("wiki/entities/alice-chen.md"),
+ fileNode("wiki/entities/alice-chen-1.md"),
+ fileNode("wiki/entities/bob.md"),
+ ]),
+ ]),
+ ])
+
+ const result = await cascadeDeleteWikiPagesWithRefs(PROJECT, [t1, t2])
+ expect(result.deletedPaths).toEqual([t1, t2])
+ expect(mockDeleteFile).toHaveBeenCalledWith(t1)
+ expect(mockDeleteFile).toHaveBeenCalledWith(t2)
+ const bobWrite = mockWriteFile.mock.calls.find(
+ (c) => c[0] === `${PROJECT}/wiki/entities/bob.md`,
+ )!
+ expect(bobWrite[1]).not.toContain("[[alice-chen]]")
+ expect(bobWrite[1]).not.toContain("[[alice-chen-1]]")
+ })
+})
diff --git a/src/lib/wiki-page-delete.ts b/src/lib/wiki-page-delete.ts
index 2a5ebc66..def9041d 100644
--- a/src/lib/wiki-page-delete.ts
+++ b/src/lib/wiki-page-delete.ts
@@ -19,9 +19,21 @@
* to apply their own fault-tolerance policy (e.g. continue with the
* next file in a batch, or surface to the user via toast).
*/
-import { deleteFile } from "@/commands/fs"
+import { deleteFile, listDirectory, readFile, writeFile } from "@/commands/fs"
import { getFileStem, normalizePath } from "@/lib/path-utils"
import { removePageEmbedding } from "@/lib/embedding"
+import {
+ buildDeletedKeys,
+ cleanIndexListing,
+ extractFrontmatterTitle,
+ stripDeletedWikilinks,
+ type DeletedPageInfo,
+} from "@/lib/wiki-cleanup"
+import {
+ parseFrontmatterArray,
+ writeFrontmatterArray,
+} from "@/lib/sources-merge"
+import type { FileNode } from "@/types/wiki"
/**
* Detect whether a wiki page lives under `wiki/sources/`. We treat
@@ -92,3 +104,150 @@ export async function cascadeDeleteWikiPage(
}
}
}
+
+function flattenMd(nodes: readonly FileNode[]): FileNode[] {
+ const out: FileNode[] = []
+ function walk(ns: readonly FileNode[]): void {
+ for (const n of ns) {
+ if (n.is_dir) {
+ if (n.children) walk(n.children)
+ continue
+ }
+ if (n.name.endsWith(".md")) out.push(n)
+ }
+ }
+ walk(nodes)
+ return out
+}
+
+/** Lower-case + strip whitespace/hyphens/underscores. Same shape that
+ * wiki-cleanup uses internally so a deleted slug `alice-chen` matches
+ * a `related: [aliceChen]` reference (and vice versa). Defined here
+ * because the helper isn't exported from wiki-cleanup. */
+function normalizeKey(s: string): string {
+ return s.toLowerCase().replace(/[\s\-_]+/g, "")
+}
+
+export interface CascadeDeleteResult {
+ /** Wiki-page paths that were actually removed from disk. */
+ deletedPaths: string[]
+ /** How many surviving wiki files we rewrote to drop stale refs. */
+ rewrittenFiles: number
+}
+
+/**
+ * Delete one or more wiki pages and clean up every reference to them
+ * in the rest of the wiki: file delete, embedding drop, media-dir
+ * cascade for source pages, plus
+ *
+ * - `wiki/index.md` listing entries whose primary `[[target]]`
+ * points at a deleted page → entry line dropped
+ * - any other wiki .md body containing `[[deleted]]` /
+ * `[[deleted|alias]]` → wikilink replaced with plain text
+ * (alias preserved when present)
+ * - any wiki .md whose frontmatter `related:` array lists a
+ * deleted slug (or its title-form variant) → that entry
+ * filtered out, array rewritten
+ *
+ * Compared to the existing source-delete cascade in `sources-view`,
+ * this also strips the `related:` frontmatter entries — that path
+ * historically only touched body wikilinks + index.md and left
+ * `related:` slugs pointing into the void. For a direct user-driven
+ * "delete this entity" action we want zero leftover dangling refs.
+ *
+ * Order of operations:
+ * 1. Read each target's content first to extract the title (need
+ * it for index-listing match) and snapshot the slug.
+ * 2. Cascade-delete each target (file + embeddings + media dir).
+ * 3. Sweep all surviving wiki .md files and rewrite them.
+ *
+ * Best-effort on the sweep — a single un-readable file does not abort
+ * the rest of the cleanup. Returns a summary so the caller can show
+ * the user what happened.
+ */
+export async function cascadeDeleteWikiPagesWithRefs(
+ projectPath: string,
+ pagePaths: readonly string[],
+): Promise<CascadeDeleteResult> {
+ const pp = normalizePath(projectPath)
+ const result: CascadeDeleteResult = {
+ deletedPaths: [],
+ rewrittenFiles: 0,
+ }
+
+ // 1. Read each target's title so the cleanup keyset includes both
+ // slug-form and title-form. Capture before delete.
+ const infos: DeletedPageInfo[] = []
+ for (const pagePath of pagePaths) {
+ let title = ""
+ try {
+ const content = await readFile(pagePath)
+ title = extractFrontmatterTitle(content)
+ } catch {
+ // file may have been deleted between selection + action; the
+ // slug-form key alone will still work.
+ }
+ const slug = getFileStem(pagePath)
+ if (slug.length > 0) infos.push({ slug, title })
+ }
+
+ // 2. Delete the target files themselves.
+ for (const pagePath of pagePaths) {
+ try {
+ await cascadeDeleteWikiPage(pp, pagePath)
+ result.deletedPaths.push(pagePath)
+ } catch (err) {
+ console.warn(`[wiki-delete] failed to delete ${pagePath}:`, err)
+ }
+ }
+
+ if (infos.length === 0) return result
+
+ // 3. Sweep surviving wiki/*.md.
+ const deletedKeys = buildDeletedKeys(infos)
+ const deletedSlugSet = new Set(infos.map((i) => normalizeKey(i.slug)))
+ const wikiTree = await listDirectory(`${pp}/wiki`)
+ const allMd = flattenMd(wikiTree)
+ const indexAbs = `${pp}/wiki/index.md`
+
+ for (const file of allMd) {
+ if (result.deletedPaths.includes(file.path)) continue // already gone
+ let content: string
+ try {
+ content = await readFile(file.path)
+ } catch {
+ continue
+ }
+
+ let updated = content
+ if (file.path === indexAbs || file.name === "index.md") {
+ updated = cleanIndexListing(updated, deletedKeys)
+ }
+ updated = stripDeletedWikilinks(updated, deletedKeys)
+
+ // `related:` frontmatter — drop entries that point at a deleted
+ // page. parseFrontmatterArray returns the parsed string list;
+ // writeFrontmatterArray rewrites only that field, preserving
+ // every other line.
+ const related = parseFrontmatterArray(updated, "related")
+ if (related.length > 0) {
+ const filtered = related.filter(
+ (s) => !deletedSlugSet.has(normalizeKey(s)),
+ )
+ if (filtered.length !== related.length) {
+ updated = writeFrontmatterArray(updated, "related", filtered)
+ }
+ }
+
+ if (updated !== content) {
+ try {
+ await writeFile(file.path, updated)
+ result.rewrittenFiles++
+ } catch (err) {
+ console.warn(`[wiki-delete] failed to rewrite ${file.path}:`, err)
+ }
+ }
+ }
+
+ return result
+}