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
feat: add SHA256 ingest cache, surprising connections, knowledge gaps
nash_su68c01cc6b191
diff --git a/src/components/graph/graph-view.tsx b/src/components/graph/graph-view.tsxindex 25098733..18726f83 100644--- a/src/components/graph/graph-view.tsx+++ b/src/components/graph/graph-view.tsx@@ -3,11 +3,12 @@ import Graph from "graphology"import { SigmaContainer, useLoadGraph, useRegisterEvents, useSigma } from "@react-sigma/core"import "@react-sigma/core/lib/style.css"import forceAtlas2 from "graphology-layout-forceatlas2"-import { Network, RefreshCw, ZoomIn, ZoomOut, Maximize, Layers, Tag } from "lucide-react"+import { Network, RefreshCw, ZoomIn, ZoomOut, Maximize, Layers, Tag, Lightbulb, AlertTriangle, Link2 } from "lucide-react"import { Button } from "@/components/ui/button"import { useWikiStore } from "@/stores/wiki-store"import { readFile } from "@/commands/fs"import { buildWikiGraph, type GraphNode, type GraphEdge, type CommunityInfo } from "@/lib/wiki-graph"+import { findSurprisingConnections, detectKnowledgeGaps, type SurprisingConnection, type KnowledgeGap } from "@/lib/graph-insights"import { normalizePath } from "@/lib/path-utils"const NODE_TYPE_COLORS: Record<string, string> = {@@ -259,10 +260,13 @@ export function GraphView() {const [nodes, setNodes] = useState<GraphNode[]>([])const [edges, setEdges] = useState<GraphEdge[]>([])const [communities, setCommunities] = useState<CommunityInfo[]>([])+ const [surprisingConns, setSurprisingConns] = useState<SurprisingConnection[]>([])+ const [knowledgeGaps, setKnowledgeGaps] = useState<KnowledgeGap[]>([])const [loading, setLoading] = useState(false)const [error, setError] = useState<string | null>(null)const [hoveredType, setHoveredType] = useState<string | null>(null)const [colorMode, setColorMode] = useState<ColorMode>("type")+ const [showInsights, setShowInsights] = useState(false)const lastLoadedVersion = useRef(-1)const loadGraph = useCallback(async () => {@@ -274,6 +278,8 @@ export function GraphView() {setNodes(result.nodes)setEdges(result.edges)setCommunities(result.communities)+ setSurprisingConns(findSurprisingConnections(result.nodes, result.edges, result.communities))+ setKnowledgeGaps(detectKnowledgeGaps(result.nodes, result.edges, result.communities))lastLoadedVersion.current = useWikiStore.getState().dataVersion} catch (err) {const message = err instanceof Error ? err.message : "Failed to build graph"@@ -381,6 +387,20 @@ export function GraphView() {<Layers className="h-3 w-3" />Community</Button>+ {(surprisingConns.length > 0 || knowledgeGaps.length > 0) && (+ <Button+ variant={showInsights ? "secondary" : "ghost"}+ size="sm"+ onClick={() => setShowInsights((v) => !v)}+ className="text-xs gap-1 h-7"+ >+ <Lightbulb className="h-3 w-3" />+ Insights+ <span className="rounded bg-muted px-1 text-[10px]">+ {surprisingConns.length + knowledgeGaps.length}+ </span>+ </Button>+ )}<Button variant="ghost" size="sm" onClick={loadGraph} className="text-xs gap-1 h-7"><RefreshCw className="h-3.5 w-3.5" /></Button>@@ -497,6 +517,49 @@ export function GraphView() {</>)}</div>++ {/* Insights Panel */}+ {showInsights && (+ <div className="absolute bottom-3 right-14 w-72 max-h-[60%] overflow-y-auto rounded-lg border bg-background/95 backdrop-blur-sm px-3 py-2 text-xs shadow-lg">+ {surprisingConns.length > 0 && (+ <div className="mb-3">+ <div className="flex items-center gap-1.5 mb-1.5 font-semibold text-foreground">+ <Link2 className="h-3.5 w-3.5 text-blue-500" />+ Surprising Connections+ </div>+ <div className="flex flex-col gap-1.5">+ {surprisingConns.map((conn, i) => (+ <div key={i} className="rounded border px-2 py-1.5 bg-muted/30">+ <div className="font-medium text-foreground">+ {conn.source.label} ↔ {conn.target.label}+ </div>+ <div className="text-muted-foreground mt-0.5">+ {conn.reasons.join(", ")}+ </div>+ </div>+ ))}+ </div>+ </div>+ )}+ {knowledgeGaps.length > 0 && (+ <div>+ <div className="flex items-center gap-1.5 mb-1.5 font-semibold text-foreground">+ <AlertTriangle className="h-3.5 w-3.5 text-amber-500" />+ Knowledge Gaps+ </div>+ <div className="flex flex-col gap-1.5">+ {knowledgeGaps.map((gap, i) => (+ <div key={i} className="rounded border px-2 py-1.5 bg-muted/30">+ <div className="font-medium text-foreground">{gap.title}</div>+ <div className="text-muted-foreground mt-0.5">{gap.description}</div>+ <div className="text-muted-foreground/80 mt-1 italic">{gap.suggestion}</div>+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ )}</div></div>diff --git a/src/lib/graph-insights.ts b/src/lib/graph-insights.tsnew file mode 100644index 00000000..cca7ff49--- /dev/null+++ b/src/lib/graph-insights.ts@@ -0,0 +1,184 @@+import type { GraphNode, GraphEdge, CommunityInfo } from "./wiki-graph"++// ---------------------------------------------------------------------------+// Types+// ---------------------------------------------------------------------------++export interface SurprisingConnection {+ source: GraphNode+ target: GraphNode+ score: number+ reasons: string[]+}++export interface KnowledgeGap {+ type: "isolated-node" | "sparse-community" | "bridge-node"+ title: string+ description: string+ nodeIds: string[]+ suggestion: string+}++// ---------------------------------------------------------------------------+// Surprising Connections+// ---------------------------------------------------------------------------++/**+ * Find edges that are "surprising" — connecting nodes across communities,+ * across types, or linking peripheral nodes to hubs.+ */+export function findSurprisingConnections(+ nodes: GraphNode[],+ edges: GraphEdge[],+ communities: CommunityInfo[],+ limit: number = 5,+): SurprisingConnection[] {+ const nodeMap = new Map(nodes.map((n) => [n.id, n]))+ const degreeMap = new Map(nodes.map((n) => [n.id, n.linkCount]))+ const maxDegree = Math.max(...nodes.map((n) => n.linkCount), 1)++ const scored: SurprisingConnection[] = []++ for (const edge of edges) {+ const source = nodeMap.get(edge.source)+ const target = nodeMap.get(edge.target)+ if (!source || !target) continue++ let score = 0+ const reasons: string[] = []++ // Signal 1: Cross-community edge (+3)+ if (source.community !== target.community) {+ score += 3+ reasons.push("crosses community boundary")+ }++ // Signal 2: Cross-type edge (+2 for distant types)+ if (source.type !== target.type) {+ const distantPairs = new Set([+ "source-concept", "concept-source",+ "source-synthesis", "synthesis-source",+ "query-entity", "entity-query",+ ])+ const pair = `${source.type}-${target.type}`+ if (distantPairs.has(pair)) {+ score += 2+ reasons.push(`connects ${source.type} to ${target.type}`)+ } else {+ score += 1+ reasons.push("different types")+ }+ }++ // Signal 3: Peripheral-to-hub coupling (+2)+ const sourceDeg = degreeMap.get(source.id) ?? 0+ const targetDeg = degreeMap.get(target.id) ?? 0+ const minDeg = Math.min(sourceDeg, targetDeg)+ const maxDeg = Math.max(sourceDeg, targetDeg)+ if (minDeg <= 2 && maxDeg >= maxDegree * 0.5) {+ score += 2+ reasons.push("peripheral node links to hub")+ }++ // Signal 4: Low-weight edge between connected nodes (+1)+ if (edge.weight < 2 && edge.weight > 0) {+ score += 1+ reasons.push("weak but present connection")+ }++ if (score >= 3 && reasons.length > 0) {+ scored.push({ source, target, score, reasons })+ }+ }++ scored.sort((a, b) => b.score - a.score)+ return scored.slice(0, limit)+}++// ---------------------------------------------------------------------------+// Knowledge Gaps+// ---------------------------------------------------------------------------++/**+ * Detect knowledge gaps based on graph structure:+ * - Isolated nodes (degree ≤ 1)+ * - Sparse communities (cohesion < 0.15 with ≥ 3 nodes)+ * - Bridge nodes (high betweenness — connected to multiple communities)+ */+export function detectKnowledgeGaps(+ nodes: GraphNode[],+ edges: GraphEdge[],+ communities: CommunityInfo[],+ limit: number = 8,+): KnowledgeGap[] {+ const gaps: KnowledgeGap[] = []+ const nodeMap = new Map(nodes.map((n) => [n.id, n]))++ // 1. Isolated nodes (degree ≤ 1, exclude overview/index)+ const isolatedNodes = nodes.filter(+ (n) => n.linkCount <= 1 && n.type !== "overview" && n.id !== "index" && n.id !== "log",+ )+ if (isolatedNodes.length > 0) {+ const topIsolated = isolatedNodes.slice(0, 5)+ gaps.push({+ type: "isolated-node",+ title: `${isolatedNodes.length} isolated page${isolatedNodes.length > 1 ? "s" : ""}`,+ description: topIsolated.map((n) => n.label).join(", ") ++ (isolatedNodes.length > 5 ? ` and ${isolatedNodes.length - 5} more` : ""),+ nodeIds: isolatedNodes.map((n) => n.id),+ suggestion: "These pages have few or no connections. Consider adding [[wikilinks]] to related pages, or research to expand their content.",+ })+ }++ // 2. Sparse communities (low cohesion)+ for (const comm of communities) {+ if (comm.cohesion < 0.15 && comm.nodeCount >= 3) {+ gaps.push({+ type: "sparse-community",+ title: `Sparse cluster: ${comm.topNodes[0] ?? `Community ${comm.id}`}`,+ description: `${comm.nodeCount} pages with cohesion ${comm.cohesion.toFixed(2)} — internal connections are weak.`,+ nodeIds: nodes.filter((n) => n.community === comm.id).map((n) => n.id),+ suggestion: `This knowledge area lacks internal cross-references. Consider adding links between these pages or researching to fill gaps.`,+ })+ }+ }++ // 3. Bridge nodes (connected to multiple communities)+ const communityNeighbors = new Map<string, Set<number>>()+ for (const node of nodes) {+ communityNeighbors.set(node.id, new Set())+ }+ for (const edge of edges) {+ const sourceNode = nodeMap.get(edge.source)+ const targetNode = nodeMap.get(edge.target)+ if (sourceNode && targetNode) {+ communityNeighbors.get(edge.source)?.add(targetNode.community)+ communityNeighbors.get(edge.target)?.add(sourceNode.community)+ }+ }++ const bridgeNodes = nodes+ .filter((n) => {+ const neighborComms = communityNeighbors.get(n.id)+ return neighborComms && neighborComms.size >= 3+ })+ .sort((a, b) => {+ const aComms = communityNeighbors.get(a.id)?.size ?? 0+ const bComms = communityNeighbors.get(b.id)?.size ?? 0+ return bComms - aComms+ })+ .slice(0, 3)++ for (const bridge of bridgeNodes) {+ const commCount = communityNeighbors.get(bridge.id)?.size ?? 0+ gaps.push({+ type: "bridge-node",+ title: `Key bridge: ${bridge.label}`,+ description: `Connects ${commCount} different knowledge clusters. This is a critical junction in your wiki.`,+ nodeIds: [bridge.id],+ suggestion: `This page bridges multiple knowledge areas. Ensure it's well-maintained — if it's thin, expanding it will strengthen your entire wiki.`,+ })+ }++ return gaps.slice(0, limit)+}diff --git a/src/lib/ingest-cache.ts b/src/lib/ingest-cache.tsnew file mode 100644index 00000000..de9bcf91--- /dev/null+++ b/src/lib/ingest-cache.ts@@ -0,0 +1,100 @@+import { readFile, writeFile } from "@/commands/fs"+import { normalizePath } from "@/lib/path-utils"++/**+ * SHA256-based ingest cache.+ * Stores hash of source file content → skips re-ingest if unchanged.+ * Cache file: .llm-wiki/ingest-cache.json+ */++interface CacheEntry {+ hash: string+ timestamp: number+ filesWritten: string[]+}++interface CacheData {+ entries: Record<string, CacheEntry> // keyed by source filename+}++async function sha256(content: string): Promise<string> {+ const encoder = new TextEncoder()+ const data = encoder.encode(content)+ const hashBuffer = await crypto.subtle.digest("SHA-256", data)+ const hashArray = Array.from(new Uint8Array(hashBuffer))+ return hashArray.map((b) => b.toString(16).padStart(2, "0")).join("")+}++function cachePath(projectPath: string): string {+ return `${normalizePath(projectPath)}/.llm-wiki/ingest-cache.json`+}++async function loadCache(projectPath: string): Promise<CacheData> {+ try {+ const raw = await readFile(cachePath(projectPath))+ return JSON.parse(raw) as CacheData+ } catch {+ return { entries: {} }+ }+}++async function saveCache(projectPath: string, cache: CacheData): Promise<void> {+ try {+ await writeFile(cachePath(projectPath), JSON.stringify(cache, null, 2))+ } catch {+ // non-critical+ }+}++/**+ * Check if a source file has already been ingested with the same content.+ * Returns the list of previously written files if cached, or null if ingest is needed.+ */+export async function checkIngestCache(+ projectPath: string,+ sourceFileName: string,+ sourceContent: string,+): Promise<string[] | null> {+ const cache = await loadCache(projectPath)+ const entry = cache.entries[sourceFileName]+ if (!entry) return null++ const currentHash = await sha256(sourceContent)+ if (entry.hash === currentHash) {+ return entry.filesWritten+ }+ return null+}++/**+ * Save ingest result to cache after successful ingest.+ */+export async function saveIngestCache(+ projectPath: string,+ sourceFileName: string,+ sourceContent: string,+ filesWritten: string[],+): Promise<void> {+ const cache = await loadCache(projectPath)+ const hash = await sha256(sourceContent)+ const newEntries = { ...cache.entries }+ newEntries[sourceFileName] = {+ hash,+ timestamp: Date.now(),+ filesWritten,+ }+ await saveCache(projectPath, { entries: newEntries })+}++/**+ * Remove a source file entry from cache (e.g., when source is deleted).+ */+export async function removeFromIngestCache(+ projectPath: string,+ sourceFileName: string,+): Promise<void> {+ const cache = await loadCache(projectPath)+ const newEntries = { ...cache.entries }+ delete newEntries[sourceFileName]+ await saveCache(projectPath, { entries: newEntries })+}diff --git a/src/lib/ingest.ts b/src/lib/ingest.tsindex 4567c9a9..c468b2bd 100644--- a/src/lib/ingest.ts+++ b/src/lib/ingest.ts@@ -6,6 +6,7 @@ import { useChatStore } from "@/stores/chat-store"import { useActivityStore } from "@/stores/activity-store"import { useReviewStore, type ReviewItem } from "@/stores/review-store"import { getFileName, normalizePath } from "@/lib/path-utils"+import { checkIngestCache, saveIngestCache } from "@/lib/ingest-cache"const FILE_BLOCK_REGEX = /---FILE:\s*([^\n-]+?)\s*---\n([\s\S]*?)---END FILE---/g@@ -41,6 +42,17 @@ export async function autoIngest(tryReadFile(`${pp}/wiki/overview.md`),])+ // ── Cache check: skip re-ingest if source content hasn't changed ──+ const cachedFiles = await checkIngestCache(pp, fileName, sourceContent)+ if (cachedFiles !== null) {+ activity.updateItem(activityId, {+ status: "done",+ detail: `Skipped (unchanged) — ${cachedFiles.length} files from previous ingest`,+ filesWritten: cachedFiles,+ })+ return cachedFiles+ }+const truncatedContent = sourceContent.length > 50000? sourceContent.slice(0, 50000) + "\n\n[...truncated...]": sourceContent@@ -163,6 +175,11 @@ export async function autoIngest(useReviewStore.getState().addItems(reviewItems)}+ // ── Step 5: Save to cache ───────────────────────────────────+ if (writtenPaths.length > 0) {+ await saveIngestCache(pp, fileName, sourceContent, writtenPaths)+ }+const detail = writtenPaths.length > 0? `${writtenPaths.length} files written${reviewItems.length > 0 ? `, ${reviewItems.length} review item(s)` : ""}`: "No files generated"