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

chore: remove internal planning docs containing local paths

nash_su7f2b93a41c18
diff --git a/docs/superpowers/plans/2026-04-05-llm-wiki-phase1-foundation.md b/docs/superpowers/plans/2026-04-05-llm-wiki-phase1-foundation.md
deleted file mode 100644
index d2779b90..00000000
--- a/docs/superpowers/plans/2026-04-05-llm-wiki-phase1-foundation.md
+++ /dev/null
@@ -1,1762 +0,0 @@
-# LLM Wiki Phase 1: Foundation — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Stand up a working Tauri v2 desktop app with file tree navigation, wiki page browsing, and a Milkdown WYSIWYG editor — the skeleton that all subsequent phases build on.
-
-**Architecture:** Tauri v2 desktop shell with React frontend and Rust backend. Rust handles all file system operations exposed via Tauri IPC commands. React renders a VS Code-style layout: icon sidebar, file tree, content area, and a collapsible Chat bar placeholder.
-
-**Tech Stack:** Tauri v2, React 19, TypeScript, Vite, Tailwind CSS v4, shadcn/ui, Milkdown, Zustand
-
----
-
-## Phase Overview
-
-All 6 phases for reference:
-
-| Phase | Scope | Status |
-|-------|-------|--------|
-| **Phase 1: Foundation** | Tauri scaffold, file system ops, layout shell, wiki browser, Milkdown editor | **Current** |
-| Phase 2: LLM Integration | LLM Router, Chat UI, basic ingest (single source) | Planned |
-| Phase 3: Search & Query | tantivy search, query pipeline, multi-format rendering, Save to Wiki | Planned |
-| Phase 4: Lint & Graph | Lint engine (structural + semantic), graph view, lint dashboard | Planned |
-| Phase 5: Polish | i18n, settings UI, templates system, schema co-evolution | Planned |
-| Phase 6: Extension | Browser clipper extension, batch ingest, image processing | Planned |
-
----
-
-## File Structure
-
-```
-llm_wiki/
-├── package.json
-├── vite.config.ts
-├── tsconfig.json
-├── tsconfig.app.json
-├── index.html
-├── src/
-│ ├── main.tsx # React entry point
-│ ├── App.tsx # Root component, layout shell
-│ ├── index.css # Tailwind import
-│ ├── lib/
-│ │ └── utils.ts # shadcn cn() utility
-│ ├── stores/
-│ │ └── wiki-store.ts # Zustand store: current project, selected file, file tree
-│ ├── components/
-│ │ ├── ui/ # shadcn/ui components (auto-generated)
-│ │ ├── layout/
-│ │ │ ├── app-layout.tsx # Top-level layout: sidebar + file tree + content + chat bar
-│ │ │ ├── icon-sidebar.tsx # Left icon bar (wiki, sources, search, graph, lint, settings)
-│ │ │ ├── file-tree.tsx # File tree panel showing wiki/ structure
-│ │ │ ├── content-area.tsx # Main content area (renders editor or welcome)
-│ │ │ └── chat-bar.tsx # Collapsible chat bar placeholder at bottom of content
-│ │ ├── editor/
-│ │ │ └── wiki-editor.tsx # Milkdown WYSIWYG editor with [[wikilink]] support
-│ │ └── project/
-│ │ ├── welcome-screen.tsx # Shown when no project is open
-│ │ └── create-project-dialog.tsx # Dialog to create new wiki project
-│ ├── commands/
-│ │ └── fs.ts # TypeScript wrappers for Rust file system commands
-│ └── types/
-│ └── wiki.ts # Shared types: WikiProject, FileNode, WikiPage
-├── src-tauri/
-│ ├── Cargo.toml
-│ ├── build.rs
-│ ├── tauri.conf.json
-│ ├── capabilities/
-│ │ └── default.json
-│ └── src/
-│ ├── main.rs # Desktop entry point
-│ ├── lib.rs # Tauri builder setup, registers all commands
-│ ├── commands/
-│ │ ├── mod.rs # Re-exports command modules
-│ │ ├── project.rs # create_project, open_project, list_recent_projects
-│ │ └── fs.rs # read_file, write_file, list_directory, create_directory
-│ └── types/
-│ ├── mod.rs # Re-exports type modules
-│ └── wiki.rs # FileNode, WikiProject structs
-└── tests/
- └── src-tauri/
- └── commands/
- ├── project_test.rs # Tests for project commands
- └── fs_test.rs # Tests for file system commands
-```
-
----
-
-### Task 1: Scaffold Tauri v2 + React + TypeScript Project
-
-**Files:**
-- Create: entire project scaffold via CLI
-- Modify: `package.json` (add dependencies)
-
-- [ ] **Step 1: Create Tauri project**
-
-```bash
-cd /Users/nash_su/projects
-npm create tauri-app@latest llm_wiki -- --template react-ts --manager npm
-```
-
-When prompted:
-- Identifier: `com.llmwiki.app`
-- Frontend: TypeScript
-- Package manager: npm
-- UI template: React
-- UI flavor: TypeScript
-
-- [ ] **Step 2: Verify scaffold runs**
-
-```bash
-cd /Users/nash_su/projects/llm_wiki
-npm install
-npm run tauri dev
-```
-
-Expected: A window opens with the default Tauri + React starter page.
-
-- [ ] **Step 3: Stop the dev server and commit**
-
-```bash
-git init
-echo ".superpowers/" >> .gitignore
-git add -A
-git commit -m "chore: scaffold Tauri v2 + React + TypeScript project"
-```
-
----
-
-### Task 2: Add Tailwind CSS v4 + shadcn/ui
-
-**Files:**
-- Modify: `vite.config.ts`
-- Modify: `tsconfig.app.json`
-- Modify: `src/index.css`
-- Create: `src/lib/utils.ts`
-- Create: `src/components/ui/` (via shadcn CLI)
-
-- [ ] **Step 1: Install Tailwind CSS v4**
-
-```bash
-npm install tailwindcss @tailwindcss/vite
-```
-
-- [ ] **Step 2: Configure Vite plugin and path alias**
-
-Replace `vite.config.ts`:
-
-```ts
-import path from "path"
-import { defineConfig } from "vite"
-import react from "@vitejs/plugin-react"
-import tailwindcss from "@tailwindcss/vite"
-
-const host = process.env.TAURI_DEV_HOST
-
-export default defineConfig(async () => ({
- plugins: [react(), tailwindcss()],
- resolve: {
- alias: { "@": path.resolve(__dirname, "./src") },
- },
- clearScreen: false,
- server: {
- port: 1420,
- strictPort: true,
- host: host || false,
- hmr: host ? { protocol: "ws", host, port: 1421 } : undefined,
- watch: { ignored: ["**/src-tauri/**"] },
- },
-}))
-```
-
-- [ ] **Step 3: Add path alias to tsconfig**
-
-Add to `tsconfig.app.json` inside `compilerOptions`:
-
-```json
-{
- "compilerOptions": {
- "baseUrl": ".",
- "paths": { "@/*": ["./src/*"] }
- }
-}
-```
-
-- [ ] **Step 4: Replace src/index.css with Tailwind import**
-
-```css
-@import "tailwindcss";
-```
-
-- [ ] **Step 5: Install shadcn/ui dependencies**
-
-```bash
-npm install -D @types/node
-npx shadcn@latest init
-```
-
-When prompted, accept defaults (New York style, Zinc base color).
-
-- [ ] **Step 6: Add initial shadcn components**
-
-```bash
-npx shadcn@latest add button scroll-area separator tooltip dialog input label
-```
-
-- [ ] **Step 7: Verify Tailwind + shadcn work**
-
-Replace `src/App.tsx`:
-
-```tsx
-import { Button } from "@/components/ui/button"
-
-function App() {
- return (
- <div className="flex h-screen items-center justify-center bg-background">
- <Button>LLM Wiki</Button>
- </div>
- )
-}
-
-export default App
-```
-
-Run: `npm run tauri dev`
-Expected: A centered button with shadcn styling appears.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add -A
-git commit -m "chore: add Tailwind CSS v4 + shadcn/ui"
-```
-
----
-
-### Task 3: Define Shared Types
-
-**Files:**
-- Create: `src/types/wiki.ts`
-- Create: `src-tauri/src/types/mod.rs`
-- Create: `src-tauri/src/types/wiki.rs`
-- Modify: `src-tauri/src/lib.rs`
-
-- [ ] **Step 1: Create TypeScript types**
-
-Create `src/types/wiki.ts`:
-
-```ts
-export interface WikiProject {
- name: string
- path: string
-}
-
-export interface FileNode {
- name: string
- path: string
- is_dir: boolean
- children?: FileNode[]
-}
-
-export interface WikiPage {
- path: string
- content: string
- frontmatter: Record<string, unknown>
-}
-```
-
-- [ ] **Step 2: Create Rust types**
-
-Create `src-tauri/src/types/mod.rs`:
-
-```rust
-pub mod wiki;
-```
-
-Create `src-tauri/src/types/wiki.rs`:
-
-```rust
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct WikiProject {
- pub name: String,
- pub path: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct FileNode {
- pub name: String,
- pub path: String,
- pub is_dir: bool,
- #[serde(skip_serializing_if = "Option::is_none")]
- pub children: Option<Vec<FileNode>>,
-}
-```
-
-- [ ] **Step 3: Register types module in lib.rs**
-
-Add to `src-tauri/src/lib.rs`:
-
-```rust
-mod types;
-```
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add src/types/wiki.ts src-tauri/src/types/
-git commit -m "feat: define shared WikiProject and FileNode types"
-```
-
----
-
-### Task 4: Rust File System Commands
-
-**Files:**
-- Create: `src-tauri/src/commands/mod.rs`
-- Create: `src-tauri/src/commands/fs.rs`
-- Create: `src-tauri/src/commands/project.rs`
-- Modify: `src-tauri/src/lib.rs`
-
-- [ ] **Step 1: Create commands module**
-
-Create `src-tauri/src/commands/mod.rs`:
-
-```rust
-pub mod fs;
-pub mod project;
-```
-
-- [ ] **Step 2: Create file system commands**
-
-Create `src-tauri/src/commands/fs.rs`:
-
-```rust
-use crate::types::wiki::FileNode;
-use std::fs;
-use std::path::Path;
-
-#[tauri::command]
-pub fn read_file(path: String) -> Result<String, String> {
- fs::read_to_string(&path).map_err(|e| format!("Failed to read {}: {}", path, e))
-}
-
-#[tauri::command]
-pub fn write_file(path: String, contents: String) -> Result<(), String> {
- if let Some(parent) = Path::new(&path).parent() {
- fs::create_dir_all(parent)
- .map_err(|e| format!("Failed to create directory: {}", e))?;
- }
- fs::write(&path, contents).map_err(|e| format!("Failed to write {}: {}", path, e))
-}
-
-#[tauri::command]
-pub fn list_directory(path: String) -> Result<Vec<FileNode>, String> {
- let path = Path::new(&path);
- if !path.is_dir() {
- return Err(format!("{} is not a directory", path.display()));
- }
- list_dir_recursive(path, 0, 3)
-}
-
-fn list_dir_recursive(path: &Path, depth: usize, max_depth: usize) -> Result<Vec<FileNode>, String> {
- let mut entries: Vec<FileNode> = Vec::new();
- let read_dir = fs::read_dir(path)
- .map_err(|e| format!("Failed to read directory {}: {}", path.display(), e))?;
-
- for entry in read_dir {
- let entry = entry.map_err(|e| e.to_string())?;
- let entry_path = entry.path();
- let name = entry
- .file_name()
- .to_string_lossy()
- .to_string();
-
- if name.starts_with('.') {
- continue;
- }
-
- let is_dir = entry_path.is_dir();
- let children = if is_dir && depth < max_depth {
- Some(list_dir_recursive(&entry_path, depth + 1, max_depth)?)
- } else if is_dir {
- Some(Vec::new())
- } else {
- None
- };
-
- entries.push(FileNode {
- name,
- path: entry_path.to_string_lossy().to_string(),
- is_dir,
- children,
- });
- }
-
- entries.sort_by(|a, b| match (a.is_dir, b.is_dir) {
- (true, false) => std::cmp::Ordering::Less,
- (false, true) => std::cmp::Ordering::Greater,
- _ => a.name.to_lowercase().cmp(&b.name.to_lowercase()),
- });
-
- Ok(entries)
-}
-
-#[tauri::command]
-pub fn create_directory(path: String) -> Result<(), String> {
- fs::create_dir_all(&path).map_err(|e| format!("Failed to create directory {}: {}", path, e))
-}
-```
-
-- [ ] **Step 3: Create project commands**
-
-Create `src-tauri/src/commands/project.rs`:
-
-```rust
-use crate::types::wiki::WikiProject;
-use std::fs;
-use std::path::Path;
-
-const DEFAULT_SCHEMA: &str = r#"# Schema
-
-## Page Types
-- source: Source summary (title, origin, date, summary, key points, related pages)
-- entity: Entity page (name, type, description, first source, related entities)
-- concept: Concept page (definition, background, key arguments, related concepts, cited sources)
-- comparison: Comparison page (subjects, dimensions, comparison table, conclusion)
-- query: Archived query (original question, answer, cited pages, date)
-- overview: Global overview (single page, high-level picture)
-- synthesis: Cross-source synthesis (deep analysis, evolving thesis, evidence tracking)
-
-## Naming Conventions
-- Lowercase, kebab-case
-- Sources: sources/author-year-keyword.md
-- Entities: entities/name.md
-- Concepts: concepts/name.md
-
-## Frontmatter
-Every wiki page has YAML frontmatter:
-- type, title, created, updated, sources[], tags[], source_count
-
-## Index Format
-Organized by category. Each entry:
-- [Page Title](path.md) — one-line summary (N sources, YYYY-MM-DD)
-
-## Log Format
-Each entry: ## [YYYY-MM-DD] type | title
-Types: ingest, query, lint, update
-
-## Cross-referencing Rules
-- Use [[wikilink]] syntax
-- First mention of entity/concept must be linked
-- After creating a new page, update all related pages' references
-
-## Contradiction Handling
-- On ingest, check new information against existing pages
-- Mark contradictions with > [!conflict] callouts
-- Update synthesis pages to record thesis evolution
-- Lint re-reviews unresolved contradictions
-"#;
-
-const DEFAULT_PURPOSE: &str = r#"# Purpose
-
-## Goal
-(Describe what this wiki is for in one or two sentences)
-
-## Key Questions
-- (What are you trying to understand or answer?)
-
-## Scope
-- In scope: (What topics belong here)
-- Out of scope: (What to exclude)
-
-## Thesis
-(Your current working hypothesis — this will evolve as you add sources)
-"#;
-
-#[tauri::command]
-pub fn create_project(name: String, path: String) -> Result<WikiProject, String> {
- let project_path = Path::new(&path).join(&name);
-
- if project_path.exists() {
- return Err(format!("Directory already exists: {}", project_path.display()));
- }
-
- let dirs = [
- "",
- "raw/sources",
- "raw/assets",
- "wiki/entities",
- "wiki/concepts",
- "wiki/sources",
- "wiki/queries",
- "wiki/comparisons",
- "wiki/synthesis",
- ];
-
- for dir in &dirs {
- fs::create_dir_all(project_path.join(dir))
- .map_err(|e| format!("Failed to create {}: {}", dir, e))?;
- }
-
- fs::write(project_path.join("schema.md"), DEFAULT_SCHEMA)
- .map_err(|e| format!("Failed to write schema.md: {}", e))?;
-
- fs::write(project_path.join("purpose.md"), DEFAULT_PURPOSE)
- .map_err(|e| format!("Failed to write purpose.md: {}", e))?;
-
- let now = chrono::Local::now().format("%Y-%m-%d").to_string();
-
- let index_content = format!(
- "# Index\n\n*Last updated: {}*\n\n## Entities\n\n(No entities yet)\n\n## Concepts\n\n(No concepts yet)\n\n## Sources\n\n(No sources yet)\n\n## Queries\n\n(No queries yet)\n\n## Comparisons\n\n(No comparisons yet)\n\n## Synthesis\n\n(No synthesis yet)\n",
- now
- );
- fs::write(project_path.join("wiki/index.md"), index_content)
- .map_err(|e| format!("Failed to write index.md: {}", e))?;
-
- let log_content = format!("# Log\n\n## [{}] init | Project created\n\nInitialized wiki project: {}\n", now, name);
- fs::write(project_path.join("wiki/log.md"), log_content)
- .map_err(|e| format!("Failed to write log.md: {}", e))?;
-
- let overview_content = format!(
- "---\ntype: overview\ntitle: Overview\ncreated: {}\nupdated: {}\nsources: []\ntags: []\nsource_count: 0\n---\n\n# Overview\n\nThis wiki is new. Add sources to start building knowledge.\n",
- now, now
- );
- fs::write(project_path.join("wiki/overview.md"), overview_content)
- .map_err(|e| format!("Failed to write overview.md: {}", e))?;
-
- let project = WikiProject {
- name,
- path: project_path.to_string_lossy().to_string(),
- };
-
- Ok(project)
-}
-
-#[tauri::command]
-pub fn open_project(path: String) -> Result<WikiProject, String> {
- let project_path = Path::new(&path);
-
- if !project_path.join("schema.md").exists() {
- return Err("Not a valid LLM Wiki project: schema.md not found".to_string());
- }
- if !project_path.join("wiki").is_dir() {
- return Err("Not a valid LLM Wiki project: wiki/ directory not found".to_string());
- }
-
- let name = project_path
- .file_name()
- .map(|n| n.to_string_lossy().to_string())
- .unwrap_or_else(|| "Unnamed".to_string());
-
- Ok(WikiProject {
- name,
- path: project_path.to_string_lossy().to_string(),
- })
-}
-```
-
-- [ ] **Step 4: Add chrono dependency**
-
-Add to `src-tauri/Cargo.toml` under `[dependencies]`:
-
-```toml
-chrono = "0.4"
-```
-
-- [ ] **Step 5: Register commands in lib.rs**
-
-Replace `src-tauri/src/lib.rs`:
-
-```rust
-mod commands;
-mod types;
-
-#[cfg_attr(mobile, tauri::mobile_entry_point)]
-pub fn run() {
- tauri::Builder::default()
- .invoke_handler(tauri::generate_handler![
- commands::fs::read_file,
- commands::fs::write_file,
- commands::fs::list_directory,
- commands::fs::create_directory,
- commands::project::create_project,
- commands::project::open_project,
- ])
- .run(tauri::generate_context!())
- .expect("error while running tauri application");
-}
-```
-
-- [ ] **Step 6: Verify it compiles**
-
-```bash
-cd src-tauri && cargo build
-```
-
-Expected: Compiles with no errors.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add src-tauri/src/commands/ src-tauri/Cargo.toml src-tauri/src/lib.rs
-git commit -m "feat: add Rust file system and project commands"
-```
-
----
-
-### Task 5: TypeScript Command Wrappers
-
-**Files:**
-- Create: `src/commands/fs.ts`
-
-- [ ] **Step 1: Create TypeScript wrappers for Rust commands**
-
-Create `src/commands/fs.ts`:
-
-```ts
-import { invoke } from "@tauri-apps/api/core"
-import type { WikiProject, FileNode } from "@/types/wiki"
-
-export async function readFile(path: string): Promise<string> {
- return invoke<string>("read_file", { path })
-}
-
-export async function writeFile(path: string, contents: string): Promise<void> {
- return invoke("write_file", { path, contents })
-}
-
-export async function listDirectory(path: string): Promise<FileNode[]> {
- return invoke<FileNode[]>("list_directory", { path })
-}
-
-export async function createDirectory(path: string): Promise<void> {
- return invoke("create_directory", { path })
-}
-
-export async function createProject(
- name: string,
- path: string
-): Promise<WikiProject> {
- return invoke<WikiProject>("create_project", { name, path })
-}
-
-export async function openProject(path: string): Promise<WikiProject> {
- return invoke<WikiProject>("open_project", { path })
-}
-```
-
-- [ ] **Step 2: Commit**
-
-```bash
-git add src/commands/fs.ts
-git commit -m "feat: add TypeScript wrappers for Rust commands"
-```
-
----
-
-### Task 6: Zustand Store
-
-**Files:**
-- Create: `src/stores/wiki-store.ts`
-
-- [ ] **Step 1: Install Zustand**
-
-```bash
-npm install zustand
-```
-
-- [ ] **Step 2: Create wiki store**
-
-Create `src/stores/wiki-store.ts`:
-
-```ts
-import { create } from "zustand"
-import type { WikiProject, FileNode } from "@/types/wiki"
-
-interface WikiState {
- project: WikiProject | null
- fileTree: FileNode[]
- selectedFile: string | null
- fileContent: string
- chatExpanded: boolean
- activeView: "wiki" | "sources" | "search" | "graph" | "lint" | "settings"
-
- setProject: (project: WikiProject | null) => void
- setFileTree: (tree: FileNode[]) => void
- setSelectedFile: (path: string | null) => void
- setFileContent: (content: string) => void
- setChatExpanded: (expanded: boolean) => void
- setActiveView: (view: WikiState["activeView"]) => void
-}
-
-export const useWikiStore = create<WikiState>((set) => ({
- project: null,
- fileTree: [],
- selectedFile: null,
- fileContent: "",
- chatExpanded: false,
- activeView: "wiki",
-
- setProject: (project) => set({ project }),
- setFileTree: (fileTree) => set({ fileTree }),
- setSelectedFile: (selectedFile) => set({ selectedFile }),
- setFileContent: (fileContent) => set({ fileContent }),
- setChatExpanded: (chatExpanded) => set({ chatExpanded }),
- setActiveView: (activeView) => set({ activeView }),
-}))
-```
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add src/stores/wiki-store.ts package.json package-lock.json
-git commit -m "feat: add Zustand wiki store"
-```
-
----
-
-### Task 7: Layout Shell — Icon Sidebar
-
-**Files:**
-- Create: `src/components/layout/icon-sidebar.tsx`
-
-- [ ] **Step 1: Create icon sidebar component**
-
-Create `src/components/layout/icon-sidebar.tsx`:
-
-```tsx
-import {
- FileText,
- FolderOpen,
- Search,
- Network,
- ClipboardCheck,
- Settings,
-} from "lucide-react"
-import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"
-import { useWikiStore } from "@/stores/wiki-store"
-import type { WikiState } from "@/stores/wiki-store"
-
-const navItems: { view: WikiState["activeView"]; icon: typeof FileText; label: string }[] = [
- { view: "wiki", icon: FileText, label: "Wiki" },
- { view: "sources", icon: FolderOpen, label: "Sources" },
- { view: "search", icon: Search, label: "Search" },
- { view: "graph", icon: Network, label: "Graph" },
- { view: "lint", icon: ClipboardCheck, label: "Lint" },
- { view: "settings", icon: Settings, label: "Settings" },
-]
-
-export function IconSidebar() {
- const activeView = useWikiStore((s) => s.activeView)
- const setActiveView = useWikiStore((s) => s.setActiveView)
-
- return (
- <TooltipProvider delayDuration={300}>
- <div className="flex h-full w-12 flex-col items-center gap-1 border-r bg-muted/50 py-2">
- {navItems.map(({ view, icon: Icon, label }) => (
- <Tooltip key={view}>
- <TooltipTrigger asChild>
- <button
- onClick={() => setActiveView(view)}
- className={`flex h-10 w-10 items-center justify-center rounded-md transition-colors ${
- activeView === view
- ? "bg-accent text-accent-foreground"
- : "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"
- }`}
- >
- <Icon className="h-5 w-5" />
- </button>
- </TooltipTrigger>
- <TooltipContent side="right">{label}</TooltipContent>
- </Tooltip>
- ))}
- </div>
- </TooltipProvider>
- )
-}
-```
-
-- [ ] **Step 2: Install lucide-react**
-
-```bash
-npm install lucide-react
-```
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add src/components/layout/icon-sidebar.tsx package.json package-lock.json
-git commit -m "feat: add icon sidebar component"
-```
-
----
-
-### Task 8: Layout Shell — File Tree
-
-**Files:**
-- Create: `src/components/layout/file-tree.tsx`
-
-- [ ] **Step 1: Create file tree component**
-
-Create `src/components/layout/file-tree.tsx`:
-
-```tsx
-import { useState } from "react"
-import { ChevronRight, ChevronDown, File, Folder } from "lucide-react"
-import { ScrollArea } from "@/components/ui/scroll-area"
-import { useWikiStore } from "@/stores/wiki-store"
-import type { FileNode } from "@/types/wiki"
-
-function TreeNode({ node, depth }: { node: FileNode; depth: number }) {
- const [expanded, setExpanded] = useState(depth < 1)
- const selectedFile = useWikiStore((s) => s.selectedFile)
- const setSelectedFile = useWikiStore((s) => s.setSelectedFile)
-
- const isSelected = selectedFile === node.path
- const paddingLeft = 12 + depth * 16
-
- if (node.is_dir) {
- return (
- <div>
- <button
- onClick={() => setExpanded(!expanded)}
- className="flex w-full items-center gap-1 py-1 text-sm text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"
- style={{ paddingLeft }}
- >
- {expanded ? (
- <ChevronDown className="h-3.5 w-3.5 shrink-0" />
- ) : (
- <ChevronRight className="h-3.5 w-3.5 shrink-0" />
- )}
- <Folder className="h-3.5 w-3.5 shrink-0 text-blue-400" />
- <span className="truncate">{node.name}</span>
- </button>
- {expanded && node.children?.map((child) => (
- <TreeNode key={child.path} node={child} depth={depth + 1} />
- ))}
- </div>
- )
- }
-
- return (
- <button
- onClick={() => setSelectedFile(node.path)}
- className={`flex w-full items-center gap-1 py-1 text-sm ${
- isSelected
- ? "bg-accent text-accent-foreground"
- : "text-muted-foreground hover:bg-accent/50 hover:text-accent-foreground"
- }`}
- style={{ paddingLeft: paddingLeft + 14 }}
- >
- <File className="h-3.5 w-3.5 shrink-0" />
- <span className="truncate">{node.name}</span>
- </button>
- )
-}
-
-export function FileTree() {
- const fileTree = useWikiStore((s) => s.fileTree)
- const project = useWikiStore((s) => s.project)
-
- if (!project) {
- return (
- <div className="flex h-full items-center justify-center p-4 text-sm text-muted-foreground">
- No project open
- </div>
- )
- }
-
- return (
- <ScrollArea className="h-full">
- <div className="p-2">
- <div className="mb-2 px-2 text-xs font-semibold uppercase text-muted-foreground">
- {project.name}
- </div>
- {fileTree.map((node) => (
- <TreeNode key={node.path} node={node} depth={0} />
- ))}
- </div>
- </ScrollArea>
- )
-}
-```
-
-- [ ] **Step 2: Commit**
-
-```bash
-git add src/components/layout/file-tree.tsx
-git commit -m "feat: add file tree component"
-```
-
----
-
-### Task 9: Layout Shell — Content Area + Chat Bar
-
-**Files:**
-- Create: `src/components/layout/content-area.tsx`
-- Create: `src/components/layout/chat-bar.tsx`
-
-- [ ] **Step 1: Create chat bar placeholder**
-
-Create `src/components/layout/chat-bar.tsx`:
-
-```tsx
-import { MessageSquare, ChevronUp, ChevronDown } from "lucide-react"
-import { useWikiStore } from "@/stores/wiki-store"
-
-export function ChatBar() {
- const chatExpanded = useWikiStore((s) => s.chatExpanded)
- const setChatExpanded = useWikiStore((s) => s.setChatExpanded)
-
- return (
- <div className="border-t">
- <button
- onClick={() => setChatExpanded(!chatExpanded)}
- className="flex w-full items-center justify-between px-4 py-2 text-sm text-muted-foreground hover:bg-accent/50"
- >
- <span className="flex items-center gap-2">
- <MessageSquare className="h-4 w-4" />
- CHAT
- </span>
- {chatExpanded ? (
- <ChevronDown className="h-4 w-4" />
- ) : (
- <ChevronUp className="h-4 w-4" />
- )}
- </button>
- {chatExpanded && (
- <div className="flex h-64 flex-col border-t">
- <div className="flex-1 overflow-auto p-4">
- <p className="text-sm text-muted-foreground">
- Chat will be available in Phase 2 (LLM Integration).
- </p>
- </div>
- <div className="border-t p-3">
- <input
- type="text"
- placeholder="Type a message..."
- disabled
- className="w-full rounded-md border bg-muted/50 px-3 py-2 text-sm"
- />
- </div>
- </div>
- )}
- </div>
- )
-}
-```
-
-- [ ] **Step 2: Create content area**
-
-Create `src/components/layout/content-area.tsx`:
-
-```tsx
-import { useEffect } from "react"
-import { useWikiStore } from "@/stores/wiki-store"
-import { readFile } from "@/commands/fs"
-import { ChatBar } from "./chat-bar"
-
-export function ContentArea() {
- const selectedFile = useWikiStore((s) => s.selectedFile)
- const fileContent = useWikiStore((s) => s.fileContent)
- const setFileContent = useWikiStore((s) => s.setFileContent)
-
- useEffect(() => {
- if (!selectedFile) {
- setFileContent("")
- return
- }
- readFile(selectedFile)
- .then(setFileContent)
- .catch((err) => setFileContent(`Error loading file: ${err}`))
- }, [selectedFile, setFileContent])
-
- return (
- <div className="flex h-full flex-col">
- <div className="flex-1 overflow-auto">
- {selectedFile ? (
- <div className="p-6">
- <div className="mb-4 text-xs text-muted-foreground">
- {selectedFile}
- </div>
- <pre className="whitespace-pre-wrap font-mono text-sm">
- {fileContent}
- </pre>
- </div>
- ) : (
- <div className="flex h-full items-center justify-center text-muted-foreground">
- Select a file from the tree to view
- </div>
- )}
- </div>
- <ChatBar />
- </div>
- )
-}
-```
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add src/components/layout/content-area.tsx src/components/layout/chat-bar.tsx
-git commit -m "feat: add content area and collapsible chat bar"
-```
-
----
-
-### Task 10: Layout Shell — App Layout + Wiring
-
-**Files:**
-- Create: `src/components/layout/app-layout.tsx`
-- Create: `src/components/project/welcome-screen.tsx`
-- Create: `src/components/project/create-project-dialog.tsx`
-- Modify: `src/App.tsx`
-- Modify: `src/stores/wiki-store.ts` (export type)
-
-- [ ] **Step 1: Export WikiState type from store**
-
-Add to the end of `src/stores/wiki-store.ts`:
-
-```ts
-export type { WikiState }
-```
-
-- [ ] **Step 2: Create welcome screen**
-
-Create `src/components/project/welcome-screen.tsx`:
-
-```tsx
-import { FolderOpen, Plus } from "lucide-react"
-import { Button } from "@/components/ui/button"
-
-interface WelcomeScreenProps {
- onCreateProject: () => void
- onOpenProject: () => void
-}
-
-export function WelcomeScreen({ onCreateProject, onOpenProject }: WelcomeScreenProps) {
- return (
- <div className="flex h-full items-center justify-center bg-background">
- <div className="flex flex-col items-center gap-6">
- <h1 className="text-3xl font-bold">LLM Wiki</h1>
- <p className="text-muted-foreground">
- Build and maintain your personal knowledge base with LLMs
- </p>
- <div className="flex gap-3">
- <Button onClick={onCreateProject}>
- <Plus className="mr-2 h-4 w-4" />
- New Project
- </Button>
- <Button variant="outline" onClick={onOpenProject}>
- <FolderOpen className="mr-2 h-4 w-4" />
- Open Project
- </Button>
- </div>
- </div>
- </div>
- )
-}
-```
-
-- [ ] **Step 3: Create project dialog**
-
-Create `src/components/project/create-project-dialog.tsx`:
-
-```tsx
-import { useState } from "react"
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- DialogFooter,
-} from "@/components/ui/dialog"
-import { Button } from "@/components/ui/button"
-import { Input } from "@/components/ui/input"
-import { Label } from "@/components/ui/label"
-import { createProject } from "@/commands/fs"
-import type { WikiProject } from "@/types/wiki"
-
-interface CreateProjectDialogProps {
- open: boolean
- onOpenChange: (open: boolean) => void
- onCreated: (project: WikiProject) => void
-}
-
-export function CreateProjectDialog({
- open,
- onOpenChange,
- onCreated,
-}: CreateProjectDialogProps) {
- const [name, setName] = useState("")
- const [path, setPath] = useState("")
- const [error, setError] = useState("")
- const [creating, setCreating] = useState(false)
-
- async function handleCreate() {
- if (!name.trim() || !path.trim()) {
- setError("Name and path are required")
- return
- }
-
- setCreating(true)
- setError("")
-
- try {
- const project = await createProject(name.trim(), path.trim())
- onCreated(project)
- onOpenChange(false)
- setName("")
- setPath("")
- } catch (err) {
- setError(String(err))
- } finally {
- setCreating(false)
- }
- }
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Create New Wiki Project</DialogTitle>
- </DialogHeader>
- <div className="flex flex-col gap-4 py-4">
- <div className="flex flex-col gap-2">
- <Label htmlFor="name">Project Name</Label>
- <Input
- id="name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="my-research-wiki"
- />
- </div>
- <div className="flex flex-col gap-2">
- <Label htmlFor="path">Parent Directory</Label>
- <Input
- id="path"
- value={path}
- onChange={(e) => setPath(e.target.value)}
- placeholder="/Users/you/projects"
- />
- </div>
- {error && <p className="text-sm text-destructive">{error}</p>}
- </div>
- <DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)}>
- Cancel
- </Button>
- <Button onClick={handleCreate} disabled={creating}>
- {creating ? "Creating..." : "Create"}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
-```
-
-- [ ] **Step 4: Create app layout**
-
-Create `src/components/layout/app-layout.tsx`:
-
-```tsx
-import { useCallback, useEffect } from "react"
-import { useWikiStore } from "@/stores/wiki-store"
-import { listDirectory } from "@/commands/fs"
-import { IconSidebar } from "./icon-sidebar"
-import { FileTree } from "./file-tree"
-import { ContentArea } from "./content-area"
-
-export function AppLayout() {
- const project = useWikiStore((s) => s.project)
- const setFileTree = useWikiStore((s) => s.setFileTree)
-
- const loadFileTree = useCallback(async () => {
- if (!project) return
- try {
- const tree = await listDirectory(project.path)
- setFileTree(tree)
- } catch (err) {
- console.error("Failed to load file tree:", err)
- }
- }, [project, setFileTree])
-
- useEffect(() => {
- loadFileTree()
- }, [loadFileTree])
-
- return (
- <div className="flex h-screen bg-background text-foreground">
- <IconSidebar />
- <div className="flex flex-1 overflow-hidden">
- <div className="w-60 border-r">
- <FileTree />
- </div>
- <div className="flex-1">
- <ContentArea />
- </div>
- </div>
- </div>
- )
-}
-```
-
-- [ ] **Step 5: Wire up App.tsx**
-
-Replace `src/App.tsx`:
-
-```tsx
-import { useState } from "react"
-import { useWikiStore } from "@/stores/wiki-store"
-import { listDirectory, openProject } from "@/commands/fs"
-import { AppLayout } from "@/components/layout/app-layout"
-import { WelcomeScreen } from "@/components/project/welcome-screen"
-import { CreateProjectDialog } from "@/components/project/create-project-dialog"
-import type { WikiProject } from "@/types/wiki"
-
-function App() {
- const project = useWikiStore((s) => s.project)
- const setProject = useWikiStore((s) => s.setProject)
- const setFileTree = useWikiStore((s) => s.setFileTree)
- const [showCreateDialog, setShowCreateDialog] = useState(false)
-
- async function handleProjectOpened(proj: WikiProject) {
- setProject(proj)
- try {
- const tree = await listDirectory(proj.path)
- setFileTree(tree)
- } catch (err) {
- console.error("Failed to load file tree:", err)
- }
- }
-
- async function handleOpenProject() {
- const path = window.prompt("Enter the path to an existing wiki project:")
- if (!path) return
- try {
- const proj = await openProject(path)
- await handleProjectOpened(proj)
- } catch (err) {
- window.alert(`Failed to open project: ${err}`)
- }
- }
-
- if (!project) {
- return (
- <>
- <WelcomeScreen
- onCreateProject={() => setShowCreateDialog(true)}
- onOpenProject={handleOpenProject}
- />
- <CreateProjectDialog
- open={showCreateDialog}
- onOpenChange={setShowCreateDialog}
- onCreated={handleProjectOpened}
- />
- </>
- )
- }
-
- return <AppLayout />
-}
-
-export default App
-```
-
-- [ ] **Step 6: Verify the full layout**
-
-```bash
-npm run tauri dev
-```
-
-Expected: App opens with welcome screen. "New Project" opens dialog. After creating a project, the three-panel layout appears: icon sidebar on left, file tree showing the wiki directory structure, content area on right with collapsible Chat bar at bottom.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add src/App.tsx src/components/ src/stores/wiki-store.ts
-git commit -m "feat: wire up app layout with welcome screen, file tree, and content area"
-```
-
----
-
-### Task 11: Milkdown WYSIWYG Editor
-
-**Files:**
-- Create: `src/components/editor/wiki-editor.tsx`
-- Modify: `src/components/layout/content-area.tsx`
-
-- [ ] **Step 1: Install Milkdown dependencies**
-
-```bash
-npm install @milkdown/kit @milkdown/theme-nord @milkdown/react
-```
-
-- [ ] **Step 2: Create wiki editor component**
-
-Create `src/components/editor/wiki-editor.tsx`:
-
-```tsx
-import { useEffect } from "react"
-import { Editor, rootCtx, defaultValueCtx } from "@milkdown/kit/core"
-import { commonmark } from "@milkdown/kit/preset/commonmark"
-import { history } from "@milkdown/kit/plugin/history"
-import { listener, listenerCtx } from "@milkdown/kit/plugin/listener"
-import { nord } from "@milkdown/theme-nord"
-import { Milkdown, MilkdownProvider, useEditor } from "@milkdown/react"
-import "@milkdown/theme-nord/style.css"
-
-interface WikiEditorInnerProps {
- content: string
- onSave: (markdown: string) => void
-}
-
-function WikiEditorInner({ content, onSave }: WikiEditorInnerProps) {
- const { get } = useEditor((root) =>
- Editor.make()
- .config(nord)
- .config((ctx) => {
- ctx.set(rootCtx, root)
- ctx.set(defaultValueCtx, content)
- ctx.get(listenerCtx).markdownUpdated((_ctx, markdown) => {
- onSave(markdown)
- })
- })
- .use(commonmark)
- .use(history)
- .use(listener),
- [content]
- )
-
- useEffect(() => {
- // Editor recreated when content (dependency) changes
- }, [get])
-
- return <Milkdown />
-}
-
-interface WikiEditorProps {
- content: string
- onSave: (markdown: string) => void
-}
-
-export function WikiEditor({ content, onSave }: WikiEditorProps) {
- return (
- <MilkdownProvider>
- <div className="prose prose-invert max-w-none p-6">
- <WikiEditorInner content={content} onSave={onSave} />
- </div>
- </MilkdownProvider>
- )
-}
-```
-
-- [ ] **Step 3: Update content area to use WikiEditor for .md files**
-
-Replace `src/components/layout/content-area.tsx`:
-
-```tsx
-import { useEffect, useCallback, useRef } from "react"
-import { useWikiStore } from "@/stores/wiki-store"
-import { readFile, writeFile } from "@/commands/fs"
-import { WikiEditor } from "@/components/editor/wiki-editor"
-import { ChatBar } from "./chat-bar"
-
-export function ContentArea() {
- const selectedFile = useWikiStore((s) => s.selectedFile)
- const fileContent = useWikiStore((s) => s.fileContent)
- const setFileContent = useWikiStore((s) => s.setFileContent)
- const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
-
- useEffect(() => {
- if (!selectedFile) {
- setFileContent("")
- return
- }
- readFile(selectedFile)
- .then(setFileContent)
- .catch((err) => setFileContent(`Error loading file: ${err}`))
- }, [selectedFile, setFileContent])
-
- const handleSave = useCallback(
- (markdown: string) => {
- if (!selectedFile) return
- if (saveTimerRef.current) {
- clearTimeout(saveTimerRef.current)
- }
- saveTimerRef.current = setTimeout(() => {
- writeFile(selectedFile, markdown).catch((err) =>
- console.error("Failed to save:", err)
- )
- }, 1000)
- },
- [selectedFile]
- )
-
- useEffect(() => {
- return () => {
- if (saveTimerRef.current) {
- clearTimeout(saveTimerRef.current)
- }
- }
- }, [])
-
- const isMarkdown = selectedFile?.endsWith(".md")
-
- return (
- <div className="flex h-full flex-col">
- <div className="flex-1 overflow-auto">
- {selectedFile ? (
- isMarkdown ? (
- <WikiEditor
- key={selectedFile}
- content={fileContent}
- onSave={handleSave}
- />
- ) : (
- <div className="p-6">
- <div className="mb-4 text-xs text-muted-foreground">
- {selectedFile}
- </div>
- <pre className="whitespace-pre-wrap font-mono text-sm">
- {fileContent}
- </pre>
- </div>
- )
- ) : (
- <div className="flex h-full items-center justify-center text-muted-foreground">
- Select a file from the tree to view
- </div>
- )}
- </div>
- <ChatBar />
- </div>
- )
-}
-```
-
-- [ ] **Step 4: Verify editor works**
-
-```bash
-npm run tauri dev
-```
-
-Expected: Open a project, click on a `.md` file in the file tree. The Milkdown WYSIWYG editor renders the markdown with formatting. Edits auto-save after 1 second of inactivity.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add src/components/editor/ src/components/layout/content-area.tsx package.json package-lock.json
-git commit -m "feat: add Milkdown WYSIWYG markdown editor with auto-save"
-```
-
----
-
-### Task 12: Resizable Panels
-
-**Files:**
-- Modify: `src/components/layout/app-layout.tsx`
-- Modify: `src/components/layout/content-area.tsx`
-
-- [ ] **Step 1: Add resizable panel component from shadcn**
-
-```bash
-npx shadcn@latest add resizable
-```
-
-- [ ] **Step 2: Update app layout with resizable file tree**
-
-Replace `src/components/layout/app-layout.tsx`:
-
-```tsx
-import { useCallback, useEffect } from "react"
-import { useWikiStore } from "@/stores/wiki-store"
-import { listDirectory } from "@/commands/fs"
-import {
- ResizablePanelGroup,
- ResizablePanel,
- ResizableHandle,
-} from "@/components/ui/resizable"
-import { IconSidebar } from "./icon-sidebar"
-import { FileTree } from "./file-tree"
-import { ContentArea } from "./content-area"
-
-export function AppLayout() {
- const project = useWikiStore((s) => s.project)
- const setFileTree = useWikiStore((s) => s.setFileTree)
-
- const loadFileTree = useCallback(async () => {
- if (!project) return
- try {
- const tree = await listDirectory(project.path)
- setFileTree(tree)
- } catch (err) {
- console.error("Failed to load file tree:", err)
- }
- }, [project, setFileTree])
-
- useEffect(() => {
- loadFileTree()
- }, [loadFileTree])
-
- return (
- <div className="flex h-screen bg-background text-foreground">
- <IconSidebar />
- <ResizablePanelGroup direction="horizontal" className="flex-1">
- <ResizablePanel defaultSize={20} minSize={15} maxSize={40}>
- <FileTree />
- </ResizablePanel>
- <ResizableHandle withHandle />
- <ResizablePanel defaultSize={80}>
- <ContentArea />
- </ResizablePanel>
- </ResizablePanelGroup>
- </div>
- )
-}
-```
-
-- [ ] **Step 3: Update content area with resizable chat panel**
-
-Replace `src/components/layout/content-area.tsx`:
-
-```tsx
-import { useEffect, useCallback, useRef } from "react"
-import { useWikiStore } from "@/stores/wiki-store"
-import { readFile, writeFile } from "@/commands/fs"
-import { WikiEditor } from "@/components/editor/wiki-editor"
-import {
- ResizablePanelGroup,
- ResizablePanel,
- ResizableHandle,
-} from "@/components/ui/resizable"
-import { ChatBar } from "./chat-bar"
-
-export function ContentArea() {
- const selectedFile = useWikiStore((s) => s.selectedFile)
- const fileContent = useWikiStore((s) => s.fileContent)
- const setFileContent = useWikiStore((s) => s.setFileContent)
- const chatExpanded = useWikiStore((s) => s.chatExpanded)
- const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
-
- useEffect(() => {
- if (!selectedFile) {
- setFileContent("")
- return
- }
- readFile(selectedFile)
- .then(setFileContent)
- .catch((err) => setFileContent(`Error loading file: ${err}`))
- }, [selectedFile, setFileContent])
-
- const handleSave = useCallback(
- (markdown: string) => {
- if (!selectedFile) return
- if (saveTimerRef.current) {
- clearTimeout(saveTimerRef.current)
- }
- saveTimerRef.current = setTimeout(() => {
- writeFile(selectedFile, markdown).catch((err) =>
- console.error("Failed to save:", err)
- )
- }, 1000)
- },
- [selectedFile]
- )
-
- useEffect(() => {
- return () => {
- if (saveTimerRef.current) {
- clearTimeout(saveTimerRef.current)
- }
- }
- }, [])
-
- const isMarkdown = selectedFile?.endsWith(".md")
-
- const editorContent = (
- <div className="h-full overflow-auto">
- {selectedFile ? (
- isMarkdown ? (
- <WikiEditor
- key={selectedFile}
- content={fileContent}
- onSave={handleSave}
- />
- ) : (
- <div className="p-6">
- <div className="mb-4 text-xs text-muted-foreground">
- {selectedFile}
- </div>
- <pre className="whitespace-pre-wrap font-mono text-sm">
- {fileContent}
- </pre>
- </div>
- )
- ) : (
- <div className="flex h-full items-center justify-center text-muted-foreground">
- Select a file from the tree to view
- </div>
- )}
- </div>
- )
-
- if (!chatExpanded) {
- return (
- <div className="flex h-full flex-col">
- <div className="flex-1 overflow-hidden">{editorContent}</div>
- <ChatBar />
- </div>
- )
- }
-
- return (
- <div className="flex h-full flex-col">
- <ResizablePanelGroup direction="vertical" className="flex-1">
- <ResizablePanel defaultSize={60} minSize={30}>
- {editorContent}
- </ResizablePanel>
- <ResizableHandle withHandle />
- <ResizablePanel defaultSize={40} minSize={20}>
- <ChatBar />
- </ResizablePanel>
- </ResizablePanelGroup>
- </div>
- )
-}
-```
-
-- [ ] **Step 4: Update ChatBar to not self-manage expanded state**
-
-Replace `src/components/layout/chat-bar.tsx`:
-
-```tsx
-import { MessageSquare, ChevronUp, ChevronDown } from "lucide-react"
-import { useWikiStore } from "@/stores/wiki-store"
-
-export function ChatBar() {
- const chatExpanded = useWikiStore((s) => s.chatExpanded)
- const setChatExpanded = useWikiStore((s) => s.setChatExpanded)
-
- if (!chatExpanded) {
- return (
- <button
- onClick={() => setChatExpanded(true)}
- className="flex w-full items-center justify-between border-t px-4 py-2 text-sm text-muted-foreground hover:bg-accent/50"
- >
- <span className="flex items-center gap-2">
- <MessageSquare className="h-4 w-4" />
- CHAT
- </span>
- <ChevronUp className="h-4 w-4" />
- </button>
- )
- }
-
- return (
- <div className="flex h-full flex-col">
- <button
- onClick={() => setChatExpanded(false)}
- className="flex w-full items-center justify-between border-b px-4 py-2 text-sm text-muted-foreground hover:bg-accent/50"
- >
- <span className="flex items-center gap-2">
- <MessageSquare className="h-4 w-4" />
- CHAT
- </span>
- <ChevronDown className="h-4 w-4" />
- </button>
- <div className="flex-1 overflow-auto p-4">
- <p className="text-sm text-muted-foreground">
- Chat will be available in Phase 2 (LLM Integration).
- </p>
- </div>
- <div className="border-t p-3">
- <input
- type="text"
- placeholder="Type a message..."
- disabled
- className="w-full rounded-md border bg-muted/50 px-3 py-2 text-sm"
- />
- </div>
- </div>
- )
-}
-```
-
-- [ ] **Step 5: Verify resizable panels**
-
-```bash
-npm run tauri dev
-```
-
-Expected: File tree panel is resizable by dragging the handle. Chat panel expands with a resizable divider between content and chat. Collapsing chat returns to the thin bar.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add src/components/layout/ src/components/ui/ package.json package-lock.json
-git commit -m "feat: add resizable panels for file tree and chat"
-```
-
----
-
-### Task 13: Final Verification + Cleanup
-
-**Files:**
-- Modify: `src/index.css` (if needed)
-- Modify: `index.html` (window title)
-
-- [ ] **Step 1: Set window title**
-
-In `src-tauri/tauri.conf.json`, find `"title"` and set to `"LLM Wiki"`.
-
-- [ ] **Step 2: Update index.html title**
-
-Change the `<title>` tag in `index.html` to `LLM Wiki`.
-
-- [ ] **Step 3: Full end-to-end test**
-
-```bash
-npm run tauri dev
-```
-
-Verify the following manually:
-1. App opens with welcome screen showing "LLM Wiki" title
-2. Click "New Project" → dialog appears → enter name and path → project is created
-3. File tree shows: `purpose.md`, `schema.md`, `raw/`, `wiki/` with subdirectories
-4. Click on `wiki/index.md` → Milkdown editor renders the markdown
-5. Edit content → wait 1 second → file is auto-saved (verify by re-opening)
-6. Click `schema.md` → content switches to schema
-7. File tree is resizable by dragging the handle
-8. Chat bar at bottom → click to expand → resizable → click to collapse
-9. Icon sidebar highlights the active view when clicked
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add -A
-git commit -m "feat: complete Phase 1 foundation — layout, file ops, editor"
-```
-
----
-
-## Phase 1 Deliverables
-
-After completing all tasks, you will have:
-
-- ✅ Tauri v2 desktop app running on Mac/Linux/Windows
-- ✅ VS Code-style layout: icon sidebar + resizable file tree + content area + collapsible chat
-- ✅ Rust backend: file read/write/list, project create/open
-- ✅ Wiki project creation with full directory structure (raw/, wiki/, schema.md, purpose.md)
-- ✅ Milkdown WYSIWYG Markdown editor with auto-save
-- ✅ File tree navigation with folder expand/collapse
-
-## What's Next
-
-**Phase 2: LLM Integration** will add:
-- Rust-side LLM Router (OpenAI, Anthropic, Google, Ollama)
-- Chat UI in the collapsible panel
-- Basic single-source interactive ingest flow
-- Schema and purpose.md reading for LLM context
diff --git a/docs/superpowers/plans/2026-04-05-llm-wiki-phase2-llm-integration.md b/docs/superpowers/plans/2026-04-05-llm-wiki-phase2-llm-integration.md
deleted file mode 100644
index 6b1e65f2..00000000
--- a/docs/superpowers/plans/2026-04-05-llm-wiki-phase2-llm-integration.md
+++ /dev/null
@@ -1,1132 +0,0 @@
-# LLM Wiki Phase 2: LLM Integration — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Connect the app to LLM providers and implement the interactive Ingest flow — the core operation that turns raw sources into structured wiki pages.
-
-**Architecture:** LLM calls happen from the TypeScript frontend using streaming fetch. This is a desktop app (no server exposure), so API keys in the webview are safe. The LLM reads source content + schema.md + purpose.md + existing wiki pages, then writes multiple wiki files via existing Rust commands. Chat UI displays the conversation in real-time with streaming.
-
-**Tech Stack:** Streaming fetch (no SDK dependencies), Zustand for chat state, existing Tauri IPC for file operations
-
----
-
-## Phase Overview
-
-| Phase | Scope | Status |
-|-------|-------|--------|
-| Phase 1: Foundation | Tauri scaffold, file system ops, layout shell, wiki browser, Milkdown editor | **Done** |
-| **Phase 2: LLM Integration** | LLM client, Chat UI, interactive Ingest flow | **Current** |
-| Phase 3: Search & Query | tantivy search, query pipeline, Save to Wiki | Planned |
-| Phase 4: Lint & Graph | Lint engine, graph view, lint dashboard | Planned |
-| Phase 5: Polish | i18n, settings persistence, templates system | Planned |
-| Phase 6: Extension | Browser clipper, batch ingest, image processing | Planned |
-
----
-
-## File Structure
-
-```
-src/
-├── lib/
-│ ├── llm-client.ts # Unified LLM streaming client (OpenAI/Anthropic/Google/Ollama/Custom)
-│ └── llm-providers.ts # Provider-specific config (endpoints, headers, body format)
-├── stores/
-│ └── chat-store.ts # Chat state: messages, streaming status, current mode (ingest/query)
-├── components/
-│ ├── chat/
-│ │ ├── chat-panel.tsx # Full chat panel (message list + input)
-│ │ ├── chat-message.tsx # Single message bubble (user/assistant/system)
-│ │ └── chat-input.tsx # Input box with send button + ingest trigger
-│ └── sources/
-│ └── sources-view.tsx # (Modify) Add "Ingest" button per source
-├── lib/
-│ └── ingest.ts # Ingest orchestrator: reads source → builds LLM prompt → parses response → writes files
-```
-
----
-
-### Task 1: LLM Provider Config and Streaming Client
-
-**Files:**
-- Create: `src/lib/llm-providers.ts`
-- Create: `src/lib/llm-client.ts`
-
-- [ ] **Step 1: Create provider configuration**
-
-Create `src/lib/llm-providers.ts`:
-
-```ts
-import type { LlmConfig } from "@/stores/wiki-store"
-
-interface ProviderConfig {
- url: string
- headers: Record<string, string>
- buildBody: (messages: ChatMessage[], model: string) => unknown
- parseStream: (line: string) => string | null
-}
-
-export interface ChatMessage {
- role: "system" | "user" | "assistant"
- content: string
-}
-
-function buildOpenAIBody(messages: ChatMessage[], model: string) {
- return { model, messages, stream: true }
-}
-
-function parseOpenAIStream(line: string): string | null {
- if (!line.startsWith("data: ")) return null
- const data = line.slice(6).trim()
- if (data === "[DONE]") return null
- try {
- const parsed = JSON.parse(data)
- return parsed.choices?.[0]?.delta?.content ?? null
- } catch {
- return null
- }
-}
-
-function buildAnthropicBody(messages: ChatMessage[], model: string) {
- const system = messages.find((m) => m.role === "system")?.content ?? ""
- const nonSystem = messages.filter((m) => m.role !== "system")
- return {
- model,
- max_tokens: 8192,
- system,
- messages: nonSystem,
- stream: true,
- }
-}
-
-function parseAnthropicStream(line: string): string | null {
- if (!line.startsWith("data: ")) return null
- const data = line.slice(6).trim()
- try {
- const parsed = JSON.parse(data)
- if (parsed.type === "content_block_delta") {
- return parsed.delta?.text ?? null
- }
- return null
- } catch {
- return null
- }
-}
-
-function buildGoogleBody(messages: ChatMessage[], model: string) {
- const system = messages.find((m) => m.role === "system")?.content ?? ""
- const nonSystem = messages.filter((m) => m.role !== "system")
- return {
- contents: nonSystem.map((m) => ({
- role: m.role === "assistant" ? "model" : "user",
- parts: [{ text: m.content }],
- })),
- systemInstruction: system ? { parts: [{ text: system }] } : undefined,
- }
-}
-
-function parseGoogleStream(line: string): string | null {
- if (!line.startsWith("data: ")) return null
- const data = line.slice(6).trim()
- try {
- const parsed = JSON.parse(data)
- return parsed.candidates?.[0]?.content?.parts?.[0]?.text ?? null
- } catch {
- return null
- }
-}
-
-export function getProviderConfig(config: LlmConfig): ProviderConfig {
- switch (config.provider) {
- case "openai":
- return {
- url: "https://api.openai.com/v1/chat/completions",
- headers: {
- Authorization: `Bearer ${config.apiKey}`,
- "Content-Type": "application/json",
- },
- buildBody: buildOpenAIBody,
- parseStream: parseOpenAIStream,
- }
- case "anthropic":
- return {
- url: "https://api.anthropic.com/v1/messages",
- headers: {
- "x-api-key": config.apiKey,
- "anthropic-version": "2023-06-01",
- "anthropic-dangerous-direct-browser-access": "true",
- "Content-Type": "application/json",
- },
- buildBody: buildAnthropicBody,
- parseStream: parseAnthropicStream,
- }
- case "google":
- return {
- url: `https://generativelanguage.googleapis.com/v1beta/models/${config.model}:streamGenerateContent?alt=sse&key=${config.apiKey}`,
- headers: { "Content-Type": "application/json" },
- buildBody: buildGoogleBody,
- parseStream: parseGoogleStream,
- }
- case "ollama":
- return {
- url: `${config.ollamaUrl}/v1/chat/completions`,
- headers: { "Content-Type": "application/json" },
- buildBody: buildOpenAIBody,
- parseStream: parseOpenAIStream,
- }
- case "custom":
- return {
- url: config.customEndpoint.endsWith("/chat/completions")
- ? config.customEndpoint
- : `${config.customEndpoint.replace(/\/$/, "")}/chat/completions`,
- headers: {
- ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}),
- "Content-Type": "application/json",
- },
- buildBody: buildOpenAIBody,
- parseStream: parseOpenAIStream,
- }
- }
-}
-```
-
-- [ ] **Step 2: Create streaming LLM client**
-
-Create `src/lib/llm-client.ts`:
-
-```ts
-import type { LlmConfig } from "@/stores/wiki-store"
-import { getProviderConfig, type ChatMessage } from "./llm-providers"
-
-export type { ChatMessage } from "./llm-providers"
-
-export interface StreamCallbacks {
- onToken: (token: string) => void
- onDone: (fullText: string) => void
- onError: (error: string) => void
-}
-
-export async function streamChat(
- config: LlmConfig,
- messages: ChatMessage[],
- callbacks: StreamCallbacks,
- signal?: AbortSignal
-): Promise<void> {
- if (!config.model) {
- callbacks.onError("No model selected. Please configure a model in Settings.")
- return
- }
-
- const provider = getProviderConfig(config)
- const body = provider.buildBody(messages, config.model)
-
- let response: Response
- try {
- response = await fetch(provider.url, {
- method: "POST",
- headers: provider.headers,
- body: JSON.stringify(body),
- signal,
- })
- } catch (err) {
- callbacks.onError(`Network error: ${err}`)
- return
- }
-
- if (!response.ok) {
- const errorText = await response.text().catch(() => "Unknown error")
- callbacks.onError(`API error (${response.status}): ${errorText}`)
- return
- }
-
- const reader = response.body?.getReader()
- if (!reader) {
- callbacks.onError("No response body")
- return
- }
-
- const decoder = new TextDecoder()
- let fullText = ""
- let buffer = ""
-
- try {
- while (true) {
- const { done, value } = await reader.read()
- if (done) break
-
- buffer += decoder.decode(value, { stream: true })
- const lines = buffer.split("\n")
- buffer = lines.pop() ?? ""
-
- for (const line of lines) {
- const trimmed = line.trim()
- if (!trimmed) continue
- const token = provider.parseStream(trimmed)
- if (token) {
- fullText += token
- callbacks.onToken(token)
- }
- }
- }
- } catch (err) {
- if (signal?.aborted) return
- callbacks.onError(`Stream error: ${err}`)
- return
- }
-
- callbacks.onDone(fullText)
-}
-```
-
-- [ ] **Step 3: Commit**
-
-```bash
-git add src/lib/llm-client.ts src/lib/llm-providers.ts
-git commit -m "feat: add unified streaming LLM client for all providers"
-```
-
----
-
-### Task 2: Chat Store
-
-**Files:**
-- Create: `src/stores/chat-store.ts`
-
-- [ ] **Step 1: Create chat store**
-
-Create `src/stores/chat-store.ts`:
-
-```ts
-import { create } from "zustand"
-import type { ChatMessage } from "@/lib/llm-client"
-
-export interface DisplayMessage {
- id: string
- role: "user" | "assistant" | "system"
- content: string
- timestamp: number
-}
-
-interface ChatState {
- messages: DisplayMessage[]
- isStreaming: boolean
- streamingContent: string
- mode: "chat" | "ingest"
- ingestSource: string | null
-
- addMessage: (role: DisplayMessage["role"], content: string) => void
- setStreaming: (streaming: boolean) => void
- appendStreamToken: (token: string) => void
- finalizeStream: (content: string) => void
- setMode: (mode: ChatState["mode"]) => void
- setIngestSource: (path: string | null) => void
- clearMessages: () => void
-}
-
-let messageCounter = 0
-
-export const useChatStore = create<ChatState>((set) => ({
- messages: [],
- isStreaming: false,
- streamingContent: "",
- mode: "chat",
- ingestSource: null,
-
- addMessage: (role, content) =>
- set((state) => ({
- messages: [
- ...state.messages,
- {
- id: `msg-${++messageCounter}`,
- role,
- content,
- timestamp: Date.now(),
- },
- ],
- })),
-
- setStreaming: (isStreaming) =>
- set({ isStreaming, streamingContent: isStreaming ? "" : "" }),
-
- appendStreamToken: (token) =>
- set((state) => ({
- streamingContent: state.streamingContent + token,
- })),
-
- finalizeStream: (content) =>
- set((state) => ({
- isStreaming: false,
- streamingContent: "",
- messages: [
- ...state.messages,
- {
- id: `msg-${++messageCounter}`,
- role: "assistant",
- content,
- timestamp: Date.now(),
- },
- ],
- })),
-
- setMode: (mode) => set({ mode }),
- setIngestSource: (ingestSource) => set({ ingestSource }),
- clearMessages: () => set({ messages: [], streamingContent: "" }),
-}))
-
-export function chatMessagesToLLM(messages: DisplayMessage[]): ChatMessage[] {
- return messages.map((m) => ({ role: m.role, content: m.content }))
-}
-```
-
-- [ ] **Step 2: Commit**
-
-```bash
-git add src/stores/chat-store.ts
-git commit -m "feat: add chat store for message state and streaming"
-```
-
----
-
-### Task 3: Chat UI Components
-
-**Files:**
-- Create: `src/components/chat/chat-message.tsx`
-- Create: `src/components/chat/chat-input.tsx`
-- Create: `src/components/chat/chat-panel.tsx`
-- Modify: `src/components/layout/chat-bar.tsx`
-
-- [ ] **Step 1: Create chat message component**
-
-Create `src/components/chat/chat-message.tsx`:
-
-```tsx
-import { Bot, User } from "lucide-react"
-import type { DisplayMessage } from "@/stores/chat-store"
-
-export function ChatMessage({ message }: { message: DisplayMessage }) {
- const isUser = message.role === "user"
-
- return (
- <div className={`flex gap-3 ${isUser ? "flex-row-reverse" : ""}`}>
- <div
- className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full ${
- isUser ? "bg-primary text-primary-foreground" : "bg-muted"
- }`}
- >
- {isUser ? <User className="h-4 w-4" /> : <Bot className="h-4 w-4" />}
- </div>
- <div
- className={`max-w-[80%] rounded-lg px-3 py-2 text-sm ${
- isUser
- ? "bg-primary text-primary-foreground"
- : "bg-muted"
- }`}
- >
- <p className="whitespace-pre-wrap">{message.content}</p>
- </div>
- </div>
- )
-}
-
-export function StreamingMessage({ content }: { content: string }) {
- return (
- <div className="flex gap-3">
- <div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-muted">
- <Bot className="h-4 w-4" />
- </div>
- <div className="max-w-[80%] rounded-lg bg-muted px-3 py-2 text-sm">
- <p className="whitespace-pre-wrap">{content}<span className="animate-pulse">▊</span></p>
- </div>
- </div>
- )
-}
-```
-
-- [ ] **Step 2: Create chat input component**
-
-Create `src/components/chat/chat-input.tsx`:
-
-```tsx
-import { useState, useRef } from "react"
-import { Send, Square } from "lucide-react"
-import { Button } from "@/components/ui/button"
-
-interface ChatInputProps {
- onSend: (message: string) => void
- onStop: () => void
- isStreaming: boolean
- placeholder?: string
-}
-
-export function ChatInput({ onSend, onStop, isStreaming, placeholder }: ChatInputProps) {
- const [input, setInput] = useState("")
- const textareaRef = useRef<HTMLTextAreaElement>(null)
-
- function handleSend() {
- const trimmed = input.trim()
- if (!trimmed || isStreaming) return
- onSend(trimmed)
- setInput("")
- if (textareaRef.current) {
- textareaRef.current.style.height = "auto"
- }
- }
-
- function handleKeyDown(e: React.KeyboardEvent) {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault()
- handleSend()
- }
- }
-
- function handleInput(e: React.ChangeEvent<HTMLTextAreaElement>) {
- setInput(e.target.value)
- const el = e.target
- el.style.height = "auto"
- el.style.height = Math.min(el.scrollHeight, 120) + "px"
- }
-
- return (
- <div className="flex items-end gap-2 border-t p-3">
- <textarea
- ref={textareaRef}
- value={input}
- onChange={handleInput}
- onKeyDown={handleKeyDown}
- placeholder={placeholder ?? "Type a message..."}
- rows={1}
- className="flex-1 resize-none rounded-md border bg-background px-3 py-2 text-sm outline-none placeholder:text-muted-foreground focus:ring-1 focus:ring-ring"
- />
- {isStreaming ? (
- <Button size="icon" variant="destructive" onClick={onStop}>
- <Square className="h-4 w-4" />
- </Button>
- ) : (
- <Button size="icon" onClick={handleSend} disabled={!input.trim()}>
- <Send className="h-4 w-4" />
- </Button>
- )}
- </div>
- )
-}
-```
-
-- [ ] **Step 3: Create chat panel**
-
-Create `src/components/chat/chat-panel.tsx`:
-
-```tsx
-import { useEffect, useRef } from "react"
-import { ScrollArea } from "@/components/ui/scroll-area"
-import { useChatStore } from "@/stores/chat-store"
-import { useWikiStore } from "@/stores/wiki-store"
-import { streamChat, type ChatMessage } from "@/lib/llm-client"
-import { chatMessagesToLLM } from "@/stores/chat-store"
-import { ChatMessage as ChatMessageComponent, StreamingMessage } from "./chat-message"
-import { ChatInput } from "./chat-input"
-
-let abortController: AbortController | null = null
-
-export function ChatPanel() {
- const messages = useChatStore((s) => s.messages)
- const isStreaming = useChatStore((s) => s.isStreaming)
- const streamingContent = useChatStore((s) => s.streamingContent)
- const addMessage = useChatStore((s) => s.addMessage)
- const setStreaming = useChatStore((s) => s.setStreaming)
- const appendStreamToken = useChatStore((s) => s.appendStreamToken)
- const finalizeStream = useChatStore((s) => s.finalizeStream)
- const llmConfig = useWikiStore((s) => s.llmConfig)
- const scrollRef = useRef<HTMLDivElement>(null)
-
- useEffect(() => {
- if (scrollRef.current) {
- scrollRef.current.scrollTop = scrollRef.current.scrollHeight
- }
- }, [messages, streamingContent])
-
- async function handleSend(text: string) {
- addMessage("user", text)
-
- const allMessages: ChatMessage[] = [
- ...chatMessagesToLLM(useChatStore.getState().messages),
- ]
-
- setStreaming(true)
- abortController = new AbortController()
-
- await streamChat(llmConfig, allMessages, {
- onToken: appendStreamToken,
- onDone: finalizeStream,
- onError: (err) => {
- setStreaming(false)
- addMessage("assistant", `Error: ${err}`)
- },
- }, abortController.signal)
- }
-
- function handleStop() {
- abortController?.abort()
- const content = useChatStore.getState().streamingContent
- if (content) {
- finalizeStream(content)
- } else {
- setStreaming(false)
- }
- }
-
- return (
- <div className="flex h-full flex-col">
- <ScrollArea className="flex-1" ref={scrollRef}>
- <div className="flex flex-col gap-3 p-4">
- {messages.length === 0 && !isStreaming && (
- <p className="text-center text-sm text-muted-foreground">
- Ask a question or start an ingest to begin.
- </p>
- )}
- {messages.map((msg) => (
- <ChatMessageComponent key={msg.id} message={msg} />
- ))}
- {isStreaming && streamingContent && (
- <StreamingMessage content={streamingContent} />
- )}
- </div>
- </ScrollArea>
- <ChatInput
- onSend={handleSend}
- onStop={handleStop}
- isStreaming={isStreaming}
- placeholder="Ask about your wiki..."
- />
- </div>
- )
-}
-```
-
-- [ ] **Step 4: Replace chat-bar.tsx to use ChatPanel**
-
-Replace `src/components/layout/chat-bar.tsx`:
-
-```tsx
-import { MessageSquare, ChevronUp, ChevronDown } from "lucide-react"
-import { useWikiStore } from "@/stores/wiki-store"
-import { ChatPanel } from "@/components/chat/chat-panel"
-
-export function ChatBar() {
- const chatExpanded = useWikiStore((s) => s.chatExpanded)
- const setChatExpanded = useWikiStore((s) => s.setChatExpanded)
-
- if (!chatExpanded) {
- return (
- <button
- onClick={() => setChatExpanded(true)}
- className="flex w-full items-center justify-between border-t px-4 py-2 text-sm text-muted-foreground hover:bg-accent/50"
- >
- <span className="flex items-center gap-2">
- <MessageSquare className="h-4 w-4" />
- CHAT
- </span>
- <ChevronUp className="h-4 w-4" />
- </button>
- )
- }
-
- return (
- <div className="flex h-full flex-col">
- <button
- onClick={() => setChatExpanded(false)}
- className="flex w-full items-center justify-between border-b px-4 py-2 text-sm text-muted-foreground hover:bg-accent/50"
- >
- <span className="flex items-center gap-2">
- <MessageSquare className="h-4 w-4" />
- CHAT
- </span>
- <ChevronDown className="h-4 w-4" />
- </button>
- <div className="flex-1 overflow-hidden">
- <ChatPanel />
- </div>
- </div>
- )
-}
-```
-
-- [ ] **Step 5: Verify build**
-
-```bash
-cd /Users/nash_su/projects/llm_wiki && npx vite build
-```
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add src/components/chat/ src/components/layout/chat-bar.tsx
-git commit -m "feat: add chat UI with streaming message display"
-```
-
----
-
-### Task 4: Ingest Orchestrator
-
-**Files:**
-- Create: `src/lib/ingest.ts`
-
-The ingest orchestrator reads the source file, builds a prompt that includes schema.md, purpose.md, and existing index.md, sends it to the LLM, parses the structured response, and writes multiple wiki files.
-
-- [ ] **Step 1: Create ingest orchestrator**
-
-Create `src/lib/ingest.ts`:
-
-```ts
-import { readFile, writeFile } from "@/commands/fs"
-import { streamChat, type ChatMessage } from "@/lib/llm-client"
-import type { LlmConfig } from "@/stores/wiki-store"
-import { useChatStore } from "@/stores/chat-store"
-
-export async function startIngest(
- projectPath: string,
- sourcePath: string,
- llmConfig: LlmConfig,
- signal?: AbortSignal
-): Promise<void> {
- const store = useChatStore.getState()
- store.setMode("ingest")
- store.setIngestSource(sourcePath)
- store.clearMessages()
-
- // Read required context files
- const sourceContent = await readFile(sourcePath)
- const schema = await readFile(`${projectPath}/schema.md`).catch(() => "")
- const purpose = await readFile(`${projectPath}/purpose.md`).catch(() => "")
- const index = await readFile(`${projectPath}/wiki/index.md`).catch(() => "")
- const log = await readFile(`${projectPath}/wiki/log.md`).catch(() => "")
-
- const fileName = sourcePath.split("/").pop() ?? "unknown"
-
- const systemPrompt = buildIngestSystemPrompt(schema, purpose, index)
- const userPrompt = buildIngestUserPrompt(fileName, sourceContent)
-
- store.addMessage("system", `Starting ingest of: ${fileName}`)
-
- const messages: ChatMessage[] = [
- { role: "system", content: systemPrompt },
- { role: "user", content: userPrompt },
- ]
-
- // Phase 1: LLM reads and presents key takeaways
- store.setStreaming(true)
-
- await streamChat(llmConfig, messages, {
- onToken: store.appendStreamToken,
- onDone: (fullText) => {
- store.finalizeStream(fullText)
- },
- onError: (err) => {
- store.setStreaming(false)
- store.addMessage("assistant", `Error during ingest: ${err}`)
- },
- }, signal)
-}
-
-export async function executeIngestWrites(
- projectPath: string,
- llmConfig: LlmConfig,
- userGuidance: string,
- signal?: AbortSignal
-): Promise<string[]> {
- const store = useChatStore.getState()
-
- store.addMessage("user", userGuidance)
-
- const schema = await readFile(`${projectPath}/schema.md`).catch(() => "")
- const index = await readFile(`${projectPath}/wiki/index.md`).catch(() => "")
-
- const writePrompt = buildWritePrompt(schema, index)
-
- const allMessages: ChatMessage[] = [
- ...store.messages
- .filter((m) => m.role !== "system")
- .map((m) => ({ role: m.role as "user" | "assistant", content: m.content })),
- { role: "user", content: writePrompt + "\n\n" + userGuidance },
- ]
-
- // Add system message
- allMessages.unshift({
- role: "system",
- content: `You are a wiki maintainer. Based on the discussion above, now write the wiki pages. Output each file in this exact format:
-
----FILE: wiki/sources/filename.md---
-(file content here)
----END FILE---
-
----FILE: wiki/entities/name.md---
-(file content here)
----END FILE---
-
-Continue for all files that need to be created or updated. Include:
-1. A source summary page in wiki/sources/
-2. Entity pages in wiki/entities/ for key entities mentioned
-3. Concept pages in wiki/concepts/ for key concepts
-4. Updated wiki/index.md with new entries
-5. Appended entry to wiki/log.md
-
-Use YAML frontmatter on each page. Use [[wikilink]] syntax for cross-references.`,
- })
-
- store.setStreaming(true)
- let fullResponse = ""
-
- await streamChat(llmConfig, allMessages, {
- onToken: (token) => {
- fullResponse += token
- store.appendStreamToken(token)
- },
- onDone: (text) => {
- fullResponse = text
- store.finalizeStream(text)
- },
- onError: (err) => {
- store.setStreaming(false)
- store.addMessage("assistant", `Error writing wiki: ${err}`)
- },
- }, signal)
-
- // Parse and write files
- const files = parseFileBlocks(fullResponse)
- const writtenFiles: string[] = []
-
- for (const file of files) {
- const fullPath = `${projectPath}/${file.path}`
- try {
- if (file.path === "wiki/log.md") {
- // Append to log instead of overwriting
- const existingLog = await readFile(fullPath).catch(() => "")
- await writeFile(fullPath, existingLog + "\n" + file.content)
- } else if (file.path === "wiki/index.md") {
- // For index, overwrite with the new version
- await writeFile(fullPath, file.content)
- } else {
- await writeFile(fullPath, file.content)
- }
- writtenFiles.push(file.path)
- } catch (err) {
- console.error(`Failed to write ${file.path}:`, err)
- }
- }
-
- if (writtenFiles.length > 0) {
- store.addMessage("system", `✓ Updated ${writtenFiles.length} files:\n${writtenFiles.map((f) => ` - ${f}`).join("\n")}`)
- }
-
- return writtenFiles
-}
-
-interface FileBlock {
- path: string
- content: string
-}
-
-function parseFileBlocks(text: string): FileBlock[] {
- const blocks: FileBlock[] = []
- const regex = /---FILE:\s*(.+?)\s*---\n([\s\S]*?)---END FILE---/g
- let match: RegExpExecArray | null
-
- while ((match = regex.exec(text)) !== null) {
- blocks.push({
- path: match[1].trim(),
- content: match[2].trim() + "\n",
- })
- }
-
- return blocks
-}
-
-function buildIngestSystemPrompt(schema: string, purpose: string, index: string): string {
- return `You are an expert knowledge base assistant. You help the user build and maintain a personal wiki.
-
-Your job right now: Read a new source document and present its key takeaways to the user. Be concise but thorough. Identify:
-1. Key entities (people, organizations, products, datasets)
-2. Key concepts (theories, methods, techniques, phenomena)
-3. Main arguments or findings
-4. How this relates to existing wiki content (if any)
-5. Any contradictions with existing knowledge
-
-After presenting takeaways, wait for the user to guide you on what to emphasize, what to ignore, and what connections to make.
-
-${purpose ? `## Wiki Purpose\n${purpose}\n` : ""}
-${schema ? `## Wiki Schema\n${schema}\n` : ""}
-${index ? `## Current Wiki Index\n${index}\n` : ""}`
-}
-
-function buildIngestUserPrompt(fileName: string, content: string): string {
- const truncated = content.length > 50000 ? content.slice(0, 50000) + "\n\n[...truncated...]" : content
- return `Please read this source document and present the key takeaways:\n\n**Source:** ${fileName}\n\n---\n\n${truncated}`
-}
-
-function buildWritePrompt(schema: string, index: string): string {
- return `Now please write the wiki pages based on our discussion. Follow the schema conventions for page types, naming, and frontmatter.
-
-Current index for reference (to avoid duplicates and maintain consistency):
-${index}
-
-Remember to use [[wikilink]] syntax for cross-references between pages.`
-}
-```
-
-- [ ] **Step 2: Commit**
-
-```bash
-git add src/lib/ingest.ts
-git commit -m "feat: add ingest orchestrator with LLM-driven wiki page generation"
-```
-
----
-
-### Task 5: Wire Ingest into Sources View and Chat
-
-**Files:**
-- Modify: `src/components/sources/sources-view.tsx`
-- Modify: `src/components/chat/chat-panel.tsx`
-- Modify: `src/stores/wiki-store.ts` (export LlmConfig type)
-
-- [ ] **Step 1: Export LlmConfig type from wiki-store**
-
-Add to the end of `src/stores/wiki-store.ts`:
-
-```ts
-export type { LlmConfig }
-```
-
-- [ ] **Step 2: Add Ingest button to sources view**
-
-In `src/components/sources/sources-view.tsx`, add an ingest button per source. Import the necessary modules and modify the source list item to include an "Ingest" button:
-
-Add imports:
-```tsx
-import { Plus, FileText, RefreshCw, BookOpen } from "lucide-react"
-import { useChatStore } from "@/stores/chat-store"
-import { useWikiStore } from "@/stores/wiki-store"
-import { startIngest } from "@/lib/ingest"
-```
-
-Add ingest handler inside the `SourcesView` component:
-```tsx
-const llmConfig = useWikiStore((s) => s.llmConfig)
-const setChatExpanded = useWikiStore((s) => s.setChatExpanded)
-
-async function handleIngest(source: FileNode) {
- if (!project) return
- setChatExpanded(true)
- await startIngest(project.path, source.path, llmConfig)
-}
-```
-
-Update the source list item to add an ingest button next to each file:
-```tsx
-<div className="flex w-full items-center gap-2">
- <button
- onClick={() => handleOpenSource(source)}
- className="flex min-w-0 flex-1 items-center gap-2 text-left"
- >
- <FileText className="h-4 w-4 shrink-0" />
- <span className="truncate">{source.name}</span>
- </button>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => handleIngest(source)}
- title="Ingest this source into wiki"
- className="shrink-0 text-xs"
- >
- <BookOpen className="mr-1 h-3 w-3" />
- Ingest
- </Button>
-</div>
-```
-
-- [ ] **Step 3: Add "Write to Wiki" button in chat panel**
-
-In `src/components/chat/chat-panel.tsx`, add the ability to trigger the write phase after the user has discussed takeaways. Import:
-
-```tsx
-import { useChatStore } from "@/stores/chat-store"
-import { useWikiStore } from "@/stores/wiki-store"
-import { executeIngestWrites } from "@/lib/ingest"
-import { listDirectory } from "@/commands/fs"
-import { Button } from "@/components/ui/button"
-import { BookOpen } from "lucide-react"
-```
-
-Add a "Write to Wiki" button that appears when in ingest mode and not streaming:
-
-```tsx
-const mode = useChatStore((s) => s.mode)
-const project = useWikiStore((s) => s.project)
-const setFileTree = useWikiStore((s) => s.setFileTree)
-
-async function handleWriteToWiki() {
- if (!project) return
- const written = await executeIngestWrites(
- project.path,
- llmConfig,
- "Please proceed with writing the wiki pages based on our discussion.",
- )
- if (written.length > 0) {
- const tree = await listDirectory(project.path)
- setFileTree(tree)
- }
-}
-```
-
-Add the button between the message list and the input, visible only when in ingest mode and not streaming:
-
-```tsx
-{mode === "ingest" && !isStreaming && messages.length > 1 && (
- <div className="flex justify-center border-t px-4 py-2">
- <Button size="sm" onClick={handleWriteToWiki}>
- <BookOpen className="mr-2 h-4 w-4" />
- Write to Wiki
- </Button>
- </div>
-)}
-```
-
-- [ ] **Step 4: Verify build**
-
-```bash
-cd /Users/nash_su/projects/llm_wiki && npx vite build
-```
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add -A
-git commit -m "feat: wire ingest flow into sources view and chat panel"
-```
-
----
-
-### Task 6: Settings Persistence
-
-**Files:**
-- Modify: `src/components/settings/settings-view.tsx`
-- Modify: `src/lib/project-store.ts`
-- Modify: `src/App.tsx`
-
-Settings currently live only in Zustand (lost on reload). Persist them using the Tauri store.
-
-- [ ] **Step 1: Add settings persistence to project-store.ts**
-
-Add to `src/lib/project-store.ts`:
-
-```ts
-import type { LlmConfig } from "@/stores/wiki-store"
-
-const LLM_CONFIG_KEY = "llmConfig"
-
-export async function saveLlmConfig(config: LlmConfig): Promise<void> {
- const store = await getStore()
- await store.set(LLM_CONFIG_KEY, config)
-}
-
-export async function loadLlmConfig(): Promise<LlmConfig | null> {
- const store = await getStore()
- return (await store.get<LlmConfig>(LLM_CONFIG_KEY)) ?? null
-}
-```
-
-- [ ] **Step 2: Update settings view to persist on save**
-
-In `src/components/settings/settings-view.tsx`, import `saveLlmConfig` and call it in `handleSave`:
-
-```tsx
-import { saveLlmConfig } from "@/lib/project-store"
-
-async function handleSave() {
- const newConfig = { provider, apiKey, model, ollamaUrl, customEndpoint }
- setLlmConfig(newConfig)
- await saveLlmConfig(newConfig)
- setSaved(true)
- setTimeout(() => setSaved(false), 2000)
-}
-```
-
-- [ ] **Step 3: Load persisted settings on startup in App.tsx**
-
-In `src/App.tsx`, import `loadLlmConfig` and load it in the startup `useEffect`:
-
-```tsx
-import { getLastProject, saveLastProject, loadLlmConfig } from "@/lib/project-store"
-
-// Inside the useEffect:
-const savedConfig = await loadLlmConfig()
-if (savedConfig) {
- useWikiStore.getState().setLlmConfig(savedConfig)
-}
-```
-
-- [ ] **Step 4: Verify build**
-
-```bash
-cd /Users/nash_su/projects/llm_wiki && npx vite build
-```
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add -A
-git commit -m "feat: persist LLM settings across app restarts"
-```
-
----
-
-### Task 7: End-to-End Verification
-
-- [ ] **Step 1: Full build check**
-
-```bash
-cd /Users/nash_su/projects/llm_wiki && npx vite build && cd src-tauri && cargo build
-```
-
-- [ ] **Step 2: Manual end-to-end test**
-
-```bash
-npm run tauri dev
-```
-
-Test the following flow:
-1. Open a project (or create new)
-2. Go to Settings → configure an LLM provider with API key and model
-3. Go to Sources → Import a markdown/text file
-4. Click "Ingest" next to the imported source
-5. Chat panel expands → LLM reads source and presents key takeaways (streaming)
-6. Type a message guiding what to emphasize
-7. Click "Write to Wiki" → LLM generates wiki pages
-8. File tree updates with new pages in wiki/entities/, wiki/concepts/, wiki/sources/
-9. Click a generated page → view in Milkdown editor
-10. Close and reopen app → settings preserved, last project auto-opens
-
-- [ ] **Step 3: Final commit**
-
-```bash
-git add -A
-git commit -m "feat: complete Phase 2 — LLM integration with interactive ingest"
-```
-
----
-
-## Phase 2 Deliverables
-
-After completing all tasks:
-
-- ✅ Streaming LLM client supporting OpenAI, Anthropic, Google, Ollama, Custom
-- ✅ Real-time chat UI with message bubbles and streaming display
-- ✅ Interactive Ingest flow: source → discuss → guide → write wiki pages
-- ✅ Multi-file wiki generation (source summary, entities, concepts, index, log)
-- ✅ LLM settings persisted across app restarts
-- ✅ File tree auto-refreshes after ingest
-
-## What's Next
-
-**Phase 3: Search & Query** will add:
-- tantivy full-text search over wiki pages
-- Query flow: ask question → search wiki → LLM synthesize → Save to Wiki
-- Multi-format response rendering
diff --git a/docs/superpowers/specs/2026-04-05-llm-wiki-design.md b/docs/superpowers/specs/2026-04-05-llm-wiki-design.md
deleted file mode 100644
index 2a5c4971..00000000
--- a/docs/superpowers/specs/2026-04-05-llm-wiki-design.md
+++ /dev/null
@@ -1,304 +0,0 @@
-# LLM Wiki — Design Spec
-
-## Overview
-
-A cross-platform desktop application for building and maintaining personal knowledge bases using LLMs. Based on [Karpathy's LLM Wiki pattern](https://github.com/karpathy/llm-wiki): instead of RAG-style retrieval on every query, the LLM incrementally builds and maintains a persistent, interlinked wiki of markdown files. Knowledge is compiled once and kept current, not re-derived on every question.
-
-The system is a generic framework with built-in scenario templates (research, reading, personal growth, etc.). Users select a template to bootstrap their wiki, then co-evolve the schema and purpose with the LLM over time.
-
-## Tech Stack
-
-| Layer | Technology | Rationale |
-|-------|-----------|-----------|
-| Desktop framework | Tauri v2 | Cross-platform (Mac/Linux/Windows), lightweight, Rust backend |
-| Frontend | React + TypeScript + Vite | Mature ecosystem, Tauri official template support |
-| UI components | shadcn/ui + Tailwind CSS | High quality, customizable, not bloated |
-| Markdown editor | Milkdown (ProseMirror-based) | WYSIWYG, plugin system, extensible for [[wikilink]] syntax |
-| i18n | react-i18next | React standard, supports dynamic language pack loading |
-| State management | Zustand | Lightweight, simple, fits medium complexity |
-| File operations | Tauri fs API (Rust side) | Direct local file system read/write, no extra backend needed |
-| LLM calls | Rust-side unified HTTP client | Secure API key storage, unified interface for all providers |
-| Search | tantivy (Rust) | Local full-text search engine, BM25 retrieval, embedded in Tauri |
-| Browser extension | Chrome Extension (Manifest V3) | Web clipper converting pages to Markdown, sent to app via deep link |
-
-## Architecture
-
-### Three-Layer Data Model
-
-```
-my-wiki/
-├── purpose.md # Soul — goals, key questions, research scope, evolving thesis
-├── schema.md # Skeleton — structure rules, page types, workflows
-├── raw/ # Raw Sources (immutable)
-│ ├── assets/ # Localized images
-│ └── sources/ # Source files (md, pdf, txt, html...)
-├── wiki/ # LLM-Generated Wiki
-│ ├── index.md # Content catalog (by category, LLM query entry point)
-│ ├── log.md # Operation log (parseable format)
-│ ├── overview.md # Global overview page (single, LLM-maintained)
-│ ├── entities/ # Entity pages (people, orgs, products...)
-│ ├── concepts/ # Concept pages (theories, methods, terms...)
-│ ├── sources/ # Source summary pages (one per raw source)
-│ ├── queries/ # Archived query result pages
-│ ├── comparisons/ # Comparison analysis pages
-│ └── synthesis/ # Cross-source deep synthesis pages
-├── templates/ # Scenario templates (research, reading, personal...)
-├── i18n/ # Language packs
-└── .llm-wiki/ # App config (LLM API keys, user preferences)
- └── config.json
-```
-
-**raw/** — Immutable input files. The LLM reads from them but never modifies them. Source of truth.
-
-**wiki/** — LLM-generated and maintained markdown files. The LLM owns this layer entirely: creates pages, updates them when new sources arrive, maintains cross-references, keeps everything consistent. The user reads and can also edit (rarely — the LLM does the grunt work).
-
-**schema.md** — Tells the LLM how the wiki is structured, what the conventions are, and what workflows to follow. Co-evolves with the LLM over time.
-
-**purpose.md** — Defines the wiki's soul: goals, key questions, research scope, evolving thesis. The LLM can suggest updates to purpose.md; user approves changes.
-
-### Role Division
-
-**User's job:** Curate sources, direct the analysis, ask good questions, think about what it all means.
-
-**LLM's job:** Everything else — summarizing, cross-referencing, filing, bookkeeping, maintaining consistency across pages. The wiki stays maintained because the cost of maintenance is near zero.
-
-### Application Layers
-
-**Frontend (React + TypeScript):**
-- Wiki Browser — browse and navigate wiki pages with [[wikilink]] support
-- Milkdown Editor — WYSIWYG markdown editing with real-time preview
-- Chat UI — unified for ingest discussions and queries
-- Source Manager — import, browse, and manage raw sources
-- Graph View — visualize page interconnections
-- Lint Report Dashboard — structured lint results with one-click fix
-- Multi-format Renderer — Markdown, tables, Marp slides, charts
-- "Save to Wiki" button — archive query results back to wiki
-- Settings — LLM provider config, i18n, preferences
-- i18n — full internationalization support
-
-**Backend (Rust / Tauri Commands):**
-- File System Ops — read/write local markdown files
-- LLM Router — unified HTTP client for OpenAI, Anthropic, Google, Ollama
-- Interactive Ingest Pipeline — orchestrates the ingest conversation and multi-file writes
-- Search (tantivy) — BM25 full-text index over wiki pages
-- Schema Engine — parses schema.md, validates page structure
-- Structured Lint Engine — Rust-side structural checks + LLM semantic checks
-- Image Processor — localize images, multimodal LLM calls (text first, then images)
-- Log Manager — parseable log format, append operations
-- Schema Advisor — LLM suggests schema/purpose improvements, user approves
-
-### External Integrations
-
-- **LLM APIs** — OpenAI, Anthropic, Google, Ollama (local models)
-- **Browser Extension** — Chrome Manifest V3, web clipper converting pages to Markdown, sent to app via Tauri deep link
-
-## UI Layout
-
-VS Code-style hybrid layout with collapsible Chat panel:
-
-```
-┌──────┬────────────┬──────────────────────────────┐
-│ Icon │ File Tree │ Content Area │
-│ Bar │ │ (Wiki page / Editor / Graph) │
-│ │ wiki/ │ │
-│ [📝] │ ├ entities│ Entity: Person A │
-│ [📁] │ │ ├ a.md │ ...content... │
-│ [🔍] │ │ └ b.md │ [[Concept X]] · [[Org B]] │
-│ [🕸️] │ ├ concepts│ │
-│ [📊] │ │ └ x.md │ ● Just updated (green) │
-│ [⚙️] │ └ sources │ │
-│ │ ├──────────────────────────────┤
-│ │ │ 💬 CHAT (collapsible) │
-│ │ │ LLM: Key takeaways: 1)... │
-│ │ │ User: Focus on point 2 │
-│ │ │ LLM: Updated 6 files ✓ │
-│ │ │ [Type a message...] │
-└──────┴────────────┴──────────────────────────────┘
-```
-
-**Chat collapsed:** Content area fills the right side. Bottom shows a thin `💬 CHAT` bar, click to expand.
-
-**Chat expanded:** Content area compresses to top half, Chat panel takes bottom half. Divider is draggable. Left file tree is unaffected.
-
-**Real-time feedback:** During ingest, content area highlights LLM-updated sections (green left border). Changed files flash in the file tree.
-
-## Core Operations
-
-### Ingest
-
-1. User imports source (drag/drop, file picker, paste URL, or browser clipper) → stored in `raw/sources/`
-2. Rust reads file content (text extraction, image detection)
-3. If images present: download to `raw/assets/`, LLM processes text first, then images separately (multimodal)
-4. LLM reads source → presents key takeaways in Chat UI
-5. User discusses with LLM: what to emphasize, what to ignore, connections to existing knowledge
-6. LLM checks for contradictions with existing wiki pages
-7. LLM executes multi-file write (one ingest may touch 10-15 files):
- - Create `wiki/sources/xxx.md` (source summary page)
- - Create or update `wiki/entities/` (related entity pages)
- - Create or update `wiki/concepts/` (related concept pages)
- - Update `wiki/synthesis/` pages if thesis is affected
- - Mark contradictions with `> [!conflict]` callouts on affected pages
- - Update `wiki/overview.md` (global overview)
- - Update `wiki/index.md` (catalog)
- - Append to `wiki/log.md` (operation log)
-8. User sees changes in real-time in the content area, can continue adjusting
-
-**Batch mode:** Users can also batch-ingest multiple sources at once with less supervision. In this mode, the LLM processes each source automatically without per-source discussion, then presents a summary of all changes at the end for review.
-
-### Query
-
-1. User asks a question in Chat UI
-2. LLM reads `index.md` as the primary navigation entry point to find relevant pages by category and summary
-3. Rust also searches `wiki/` via tantivy for full-text matches the index might miss
-4. LLM reads the combined set of relevant pages → synthesizes answer
-5. Response rendered in chosen format (Markdown, table, chart, Marp slides, Obsidian Canvas)
-6. User can click "Save to Wiki" → stored in `wiki/queries/`
- - Updates `index.md` and appends to `log.md`
-
-### Lint
-
-Two-layer checking for efficiency:
-
-**Layer 1 — Rust structural checks (fast, deterministic):**
-- Orphan pages (no inbound links)
-- Broken links (references to non-existent pages)
-- Missing cross-references (entities/concepts mentioned but not linked)
-
-**Layer 2 — LLM semantic checks (requires content understanding):**
-- Contradictions between pages
-- Stale claims superseded by newer sources
-- Important concepts mentioned but lacking their own page
-- Data gaps that could be filled with web search
-- Suggested new questions to investigate
-- Suggested new sources to look for
-
-**Output:** Structured lint report displayed in dashboard. Each issue has severity level and one-click fix or dismiss. Results appended to `log.md`.
-
-## Schema Design
-
-### schema.md Structure
-
-```markdown
-# Schema
-
-## Page Types
-- source: Source summary (title, origin, date, summary, key points, related pages)
-- entity: Entity page (name, type, description, first source, related entities)
-- concept: Concept page (definition, background, key arguments, related concepts, cited sources)
-- comparison: Comparison page (subjects, dimensions, comparison table, conclusion)
-- query: Archived query (original question, answer, cited pages, date)
-- overview: Global overview (single page, high-level picture)
-- synthesis: Cross-source synthesis (deep analysis, evolving thesis, evidence tracking)
-
-## Naming Conventions
-- Lowercase, kebab-case
-- Sources: sources/author-year-keyword.md
-- Entities: entities/name.md
-- Concepts: concepts/name.md
-
-## Frontmatter
-Every wiki page has YAML frontmatter:
-- type, title, created, updated, sources[], tags[], source_count
-
-## Index Format
-Organized by category. Each entry:
-- [Page Title](path.md) — one-line summary (N sources, YYYY-MM-DD)
-
-## Log Format
-Each entry: ## [YYYY-MM-DD] type | title
-Types: ingest, query, lint, update
-
-## Cross-referencing Rules
-- Use [[wikilink]] syntax
-- First mention of entity/concept must be linked
-- After creating a new page, update all related pages' references
-
-## Contradiction Handling
-- On ingest, LLM checks new information against existing pages
-- Contradictions marked with > [!conflict] callouts on affected pages
-- Synthesis pages updated to record thesis evolution
-- Lint re-reviews unresolved contradictions
-
-## Workflows
-(Detailed ingest/query/lint steps as defined in Core Operations above)
-
-## Conventions
-(Domain-specific, pre-set by template, user-customizable)
-```
-
-### Scenario Templates
-
-Each template pre-sets Page Types, Conventions, and initial purpose.md:
-
-| Template | Extra Page Types | Special Conventions |
-|----------|-----------------|-------------------|
-| Research | thesis, methodology, finding | Evidence strength scoring, thesis evolution tracking |
-| Reading | character, theme, plot-thread, chapter | Chapter-by-chapter tracking, character relationship graph |
-| Personal Growth | goal, habit, reflection, journal | Periodic review, progress tracking |
-| Business | meeting, decision, project, stakeholder | Decision log, action item tracking |
-| General | (base types only) | Minimal conventions, maximum flexibility |
-
-### Schema Co-evolution
-
-The LLM can suggest improvements to `schema.md` and `purpose.md` based on usage patterns. Suggestions appear in Chat UI; user reviews and approves before changes take effect. This keeps the wiki's structure and direction evolving with the knowledge it contains.
-
-## LLM Provider Support
-
-Unified LLM Router in Rust backend:
-
-| Provider | Models | Connection |
-|----------|--------|------------|
-| OpenAI | GPT-4o, GPT-4.1, etc. | HTTPS API |
-| Anthropic | Claude Sonnet, Opus, etc. | HTTPS API |
-| Google | Gemini Pro, etc. | HTTPS API |
-| Ollama | Any local model | Local HTTP (localhost) |
-
-Configuration stored in `.llm-wiki/config.json`. API keys stored securely via Tauri's secure storage API. User can set default provider and model, or choose per-operation.
-
-## Internationalization
-
-- Full i18n via react-i18next
-- Language packs in `i18n/` directory (JSON files)
-- Initial languages: English, Chinese (Simplified)
-- Wiki content language follows source material language
-- UI language independently configurable
-
-## Browser Extension (Web Clipper)
-
-Chrome Extension (Manifest V3):
-- Converts current web page to clean Markdown
-- Sends to LLM Wiki app via Tauri deep link (`llm-wiki://clip?...`)
-- Source saved to `raw/sources/`, images downloaded to `raw/assets/`
-- Optionally triggers ingest immediately after clipping
-
-## Obsidian Compatibility
-
-The wiki directory is designed to be directly openable in Obsidian:
-
-- **[[wikilink]] syntax** — Obsidian's native linking format, used throughout
-- **YAML frontmatter** — compatible with Obsidian's Dataview plugin for dynamic tables and queries
-- **Graph View** — while the app has its own graph view, users can also use Obsidian's graph view on the same directory
-- **`raw/assets/`** — matches Obsidian's attachment folder pattern
-- **Canvas format** — query results can be exported as `.canvas` files (Obsidian's spatial canvas format)
-
-The app and Obsidian can operate on the same directory simultaneously.
-
-## Git Integration
-
-The wiki is just a directory of markdown files — it can be a git repository. This provides:
-
-- **Version history** — every ingest, query archive, and lint fix is trackable
-- **Branching** — experiment with different synthesis directions
-- **Collaboration** — share wikis via git remotes
-- **Backup** — push to any git host
-
-The app does not manage git directly in v1. Users manage git themselves or via Obsidian's git plugin. Future versions may add built-in git support.
-
-## Non-Goals (v1)
-
-- Real-time collaboration / multi-user
-- Cloud sync (users can use git for this)
-- Mobile app
-- Embedding-based vector search (tantivy BM25 is sufficient for v1)
-- Scheduled/automated ingest from RSS or other feeds
-- Built-in git management (users manage git externally)