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(api): expose unresolved review items
Dongmin, Yu7756663ddbf1
diff --git a/README.md b/README.mdindex a3f9f1f8..c8ced7fd 100644--- a/README.md+++ b/README.md@@ -414,13 +414,14 @@ LLM Wiki ships a built-in local HTTP API at `http://127.0.0.1:19828` (token-prot- `GET /api/v1/health` — server status (no auth)- `GET /api/v1/projects` — list projects- `GET /api/v1/projects/{id}/files` / `files/content` — read files and content+- `GET /api/v1/projects/{id}/reviews?status=unresolved` — export Review tab items for wiki maintenance (`status`: `unresolved`, `resolved`, or `all`; optional `type` and `limit`)- `POST /api/v1/projects/{id}/search` — **hybrid** retrieval (keyword + vector) returning `mode`, `tokenHits`, `vectorHits`, per-result `vectorScore`- `GET /api/v1/projects/{id}/graph` — wikilinks graph- `POST /api/v1/projects/{id}/sources/rescan` — trigger a backend rescanEnable the API, generate a token, and choose whether local unauthenticated access is allowed in **Settings → API + MCP**.-For MCP-compatible clients, LLM Wiki also includes a local MCP server in `mcp-server/`. After building it with `npm run mcp:build`, **Settings → API + MCP** shows a copyable MCP client configuration with the correct local path for your machine. The MCP tools call the same API surface, so agent clients can list projects, read files, run hybrid search, inspect the graph, and trigger source rescans without custom HTTP glue code.+For MCP-compatible clients, LLM Wiki also includes a local MCP server in `mcp-server/`. After building it with `npm run mcp:build`, **Settings → API + MCP** shows a copyable MCP client configuration with the correct local path for your machine. The MCP tools call the same API surface, so agent clients can list projects, read files, export unresolved Review items, run hybrid search, inspect the graph, and trigger source rescans without custom HTTP glue code.### Plug your AI agent in with one commanddiff --git a/mcp-server/README.md b/mcp-server/README.mdindex 4e189a91..4dec94d8 100644--- a/mcp-server/README.md+++ b/mcp-server/README.md@@ -56,6 +56,7 @@ When API unauthenticated mode is enabled, omit `LLM_WIKI_API_TOKEN`. If MCP acce- `llm_wiki_projects`: known projects and active project.- `llm_wiki_files`: list project files. `project_id` can be a project UUID, a project filesystem path, or `current`.- `llm_wiki_read_file`: read an allowed text file such as `wiki/index.md`.+- `llm_wiki_reviews`: list Review tab items. Defaults to unresolved items and supports `status`, `type`, and `limit` filters.- `llm_wiki_search`: search with the app's shared keyword/vector backend.- `llm_wiki_graph`: query the app's knowledge graph endpoint.- `llm_wiki_rescan_sources`: trigger a Source Watch rescan using the user's configured rules.@@ -67,6 +68,7 @@ The MCP server inherits the desktop API's security model:- It only talks to `127.0.0.1` by default.- It uses the same API token or unauthenticated setting as Settings → API + MCP.- File reads go through the API path allow-list. Internal app state files are not exposed.+- Review data is exposed only through the dedicated Review endpoint/tool, which defaults to unresolved items rather than opening internal state files directly.- Search and graph tools operate on projects known to the app; use `project_id: "current"` for the active project.Do not pass API tokens via command-line arguments. Prefer environment variables so they do not appear in shell history.diff --git a/mcp-server/src/api-client.ts b/mcp-server/src/api-client.tsindex 6ad99f44..cebb08d2 100644--- a/mcp-server/src/api-client.ts+++ b/mcp-server/src/api-client.ts@@ -52,6 +52,34 @@ export interface ApiGraphEdge {weight?: number}+export type ApiReviewStatus = "unresolved" | "resolved" | "all"++export interface ApiReviewOption {+ label: string+ action: string+}++export interface ApiReviewItem {+ id: string+ type: string+ title: string+ description: string+ sourcePath?: string+ affectedPages?: string[]+ searchQueries?: string[]+ options: ApiReviewOption[]+ resolved: boolean+ resolvedAction?: string+ createdAt: number+}++export interface ApiReviewsResponse {+ projectId?: string+ status: ApiReviewStatus+ count: number+ reviews: ApiReviewItem[]+}+export interface ApiFilesResponse {files: ApiFileNode[]truncated?: boolean@@ -132,6 +160,22 @@ export class LlmWikiApiClient {}}+ async reviews(projectId = "current", options: { status?: ApiReviewStatus; type?: string; limit?: number } = {}): Promise<ApiReviewsResponse> {+ const params = new URLSearchParams()+ if (options.status) params.set("status", options.status)+ if (options.type) params.set("type", options.type)+ if (options.limit !== undefined) params.set("limit", String(options.limit))+ const suffix = params.toString() ? `?${params.toString()}` : ""+ const json = await this.request(`/projects/${encodeURIComponent(projectId)}/reviews${suffix}`)+ const reviews = Array.isArray(json.reviews) ? json.reviews.map(parseReviewItem) : []+ return {+ projectId: typeof json.projectId === "string" ? json.projectId : undefined,+ status: parseReviewStatus(json.status),+ count: numberOrUndefined(json.count) ?? reviews.length,+ reviews,+ }+ }+async search(projectId = "current", query: string, options: { topK?: number; includeContent?: boolean } = {}): Promise<ApiSearchResponse> {const json = await this.request(`/projects/${encodeURIComponent(projectId)}/search`, {method: "POST",@@ -240,6 +284,35 @@ function parseSearchResult(value: unknown): ApiSearchResult {}}+function parseReviewStatus(value: unknown): ApiReviewStatus {+ return value === "resolved" || value === "all" ? value : "unresolved"+}++function stringArray(value: unknown): string[] | undefined {+ if (!Array.isArray(value)) return undefined+ return value.map((item) => String(item))+}++function parseReviewItem(value: unknown): ApiReviewItem {+ const obj = requireObject(value, "review item")+ return {+ id: String(obj.id ?? ""),+ type: String(obj.type ?? ""),+ title: String(obj.title ?? ""),+ description: String(obj.description ?? ""),+ sourcePath: typeof obj.sourcePath === "string" ? obj.sourcePath : undefined,+ affectedPages: stringArray(obj.affectedPages),+ searchQueries: stringArray(obj.searchQueries),+ options: Array.isArray(obj.options) ? obj.options.map((option) => {+ const item = requireObject(option, "review option")+ return { label: String(item.label ?? ""), action: String(item.action ?? "") }+ }) : [],+ resolved: obj.resolved === true,+ resolvedAction: typeof obj.resolvedAction === "string" ? obj.resolvedAction : undefined,+ createdAt: numberOrUndefined(obj.createdAt) ?? 0,+ }+}+function parseGraphNode(value: unknown): ApiGraphNode {const obj = requireObject(value, "graph node")return {diff --git a/mcp-server/src/index.ts b/mcp-server/src/index.tsindex af57a7f0..349b7f62 100644--- a/mcp-server/src/index.ts+++ b/mcp-server/src/index.ts@@ -7,7 +7,14 @@ import {ListToolsRequestSchema,McpError,} from "@modelcontextprotocol/sdk/types.js"-import { LlmWikiApiClient, type ApiFileNode, type ApiGraphNode, type ApiSearchResult } from "./api-client.js"+import {+ LlmWikiApiClient,+ type ApiFileNode,+ type ApiGraphNode,+ type ApiReviewItem,+ type ApiReviewsResponse,+ type ApiSearchResult,+} from "./api-client.js"const VERSION = "0.4.20"const DEFAULT_PROJECT_ID = "current"@@ -67,6 +74,20 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({additionalProperties: false,},},+ {+ name: "llm_wiki_reviews",+ description: "List Review tab items from a project. Defaults to unresolved items so agent clients can help manage pending wiki review work.",+ inputSchema: {+ type: "object",+ properties: {+ project_id: { type: "string", description: "Project UUID, project path, or 'current'. Defaults to current." },+ status: { type: "string", enum: ["unresolved", "resolved", "all"], description: "Review status filter. Defaults to unresolved." },+ type: { type: "string", description: "Optional Review item type filter, for example missing-page, duplicate, contradiction, confirm, or suggestion." },+ limit: { type: "number", description: "Maximum review items returned. The local API clamps to its configured maximum." },+ },+ additionalProperties: false,+ },+ },{name: "llm_wiki_search",description: "Search a project using the same backend keyword/vector retrieval used by the desktop API.",@@ -140,6 +161,15 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {const { path, content } = await client.fileContent(projectId(args), relPath)return textResult(`# ${path}\n\n${truncateText(content, MAX_TEXT_BYTES)}`)}+ case "llm_wiki_reviews": {+ await assertMcpEnabled()+ const reviews = await client.reviews(projectId(args), {+ status: enumArg(args.status, ["unresolved", "resolved", "all"] as const, "unresolved"),+ type: optionalStringArg(args.type),+ limit: numberArg(args.limit),+ })+ return textResult(formatReviews(reviews))+ }case "llm_wiki_search": {await assertMcpEnabled()const query = stringArg(args.query, "query")@@ -274,6 +304,43 @@ function formatSearchResults(query: string, search: { results: ApiSearchResult[]return lines.join("\n")}+function formatReviews(response: ApiReviewsResponse): string {+ const { reviews } = response+ if (reviews.length === 0) return `No ${response.status} review items found.`+ const lines = [+ "# Review items",+ "",+ `Status: ${response.status}`,+ `Count: ${response.count}`,+ "",+ ]+ reviews.forEach((review, index) => {+ lines.push(`## ${index + 1}. ${review.title || review.id}`)+ lines.push(`ID: ${review.id}`)+ lines.push(`Type: ${review.type}`)+ lines.push(`Resolved: ${review.resolved ? "yes" : "no"}`)+ if (review.sourcePath) lines.push(`Source: ${review.sourcePath}`)+ if (review.affectedPages && review.affectedPages.length > 0) {+ lines.push(`Affected pages: ${review.affectedPages.join(", ")}`)+ }+ if (review.searchQueries && review.searchQueries.length > 0) {+ lines.push(`Search queries: ${review.searchQueries.join(", ")}`)+ }+ if (review.description) lines.push(`Description: ${review.description}`)+ const optionSummary = formatReviewOptions(review)+ if (optionSummary) lines.push(`Options: ${optionSummary}`)+ lines.push("")+ })+ return lines.join("\n")+}++function formatReviewOptions(review: ApiReviewItem): string {+ if (!review.options || review.options.length === 0) return ""+ return review.options+ .map((option) => option.label ? `${option.label} (${option.action})` : option.action)+ .join(", ")+}+function formatGraph(nodes: ApiGraphNode[], edges: Array<{ source: string; target: string; weight?: number }>): string {const typeCounts = new Map<string, number>()for (const node of nodes) typeCounts.set(node.type, (typeCounts.get(node.type) ?? 0) + 1)diff --git a/mcp-server/test/api-client.test.ts b/mcp-server/test/api-client.test.tsindex 259753ce..23ddad00 100644--- a/mcp-server/test/api-client.test.ts+++ b/mcp-server/test/api-client.test.ts@@ -100,6 +100,41 @@ test("files exposes truncated flag", async () => {assert.equal(files.files[0]?.path, "wiki/index.md")})+test("reviews requests unresolved review items with filters", async () => {+ const calls: string[] = []+ const fetchImpl = async (url: string | URL | Request): Promise<Response> => {+ calls.push(String(url))+ return new Response(JSON.stringify({+ ok: true,+ projectId: "p1",+ status: "unresolved",+ count: 1,+ reviews: [{+ id: "r1",+ type: "missing-page",+ title: "Missing page: Attention",+ description: "Add the Attention page",+ options: [],+ resolved: false,+ createdAt: 1,+ }],+ }), { status: 200 })+ }++ const client = new LlmWikiApiClient({ baseUrl: "http://localhost:19828", fetchImpl })+ const result = await client.reviews("current", {+ status: "unresolved",+ type: "missing-page",+ limit: 5,+ })++ assert.equal(calls[0], "http://localhost:19828/api/v1/projects/current/reviews?status=unresolved&type=missing-page&limit=5")+ assert.equal(result.status, "unresolved")+ assert.equal(result.count, 1)+ assert.equal(result.reviews[0]?.id, "r1")+ assert.equal(result.reviews[0]?.resolved, false)+})+test("network failures include desktop app hint", async () => {const fetchImpl = async (): Promise<Response> => {throw new Error("ECONNREFUSED")diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex 8fd4d924..aaafec9c 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -21,6 +21,8 @@ const MAX_BODY_BYTES: usize = 1024 * 1024;const MAX_FILE_CONTENT_BYTES: u64 = 2 * 1024 * 1024;const DEFAULT_MAX_FILES: usize = 2_000;const HARD_MAX_FILES: usize = 10_000;+const DEFAULT_MAX_REVIEWS: usize = 200;+const HARD_MAX_REVIEWS: usize = 1_000;const MAX_SEARCH_RESULTS: usize = 50;const BIND_RETRY_DELAY_SECS: u64 = 2;const MAX_BIND_RETRIES: u32 = 3;@@ -255,6 +257,9 @@ fn handle_request((&Method::Get, ["projects", project_id, "files", "content"]) => {handle_file_content(app, project_id, query)}+ (&Method::Get, ["projects", project_id, "reviews"]) => {+ handle_reviews(app, project_id, query)+ }(&Method::Post, ["projects", project_id, "search"]) => handle_search(app, project_id, body),(&Method::Get, ["projects", project_id, "graph"]) => handle_graph(app, project_id, query),(&Method::Post, ["projects", project_id, "sources", "rescan"]) => {@@ -942,6 +947,128 @@ fn relative_to_project(project_path: &str, path: &Path) -> String {.unwrap_or_else(|_| path.to_string_lossy().replace('\\', "/"))}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ReviewStatus {+ Unresolved,+ Resolved,+ All,+}++impl ReviewStatus {+ fn as_str(self) -> &'static str {+ match self {+ ReviewStatus::Unresolved => "unresolved",+ ReviewStatus::Resolved => "resolved",+ ReviewStatus::All => "all",+ }+ }++ fn matches(self, resolved: bool) -> bool {+ match self {+ ReviewStatus::Unresolved => !resolved,+ ReviewStatus::Resolved => resolved,+ ReviewStatus::All => true,+ }+ }+}++#[derive(Debug, Clone)]+struct ReviewQuery {+ status: ReviewStatus,+ item_type: Option<String>,+ limit: usize,+}++fn parse_review_query(query: &str) -> Result<ReviewQuery, String> {+ let params = parse_query(query);+ let status = match params+ .get("status")+ .map(|s| s.as_str())+ .unwrap_or("unresolved")+ {+ "unresolved" | "pending" => ReviewStatus::Unresolved,+ "resolved" => ReviewStatus::Resolved,+ "all" => ReviewStatus::All,+ value => {+ return Err(format!(+ "Invalid review status '{value}'. Expected unresolved, resolved, or all"+ ))+ }+ };+ let item_type = params+ .get("type")+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty());+ let limit = params+ .get("limit")+ .and_then(|s| s.parse::<usize>().ok())+ .unwrap_or(DEFAULT_MAX_REVIEWS)+ .clamp(1, HARD_MAX_REVIEWS);++ Ok(ReviewQuery {+ status,+ item_type,+ limit,+ })+}++fn load_review_items(project_path: &str, query: &ReviewQuery) -> Result<Vec<Value>, String> {+ let path = Path::new(project_path).join(".llm-wiki/review.json");+ let raw = match fs::read_to_string(&path) {+ Ok(raw) => raw,+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),+ Err(err) => return Err(format!("Failed to read review state: {err}")),+ };+ let parsed: Value =+ serde_json::from_str(&raw).map_err(|err| format!("Invalid review state JSON: {err}"))?;+ let items = parsed+ .as_array()+ .ok_or_else(|| "Invalid review state JSON: expected an array".to_string())?;++ let mut reviews = Vec::new();+ for item in items {+ let resolved = item+ .get("resolved")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ if !query.status.matches(resolved) {+ continue;+ }+ if let Some(item_type) = &query.item_type {+ if item.get("type").and_then(Value::as_str) != Some(item_type.as_str()) {+ continue;+ }+ }+ reviews.push(item.clone());+ if reviews.len() >= query.limit {+ break;+ }+ }++ Ok(reviews)+}++fn handle_reviews(app: &AppHandle, project_id: &str, query: &str) -> ApiResponse {+ let project = match resolve_project(app, project_id) {+ Ok(project) => project,+ Err(e) => return err(404, e),+ };+ let query = match parse_review_query(query) {+ Ok(query) => query,+ Err(e) => return err(400, e),+ };+ match load_review_items(&project.path, &query) {+ Ok(reviews) => ok(json!({+ "ok": true,+ "projectId": project.id,+ "status": query.status.as_str(),+ "count": reviews.len(),+ "reviews": reviews,+ })),+ Err(e) => err(500, e),+ }+}+#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct SearchRequest {@@ -1272,6 +1399,77 @@ mod tests {assert!(!is_public_project_rel("wiki/.draft.md"));}+ #[test]+ fn review_query_defaults_to_unresolved_items() {+ let root = test_project_dir();+ let state_dir = root.join(".llm-wiki");+ fs::create_dir_all(&state_dir).unwrap();+ fs::write(+ state_dir.join("review.json"),+ json!([+ {+ "id": "r1",+ "type": "missing-page",+ "title": "Missing page: Attention",+ "description": "Add Attention",+ "options": [],+ "resolved": false,+ "createdAt": 1+ },+ {+ "id": "r2",+ "type": "duplicate",+ "title": "Duplicate: LLM",+ "description": "Merge pages",+ "options": [],+ "resolved": true,+ "createdAt": 2+ }+ ])+ .to_string(),+ )+ .unwrap();++ let query = parse_review_query("").unwrap();+ let reviews = load_review_items(root.to_str().unwrap(), &query).unwrap();++ assert_eq!(query.status.as_str(), "unresolved");+ assert_eq!(reviews.len(), 1);+ assert_eq!(reviews[0].get("id").and_then(Value::as_str), Some("r1"));+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn review_query_filters_by_type_status_and_limit() {+ let root = test_project_dir();+ let state_dir = root.join(".llm-wiki");+ fs::create_dir_all(&state_dir).unwrap();+ fs::write(+ state_dir.join("review.json"),+ json!([+ { "id": "r1", "type": "missing-page", "resolved": false, "createdAt": 1 },+ { "id": "r2", "type": "missing-page", "resolved": false, "createdAt": 2 },+ { "id": "r3", "type": "duplicate", "resolved": false, "createdAt": 3 },+ { "id": "r4", "type": "missing-page", "resolved": true, "createdAt": 4 }+ ])+ .to_string(),+ )+ .unwrap();++ let query = parse_review_query("status=all&type=missing-page&limit=2").unwrap();+ let reviews = load_review_items(root.to_str().unwrap(), &query).unwrap();++ assert_eq!(query.status.as_str(), "all");+ assert_eq!(+ reviews+ .iter()+ .filter_map(|r| r.get("id").and_then(Value::as_str))+ .collect::<Vec<_>>(),+ vec!["r1", "r2"]+ );+ let _ = fs::remove_dir_all(root);+ }+#[test]fn project_path_match_normalizes_separators() {assert!(project_path_matches(