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 lifecycle cleanup and sync handling

nash_su7b4e52d5776d
diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rs
index c4937390..c45300ec 100644
--- a/src-tauri/src/commands/fs.rs
+++ b/src-tauri/src/commands/fs.rs
@@ -134,6 +134,7 @@ fn write_cache(original: &Path, text: &str) -> Result<(), String> {
if let Some(parent) = cache_path.parent() {
fs::create_dir_all(parent).ok();
}
+ crate::commands::file_sync::mark_app_write_path(&cache_path);
fs::write(&cache_path, text)
.map_err(|e| format!("Failed to write cache: {}", e))
}
diff --git a/src/commands/fs.ts b/src/commands/fs.ts
index 64e53b06..4efe013e 100644
--- a/src/commands/fs.ts
+++ b/src/commands/fs.ts
@@ -27,6 +27,13 @@ export async function copyFile(
return invoke("copy_file", { source, destination })
}
+export async function copyDirectory(
+ source: string,
+ destination: string
+): Promise<string[]> {
+ return invoke<string[]>("copy_directory", { source, destination })
+}
+
export async function preprocessFile(path: string): Promise<string> {
return invoke<string>("preprocess_file", { path })
}
diff --git a/src/components/search/search-view.tsx b/src/components/search/search-view.tsx
index d4a44a98..08c95011 100644
--- a/src/components/search/search-view.tsx
+++ b/src/components/search/search-view.tsx
@@ -30,7 +30,6 @@ export function SearchView() {
const project = useWikiStore((s) => s.project)
const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
const setFileContent = useWikiStore((s) => s.setFileContent)
- const setActiveView = useWikiStore((s) => s.setActiveView)
const setPendingScrollImageSrc = useWikiStore((s) => s.setPendingScrollImageSrc)
const [query, setQuery] = useState("")
@@ -120,7 +119,6 @@ export function SearchView() {
const content = await readFile(path)
setSelectedFile(path)
setFileContent(content)
- setActiveView("wiki")
} catch (err) {
console.error("Failed to open search result:", err)
}
@@ -178,7 +176,6 @@ export function SearchView() {
setPendingScrollImageSrc(scrollTarget)
setSelectedFile(openPath)
setFileContent(content)
- setActiveView("wiki")
setLightbox(null)
} catch (err) {
console.error("Failed to jump to source:", err)
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index 1548a236..b9128499 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -6,13 +6,13 @@ import { ScrollArea } from "@/components/ui/scroll-area"
import { useWikiStore } from "@/stores/wiki-store"
import { listDirectory, readFile } from "@/commands/fs"
import type { FileNode } from "@/types/wiki"
-import { enqueueIngest } from "@/lib/ingest-queue"
import { useTranslation } from "react-i18next"
import { normalizePath } from "@/lib/path-utils"
import { decideDeleteClick } from "@/lib/sources-tree-delete"
import {
deleteSourceFile,
deleteSourceFolder,
+ enqueueSourceIngest,
importSourceFiles,
importSourceFolder,
} from "@/lib/source-lifecycle"
@@ -223,7 +223,7 @@ export function SourcesView() {
// who expected a fresh-import re-run. One button, one path now.
setIngestingPath(node.path)
try {
- await enqueueIngest(project.id, node.path)
+ await enqueueSourceIngest(project, [node.path], llmConfig)
} catch (err) {
console.error("Failed to enqueue ingest:", err)
} finally {
diff --git a/src/lib/project-file-sync.test.ts b/src/lib/project-file-sync.test.ts
index ecca20d5..52da98ab 100644
--- a/src/lib/project-file-sync.test.ts
+++ b/src/lib/project-file-sync.test.ts
@@ -45,7 +45,10 @@ const mocks = vi.hoisted(() => {
enqueueBatch: vi.fn(async () => []),
removeFromIngestCache: vi.fn(async () => undefined),
removePageEmbedding: vi.fn(async () => undefined),
- cascadeDeleteWikiPagesWithRefs: vi.fn(async () => ({ deletedPaths: [], rewrittenFiles: 0 })),
+ cascadeDeleteWikiPagesWithRefs: vi.fn(async () => ({
+ deletedPaths: [] as string[],
+ rewrittenFiles: 0,
+ })),
}
})
@@ -87,6 +90,18 @@ describe("project file sync", () => {
vi.useRealTimers()
vi.clearAllMocks()
mocks.clearResolvers()
+ mocks.listDirectory.mockImplementation(async (_path?: string) => [])
+ mocks.readFile.mockImplementation(async (_path?: string) => "")
+ mocks.writeFile.mockImplementation(async () => undefined)
+ mocks.deleteFile.mockImplementation(async () => undefined)
+ mocks.findRelatedWikiPages.mockImplementation(async () => [])
+ mocks.enqueueBatch.mockImplementation(async () => [])
+ mocks.removeFromIngestCache.mockImplementation(async () => undefined)
+ mocks.removePageEmbedding.mockImplementation(async () => undefined)
+ mocks.cascadeDeleteWikiPagesWithRefs.mockImplementation(async () => ({
+ deletedPaths: [] as string[],
+ rewrittenFiles: 0,
+ }))
const { useWikiStore } = await import("@/stores/wiki-store")
const { useFileSyncStore } = await import("@/stores/file-sync-store")
await import("@/lib/project-file-sync").then((m) => m.stopProjectFileSync())
@@ -182,6 +197,41 @@ describe("project file sync", () => {
])
})
+ it("does not ingest preprocessed cache files from raw/sources/.cache", async () => {
+ vi.useFakeTimers()
+ const { startProjectFileSync } = await import("@/lib/project-file-sync")
+ const { useWikiStore } = await import("@/stores/wiki-store")
+
+ const project = { id: "A", name: "A", path: "/tmp/a" }
+ useWikiStore.getState().setProject(project)
+ void startProjectFileSync(project)
+
+ await vi.waitFor(() => {
+ expect(mocks.listen).toHaveBeenCalledTimes(2)
+ })
+
+ mocks.emit("file-sync://changed", {
+ projectId: "A",
+ tasks: [
+ {
+ id: "t1",
+ projectId: "A",
+ path: "raw/sources/.cache/report.pdf.txt",
+ kind: "created",
+ status: "done",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ },
+ ],
+ })
+
+ await vi.advanceTimersByTimeAsync(250)
+
+ expect(mocks.enqueueBatch).not.toHaveBeenCalled()
+ })
+
it("removes an externally deleted raw source from every wiki page sources field", async () => {
vi.useFakeTimers()
const { startProjectFileSync } = await import("@/lib/project-file-sync")
@@ -251,4 +301,149 @@ describe("project file sync", () => {
)
})
})
+
+ it("cascades delete for wiki pages whose only source was externally deleted", async () => {
+ vi.useFakeTimers()
+ const { startProjectFileSync } = await import("@/lib/project-file-sync")
+ const { useWikiStore } = await import("@/stores/wiki-store")
+
+ const project = { id: "A", name: "A", path: "/tmp/a" }
+ useWikiStore.getState().setProject(project)
+ mocks.listDirectory.mockImplementation(async (path?: string) => {
+ if (path === "/tmp/a/wiki") {
+ return [
+ {
+ name: "sources",
+ path: "/tmp/a/wiki/sources",
+ is_dir: true,
+ children: [
+ {
+ name: "life.md",
+ path: "/tmp/a/wiki/sources/life.md",
+ is_dir: false,
+ },
+ ],
+ },
+ ]
+ }
+ return []
+ })
+ mocks.readFile.mockImplementation(async (path?: string) => {
+ if (path === "/tmp/a/wiki/sources/life.md") {
+ return "---\nsources: [life_is_a_mind_game.md]\n---\n# Life\n"
+ }
+ if (path === "/tmp/a/wiki/log.md") return "# Wiki Log\n"
+ return ""
+ })
+ mocks.cascadeDeleteWikiPagesWithRefs.mockResolvedValueOnce({
+ deletedPaths: ["/tmp/a/wiki/sources/life.md"],
+ rewrittenFiles: 1,
+ })
+
+ void startProjectFileSync(project)
+ await vi.waitFor(() => {
+ expect(mocks.listen).toHaveBeenCalledTimes(2)
+ })
+
+ mocks.emit("file-sync://changed", {
+ projectId: "A",
+ tasks: [
+ {
+ id: "t1",
+ projectId: "A",
+ path: "raw/sources/life_is_a_mind_game.md",
+ kind: "deleted",
+ status: "done",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ },
+ ],
+ })
+
+ await vi.advanceTimersByTimeAsync(250)
+
+ await vi.waitFor(() => {
+ expect(mocks.cascadeDeleteWikiPagesWithRefs).toHaveBeenCalledWith(
+ "/tmp/a",
+ ["/tmp/a/wiki/sources/life.md"],
+ )
+ })
+ })
+
+ it("processes external batch source deletion with one wiki scan and one cascade", async () => {
+ vi.useFakeTimers()
+ const { startProjectFileSync } = await import("@/lib/project-file-sync")
+ const { useWikiStore } = await import("@/stores/wiki-store")
+
+ const project = { id: "A", name: "A", path: "/tmp/a" }
+ useWikiStore.getState().setProject(project)
+ mocks.listDirectory.mockImplementation(async (path?: string) => {
+ if (path === "/tmp/a/wiki") {
+ return [
+ {
+ name: "sources",
+ path: "/tmp/a/wiki/sources",
+ is_dir: true,
+ children: [
+ { name: "one.md", path: "/tmp/a/wiki/sources/one.md", is_dir: false },
+ { name: "two.md", path: "/tmp/a/wiki/sources/two.md", is_dir: false },
+ ],
+ },
+ ]
+ }
+ return []
+ })
+ mocks.readFile.mockImplementation(async (path?: string) => {
+ if (path === "/tmp/a/wiki/sources/one.md") return "---\nsources: [one.pdf]\n---\n# One\n"
+ if (path === "/tmp/a/wiki/sources/two.md") return "---\nsources: [two.pdf]\n---\n# Two\n"
+ if (path === "/tmp/a/wiki/log.md") return "# Wiki Log\n"
+ return ""
+ })
+ mocks.cascadeDeleteWikiPagesWithRefs.mockResolvedValueOnce({
+ deletedPaths: ["/tmp/a/wiki/sources/one.md", "/tmp/a/wiki/sources/two.md"],
+ rewrittenFiles: 2,
+ })
+
+ void startProjectFileSync(project)
+ await vi.waitFor(() => {
+ expect(mocks.listen).toHaveBeenCalledTimes(2)
+ })
+
+ mocks.emit("file-sync://changed", {
+ projectId: "A",
+ tasks: [
+ {
+ id: "t1",
+ projectId: "A",
+ path: "raw/sources/one.pdf",
+ kind: "deleted",
+ status: "done",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ },
+ {
+ id: "t2",
+ projectId: "A",
+ path: "raw/sources/two.pdf",
+ kind: "deleted",
+ status: "done",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ },
+ ],
+ })
+
+ await vi.advanceTimersByTimeAsync(250)
+
+ await vi.waitFor(() => {
+ expect(mocks.cascadeDeleteWikiPagesWithRefs).toHaveBeenCalledTimes(1)
+ })
+ expect(mocks.listDirectory.mock.calls.filter(([path]) => path === "/tmp/a/wiki")).toHaveLength(1)
+ })
})
diff --git a/src/lib/project-file-sync.ts b/src/lib/project-file-sync.ts
index 6bd1aa1a..d7848214 100644
--- a/src/lib/project-file-sync.ts
+++ b/src/lib/project-file-sync.ts
@@ -7,12 +7,12 @@ import {
} from "@/commands/file-sync"
import { useFileSyncStore } from "@/stores/file-sync-store"
import { useWikiStore } from "@/stores/wiki-store"
-import { normalizePath } from "@/lib/path-utils"
+import { getFileStem, normalizePath } from "@/lib/path-utils"
import type { WikiProject } from "@/types/wiki"
import type { FileChangeTask } from "@/commands/file-sync"
import {
cleanupDeletedWikiPages,
- deleteSourceFile,
+ deleteSourceFiles,
enqueueSourceIngest,
isIngestableSourcePath,
} from "@/lib/source-lifecycle"
@@ -98,12 +98,20 @@ function scheduleRefreshAfterFileChanges(tasks: FileChangeTask[]): void {
const tasks = [...pendingChangeTasks.values()]
pendingRefreshPaths.clear()
pendingChangeTasks.clear()
- void refreshAfterFileChanges(project, paths)
- void enqueueRawSourceChanges(project, tasks)
- void cleanupDeletedFiles(project, tasks)
+ void processFileChangeBatch(project, paths, tasks)
}, 250)
}
+async function processFileChangeBatch(
+ project: WikiProject,
+ paths: string[],
+ tasks: FileChangeTask[],
+): Promise<void> {
+ await cleanupDeletedFiles(project, tasks)
+ await enqueueRawSourceChanges(project, tasks)
+ await refreshAfterFileChanges(project, paths)
+}
+
async function refreshAfterFileChanges(project: WikiProject, relativePaths: string[]): Promise<void> {
const pp = normalizePath(project.path)
const store = useWikiStore.getState()
@@ -163,20 +171,23 @@ async function cleanupDeletedFiles(project: WikiProject, tasks: FileChangeTask[]
const rawSources = deleted.filter(isRawSourcePathForCascade)
const wikiPages = deleted.filter(isWikiPageForCascade)
- for (const rel of rawSources) {
+ let deletedWikiSlugs = new Set<string>()
+ if (rawSources.length > 0) {
try {
- await deleteSourceFile(project.path, rel, {
+ const result = await deleteSourceFiles(project.path, rawSources, {
fileAlreadyDeleted: true,
- logReason: "external delete",
+ logReason: rawSources.length === 1 ? "external delete" : "external batch delete",
})
+ deletedWikiSlugs = new Set(result.deletedWikiPaths.map((path) => getFileStem(path)))
} catch (err) {
- console.error(`[file-sync] failed to clean deleted raw source ${rel}:`, err)
+ console.error("[file-sync] failed to clean deleted raw sources:", err)
}
}
- if (wikiPages.length > 0) {
+ const wikiPagesToClean = wikiPages.filter((path) => !deletedWikiSlugs.has(getFileStem(path)))
+ if (wikiPagesToClean.length > 0) {
try {
- await cleanupDeletedWikiPages(project.path, wikiPages)
+ await cleanupDeletedWikiPages(project.path, wikiPagesToClean)
} catch (err) {
console.error("[file-sync] failed to clean deleted wiki pages:", err)
}
@@ -193,9 +204,11 @@ function isRawSourcePathForCascade(relativePath: string): boolean {
function isWikiPageForCascade(relativePath: string): boolean {
const path = normalizePath(relativePath)
- if (!path.startsWith("wiki/") || !path.endsWith(".md")) return false
- if (path === "wiki/index.md" || path === "wiki/log.md" || path === "wiki/overview.md") {
+ const lower = path.toLowerCase()
+ if (!lower.startsWith("wiki/") || !lower.endsWith(".md")) return false
+ const name = lower.split("/").pop()
+ if (name === "index.md" || name === "log.md" || name === "overview.md") {
return false
}
- return !path.startsWith("wiki/media/")
+ return !lower.startsWith("wiki/media/")
}
diff --git a/src/lib/source-lifecycle.test.ts b/src/lib/source-lifecycle.test.ts
new file mode 100644
index 00000000..6c3c25aa
--- /dev/null
+++ b/src/lib/source-lifecycle.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest"
+import {
+ folderContextForSourcePath,
+ isIngestableSourcePath,
+} from "./source-lifecycle"
+
+describe("source-lifecycle path helpers", () => {
+ it("does not treat preprocessed cache files as ingestable sources", () => {
+ expect(isIngestableSourcePath("raw/sources/.cache/report.pdf.txt")).toBe(false)
+ expect(isIngestableSourcePath("/project/raw/sources/.cache/report.pdf.txt")).toBe(false)
+ })
+
+ it("derives folder context from absolute raw/sources paths without leaking the project prefix", () => {
+ expect(
+ folderContextForSourcePath("/tmp/project/raw/sources/reports/2026/report.pdf"),
+ ).toBe("reports > 2026")
+ })
+})
diff --git a/src/lib/source-lifecycle.ts b/src/lib/source-lifecycle.ts
index 1e7eeca5..37d71cb0 100644
--- a/src/lib/source-lifecycle.ts
+++ b/src/lib/source-lifecycle.ts
@@ -1,8 +1,8 @@
-import { invoke } from "@tauri-apps/api/core"
import {
+ copyDirectory,
copyFile,
deleteFile,
- findRelatedWikiPages,
+ fileExists,
listDirectory,
preprocessFile,
readFile,
@@ -10,10 +10,9 @@ import {
} from "@/commands/fs"
import type { WikiProject, FileNode } from "@/types/wiki"
import type { LlmConfig } from "@/stores/wiki-store"
-import { enqueueBatch, enqueueIngest } from "@/lib/ingest-queue"
+import { enqueueBatch } from "@/lib/ingest-queue"
import { hasUsableLlm } from "@/lib/has-usable-llm"
import { getFileName, getFileStem, normalizePath } from "@/lib/path-utils"
-import { decidePageFate } from "@/lib/source-delete-decision"
import {
parseFrontmatterArray,
parseSources,
@@ -25,6 +24,7 @@ import { removePageEmbedding } from "@/lib/embedding"
import {
buildDeletedKeys,
cleanIndexListing,
+ normalizeWikiRefKey,
stripDeletedWikilinks,
} from "@/lib/wiki-cleanup"
import { collectAllFilesIncludingDot } from "@/lib/sources-tree-delete"
@@ -57,8 +57,16 @@ export interface DeleteSourceFolderResult {
deletedWikiPaths: string[]
}
+export interface DeleteSourcesResult {
+ deletedWikiPaths: string[]
+ rewrittenSourcePages: number
+ skippedPages: number
+}
+
export function isIngestableSourcePath(path: string): boolean {
- const fileName = normalizePath(path).split("/").pop() ?? ""
+ const normalized = normalizePath(path)
+ if (normalized.split("/").includes(".cache")) return false
+ const fileName = normalized.split("/").pop() ?? ""
if (!fileName || fileName.startsWith(".")) return false
const ext = fileName.includes(".") ? fileName.split(".").pop()?.toLowerCase() : ""
return ext ? INGESTABLE_SOURCE_EXTENSIONS.has(ext) : false
@@ -67,7 +75,12 @@ export function isIngestableSourcePath(path: string): boolean {
export function folderContextForSourcePath(sourcePath: string, sourcesRoot = "raw/sources"): string {
const path = normalizePath(sourcePath)
const root = normalizePath(sourcesRoot)
- const rel = path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path
+ const rawMarker = "/raw/sources/"
+ const rel = path.startsWith(`${root}/`)
+ ? path.slice(root.length + 1)
+ : path.includes(rawMarker)
+ ? path.slice(path.indexOf(rawMarker) + rawMarker.length)
+ : path
const parts = rel.split("/")
parts.pop()
return parts.join(" > ")
@@ -113,13 +126,7 @@ export async function importSourceFiles(
}
}
- if (hasUsableLlm(llmConfig)) {
- for (const destPath of importedPaths) {
- enqueueIngest(project.id, destPath).catch((err) =>
- console.error("Failed to enqueue ingest:", err),
- )
- }
- }
+ await enqueueSourceIngest(project, importedPaths, llmConfig)
return importedPaths
}
@@ -132,10 +139,7 @@ export async function importSourceFolder(
const pp = normalizePath(project.path)
const folderName = getFileName(selectedFolder) || "imported"
const destDir = `${pp}/raw/sources/${folderName}`
- const copiedFiles: string[] = await invoke("copy_directory", {
- source: selectedFolder,
- destination: destDir,
- })
+ const copiedFiles = await copyDirectory(selectedFolder, destDir)
for (const filePath of copiedFiles) {
preprocessFile(filePath).catch(() => {})
@@ -156,55 +160,89 @@ export async function deleteSourceFile(
sourcePath: string,
options: { fileAlreadyDeleted?: boolean; logReason?: string } = {},
): Promise<DeleteSourceResult> {
- const pp = normalizePath(projectPath)
- const normalizedSource = normalizePath(sourcePath)
- const fileName = normalizedSource.split("/").pop() ?? ""
- if (!fileName) return { deletedWikiPaths: [], rewrittenSourcePages: 0 }
+ const result = await deleteSourceFiles(projectPath, [sourcePath], options)
+ return {
+ deletedWikiPaths: result.deletedWikiPaths,
+ rewrittenSourcePages: result.rewrittenSourcePages,
+ }
+}
- const relatedPages = await findRelatedWikiPages(pp, fileName)
- const candidatePages = new Set(relatedPages)
+export async function deleteSourceFiles(
+ projectPath: string,
+ sourcePaths: string[],
+ options: { fileAlreadyDeleted?: boolean; logReason?: string } = {},
+): Promise<DeleteSourcesResult> {
+ const pp = normalizePath(projectPath)
+ const normalizedSources = sourcePaths.map(normalizePath)
+ const fileNames = normalizedSources
+ .map((source) => source.split("/").pop() ?? "")
+ .filter(Boolean)
- try {
- const wikiTree = await listDirectory(`${pp}/wiki`)
- for (const file of flattenMd(wikiTree)) {
- try {
- const content = await readFile(file.path)
- if (parseSources(content).some((source) => sourceMatchesDeletedFile(source, fileName))) {
- candidatePages.add(file.path)
- }
- } catch {
- // Ignore unreadable pages; related-pages matching may still cover them.
- }
- }
- } catch (err) {
- console.warn("[source-lifecycle] failed to scan wiki sources during delete:", err)
+ if (fileNames.length === 0) {
+ return { deletedWikiPaths: [], rewrittenSourcePages: 0, skippedPages: 0 }
}
+ const deletingNames = new Set(fileNames.map((name) => name.toLowerCase()))
+
if (!options.fileAlreadyDeleted) {
- await deleteFile(normalizedSource)
+ for (const source of normalizedSources) {
+ await deleteFile(source)
+ }
}
- try {
- await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)
- } catch {
- // cache file may not exist
+ for (const fileName of fileNames) {
+ try {
+ await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)
+ } catch {
+ // cache file may not exist
+ }
+ try {
+ await removeFromIngestCache(pp, fileName)
+ } catch {
+ // non-critical
+ }
}
const pagesToDelete: string[] = []
let rewrittenSourcePages = 0
+ let skippedPages = 0
- for (const pagePath of candidatePages) {
+ let allMd: FileNode[] = []
+ try {
+ allMd = flattenMd(await listDirectory(`${pp}/wiki`))
+ } catch (err) {
+ console.warn("[source-lifecycle] failed to scan wiki sources during delete:", err)
+ }
+
+ for (const file of allMd) {
+ let content: string
try {
- const content = await readFile(pagePath)
- const decision = decidePageFate(parseSources(content), fileName)
- if (decision.action === "keep") {
- await writeFile(pagePath, writeSources(content, decision.updatedSources))
+ content = await readFile(file.path)
+ } catch (err) {
+ console.warn(`[source-lifecycle] failed to read ${file.path}:`, err)
+ continue
+ }
+
+ const sources = parseSources(content)
+ if (sources.length === 0) {
+ skippedPages++
+ continue
+ }
+
+ const survivors = sources.filter((source) => !sourceNameMatchesAny(source, deletingNames))
+ if (survivors.length === sources.length) {
+ continue
+ }
+
+ if (survivors.length === 0) {
+ pagesToDelete.push(file.path)
+ } else {
+ try {
+ await writeFile(file.path, writeSources(content, survivors))
rewrittenSourcePages++
- } else if (decision.action === "delete") {
- pagesToDelete.push(pagePath)
+ } catch (err) {
+ console.warn(`[source-lifecycle] failed to rewrite sources for ${file.path}:`, err)
}
- } catch (err) {
- console.error(`Failed to process wiki page ${pagePath}:`, err)
}
}
@@ -215,19 +253,19 @@ export async function deleteSourceFile(
deletedWikiPaths = result.deletedPaths
}
- try {
- await removeFromIngestCache(pp, fileName)
- } catch {
- // non-critical
- }
-
- await appendSourceDeleteLog(pp, fileName, {
+ await appendSourceDeleteLog(pp, fileNames, {
reason: options.logReason ?? (options.fileAlreadyDeleted ? "external delete" : "delete"),
deletedWikiCount: deletedWikiPaths.length,
keptWikiCount: rewrittenSourcePages,
})
- return { deletedWikiPaths, rewrittenSourcePages }
+ if (skippedPages > 0) {
+ console.debug(
+ `[source-lifecycle] skipped ${skippedPages} wiki pages with no parseable sources while deleting ${fileNames.length} source(s)`,
+ )
+ }
+
+ return { deletedWikiPaths, rewrittenSourcePages, skippedPages }
}
export async function deleteSourceFolder(
@@ -236,16 +274,13 @@ export async function deleteSourceFolder(
options: { folderAlreadyDeleted?: boolean } = {},
): Promise<DeleteSourceFolderResult> {
const deletedWikiPaths: string[] = []
- for (const file of collectAllFilesIncludingDot(folder)) {
- try {
- const result = await deleteSourceFile(projectPath, file.path, {
- fileAlreadyDeleted: options.folderAlreadyDeleted,
- logReason: options.folderAlreadyDeleted ? "external folder delete" : "folder delete",
- })
- deletedWikiPaths.push(...result.deletedWikiPaths)
- } catch (err) {
- console.warn(`Failed to delete ${file.path} during source folder delete:`, err)
- }
+ const files = collectAllFilesIncludingDot(folder).map((file) => file.path)
+ if (files.length > 0) {
+ const result = await deleteSourceFiles(projectPath, files, {
+ fileAlreadyDeleted: options.folderAlreadyDeleted,
+ logReason: options.folderAlreadyDeleted ? "external folder delete" : "folder delete",
+ })
+ deletedWikiPaths.push(...result.deletedWikiPaths)
}
if (!options.folderAlreadyDeleted) {
@@ -280,7 +315,6 @@ export async function cleanupDeletedWikiPages(
}
const deletedKeys = buildDeletedKeys(deletedInfos)
- const deletedSlugSet = new Set(deletedInfos.map((info) => normalizeCleanupKey(info.slug)))
const wikiTree = await listDirectory(`${pp}/wiki`)
const allMd = flattenMd(wikiTree)
@@ -300,7 +334,7 @@ export async function cleanupDeletedWikiPages(
const related = parseFrontmatterArray(updated, "related")
if (related.length > 0) {
- const filtered = related.filter((s) => !deletedSlugSet.has(normalizeCleanupKey(s)))
+ const filtered = related.filter((s) => !deletedKeys.has(normalizeWikiRefKey(s)))
if (filtered.length !== related.length) {
updated = writeFrontmatterArray(updated, "related", filtered)
}
@@ -319,9 +353,7 @@ export async function cleanupDeletedWikiPages(
async function getUniqueDestPath(dir: string, fileName: string): Promise<string> {
const basePath = `${dir}/${fileName}`
- try {
- await readFile(basePath)
- } catch {
+ if (!(await fileExists(basePath))) {
return basePath
}
@@ -330,17 +362,13 @@ async function getUniqueDestPath(dir: string, fileName: string): Promise<string>
const date = new Date().toISOString().slice(0, 10).replace(/-/g, "")
const withDate = `${dir}/${nameWithoutExt}-${date}${ext}`
- try {
- await readFile(withDate)
- } catch {
+ if (!(await fileExists(withDate))) {
return withDate
}
for (let i = 2; i <= 99; i++) {
const withCounter = `${dir}/${nameWithoutExt}-${date}-${i}${ext}`
- try {
- await readFile(withCounter)
- } catch {
+ if (!(await fileExists(withCounter))) {
return withCounter
}
}
@@ -350,17 +378,20 @@ async function getUniqueDestPath(dir: string, fileName: string): Promise<string>
async function appendSourceDeleteLog(
projectPath: string,
- fileName: string,
+ fileNames: string | string[],
detail: { reason: string; deletedWikiCount: number; keptWikiCount: number },
): Promise<void> {
try {
+ const names = Array.isArray(fileNames) ? fileNames : [fileNames]
const logPath = `${projectPath}/wiki/log.md`
const logContent = await readFile(logPath).catch(() => "# Wiki Log\n")
const date = new Date().toISOString().slice(0, 10)
- const logEntry = `\n## [${date}] ${detail.reason} | ${fileName}\n\nDeleted source file and ${detail.deletedWikiCount} wiki pages.${detail.keptWikiCount > 0 ? ` ${detail.keptWikiCount} shared pages kept (have other sources).` : ""}\n`
+ const subject = names.length === 1 ? names[0] : `${names.length} source files`
+ const listed = names.length === 1 ? "" : `\n\nSources:\n${names.map((name) => `- ${name}`).join("\n")}`
+ const logEntry = `\n## [${date}] ${detail.reason} | ${subject}\n\nDeleted ${names.length} source file${names.length === 1 ? "" : "s"} and ${detail.deletedWikiCount} wiki pages.${detail.keptWikiCount > 0 ? ` ${detail.keptWikiCount} shared pages kept (have other sources).` : ""}${listed}\n`
await writeFile(logPath, logContent.trimEnd() + logEntry)
- } catch {
- // non-critical
+ } catch (err) {
+ console.warn("[source-lifecycle] failed to append delete log:", err)
}
}
@@ -379,13 +410,9 @@ function flattenMd(nodes: readonly FileNode[]): FileNode[] {
return out
}
-function sourceMatchesDeletedFile(source: string, fileName: string): boolean {
+function sourceNameMatchesAny(source: string, deletingNames: Set<string>): boolean {
const normalizedSource = normalizePath(source).split("/").pop()?.toLowerCase() ?? ""
- return normalizedSource === fileName.toLowerCase()
-}
-
-function normalizeCleanupKey(value: string): string {
- return value.toLowerCase().replace(/[\s\-_]+/g, "")
+ return deletingNames.has(normalizedSource)
}
function withRootContext(context: string, rootContext?: string): string {
diff --git a/src/lib/wiki-cleanup.test.ts b/src/lib/wiki-cleanup.test.ts
index 7e2ec9ba..9d0135f6 100644
--- a/src/lib/wiki-cleanup.test.ts
+++ b/src/lib/wiki-cleanup.test.ts
@@ -69,6 +69,16 @@ describe("buildDeletedKeys", () => {
expect(keys.size).toBe(1)
})
+ it("treats path and .md variants as the same deleted wiki target", () => {
+ const keys = buildDeletedKeys([{ slug: "life_is_a_mind_game", title: "" }])
+ expect(keys.has("lifeisamindgame")).toBe(true)
+
+ const pathKeys = buildDeletedKeys([
+ { slug: "wiki/sources/life_is_a_mind_game.md", title: "" },
+ ])
+ expect(pathKeys.has("lifeisamindgame")).toBe(true)
+ })
+
it("is empty when given no pages", () => {
expect(buildDeletedKeys([]).size).toBe(0)
})
@@ -114,6 +124,17 @@ describe("cleanIndexListing — title/slug matching (Bug A)", () => {
const keys = buildDeletedKeys([{ slug: "kv-cache", title: "KV Cache" }])
expect(cleanIndexListing(text, keys).trim()).toBe("")
})
+
+ it("drops bullets whose wikilink target includes a path or .md suffix", () => {
+ const text = [
+ "- [[wiki/sources/life_is_a_mind_game.md]] — source summary",
+ "- [[wiki/entities/kept.md]] — kept",
+ ].join("\n")
+ const keys = buildDeletedKeys([{ slug: "life_is_a_mind_game", title: "" }])
+ const result = cleanIndexListing(text, keys)
+ expect(result).not.toContain("life_is_a_mind_game")
+ expect(result).toContain("wiki/entities/kept.md")
+ })
})
describe("cleanIndexListing — substring safety (Bug B)", () => {
@@ -302,6 +323,14 @@ describe("stripDeletedWikilinks", () => {
)
})
+ it("strips wikilinks whose target includes a path or .md suffix", () => {
+ const text = "See [[life_is_a_mind_game.md]] and [[wiki/sources/life_is_a_mind_game|Life]]."
+ const keys = buildDeletedKeys([{ slug: "life_is_a_mind_game", title: "" }])
+ expect(stripDeletedWikilinks(text, keys)).toBe(
+ "See life_is_a_mind_game.md and Life.",
+ )
+ })
+
it("does NOT wipe `[[OpenAI]]` when deleting `ai` (Bug B — substring safety)", () => {
const text = "Companies: [[OpenAI]], [[Anthropic]]. Concept: [[AI]]."
const keys = buildDeletedKeys([{ slug: "ai", title: "AI" }])
diff --git a/src/lib/wiki-cleanup.ts b/src/lib/wiki-cleanup.ts
index 5caf5904..a48bb025 100644
--- a/src/lib/wiki-cleanup.ts
+++ b/src/lib/wiki-cleanup.ts
@@ -39,12 +39,18 @@ export interface DeletedPageInfo {
* "KV Cache" → "kvcache"
* "kv-cache" → "kvcache"
* "kv_cache" → "kvcache"
+ * "wiki/concepts/kv-cache.md" → "kvcache"
*
- * Does NOT strip punctuation — `[[Hello, World]]` and `[[Hello World]]`
- * stay distinct on purpose.
+ * It strips path prefixes and a trailing `.md` because wiki refs may
+ * be written as bare slugs, filenames, or paths. It does NOT strip
+ * other punctuation — `[[Hello, World]]` and `[[Hello World]]` stay
+ * distinct on purpose.
*/
-function normalizeKey(s: string): string {
- return s.toLowerCase().replace(/[\s\-_]+/g, "")
+export function normalizeWikiRefKey(s: string): string {
+ const normalized = s.trim().replace(/\\/g, "/")
+ const leaf = normalized.split("/").pop() ?? normalized
+ const withoutMd = leaf.toLowerCase().endsWith(".md") ? leaf.slice(0, -3) : leaf
+ return withoutMd.toLowerCase().replace(/[\s\-_]+/g, "")
}
/**
@@ -55,8 +61,8 @@ function normalizeKey(s: string): string {
export function buildDeletedKeys(infos: DeletedPageInfo[]): Set<string> {
const keys = new Set<string>()
for (const info of infos) {
- if (info.slug) keys.add(normalizeKey(info.slug))
- if (info.title) keys.add(normalizeKey(info.title))
+ if (info.slug) keys.add(normalizeWikiRefKey(info.slug))
+ if (info.title) keys.add(normalizeWikiRefKey(info.title))
}
return keys
}
@@ -96,7 +102,7 @@ export function cleanIndexListing(text: string, deletedKeys: Set<string>): strin
.filter((line) => {
const m = line.match(INDEX_ENTRY_RE)
if (!m) return true
- return !deletedKeys.has(normalizeKey(m[1].trim()))
+ return !deletedKeys.has(normalizeWikiRefKey(m[1].trim()))
})
.join("\n")
}
@@ -117,7 +123,7 @@ const WIKILINK_RE = /\[\[([^\]|]+?)(?:\|([^\]]+))?\]\]/g
export function stripDeletedWikilinks(text: string, deletedKeys: Set<string>): string {
if (deletedKeys.size === 0) return text
return text.replace(WIKILINK_RE, (match, target: string, display: string | undefined) => {
- const key = normalizeKey(target.trim())
+ const key = normalizeWikiRefKey(target.trim())
if (!deletedKeys.has(key)) return match
return display ?? target
})
diff --git a/src/lib/wiki-page-delete.test.ts b/src/lib/wiki-page-delete.test.ts
index acfed16a..408516a2 100644
--- a/src/lib/wiki-page-delete.test.ts
+++ b/src/lib/wiki-page-delete.test.ts
@@ -357,7 +357,7 @@ describe("cascadeDeleteWikiPagesWithRefs", () => {
"---",
"type: project",
"title: Migration",
- "related: [alice-chen, bob, carol]",
+ "related: [alice-chen.md, wiki/entities/bob.md, carol]",
"---",
"",
"Project body.",
@@ -378,9 +378,44 @@ describe("cascadeDeleteWikiPagesWithRefs", () => {
(c) => c[0] === `${PROJECT}/wiki/projects/migration.md`,
)!
const written = projWrite[1]
- // alice-chen filtered out; bob & carol kept.
+ // alice-chen filtered out even when stored with a .md suffix; bob & carol kept.
expect(written).not.toMatch(/\balice-chen\b/)
- expect(written).toContain("bob")
+ expect(written).toContain("wiki/entities/bob.md")
+ expect(written).toContain("carol")
+ })
+
+ it("drops path-style `related:` entries that point at deleted pages", async () => {
+ const target = `${PROJECT}/wiki/entities/bob.md`
+ mockReadFile.mockImplementation(async (p: string) => {
+ if (p === target) return `---\ntitle: "Bob"\n---\nbody`
+ if (p === `${PROJECT}/wiki/projects/migration.md`) {
+ return [
+ "---",
+ "type: project",
+ "title: Migration",
+ "related: [alice-chen, wiki/entities/bob.md, carol]",
+ "---",
+ "",
+ "Project body.",
+ ].join("\n")
+ }
+ throw new Error(`unexpected read ${p}`)
+ })
+ mockListDirectory.mockResolvedValueOnce([
+ dirNode("wiki", [
+ dirNode("wiki/entities", [fileNode("wiki/entities/bob.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]
+ expect(written).toContain("alice-chen")
+ expect(written).not.toContain("wiki/entities/bob.md")
expect(written).toContain("carol")
})
diff --git a/src/lib/wiki-page-delete.ts b/src/lib/wiki-page-delete.ts
index def9041d..a558fc14 100644
--- a/src/lib/wiki-page-delete.ts
+++ b/src/lib/wiki-page-delete.ts
@@ -26,6 +26,7 @@ import {
buildDeletedKeys,
cleanIndexListing,
extractFrontmatterTitle,
+ normalizeWikiRefKey,
stripDeletedWikilinks,
type DeletedPageInfo,
} from "@/lib/wiki-cleanup"
@@ -120,14 +121,6 @@ function flattenMd(nodes: readonly FileNode[]): FileNode[] {
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[]
@@ -205,7 +198,6 @@ export async function cascadeDeleteWikiPagesWithRefs(
// 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`
@@ -232,7 +224,7 @@ export async function cascadeDeleteWikiPagesWithRefs(
const related = parseFrontmatterArray(updated, "related")
if (related.length > 0) {
const filtered = related.filter(
- (s) => !deletedSlugSet.has(normalizeKey(s)),
+ (s) => !deletedKeys.has(normalizeWikiRefKey(s)),
)
if (filtered.length !== related.length) {
updated = writeFrontmatterArray(updated, "related", filtered)