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
Refactor source lifecycle flows
nash_su8767e78e264c
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsxindex 65881b42..1548a236 100644--- a/src/components/sources/sources-view.tsx+++ b/src/components/sources/sources-view.tsx@@ -1,23 +1,21 @@import { useState, useEffect, useCallback } from "react"import { open } from "@tauri-apps/plugin-dialog"-import { invoke } from "@tauri-apps/api/core"import { Plus, FileText, RefreshCw, BookOpen, Trash2, Folder, ChevronRight, ChevronDown } from "lucide-react"import { Button } from "@/components/ui/button"import { ScrollArea } from "@/components/ui/scroll-area"import { useWikiStore } from "@/stores/wiki-store"-import { copyFile, listDirectory, readFile, writeFile, deleteFile, findRelatedWikiPages, preprocessFile } from "@/commands/fs"+import { listDirectory, readFile } from "@/commands/fs"import type { FileNode } from "@/types/wiki"-import { enqueueIngest, enqueueBatch } from "@/lib/ingest-queue"-import { hasUsableLlm } from "@/lib/has-usable-llm"+import { enqueueIngest } from "@/lib/ingest-queue"import { useTranslation } from "react-i18next"-import { normalizePath, getFileName } from "@/lib/path-utils"-import { parseSources, writeSources } from "@/lib/sources-merge"-import { decidePageFate } from "@/lib/source-delete-decision"-import { removeFromIngestCache } from "@/lib/ingest-cache"+import { normalizePath } from "@/lib/path-utils"+import { decideDeleteClick } from "@/lib/sources-tree-delete"import {- collectAllFilesIncludingDot,- decideDeleteClick,-} from "@/lib/sources-tree-delete"+ deleteSourceFile,+ deleteSourceFolder,+ importSourceFiles,+ importSourceFolder,+} from "@/lib/source-lifecycle"export function SourcesView() {const { t } = useTranslation()@@ -112,33 +110,12 @@ export function SourcesView() {if (!selected || selected.length === 0) returnsetImporting(true)- const pp = normalizePath(project.path)const paths = Array.isArray(selected) ? selected : [selected]-- const importedPaths: string[] = []- for (const sourcePath of paths) {- const originalName = getFileName(sourcePath) || "unknown"- const destPath = await getUniqueDestPath(`${pp}/raw/sources`, originalName)- try {- await copyFile(sourcePath, destPath)- importedPaths.push(destPath)- // Pre-process file (extract text from PDF, etc.) for instant preview later- preprocessFile(destPath).catch(() => {})- } catch (err) {- console.error(`Failed to import ${originalName}:`, err)- }- }-- setImporting(false)- await loadSources()-- // Enqueue for serial ingest (runs in background via ingest queue)- if (hasUsableLlm(llmConfig)) {- for (const destPath of importedPaths) {- enqueueIngest(project.id, destPath).catch((err) =>- console.error(`Failed to enqueue ingest:`, err)- )- }+ try {+ await importSourceFiles(project, paths, llmConfig)+ await loadSources()+ } finally {+ setImporting(false)}}@@ -153,59 +130,12 @@ export function SourcesView() {if (!selected || typeof selected !== "string") returnsetImporting(true)- const pp = normalizePath(project.path)- const folderName = getFileName(selected) || "imported"- const destDir = `${pp}/raw/sources/${folderName}`-try {- // Recursively copy the folder- const copiedFiles: string[] = await invoke("copy_directory", {- source: selected,- destination: destDir,- })-- console.log(`[Folder Import] Copied ${copiedFiles.length} files from ${folderName}`)-- // Preprocess all files- for (const filePath of copiedFiles) {- preprocessFile(filePath).catch(() => {})- }-- setImporting(false)+ await importSourceFolder(project, selected, llmConfig)await loadSources()-- // Build ingest tasks with folder context- if (hasUsableLlm(llmConfig)) {- const tasks = copiedFiles- .filter((fp) => {- const ext = fp.split(".").pop()?.toLowerCase() ?? ""- // Only ingest text-based files, skip images/media- return ["md", "mdx", "txt", "pdf", "docx", "pptx", "xlsx", "xls",- "csv", "json", "html", "htm", "rtf", "xml", "yaml", "yml"].includes(ext)- })- .map((filePath) => {- // Build folder context from relative path. On Windows the- // Rust-returned filePath uses backslashes while destDir was- // composed with forward slashes — normalize both sides before- // the replace so this works on every platform.- const normFilePath = normalizePath(filePath)- const normDestDir = normalizePath(destDir)- const relPath = normFilePath.replace(normDestDir + "/", "")- const parts = relPath.split("/")- parts.pop() // remove filename- const context = parts.length > 0- ? `${folderName} > ${parts.join(" > ")}`- : folderName- return { sourcePath: filePath, folderContext: context }- })-- if (tasks.length > 0) {- await enqueueBatch(project.id, tasks)- console.log(`[Folder Import] Enqueued ${tasks.length} files for ingest`)- }- }} catch (err) {console.error(`Failed to import folder:`, err)+ } finally {setImporting(false)}}@@ -228,7 +158,7 @@ export function SourcesView() {// delete). Reaching this handler means the user has already// confirmed via the inline UI, so we proceed unconditionally.try {- const result = await deleteSourceWithCascade(pp, node)+ const result = await deleteSourceFile(pp, node.path)// Step 8: Refresh everything (UI side — must run with parent// context, hence kept here rather than inside the helper).await loadSources()@@ -265,31 +195,14 @@ export function SourcesView() {if (!project) returnconst pp = normalizePath(project.path)try {- const allFiles = collectAllFilesIncludingDot(folder)- const allDeletedWikiPaths: string[] = []- for (const file of allFiles) {- try {- const r = await deleteSourceWithCascade(pp, file)- allDeletedWikiPaths.push(...r.deletedWikiPaths)- } catch (err) {- console.warn(`Failed to delete ${file.path} during folder delete:`, err)- }- }- // Now remove the folder (and any leftover empty subdirs / dot- // cache dirs) in one shot. Files we just deleted above are- // gone; this call mostly tears down empty directories.- try {- await deleteFile(folder.path)- } catch (err) {- console.warn(`Failed to remove folder ${folder.path}:`, err)- }+ const result = await deleteSourceFolder(pp, folder)await loadSources()const tree = await listDirectory(pp)setFileTree(tree)useWikiStore.getState().bumpDataVersion()if (selectedFile?.startsWith(folder.path + "/") ||- allDeletedWikiPaths.includes(selectedFile ?? "")+ result.deletedWikiPaths.includes(selectedFile ?? "")) {setSelectedFile(null)}@@ -299,124 +212,6 @@ export function SourcesView() {}}- /**- * Per-file deletion: the wiki cascade portion (steps 1-7 of the- * old handleDelete), without the confirmation dialog or the- * UI-state refresh (callers do those once at the end of a batch).- *- * Returns the wiki page paths we actually removed so the caller- * can reset selectedFile if one of them was open.- */- async function deleteSourceWithCascade(- pp: string,- node: FileNode,- ): Promise<{ deletedWikiPaths: string[] }> {- const fileName = node.name- // Step 1: Find related wiki pages before deleting- const relatedPages = await findRelatedWikiPages(pp, fileName)-- // Step 2: Delete the source file- await deleteFile(node.path)-- // Step 3: Delete preprocessed cache- try {- await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)- } catch {- // cache file may not exist- }-- // 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.- // Pass 1: keep / skip — rewrite sources for shared pages, no- // deletion needed. The "delete" decisions are deferred to a- // single batch call after the loop so we can route them- // through the unified cascade helper.- const pagesToDelete: string[] = []- for (const pagePath of relatedPages) {- try {- const content = await readFile(pagePath)- 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- }-- // action === "delete" → defer.- pagesToDelete.push(pagePath)- } catch (err) {- console.error(`Failed to process wiki page ${pagePath}:`, err)- }- }-- // Pass 2: full cascade for every page whose sole source was- // this file. The helper deletes the file + drops embeddings- // + sweeps every other wiki .md to clean stale body- // wikilinks, index.md listings, AND `related:` frontmatter- // arrays. The previous inline cleanup loop did 1 and 2 but- // left `related:` slugs pointing at deleted pages, which- // FrontmatterPanel renders as a broken-ref warning icon.- const { cascadeDeleteWikiPagesWithRefs } = await import(- "@/lib/wiki-page-delete"- )- const cascadeResult =- pagesToDelete.length > 0- ? await cascadeDeleteWikiPagesWithRefs(pp, pagesToDelete)- : { deletedPaths: [], rewrittenFiles: 0 }- const actuallyDeleted = cascadeResult.deletedPaths-- // Step 7: Append deletion record to log.md- try {- const logPath = `${pp}/wiki/log.md`- const logContent = await readFile(logPath).catch(() => "# Wiki Log\n")- const date = new Date().toISOString().slice(0, 10)- const keptCount = relatedPages.length - actuallyDeleted.length- const logEntry = `\n## [${date}] delete | ${fileName}\n\nDeleted source file and ${actuallyDeleted.length} wiki pages.${keptCount > 0 ? ` ${keptCount} shared pages kept (have other sources).` : ""}\n`- await writeFile(logPath, logContent.trimEnd() + logEntry)- } catch {- // non-critical- }-- // Step 8: Drop the source's ingest-cache entry so a future- // re-import doesn't hit a stale "already ingested" record.- // The cache's existence-check fallback would have caught this- // anyway (it falls through to re-ingest when wiki/sources/<slug>.md- // is gone), but removing the entry up front keeps the cache- // file small and avoids confusing log lines like "cache miss- // for foo.pdf: wiki/sources/foo.md no longer on disk" on- // every search after a delete.- try {- await removeFromIngestCache(pp, fileName)- } catch {- // non-critical- }-- return { deletedWikiPaths: actuallyDeleted }- }-async function handleIngest(node: FileNode) {if (!project || ingestingPath) return// Re-ingest goes through the same automated queue path as a fresh@@ -495,49 +290,6 @@ export function SourcesView() {)}-/**- * Generate a unique destination path. If file already exists, adds date/counter suffix.- * "file.pdf" → "file.pdf" (first time)- * "file.pdf" → "file-20260406.pdf" (conflict)- * "file.pdf" → "file-20260406-2.pdf" (second conflict same day)- */-async function getUniqueDestPath(dir: string, fileName: string): Promise<string> {- const basePath = `${dir}/${fileName}`-- // Check if file exists by trying to read it- try {- await readFile(basePath)- } catch {- // File doesn't exist — use original name- return basePath- }-- // File exists — add date suffix- const ext = fileName.includes(".") ? fileName.slice(fileName.lastIndexOf(".")) : ""- const nameWithoutExt = ext ? fileName.slice(0, -ext.length) : fileName- const date = new Date().toISOString().slice(0, 10).replace(/-/g, "")-- const withDate = `${dir}/${nameWithoutExt}-${date}${ext}`- try {- await readFile(withDate)- } catch {- return withDate- }-- // Date suffix also exists — add counter- for (let i = 2; i <= 99; i++) {- const withCounter = `${dir}/${nameWithoutExt}-${date}-${i}${ext}`- try {- await readFile(withCounter)- } catch {- return withCounter- }- }-- // Shouldn't happen, but fallback- return `${dir}/${nameWithoutExt}-${date}-${Date.now()}${ext}`-}-function filterTree(nodes: FileNode[]): FileNode[] {return nodes.filter((n) => !n.name.startsWith("."))@@ -762,4 +514,3 @@ function DeleteButton({</Button>)}-diff --git a/src/lib/project-file-sync.test.ts b/src/lib/project-file-sync.test.tsindex 31fac8bb..ecca20d5 100644--- a/src/lib/project-file-sync.test.ts+++ b/src/lib/project-file-sync.test.ts@@ -91,6 +91,14 @@ describe("project file sync", () => {const { useFileSyncStore } = await import("@/stores/file-sync-store")await import("@/lib/project-file-sync").then((m) => m.stopProjectFileSync())useWikiStore.getState().setProject(null)+ useWikiStore.getState().setLlmConfig({+ provider: "openai",+ apiKey: "k",+ model: "m",+ ollamaUrl: "",+ customEndpoint: "",+ maxContextSize: 128000,+ })useFileSyncStore.getState().clear()})diff --git a/src/lib/project-file-sync.ts b/src/lib/project-file-sync.tsindex 4abafed3..6bd1aa1a 100644--- a/src/lib/project-file-sync.ts+++ b/src/lib/project-file-sync.ts@@ -1,5 +1,5 @@import { listen, type UnlistenFn } from "@tauri-apps/api/event"-import { deleteFile, findRelatedWikiPages, readFile, listDirectory, writeFile } from "@/commands/fs"+import { readFile, listDirectory } from "@/commands/fs"import {startProjectFileWatcher,stopProjectFileWatcher,@@ -9,23 +9,13 @@ import { useFileSyncStore } from "@/stores/file-sync-store"import { useWikiStore } from "@/stores/wiki-store"import { normalizePath } from "@/lib/path-utils"import type { WikiProject } from "@/types/wiki"-import { enqueueBatch } from "@/lib/ingest-queue"import type { FileChangeTask } from "@/commands/file-sync"-import { decidePageFate } from "@/lib/source-delete-decision"-import { parseSources, writeSources } from "@/lib/sources-merge"-import { removeFromIngestCache } from "@/lib/ingest-cache"-import { getFileStem } from "@/lib/path-utils"-import { removePageEmbedding } from "@/lib/embedding"import {- buildDeletedKeys,- cleanIndexListing,- stripDeletedWikilinks,-} from "@/lib/wiki-cleanup"-import {- parseFrontmatterArray,- writeFrontmatterArray,-} from "@/lib/sources-merge"-import type { FileNode } from "@/types/wiki"+ cleanupDeletedWikiPages,+ deleteSourceFile,+ enqueueSourceIngest,+ isIngestableSourcePath,+} from "@/lib/source-lifecycle"let unlistenQueue: UnlistenFn | null = nulllet unlistenChanged: UnlistenFn | null = null@@ -34,25 +24,6 @@ let refreshTimer: ReturnType<typeof setTimeout> | null = nulllet pendingRefreshPaths = new Set<string>()let pendingChangeTasks = new Map<string, FileChangeTask>()-const INGESTABLE_SOURCE_EXTENSIONS = new Set([- "md",- "mdx",- "txt",- "pdf",- "docx",- "pptx",- "xlsx",- "xls",- "csv",- "json",- "html",- "htm",- "rtf",- "xml",- "yaml",- "yml",-])-export async function startProjectFileSync(project: WikiProject): Promise<void> {await stopProjectFileSync()const seq = ++startSeq@@ -161,19 +132,16 @@ async function refreshAfterFileChanges(project: WikiProject, relativePaths: stri}async function enqueueRawSourceChanges(project: WikiProject, tasks: FileChangeTask[]): Promise<void> {- const files = tasks+ const paths = tasks.filter((task) => task.projectId === project.id).filter((task) => task.kind === "created" || task.kind === "modified")- .filter((task) => isIngestableRawSource(task.path))- .map((task) => ({- sourcePath: task.path,- folderContext: folderContextForRawSource(task.path),- }))+ .map((task) => task.path)+ .filter(isIngestableRawSource)- if (files.length === 0) return+ if (paths.length === 0) returntry {- await enqueueBatch(project.id, files)+ await enqueueSourceIngest(project, paths, useWikiStore.getState().llmConfig)} catch (err) {console.error("[file-sync] failed to enqueue raw source ingest:", err)}@@ -182,17 +150,7 @@ async function enqueueRawSourceChanges(project: WikiProject, tasks: FileChangeTafunction isIngestableRawSource(relativePath: string): boolean {const path = normalizePath(relativePath)if (!path.startsWith("raw/sources/")) return false- const fileName = path.split("/").pop() ?? ""- if (!fileName || fileName.startsWith(".")) return false- const ext = fileName.includes(".") ? fileName.split(".").pop()?.toLowerCase() : ""- return ext ? INGESTABLE_SOURCE_EXTENSIONS.has(ext) : false-}--function folderContextForRawSource(relativePath: string): string {- const rel = normalizePath(relativePath).slice("raw/sources/".length)- const parts = rel.split("/")- parts.pop()- return parts.join(" > ")+ return isIngestableSourcePath(path)}async function cleanupDeletedFiles(project: WikiProject, tasks: FileChangeTask[]): Promise<void> {@@ -207,7 +165,10 @@ async function cleanupDeletedFiles(project: WikiProject, tasks: FileChangeTask[]for (const rel of rawSources) {try {- await cleanupExternallyDeletedRawSource(project.path, rel)+ await deleteSourceFile(project.path, rel, {+ fileAlreadyDeleted: true,+ logReason: "external delete",+ })} catch (err) {console.error(`[file-sync] failed to clean deleted raw source ${rel}:`, err)}@@ -215,7 +176,7 @@ async function cleanupDeletedFiles(project: WikiProject, tasks: FileChangeTask[]if (wikiPages.length > 0) {try {- await cleanupExternallyDeletedWikiPages(project.path, wikiPages)+ await cleanupDeletedWikiPages(project.path, wikiPages)} catch (err) {console.error("[file-sync] failed to clean deleted wiki pages:", err)}@@ -238,156 +199,3 @@ function isWikiPageForCascade(relativePath: string): boolean {}return !path.startsWith("wiki/media/")}--async function cleanupExternallyDeletedRawSource(- projectPath: string,- relativePath: string,-): Promise<void> {- const pp = normalizePath(projectPath)- const fileName = relativePath.split("/").pop() ?? ""- if (!fileName) return-- const relatedPages = await findRelatedWikiPages(pp, fileName)- const candidatePages = new Set(relatedPages)- 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; the related-pages pass may still cover them.- }- }- } catch (err) {- console.warn("[file-sync] failed to scan wiki sources during source delete cleanup:", err)- }-- const pagesToDelete: string[] = []- let keptCount = 0-- for (const pagePath of candidatePages) {- try {- const content = await readFile(pagePath)- const decision = decidePageFate(parseSources(content), fileName)- if (decision.action === "keep") {- await writeFile(pagePath, writeSources(content, decision.updatedSources))- keptCount++- } else if (decision.action === "delete") {- pagesToDelete.push(pagePath)- }- } catch (err) {- console.warn(`[file-sync] failed to process related page ${pagePath}:`, err)- }- }-- if (pagesToDelete.length > 0) {- const { cascadeDeleteWikiPagesWithRefs } = await import("@/lib/wiki-page-delete")- await cascadeDeleteWikiPagesWithRefs(pp, pagesToDelete)- }-- try {- await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)- } catch {- // cache may not exist- }-- try {- await removeFromIngestCache(pp, fileName)- } catch {- // non-critical- }-- try {- const logPath = `${pp}/wiki/log.md`- const logContent = await readFile(logPath).catch(() => "# Wiki Log\n")- const date = new Date().toISOString().slice(0, 10)- const logEntry = `\n## [${date}] external delete | ${fileName}\n\nDetected deleted source file and cleaned ${pagesToDelete.length} wiki pages.${keptCount > 0 ? ` ${keptCount} shared pages kept (have other sources).` : ""}\n`- await writeFile(logPath, logContent.trimEnd() + logEntry)- } catch {- // non-critical- }-}--async function cleanupExternallyDeletedWikiPages(- projectPath: string,- relativePaths: string[],-): Promise<void> {- const pp = normalizePath(projectPath)- const deletedInfos = relativePaths- .map((path) => ({ slug: getFileStem(path), title: "" }))- .filter((info) => info.slug.length > 0 && !info.slug.startsWith("."))-- if (deletedInfos.length === 0) return-- for (const info of deletedInfos) {- await removePageEmbedding(pp, info.slug)- try {- await deleteFile(`${pp}/wiki/media/${info.slug}`)- } catch {- // only source-summary pages usually own media; absence is normal- }- }-- const deletedKeys = buildDeletedKeys(deletedInfos)- const deletedSlugSet = new Set(deletedInfos.map((info) => normalizeCleanupKey(info.slug)))- const wikiTree = await listDirectory(`${pp}/wiki`)- const allMd = flattenMd(wikiTree)-- for (const file of allMd) {- let content: string- try {- content = await readFile(file.path)- } catch {- continue- }-- let updated = content- if (file.path === `${pp}/wiki/index.md` || file.name === "index.md") {- updated = cleanIndexListing(updated, deletedKeys)- }- updated = stripDeletedWikilinks(updated, deletedKeys)-- const related = parseFrontmatterArray(updated, "related")- if (related.length > 0) {- const filtered = related.filter((s) => !deletedSlugSet.has(normalizeCleanupKey(s)))- if (filtered.length !== related.length) {- updated = writeFrontmatterArray(updated, "related", filtered)- }- }-- if (updated !== content) {- try {- await writeFile(file.path, updated)- } catch (err) {- console.warn(`[file-sync] failed to rewrite ${file.path}:`, err)- }- }- }-}--function flattenMd(nodes: readonly FileNode[]): FileNode[] {- const out: FileNode[] = []- function walk(items: readonly FileNode[]): void {- for (const item of items) {- if (item.is_dir) {- if (item.children) walk(item.children)- } else if (item.name.endsWith(".md")) {- out.push(item)- }- }- }- walk(nodes)- return out-}--function sourceMatchesDeletedFile(source: string, fileName: string): boolean {- const normalizedSource = normalizePath(source).split("/").pop()?.toLowerCase() ?? ""- return normalizedSource === fileName.toLowerCase()-}--function normalizeCleanupKey(value: string): string {- return value.toLowerCase().replace(/[\s\-_]+/g, "")-}diff --git a/src/lib/source-lifecycle.ts b/src/lib/source-lifecycle.tsnew file mode 100644index 00000000..1e7eeca5--- /dev/null+++ b/src/lib/source-lifecycle.ts@@ -0,0 +1,395 @@+import { invoke } from "@tauri-apps/api/core"+import {+ copyFile,+ deleteFile,+ findRelatedWikiPages,+ listDirectory,+ preprocessFile,+ readFile,+ writeFile,+} 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 { hasUsableLlm } from "@/lib/has-usable-llm"+import { getFileName, getFileStem, normalizePath } from "@/lib/path-utils"+import { decidePageFate } from "@/lib/source-delete-decision"+import {+ parseFrontmatterArray,+ parseSources,+ writeFrontmatterArray,+ writeSources,+} from "@/lib/sources-merge"+import { removeFromIngestCache } from "@/lib/ingest-cache"+import { removePageEmbedding } from "@/lib/embedding"+import {+ buildDeletedKeys,+ cleanIndexListing,+ stripDeletedWikilinks,+} from "@/lib/wiki-cleanup"+import { collectAllFilesIncludingDot } from "@/lib/sources-tree-delete"++export const INGESTABLE_SOURCE_EXTENSIONS = new Set([+ "md",+ "mdx",+ "txt",+ "pdf",+ "docx",+ "pptx",+ "xlsx",+ "xls",+ "csv",+ "json",+ "html",+ "htm",+ "rtf",+ "xml",+ "yaml",+ "yml",+])++export interface DeleteSourceResult {+ deletedWikiPaths: string[]+ rewrittenSourcePages: number+}++export interface DeleteSourceFolderResult {+ deletedWikiPaths: string[]+}++export function isIngestableSourcePath(path: string): boolean {+ const fileName = normalizePath(path).split("/").pop() ?? ""+ if (!fileName || fileName.startsWith(".")) return false+ const ext = fileName.includes(".") ? fileName.split(".").pop()?.toLowerCase() : ""+ return ext ? INGESTABLE_SOURCE_EXTENSIONS.has(ext) : false+}++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 parts = rel.split("/")+ parts.pop()+ return parts.join(" > ")+}++export async function enqueueSourceIngest(+ project: WikiProject,+ sourcePaths: string[],+ llmConfig: LlmConfig,+ options: { sourceRoot?: string; rootContext?: string } = {},+): Promise<string[]> {+ if (!hasUsableLlm(llmConfig)) return []+ const files = sourcePaths+ .filter(isIngestableSourcePath)+ .map((sourcePath) => ({+ sourcePath,+ folderContext: withRootContext(+ folderContextForSourcePath(sourcePath, options.sourceRoot),+ options.rootContext,+ ),+ }))+ if (files.length === 0) return []+ return enqueueBatch(project.id, files)+}++export async function importSourceFiles(+ project: WikiProject,+ sourcePaths: string[],+ llmConfig: LlmConfig,+): Promise<string[]> {+ const pp = normalizePath(project.path)+ const importedPaths: string[] = []++ for (const sourcePath of sourcePaths) {+ const originalName = getFileName(sourcePath) || "unknown"+ const destPath = await getUniqueDestPath(`${pp}/raw/sources`, originalName)+ try {+ await copyFile(sourcePath, destPath)+ importedPaths.push(destPath)+ preprocessFile(destPath).catch(() => {})+ } catch (err) {+ console.error(`Failed to import ${originalName}:`, err)+ }+ }++ if (hasUsableLlm(llmConfig)) {+ for (const destPath of importedPaths) {+ enqueueIngest(project.id, destPath).catch((err) =>+ console.error("Failed to enqueue ingest:", err),+ )+ }+ }++ return importedPaths+}++export async function importSourceFolder(+ project: WikiProject,+ selectedFolder: string,+ llmConfig: LlmConfig,+): Promise<string[]> {+ 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,+ })++ for (const filePath of copiedFiles) {+ preprocessFile(filePath).catch(() => {})+ }++ if (hasUsableLlm(llmConfig)) {+ await enqueueSourceIngest(project, copiedFiles, llmConfig, {+ sourceRoot: destDir,+ rootContext: folderName,+ })+ }++ return copiedFiles+}++export async function deleteSourceFile(+ projectPath: string,+ 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 relatedPages = await findRelatedWikiPages(pp, fileName)+ const candidatePages = new Set(relatedPages)++ 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 (!options.fileAlreadyDeleted) {+ await deleteFile(normalizedSource)+ }++ try {+ await deleteFile(`${pp}/raw/sources/.cache/${fileName}.txt`)+ } catch {+ // cache file may not exist+ }++ const pagesToDelete: string[] = []+ let rewrittenSourcePages = 0++ for (const pagePath of candidatePages) {+ try {+ const content = await readFile(pagePath)+ const decision = decidePageFate(parseSources(content), fileName)+ if (decision.action === "keep") {+ await writeFile(pagePath, writeSources(content, decision.updatedSources))+ rewrittenSourcePages+++ } else if (decision.action === "delete") {+ pagesToDelete.push(pagePath)+ }+ } catch (err) {+ console.error(`Failed to process wiki page ${pagePath}:`, err)+ }+ }++ let deletedWikiPaths: string[] = []+ if (pagesToDelete.length > 0) {+ const { cascadeDeleteWikiPagesWithRefs } = await import("@/lib/wiki-page-delete")+ const result = await cascadeDeleteWikiPagesWithRefs(pp, pagesToDelete)+ deletedWikiPaths = result.deletedPaths+ }++ try {+ await removeFromIngestCache(pp, fileName)+ } catch {+ // non-critical+ }++ await appendSourceDeleteLog(pp, fileName, {+ reason: options.logReason ?? (options.fileAlreadyDeleted ? "external delete" : "delete"),+ deletedWikiCount: deletedWikiPaths.length,+ keptWikiCount: rewrittenSourcePages,+ })++ return { deletedWikiPaths, rewrittenSourcePages }+}++export async function deleteSourceFolder(+ projectPath: string,+ folder: FileNode,+ 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)+ }+ }++ if (!options.folderAlreadyDeleted) {+ try {+ await deleteFile(folder.path)+ } catch (err) {+ console.warn(`Failed to remove folder ${folder.path}:`, err)+ }+ }++ return { deletedWikiPaths }+}++export async function cleanupDeletedWikiPages(+ projectPath: string,+ relativePaths: string[],+): Promise<void> {+ const pp = normalizePath(projectPath)+ const deletedInfos = relativePaths+ .map((path) => ({ slug: getFileStem(path), title: "" }))+ .filter((info) => info.slug.length > 0 && !info.slug.startsWith("."))++ if (deletedInfos.length === 0) return++ for (const info of deletedInfos) {+ await removePageEmbedding(pp, info.slug)+ try {+ await deleteFile(`${pp}/wiki/media/${info.slug}`)+ } catch {+ // only source-summary pages usually own media; absence is normal+ }+ }++ const deletedKeys = buildDeletedKeys(deletedInfos)+ const deletedSlugSet = new Set(deletedInfos.map((info) => normalizeCleanupKey(info.slug)))+ const wikiTree = await listDirectory(`${pp}/wiki`)+ const allMd = flattenMd(wikiTree)++ for (const file of allMd) {+ let content: string+ try {+ content = await readFile(file.path)+ } catch {+ continue+ }++ let updated = content+ if (file.path === `${pp}/wiki/index.md` || file.name === "index.md") {+ updated = cleanIndexListing(updated, deletedKeys)+ }+ updated = stripDeletedWikilinks(updated, deletedKeys)++ const related = parseFrontmatterArray(updated, "related")+ if (related.length > 0) {+ const filtered = related.filter((s) => !deletedSlugSet.has(normalizeCleanupKey(s)))+ if (filtered.length !== related.length) {+ updated = writeFrontmatterArray(updated, "related", filtered)+ }+ }++ if (updated !== content) {+ try {+ await writeFile(file.path, updated)+ } catch (err) {+ console.warn(`[source-lifecycle] failed to rewrite ${file.path}:`, err)+ }+ }+ }+}++async function getUniqueDestPath(dir: string, fileName: string): Promise<string> {+ const basePath = `${dir}/${fileName}`++ try {+ await readFile(basePath)+ } catch {+ return basePath+ }++ const ext = fileName.includes(".") ? fileName.slice(fileName.lastIndexOf(".")) : ""+ const nameWithoutExt = ext ? fileName.slice(0, -ext.length) : fileName+ const date = new Date().toISOString().slice(0, 10).replace(/-/g, "")++ const withDate = `${dir}/${nameWithoutExt}-${date}${ext}`+ try {+ await readFile(withDate)+ } catch {+ return withDate+ }++ for (let i = 2; i <= 99; i++) {+ const withCounter = `${dir}/${nameWithoutExt}-${date}-${i}${ext}`+ try {+ await readFile(withCounter)+ } catch {+ return withCounter+ }+ }++ return `${dir}/${nameWithoutExt}-${date}-${Date.now()}${ext}`+}++async function appendSourceDeleteLog(+ projectPath: string,+ fileName: string,+ detail: { reason: string; deletedWikiCount: number; keptWikiCount: number },+): Promise<void> {+ try {+ 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`+ await writeFile(logPath, logContent.trimEnd() + logEntry)+ } catch {+ // non-critical+ }+}++function flattenMd(nodes: readonly FileNode[]): FileNode[] {+ const out: FileNode[] = []+ function walk(items: readonly FileNode[]): void {+ for (const item of items) {+ if (item.is_dir) {+ if (item.children) walk(item.children)+ } else if (item.name.endsWith(".md")) {+ out.push(item)+ }+ }+ }+ walk(nodes)+ return out+}++function sourceMatchesDeletedFile(source: string, fileName: string): boolean {+ const normalizedSource = normalizePath(source).split("/").pop()?.toLowerCase() ?? ""+ return normalizedSource === fileName.toLowerCase()+}++function normalizeCleanupKey(value: string): string {+ return value.toLowerCase().replace(/[\s\-_]+/g, "")+}++function withRootContext(context: string, rootContext?: string): string {+ if (!rootContext) return context+ if (!context) return rootContext+ return `${rootContext} > ${context}`+}