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

release: v0.6.2 reliability fixes

nash_su3796aa6bce76
diff --git a/README.md b/README.md
index e07bea17..2cde8154 100644
--- a/README.md
+++ b/README.md
@@ -450,7 +450,7 @@ For MCP-compatible clients, LLM Wiki also includes a local MCP server in `mcp-se
A ready-made **agent skill** for LLM Wiki lives in its own repo. Install it into Claude Code / Codex / any skills-compatible runtime:
```bash
-npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm_wiki_skill
+npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm-wiki
```
After install, the agent can answer prompts like "what does my LLM Wiki say about X", "search my 知识库 for Y", "show the neighborhood of node Z in my wiki graph", and "rescan my wiki sources" by talking to your locally-running app — read-only by default, citing wiki page paths so you can verify in-app.
diff --git a/README_CN.md b/README_CN.md
index 9c433b05..82c3975e 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -447,7 +447,7 @@ LLM Wiki 内置一个本地 HTTP API(监听 `http://127.0.0.1:19828`,Token
LLM Wiki 配套的 **agent skill** 单独维护在另一个仓库。把它装进 Claude Code / Codex / 任意兼容 skills 的 runtime:
```bash
-npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm_wiki_skill
+npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm-wiki
```
安装完成后,Agent 就能响应 "我的 LLM Wiki 里关于 X 是怎么说的"、"在我的知识库里搜 Y"、"展示我 wiki 图谱里 Z 的邻居"、"重新索引我的资料源" 等请求——直接调用本机运行的 App,默认只读,引用 wiki 页面路径方便你在 App 内核对。
diff --git a/README_JA.md b/README_JA.md
index 75285bb0..8375b86a 100644
--- a/README_JA.md
+++ b/README_JA.md
@@ -456,7 +456,7 @@ MCP 互換クライアント向けに、LLM Wiki には `mcp-server/` も同梱
LLM Wiki 用の **agent skill** は別リポジトリで管理されています。Claude Code / Codex / skills 互換のランタイムにインストールできます。
```bash
-npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm_wiki_skill
+npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm-wiki
```
インストール後、エージェントは「自分の LLM Wiki に X について何が書かれている?」「自分の知識ベースで Y を検索して」「自分の Wiki グラフで Z の近傍を表示して」「ソースを再スキャンして」といった依頼に対し、ローカルで動いているアプリと直接通信して応答します。デフォルトは読み取り専用で、アプリ内で確認できるよう Wiki ページのパスを引用します。
diff --git a/README_KO.md b/README_KO.md
index d914804b..ed778a94 100644
--- a/README_KO.md
+++ b/README_KO.md
@@ -456,7 +456,7 @@ MCP 호환 클라이언트를 위해 LLM Wiki는 `mcp-server/`도 함께 제공
LLM Wiki용 **agent skill**은 별도 repo에 있습니다. Claude Code / Codex / skills 호환 runtime에 설치할 수 있습니다.
```bash
-npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm_wiki_skill
+npx skills add https://github.com/nashsu/llm_wiki_skill.git --skill llm-wiki
```
설치 후 에이전트는 "내 LLM Wiki는 X에 대해 뭐라고 말해?", "내 지식 베이스에서 Y를 검색해", "내 Wiki graph에서 Z의 이웃을 보여줘", "내 Wiki sources를 다시 스캔해" 같은 프롬프트에 답할 수 있습니다. 로컬에서 실행 중인 앱과 직접 통신하며, 기본값은 read-only이고 앱에서 검증할 수 있도록 Wiki 페이지 경로를 인용합니다.
diff --git a/package-lock.json b/package-lock.json
index 5f5e79da..fd9ee6d2 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "llm-wiki",
- "version": "0.6.1",
+ "version": "0.6.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "llm-wiki",
- "version": "0.6.1",
+ "version": "0.6.2",
"dependencies": {
"@base-ui/react": "^1.3.0",
"@fontsource-variable/geist": "^5.2.8",
diff --git a/package.json b/package.json
index 0332f336..5b3e92e8 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
"name": "llm-wiki",
"private": true,
- "version": "0.6.1",
+ "version": "0.6.2",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index bf3ce046..7b11d692 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -4461,7 +4461,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"
[[package]]
name = "llm-wiki"
-version = "0.6.1"
+version = "0.6.2"
dependencies = [
"arrow-array",
"arrow-schema",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index d91c1cfd..69e55305 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "llm-wiki"
-version = "0.6.1"
+version = "0.6.2"
description = "LLM Wiki - A personal knowledge base for LLM concepts"
authors = []
edition = "2021"
diff --git a/src-tauri/src/commands/claude_cli.rs b/src-tauri/src/commands/claude_cli.rs
index aca743e8..f11d8d61 100644
--- a/src-tauri/src/commands/claude_cli.rs
+++ b/src-tauri/src/commands/claude_cli.rs
@@ -28,7 +28,7 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
-use super::cli_resolver::find_cli_command;
+use super::cli_resolver::{child_path_env, find_cli_command};
const ISOLATED_MCP_CONFIG: &str = "{\"mcpServers\":{}}";
@@ -189,6 +189,11 @@ pub async fn claude_cli_detect() -> Result<DetectResult, String> {
let mut cmd = Command::new(&path);
suppress_windows_console(&mut cmd);
+ // npm-installed Claude is a Node shim. Desktop apps do not inherit the
+ // user's login-shell PATH, so detection and execution must both supply it.
+ if let Some(path_env) = child_path_env().await {
+ cmd.env("PATH", path_env);
+ }
let output = tokio::time::timeout(Duration::from_secs(3), cmd.arg("--version").output()).await;
match output {
@@ -292,6 +297,9 @@ pub async fn claude_cli_spawn(
let claude = find_claude_command().await?;
let mut cmd = Command::new(&claude);
suppress_windows_console(&mut cmd);
+ if let Some(path_env) = child_path_env().await {
+ cmd.env("PATH", path_env);
+ }
cmd.args(build_claude_cli_args(&model, isolate_local_config));
cmd.current_dir(&working_directory);
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index d1d89d7c..d2052a75 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.1",
+ "version": "0.6.2",
"identifier": "com.llmwiki.app",
"build": {
"beforeDevCommand": "npm run dev",
diff --git a/src/components/graph/graph-view.tsx b/src/components/graph/graph-view.tsx
index b5ea09f5..9158a7d9 100644
--- a/src/components/graph/graph-view.tsx
+++ b/src/components/graph/graph-view.tsx
@@ -963,8 +963,8 @@ export function GraphView() {
return (
<div className="relative flex h-full flex-col">
{/* Header */}
- <div className="flex items-center justify-between border-b px-4 py-2 shrink-0">
- <div className="flex items-center gap-3">
+ <div className="flex flex-wrap items-center justify-between gap-2 border-b px-4 py-2 shrink-0">
+ <div className="flex min-w-0 flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
<Network className="h-4 w-4 text-muted-foreground" />
<span className="text-sm font-medium">{t("graph.knowledgeGraph")}</span>
@@ -979,9 +979,9 @@ export function GraphView() {
)}
</div>
</div>
- <div className="flex items-center gap-1">
+ <div className="flex min-w-0 flex-wrap items-center justify-end gap-1">
{graphSearchOpen || searchActive ? (
- <div className="relative mr-1 w-52">
+ <div className="relative mr-1 w-52 max-w-full">
<Search className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
<input
ref={graphSearchInputRef}
diff --git a/src/components/settings/sections/embedding-section.tsx b/src/components/settings/sections/embedding-section.tsx
index 8672e8fd..c9a15499 100644
--- a/src/components/settings/sections/embedding-section.tsx
+++ b/src/components/settings/sections/embedding-section.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useState } from "react"
+import { useCallback, useEffect, useState, useSyncExternalStore } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
@@ -10,7 +10,9 @@ import {
embedAllPages,
getEmbeddingCount,
getLastEmbeddingError,
+ getEmbeddingReindexState,
legacyVectorRowCount,
+ subscribeEmbeddingReindexState,
} from "@/lib/embedding"
import { testEmbeddingConnection, testEmbeddingFunction, type ProviderTestResult } from "@/lib/connection-tests"
import type { SettingsDraft, DraftSetter } from "../settings-types"
@@ -20,12 +22,6 @@ interface Props {
setDraft: DraftSetter
}
-type ReindexState =
- | { kind: "idle" }
- | { kind: "running"; done: number; total: number }
- | { kind: "done"; count: number }
- | { kind: "error"; message: string }
-
type TestState =
| { kind: "idle" }
| { kind: "running"; label: string }
@@ -89,7 +85,15 @@ export function EmbeddingSection({ draft, setDraft }: Props) {
const [chunkCount, setChunkCount] = useState<number | null>(null)
const [legacyCount, setLegacyCount] = useState<number>(0)
const [lastError, setLastError] = useState<string | null>(null)
- const [reindex, setReindex] = useState<ReindexState>({ kind: "idle" })
+ const sharedReindex = useSyncExternalStore(
+ subscribeEmbeddingReindexState,
+ getEmbeddingReindexState,
+ )
+ const reindex = "projectPath" in sharedReindex
+ && project
+ && sharedReindex.projectPath === project.path.replace(/\\/g, "/")
+ ? sharedReindex
+ : { kind: "idle" as const }
const [testState, setTestState] = useState<TestState>({ kind: "idle" })
const [legacyDropped, setLegacyDropped] = useState(false)
const [headersText, setHeadersText] = useState<string>(() => headersToText(draft.embeddingExtraHeaders ?? {}))
@@ -115,21 +119,15 @@ export function EmbeddingSection({ draft, setDraft }: Props) {
const handleReindex = useCallback(async () => {
if (!project) return
- setReindex({ kind: "running", done: 0, total: 0 })
try {
- const count = await embedAllPages(
+ await embedAllPages(
project.path,
embeddingConfig,
- (done, total) => {
- setReindex({ kind: "running", done, total })
- },
+ undefined,
{ clearExisting: true },
)
- setReindex({ kind: "done", count })
await refreshStats()
} catch (err) {
- const message = err instanceof Error ? err.message : String(err)
- setReindex({ kind: "error", message })
await refreshStats()
}
}, [project, embeddingConfig, refreshStats])
diff --git a/src/lib/embedding.test.ts b/src/lib/embedding.test.ts
index 3072e61c..9544eac1 100644
--- a/src/lib/embedding.test.ts
+++ b/src/lib/embedding.test.ts
@@ -1631,7 +1631,7 @@ describe("embedAllPages", () => {
warn.mockRestore()
})
- it("does not clear existing chunks when forced rebuild cannot embed every page", async () => {
+ it("updates successful pages without clearing existing chunks when some pages fail", async () => {
listDirectoryMock.mockResolvedValueOnce([
{ name: "a.md", path: "/proj/wiki/a.md", is_dir: false },
{ name: "b.md", path: "/proj/wiki/b.md", is_dir: false },
@@ -1653,10 +1653,11 @@ describe("embedAllPages", () => {
message = err instanceof Error ? err.message : String(err)
}
expect(message).toContain("1 of 2 pages could not be embedded")
+ expect(message).toContain("1 successful page(s) were updated")
expect(message).not.toContain("Re-index failed: Re-index failed")
expect(mockInvoke.mock.calls.map((call) => call[0])).not.toContain("vector_clear_chunks")
- expect(mockInvoke.mock.calls.map((call) => call[0])).not.toContain("vector_upsert_chunks")
+ expect(mockInvoke.mock.calls.map((call) => call[0])).toContain("vector_upsert_chunks")
expect(mockInvoke.mock.calls.map((call) => call[0])).not.toContain("vector_drop_legacy")
})
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
index d90f220a..f1dc384c 100644
--- a/src/lib/embedding.ts
+++ b/src/lib/embedding.ts
@@ -352,6 +352,57 @@ export async function embedPage(
return true
}
+export type EmbeddingReindexState =
+ | { kind: "idle" }
+ | { kind: "running"; projectPath: string; done: number; total: number }
+ | { kind: "done"; projectPath: string; count: number }
+ | { kind: "error"; projectPath: string; message: string }
+
+let embeddingReindexState: EmbeddingReindexState = { kind: "idle" }
+const embeddingReindexListeners = new Set<() => void>()
+
+export function getEmbeddingReindexState(): EmbeddingReindexState {
+ return embeddingReindexState
+}
+
+export function subscribeEmbeddingReindexState(listener: () => void): () => void {
+ embeddingReindexListeners.add(listener)
+ return () => embeddingReindexListeners.delete(listener)
+}
+
+function setEmbeddingReindexState(state: EmbeddingReindexState): void {
+ embeddingReindexState = state
+ for (const listener of embeddingReindexListeners) listener()
+}
+
+function throwEmbeddingReindexError(projectPath: string, message: string): never {
+ setEmbeddingReindexState({ kind: "error", projectPath, message })
+ throw new Error(message)
+}
+
+async function preparePageEmbeddingRowsWithRetry(
+ pageId: string,
+ title: string,
+ content: string,
+ cfg: EmbeddingConfig,
+ attempts = 3,
+): Promise<PageEmbeddingPreparation> {
+ let best = await preparePageEmbeddingRows(pageId, title, content, cfg)
+ for (let attempt = 1; attempt < attempts; attempt += 1) {
+ if (best.status === "empty") return best
+ if (best.status === "ready" && best.page.failedChunks === 0) return best
+ await new Promise((resolve) => setTimeout(resolve, attempt * 250))
+ const candidate = await preparePageEmbeddingRows(pageId, title, content, cfg)
+ if (
+ candidate.status === "ready"
+ && (best.status !== "ready" || candidate.page.failedChunks < best.page.failedChunks)
+ ) {
+ best = candidate
+ }
+ }
+ return best
+}
+
/**
* Embed every wiki content page that isn't already indexed (or re-embed
* all when `force === true`). Driven from Settings → Embedding or on
@@ -368,14 +419,18 @@ export async function embedAllPages(
lastEmbeddingError = null
const pp = normalizePath(projectPath)
+ setEmbeddingReindexState({ kind: "running", projectPath: pp, done: 0, total: 0 })
let tree: FileNode[]
try {
tree = await listDirectory(`${pp}/wiki`)
} catch {
if (options?.clearExisting) {
- throw new Error("Could not read wiki tree; existing index was left unchanged.")
+ const message = "Could not read wiki tree; existing index was left unchanged."
+ setEmbeddingReindexState({ kind: "error", projectPath: pp, message })
+ throw new Error(message)
}
+ setEmbeddingReindexState({ kind: "done", projectPath: pp, count: 0 })
return 0
}
@@ -398,12 +453,14 @@ export async function embedAllPages(
if (mdFiles.length === 0) {
const existingChunks = await vectorCountChunks(pp).catch(() => 0)
if (existingChunks > 0) {
- throw new Error(
+ throwEmbeddingReindexError(
+ pp,
`Wiki tree returned no content pages, but ${existingChunks} chunks are currently indexed. Existing index was left unchanged.`,
)
}
await clearChunkVectorTable(pp)
await dropLegacyVectorTableBestEffort(pp)
+ setEmbeddingReindexState({ kind: "done", projectPath: pp, count: 0 })
return 0
}
@@ -414,7 +471,7 @@ export async function embedAllPages(
try {
const content = await readFile(file.path)
const title = extractEmbeddingTitle(content, file.id)
- const prepared = await preparePageEmbeddingRows(file.id, title, content, cfg)
+ const prepared = await preparePageEmbeddingRowsWithRetry(file.id, title, content, cfg)
if (prepared.status === "ready") {
if (prepared.page.failedChunks > 0) {
const reason = getLastEmbeddingError()
@@ -431,19 +488,38 @@ export async function embedAllPages(
failures.push(`${file.id}: ${err instanceof Error ? err.message : String(err)}`)
}
attempted++
+ setEmbeddingReindexState({
+ kind: "running",
+ projectPath: pp,
+ done: attempted,
+ total: mdFiles.length,
+ })
if (onProgress) onProgress(attempted, mdFiles.length)
}
if (failures.length > 0) {
- throw new Error(
- `${failures.length} of ${mdFiles.length} pages could not be embedded (${failures[0]}). Existing index was left unchanged.`,
- )
+ let updated = 0
+ for (const page of preparedPages) {
+ try {
+ await vectorUpsertChunks(pp, page.pageId, page.rows)
+ updated++
+ } catch (err) {
+ failures.push(
+ `${page.pageId}: ${err instanceof Error ? err.message : String(err)}`,
+ )
+ }
+ }
+ if (updated > 0) await optimizeChunkVectorTableBestEffort(pp)
+ const error = `${failures.length} of ${mdFiles.length} pages could not be embedded (${failures[0]}). ${updated} successful page(s) were updated; failed pages kept their previous vectors and can be retried.`
+ setEmbeddingReindexState({ kind: "error", projectPath: pp, message: error })
+ throw new Error(error)
}
if (preparedPages.length === 0) {
const existingChunks = await vectorCountChunks(pp).catch(() => 0)
if (existingChunks > 0) {
- throw new Error(
+ throwEmbeddingReindexError(
+ pp,
`Wiki tree has only empty content pages, but ${existingChunks} chunks are currently indexed. Existing index was left unchanged.`,
)
}
@@ -457,7 +533,8 @@ export async function embedAllPages(
await vectorUpsertChunks(pp, page.pageId, page.rows)
} catch (err) {
const reason = err instanceof Error ? err.message : String(err)
- throw new Error(
+ throwEmbeddingReindexError(
+ pp,
`Rebuild write failed after clearing existing chunks (${page.pageId}: ${reason}). The rebuilt index may be incomplete; run re-index again after fixing the error.`,
)
}
@@ -475,6 +552,7 @@ export async function embedAllPages(
// written. Keep this outside the `written > 0` optimization guard.
await dropLegacyVectorTableBestEffort(pp)
+ setEmbeddingReindexState({ kind: "done", projectPath: pp, count: written })
return written
}
@@ -491,6 +569,7 @@ export async function embedAllPages(
// skip — individual file failure doesn't halt the batch
}
done++
+ setEmbeddingReindexState({ kind: "running", projectPath: pp, done, total: mdFiles.length })
if (onProgress) onProgress(done, mdFiles.length)
}
@@ -498,6 +577,7 @@ export async function embedAllPages(
await optimizeChunkVectorTableBestEffort(pp)
}
+ setEmbeddingReindexState({ kind: "done", projectPath: pp, count: indexed })
return indexed
}
diff --git a/src/lib/ingest-parse.test.ts b/src/lib/ingest-parse.test.ts
index 501f59aa..525b4d72 100644
--- a/src/lib/ingest-parse.test.ts
+++ b/src/lib/ingest-parse.test.ts
@@ -28,6 +28,9 @@ import {
aggregatePathsNeedingRepair,
filterAggregateRepairOutput,
rewriteIngestPathFromTitleForTargetLanguage,
+ canonicalizeSourcesField,
+ isAppManagedAggregatePath,
+ updateBoundedRecentIndexSection,
} from "./ingest"
// ── Happy paths ─────────────────────────────────────────────────────
@@ -110,11 +113,13 @@ describe("source summary media refs", () => {
})
describe("aggregate repair targeting", () => {
- it("requests missing aggregate pages and aggregate pages dropped by truncation warnings", () => {
+ it("repairs only the append-only log and leaves deterministic aggregates to the app", () => {
expect(aggregatePathsNeedingRepair(
["wiki/index.md", "wiki/log.md"],
['FILE block "wiki/overview.md" was not closed before end of stream — likely truncation.'],
- )).toEqual(["wiki/overview.md"])
+ )).toEqual([])
+
+ expect(aggregatePathsNeedingRepair(["wiki/index.md"], [])).toEqual(["wiki/log.md"])
expect(aggregatePathsNeedingRepair(
["wiki/index.md", "wiki/overview.md", "wiki/log.md"],
@@ -625,3 +630,55 @@ describe("rewriteIngestPathFromTitleForTargetLanguage", () => {
).toBe("wiki/index.md")
})
})
+
+describe("canonicalizeSourcesField", () => {
+ it("removes generated and unsafe paths while preserving raw source identities", () => {
+ const content = [
+ "---",
+ "title: Entity",
+ 'sources: ["wiki/log.md", "wiki/index.md", ".llm-wiki/state.json", "/tmp/secret.md", "../escape.md", "raw/sources/folder/source.md"]',
+ "---",
+ "# Entity",
+ ].join("\n")
+
+ const result = canonicalizeSourcesField(content, "folder/source.md")
+
+ expect(result).toContain('sources: ["folder/source.md"]')
+ expect(result).not.toContain("wiki/log.md")
+ expect(result).not.toContain(".llm-wiki")
+ expect(result).not.toContain("/tmp/secret.md")
+ expect(result).not.toContain("../escape.md")
+ })
+
+ it("preserves a legitimate source identity under a wiki-named raw subfolder", () => {
+ const content = '---\ntitle: Notes\nsources: ["raw/sources/wiki/notes.md"]\n---\n# Notes'
+ expect(canonicalizeSourcesField(content, "wiki/notes.md")).toContain(
+ 'sources: ["wiki/notes.md"]',
+ )
+ })
+})
+
+describe("application-managed aggregate boundaries", () => {
+ it("recognizes case and separator variants", () => {
+ expect(isAppManagedAggregatePath("wiki/INDEX.md")).toBe(true)
+ expect(isAppManagedAggregatePath("wiki\\overview.MD")).toBe(true)
+ expect(isAppManagedAggregatePath("wiki/entities/index.md")).toBe(false)
+ })
+
+ it("bounds recent entries and preserves following sections", () => {
+ const existing = [
+ "# Wiki Index",
+ "",
+ "## Recently Updated",
+ ...Array.from({ length: 205 }, (_, index) => `- [[old-${index}]] — Old ${index}`),
+ "",
+ "## Other",
+ "Keep me",
+ ].join("\n")
+ const result = updateBoundedRecentIndexSection(existing, ["- [[new]] — New"])
+ const recent = result.split("## Recently Updated")[1].split("## Other")[0]
+ expect(recent.match(/^- \[\[/gm)).toHaveLength(200)
+ expect(recent).toContain("[[new]]")
+ expect(result).toContain("## Other\nKeep me")
+ })
+})
diff --git a/src/lib/ingest-source-path-collision.test.ts b/src/lib/ingest-source-path-collision.test.ts
index 25b41fc6..0e15b268 100644
--- a/src/lib/ingest-source-path-collision.test.ts
+++ b/src/lib/ingest-source-path-collision.test.ts
@@ -15,6 +15,7 @@ let failLongChunksOnce = new Set<number>()
let extraReviewResponse = ""
let generationSuffix = ""
let abortDuringReview: AbortController | null = null
+let interactiveGenerationOverride = ""
vi.mock("./llm-client", () => ({
streamChat: vi.fn(async (_cfg, messages, cb) => {
@@ -29,6 +30,11 @@ vi.mock("./llm-client", () => ({
}
if (systemPrompt.startsWith("You are a wiki generation assistant")) {
+ if (interactiveGenerationOverride) {
+ cb.onToken(interactiveGenerationOverride)
+ cb.onDone()
+ return
+ }
cb.onToken([
"---FILE: wiki/sources/config.md---",
"---",
@@ -129,6 +135,7 @@ describe("autoIngest source summary paths", () => {
extraReviewResponse = ""
generationSuffix = ""
abortDuringReview = null
+ interactiveGenerationOverride = ""
mockStreamChat.mockClear()
mockParseWithMineru.mockReset()
tmp = await createTempProject("same-basename-sources")
@@ -620,4 +627,19 @@ describe("autoIngest source summary paths", () => {
await expect(fs.access(staleSummaryPath)).rejects.toThrow()
expect(content).toContain('sources: ["project-a/config.yaml"]')
})
+
+ it("rejects unsafe and application-managed paths from interactive writes", async () => {
+ if (!tmp) throw new Error("missing temp project")
+ interactiveGenerationOverride = [
+ "---FILE: wiki/INDEX.md---\n# hostile index\n---END FILE---",
+ "---FILE: wiki\\overview.MD---\n# hostile overview\n---END FILE---",
+ "---FILE: ../escape.md---\n# escape\n---END FILE---",
+ ].join("\n")
+ useChatStore.setState({ ingestSource: `${tmp.path}/raw/sources/project-a/config.yaml` })
+
+ const written = await executeIngestWrites(tmp.path, useWikiStore.getState().llmConfig)
+
+ expect(written).toEqual([])
+ await expect(fs.access(path.join(tmp.path, "escape.md"))).rejects.toThrow()
+ })
})
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 7fd5fc3b..85fab0ca 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -19,6 +19,7 @@ import { useReviewStore, type ReviewItem } from "@/stores/review-store"
import { getFileName, normalizePath } from "@/lib/path-utils"
import {
sourceIdentityForPath,
+ sourceReferenceIdentity,
sourceSummarySlugCandidatesFromIdentity,
sourceSummarySlugFromIdentity,
} from "@/lib/source-identity"
@@ -1110,6 +1111,17 @@ async function autoIngestImpl(
const writeWarnings = writeResult.warnings
const hardFailures = writeResult.hardFailures
+ try {
+ if (await updateWikiIndexDeterministically(pp, writtenPaths)) {
+ writtenPaths.push("wiki/index.md")
+ onFileWritten?.("wiki/index.md")
+ }
+ } catch (err) {
+ writeWarnings.push(
+ `Deterministic index update failed: ${err instanceof Error ? err.message : String(err)}`,
+ )
+ }
+
const aggregateRepairPaths = aggregatePathsNeedingRepair(writtenPaths, writeWarnings)
const repairableAggregatePaths = aggregateRepairPaths.filter((path) =>
isAggregateRepairSafe(path, index, overview, llmConfig.maxContextSize),
@@ -1375,6 +1387,11 @@ function isListingPath(relativePath: string): boolean {
)
}
+export function isAppManagedAggregatePath(relativePath: string): boolean {
+ const normalized = relativePath.replace(/\\/g, "/").toLowerCase()
+ return normalized === "wiki/index.md" || normalized === "wiki/overview.md"
+}
+
const CJK_OUTPUT_LANGUAGES = new Set(["Chinese", "Traditional Chinese", "Japanese", "Korean"])
function containsCjk(text: string): boolean {
@@ -1420,11 +1437,70 @@ export function rewriteIngestPathFromTitleForTargetLanguage(
export function aggregatePathsNeedingRepair(writtenPaths: string[], warnings: string[]): string[] {
const written = new Set(writtenPaths.map((path) => normalizePath(path)))
const warningText = warnings.join("\n")
- return AGGREGATE_WIKI_PATHS.filter((path) =>
+ // index.md is maintained deterministically and overview.md is intentionally
+ // bounded/stable. Only the append-only log still needs an LLM repair block.
+ return AGGREGATE_WIKI_PATHS.filter((path) => path === "wiki/log.md").filter((path) =>
!written.has(path) || warningText.includes(`"${path}"`),
)
}
+async function updateWikiIndexDeterministically(
+ projectPath: string,
+ writtenPaths: string[],
+): Promise<boolean> {
+ const candidates = Array.from(new Set(writtenPaths.map(normalizePath))).filter((path) =>
+ path.startsWith("wiki/")
+ && path.endsWith(".md")
+ && !AGGREGATE_WIKI_PATHS.includes(path as (typeof AGGREGATE_WIKI_PATHS)[number]),
+ )
+ if (candidates.length === 0) return false
+
+ const indexPath = `${projectPath}/wiki/index.md`
+ const index = await readFile(indexPath).catch(() => "# Wiki Index\n")
+ const knownTargets = new Set(
+ Array.from(index.matchAll(/\[\[([^\]|#]+)(?:#[^\]|]+)?(?:\|[^\]]+)?\]\]/g))
+ .map((match) => normalizeIndexTarget(match[1])),
+ )
+ const additions: string[] = []
+ for (const path of candidates) {
+ const target = path.replace(/^wiki\//, "").replace(/\.md$/i, "")
+ if (knownTargets.has(normalizeIndexTarget(target))) continue
+ const content = await readFile(`${projectPath}/${path}`).catch(() => "")
+ const parsed = parseFrontmatter(content)
+ const title = typeof parsed.frontmatter?.title === "string"
+ ? parsed.frontmatter.title.trim()
+ : getFileName(path).replace(/\.md$/i, "")
+ additions.push(`- [[${target}]] — ${title}`)
+ }
+ if (additions.length === 0) return false
+
+ await writeFile(indexPath, updateBoundedRecentIndexSection(index, additions))
+ return true
+}
+
+function normalizeIndexTarget(target: string): string {
+ return normalizePath(target)
+ .replace(/^wiki\//i, "")
+ .replace(/\.md$/i, "")
+ .toLowerCase()
+}
+
+export function updateBoundedRecentIndexSection(index: string, additions: string[]): string {
+ const section = "## Recently Updated"
+ const lines = index.trimEnd().split("\n")
+ const start = lines.findIndex((line) => line.trim() === section)
+ const prefix = start >= 0 ? lines.slice(0, start) : lines
+ const sectionEnd = start >= 0
+ ? lines.findIndex((line, position) => position > start && /^##\s+/.test(line))
+ : -1
+ const existing = start >= 0
+ ? lines.slice(start + 1, sectionEnd >= 0 ? sectionEnd : undefined).filter((line) => /^-\s+/.test(line))
+ : []
+ const suffix = sectionEnd >= 0 ? lines.slice(sectionEnd) : []
+ const recent = Array.from(new Set([...additions, ...existing])).slice(0, 200)
+ return [...prefix, "", section, ...recent, ...(suffix.length ? ["", ...suffix] : []), ""].join("\n")
+}
+
export function filterAggregateRepairOutput(text: string, allowedPaths: string[]): {
text: string
warnings: string[]
@@ -1463,18 +1539,32 @@ function isAggregateRepairSafe(
return true
}
-function canonicalizeSourcesField(content: string, sourceIdentity: string): string {
+function isValidSourceReference(source: string, activeSourceIdentity: string): boolean {
+ const normalized = normalizePath(source).replace(/^(?:\.\/)+/, "")
+ const key = normalized.toLowerCase()
+ const identityKey = normalizePath(activeSourceIdentity).toLowerCase()
+ if (!normalized || normalized.startsWith("/") || /^[a-z]:\//i.test(normalized)) return false
+ if (normalized.split("/").some((part) => part === "..")) return false
+ if (sourceReferenceIdentity(normalized).toLowerCase() === identityKey) return true
+ if (["wiki/index.md", "wiki/overview.md", "wiki/log.md"].includes(key)) return false
+ if (key === ".llm-wiki" || key.startsWith(".llm-wiki/")) return false
+ return true
+}
+
+export function canonicalizeSourcesField(content: string, sourceIdentity: string): string {
if (!/^---\n/.test(content)) return content
const identityKey = normalizePath(sourceIdentity).toLowerCase()
const identityBaseName = getFileName(sourceIdentity).toLowerCase()
const sourceValues = parseSources(content)
- const canonicalValues = sourceValues.map((source) => {
- const normalized = normalizePath(source)
+ const canonicalValues = sourceValues.filter((source) =>
+ isValidSourceReference(source, sourceIdentity)
+ ).map((source) => {
+ const normalized = sourceReferenceIdentity(source)
const key = normalized.toLowerCase()
if (key === identityKey) return sourceIdentity
if (!normalized.includes("/") && key === identityBaseName) return sourceIdentity
- return source
+ return normalized
})
if (!canonicalValues.some((source) => normalizePath(source).toLowerCase() === identityKey)) {
canonicalValues.push(sourceIdentity)
@@ -1712,6 +1802,12 @@ async function writeFileBlocks(
if (sourceSummaryPath && relativePath.startsWith("wiki/sources/")) {
relativePath = sourceSummaryPath
}
+ if (isAppManagedAggregatePath(relativePath)) {
+ warnings.push(
+ `Ignored model-generated "${relativePath}"; aggregate navigation is maintained by the application.`,
+ )
+ continue
+ }
// Sanitize at the boundary — strip stray code-fence wrappers,
// `frontmatter:` prefixes, and repair invalid wikilink-list
@@ -1811,7 +1907,7 @@ async function writeFileBlocks(
// body + array-field union" with a best-effort backup.
// See page-merge.ts.
const existing = await tryReadFile(fullPath)
- const toWrite = await mergePageContent(
+ const merged = await mergePageContent(
content,
existing || null,
buildPageMerger(llmConfig),
@@ -1822,6 +1918,9 @@ async function writeFileBlocks(
backup: (oldContent) => backupExistingPage(projectPath, relativePath, oldContent),
},
)
+ // The merge unions existing frontmatter arrays, so sanitize again to
+ // remove legacy/generated paths that may already be stored on disk.
+ const toWrite = canonicalizeSourcesField(merged, sourceFileName)
await writeFile(fullPath, toWrite)
}
writtenPaths.push(relativePath)
@@ -2019,9 +2118,8 @@ export function buildGenerationPrompt(
`1. A source summary page at **${summaryPath}** (MUST use this exact path)`,
"2. Entity or schema-defined typed pages for key named things identified in the analysis. Prefer schema-defined directories when present; otherwise use wiki/entities/.",
"3. Concept or schema-defined typed pages for key ideas, methods, techniques, and abstractions. Prefer schema-defined directories when present; otherwise use wiki/concepts/.",
- "4. An updated wiki/index.md — add new entries to existing categories, preserve all existing entries",
- "5. A log entry for wiki/log.md (just the new entry to append, format: ## [YYYY-MM-DD] ingest | Title)",
- "6. An updated wiki/overview.md — a high-level summary of what the entire wiki covers, updated to reflect the newly ingested source. This should be a comprehensive 2-5 paragraph overview of ALL topics in the wiki, not just the new source.",
+ "4. A log entry for wiki/log.md (just the new entry to append, format: ## [YYYY-MM-DD] ingest | Title)",
+ "Do not generate wiki/index.md or wiki/overview.md. The application maintains aggregate navigation separately so large wikis are never rewritten through model output.",
"",
"## Frontmatter Rules (CRITICAL — parser is strict)",
"",
@@ -3037,7 +3135,19 @@ export async function startIngest(
)
}
-export async function executeIngestWrites(
+export function executeIngestWrites(
+ projectPath: string,
+ llmConfig: LlmConfig,
+ userGuidance?: string,
+ signal?: AbortSignal,
+): Promise<string[]> {
+ const pp = normalizePath(projectPath)
+ return withProjectLock(pp, () =>
+ executeIngestWritesImpl(pp, llmConfig, userGuidance, signal)
+ )
+}
+
+async function executeIngestWritesImpl(
projectPath: string,
llmConfig: LlmConfig,
userGuidance?: string,
@@ -3089,6 +3199,7 @@ export async function executeIngestWrites(
"```",
"",
"For wiki/log.md, include a log entry to append. For all other files, output the complete file content.",
+ "Do not generate wiki/index.md or wiki/overview.md. The application owns those aggregate files.",
"Use relative paths from the project root (e.g., wiki/sources/topic.md).",
"Do not include any other text outside the FILE blocks.",
]
@@ -3152,6 +3263,11 @@ export async function executeIngestWrites(
relativePath = activeSourceSummaryPath
}
+ if (!isSafeIngestPath(relativePath) || isAppManagedAggregatePath(relativePath)) {
+ console.warn(`[executeIngestWrites] rejected unsafe or app-managed path: ${relativePath}`)
+ continue
+ }
+
if (
activeSourceIdentity &&
!isLogPath(relativePath) &&