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
release: v0.6.3 fix ingest lifecycle issues
nash_su9b71ade7b7e1
diff --git a/package-lock.json b/package-lock.jsonindex fd9ee6d2..587a0a2d 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "llm-wiki",- "version": "0.6.2",+ "version": "0.6.3","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "llm-wiki",- "version": "0.6.2",+ "version": "0.6.3","dependencies": {"@base-ui/react": "^1.3.0","@fontsource-variable/geist": "^5.2.8",diff --git a/package.json b/package.jsonindex 5b3e92e8..5443f98e 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "llm-wiki","private": true,- "version": "0.6.2",+ "version": "0.6.3","type": "module","scripts": {"dev": "vite",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 7b11d692..1b8f287d 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4461,7 +4461,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"[[package]]name = "llm-wiki"-version = "0.6.2"+version = "0.6.3"dependencies = ["arrow-array","arrow-schema",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 69e55305..3d7c35c9 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "llm-wiki"-version = "0.6.2"+version = "0.6.3"description = "LLM Wiki - A personal knowledge base for LLM concepts"authors = []edition = "2021"diff --git a/src-tauri/src/commands/file_sync.rs b/src-tauri/src/commands/file_sync.rsindex b4d0ead3..5b7791f8 100644--- a/src-tauri/src/commands/file_sync.rs+++ b/src-tauri/src/commands/file_sync.rs@@ -767,7 +767,7 @@ fn upsert_task(}) {task.kind = merge_kind(&task.kind, &kind);task.hash_after = new.as_ref().and_then(|m| m.hash.clone());- task.size = new.as_ref().map(|m| m.size);+ task.size = new.as_ref().or(old.as_ref()).map(|m| m.size);task.mtime_ms = new.as_ref().map(|m| m.mtime_ms);task.updated_at = now;if task.status == FileChangeStatus::Failed {@@ -792,9 +792,11 @@ fn upsert_task(path: rel.to_string(),kind,status: FileChangeStatus::Pending,- hash_before: old.and_then(|m| m.hash),+ hash_before: old.as_ref().and_then(|m| m.hash.clone()),hash_after: new.as_ref().and_then(|m| m.hash.clone()),- size: new.as_ref().map(|m| m.size),+ // Deleted tasks need the previous size so frontend rename detection+ // can reject empty/tiny hash matches without disabling all moves.+ size: new.as_ref().or(old.as_ref()).map(|m| m.size),mtime_ms: new.as_ref().map(|m| m.mtime_ms),created_at: now,updated_at: now,@@ -1631,6 +1633,28 @@ mod tests {let _ = fs::remove_dir_all(root);}+ #[test]+ fn deleted_task_keeps_previous_file_size_for_move_detection() {+ let mut queue = FileChangeQueue::default();+ let old = FileMeta {+ hash: Some("same".into()),+ size: 128,+ mtime_ms: 1,+ };+ upsert_task(+ &mut queue,+ "p1",+ "raw/sources/old.md",+ FileChangeKind::Deleted,+ Some(old),+ None,+ 2,+ );++ assert_eq!(queue.tasks[0].size, Some(128));+ assert_eq!(queue.tasks[0].hash_before.as_deref(), Some("same"));+ }+#[test]fn watch_rules_exclude_temporary_and_app_dirs() {let config = default_watch_config();diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex d2052a75..94a9c87a 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "LLM Wiki",- "version": "0.6.2",+ "version": "0.6.3","identifier": "com.llmwiki.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/lib/deep-research.ts b/src/lib/deep-research.tsindex 4d635907..97df64a6 100644--- a/src/lib/deep-research.ts+++ b/src/lib/deep-research.ts@@ -1,7 +1,7 @@import { anyTxtSearchSmart, hasConfiguredAnyTxt } from "./anytxt-search"import { hasConfiguredSearchProvider, resolveSearchConfig, webSearch } from "./web-search"import { streamChat } from "./llm-client"-import { autoIngest, currentWikiDate } from "./ingest"+import { currentWikiDate } from "./ingest"import { writeFile, readFile } from "@/commands/fs"import { useWikiStore, type LlmConfig, type SearchApiConfig } from "@/stores/wiki-store"import { useResearchStore } from "@/stores/research-store"@@ -335,12 +335,23 @@ async function executeResearch(// ignore}- // Auto-ingest the research result to generate entities, concepts, cross-references- if (isActiveProjectPath(pp)) {- autoIngest(pp, `${pp}/${savedPath}`, llmConfig).catch((err) => {- console.error("Failed to auto-ingest research result:", err)- })+ // The query page no longer goes through source ingest, so index it here+ // directly. This keeps freshly generated research available to hybrid+ // search without recreating the review-amplifying ingest loop.+ const embeddingConfig = useWikiStore.getState().embeddingConfig+ if (embeddingConfig.enabled && embeddingConfig.model) {+ try {+ const { embedPage } = await import("@/lib/embedding")+ await embedPage(pp, fileName.replace(/\.md$/i, ""), `Research: ${topic}`, pageContent, embeddingConfig)+ } catch (err) {+ console.warn("[DeepResearch] failed to index generated query page:", err)+ }}++ // A research result is already a generated wiki page. Feeding it back+ // through source ingest creates a second summary page and recursively+ // produces low-value review suggestions from its own gaps/references.+ // Keep it directly searchable as the query page instead.} catch (err) {const message = err instanceof Error ? err.message : String(err)updateTaskIfActive(pp, taskId, {diff --git a/src/lib/enrich-wikilinks.test.ts b/src/lib/enrich-wikilinks.test.tsindex a8ead18d..34301f63 100644--- a/src/lib/enrich-wikilinks.test.ts+++ b/src/lib/enrich-wikilinks.test.ts@@ -13,12 +13,13 @@ vi.mock("@/commands/fs", () => ({import { enrichWithWikilinks } from "./enrich-wikilinks"import { streamChat } from "./llm-client"-import { readFile, writeFile } from "@/commands/fs"+import { listDirectory, readFile, writeFile } from "@/commands/fs"import { useWikiStore } from "@/stores/wiki-store"const mockStreamChat = vi.mocked(streamChat)const mockReadFile = vi.mocked(readFile)const mockWriteFile = vi.mocked(writeFile)+const mockListDirectory = vi.mocked(listDirectory)function fakeLlmConfig(): LlmConfig {return {@@ -43,6 +44,13 @@ beforeEach(() => {mockStreamChat.mockReset()mockReadFile.mockReset()mockWriteFile.mockReset()+ mockListDirectory.mockReset()+ mockListDirectory.mockResolvedValue([+ { path: "/p/wiki/transformer.md", name: "transformer.md", is_dir: false },+ { path: "/p/wiki/attention.md", name: "attention.md", is_dir: false },+ { path: "/p/wiki/encoder.md", name: "encoder.md", is_dir: false },+ { path: "/p/wiki/注意力机制.md", name: "注意力机制.md", is_dir: false },+ ])useWikiStore.getState().setOutputLanguage("auto")})@@ -103,6 +111,58 @@ describe("enrichWithWikilinks — language directive is built at call time", ()})describe("enrichWithWikilinks — JSON-based substitution", () => {+ it("skips enrichment when the authoritative wiki listing is unavailable", async () => {+ mockReadFile.mockResolvedValue("Transformer architecture.")+ mockListDirectory.mockRejectedValue(new Error("scan failed"))+ mockStreamChatReturns(JSON.stringify({+ links: [{ term: "Transformer", target: "invented-page" }],+ }))++ await enrichWithWikilinks("/p", "/p/wiki/f.md", fakeLlmConfig())+ expect(mockWriteFile).not.toHaveBeenCalled()+ })++ it("drops substitutions whose target has no wiki page", async () => {+ mockReadFile.mockImplementation(async (path: string) =>+ path.endsWith("index.md") ? "- transformer\n- 注意力" : "Transformer and 注意力 are related.",+ )+ mockListDirectory.mockResolvedValue([+ { path: "/p/wiki/注意力.md", name: "注意力.md", is_dir: false },+ ])+ mockStreamChatReturns(JSON.stringify({+ links: [+ { term: "Transformer", target: "transformer" },+ { term: "注意力", target: "注意力" },+ ],+ }))++ await enrichWithWikilinks("/p", "/p/wiki/f.md", fakeLlmConfig())++ expect(mockWriteFile).toHaveBeenCalledWith(+ "/p/wiki/f.md",+ "Transformer and [[注意力]] are related.",+ )+ })++ it("rewrites case-drifted targets to the reader-resolvable filename", async () => {+ mockReadFile.mockImplementation(async (path: string) =>+ path.endsWith("index.md") ? "- transformer" : "Transformer architecture.",+ )+ mockListDirectory.mockResolvedValue([+ { path: "/p/wiki/Transformer.md", name: "Transformer.md", is_dir: false },+ ])+ mockStreamChatReturns(JSON.stringify({+ links: [{ term: "Transformer", target: "transformer#overview" }],+ }))++ await enrichWithWikilinks("/p", "/p/wiki/f.md", fakeLlmConfig())++ expect(mockWriteFile).toHaveBeenCalledWith(+ "/p/wiki/f.md",+ "[[Transformer]] architecture.",+ )+ })+it("does NOT overwrite when LLM response is not parseable JSON", async () => {// The v2 implementation expects a JSON `{links:[...]}` object; anything// else produces zero substitutions and writeFile is never called.diff --git a/src/lib/enrich-wikilinks.ts b/src/lib/enrich-wikilinks.tsindex 5dec8464..c0ef999b 100644--- a/src/lib/enrich-wikilinks.ts+++ b/src/lib/enrich-wikilinks.ts@@ -1,4 +1,5 @@-import { readFile, writeFile } from "@/commands/fs"+import { listDirectory, readFile, writeFile } from "@/commands/fs"+import type { FileNode } from "@/types/wiki"import { streamChat } from "./llm-client"import { useWikiStore, type LlmConfig } from "@/stores/wiki-store"import { buildLanguageDirective } from "./output-language"@@ -29,9 +30,10 @@ export async function enrichWithWikilinks(): Promise<void> {const pp = normalizePath(projectPath)const fp = normalizePath(filePath)- const [content, index] = await Promise.all([+ const [content, index, wikiTree] = await Promise.all([readFile(fp),readFile(`${pp}/wiki/index.md`).catch(() => ""),+ listDirectory(`${pp}/wiki`).catch(() => []),])if (!content || !index) return@@ -88,7 +90,18 @@ export async function enrichWithWikilinks()// Parse the LLM response. Be tolerant of fences / prose wrappers.- const links = parseLinkResponse(raw)+ const pageSlugs = collectWikiPageSlugs(wikiTree)+ const parsedLinks = parseLinkResponse(raw)+ // The index is prompt context, not an authority boundary: models can still+ // invent or translate a target. Only write links that resolve to a page on+ // disk. If listing fails or yields no authoritative pages, skip this+ // optional enrichment pass rather than reintroducing broken links.+ const links = pageSlugs.size === 0+ ? []+ : parsedLinks.flatMap((link) => {+ const canonicalTarget = pageSlugs.get(normalizeTargetSlug(link.target))+ return canonicalTarget ? [{ ...link, target: canonicalTarget }] : []+ })if (links.length === 0) return // nothing to do// Apply substitutions to the ORIGINAL content. This guarantees the only@@ -105,6 +118,40 @@ interface LinkEntry {target: string}+function collectWikiPageSlugs(nodes: FileNode[]): Map<string, string> {+ const candidates = new Map<string, Set<string>>()+ const visit = (entries: FileNode[]) => {+ for (const node of entries) {+ if (node.is_dir) {+ visit(node.children ?? [])+ continue+ }+ const name = normalizePath(node.path).split("/").pop() ?? ""+ if (name.toLowerCase().endsWith(".md")) {+ const canonical = name.slice(0, -3)+ const key = normalizeTargetSlug(canonical)+ const values = candidates.get(key) ?? new Set<string>()+ values.add(canonical)+ candidates.set(key, values)+ }+ }+ }+ visit(nodes)+ const slugs = new Map<string, string>()+ for (const [key, values] of candidates) {+ // Case/Unicode-equivalent filenames can coexist on case-sensitive file+ // systems. Do not choose arbitrarily when the reader would be ambiguous.+ if (values.size === 1) slugs.set(key, [...values][0])+ }+ return slugs+}++function normalizeTargetSlug(target: string): string {+ const withoutAlias = target.split("|", 1)[0].split("#", 1)[0]+ const name = normalizePath(withoutAlias).split("/").pop() ?? ""+ return name.replace(/\.md$/i, "").normalize("NFKC").trim().toLowerCase()+}+function parseLinkResponse(raw: string): LinkEntry[] {if (!raw.trim()) return []// Extract the first balanced {...}diff --git a/src/lib/ingest-cache.ts b/src/lib/ingest-cache.tsindex 5e59cdf4..eaa82d7d 100644--- a/src/lib/ingest-cache.ts+++ b/src/lib/ingest-cache.ts@@ -124,3 +124,22 @@ export async function removeFromIngestCache(delete newEntries[sourceFileName]await saveCache(projectPath, { entries: newEntries })}++/** Move a cache entry when an unchanged source is renamed inside raw/sources. */+export async function moveIngestCacheEntry(+ projectPath: string,+ oldSourceIdentity: string,+ newSourceIdentity: string,+ movedFiles: ReadonlyMap<string, string> = new Map(),+): Promise<void> {+ const cache = await loadCache(projectPath)+ const entry = cache.entries[oldSourceIdentity]+ if (!entry || oldSourceIdentity === newSourceIdentity) return+ const migratedEntry: CacheEntry = {+ ...entry,+ filesWritten: entry.filesWritten.map((path) => movedFiles.get(path) ?? path),+ }+ const newEntries = { ...cache.entries, [newSourceIdentity]: migratedEntry }+ delete newEntries[oldSourceIdentity]+ await saveCache(projectPath, { entries: newEntries })+}diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.tsindex 0e15b268..5fb8aa13 100644--- a/src/lib/ingest-source-path-collision.test.ts+++ b/src/lib/ingest-source-path-collision.test.ts@@ -7,6 +7,7 @@ import { useChatStore } from "@/stores/chat-store"import { useReviewStore } from "@/stores/review-store"import { useWikiStore } from "@/stores/wiki-store"import { sourceSummarySlugFromIdentity } from "./source-identity"+import { migrateSourcePath } from "./source-lifecycle"vi.mock("@/commands/fs", () => realFs)@@ -16,6 +17,7 @@ let extraReviewResponse = ""let generationSuffix = ""let abortDuringReview: AbortController | null = nulllet interactiveGenerationOverride = ""+let mergeRequestCount = 0vi.mock("./llm-client", () => ({streamChat: vi.fn(async (_cfg, messages, cb) => {@@ -23,6 +25,7 @@ vi.mock("./llm-client", () => ({const userPrompt = String(messages?.[1]?.content ?? "")if (systemPrompt.startsWith("You are merging two versions")) {+ mergeRequestCount++const incoming = userPrompt.split("## Newly generated version")[1]?.split("---")[2]cb.onToken(incoming?.trim() || "---\ntitle: merged\n---\n\n# merged")cb.onDone()@@ -119,7 +122,12 @@ vi.mock("./mineru", () => ({parseWithMineruResult: vi.fn(),}))-import { autoIngest, executeIngestWrites, hasMineruImageRefs } from "./ingest"+import {+ autoIngest,+ buildFallbackSourceSummary,+ executeIngestWrites,+ hasMineruImageRefs,+} from "./ingest"import { streamChat } from "./llm-client"import { parseWithMineruResult } from "./mineru"@@ -136,6 +144,7 @@ describe("autoIngest source summary paths", () => {generationSuffix = ""abortDuringReview = nullinteractiveGenerationOverride = ""+ mergeRequestCount = 0mockStreamChat.mockClear()mockParseWithMineru.mockReset()tmp = await createTempProject("same-basename-sources")@@ -208,6 +217,13 @@ describe("autoIngest source summary paths", () => {)).toBe(false)})+ it("preserves complete analysis in a fallback source summary", () => {+ const analysis = `begin-${"x".repeat(5000)}-end`+ const content = buildFallbackSourceSummary("long.md", analysis, "2026-07-11")+ expect(content).toContain(analysis)+ expect(content).toContain("-end")+ })+it("keeps distinct source summaries for same-basename files in different source subdirectories", async () => {if (!tmp) throw new Error("missing temp project")sourceMarkers = ["project-a config", "project-b config"]@@ -241,6 +257,110 @@ describe("autoIngest source summary paths", () => {expect(allSummaries).toContain("project-b/config.yaml")})+ it("replaces stale content when a corrected source solely owns the page", async () => {+ if (!tmp) throw new Error("missing temp project")+ const sourcePath = `${tmp.path}/raw/sources/project-a/config.yaml`+ sourceMarkers = ["obsolete wording"]+ await autoIngest(tmp.path, sourcePath, useWikiStore.getState().llmConfig)++ await writeFileRaw(sourcePath, "name: corrected\n")+ sourceMarkers = ["corrected wording"]+ await autoIngest(tmp.path, sourcePath, useWikiStore.getState().llmConfig)++ const summaryPath = `${tmp.path}/wiki/sources/${sourceSummarySlugFromIdentity("project-a/config.yaml")}.md`+ const content = await fs.readFile(summaryPath, "utf8")+ expect(content).toContain("corrected wording")+ expect(content).not.toContain("obsolete wording")+ expect(mergeRequestCount).toBe(0)+ })++ it("moves the canonical source summary and its source reference", async () => {+ if (!tmp) throw new Error("missing temp project")+ sourceMarkers = ["movable summary"]+ const oldSource = `${tmp.path}/raw/sources/project-a/config.yaml`+ await autoIngest(tmp.path, oldSource, useWikiStore.getState().llmConfig)++ const oldIdentity = "project-a/config.yaml"+ const newIdentity = "archive/config.yaml"+ const oldSummary = `${tmp.path}/wiki/sources/${sourceSummarySlugFromIdentity(oldIdentity)}.md`+ const newSummary = `${tmp.path}/wiki/sources/${sourceSummarySlugFromIdentity(newIdentity)}.md`+ await migrateSourcePath(+ tmp.path,+ "raw/sources/project-a/config.yaml",+ "raw/sources/archive/config.yaml",+ )++ await expect(fs.access(oldSummary)).rejects.toThrow()+ const content = await fs.readFile(newSummary, "utf8")+ expect(content).toContain('sources: ["archive/config.yaml"]')+ })++ it("migrates source references for a case-only rename", async () => {+ if (!tmp) throw new Error("missing temp project")+ const pagePath = `${tmp.path}/wiki/entities/case.md`+ await writeFileRaw(pagePath, [+ "---",+ 'sources: ["project-a/config.yaml"]',+ "---",+ "# Case",+ ].join("\n"))++ await migrateSourcePath(+ tmp.path,+ "raw/sources/project-a/config.yaml",+ "raw/sources/Project-A/config.yaml",+ )++ expect(await fs.readFile(pagePath, "utf8")).toContain(+ 'sources: ["Project-A/config.yaml"]',+ )+ })++ it("migrates a unique legacy basename source reference", async () => {+ if (!tmp) throw new Error("missing temp project")+ // Remove the second same-basename source so the legacy shorthand is+ // unambiguous after the move.+ await fs.rm(`${tmp.path}/raw/sources/project-b/config.yaml`)+ const pagePath = `${tmp.path}/wiki/entities/legacy.md`+ await writeFileRaw(pagePath, [+ "---",+ 'sources: ["config.yaml"]',+ "---",+ "# Legacy",+ ].join("\n"))++ await migrateSourcePath(+ tmp.path,+ "raw/sources/project-a/config.yaml",+ "raw/sources/archive/config.yaml",+ )++ expect(await fs.readFile(pagePath, "utf8")).toContain(+ 'sources: ["archive/config.yaml"]',+ )+ })++ it("does not rewrite an ambiguous legacy basename source reference", async () => {+ if (!tmp) throw new Error("missing temp project")+ const pagePath = `${tmp.path}/wiki/entities/ambiguous.md`+ await writeFileRaw(pagePath, [+ "---",+ 'sources: ["config.yaml"]',+ "---",+ "# Ambiguous",+ ].join("\n"))++ await migrateSourcePath(+ tmp.path,+ "raw/sources/project-a/config.yaml",+ "raw/sources/archive/config.yaml",+ )++ expect(await fs.readFile(pagePath, "utf8")).toContain(+ 'sources: ["config.yaml"]',+ )+ })+it("migrates a safe legacy basename source summary to the canonical nested source path", async () => {if (!tmp) throw new Error("missing temp project")sourceMarkers = ["project-a config"]diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 85fab0ca..1a5c50a0 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -1230,22 +1230,7 @@ async function autoIngestImpl(// task for retry rather than "success".if (!hasSourceSummary && !signal?.aborted) {const date = new Date().toISOString().slice(0, 10)- const fallbackContent = [- "---",- `type: source`,- `title: "Source: ${sourceIdentity}"`,- `created: ${date}`,- `updated: ${date}`,- `sources: ["${sourceIdentity}"]`,- `tags: []`,- `related: []`,- "---",- "",- `# Source: ${sourceIdentity}`,- "",- analysis ? analysis.slice(0, 3000) : "(Analysis not available)",- "",- ].join("\n")+ const fallbackContent = buildFallbackSourceSummary(sourceIdentity, analysis, date)try {await writeFile(sourceSummaryFullPath, fallbackContent)writtenPaths.push(sourceSummaryPath)@@ -1739,6 +1724,32 @@ export function currentWikiDate(now: Date = new Date()): string {return `${year}-${month}-${day}`}+export function buildFallbackSourceSummary(+ sourceIdentity: string,+ analysis: string,+ date: string,+): string {+ return [+ "---",+ "type: source",+ `title: "Source: ${sourceIdentity}"`,+ `created: ${date}`,+ `updated: ${date}`,+ `sources: ["${sourceIdentity}"]`,+ "tags: []",+ "related: []",+ "---",+ "",+ `# Source: ${sourceIdentity}`,+ "",+ // This is a recovery page, so preserving the complete analysis matters+ // more than keeping the page short. Truncating here used to create+ // syntactically valid but silently incomplete source summaries.+ analysis || "(Analysis not available)",+ "",+ ].join("\n")+}+export function stampGeneratedFrontmatterDates(content: string, date: string): string {const fmRe = /^(---\s*\r?\n)([\s\S]*?)(\r?\n---\s*(?:\r?\n|$))/const match = content.match(fmRe)@@ -1907,6 +1918,13 @@ async function writeFileBlocks(// body + array-field union" with a best-effort backup.// See page-merge.ts.const existing = await tryReadFile(fullPath)+ // Re-ingesting a corrected source must replace pages owned solely by+ // that source. Merging the old body back into the new generation kept+ // retracted wording alive indefinitely. Multi-source pages still use+ // the merger because their other sources' contributions must survive.+ const replaceExistingBody = Boolean(+ existing && isOwnedOnlyBySource(existing, sourceFileName),+ )const merged = await mergePageContent(content,existing || null,@@ -1916,6 +1934,7 @@ async function writeFileBlocks(pagePath: relativePath,signal,backup: (oldContent) => backupExistingPage(projectPath, relativePath, oldContent),+ replaceExistingBody,},)// The merge unions existing frontmatter arrays, so sanitize again to@@ -1936,6 +1955,15 @@ async function writeFileBlocks(return { writtenPaths, warnings, hardFailures }}+function isOwnedOnlyBySource(content: string, sourceIdentity: string): boolean {+ const sources = parseSources(content)+ if (sources.length === 0) return false+ const expected = sourceReferenceIdentity(sourceIdentity).toLowerCase()+ return sources.every(+ (source) => sourceReferenceIdentity(source).toLowerCase() === expected,+ )+}+const REVIEW_BLOCK_REGEX = /---REVIEW:\s*(\w[\w-]*)\s*\|\s*(.+?)\s*---\n([\s\S]*?)---END REVIEW---/gfunction parseReviewBlocks(diff --git a/src/lib/page-merge.test.ts b/src/lib/page-merge.test.tsindex 478a321d..02bce00d 100644--- a/src/lib/page-merge.test.ts+++ b/src/lib/page-merge.test.ts@@ -64,6 +64,58 @@ describe("mergePageContent — fast paths", () => {})})+describe("mergePageContent — corrected single-source replacement", () => {+ it("replaces only the body while preserving metadata, arrays, and backup", async () => {+ const existing = PAGE(+ 'type: entity\ntitle: Stable title\ncreated: 2025-01-01\nupdated: 2025-01-02\nsources: ["doc.pdf"]\ntags: [manual]\nrelated: [kept-link]',+ "obsolete source wording plus a manual-era body",+ )+ const incoming = PAGE(+ 'type: concept\ntitle: Changed title\ncreated: 2026-01-01\nsources: ["doc.pdf"]\ntags: [generated]\nrelated: [new-link]',+ "corrected source wording",+ )+ const merger = vi.fn()+ const backup = vi.fn().mockResolvedValue(undefined)++ const out = await mergePageContent(incoming, existing, merger, {+ ...baseOpts,+ replaceExistingBody: true,+ backup,+ })++ expect(out).toContain("corrected source wording")+ expect(out).not.toContain("obsolete source wording")+ expect(out).toContain("type: entity")+ expect(out).toContain("title: Stable title")+ expect(out).toContain("created: 2025-01-01")+ expect(out).toContain("updated: 2026-04-30")+ expect(out).toMatch(/tags:\s*\[\s*"manual",\s*"generated"\s*\]/)+ expect(out).toMatch(/related:\s*\[\s*"kept-link",\s*"new-link"\s*\]/)+ expect(backup).toHaveBeenCalledWith(existing)+ expect(merger).not.toHaveBeenCalled()+ })++ it("keeps normal merge behavior for a page with another source", async () => {+ const existing = PAGE(+ 'type: entity\ntitle: Shared\nsources: ["doc.pdf", "other.pdf"]',+ "other source contribution",+ )+ const incoming = PAGE(+ 'type: entity\ntitle: Shared\nsources: ["doc.pdf"]',+ "corrected doc contribution",+ )+ const merger = vi.fn().mockResolvedValue(PAGE(+ 'type: entity\ntitle: Shared\nsources: ["doc.pdf", "other.pdf"]',+ "other source contribution and corrected doc contribution retained together",+ ))++ const out = await mergePageContent(incoming, existing, merger, baseOpts)+ expect(merger).toHaveBeenCalledOnce()+ expect(out).toContain("other source contribution")+ expect(out).toContain("corrected doc contribution")+ })+})+// ──────────────────────────────────────────────────────────────────// LLM merge happy path// ──────────────────────────────────────────────────────────────────diff --git a/src/lib/page-merge.ts b/src/lib/page-merge.tsindex 05448b82..aabc4898 100644--- a/src/lib/page-merge.ts+++ b/src/lib/page-merge.ts@@ -84,6 +84,11 @@ export interface MergePageOptions {/** Date provider for the `updated` field. Injectable for* deterministic tests. Defaults to today's UTC date. */today?: () => string+ /**+ * Replace the old body after a corrected source is regenerated, while+ * retaining union fields, locked metadata, and a recovery backup.+ */+ replaceExistingBody?: boolean}export async function mergePageContent(@@ -111,6 +116,21 @@ export async function mergePageContent(// skip the LLM.const oldParsed = parseFrontmatter(existingContent)const arrayMergedParsed = parseFrontmatter(arrayMerged)+ if (opts.replaceExistingBody) {+ await tryBackup(opts, existingContent)+ let replacement = arrayMerged+ for (const field of LOCKED_FIELDS) {+ const existingValue = oldParsed.frontmatter?.[field]+ if (typeof existingValue === "string" && existingValue !== "") {+ replacement = setFrontmatterScalar(replacement, field, existingValue)+ }+ }+ return setFrontmatterScalar(+ replacement,+ "updated",+ (opts.today ?? defaultToday)(),+ )+ }if (oldParsed.body.trim() === arrayMergedParsed.body.trim()) {return arrayMerged}diff --git a/src/lib/project-file-sync.test.ts b/src/lib/project-file-sync.test.tsindex 3453e7a5..2daf4536 100644--- a/src/lib/project-file-sync.test.ts+++ b/src/lib/project-file-sync.test.ts@@ -79,11 +79,13 @@ const mocks = vi.hoisted(() => {}>),readFile: vi.fn(async (_path?: string) => ""),getFileSize: vi.fn(async (_path?: string) => 1024),+ fileExists: vi.fn(async (_path?: string) => false),writeFile: vi.fn(async () => undefined),deleteFile: vi.fn(async () => undefined),findRelatedWikiPages: vi.fn(async () => []),enqueueBatch: vi.fn(async () => []),removeFromIngestCache: vi.fn(async () => undefined),+ moveIngestCacheEntry: vi.fn(async () => undefined),removePageEmbedding: vi.fn(async () => undefined),cascadeDeleteWikiPagesWithRefs: vi.fn(async () => ({deletedPaths: [] as string[],@@ -106,6 +108,7 @@ vi.mock("@/commands/fs", () => ({listDirectory: mocks.listDirectory,readFile: mocks.readFile,getFileSize: mocks.getFileSize,+ fileExists: mocks.fileExists,writeFile: mocks.writeFile,deleteFile: mocks.deleteFile,findRelatedWikiPages: mocks.findRelatedWikiPages,@@ -117,6 +120,7 @@ vi.mock("@/lib/ingest-queue", () => ({vi.mock("@/lib/ingest-cache", () => ({removeFromIngestCache: mocks.removeFromIngestCache,+ moveIngestCacheEntry: mocks.moveIngestCacheEntry,}))vi.mock("@/lib/embedding", () => ({@@ -145,11 +149,13 @@ describe("project file sync", () => {mocks.listDirectory.mockImplementation(async (_path?: string) => [])mocks.readFile.mockImplementation(async (_path?: string) => "")mocks.getFileSize.mockImplementation(async (_path?: string) => 1024)+ mocks.fileExists.mockImplementation(async (_path?: string) => false)mocks.writeFile.mockImplementation(async () => undefined)mocks.deleteFile.mockImplementation(async () => undefined)mocks.findRelatedWikiPages.mockImplementation(async () => [])mocks.enqueueBatch.mockImplementation(async () => [])mocks.removeFromIngestCache.mockImplementation(async () => undefined)+ mocks.moveIngestCacheEntry.mockImplementation(async () => undefined)mocks.removePageEmbedding.mockImplementation(async () => undefined)mocks.cascadeDeleteWikiPagesWithRefs.mockImplementation(async () => ({deletedPaths: [] as string[],@@ -250,6 +256,116 @@ describe("project file sync", () => {])})+ it("migrates an unchanged source move without deleting or re-ingesting it", 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.mockResolvedValue([+ { name: "topic.md", path: "/tmp/a/wiki/topic.md", is_dir: false },+ ])+ mocks.readFile.mockResolvedValue("---\nsources: [old/report.md]\n---\n# Topic")+ void startProjectFileSync(project)+ await vi.waitFor(() => expect(mocks.listen).toHaveBeenCalledTimes(2))++ mocks.emit("file-sync://changed", {+ projectId: "A",+ tasks: [+ { id: "d", projectId: "A", path: "raw/sources/old/report.md", kind: "deleted", status: "done", hashBefore: "same", size: 100, createdAt: 1, updatedAt: 1, retryCount: 0, needsRerun: false },+ { id: "c", projectId: "A", path: "raw/sources/new/report.md", kind: "created", status: "done", hashAfter: "same", size: 100, createdAt: 1, updatedAt: 1, retryCount: 0, needsRerun: false },+ ],+ })+ await vi.advanceTimersByTimeAsync(300)++ expect(mocks.writeFile).toHaveBeenCalledWith(+ "/tmp/a/wiki/topic.md",+ expect.stringContaining('sources: ["new/report.md"]'),+ )+ expect(mocks.moveIngestCacheEntry).toHaveBeenCalledWith(+ "/tmp/a",+ "old/report.md",+ "new/report.md",+ expect.any(Map),+ )+ expect(mocks.enqueueBatch).not.toHaveBeenCalled()+ expect(mocks.deleteFile).not.toHaveBeenCalled()+ })++ it("does not infer a move when either hash side is ambiguous", 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))++ const base = { projectId: "A", status: "done", size: 100, createdAt: 1, updatedAt: 1, retryCount: 0, needsRerun: false } as const+ mocks.emit("file-sync://changed", {+ projectId: "A",+ tasks: [+ { ...base, id: "d1", path: "raw/sources/a.md", kind: "deleted", hashBefore: "same" },+ { ...base, id: "d2", path: "raw/sources/b.md", kind: "deleted", hashBefore: "same" },+ { ...base, id: "c", path: "raw/sources/c.md", kind: "created", hashAfter: "same" },+ ],+ })+ await vi.advanceTimersByTimeAsync(300)++ expect(mocks.moveIngestCacheEntry).not.toHaveBeenCalled()+ expect(mocks.enqueueBatch).toHaveBeenCalledWith("A", [+ { sourcePath: "raw/sources/c.md", folderContext: "" },+ ])+ })++ it("does not infer moves for tiny identical files", 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))+ const base = { projectId: "A", status: "done", size: 0, createdAt: 1, updatedAt: 1, retryCount: 0, needsRerun: false } as const+ mocks.emit("file-sync://changed", {+ projectId: "A",+ tasks: [+ { ...base, id: "d", path: "raw/sources/empty-a.md", kind: "deleted", hashBefore: "empty" },+ { ...base, id: "c", path: "raw/sources/empty-b.md", kind: "created", hashAfter: "empty" },+ ],+ })+ await vi.advanceTimersByTimeAsync(300)+ expect(mocks.moveIngestCacheEntry).not.toHaveBeenCalled()+ })++ it("consumes a proven move even when one wiki reference cannot be rewritten", 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.mockResolvedValue([+ { name: "locked.md", path: "/tmp/a/wiki/locked.md", is_dir: false },+ ])+ mocks.readFile.mockResolvedValue("---\nsources: [old.md]\n---\n# Locked")+ mocks.writeFile.mockRejectedValueOnce(new Error("permission denied"))+ void startProjectFileSync(project)+ await vi.waitFor(() => expect(mocks.listen).toHaveBeenCalledTimes(2))+ const base = { projectId: "A", status: "done", size: 100, createdAt: 1, updatedAt: 1, retryCount: 0, needsRerun: false } as const+ mocks.emit("file-sync://changed", {+ projectId: "A",+ tasks: [+ { ...base, id: "d", path: "raw/sources/old.md", kind: "deleted", hashBefore: "same" },+ { ...base, id: "c", path: "raw/sources/new.md", kind: "created", hashAfter: "same" },+ ],+ })+ await vi.advanceTimersByTimeAsync(300)++ expect(mocks.moveIngestCacheEntry).not.toHaveBeenCalled()+ expect(mocks.enqueueBatch).not.toHaveBeenCalled()+ expect(mocks.deleteFile).not.toHaveBeenCalled()+ })+it("does not ingest preprocessed cache files from raw/sources/.cache", async () => {vi.useFakeTimers()const { startProjectFileSync } = await import("@/lib/project-file-sync")diff --git a/src/lib/project-file-sync.ts b/src/lib/project-file-sync.tsindex f0710532..c04635fd 100644--- a/src/lib/project-file-sync.ts+++ b/src/lib/project-file-sync.ts@@ -17,6 +17,7 @@ import {deleteSourceFiles,enqueueSourceIngest,isIngestableSourcePath,+ migrateSourcePath,} from "@/lib/source-lifecycle"import { isPathAllowedBySourceWatch, normalizeSourceWatchConfig } from "@/lib/source-watch-config"import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"@@ -177,11 +178,58 @@ async function processFileChangeBatch(if (handledChangeTaskKeys.size > 4096) {handledChangeTaskKeys = new Set([...handledChangeTaskKeys].slice(-2048))}- await cleanupDeletedFiles(project, tasks)- await enqueueRawSourceChanges(project, tasks)+ const movedTaskIds = await migrateUnchangedSourceMoves(project, tasks)+ const remainingTasks = tasks.filter((task) => !movedTaskIds.has(task.id))+ await cleanupDeletedFiles(project, remainingTasks)+ await enqueueRawSourceChanges(project, remainingTasks)await refreshAfterFileChanges(project, paths)}+async function migrateUnchangedSourceMoves(+ project: WikiProject,+ tasks: FileChangeTask[],+): Promise<Set<string>> {+ const moved = new Set<string>()+ const createdByHash = new Map<string, FileChangeTask[]>()+ const deletedByHash = new Map<string, FileChangeTask[]>()+ for (const task of tasks) {+ if (!isRawSourcePathForCascade(task.path)) continue+ if (task.kind === "created" && task.hashAfter && (task.size ?? 0) >= 32) {+ const matches = createdByHash.get(task.hashAfter) ?? []+ matches.push(task)+ createdByHash.set(task.hashAfter, matches)+ } else if (task.kind === "deleted" && task.hashBefore && (task.size ?? 0) >= 32) {+ const matches = deletedByHash.get(task.hashBefore) ?? []+ matches.push(task)+ deletedByHash.set(task.hashBefore, matches)+ }+ }++ for (const [hash, deletedMatches] of deletedByHash) {+ const createdMatches = createdByHash.get(hash)+ // Content identity only proves a move when both sides are unique.+ if (deletedMatches.length !== 1 || createdMatches?.length !== 1) continue+ const deleted = deletedMatches[0]+ const created = createdMatches[0]+ try {+ await migrateSourcePath(project.path, deleted.path, created.path)+ moved.add(deleted.id)+ moved.add(created.id)+ } catch (err) {+ console.error("[file-sync] failed to migrate unchanged source move:", err)+ // The hash pair still proves this is a move. Suppress destructive+ // delete/create fallback after a transactional migration rollback;+ // surface the failure so the user can retry with a manual rescan.+ moved.add(deleted.id)+ moved.add(created.id)+ useFileSyncStore.getState().setLastError(+ `Failed to migrate moved source metadata: ${err instanceof Error ? err.message : String(err)}`,+ )+ }+ }+ return moved+}+async function refreshAfterFileChanges(project: WikiProject, relativePaths: string[]): Promise<void> {const pp = normalizePath(project.path)const store = useWikiStore.getState()diff --git a/src/lib/source-lifecycle.ts b/src/lib/source-lifecycle.tsindex 55e1ceab..243bd4ca 100644--- a/src/lib/source-lifecycle.ts+++ b/src/lib/source-lifecycle.ts@@ -17,6 +17,7 @@ import { getFileName, getFileStem, getRelativePath, normalizePath } from "@/lib/import {sourceIdentityForPath,sourceReferenceIdentity,+ sourceSummarySlugFromIdentity,} from "@/lib/source-identity"import {parseFrontmatterArray,@@ -24,7 +25,7 @@ import {writeFrontmatterArray,writeSources,} from "@/lib/sources-merge"-import { removeFromIngestCache } from "@/lib/ingest-cache"+import { moveIngestCacheEntry, removeFromIngestCache } from "@/lib/ingest-cache"import { removePageEmbedding } from "@/lib/embedding"import {buildDeletedKeys,@@ -110,6 +111,104 @@ export interface DeleteSourcesResult {skippedPages: number}+/**+ * Preserve source ownership when a watcher proves that a delete/create pair+ * is an unchanged file move. The caller must establish content identity from+ * watcher hashes; this function intentionally does not infer moves by name.+ */+export async function migrateSourcePath(+ projectPath: string,+ oldSourcePath: string,+ newSourcePath: string,+): Promise<number> {+ const pp = normalizePath(projectPath)+ const oldIdentity = sourceIdentityForPath(pp, oldSourcePath)+ const newIdentity = sourceIdentityForPath(pp, newSourcePath)+ // Cache keys preserve spelling, so case-only renames still require a+ // migration even on case-insensitive filesystems.+ if (oldIdentity === newIdentity) return 0++ const allMd = flattenMd(await listDirectory(`${pp}/wiki`))+ const oldBaseName = getFileName(oldIdentity).toLowerCase()+ const rawSourceFiles = flattenFiles(await listDirectory(`${pp}/raw/sources`, true))+ const matchingBasenames = rawSourceFiles.filter(+ (file) => getFileName(file.path).toLowerCase() === oldBaseName,+ )+ // Legacy pages sometimes stored only `config.yaml` for a nested source.+ // Rewrite that shorthand only when the live source basename is unique.+ const canMigrateLegacyBasename = oldIdentity.includes("/") && matchingBasenames.length === 1+ const writes: Array<{ path: string; original: string; migrated: string }> = []+ for (const file of allMd) {+ const content = await readFile(file.path)+ if (!content) continue+ const sources = parseSources(content)+ let changed = false+ const migrated = sources.map((source) => {+ const normalizedSource = sourceReferenceIdentity(source)+ const matchesIdentity = normalizedSource.toLowerCase() === oldIdentity.toLowerCase()+ const matchesUniqueLegacyBasename = canMigrateLegacyBasename &&+ !normalizedSource.includes("/") &&+ normalizedSource.toLowerCase() === oldBaseName+ if (!matchesIdentity && !matchesUniqueLegacyBasename) {+ return source+ }+ changed = true+ return newIdentity+ })+ if (!changed) continue+ writes.push({+ path: file.path,+ original: content,+ migrated: writeSources(content, Array.from(new Set(migrated))),+ })+ }++ const oldSummaryRel = `wiki/sources/${sourceSummarySlugFromIdentity(oldIdentity)}.md`+ const newSummaryRel = `wiki/sources/${sourceSummarySlugFromIdentity(newIdentity)}.md`+ const oldSummaryPath = `${pp}/${oldSummaryRel}`+ const newSummaryPath = `${pp}/${newSummaryRel}`+ const summaryMoves = new Map<string, string>()+ const shouldMoveSummary = oldSummaryRel !== newSummaryRel && await fileExists(oldSummaryPath)+ if (shouldMoveSummary && await fileExists(newSummaryPath)) {+ throw new Error(`Cannot migrate source summary because destination exists: ${newSummaryRel}`)+ }++ const completedWrites: typeof writes = []+ let newSummaryCreated = false+ try {+ for (const write of writes) {+ await writeFile(write.path, write.migrated)+ completedWrites.push(write)+ }+ if (shouldMoveSummary) {+ const migratedSummary = writes.find((write) => write.path === oldSummaryPath)?.migrated+ ?? await readFile(oldSummaryPath)+ await writeFile(newSummaryPath, migratedSummary)+ newSummaryCreated = true+ await deleteFile(oldSummaryPath)+ summaryMoves.set(oldSummaryRel, newSummaryRel)+ }+ await moveIngestCacheEntry(pp, oldIdentity, newIdentity, summaryMoves)+ return writes.length+ } catch (err) {+ if (newSummaryCreated) {+ try {+ await deleteFile(newSummaryPath)+ } catch {+ // Best-effort rollback; preserve the original error.+ }+ }+ for (const write of completedWrites.reverse()) {+ try {+ await writeFile(write.path, write.original)+ } catch {+ // Best-effort rollback; preserve the original error.+ }+ }+ throw err+ }+}+export function isIngestableSourcePath(path: string): boolean {const normalized = normalizePath(path)if (normalized.split("/").includes(".cache")) return falsediff --git a/src/test-helpers/scenarios/enrich-scenarios.ts b/src/test-helpers/scenarios/enrich-scenarios.tsindex 2574097d..e0bcdd56 100644--- a/src/test-helpers/scenarios/enrich-scenarios.ts+++ b/src/test-helpers/scenarios/enrich-scenarios.ts@@ -27,6 +27,8 @@ export const enrichScenarios: EnrichScenario[] = ["occurrence of each.",initialWiki: {"wiki/index.md": WIKI_INDEX_WITH_TRANSFORMER,+ "wiki/attention.md": "# Attention\n",+ "wiki/transformer.md": "# Transformer\n","wiki/survey.md":"# Deep Learning Survey\n\n" +"Modern NLP relies on Transformer architectures for most tasks. " +@@ -61,6 +63,7 @@ export const enrichScenarios: EnrichScenario[] = ["LLM just returns the term→target list.",initialWiki: {"wiki/index.md": WIKI_INDEX_WITH_TRANSFORMER,+ "wiki/encoder.md": "# Encoder\n","wiki/attention.md":"---\n" +"title: Attention\n" +@@ -117,6 +120,8 @@ export const enrichScenarios: EnrichScenario[] = ["Byte-accurate substitution through UTF-8.",initialWiki: {"wiki/index.md": "# 索引\n\n- [[注意力机制]]\n- [[transformer]]\n",+ "wiki/注意力机制.md": "# 注意力机制\n",+ "wiki/transformer.md": "# Transformer\n","wiki/intro.md":"# 简介\n\n" +"注意力机制是 transformer 架构的核心组件之一。" +