From 11e0c4c65f90af1b9d9b43f468520bb9c62ae2bb Mon Sep 17 00:00:00 2001 From: wizardchen Date: Wed, 22 Apr 2026 20:27:59 +0800 Subject: [PATCH] feat: Remove outdated analysis and documentation files - Deleted `AGENT_WIKI_ANALYSIS.md`, `ANALYSIS_SUMMARY.md`, `COMPLETION_REPORT.md`, `DEPLOYMENT_CHECKLIST.md`, `DOCUMENTATION_INDEX.md`, `EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md`, and `EXECUTIVE_SUMMARY.md` as they are no longer relevant to the current project scope. - This cleanup helps streamline the repository and reduces clutter, ensuring that only up-to-date and necessary documentation remains accessible. --- AGENT_WIKI_ANALYSIS.md | 492 -------- ANALYSIS_SUMMARY.md | 319 ------ COMPLETION_REPORT.md | 323 ------ DEPLOYMENT_CHECKLIST.md | 396 ------- DOCUMENTATION_INDEX.md | 360 ------ EXECUTIVE_SUMMARY.md | 310 ------ EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md | 227 ---- FINAL_COMPLETION_SUMMARY.md | 401 ------- FRONTEND_KB_QUICK_REFERENCE.md | 245 ---- FRONTEND_KB_WIKI_ANALYSIS_COMPREHENSIVE.md | 492 -------- IMPLEMENTATION_GUIDE.md | 410 ------- IMPLEMENTATION_SUMMARY.md | 216 ---- INDEX_ALL_ANALYSIS.md | 522 --------- KB_DATA_MODEL_COMPLETE_ANALYSIS.txt | 439 -------- KB_WIKI_ARCHITECTURE_ANALYSIS.md | 1021 ----------------- KB_WIKI_FILE_INDEX.md | 415 ------- KB_WIKI_QUICK_REFERENCE.md | 426 ------- KNOWLEDGE_FLOW_DETAILED.md | 403 ------- KNOWLEDGE_MODEL_ANALYSIS.md | 532 --------- KNOWLEDGE_MODEL_QUICK_REF.md | 167 --- LANGUAGE_MIDDLEWARE_ANALYSIS.md | 349 ------ LANGUAGE_REFACTORING_COMPLETED.md | 234 ---- LANGUAGE_REFACTORING_QUICK_REFERENCE.md | 111 -- LANGUAGE_REFACTORING_README.md | 287 ----- PROJECT_COMPLETION_REPORT.md | 477 -------- PROJECT_INDEX.md | 406 ------- QUICK_FIX_GUIDE.md | 228 ---- QUICK_REFERENCE.md | 154 --- README_ANALYSIS.md | 427 ------- README_WIKI_CONFIG_FIX.md | 247 ----- README_WIKI_FEATURE.md | 560 ---------- REFACTORING_IMPLEMENTATION_REPORT.md | 273 ----- REFACTORING_PLAN.md | 204 ---- REFACTORING_SUMMARY.txt | 257 ----- SESSION_2_COMPLETION_SUMMARY.md | 418 ------- START_HERE.md | 225 ---- WEKNORA_ANALYSIS_SUMMARY.md | 537 --------- WIKI_CONFIG_FIX.md | 328 ------ WIKI_CONFIG_FIX_COMPLETE.md | 386 ------- WIKI_CONFIG_FLOW_ANALYSIS.md | 501 --------- WIKI_CONFIG_QUICK_REFERENCE.md | 201 ---- WIKI_CONFIG_TRACE_SUMMARY.md | 354 ------ WIKI_CONFIG_VERIFICATION.md | 203 ---- WIKI_DOCS_INDEX.md | 482 -------- WIKI_IMPLEMENTATION_GUIDE.md | 756 ------------- WIKI_README.md | 301 ----- WIKI_SYSTEM_DEEP_DIVE.md | 948 ---------------- WIKI_SYSTEM_SUMMARY.md | 469 -------- WIKI_TECHNICAL_ANALYSIS.md | 1171 -------------------- docs/AGENT_KB_IMPLEMENTATION_PATTERNS.md | 619 ----------- docs/AGENT_KB_QUICK_REFERENCE.md | 286 ----- docs/AGENT_KB_RETRIEVAL_ARCHITECTURE.md | 581 ---------- docs/AGENT_KB_RETRIEVAL_FLOW_DEEP_DIVE.md | 910 --------------- docs/README_AGENT_KB_INTEGRATION.md | 256 ----- 54 files changed, 22262 deletions(-) delete mode 100644 AGENT_WIKI_ANALYSIS.md delete mode 100644 ANALYSIS_SUMMARY.md delete mode 100644 COMPLETION_REPORT.md delete mode 100644 DEPLOYMENT_CHECKLIST.md delete mode 100644 DOCUMENTATION_INDEX.md delete mode 100644 EXECUTIVE_SUMMARY.md delete mode 100644 EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md delete mode 100644 FINAL_COMPLETION_SUMMARY.md delete mode 100644 FRONTEND_KB_QUICK_REFERENCE.md delete mode 100644 FRONTEND_KB_WIKI_ANALYSIS_COMPREHENSIVE.md delete mode 100644 IMPLEMENTATION_GUIDE.md delete mode 100644 IMPLEMENTATION_SUMMARY.md delete mode 100644 INDEX_ALL_ANALYSIS.md delete mode 100644 KB_DATA_MODEL_COMPLETE_ANALYSIS.txt delete mode 100644 KB_WIKI_ARCHITECTURE_ANALYSIS.md delete mode 100644 KB_WIKI_FILE_INDEX.md delete mode 100644 KB_WIKI_QUICK_REFERENCE.md delete mode 100644 KNOWLEDGE_FLOW_DETAILED.md delete mode 100644 KNOWLEDGE_MODEL_ANALYSIS.md delete mode 100644 KNOWLEDGE_MODEL_QUICK_REF.md delete mode 100644 LANGUAGE_MIDDLEWARE_ANALYSIS.md delete mode 100644 LANGUAGE_REFACTORING_COMPLETED.md delete mode 100644 LANGUAGE_REFACTORING_QUICK_REFERENCE.md delete mode 100644 LANGUAGE_REFACTORING_README.md delete mode 100644 PROJECT_COMPLETION_REPORT.md delete mode 100644 PROJECT_INDEX.md delete mode 100644 QUICK_FIX_GUIDE.md delete mode 100644 QUICK_REFERENCE.md delete mode 100644 README_ANALYSIS.md delete mode 100644 README_WIKI_CONFIG_FIX.md delete mode 100644 README_WIKI_FEATURE.md delete mode 100644 REFACTORING_IMPLEMENTATION_REPORT.md delete mode 100644 REFACTORING_PLAN.md delete mode 100644 REFACTORING_SUMMARY.txt delete mode 100644 SESSION_2_COMPLETION_SUMMARY.md delete mode 100644 START_HERE.md delete mode 100644 WEKNORA_ANALYSIS_SUMMARY.md delete mode 100644 WIKI_CONFIG_FIX.md delete mode 100644 WIKI_CONFIG_FIX_COMPLETE.md delete mode 100644 WIKI_CONFIG_FLOW_ANALYSIS.md delete mode 100644 WIKI_CONFIG_QUICK_REFERENCE.md delete mode 100644 WIKI_CONFIG_TRACE_SUMMARY.md delete mode 100644 WIKI_CONFIG_VERIFICATION.md delete mode 100644 WIKI_DOCS_INDEX.md delete mode 100644 WIKI_IMPLEMENTATION_GUIDE.md delete mode 100644 WIKI_README.md delete mode 100644 WIKI_SYSTEM_DEEP_DIVE.md delete mode 100644 WIKI_SYSTEM_SUMMARY.md delete mode 100644 WIKI_TECHNICAL_ANALYSIS.md delete mode 100644 docs/AGENT_KB_IMPLEMENTATION_PATTERNS.md delete mode 100644 docs/AGENT_KB_QUICK_REFERENCE.md delete mode 100644 docs/AGENT_KB_RETRIEVAL_ARCHITECTURE.md delete mode 100644 docs/AGENT_KB_RETRIEVAL_FLOW_DEEP_DIVE.md delete mode 100644 docs/README_AGENT_KB_INTEGRATION.md diff --git a/AGENT_WIKI_ANALYSIS.md b/AGENT_WIKI_ANALYSIS.md deleted file mode 100644 index b236569b..00000000 --- a/AGENT_WIKI_ANALYSIS.md +++ /dev/null @@ -1,492 +0,0 @@ -# WeKnora Agent ReAct Engine & Wiki Tool Analysis - -## Executive Summary - -The WeKnora Agent uses a **ReAct (Reasoning + Acting)** loop architecture where: -1. The **Agent Engine** calls the LLM with available tools -2. The LLM decides which tools to call (or provide a final answer) -3. Tools are **automatically dispatched** by the engine - **NOT** requiring user explicit request -4. Wiki tools are **conditionally registered** when wiki knowledge bases are detected -5. **`wiki_write_page` is NOT automatically triggered** - it requires the Agent to explicitly decide to use it based on the system prompt - ---- - -## 1. Agent ReAct Engine - Main Loop Architecture - -### File: `/internal/agent/engine.go` - -**Core Components:** -- **`AgentEngine` struct** (line 24-41): Main ReAct engine orchestrating the loop -- **`Execute()` method** (line 155-256): Entry point for agent execution -- **`executeLoop()` method** (line 260-394): Main ReAct loop implementation - -**ReAct Loop Flow:** - -``` -executeLoop() iteration: - 1. Think Phase - - Call LLM with messages + available tools (line 315) - - LLM returns response with optional tool calls - - 2. Analyze Phase - - Check for stop conditions: finish_reason=="stop" OR final_answer tool (line 338) - - If LLM signals done: extract final answer and break loop - - 3. Act Phase - - Execute ALL tool calls in the response (line 369) - - Support parallel execution if enabled (line 81 in act.go) - - 4. Observe Phase - - Collect tool results - - Append results to message history (line 373) - - Write to context manager (line 236 in observe.go) - - 5. Continue to next round (line 382) -``` - -**Key Characteristics:** -- Max iterations configured in `config.MaxIterations` (default 5) -- Loop exits when: - - LLM calls `final_answer` tool (explicit stop) - - LLM stops naturally with `finish_reason=="stop"` (implicit stop) - - Max iterations reached (graceful synthesis from existing results) - - Context cancelled/timeout - ---- - -## 2. Tool Dispatch Mechanism - Automatic, Not User-Triggered - -### File: `/internal/agent/act.go` - -**Tool Dispatch Logic:** - -```go -// executeToolCalls (line 68-89) -// Called AUTOMATICALLY after LLM response, regardless of user action -func (e *AgentEngine) executeToolCalls( - ctx context.Context, response *types.ChatResponse, - step *types.AgentStep, iteration int, sessionID string, -) -``` - -**Process:** -1. **Line 72**: Check if response contains tool calls (`len(response.ToolCalls) == 0`) -2. **Lines 81-88**: Route to parallel or sequential execution -3. **For each tool call:** - - Parse arguments (line 216-236) - - Call `e.toolRegistry.ExecuteTool()` (line 266-269) - - Emit events for UI feedback (line 244-255) - - Collect results (line 279) - -**Tool Execution Flow:** -``` -LLM Response with tool calls - ↓ -parseToolCall() - parse JSON args - ↓ -runToolCall() - execute with timeout (line 207-330) - ↓ -Emit toolCallStart event (line 244-255) - ↓ -ExecuteTool() - actual tool execution - ↓ -Emit toolResult event + collect result (line 127-141, 173-187) - ↓ -Append to step.ToolCalls - ↓ -Continue loop or synthesize answer -``` - -**CRITICAL: Tool calls are triggered BY THE LLM, NOT the user** -- User input → LLM decision → Tool dispatch (automatic) -- The Agent never queries the user "should I call tool X?" -- Tools are included in the system prompt as options the LLM can choose from - ---- - -## 3. System Prompts - Where Tools Are Described - -### File: `/internal/agent/prompts.go` - -**System Prompt Building:** -```go -BuildSystemPromptWithOptions() (line 315-360) -``` - -This function constructs the system prompt that: -1. Loads a template from config or uses default -2. Renders placeholders (knowledge bases, web search status, language) -3. Appends skill metadata if enabled -4. Appends selected documents info - -**Template Sources:** -- **Pure Agent Mode** (no KB): `GetPureAgentSystemPrompt()` (line 365-372) -- **Progressive RAG Mode** (with KB): `GetProgressiveRAGSystemPrompt()` (line 377-384) -- **Custom Templates**: From config YAML files - -**Default Templates loaded from:** -- Config: `config.PromptTemplates.AgentSystemPrompt` -- Mode-based: "pure" or "rag" template variant -- Fallback: Hardcoded defaults (if config not provided) - -**The system prompt DOES NOT mention wiki tools explicitly** - it's handled at tool registration time. - -### File: `/internal/agent/prompts_wiki.go` - -**Wiki-Specific Prompts** (for document ingestion, NOT Agent decision): -- `WikiSummaryPrompt` (line 8): Generate summary page from document -- `WikiKnowledgeExtractPrompt` (line 32): Extract entities and concepts (single LLM call) -- `WikiPageUpdatePrompt` (line 87): Incrementally update existing page -- `WikiIndexRebuildPrompt` (line 107): Generate index from page listing -- `WikiLogEntryTemplate` (line 122): Simple template for log entries - -**These prompts are used by the wiki ingest pipeline, NOT the Agent ReAct loop.** - ---- - -## 4. Wiki Tool Registration - Conditional Based on KB Type - -### File: `/internal/application/service/agent_service.go` - -**Tool Registration Flow:** - -```go -registerTools() (line 316-477) -``` - -**Step 1: Determine which tools to register** -```go -// Line 336-362: Filter tools based on KB availability -hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0 - -if !hasKnowledge { - // Remove KB-related tools for Pure Agent Mode - // tools like: knowledge_search, grep_chunks, list_knowledge_chunks, etc. -} -``` - -**Step 2: Detect Wiki KBs and add wiki tools automatically** -```go -// Line 370-389: AUTO-DETECT WIKI KBs -var wikiKBIDs []string -for _, target := range config.SearchTargets { - kb, err := s.knowledgeBaseService.GetKnowledgeBaseByIDOnly(ctx, target.KnowledgeBaseID) - if err == nil && kb.Type == types.KnowledgeBaseTypeWiki { - wikiKBIDs = append(wikiKBIDs, kb.ID) - wikiTenantID = kb.TenantID - } -} - -// If wiki KBs found → automatically add wiki tools -if len(wikiKBIDs) > 0 { - allowedTools = append(allowedTools, - tools.ToolWikiReadPage, - tools.ToolWikiWritePage, - tools.ToolWikiSearch, - tools.ToolWikiReadIndex, - tools.ToolWikiLint, - ) -} -``` - -**Step 3: Register each tool** -```go -// Line 394-473: Register tool implementations -for _, toolName := range allowedTools { - switch toolName { - case tools.ToolWikiReadPage: - toolToRegister = tools.NewWikiReadPageTool(s.wikiPageService, wikiKBIDs) - case tools.ToolWikiWritePage: - toolToRegister = tools.NewWikiWritePageTool(s.wikiPageService, wikiKBIDs, wikiTenantID) - case tools.ToolWikiSearch: - toolToRegister = tools.NewWikiSearchTool(s.wikiPageService, wikiKBIDs) - case tools.ToolWikiReadIndex: - toolToRegister = tools.NewWikiReadIndexTool(s.wikiPageService, wikiKBIDs) - case tools.ToolWikiLint: - toolToRegister = tools.NewWikiLintTool(s.wikiPageService, wikiKBIDs) - } - registry.RegisterTool(toolToRegister) -} -``` - -**Result:** Wiki tools are included in the tools passed to LLM if wiki KBs are detected. - ---- - -## 5. Wiki Tools Implementation - -### File: `/internal/agent/tools/wiki_tools.go` - -**5 Wiki Tools Available:** - -#### 1. **wiki_read_page** (line 14-76) -```go -type wikiReadPageTool struct { - wikiService interfaces.WikiPageService - kbIDs []string // Search across these KBs -} - -// Parameters: slug, knowledge_base_id (optional) -// Output: Full markdown content + metadata + links -``` - -#### 2. **wiki_write_page** (line 78-185) -```go -type wikiWritePageTool struct { - wikiService interfaces.WikiPageService - kbIDs []string - tenantID uint64 -} - -// Parameters: -// - slug: e.g. "synthesis/quarterly-review" or "comparison/tool-a-vs-tool-b" -// - title: Human-readable title -// - content: Full Markdown -// - page_type: enum ["summary", "entity", "concept", "synthesis", "comparison"] -// - knowledge_base_id: Target KB (optional, uses first if multiple) - -// Behavior: -// 1. Check if page exists (line 148) -// - If exists: UPDATE and increment version (line 155) -// - If new: CREATE with default status (line 165-175) -// 2. Return success + page info -``` - -#### 3. **wiki_search** (line 187-255) -```go -// Parameters: query (keyword search), limit (default 10) -// Output: List of matching pages with titles, slugs, summaries -``` - -#### 4. **wiki_read_index** (line 257-314) -```go -// Parameters: knowledge_base_id (optional) -// Output: Index page content (TOC of all pages) -``` - -#### 5. **wiki_lint** (line 316-427) -```go -// Parameters: knowledge_base_id (optional) -// Output: Wiki health report with: -// - Statistics (total pages, orphan pages, broken links) -// - Health score (0-100) -// - Suggestions for improvement -``` - -**Key: `wiki_write_page` is a TOOL like any other - the LLM decides if/when to call it based on the system prompt and context.** - ---- - -## 6. How the Agent Knows About Wiki Tools - -### Tool Visibility in LLM Call - -**File: `/internal/agent/observe.go` (line 183-198)** - -```go -func (e *AgentEngine) buildToolsForLLM() []chat.Tool { - functionDefs := e.toolRegistry.GetFunctionDefinitions() - tools := make([]chat.Tool, 0, len(functionDefs)) - - for _, def := range functionDefs { - tools = append(tools, chat.Tool{ - Type: "function", - Function: chat.FunctionDef{ - Name: def.Name, - Description: def.Description, - Parameters: def.Parameters, - }, - }) - } - return tools -} -``` - -**Description of wiki_write_page in tool definition:** - -```go -// From wiki_tools.go line 91-92 -`Create or update a wiki page. Use this to save valuable analysis, -synthesis, or new knowledge into the wiki. -The page content should be in Markdown format. Use [[slug]] syntax -to create links between pages.` -``` - -The description tells the LLM: -- **Purpose**: Save analysis, synthesis, new knowledge -- **Format**: Markdown -- **When**: "valuable", "synthesis", "analysis" contexts -- **How**: Call `wiki_write_page` with slug, title, content, page_type - ---- - -## 7. Is There a Dedicated Wiki-Specific System Prompt for the Agent? - -### **NO - There is no dedicated system prompt that tells the Agent to use wiki_write_page** - -**Evidence:** -1. **No wiki-specific prompt in `prompts.go`**: - - Only generic RAG/Pure Agent prompts - - No mention of synthesis detection or wiki page creation instructions - -2. **Wiki prompts in `prompts_wiki.go` are for ingest pipeline ONLY:** - - `WikiSummaryPrompt` - used by wiki_ingest_service.ProcessWikiIngest() - - `WikiKnowledgeExtractPrompt` - used by wiki_ingest_service.extractEntitiesAndConcepts() - - `WikiPageUpdatePrompt` - used by wiki_ingest_service.upsertExtractedPages() - - These are NOT part of the Agent's system prompt - -3. **Tool description is minimal** (line 91-92 in wiki_tools.go): - - Only says "save valuable analysis, synthesis..." - - Doesn't explicitly instruct WHEN to write pages - -**Result: The Agent will only call `wiki_write_page` if:** -- It's in the mood to write analysis (depends on its reasoning) -- The LLM interprets "valuable analysis" broadly -- **NOT guaranteed by any explicit instruction in the system prompt** - ---- - -## 8. Synthesis Detection - Where It Actually Happens - -### NOT in Agent ReAct Loop - Instead, in Wiki Ingest Pipeline - -**File: `/internal/application/service/wiki_ingest.go`** - -**Synthesis opportunities are detected AUTOMATICALLY during document ingest:** - -```go -// ProcessWikiIngest() line 85-214 -// Step 3: Detect synthesis opportunities (line 200-201) -synthesisSuggestions = s.detectSynthesisOpportunities(ctx, payload) -``` - -**Detection Logic: `detectSynthesisOpportunities()` (line 350-389)** - -```go -// Pure heuristic - NO LLM CALL, just counts pages by type - -typeCounts := make(map[string]int) - -// Iterate all pages, count by type -for _, p := range resp.Pages { - if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog { - continue - } - typeCounts[p.PageType]++ -} - -// Generate suggestions if thresholds met: -if count := typeCounts[types.WikiPageTypeEntity]; count >= 3 { - // "Synthesis opportunity: N entity pages could be synthesized..." -} -if count := typeCounts[types.WikiPageTypeConcept]; count >= 3 { - // "Synthesis opportunity: N concept pages could be synthesized..." -} -``` - -**Rules:** -- Trigger if ≥3 entity pages exist -- Trigger if ≥3 concept pages exist -- Return human-readable suggestions -- Append to wiki log page (line 435-460) - -**Result:** Suggestions are logged to the wiki, NOT automatically acted upon by the Agent. - ---- - -## 9. Complete Tool List and Filter Logic - -### File: `/internal/agent/tools/definitions.go` - -**All Available Tools:** - -```go -const ( - ToolThinking = "thinking" - ToolTodoWrite = "todo_write" - ToolGrepChunks = "grep_chunks" - ToolKnowledgeSearch = "knowledge_search" - ToolListKnowledgeChunks = "list_knowledge_chunks" - ToolQueryKnowledgeGraph = "query_knowledge_graph" - ToolGetDocumentInfo = "get_document_info" - ToolDatabaseQuery = "database_query" - ToolDataAnalysis = "data_analysis" - ToolDataSchema = "data_schema" - ToolWebSearch = "web_search" - ToolWebFetch = "web_fetch" - ToolFinalAnswer = "final_answer" - ToolExecuteSkillScript = "execute_skill_script" - ToolReadSkill = "read_skill" - ToolWikiReadPage = "wiki_read_page" - ToolWikiWritePage = "wiki_write_page" - ToolWikiSearch = "wiki_search" - ToolWikiReadIndex = "wiki_read_index" - ToolWikiLint = "wiki_lint" -) -``` - -**Default Allowed Tools (`DefaultAllowedTools()`, line 66-80):** -``` -thinking, todo_write, knowledge_search, grep_chunks, list_knowledge_chunks, -query_knowledge_graph, get_document_info, database_query, data_analysis, -data_schema, final_answer -``` - -**Dynamically Added Tools:** -- `web_search`, `web_fetch` - if `config.WebSearchEnabled` -- `read_skill`, `execute_skill_script` - if `config.SkillsEnabled` -- `wiki_*` (5 tools) - if wiki KBs detected in search targets - ---- - -## 10. Event-Driven Architecture - -**All agent actions emit events through EventBus for UI feedback:** - -### File: `/internal/agent/act.go` (event emission points) - -1. **Tool hint event** (line 244-255) - For UI progress bar -2. **Tool call pending event** (line 133-142 in think.go) -3. **Tool result event** (line 127-141) - Output + duration -4. **Tool execution event** (line 143-156) - For logging - -### File: `/internal/agent/observe.go` (event emission for analysis) - -1. **Final answer event** (line 85-103) - When agent stops -2. **Thinking events** (line 189-198 in think.go) - Thought streaming - -**EventBus types:** -- `EventAgentToolCall` - Tool invocation -- `EventAgentTool` - Tool execution -- `EventAgentToolResult` - Tool result -- `EventAgentFinalAnswer` - Final answer -- `EventAgentThought` - Thinking content - ---- - -## Summary Table - -| Aspect | Details | -|--------|---------| -| **ReAct Loop File** | `/internal/agent/engine.go` (executeLoop) | -| **Tool Dispatch** | `/internal/agent/act.go` (executeToolCalls) - AUTOMATIC | -| **System Prompts** | `/internal/agent/prompts.go` (progressive RAG + pure agent) | -| **Wiki Tool Prompts** | `/internal/agent/prompts_wiki.go` (for ingest pipeline ONLY) | -| **Wiki Tool Registration** | `/internal/application/service/agent_service.go` (line 370-389) - AUTO-DETECT | -| **Wiki Tool Impl** | `/internal/agent/tools/wiki_tools.go` (5 tools) | -| **Synthesis Detection** | `/internal/application/service/wiki_ingest.go` (line 350-389) - HEURISTIC | -| **Tool Visibility** | `/internal/agent/observe.go` buildToolsForLLM() | -| **Is wiki_write_page auto-triggered?** | **NO** - LLM decides based on tool description + reasoning | -| **Dedicated wiki-specific Agent prompt?** | **NO** - Wiki prompts are for ingest, not Agent system prompt | - ---- - -## Key Takeaways - -1. ✅ **Agent uses ReAct loop** - Reason (LLM) → Act (tool dispatch) → Observe (results) → Repeat -2. ✅ **Tools are conditionally registered** - Wiki tools added if wiki KBs detected -3. ✅ **Tool dispatch is automatic** - No user prompt needed, LLM decides based on context -4. ❌ **No dedicated wiki system prompt** - General RAG prompt, wiki tools described minimally in tool definition -5. ❌ **`wiki_write_page` NOT guaranteed** - LLM must decide it's valuable, no explicit instruction -6. ✅ **Synthesis detection exists** - But in ingest pipeline, not Agent loop (heuristic, not LLM-driven) - diff --git a/ANALYSIS_SUMMARY.md b/ANALYSIS_SUMMARY.md deleted file mode 100644 index 989801c2..00000000 --- a/ANALYSIS_SUMMARY.md +++ /dev/null @@ -1,319 +0,0 @@ -# WeKnora Agent & Language Infrastructure - Complete Analysis Summary - -**Generated:** April 7, 2026 -**Status:** Complete ✅ - ---- - -## Executive Summary - -This analysis addresses four key areas of the WeKnora codebase: - -1. **Agent ReAct Engine Architecture** - Understanding how tools are dispatched -2. **System Prompts** - How the agent learns about available tools -3. **Wiki Tool Registration** - Dynamic tool availability based on KB type -4. **Language Infrastructure Refactoring** - Eliminating duplicate language logic - -### Key Findings - -✅ **Agent uses automatic tool dispatch** - No user intervention needed, LLM decides tool usage -✅ **Wiki tools conditionally registered** - Only visible when wiki KBs are detected -✅ **System prompts are generic** - No dedicated wiki-specific prompt for the Agent -✅ **Language infrastructure exists** - Middleware contains reusable language mapping -❌ **wiki_write_page not guaranteed** - LLM must independently decide to use it -❌ **Synthesis detection is heuristic** - In ingest pipeline, not Agent loop - ---- - -## Document Overview - -### 1. **AGENT_WIKI_ANALYSIS.md** (16 KB) -**Purpose:** Complete technical analysis of the Agent ReAct engine - -**Sections:** -- Agent ReAct Engine - Main Loop Architecture -- Tool Dispatch Mechanism - Automatic, Not User-Triggered -- System Prompts - Where Tools Are Described -- Wiki Tool Registration - Conditional Based on KB Type -- Wiki Tools Implementation - 5 Tools Overview -- How the Agent Knows About Wiki Tools -- Is There a Dedicated Wiki-Specific System Prompt? (Answer: NO) -- Synthesis Detection - Where It Actually Happens -- Complete Tool List and Filter Logic -- Event-Driven Architecture -- Summary Table - -**Key Code Files Referenced:** -- `/internal/agent/engine.go` - Core ReAct engine -- `/internal/agent/act.go` - Tool dispatch -- `/internal/agent/prompts.go` - System prompt building -- `/internal/agent/tools/wiki_tools.go` - Wiki tool implementations -- `/internal/application/service/agent_service.go` - Tool registration -- `/internal/application/service/wiki_ingest.go` - Wiki ingest pipeline - ---- - -### 2. **LANGUAGE_MIDDLEWARE_ANALYSIS.md** (11 KB) -**Purpose:** Identify and document existing language infrastructure - -**Sections:** -- Existing Language Middleware Infrastructure -- Current Wiki Ingest Language Logic (NEEDS REFACTORING) -- Refactoring Recommendations -- Integration Points -- Implementation Checklist -- Additional Observations -- Code Migration Path -- Files Modified Summary - -**Key Functions Identified:** -- `types.LanguageLocaleName()` - 9+ language mapping (the solution!) -- `types.LanguageFromContext()` - Extract language from context -- `types.DefaultLanguage()` - Get configured default language -- `types.EnvLanguage()` - Read WEKNORA_LANGUAGE env var -- `middleware.Language()` - HTTP middleware for language extraction -- `middleware.parseFirstLanguageTag()` - Parse Accept-Language header - ---- - -### 3. **REFACTORING_PLAN.md** (6.3 KB) -**Purpose:** Detailed implementation plan for language refactoring - -**Sections:** -- Problem Statement -- Solution Overview -- Implementation Details (with code diffs) -- Impact Analysis -- Supported Languages (9+) -- Backward Compatibility Analysis -- Testing Recommendations -- Future Enhancement Options -- Implementation Steps (5 steps) -- Rollback Plan - -**The One-Line Fix:** -```go -// Replace lines 135-141 in wiki_ingest.go with: -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Benefits:** -- Reduces code from 6 lines to 1 line -- Supports 9+ languages instead of 2 -- Eliminates code duplication -- Improves maintainability -- Fully backward compatible - ---- - -### 4. **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** (3.0 KB) -**Purpose:** Quick copy-paste guide for implementation - -**Sections:** -- TL;DR Summary -- What to Change (exact location + code) -- Key Benefits Table -- Function Reference -- Testing Instructions -- Implementation Checklist - -**Perfect for:** Developers implementing the refactoring quickly - ---- - -## Key Questions Answered - -### Q1: How does the Agent's ReAct engine dispatch tools? - -**Answer:** Automatic and LLM-driven. - -**Evidence:** -- File: `/internal/agent/engine.go` - `executeLoop()` method (lines 260-394) -- File: `/internal/agent/act.go` - `executeToolCalls()` function (lines 68-89) -- Tools are called automatically after LLM response without user intervention -- Max 5 iterations per query, each iteration: Think → Analyze → Act → Observe - -**Key Detail:** Tool execution is triggered by LLM decision, not user action. - -### Q2: What system prompts does the Agent use? - -**Answer:** Generic RAG or Pure Agent templates, no dedicated wiki prompt. - -**Evidence:** -- File: `/internal/agent/prompts.go` - `BuildSystemPromptWithOptions()` (lines 315-360) -- Two templates: - - `GetPureAgentSystemPrompt()` - For no knowledge bases - - `GetProgressiveRAGSystemPrompt()` - For knowledge bases -- Placeholders: `{{knowledge_bases}}`, `{{web_search_status}}`, `{{current_time}}`, `{{language}}` -- Wiki-specific prompts are in `prompts_wiki.go` but used only by ingest pipeline, not Agent - -### Q3: How does the Agent know about wiki tools? - -**Answer:** Via conditional registration based on KB type detection. - -**Evidence:** -- File: `/internal/application/service/agent_service.go` - `registerTools()` (lines 316-477) -- Lines 370-389: Iterate search targets, detect wiki KBs by type -- If wiki KBs found → automatically add 5 wiki tools to allowed tools list -- Tools then passed to LLM via `buildToolsForLLM()` in `/internal/agent/observe.go` - -**Key Detail:** Wiki tools only visible if wiki KBs are in search targets. - -### Q4: Is there a dedicated wiki-related system prompt for the Agent? - -**Answer:** NO. There is no such prompt. - -**Evidence:** -- Searched `prompts.go` - no wiki-specific system prompt -- Wiki prompts in `prompts_wiki.go` are for ingest pipeline only, not Agent loop -- Tool description is minimal (lines 91-92 in `wiki_tools.go`) -- Agent decides to use `wiki_write_page` based on general reasoning, not explicit instruction - -**Implication:** `wiki_write_page` is NOT guaranteed to be called - LLM must independently decide it's appropriate. - -### Q5: Can the wiki language logic be refactored? - -**Answer:** YES, completely. Reuse `types.LanguageLocaleName()`. - -**Current Issue:** -- `wiki_ingest.go` lines 135-141 contain hardcoded language mapping (2 languages only) -- `types.LanguageLocaleName()` (lines 85-112 in `context_helpers.go`) already does this (9+ languages) -- Duplicated logic, inconsistent naming, hard to extend - -**Solution:** -```go -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Benefits:** -- 6 lines → 1 line (83% reduction) -- 2 languages → 9+ languages -- Consistent with middleware naming -- Centralized maintenance -- Fully backward compatible - ---- - -## Recommended Actions - -### Immediate (Next Sprint) -1. ✅ Review `AGENT_WIKI_ANALYSIS.md` for understanding Agent architecture -2. ✅ Review `LANGUAGE_MIDDLEWARE_ANALYSIS.md` for language infrastructure -3. 🔄 **Plan refactoring sprint** using `REFACTORING_PLAN.md` - -### Short-term (1-2 weeks) -1. 🔄 **Implement language refactoring** using `LANGUAGE_REFACTORING_QUICK_REFERENCE.md` - - Edit 1 file, 6 lines → 1 line - - Run existing tests - - Commit and merge - - Time estimate: 30 minutes - -### Medium-term (Optional Enhancements) -1. Add support for context-aware language fallback (use context language if KB language empty) -2. Normalize `WikiLanguage` storage format from short codes to full locales -3. Audit codebase for other hardcoded language mappings - -### Long-term (Architectural) -1. Document language handling best practices -2. Consider similar refactorings for other duplicated logic -3. Expand language support based on user demand - ---- - -## File Locations & Quick Links - -### Analysis Documents -| Document | Size | Purpose | -|----------|------|---------| -| `AGENT_WIKI_ANALYSIS.md` | 16 KB | Complete Agent architecture analysis | -| `LANGUAGE_MIDDLEWARE_ANALYSIS.md` | 11 KB | Language infrastructure deep dive | -| `REFACTORING_PLAN.md` | 6.3 KB | Detailed implementation plan | -| `LANGUAGE_REFACTORING_QUICK_REFERENCE.md` | 3 KB | Quick copy-paste guide | -| `ANALYSIS_SUMMARY.md` | This file | Executive overview | - -### Code Files Referenced - -**Agent Engine:** -- `/internal/agent/engine.go` - ReAct loop implementation -- `/internal/agent/act.go` - Tool execution -- `/internal/agent/observe.go` - Tool visibility -- `/internal/agent/think.go` - LLM invocation -- `/internal/agent/prompts.go` - System prompt building - -**Tools:** -- `/internal/agent/tools/wiki_tools.go` - 5 wiki tool implementations -- `/internal/agent/tools/definitions.go` - Tool metadata - -**Services:** -- `/internal/application/service/agent_service.go` - Tool registration -- `/internal/application/service/wiki_ingest.go` - Wiki ingest pipeline (to be refactored) - -**Infrastructure:** -- `/internal/middleware/language.go` - Language extraction middleware -- `/internal/types/context_helpers.go` - Language helpers (LanguageLocaleName function) -- `/internal/types/const.go` - Context key definitions - ---- - -## Testing Recommendations - -### Unit Tests -```bash -# Test language mapping -go test -v ./internal/types -run TestLanguageLocaleName - -# Test agent engine -go test -v ./internal/agent -run TestEngine - -# Test wiki ingest (after refactoring) -go test -v ./internal/application/service -run TestWikiIngest -``` - -### Integration Tests -```bash -# Full test suite -go test -v ./internal/... -``` - -### Manual Testing (After Refactoring) -1. Create wiki KB with WikiLanguage: "zh" → Verify Chinese output -2. Create wiki KB with WikiLanguage: "en" → Verify English output -3. Create wiki KB with WikiLanguage: "ko" → Verify Korean output (new!) -4. Create wiki KB with WikiLanguage: "unknown" → Verify graceful fallback - ---- - -## Glossary - -**ReAct:** Reasoning + Acting - LLM loop that reasons about problems and invokes tools -**Progressive RAG:** Retrieval-Augmented Generation mode with knowledge bases -**Pure Agent:** Mode with no knowledge bases -**Tool Registry:** Central registry holding all available tools -**Automatic Tool Dispatch:** Tools are executed by engine when LLM decides, without user confirmation -**Synthesis Detection:** Heuristic that counts page types and suggests synthesis opportunities -**EventBus:** Event-driven system for UI feedback - ---- - -## Contact & Follow-up - -**Questions about analysis?** Review the specific document sections above. - -**Ready to implement?** Start with `LANGUAGE_REFACTORING_QUICK_REFERENCE.md`. - -**Need more details?** Each major document section has code snippets and file references. - ---- - -## Version History - -| Version | Date | Changes | -|---------|------|---------| -| 1.0 | 2026-04-07 | Initial analysis and documentation | - ---- - -**End of Summary** - -All documents are located in `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/` - diff --git a/COMPLETION_REPORT.md b/COMPLETION_REPORT.md deleted file mode 100644 index 3eb4fc2e..00000000 --- a/COMPLETION_REPORT.md +++ /dev/null @@ -1,323 +0,0 @@ -# WikiConfig Update Fix - COMPLETION REPORT - -**Project:** Fix WikiConfig Updates in Knowledge Base Configuration -**Status:** ✅ **COMPLETE** -**Date Completed:** April 7, 2026 -**Implementation Time:** ~4 hours - ---- - -## 📋 Executive Summary - -Successfully identified, analyzed, and fixed a critical bug preventing wiki configuration from being updated through the REST API. The fix was implemented across three system layers with comprehensive documentation and is ready for production deployment. - ---- - -## 🎯 What Was Accomplished - -### Phase 1: Analysis (Previous Session) -- ✅ Comprehensive trace of wiki_config flow through entire system -- ✅ Root cause identified: Missing `WikiConfig` field in `KnowledgeBaseConfig` struct -- ✅ Asymmetry discovered between create and update endpoints -- ✅ Four detailed analysis documents created - -### Phase 2: Implementation (This Session) -- ✅ Backend types layer: Added `WikiConfig` field to `KnowledgeBaseConfig` struct -- ✅ Backend service layer: Added wiki_config persistence logic -- ✅ Frontend layer: Added WikiConfig type hints for IDE completion -- ✅ Code changes committed with proper attribution -- ✅ Zero breaking changes, 100% backward compatible - -### Phase 3: Documentation (This Session) -- ✅ Executive summary for stakeholders (EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md) -- ✅ Complete technical implementation guide (WIKI_CONFIG_FIX_COMPLETE.md) -- ✅ Detailed implementation summary (IMPLEMENTATION_SUMMARY.md) -- ✅ Testing and verification procedures (WIKI_CONFIG_VERIFICATION.md) -- ✅ Documentation index by audience (README_WIKI_CONFIG_FIX.md) -- ✅ Changes summary with all details (CHANGES_SUMMARY.txt) - ---- - -## 📊 Implementation Statistics - -| Metric | Value | -|--------|-------| -| Files Modified | 3 | -| Lines Added | 43 | -| Lines Removed | 20 | -| Net Changes | +23 lines | -| Code Commits | 2 | -| Documentation Files | 6 | -| Test Cases Provided | 4 | -| Breaking Changes | 0 | -| Backward Compatibility | 100% ✅ | - ---- - -## 🔧 Code Changes Summary - -### Commit 1: `b09893d5` - Fix Implementation -**Fix: Enable wiki_config updates in knowledge base configuration** - -Changes: -1. `internal/types/knowledgebase.go` (Lines 107-108) - - Added `WikiConfig *WikiConfig` field to `KnowledgeBaseConfig` struct - -2. `internal/application/service/knowledgebase.go` (Lines 297-299) - - Added persistence logic: `if config.WikiConfig != nil { kb.WikiConfig = config.WikiConfig }` - -3. `frontend/src/api/knowledge-base/index.ts` (Lines 31-37, 49-64) - - Added WikiConfig type hints to createKnowledgeBase() and updateKnowledgeBase() - -### Commit 2: `18fe50f3` - Documentation -**Docs: Add comprehensive WikiConfig update fix documentation** - -Added 6 comprehensive documentation files: -1. EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md -2. WIKI_CONFIG_FIX_COMPLETE.md -3. IMPLEMENTATION_SUMMARY.md -4. WIKI_CONFIG_VERIFICATION.md -5. README_WIKI_CONFIG_FIX.md -6. CHANGES_SUMMARY.txt - ---- - -## ✅ Quality Assurance - -### Code Quality -- ✅ Follows existing code patterns (mirrors FAQConfig implementation) -- ✅ Proper struct tags for JSON marshaling/unmarshaling -- ✅ Type-safe implementation with no type casting -- ✅ Null-safe checks before accessing config - -### Testing -- ✅ 4 comprehensive test cases provided -- ✅ Test cases cover all aspects: create, update, read, database -- ✅ Curl examples provided for manual testing -- ✅ Database query provided for verification - -### Documentation -- ✅ 6 comprehensive documentation files -- ✅ Multiple audiences addressed (PM, Dev, QA, DevOps) -- ✅ Complete cross-references between documents -- ✅ Troubleshooting section included -- ✅ Rollback procedures documented - -### Deployment Readiness -- ✅ Backward compatible with existing code -- ✅ No database migrations required -- ✅ Zero breaking changes -- ✅ Code-only change, no infrastructure changes -- ✅ Simple rollback procedure - ---- - -## 📚 Documentation Deliverables - -### 1. For Project Managers -**Document:** EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md -- Business impact analysis -- Risk assessment (LOW risk) -- Deployment timeline (5-7 days) -- Stakeholder action items - -### 2. For Backend Developers -**Documents:** WIKI_CONFIG_FIX_COMPLETE.md, IMPLEMENTATION_SUMMARY.md -- Root cause analysis -- Complete data flow diagrams -- Code examples and snippets -- Unit test examples -- Impact analysis - -### 3. For QA/Testers -**Document:** WIKI_CONFIG_VERIFICATION.md -- 4 complete test cases with curl commands -- Expected results for each test -- Database verification procedures -- Comprehensive verification checklist - -### 4. For DevOps/SRE -**Document:** WIKI_CONFIG_FIX_COMPLETE.md (Deployment section) -- Deployment checklist -- Monitoring recommendations -- Rollback plan -- No downtime required - -### 5. For All Audiences -**Document:** README_WIKI_CONFIG_FIX.md -- Documentation index by role -- Quick start guide -- Troubleshooting section -- Cross-references to all docs - ---- - -## 🚀 Deployment Readiness Checklist - -### Code Level -- [x] Implemented across all three system layers -- [x] Follows existing code patterns -- [x] Includes proper type safety -- [x] Has null-safe checks -- [x] Committed with proper messages - -### Testing Level -- [x] 4 comprehensive test cases provided -- [x] Manual testing steps documented -- [x] Database verification procedures included -- [x] Expected results specified for each test - -### Documentation Level -- [x] Executive summary for stakeholders -- [x] Technical documentation for developers -- [x] Testing procedures for QA -- [x] Deployment guide for DevOps -- [x] Troubleshooting guide for support - -### Deployment Level -- [x] Backward compatible implementation -- [x] No database migrations required -- [x] Zero breaking changes -- [x] Simple rollback procedure -- [x] Low deployment risk - ---- - -## 🎓 Key Learning Points - -### Root Cause Analysis -The issue demonstrated an important architectural pattern: -- **Asymmetry** between create (uses full struct) and update (uses limited struct) -- **Silent data loss** - JSON unmarshaling silently drops unknown fields -- **Importance of consistency** - All configuration types should be updatable - -### Solution Pattern -The fix followed an established pattern in the codebase: -- Used same approach as `FAQConfig` -- Maintained consistency across configuration types -- Applied to all three system layers (types, service, frontend) - -### Testing Approach -Four-layer testing strategy: -1. **Unit test** - Service logic -2. **Integration test** - API handler -3. **API test** - HTTP request/response -4. **Database test** - Persistence verification - ---- - -## 📈 Impact Analysis - -### Business Impact -- ✅ Enables wiki features to be fully configured -- ✅ Removes blocker for wiki feature adoption -- ✅ Improves user experience -- ✅ No additional infrastructure costs - -### Technical Impact -- ✅ No performance degradation -- ✅ Minimal code footprint (+23 net lines) -- ✅ No architectural changes -- ✅ Maintains backward compatibility - -### Operational Impact -- ✅ No deployment downtime required -- ✅ Simple rollback if issues occur -- ✅ Minimal monitoring overhead -- ✅ No database maintenance required - ---- - -## 🔄 Next Steps - -### Immediate (Today) -1. ✅ Code complete and committed -2. ✅ Documentation complete -3. → Share commits with team for review - -### Short Term (1-2 days) -4. → Code review and approval -5. → Run automated tests -6. → Manual testing verification - -### Medium Term (3-7 days) -7. → Deploy to staging environment -8. → Verify in staging with test cases -9. → Deploy to production -10. → Monitor logs and user feedback - -### Follow-up -- Monitor wiki_config operations in production logs -- Collect user feedback on wiki configuration feature -- Plan enhancements based on usage patterns - ---- - -## 🏆 Success Criteria - ALL MET ✅ - -- ✅ Problem identified and root cause documented -- ✅ Solution implemented across all three system layers -- ✅ Code changes verified and committed -- ✅ Backward compatibility confirmed -- ✅ Documentation comprehensive and clear -- ✅ Test cases provided and documented -- ✅ Deployment procedures specified -- ✅ Risk assessment completed (LOW) -- ✅ Ready for production deployment - ---- - -## 📞 Support & References - -### Documentation Files -1. **README_WIKI_CONFIG_FIX.md** - Start here for documentation index -2. **EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md** - For stakeholders -3. **WIKI_CONFIG_FIX_COMPLETE.md** - Technical overview -4. **IMPLEMENTATION_SUMMARY.md** - Developer guide -5. **WIKI_CONFIG_VERIFICATION.md** - Testing procedures -6. **CHANGES_SUMMARY.txt** - Concise summary - -### Code References -- **Commit:** `b09893d5` (fix implementation) -- **Commit:** `18fe50f3` (documentation) -- **Files Modified:** - - `internal/types/knowledgebase.go` - - `internal/application/service/knowledgebase.go` - - `frontend/src/api/knowledge-base/index.ts` - ---- - -## 📝 Sign-Off - -**Implementation:** ✅ Complete -**Documentation:** ✅ Complete -**Testing Procedures:** ✅ Provided -**Deployment Ready:** ✅ Yes - -**Status:** 🟢 **READY FOR PRODUCTION** - ---- - -## Appendix: Git Commits - -```bash -# Commit 1: Implementation -b09893d5 fix: Enable wiki_config updates in knowledge base configuration - -# Commit 2: Documentation -18fe50f3 docs: Add comprehensive WikiConfig update fix documentation -``` - -**View changes:** -```bash -git show b09893d5 # View implementation commit -git show 18fe50f3 # View documentation commit -git diff b09893d5~1 b09893d5 # View implementation details -``` - ---- - -**Project Completion Date:** April 7, 2026 15:19:53 UTC+8 -**Total Implementation Time:** ~4 hours -**Status:** ✅ **COMPLETE AND PRODUCTION-READY** - diff --git a/DEPLOYMENT_CHECKLIST.md b/DEPLOYMENT_CHECKLIST.md deleted file mode 100644 index f792cf8e..00000000 --- a/DEPLOYMENT_CHECKLIST.md +++ /dev/null @@ -1,396 +0,0 @@ -# WeKnora Wiki Feature - Deployment Checklist - -**Last Updated:** April 7, 2026 -**Status:** ✅ READY FOR PRODUCTION - ---- - -## Pre-Deployment Verification - -### Code Quality -- [x] All tests passing (50+ test cases) -- [x] Build succeeds without errors -- [x] No security vulnerabilities identified -- [x] Code review requirements met -- [x] Documentation complete - -### Git Status -- [x] All changes committed -- [x] Commit history clean -- [x] No uncommitted files -- [x] Proper commit messages -- [x] Ready to push - -### Database -- [x] Migration files created (000032_wiki_pages.up/down.sql) -- [x] Schema validated -- [x] Indexes defined -- [x] Foreign keys configured -- [x] Rollback capability verified - -### Configuration -- [x] Container DI setup complete -- [x] Router endpoints registered -- [x] Middleware properly chained -- [x] Error handling configured -- [x] Logging implemented - ---- - -## Deployment Steps - -### 1. Pre-Production (Staging) - -#### Database Migration -```bash -# Backup current database -mysqldump -u root -p weknora > backup_$(date +%Y%m%d_%H%M%S).sql - -# Run migration -go run ./cmd/migrate/main.go up - -# Verify tables -mysql -u root -p weknora -e "SHOW TABLES LIKE 'wiki%';" -``` - -#### Build & Test -```bash -# Build binary -cd cmd/server && go build -o weknora-staging - -# Run tests -go test ./... -v - -# Check binary -./weknora-staging --version -``` - -#### Staging Deploy -```bash -# Copy to staging server -scp weknora-staging staging.server:/opt/weknora/ - -# Start service -ssh staging.server "systemctl restart weknora-staging" - -# Verify logs -ssh staging.server "tail -f /var/log/weknora/staging.log" -``` - -### 2. Production Deployment - -#### Pre-Production Checks -```bash -# Verify staging health -curl -s https://staging.weknora.internal/health | jq . - -# Check wiki endpoints -curl -s https://staging.weknora.internal/api/v1/wiki/pages | jq . - -# Monitor logs for errors -ssh staging.server "grep -i error /var/log/weknora/staging.log | tail -20" -``` - -#### Production Database Migration -```bash -# Backup production database -mysqldump -u root -p weknora > backup_prod_$(date +%Y%m%d_%H%M%S).sql - -# Verify backup -mysql -u root -p < backup_prod_$(date +%Y%m%d_%H%M%S).sql --execute="SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='weknora';" - -# Run migration -go run ./cmd/migrate/main.go up - -# Verify migration -mysql -u root -p weknora -e "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='wiki_pages';" -``` - -#### Production Build & Deploy -```bash -# Build production binary -cd cmd/server && go build -ldflags="-s -w" -o weknora-prod - -# Copy to production servers -for server in prod1.weknora.internal prod2.weknora.internal; do - scp weknora-prod $server:/opt/weknora/ -done - -# Update services (with zero-downtime deployment) -ssh prod1.weknora.internal "systemctl restart weknora" -sleep 5 -ssh prod2.weknora.internal "systemctl restart weknora" - -# Verify production health -for server in prod1.weknora.internal prod2.weknora.internal; do - curl -s https://$server/health | jq . -done -``` - -#### Post-Deployment Verification -```bash -# Check wiki service endpoints -curl -s https://api.weknora.com/api/v1/wiki/pages | jq . - -# Test wiki operations -curl -X GET https://api.weknora.com/api/v1/wiki/pages?knowledge_base_id=test - -# Check logs -grep -i "wiki" /var/log/weknora/production.log | tail -50 - -# Monitor metrics -# - Check wiki page creation rate -# - Monitor ingest job completion -# - Verify API response times -``` - ---- - -## Rollback Plan (If Needed) - -### Immediate Rollback -```bash -# Stop current service -ssh prod.server "systemctl stop weknora" - -# Restore previous binary -ssh prod.server "cp /opt/weknora/weknora.backup /opt/weknora/weknora" - -# Restart service -ssh prod.server "systemctl start weknora" - -# Verify -curl -s https://api.weknora.com/health | jq . -``` - -### Database Rollback -```bash -# If migration caused issues, rollback -go run ./cmd/migrate/main.go down - -# Or restore from backup -mysql -u root -p < backup_prod_$(date +%Y%m%d_%H%M%S).sql -``` - -### Monitoring During Rollback -```bash -# Watch logs -ssh prod.server "tail -f /var/log/weknora/production.log | grep -i wiki" - -# Check error rate -curl -s https://api.weknora.com/api/v1/metrics | jq '.errors' -``` - ---- - -## Post-Deployment Monitoring - -### 1. Immediate (First Hour) - -- [ ] Monitor error logs for wiki-related errors -- [ ] Check wiki page creation rates -- [ ] Verify ingest pipeline is processing tasks -- [ ] Monitor API response times -- [ ] Check database query performance -- [ ] Monitor CPU and memory usage - -### 2. Short-term (First 24 Hours) - -- [ ] Run full test suite on production -- [ ] Verify all wiki endpoints responding -- [ ] Check wiki page search functionality -- [ ] Test agent wiki tools -- [ ] Monitor async task queue -- [ ] Verify database migrations completed - -### 3. Long-term (First Week) - -- [ ] Monitor wiki page generation quality -- [ ] Check entity/concept extraction accuracy -- [ ] Verify synthesis opportunity detection -- [ ] Monitor user feedback -- [ ] Analyze wiki usage patterns -- [ ] Review performance metrics - ---- - -## Health Checks - -### Endpoint Verification -```bash -# List all wiki pages -curl -s https://api.weknora.com/api/v1/wiki/pages | jq . - -# Get specific page -curl -s https://api.weknora.com/api/v1/wiki/pages/summary%2Ftest | jq . - -# Search wiki -curl -s https://api.weknora.com/api/v1/wiki/search?q=entity | jq . - -# Health check -curl -s https://api.weknora.com/health | jq . -``` - -### Database Verification -```bash -# Check wiki_pages table -mysql -u root -p weknora -e "SELECT COUNT(*) as total_pages FROM wiki_pages;" -mysql -u root -p weknora -e "SELECT page_type, COUNT(*) FROM wiki_pages GROUP BY page_type;" -mysql -u root -p weknora -e "SELECT status, COUNT(*) FROM wiki_pages GROUP BY status;" -``` - -### Service Verification -```bash -# Check service status -systemctl status weknora - -# Check logs for errors -grep -i error /var/log/weknora/production.log | wc -l - -# Check wiki ingest tasks -ps aux | grep wiki_ingest - -# Check connected clients -netstat -an | grep ESTABLISHED | wc -l -``` - ---- - -## Performance Targets - -After deployment, verify: - -| Metric | Target | Acceptance | -|--------|--------|-----------| -| API Response Time | < 100ms | ✅ Must achieve | -| Wiki Page Creation | < 5 seconds | ✅ Must achieve | -| Search Response | < 200ms | ✅ Must achieve | -| Ingest Pipeline | < 30s per document | ✅ Target | -| Error Rate | < 0.1% | ✅ Must achieve | -| Database Query | < 10ms | ✅ Target | - ---- - -## Troubleshooting Guide - -### Issue: Wiki pages not being created - -**Diagnosis:** -```bash -# Check ingest logs -grep -i "ingest" /var/log/weknora/production.log | grep -i error - -# Check async task queue -redis-cli LLEN wiki:ingest:queue - -# Check database -mysql -u root -p weknora -e "SELECT * FROM wiki_pages ORDER BY created_at DESC LIMIT 5;" -``` - -**Solution:** -- Verify LLM service is accessible -- Check async task queue configuration -- Verify database permissions -- Review error logs for specific errors - -### Issue: High API response times - -**Diagnosis:** -```bash -# Check database performance -mysql -u root -p weknora -e "SHOW PROCESSLIST;" - -# Check index usage -mysql -u root -p weknora -e "EXPLAIN SELECT * FROM wiki_pages WHERE knowledge_base_id = 'test';" - -# Check server resources -top -b -n 1 | head -20 -``` - -**Solution:** -- Add missing database indexes -- Optimize query patterns -- Increase connection pool size -- Scale horizontally if needed - -### Issue: Ingest pipeline not processing tasks - -**Diagnosis:** -```bash -# Check task queue -redis-cli KEYS "wiki:ingest:*" | redis-cli - -# Check worker logs -grep -i "task" /var/log/weknora/production.log | tail -50 - -# Check LLM connectivity -curl -s https://llm-service/health | jq . -``` - -**Solution:** -- Restart task worker process -- Verify LLM service connectivity -- Check Redis connection -- Review worker configuration - ---- - -## Rollback Triggers - -Automatic rollback should be triggered if: - -1. **Error Rate > 5%** - - Too many wiki operations failing - -2. **API Response Time > 1s** - - Performance degradation - -3. **Database Connection Pool Exhausted** - - Service unable to respond - -4. **Critical Errors in Logs** - - Data corruption or security issues - -5. **Task Queue Backing Up** - - Ingest pipeline unable to keep up - ---- - -## Success Criteria - -Deployment is successful when: - -- [x] All wiki endpoints responding -- [x] Wiki pages can be created and retrieved -- [x] Search functionality working -- [x] Ingest pipeline processing documents -- [x] Agent tools accessible -- [x] No critical errors in logs -- [x] Performance metrics within targets -- [x] Database stable -- [x] Users can access wiki UI -- [x] Async tasks completing - ---- - -## Sign-off - -**Deployment Date:** _______________ - -**Deployed By:** _______________ - -**Approved By:** _______________ - -**Notes:** -``` - - - - -``` - ---- - -**Status:** ✅ READY FOR PRODUCTION DEPLOYMENT - -All systems are operational and ready. Deploy with confidence! diff --git a/DOCUMENTATION_INDEX.md b/DOCUMENTATION_INDEX.md deleted file mode 100644 index dccb9287..00000000 --- a/DOCUMENTATION_INDEX.md +++ /dev/null @@ -1,360 +0,0 @@ -# WeKnora Frontend Analysis - Complete Documentation Index - -**Session Date:** April 20, 2026 -**Status:** ✅ Complete and Ready for Implementation -**Total Documentation:** 2287 lines across 4 primary documents - ---- - -## 📋 Quick Start - -### What You Need to Know (5 minutes) - -Start here if you just want to understand the bug and fix it: -→ **[QUICK_FIX_GUIDE.md](./QUICK_FIX_GUIDE.md)** (228 lines) - -### What Needs to Be Fixed (15 minutes) - -Understand the problem and the solution approach: -→ **[WIKI_CONFIG_FLOW_ANALYSIS.md](./WIKI_CONFIG_FLOW_ANALYSIS.md)** (501 lines) - -### Complete System Architecture (30 minutes) - -Understand how the entire KB system works: -→ **[KB_WIKI_ARCHITECTURE_ANALYSIS.md](./KB_WIKI_ARCHITECTURE_ANALYSIS.md)** (1021 lines) - -### Implementation Roadmap (20 minutes) - -Detailed step-by-step implementation plan: -→ **[Plans/../woolly-jumping-rabin-agent-a4799b0d64a0d4f44.md]** (in .claude-internal/plans/) - ---- - -## 📚 Document Directory - -### Primary Documents (Session 20 Apr 2026) - -| Document | Size | Focus | Audience | -|----------|------|-------|----------| -| **QUICK_FIX_GUIDE.md** | 228 L | Immediate fix procedure | Developers ready to code | -| **WIKI_CONFIG_FLOW_ANALYSIS.md** | 501 L | Problem root cause + solution | QA, reviewers, architects | -| **KB_WIKI_ARCHITECTURE_ANALYSIS.md** | 1021 L | Complete system design | Team leads, architects, new team members | -| **WEKNORA_ANALYSIS_SUMMARY.md** | 537 L | Overview + quick reference | Anyone starting work | -| **DOCUMENTATION_INDEX.md** | This file | Navigation guide | Everyone | - -### Historical Documents (Earlier Sessions) - -These documents contain related analysis and may have partial/duplicate information: - -- `KB_WIKI_ARCHITECTURE_ANALYSIS.md` ← **USE THIS (updated)** -- `WIKI_TECHNICAL_ANALYSIS.md` -- `WIKI_CONFIG_FLOW_ANALYSIS.md` ← **USE THIS (complete)** -- `KNOWLEDGE_MODEL_ANALYSIS.md` -- `FRONTEND_KB_WIKI_ANALYSIS_COMPREHENSIVE.md` -- And others... - -**Recommendation:** Focus on the 4 primary documents listed above. They contain the latest findings. - ---- - -## 🎯 By Use Case - -### "I need to fix the bug RIGHT NOW" -1. Read: **QUICK_FIX_GUIDE.md** (5 min) -2. Make the 3 code changes -3. Test using provided checklist -4. Done! ✅ - -### "I need to understand what's broken and why" -1. Read: **WIKI_CONFIG_FLOW_ANALYSIS.md** (15 min) - - Understand the data model (section 1-2) - - See the exact problem (section 3-4) - - Get detailed root cause (section 5) - -### "I'm new to the team and need to understand the KB system" -1. Read: **KB_WIKI_ARCHITECTURE_ANALYSIS.md** (30 min) - - Data models (section 1-2) - - How chunks work (section 3) - - Wiki pages (section 4) - - The complete pipeline (section 5) - -### "I need to implement a feature that touches KB settings" -1. Review: **KB_WIKI_ARCHITECTURE_ANALYSIS.md** sections 7-12 -2. Study: Code examples and interfaces (section 9-10) -3. Reference: API endpoints (section 10) -4. Follow: Configuration hierarchy (section 13) - -### "I need to test this fix" -1. Quick test: **QUICK_FIX_GUIDE.md** "Testing the Fix" -2. Detailed testing: Implementation plan document -3. Regression testing: Original test suite - ---- - -## 🔍 Finding Specific Information - -### Data Models -- **KnowledgeBase struct:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 1.1 -- **WikiConfig struct:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 1.3 OR WIKI_CONFIG_FLOW_ANALYSIS.md § 2a -- **Knowledge (document):** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 2 -- **Chunk & indexing:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 3 -- **WikiPage struct:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 4 - -### Data Flows -- **Document ingestion:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 11.1 -- **Wiki generation:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 5 -- **Agent interaction:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 11.2 -- **KB settings update:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 11.3 OR WIKI_CONFIG_FLOW_ANALYSIS.md § 3-4 - -### API Endpoints -- **All KB endpoints:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 10 -- **Create vs Update:** WIKI_CONFIG_FLOW_ANALYSIS.md § 3 - -### Frontend Components -- **Main UI:** KB_WIKI_ARCHITECTURE_ANALYSIS.md § 7.4 -- **Component locations:** WEKNORA_ANALYSIS_SUMMARY.md "Frontend Component Map" -- **Wiki settings code:** Any doc (KB_WIKI_ARCHITECTURE_ANALYSIS.md § 7.4) - -### The Bug Details -- **Quick explanation:** QUICK_FIX_GUIDE.md "The Problem" -- **Detailed trace:** WIKI_CONFIG_FLOW_ANALYSIS.md § 5-6 -- **Code snippets:** WIKI_CONFIG_FLOW_ANALYSIS.md § 3 (side-by-side comparison) - -### The Fix -- **Quick version:** QUICK_FIX_GUIDE.md "The Solution" -- **Detailed version:** WIKI_CONFIG_FLOW_ANALYSIS.md § "Required Fixes" -- **Implementation plan:** Plans/woolly-jumping-rabin-agent-*.md - ---- - -## 📖 Reading Paths by Role - -### Frontend Developer -1. WEKNORA_ANALYSIS_SUMMARY.md - "Frontend Architecture" -2. KB_WIKI_ARCHITECTURE_ANALYSIS.md § 7 - Frontend API layer -3. QUICK_FIX_GUIDE.md § "Change 3" - Type hints update - -### Backend Developer -1. QUICK_FIX_GUIDE.md - Quick overview -2. WIKI_CONFIG_FLOW_ANALYSIS.md § 3-4 - Handler and service layer -3. KB_WIKI_ARCHITECTURE_ANALYSIS.md § 1-6 - Data models and services - -### QA / Test Engineer -1. QUICK_FIX_GUIDE.md "Testing the Fix" -2. Implementation plan "Testing Strategy" -3. KB_WIKI_ARCHITECTURE_ANALYSIS.md § 5 - Understanding the pipeline - -### Technical Architect -1. KB_WIKI_ARCHITECTURE_ANALYSIS.md - Complete architecture -2. KB_WIKI_ARCHITECTURE_ANALYSIS.md § 8 - Database schema -3. KB_WIKI_ARCHITECTURE_ANALYSIS.md § 14 - Critical integration points - -### Product Manager -1. WEKNORA_ANALYSIS_SUMMARY.md - "What We Found" -2. QUICK_FIX_GUIDE.md - "The Problem" -3. KB_WIKI_ARCHITECTURE_ANALYSIS.md § 5 - Feature explanation - ---- - -## 🚀 Implementation Checklist - -### Before You Start -- [ ] Read QUICK_FIX_GUIDE.md -- [ ] Understand the 3 changes needed -- [ ] Verify you have git access to the repo -- [ ] Check you can compile Go code - -### Making the Changes -- [ ] Edit `internal/types/knowledgebase.go` - Add WikiConfig field -- [ ] Edit `internal/application/service/knowledgebase.go` - Add update logic -- [ ] (Optional) Edit `frontend/src/api/knowledge-base/index.ts` - Add types - -### Testing -- [ ] Go compilation successful -- [ ] TypeScript compilation successful -- [ ] Unit tests pass -- [ ] Manual testing (30 second test) -- [ ] UI testing (create and edit KB with wiki) - -### Verification -- [ ] Create KB with wiki_config works -- [ ] Update KB wiki_config works -- [ ] Changes persist after page reload -- [ ] No regressions in other KB settings - -### Deployment -- [ ] Commit changes (with good message) -- [ ] Push to branch -- [ ] Create pull request -- [ ] Code review -- [ ] Merge -- [ ] Deploy - ---- - -## 🔗 Cross-References - -### Files That Need Changes -- `internal/types/knowledgebase.go` → WIKI_CONFIG_FLOW_ANALYSIS.md § 2c -- `internal/application/service/knowledgebase.go` → WIKI_CONFIG_FLOW_ANALYSIS.md § 4c -- `internal/handler/knowledgebase.go` → WIKI_CONFIG_FLOW_ANALYSIS.md § 3b -- `frontend/src/api/knowledge-base/index.ts` → WIKI_CONFIG_FLOW_ANALYSIS.md § 6b - -### Database Tables -- `knowledge_bases` → KB_WIKI_ARCHITECTURE_ANALYSIS.md § 8.1 -- `knowledges` → KB_WIKI_ARCHITECTURE_ANALYSIS.md § 8.1 -- `chunks` → KB_WIKI_ARCHITECTURE_ANALYSIS.md § 8.1 -- `wiki_pages` → KB_WIKI_ARCHITECTURE_ANALYSIS.md § 8.1 - -### Service Interfaces -- `KnowledgeBaseService` → KB_WIKI_ARCHITECTURE_ANALYSIS.md § 9.1 -- `WikiPageService` → KB_WIKI_ARCHITECTURE_ANALYSIS.md § 9.1 -- `RetrieveEngine` → KB_WIKI_ARCHITECTURE_ANALYSIS.md § 3.3-3.4 - ---- - -## 📊 Statistics - -### Documentation Scope -- **Total Lines:** 2287 across 4 documents -- **Code Snippets:** 40+ code examples -- **Diagrams:** 5 ASCII flow diagrams -- **Tables:** 15+ reference tables -- **API Endpoints Documented:** 20+ - -### System Coverage -- **Go Files Analyzed:** 15+ -- **TypeScript Files Analyzed:** 5+ -- **Database Tables:** 5 -- **Service Layers:** 3 (handler, service, repository) -- **API Endpoints:** 20+ -- **Frontend Components:** 8+ - -### Fix Scope -- **Files to Modify:** 2-3 -- **Lines of Code:** ~10 LOC -- **Complexity:** Low -- **Risk Level:** Low -- **Estimated Time:** 5 minutes - ---- - -## ❓ FAQ - -**Q: Where do I start?** -A: Read QUICK_FIX_GUIDE.md (5 minutes), then make the 3 changes. - -**Q: What if I get stuck?** -A: Check WIKI_CONFIG_FLOW_ANALYSIS.md for detailed explanations at each layer. - -**Q: How do I test?** -A: Use the "Testing the Fix" section in QUICK_FIX_GUIDE.md. - -**Q: Is this backward compatible?** -A: Yes, WikiConfig is optional (pointer), existing code keeps working. - -**Q: Do I need a database migration?** -A: No, the column already exists in the database. - -**Q: Can I implement just the backend?** -A: Yes, frontend is already sending wiki_config; backend just needs to receive it. - -**Q: Will this fix existing KBs' wiki_config?** -A: No, it enables updating wiki_config going forward. Existing configs remain unchanged. - -**Q: Should I read all 4 documents?** -A: No, start with QUICK_FIX_GUIDE.md. Read others only if you need more context. - ---- - -## 📞 Getting Help - -### If compilation fails -→ Check WIKI_CONFIG_FLOW_ANALYSIS.md § 2a for exact syntax of WikiConfig struct - -### If tests fail -→ See Implementation Plan "Testing Strategy" section - -### If you don't understand the architecture -→ Read KB_WIKI_ARCHITECTURE_ANALYSIS.md § 1-6 - -### If you need to debug -→ Review WIKI_CONFIG_FLOW_ANALYSIS.md "Tracing the Flow" section - ---- - -## ✅ Success Criteria - -Once you complete the fix, you should be able to: - -1. ✅ Create a KB with wiki enabled -2. ✅ Edit the KB and change wiki settings -3. ✅ Save the changes -4. ✅ Reload the page and see the changes persisted -5. ✅ No compilation errors -6. ✅ Tests pass -7. ✅ No regressions in other KB settings - ---- - -## 📝 Notes - -- All line numbers reference the code as of April 20, 2026 -- Code structure may evolve; use line numbers as guide, not absolute reference -- All documents are stored in the repo root directory: `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/` -- Implementation plan is in: `/Users/wizard/.claude-internal/plans/` - ---- - -## 🎓 Learning Resources - -### For Understanding the System -1. Start: WEKNORA_ANALYSIS_SUMMARY.md § "System Architecture at a Glance" -2. Deep dive: KB_WIKI_ARCHITECTURE_ANALYSIS.md § 1-7 -3. Practical: Follow a document through the pipeline (§ 11.1) - -### For Understanding the Bug -1. Start: QUICK_FIX_GUIDE.md § "The Problem" -2. Trace: WIKI_CONFIG_FLOW_ANALYSIS.md § "Tracing the Flow" -3. Root cause: WIKI_CONFIG_FLOW_ANALYSIS.md § 2-4 - -### For Understanding the Fix -1. Start: QUICK_FIX_GUIDE.md § "The Solution" -2. Why it works: WIKI_CONFIG_FLOW_ANALYSIS.md § "Required Fixes" -3. How to test: QUICK_FIX_GUIDE.md § "Testing the Fix" - ---- - -## 🎯 Next Steps - -### Immediate (Next 5 minutes) -1. Open QUICK_FIX_GUIDE.md -2. Read "The Problem" and "The Solution" -3. Verify you understand the 3 changes - -### Short Term (Next 30 minutes) -1. Make the 3 code changes -2. Run tests -3. Test in UI -4. Commit and push - -### Medium Term (Next few hours) -1. Create PR -2. Get review -3. Merge -4. Deploy - -### Long Term (Knowledge building) -1. Read KB_WIKI_ARCHITECTURE_ANALYSIS.md when you have time -2. Understand how wiki generation works -3. Understand how agents interact with KBs - ---- - -**Generated:** April 20, 2026 -**Maintained By:** Comprehensive analysis session -**Last Updated:** April 20, 2026 12:03 UTC - ---- - -**Ready to get started?** → Open [QUICK_FIX_GUIDE.md](./QUICK_FIX_GUIDE.md) ⚡ diff --git a/EXECUTIVE_SUMMARY.md b/EXECUTIVE_SUMMARY.md deleted file mode 100644 index 803b5161..00000000 --- a/EXECUTIVE_SUMMARY.md +++ /dev/null @@ -1,310 +0,0 @@ -# WeKnora Wiki Feature - Executive Summary - -**Project Status:** ✅ **COMPLETE - PRODUCTION READY** - -**Completion Date:** April 7, 2026 -**Build Status:** ✅ Passing (243MB executable) -**Test Status:** ✅ Passing (50+ test cases) -**Code Quality:** ✅ Verified -**Documentation:** ✅ Complete - ---- - -## Overview - -Successfully implemented and deployed a comprehensive AI-powered wiki feature for WeKnora knowledge bases. The system automatically generates, manages, and enhances wiki pages using LLM-powered extraction and synthesis. - -**Key Achievement:** Full end-to-end feature from database schema to frontend UI, with 9+ language support and production-ready code quality. - ---- - -## What Was Delivered - -### Core Feature -✅ **Automated Wiki Generation** - LLM-powered pipeline for creating wiki pages from documents -✅ **Multi-Language Support** - 9+ languages (Chinese, English, Korean, Japanese, Russian, French, German, Spanish, Portuguese) -✅ **Intelligent Extraction** - Entity and concept extraction in single LLM call for efficiency -✅ **Smart Management** - CRUD operations, search, filtering, and pagination -✅ **User Interface** - Beautiful Vue.js frontend for browsing and managing wikis - -### Technical Components -✅ **Backend Services** - 5 main services (WikiPageService, WikiIngestService, WikiLintService, WikiBoostService, WikiToolsService) -✅ **Database Layer** - GORM repository with optimized queries and proper indexes -✅ **API Endpoints** - 8 REST endpoints for full wiki management -✅ **Agent Integration** - Wiki tools for AI agents to query and manage wikis -✅ **Chat Enhancement** - Context injection into chat responses -✅ **Async Processing** - Non-blocking task queue for wiki generation - -### Testing & Quality -✅ **Unit Tests** - 50+ test cases covering all critical paths -✅ **Integration Tests** - End-to-end pipeline verification -✅ **Performance Tests** - Benchmarks showing 4.3 ns/op overhead -✅ **Code Coverage** - >90% on core logic -✅ **No Security Issues** - Code reviewed and validated - -### Documentation -✅ **README** - Comprehensive wiki feature guide -✅ **Deployment Guide** - Step-by-step production deployment -✅ **API Reference** - Complete endpoint documentation -✅ **Development Guide** - Instructions for extending the feature -✅ **Troubleshooting** - Common issues and solutions -✅ **Architecture Docs** - System design and data flow - ---- - -## Commit History - -``` -0f34c6f6 docs: Add comprehensive wiki feature README with API and deployment guide -c1771fbe docs: Add comprehensive deployment checklist and guide -2c1ad4e5 docs: Add final completion summary for wiki feature -8c3be4ca feat: Implement comprehensive wiki feature for knowledge bases (MAIN COMMIT) -6fce4de4 docs: Add quick reference card for language refactoring -b56b87a8 docs: Add language refactoring README with quick start guide -9913fac4 refactor: Replace hardcoded language logic with middleware infrastructure -``` - -**Total Changes:** 46 files, 8171+ insertions -**Build Size:** 243 MB (arm64 executable) - ---- - -## Key Statistics - -### Code -- **Backend Files:** 14 new services and models -- **Frontend Files:** 2 components + API client -- **Test Files:** 5 comprehensive test suites -- **Database:** 1 migration (wiki_pages table with 9 fields, 5 indexes) -- **Documentation:** 10+ detailed guides - -### Features -- **Page Types:** 6 types (Summary, Entity, Concept, Index, Log, Synthesis) -- **API Endpoints:** 8 operations (List, Get, Create, Update, Delete, Search, etc.) -- **Supported Languages:** 9+ -- **Test Cases:** 50+ -- **Response Time:** <200ms average for API calls - -### Quality Metrics -- **Build Status:** ✅ Passing -- **Test Status:** ✅ 50/50 Passing -- **Test Coverage:** >90% on core logic -- **Performance:** 4.3 ns/op (negligible overhead) -- **Security:** ✅ No vulnerabilities identified -- **Documentation:** 100% coverage - ---- - -## Production Readiness Checklist - -| Item | Status | Notes | -|------|--------|-------| -| **Code Implementation** | ✅ | All features complete | -| **Unit Tests** | ✅ | 50+ test cases passing | -| **Integration Tests** | ✅ | End-to-end verified | -| **Database Migration** | ✅ | Tested and validated | -| **API Endpoints** | ✅ | 8 endpoints fully functional | -| **Frontend UI** | ✅ | Vue.js component complete | -| **Build** | ✅ | 243MB executable | -| **Documentation** | ✅ | Comprehensive guides | -| **Security** | ✅ | No issues identified | -| **Performance** | ✅ | Benchmarked and optimized | -| **Language Support** | ✅ | 9+ languages tested | -| **Deployment Guide** | ✅ | Step-by-step instructions | - -**Overall Status:** ✅ **READY FOR PRODUCTION** - ---- - -## Deployment Information - -### Prerequisites -- Go 1.20+ -- MySQL 5.7+ or MariaDB 10.3+ -- Redis 6.0+ (for async tasks) -- Node.js 16+ (frontend) - -### Quick Start -```bash -# Build backend -cd cmd/server && go build -o weknora - -# Run migrations -go run ./cmd/migrate/main.go up - -# Start service -./weknora - -# Access UI -http://localhost:8080/wiki -``` - -### Production Deployment -- Full deployment guide available in [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) -- Staging tests complete -- Zero-downtime deployment supported -- Rollback procedures documented - ---- - -## Technical Highlights - -### Architecture Excellence -- **Clean Separation:** Handler → Service → Repository layers -- **Dependency Injection:** Proper IoC container setup -- **Error Handling:** Comprehensive error logging and reporting -- **Concurrency:** Async task processing with proper queue management -- **Scalability:** Database indexes optimized for large datasets - -### Code Quality -- **Best Practices:** Follows Go conventions and patterns -- **Type Safety:** Proper type system usage -- **Testing:** Comprehensive test coverage -- **Documentation:** Inline comments and doc strings -- **Refactoring:** DRY principle applied (language infrastructure reuse) - -### Language Support Innovation -- **Middleware Reuse:** Leverages existing language infrastructure -- **9+ Languages:** Comprehensive international support -- **Type Mapping:** Locale codes to human-readable names -- **Template Support:** Language substitution in LLM prompts -- **Performance:** 288M ops/sec, 4.3 ns/op overhead - ---- - -## Key Improvements - -### Efficiency -- **Single LLM Call:** Entity and concept extraction combined -- **Async Processing:** Non-blocking wiki generation -- **Intelligent Caching:** Database indexes for fast queries -- **Language Reuse:** No code duplication - -### User Experience -- **Intuitive UI:** Vue.js component with search and filtering -- **Auto-Generation:** Minimal manual effort required -- **Multi-Language:** Support for users worldwide -- **Rich Content:** Support for formatting and relationships - -### Reliability -- **Database Integrity:** Constraints and foreign keys -- **Error Handling:** Proper error propagation -- **Logging:** Comprehensive audit trail -- **Testing:** 50+ test cases -- **Rollback:** Migration rollback support - ---- - -## Business Value - -### Immediate Benefits -1. **Automation** - Reduces manual wiki creation time by 80%+ -2. **Consistency** - Ensures consistent structure and formatting -3. **Scale** - Handles unlimited wiki pages -4. **Quality** - LLM-powered content generation -5. **Speed** - Fast deployment and easy integration - -### Long-term Value -1. **Knowledge Base** - Builds searchable knowledge base automatically -2. **AI Agents** - Enables agents to query and manage wikis -3. **Chat Enhancement** - Improves chat responses with wiki context -4. **User Productivity** - Reduces search time through wiki browser -5. **Multi-Language** - Supports global audience - ---- - -## Risk Mitigation - -| Risk | Mitigation | -|------|-----------| -| LLM Latency | Async processing, no user blocking | -| Database Load | Proper indexes, query optimization | -| Memory Usage | Content truncation at 32KB limit | -| Error Handling | Comprehensive error logging | -| Rollback | Full migration rollback support | -| Language Issues | Fallback mechanism, testing for all languages | -| Concurrent Access | Database transactions and locking | - ---- - -## Support & Maintenance - -### Documentation Provided -- API Reference -- Deployment Guide -- Troubleshooting Guide -- Development Guide -- Architecture Diagrams -- Test Examples -- Code Comments - -### Monitoring -- Performance metrics documented -- Alert thresholds defined -- Health check endpoints available -- Logging infrastructure in place - -### Future Enhancements (Optional) -- Advanced wiki graph visualization -- Cross-document entity linking -- Automatic taxonomy generation -- Wiki page versioning -- Collaborative editing - ---- - -## Sign-Off - -**Project:** WeKnora Wiki Feature -**Version:** 1.0 -**Status:** ✅ COMPLETE & PRODUCTION READY -**Build:** 243MB (arm64) -**Tests:** 50/50 Passing - -**Deliverables:** -- [x] Complete backend implementation -- [x] Frontend UI -- [x] Database schema and migrations -- [x] Comprehensive test suite -- [x] Production documentation -- [x] Deployment guide -- [x] Build verification - -**Ready for:** -- [x] Staging deployment -- [x] Production deployment -- [x] User testing -- [x] Monitoring and operations - ---- - -## Next Steps - -1. **Review** - Team review of implementation -2. **Staging** - Deploy to staging environment -3. **Testing** - Full end-to-end testing -4. **Monitoring** - Setup monitoring and alerts -5. **Production** - Deploy to production -6. **Support** - Ongoing maintenance and support - ---- - -## Contact - -For questions about the implementation: -1. Review the documentation in [README_WIKI_FEATURE.md](README_WIKI_FEATURE.md) -2. Check the deployment guide: [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) -3. Review test examples in `internal/application/service/wiki_page_test.go` -4. Check API handler documentation in `internal/handler/wiki_page.go` - ---- - -**Final Status: ✅ PROJECT COMPLETE** - -All objectives achieved. The wiki feature is fully implemented, tested, documented, and ready for production deployment. - ---- - -*Generated: April 7, 2026* -*Project Duration: 2 sessions* -*Final Commit: 0f34c6f6* diff --git a/EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md b/EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md deleted file mode 100644 index be12bc5b..00000000 --- a/EXECUTIVE_SUMMARY_WIKI_CONFIG_FIX.md +++ /dev/null @@ -1,227 +0,0 @@ -# WikiConfig Update Fix - Executive Summary - -**Date:** April 7, 2026 -**Status:** ✅ **COMPLETE AND COMMITTED** -**Commit:** `b09893d5` - ---- - -## Overview - -Successfully fixed a critical bug preventing wiki configuration from being updated through the REST API. The issue was an asymmetry in the data model between knowledge base creation (which worked) and updates (which silently dropped configuration). - ---- - -## Problem Statement - -**Business Impact:** Users could enable wiki features when creating a knowledge base, but could not modify wiki settings afterward, making the wiki feature partially non-functional. - -**Technical Summary:** The `KnowledgeBaseConfig` struct used to deserialize PUT request bodies was missing the `WikiConfig` field. This caused JSON unmarshaling to silently drop any `wiki_config` data sent in update requests. - -**Example:** -```bash -# This worked: -POST /api/v1/knowledge-bases -{ "name": "My KB", "wiki_config": { "enabled": true } } - -# This didn't work (wiki_config was silently ignored): -PUT /api/v1/knowledge-bases/kb-123 -{ "config": { "wiki_config": { "enabled": true } } } -``` - ---- - -## Solution Implemented - -### Three-Layer Fix - -| Layer | File | Change | Lines | -|-------|------|--------|-------| -| **Backend Types** | `internal/types/knowledgebase.go` | Added `WikiConfig` field to `KnowledgeBaseConfig` struct | 107-108 | -| **Backend Service** | `internal/application/service/knowledgebase.go` | Added wiki_config persistence logic | 297-299 | -| **Frontend Types** | `frontend/src/api/knowledge-base/index.ts` | Added WikiConfig type hints | 31-37, 49-64 | - -**Total Impact:** 3 files modified, 43 lines added, 20 lines removed - ---- - -## Key Achievements - -✅ **Problem Solved:** Wiki configuration now persists on updates -✅ **Backward Compatible:** 100% - all changes are optional -✅ **Zero Risk:** Code-only change, no database migrations needed -✅ **Documented:** Comprehensive documentation for all stakeholders -✅ **Production Ready:** All three system layers properly fixed - ---- - -## Testing Coverage - -Four test cases provided: -1. **Create KB with wiki_config** → Expected: Persisted ✓ -2. **Update KB with wiki_config** → Expected: Persisted ✓ (NOW WORKS) -3. **Verify persistence via GET** → Expected: All fields present ✓ -4. **Database level verification** → Expected: JSONB column populated ✓ - ---- - -## Deployment Plan - -| Phase | Action | Timeline | -|-------|--------|----------| -| **Review** | Code review and approval | 1-2 days | -| **Test** | Run all test cases | 1-2 days | -| **Stage** | Deploy to staging environment | 1 day | -| **Verify** | Run test cases in staging | 1 day | -| **Prod** | Deploy to production | 1 day | -| **Monitor** | Watch for wiki_config operations | Ongoing | - -**Total Estimated Time:** 5-7 days - ---- - -## Risk Assessment - -**Overall Risk Level:** 🟢 **LOW** - -| Factor | Rating | Notes | -|--------|--------|-------| -| Code Complexity | Low | Simple null check and field assignment | -| Testing Scope | Moderate | Well-defined test cases provided | -| Deployment Risk | Low | Code-only, backward compatible | -| Rollback Risk | Very Low | Simple revert if needed | -| Performance Impact | None | Minimal overhead (one check) | - ---- - -## Success Metrics - -After deployment, these should be true: - -- ✅ Users can create KBs with wiki_config -- ✅ Users can update KB wiki_config via REST API -- ✅ All wiki_config fields properly persisted to database -- ✅ Frontend provides IDE autocompletion for wiki fields -- ✅ No breaking changes to existing code -- ✅ All existing workflows continue to work - ---- - -## Documentation Provided - -1. **README_WIKI_CONFIG_FIX.md** - Documentation index (START HERE) -2. **WIKI_CONFIG_FIX_COMPLETE.md** - Full technical overview -3. **IMPLEMENTATION_SUMMARY.md** - Detailed implementation guide -4. **WIKI_CONFIG_VERIFICATION.md** - Testing procedures -5. **CHANGES_SUMMARY.txt** - This comprehensive summary -6. **WIKI_CONFIG_QUICK_REFERENCE.md** - Developer quick reference - ---- - -## Stakeholder Actions - -### Project Manager -- [ ] Review this document -- [ ] Review deployment checklist in WIKI_CONFIG_FIX_COMPLETE.md -- [ ] Approve code review -- [ ] Schedule deployment window - -### Backend Developer -- [ ] Review commit `b09893d5` -- [ ] Check unit tests -- [ ] Verify against IMPLEMENTATION_SUMMARY.md - -### QA/Tester -- [ ] Use WIKI_CONFIG_VERIFICATION.md -- [ ] Execute all four test cases -- [ ] Sign off on testing - -### DevOps/Deployment -- [ ] Review deployment checklist -- [ ] Prepare rollback plan (simple git revert) -- [ ] Schedule maintenance window if needed (not required) - ---- - -## Questions & Answers - -**Q: Do we need database migrations?** -A: No. The `wiki_config` JSONB column already exists from migration 000032. - -**Q: Will this break existing code?** -A: No. All changes are backward compatible with optional fields. - -**Q: What if we find an issue after deployment?** -A: Simple rollback: `git revert b09893d5` - -**Q: Do we need downtime?** -A: No. This is a code-only change. - -**Q: How long will this take to test?** -A: 4 test cases, approximately 30 minutes for manual testing. - ---- - -## Financial Impact - -**Cost of Fix:** -- Development: 1-2 hours (already completed) -- Testing: 1-2 hours -- Deployment: 1 hour -- **Total:** 3-5 hours - -**Cost of Not Fixing:** -- Users cannot configure wiki features -- Feature partially broken -- Support burden for workarounds -- **Annual impact:** Significant (feature unusable) - -**ROI:** Extremely positive - enables critical feature with minimal effort. - ---- - -## Next Steps (Priority Order) - -1. **Immediate:** Review this document (30 mins) -2. **Day 1:** Code review and approval (1-2 hours) -3. **Day 2:** Run test cases (1-2 hours) -4. **Day 3:** Deploy to staging (30 mins) -5. **Day 4:** Verify in staging (1-2 hours) -6. **Day 5:** Deploy to production (1 hour) -7. **Ongoing:** Monitor logs and user feedback - ---- - -## Contacts - -**Implemented by:** Claude Opus 4.6 (1M context) -**Date:** April 7, 2026 -**Commit:** b09893d5a388d709ac144730f5d61bbc9cf460c8 - -For questions: -- Technical details: See WIKI_CONFIG_FIX_COMPLETE.md -- Testing help: See WIKI_CONFIG_VERIFICATION.md -- Implementation details: See IMPLEMENTATION_SUMMARY.md - ---- - -## Final Recommendation - -**✅ APPROVED FOR PRODUCTION DEPLOYMENT** - -This fix is: -- ✓ Complete and tested -- ✓ Properly documented -- ✓ Backward compatible -- ✓ Low risk -- ✓ Ready for immediate deployment - -**Recommendation:** Proceed with code review and deployment planning. - ---- - -**Status:** ✅ Ready for Production -**Quality:** Enterprise-grade -**Risk Level:** Low -**Estimated Deployment:** 5-7 days - diff --git a/FINAL_COMPLETION_SUMMARY.md b/FINAL_COMPLETION_SUMMARY.md deleted file mode 100644 index 24717888..00000000 --- a/FINAL_COMPLETION_SUMMARY.md +++ /dev/null @@ -1,401 +0,0 @@ -# WeKnora Wiki Feature - Final Completion Summary - -**Date:** April 7, 2026 -**Status:** ✅ COMPLETE AND COMMITTED -**Build Status:** ✅ PASSING (243MB binary) - ---- - -## Executive Summary - -The comprehensive WeKnora Wiki Feature has been successfully implemented, tested, and committed to the main branch. This feature enables AI-powered wiki page generation and management for knowledge bases, with support for 9+ languages. - -**Key Commit:** `8c3be4ca` - "feat: Implement comprehensive wiki feature for knowledge bases" - ---- - -## What Was Completed - -### 1. Backend Implementation (Complete) - -#### Data Models -- **WikiPage Type** (`internal/types/wiki_page.go`) - - Fields: ID, TenantID, KnowledgeBaseID, Slug, Title, Content, Summary, PageType, Status, SourceRefs - - PageTypes: Summary, Entity, Concept, Index, Log, Synthesis - - Status: Draft, Published, Archived - - Full test coverage in `wiki_page_test.go` - -- **WikiConfig in KnowledgeBase** - - WikiLanguage: Target language for wiki generation - - AutoIngest: Enable/disable automatic wiki generation - - SynthesisModelID: LLM model for synthesis tasks - -#### Database Layer -- **Migration:** `000032_wiki_pages.up.sql` / `down.sql` - - `wiki_pages` table with proper indexes - - Foreign key constraints - - Rollback capability - -#### Repository Layer -- **WikiPageRepository** (`internal/application/repository/wiki_page.go`) - - CRUD operations: Create, Read, Update, Delete - - List with filtering and sorting - - GetBySlug, GetIndex, GetLog - - GORM-based implementation - -#### Service Layer -- **WikiPageService** (`internal/application/service/wiki_page.go`) - - Business logic for wiki operations - - Page validation and rules - - Transaction handling - -- **WikiIngestService** (`internal/application/service/wiki_ingest.go`) - - Automated wiki generation from documents - - Step 1: Generate summary page - - Step 2: Extract entities and concepts (single LLM call) - - Step 3: Detect synthesis opportunities - - Step 4: Rebuild index page - - Step 5: Append log entry - - Full test coverage in `wiki_ingest_test.go` - -- **WikiLintService** (`internal/application/service/wiki_lint.go`) - - Maintenance and validation - - Link verification - - Content quality checks - -#### Language Support -- **Reused Infrastructure** from middleware layer -- Supports: Chinese (Simplified/Traditional), English, Korean, Japanese, Russian, French, German, Spanish, Portuguese -- Function: `types.LanguageLocaleName()` maps locale codes to human-readable names -- Applied in all LLM prompt templates - -#### Chat Integration -- **WikiBoost** (`internal/application/service/chat_pipeline/wiki_boost.go`) - - Enhance chat retrieval with wiki context - - Inject relevant wiki pages into chat responses - -#### Agent Integration -- **Wiki Tools** (`internal/agent/tools/wiki_tools.go`) - - QueryWikiPages: Search wiki for relevant pages - - CreateWikiPage: Create new wiki pages - - UpdateWikiPage: Update existing pages - - Full test coverage in `wiki_tools_test.go` - -- **Prompts** (`internal/agent/prompts_wiki.go`) - - WikiSummaryPrompt: Generate summary pages - - WikiKnowledgeExtractPrompt: Extract entities and concepts - - WikiPageUpdatePrompt: Update pages incrementally - - WikiIndexRebuildPrompt: Rebuild index - - WikiDefinitionPrompt: Generate definitions - -#### API Handler -- **WikiPageHandler** (`internal/handler/wiki_page.go`) - - GET /api/v1/wiki/pages: List all pages - - GET /api/v1/wiki/pages/:slug: Get page by slug - - POST /api/v1/wiki/pages: Create page - - PUT /api/v1/wiki/pages/:id: Update page - - DELETE /api/v1/wiki/pages/:id: Delete page - - GET /api/v1/wiki/search: Search pages - -#### Dependency Injection -- **Container** (`internal/container/container.go`) - - Wired all wiki services - - Repository registration - - Handler setup - -#### Task Processing -- **Async Tasks** (`internal/router/task.go`) - - WikiIngest task type handling - - Payload marshaling/unmarshaling - - Retry logic - -### 2. Frontend Implementation (Complete) - -#### Components -- **WikiBrowser** (`frontend/src/views/knowledge/wiki/WikiBrowser.vue`) - - Display all wiki pages - - Filter by page type - - Search functionality - - Pagination support - -#### API Client -- **Wiki API** (`frontend/src/api/wiki/index.ts`) - - CRUD operations - - List and search - - Error handling - -#### Knowledge Base Editor -- **Wiki Settings** (`frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue`) - - Configure WikiLanguage - - Enable/disable AutoIngest - - Select SynthesisModelID - -#### Internationalization -- **Localization** (`frontend/src/i18n/locales/`) - - Chinese (zh-CN) - - English (en-US) - - Korean (ko-KR) - - Russian (ru-RU) - - All wiki-related strings translated - -#### Router Configuration -- **Routes** (`internal/router/router.go`) - - Registered wiki endpoints - - Proper middleware chain - -### 3. Testing (Complete) - -#### Unit Tests -- **WikiPage Tests** (`internal/types/wiki_page_test.go`) - - Type validation - - Field constraints - - Serialization - -- **WikiIngest Tests** (`internal/application/service/wiki_ingest_test.go`) - - Payload marshaling - - Error handling - - Mock LLM calls - -- **WikiTools Tests** (`internal/agent/tools/wiki_tools_test.go`) - - Tool invocation - - Parameter validation - - Error cases - -- **WikiPageService Tests** (`internal/application/service/wiki_page_test.go`) - - CRUD operations - - Validation rules - -- **Language Tests** (`internal/types/context_helpers_test.go`) - - LanguageLocaleName mapping - - All 9+ language variants - - Edge cases - - Benchmark: 288M ops/sec, 4.3 ns/op - -**Test Summary:** -- Total test cases: 50+ -- All tests passing: ✅ -- Coverage: Core logic >90% - -### 4. Documentation (Complete) - -#### Analysis Documents -- `LANGUAGE_MIDDLEWARE_ANALYSIS.md` - Infrastructure analysis -- `AGENT_WIKI_ANALYSIS.md` - Agent tool analysis -- `INDEX_ALL_ANALYSIS.md` - Complete analysis index -- `README_ANALYSIS.md` - Codebase overview -- `ANALYSIS_SUMMARY.md` - Executive summary - -#### Implementation Guides -- `IMPLEMENTATION_GUIDE.md` - Complete implementation details -- `LANGUAGE_REFACTORING_README.md` - Refactoring quick start -- `QUICK_REFERENCE.md` - One-page reference -- `REFACTORING_IMPLEMENTATION_REPORT.md` - Detailed report - -#### Planning Documents -- `REFACTORING_PLAN.md` - Project planning -- `START_HERE.md` - Getting started guide -- `SESSION_2_COMPLETION_SUMMARY.md` - Session summary -- `PROJECT_COMPLETION_REPORT.md` - Project report -- `LANGUAGE_REFACTORING_QUICK_REFERENCE.md` - Language reference - ---- - -## Git History - -``` -8c3be4ca feat: Implement comprehensive wiki feature for knowledge bases -6fce4de4 docs: Add quick reference card for language refactoring -b56b87a8 docs: Add language refactoring README with quick start guide -9913fac4 refactor: Replace hardcoded language logic with middleware infrastructure -``` - -### Commit Statistics -- **44 files changed** -- **7374 insertions** -- **29 deletions** - ---- - -## Build Verification - -``` -✅ Build Status: SUCCESS -✅ Binary Size: 243 MB -✅ Target: arm64 Mach-O executable -✅ Dependencies: Resolved (warnings only from external C++ libraries) -``` - ---- - -## Code Quality - -### Backend -- ✅ Proper error handling with context -- ✅ Comprehensive logging -- ✅ Type-safe operations -- ✅ Consistent naming conventions -- ✅ DRY principle applied (language infrastructure reuse) - -### Frontend -- ✅ TypeScript for type safety -- ✅ Vue 3 composition API -- ✅ Proper error handling -- ✅ i18n support for all strings -- ✅ Responsive design - -### Testing -- ✅ Unit tests for all critical paths -- ✅ Mock objects for external dependencies -- ✅ Edge case coverage -- ✅ Performance benchmarks - ---- - -## Language Support - -The implementation reuses the existing language middleware infrastructure: - -| Language | Code | Supported | -|----------|------|-----------| -| Chinese (Simplified) | zh-CN, zh, zh-Hans | ✅ | -| Chinese (Traditional) | zh-TW, zh-HK, zh-Hant | ✅ | -| English | en-US, en, en-GB | ✅ | -| Korean | ko-KR, ko | ✅ | -| Japanese | ja-JP, ja | ✅ | -| Russian | ru-RU, ru | ✅ | -| French | fr-FR, fr | ✅ | -| German | de-DE, de | ✅ | -| Spanish | es-ES, es | ✅ | -| Portuguese | pt-BR, pt | ✅ | - -**Total Language Support:** 9+ languages - ---- - -## Key Features - -### Wiki Generation -- ✅ Automatic summary page generation from documents -- ✅ Entity and concept extraction (single LLM call for efficiency) -- ✅ Synthesis opportunity detection -- ✅ Index page rebuilding -- ✅ Log page maintenance - -### Wiki Management -- ✅ CRUD operations via REST API -- ✅ Search and filtering -- ✅ Pagination support -- ✅ Page type organization -- ✅ Status tracking (Draft, Published, Archived) - -### Integration -- ✅ Agent-based wiki interaction -- ✅ Chat retrieval enhancement -- ✅ Async task processing -- ✅ Event-driven architecture -- ✅ Dependency injection - -### User Interface -- ✅ Wiki browser component -- ✅ Knowledge base configuration -- ✅ Multi-language support -- ✅ Search functionality -- ✅ Responsive design - ---- - -## Files Summary - -### Backend Files (14 new) -- `internal/types/wiki_page.go` - Data model -- `internal/types/interfaces/wiki_page.go` - Interface definitions -- `internal/application/repository/wiki_page.go` - Repository -- `internal/application/service/wiki_page.go` - Service -- `internal/application/service/wiki_ingest.go` - Ingest pipeline -- `internal/application/service/wiki_lint.go` - Linting -- `internal/application/service/chat_pipeline/wiki_boost.go` - Chat integration -- `internal/handler/wiki_page.go` - HTTP handler -- `internal/agent/prompts_wiki.go` - LLM prompts -- `internal/agent/tools/wiki_tools.go` - Agent tools -- `migrations/versioned/000032_wiki_pages.up.sql` - Migration up -- `migrations/versioned/000032_wiki_pages.down.sql` - Migration down - -### Frontend Files (2 new) -- `frontend/src/views/knowledge/wiki/WikiBrowser.vue` - Wiki UI -- `frontend/src/api/wiki/index.ts` - Wiki API client - -### Test Files (5 new) -- `internal/types/wiki_page_test.go` -- `internal/types/context_helpers_test.go` -- `internal/application/service/wiki_page_test.go` -- `internal/application/service/wiki_ingest_test.go` -- `internal/agent/tools/wiki_tools_test.go` - -### Documentation Files (9 new) -- Comprehensive analysis and implementation guides - -### Modified Files (17) -- Router configuration -- Container setup -- Handler definitions -- Frontend components -- i18n strings -- Type definitions -- Service integrations - ---- - -## Next Steps (Optional) - -The wiki feature is production-ready. Optional enhancements for future work: - -1. **Schema Normalization** (Low Priority) - - Convert WikiLanguage from short codes ("zh") to full locales ("zh-CN") - - Requires database migration - -2. **UI Enhancements** (Medium Priority) - - Advanced wiki graph visualization - - Related pages suggestions - - Wiki page versioning and history - - Collaborative editing - -3. **Content Improvements** (Medium Priority) - - Better entity relationship detection - - Cross-document entity linking - - Automatic taxonomy generation - - Content quality scoring - -4. **Performance** (Low Priority) - - Caching for frequently accessed pages - - Async index rebuilding optimization - - Batch wiki generation - ---- - -## Verification Checklist - -- ✅ All source files created -- ✅ All tests passing (50+ test cases) -- ✅ Build succeeds (243MB binary) -- ✅ No compilation errors -- ✅ Dependencies resolved -- ✅ Git history clean -- ✅ Documentation complete -- ✅ Code committed -- ✅ Ready for production - ---- - -## Contact & Support - -For questions or issues: -1. Review the implementation guides -2. Check the test cases for usage examples -3. Refer to the API handler for endpoint documentation -4. Review the prompts for LLM integration details - ---- - -**Project Status: ✅ COMPLETE** - -All objectives have been achieved. The wiki feature is ready for deployment and production use. diff --git a/FRONTEND_KB_QUICK_REFERENCE.md b/FRONTEND_KB_QUICK_REFERENCE.md deleted file mode 100644 index 44c3a75c..00000000 --- a/FRONTEND_KB_QUICK_REFERENCE.md +++ /dev/null @@ -1,245 +0,0 @@ -# Frontend KB & Wiki Settings - Quick Reference - -## File Paths Summary - -### 1️⃣ **Wiki Settings Component** -``` -📁 frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue - └─ Lines 123-187: Wiki settings panel (INLINE, no separate file!) -``` - -**Key Data Fields**: -- `wikiConfig.enabled` - Toggle wiki on/off -- `wikiConfig.autoIngest` - Auto-ingest mode (default: true) -- `wikiConfig.synthesisModelId` - Model ID (KnowledgeQA type) -- `wikiConfig.maxPagesPerIngest` - Max pages per batch (0-50) - ---- - -### 2️⃣ **Main KB Settings Page** -``` -📁 frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue (1353 lines) -``` - -**Sidebar Navigation**: -- Basic Info -- Model Config -- Parser Settings -- Multimodal Config -- ASR Config -- Storage Engine -- **Chunking** (分块设置) -- **Knowledge Graph** (知识图谱) -- **Wiki** (Wiki 设置) -- Advanced Settings -- Data Sources (edit only) -- Share Management (edit only) - ---- - -### 3️⃣ **KB API Client** -``` -📁 frontend/src/api/knowledge-base/index.ts -``` - -**Key Functions**: -- `createKnowledgeBase(data)` - POST `/api/v1/knowledge-bases` -- `updateKnowledgeBase(id, data)` - PUT `/api/v1/knowledge-bases/{id}` -- `getKnowledgeBaseById(id)` - GET `/api/v1/knowledge-bases/{id}` - -**Wiki Config Type**: -```typescript -wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - max_pages_per_ingest?: number; -} -``` - ---- - -### 4️⃣ **Chunking Settings** -``` -📁 frontend/src/views/knowledge/settings/KBChunkingSettings.vue (297 lines) -``` - -**Config Options**: -- Chunk Size: 100-4000 (default: 512) -- Chunk Overlap: 0-500 (default: 100) -- Separators: Multi-select customizable -- Parent-Child Chunking: Toggle -- Parent Size: 512-8192 (default: 4096) -- Child Size: 64-2048 (default: 384) - ---- - -### 5️⃣ **Knowledge Graph Settings** -``` -📁 frontend/src/views/knowledge/settings/GraphSettings.vue (21276 bytes) -``` - -**Features**: -- Enable/disable entity extraction -- Tags management with auto-generate -- Sample text configuration -- Database status check - ---- - -## Data Flow - -### Create Mode -``` -Form (empty) - ↓ [Fill sections via sidebar] -Validation - ↓ -buildSubmitData() - ↓ -createKnowledgeBase(data) - ↓ [One API call] -New KB created -``` - -### Edit Mode -``` -loadKBData() → GET /api/v1/knowledge-bases/{id} - ↓ -Map response to formData - ↓ [User edits] -Validation - ↓ -PUT /api/v1/knowledge-bases/{id} [name, desc, FAQ, Wiki] -PUT /api/v1/initialization/config/{kbId} [models, chunking, storage, etc.] - ↓ [Two API calls] -Changes saved -``` - ---- - -## Form Data Structure - -```typescript -{ - type: 'document' | 'faq', - name: string, - description: string, - - // For FAQ KBs - faqConfig: { - indexMode: 'question_only' | 'question_answer', - questionIndexMode: 'combined' | 'separate' - }, - - // Models - modelConfig: { - llmModelId: string, - embeddingModelId: string - }, - - // Document chunking - chunkingConfig: { - chunkSize: number, - chunkOverlap: number, - separators: string[], - enableParentChild: boolean, - parentChunkSize: number, - childChunkSize: number - }, - - storageProvider: string, - multimodalConfig: { enabled: boolean, vllmModelId: string }, - asrConfig: { enabled: boolean, modelId: string, language: string }, - nodeExtractConfig: { /* ... graph config ... */ }, - questionGenerationConfig: { enabled: boolean, questionCount: number }, - - // Wiki settings - wikiConfig: { - enabled: boolean, - autoIngest: boolean, - synthesisModelId: string, - maxPagesPerIngest: number - } -} -``` - ---- - -## Indexing Strategies - -### FAQ Indexing -- `index_mode`: "question_only" (precision) vs "question_answer" (recall) -- `question_index_mode`: "combined" vs "separate" - -### Document Indexing -- Chunk-based with configurable size, overlap, separators -- Optional parent-child hierarchy - -### Wiki Indexing -- Controlled by `wikiConfig.auto_ingest` flag -- Synthesis model handles page summarization -- Batch limit via `maxPagesPerIngest` - ---- - -## Key Components by Path - -| Feature | File | Lines | -|---------|------|-------| -| **Main Editor** | `KnowledgeBaseEditorModal.vue` | 1353 | -| **Models** | `settings/KBModelConfig.vue` | ~80 | -| **Chunking** | `settings/KBChunkingSettings.vue` | 297 | -| **Graph** | `settings/GraphSettings.vue` | 21276 | -| **Parser** | `settings/KBParserSettings.vue` | 31516 | -| **Storage** | `settings/KBStorageSettings.vue` | 7100 | -| **Advanced** | `settings/KBAdvancedSettings.vue` | ~80 | -| **Share** | `settings/KBShareSettings.vue` | 18014 | -| **DataSource** | `settings/DataSourceSettings.vue` | 16899 | - ---- - -## Important Implementation Notes - -1. **Wiki settings INLINE**: No separate Vue file - all in KnowledgeBaseEditorModal.vue (lines 123-187) - -2. **Wiki always sent**: For document KBs, wiki_config is always sent even when disabled - -3. **Dual storage config**: Both `storage_provider_config` and `storage_config` written for backward compatibility - -4. **Conditional visibility**: - - Wiki section: Document KBs only - - FAQ section: FAQ KBs only - - DataSource/Share: Edit mode only - -5. **Embedding model locked**: Cannot change embedding model if KB has files - -6. **Storage change warning**: Confirms user when changing storage provider if files exist - ---- - -## Translation Keys (Chinese) - -``` -knowledgeEditor.wiki.enableLabel = "启用 Wiki" -knowledgeEditor.wiki.autoIngestLabel = "自动 Ingest" -knowledgeEditor.wiki.synthesisModelLabel = "合成模型" -knowledgeEditor.wiki.maxPagesLabel = "单次最大页面数" -``` - ---- - -## API Endpoints - -| Method | Endpoint | Purpose | -|--------|----------|---------| -| GET | `/api/v1/knowledge-bases` | List KBs | -| POST | `/api/v1/knowledge-bases` | Create KB | -| GET | `/api/v1/knowledge-bases/{id}` | Get KB details | -| PUT | `/api/v1/knowledge-bases/{id}` | Update name/desc/FAQ/Wiki | -| PUT | `/api/v1/initialization/config/{kbId}` | Update models/chunking/storage | -| DELETE | `/api/v1/knowledge-bases/{id}` | Delete KB | - ---- - -Generated: 2026-04-20 diff --git a/FRONTEND_KB_WIKI_ANALYSIS_COMPREHENSIVE.md b/FRONTEND_KB_WIKI_ANALYSIS_COMPREHENSIVE.md deleted file mode 100644 index ef16937a..00000000 --- a/FRONTEND_KB_WIKI_ANALYSIS_COMPREHENSIVE.md +++ /dev/null @@ -1,492 +0,0 @@ -# Frontend Knowledge Base & Wiki Settings - Comprehensive Analysis - -**Date**: 2026-04-20 -**Status**: Complete Frontend Architecture Discovery - ---- - -## Executive Summary - -The frontend implementation uses **Vue 3 + TypeScript** with **TDesign UI components**. The knowledge base configuration system is centered around a **modal-based editor** with a **left sidebar navigation** that controls which settings section is displayed. - -### Key Architecture -- **Main Editor Modal**: `KnowledgeBaseEditorModal.vue` (1353 lines) - Central hub for all KB settings -- **Navigation Model**: Sidebar with tabs for basic, models, parser, storage, chunking, graph, wiki, asr, multimodal, advanced, datasource (edit only), and share (edit only) -- **Settings Panel Components**: Modular components for each settings category -- **API Layer**: RESTful API calls to `/api/v1/knowledge-bases` and `/api/v1/initialization/config/{kbId}` - ---- - -## 1. WIKI SETTINGS COMPONENT - -### ⚠️ Important Discovery: No Separate File! - -**Wiki settings are INLINE in KnowledgeBaseEditorModal.vue (lines 123-187)** - -**File Path**: `frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue` - -### Wiki Config Data Model - -```typescript -wikiConfig: { - enabled: false, // Boolean - Wiki feature enable/disable - autoIngest: true, // Boolean - Auto-ingest mode - synthesisModelId: '', // String - Model ID for wiki synthesis (KnowledgeQA type) - maxPagesPerIngest: 0, // Number - Max pages to process per ingest cycle (0-50) -} -``` - -### Settings Fields - -1. **启用 Wiki** (Enable Wiki) - Toggle switch - - Binding: `formData.wikiConfig.enabled` - - Tip: "启用后可自动处理 Wiki 内容" - -2. **自动 Ingest** (Auto Ingest) - Toggle switch (conditional on enabled) - - Binding: `formData.wikiConfig.autoIngest` - - Default: true - - Tip: "启用自动获取和处理新页面" - -3. **合成模型** (Synthesis Model) - Model selector (conditional on enabled) - - Binding: `formData.wikiConfig.synthesisModelId` - - Model Type: "KnowledgeQA" - - Tip: "用于生成 Wiki 页面摘要的模型" - -4. **单次最大页面数** (Max Pages Per Ingest) - Number input (conditional on enabled) - - Binding: `formData.wikiConfig.maxPagesPerIngest` - - Range: 0-50 - - Tip: "每次处理的最大页面数" - -### Backend Mapping (From KB Response) - -```typescript -wikiConfig: { - enabled: kb.wiki_config?.enabled ?? false, - autoIngest: kb.wiki_config?.auto_ingest ?? true, - synthesisModelId: kb.wiki_config?.synthesis_model_id || '', - maxPagesPerIngest: kb.wiki_config?.max_pages_per_ingest || 0, -} -``` - ---- - -## 2. KNOWLEDGE BASE SETTINGS MAIN PAGE - -### File Path: `frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue` - -This is the **primary and comprehensive** knowledge base settings interface with a modal + sidebar navigation pattern. - -### Sidebar Navigation Structure - -**For Document KBs** (13 sections): -1. **基本信息** (Basic Info) - name, description, type selection -2. **模型配置** (Model Config) - LLM and Embedding models -3. **解析引擎** (Parser Settings) - Parser engine rules -4. **多模态配置** (Multimodal) - Image/video processing with VLM -5. **音频处理** (ASR) - Audio to speech recognition -6. **存储引擎** (Storage Engine) - local/minio/cos selection -7. **分块设置** (Chunking) - Chunk size, overlap, separators -8. **知识图谱** (Knowledge Graph) - Entity/relation extraction -9. **Wiki 设置** (Wiki Settings) - Wiki-specific config -10. **高级设置** (Advanced) - Question generation -11. **数据源** (Data Sources) - Edit mode only -12. **共享管理** (Sharing) - Edit mode only -13. Plus datasource badge counter - -**For FAQ KBs** (3 sections): -1. **基本信息** (Basic Info) -2. **模型配置** (Model Config) -3. **FAQ 配置** (FAQ Config) - Index modes - -### Complete FormData Structure - -```typescript -{ - type: 'document' | 'faq', - name: string, - description: string, - - faqConfig: { - indexMode: 'question_only' | 'question_answer', - questionIndexMode: 'combined' | 'separate' - }, - - modelConfig: { - llmModelId: string, - embeddingModelId: string - }, - - chunkingConfig: { - chunkSize: number, - chunkOverlap: number, - separators: string[], - parserEngineRules?: ParserEngineRule[], - enableParentChild: boolean, - parentChunkSize: number, - childChunkSize: number - }, - - storageProvider: string, - - multimodalConfig: { - enabled: boolean, - vllmModelId: string - }, - - asrConfig: { - enabled: boolean, - modelId: string, - language: string - }, - - nodeExtractConfig: { - enabled: boolean, - text: string, - tags: string[], - nodes: Array<{ name: string; attributes: string[] }>, - relations: Array<{ node1: string; node2: string; type: string }> - }, - - questionGenerationConfig: { - enabled: boolean, - questionCount: number - }, - - wikiConfig: { - enabled: boolean, - autoIngest: boolean, - synthesisModelId: string, - maxPagesPerIngest: number - } -} -``` - ---- - -## 3. KNOWLEDGE BASE API CLIENT - -### File Path: `frontend/src/api/knowledge-base/index.ts` - -### Create KB Function - -```typescript -export function createKnowledgeBase(data: { - name: string; - description?: string; - type?: 'document' | 'faq'; - chunking_config?: ChunkingConfig; - embedding_model_id?: string; - summary_model_id?: string; - vlm_config?: VLMConfig; - storage_provider_config?: { provider: string }; - storage_config?: any; - asr_config?: ASRConfig; - extract_config?: any; - faq_config?: FAQConfig; - wiki_config?: WikiConfig; -}) { - return post(`/api/v1/knowledge-bases`, data); -} -``` - -### Update KB Function - -```typescript -export function updateKnowledgeBase(id: string, data: { - name: string; - description?: string; - config?: { - chunking_config?: ChunkingConfig; - image_processing_config?: any; - faq_config?: FAQConfig; - wiki_config?: WikiConfig; - } -}) { - return put(`/api/v1/knowledge-bases/${id}`, data); -} -``` - -### TypeScript Interfaces - -```typescript -interface WikiConfig { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; -} - -interface FAQConfig { - index_mode: string; - question_index_mode?: string; -} - -interface ChunkingConfig { - chunk_size?: number; - chunk_overlap?: number; - separators?: string[]; - parser_engine_rules?: { file_types: string[]; engine: string }[]; - enable_parent_child?: boolean; - parent_chunk_size?: number; - child_chunk_size?: number; -} - -interface VLMConfig { - enabled: boolean; - model_id?: string; -} - -interface ASRConfig { - enabled: boolean; - model_id?: string; - language?: string; -} -``` - -### KBModelConfigRequest (For Updates) - -From `frontend/src/api/initialization/index.ts`: - -```typescript -export interface KBModelConfigRequest { - llmModelId: string - embeddingModelId: string - vlm_config?: VLMConfig - asr_config?: ASRConfig - documentSplitting: { - chunkSize: number - chunkOverlap: number - separators: string[] - parserEngineRules?: { file_types: string[]; engine: string }[] - enableParentChild?: boolean - parentChunkSize?: number - childChunkSize?: number - } - multimodal: { enabled: boolean } - storageProvider?: string - nodeExtract: { - enabled: boolean - text: string - tags: string[] - nodes: Node[] - relations: Relation[] - } - questionGeneration?: { - enabled: boolean - questionCount: number - } -} -``` - ---- - -## 4. CHUNKING SETTINGS COMPONENT - -### File Path: `frontend/src/views/knowledge/settings/KBChunkingSettings.vue` (297 lines) - -### Configuration Options - -1. **Chunk Size** - - Range: 100-4000 characters - - Default: 512 - - Slider control with marks - -2. **Chunk Overlap** - - Range: 0-500 characters - - Default: 100 - - Slider control - -3. **Separators** - - Multi-select with creatable option - - Predefined: `\n\n`, `\n`, `。`, `!`, `?`, `;`, `;`, ` ` - - Default: `['\n\n', '\n', '。', '!', '?', ';', ';']` - -4. **Parent-Child Chunking** - - Boolean toggle - - Enables hierarchical chunking - -5. **Parent Chunk Size** (conditional) - - Range: 512-8192 characters - - Default: 4096 - -6. **Child Chunk Size** (conditional) - - Range: 64-2048 characters - - Default: 384 - ---- - -## 5. KNOWLEDGE GRAPH SETTINGS COMPONENT - -### File Path: `frontend/src/views/knowledge/settings/GraphSettings.vue` (21276 bytes) - -### Features - -1. **Database Status Warning** - - Shows if graph database not enabled - - Link to enable instructions - -2. **Enable Entity/Relation Extraction** - - Boolean toggle - -3. **Tags Configuration** - - Multi-select with creatable option - - Auto-generate button (requires LLM) - - Model type: KnowledgeQA - -4. **Sample Text** - - Textarea input - - Auto-generate button - - 5000 character limit - - 6-12 lines display - ---- - -## 6. ADDITIONAL SETTINGS COMPONENTS - -| File | Purpose | -|------|---------| -| `KBModelConfig.vue` | LLM and Embedding model selection | -| `KBStorageSettings.vue` | Storage provider (local/minio/cos) | -| `KBAdvancedSettings.vue` | Question generation settings | -| `KBParserSettings.vue` | Parser engine rule mapping | -| `KBShareSettings.vue` | User/org sharing & permissions | -| `DataSourceSettings.vue` | Data source management | - ---- - -## 7. INDEXING STRATEGY & INDEX-TYPE CONFIGS - -### FAQ Indexing Strategy - -```typescript -faqConfig: { - indexMode: 'question_only' | 'question_answer', - questionIndexMode: 'combined' | 'separate' -} -``` - -**Index Modes**: -- `question_only` - Higher precision (questions only) -- `question_answer` - Higher recall (Q+A both) - -**Question Modes**: -- `combined` - Single combined vector -- `separate` - Separate entries - -### Document Indexing - -**Chunk-based indexing** with configurable: -- Chunk size (100-4000 tokens) -- Chunk overlap (0-500 tokens) -- Custom separators -- Parent-child hierarchy option - -### Wiki Indexing - -```typescript -wikiConfig: { - enabled: boolean - auto_ingest: boolean // Automatic indexing toggle - synthesis_model_id: string // Model for synthesis - max_pages_per_ingest: number // Batch limit -} -``` - ---- - -## 8. DATA FLOW - -### Create Mode -1. Initialize empty form with defaults -2. Fill sections via sidebar navigation -3. Validate all fields -4. Submit in **one request** to `/api/v1/knowledge-bases` -5. Return with new KB ID - -### Edit Mode -1. Load KB data from `/api/v1/knowledge-bases/{id}` -2. Map response to form data -3. User modifies sections -4. On submit: - - **PUT** `/api/v1/knowledge-bases/{id}` (name, description, FAQ, Wiki) - - **PUT** `/api/v1/initialization/config/{kbId}` (models, chunking, storage, etc.) - ---- - -## 9. VALIDATION RULES - -```typescript -- KB name: Required, non-empty -- Embedding model: Required, must select one -- LLM model: Required, must select one -- Multimodal: If enabled, VLLM model required -- FAQ: If type='faq', indexMode required -- Storage: Can only change if NO files exist -``` - ---- - -## 10. FILE INVENTORY - -### Settings Views -| File | Path | Lines | Purpose | -|------|------|-------|---------| -| Main Editor | `views/knowledge/KnowledgeBaseEditorModal.vue` | 1353 | Core settings modal | -| KB View | `views/knowledge/KnowledgeBase.vue` | 27993 | KB main interface | -| Model Config | `settings/KBModelConfig.vue` | ~80 | Model selection | -| Chunking | `settings/KBChunkingSettings.vue` | 297 | Chunking config | -| Graph | `settings/GraphSettings.vue` | 21276 | Knowledge graph | -| Parser | `settings/KBParserSettings.vue` | 31516 | Parser rules | -| Storage | `settings/KBStorageSettings.vue` | 7100 | Storage engine | -| Advanced | `settings/KBAdvancedSettings.vue` | ~80 | Advanced options | -| Share | `settings/KBShareSettings.vue` | 18014 | Sharing config | -| DataSource | `settings/DataSourceSettings.vue` | 16899 | Data management | - -### API Layer -| File | Purpose | -|------|---------| -| `api/knowledge-base/index.ts` | KB CRUD operations | -| `api/initialization/index.ts` | Config updates | - ---- - -## Key Implementation Details - -### Wiki Config Always Sent (For Non-FAQ) - -```typescript -if (formData.value.type !== 'faq') { - data.wiki_config = { - enabled: formData.value.wikiConfig?.enabled ?? false, - auto_ingest: formData.value.wikiConfig?.autoIngest ?? true, - synthesis_model_id: formData.value.wikiConfig?.synthesisModelId || '', - max_pages_per_ingest: formData.value.wikiConfig?.maxPagesPerIngest || 0, - } -} -``` - -### Dual Storage Config (Backward Compat) - -```typescript -data.storage_provider_config = { provider: ... } -data.storage_config = { provider: ... } // Legacy -``` - -### Conditional Section Visibility - -- **Wiki section**: Only for document KBs -- **FAQ section**: Only for FAQ KBs -- **ASR/Multimodal**: Only for document KBs -- **DataSource/Share**: Only in edit mode - ---- - -## Translation Keys - -**Chinese (zh-CN)**: -- `knowledgeEditor.wiki.enableLabel` = "启用 Wiki" -- `knowledgeEditor.wiki.autoIngestLabel` = "自动 Ingest" -- `knowledgeEditor.wiki.synthesisModelLabel` = "合成模型" -- `knowledgeEditor.wiki.maxPagesLabel` = "单次最大页面数" - diff --git a/IMPLEMENTATION_GUIDE.md b/IMPLEMENTATION_GUIDE.md deleted file mode 100644 index bd8b73cd..00000000 --- a/IMPLEMENTATION_GUIDE.md +++ /dev/null @@ -1,410 +0,0 @@ -# Language Infrastructure Refactoring - Implementation Guide - -**Status:** ✅ COMPLETED & TESTED -**Date:** 2026-04-07 -**Version:** 1.0 - ---- - -## Executive Summary - -This guide documents the completed refactoring of language handling in the WeKnora Wiki Ingest Service. The refactoring eliminates code duplication by reusing existing language infrastructure from the middleware layer. - -**Key Achievement:** -- Replaced 7 lines of hardcoded language logic with a single call to an existing, well-tested function -- Now supports 9+ languages instead of 2 -- Improved code maintainability and consistency -- Zero breaking changes -- All tests passing - ---- - -## 1. What Was Changed - -### Location -**File:** `internal/application/service/wiki_ingest.go` -**Lines:** 135-139 (was 135-141) - -### The Refactoring - -#### Before -```go -// Determine language -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} -``` - -**Problems:** -- Only supports 2 languages (zh, en) -- Hardcoded mapping -- Inconsistent naming ("Chinese (中文)" vs. standard format) -- Generic fallback message - -#### After -```go -// Get human-readable language name for LLM prompts -// Reuses language mapping from middleware infrastructure (supports 9+ languages) -// Maps locale codes like "zh", "en" to names like "Chinese (Simplified)", "English" -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Benefits:** -- Supports 9+ languages -- Single source of truth: `types.LanguageLocaleName()` -- Consistent naming with middleware -- Clear comments explaining the reuse -- Reduced from 7 lines to 4 lines - ---- - -## 2. Infrastructure Overview - -### Core Component: `types.LanguageLocaleName()` - -**Location:** `internal/types/context_helpers.go` (lines 85-112) - -**Function Signature:** -```go -func LanguageLocaleName(locale string) string -``` - -**Purpose:** Maps locale codes to human-readable language names suitable for LLM prompts. - -**Supported Languages:** - -| Input Code(s) | Output Name | -|----------------|-------------| -| zh-CN, zh, zh-Hans | Chinese (Simplified) | -| zh-TW, zh-HK, zh-Hant | Chinese (Traditional) | -| en-US, en, en-GB | English | -| ko-KR, ko | Korean | -| ja-JP, ja | Japanese | -| ru-RU, ru | Russian | -| fr-FR, fr | French | -| de-DE, de | German | -| es-ES, es | Spanish | -| pt-BR, pt | Portuguese | -| *any other* | Returns the input as-is | - -### Related Functions - -**Location:** `internal/types/context_helpers.go` - -1. **`EnvLanguage() string`** (lines 9-12) - - Returns WEKNORA_LANGUAGE environment variable - - Used for deployment-level language override - -2. **`DefaultLanguage() string`** (lines 14-21) - - Returns WEKNORA_LANGUAGE if set, otherwise "zh-CN" - - Used for fallback language when no context is available - -3. **`LanguageFromContext(ctx context.Context) (string, bool)`** (lines 67-72) - - Extracts locale code from request context - - Returns (locale, found?) - -4. **`LanguageNameFromContext(ctx context.Context) string`** (lines 74-83) - - Combines LanguageFromContext + LanguageLocaleName - - Returns human-readable language name from context - - Falls back to DefaultLanguage() - -### Middleware Integration - -**Location:** `internal/middleware/language.go` - -The Language middleware: -1. Checks WEKNORA_LANGUAGE environment variable (deployment override) -2. If not set, parses Accept-Language HTTP header -3. If header missing, uses "zh-CN" fallback -4. Injects result into request context via `LanguageContextKey` - -**Registration:** `internal/router/router.go` (line 85) - ---- - -## 3. Test Coverage - -### Unit Tests - -**File:** `internal/types/context_helpers_test.go` (New) - -**Test Cases:** 30 test cases covering: -- All 9 supported languages (full locale codes) -- All short codes (e.g., "zh", "en", "ko") -- All regional variants (e.g., "zh-TW", "zh-HK") -- Unknown locales (fallback behavior) -- Empty strings -- Edge cases - -**Test Results:** -``` -✅ PASS: TestLanguageLocaleName (30 test cases) -✅ PASS: BenchmarkLanguageLocaleName - - 288,239,468 ops/sec - - ~4.3 ns/op (very efficient) -``` - -### Integration Tests - -**Existing Tests:** `internal/types/context_helpers.go` is integrated with service layer and already used in multiple service functions. - -**New Usage:** `wiki_ingest.go` now calls `types.LanguageLocaleName()` which is covered by the unit tests. - ---- - -## 4. Build & Deployment Verification - -### Build Status -```bash -$ go build -o /tmp/test_weknora ./cmd/server -# ✅ Successful - 243MB binary -# Only warnings from dependencies (safe to ignore) -``` - -### Runtime Behavior -The refactoring maintains identical runtime behavior: -- Same input types (string) -- Same output type (string) -- Same values produced -- Improved code quality and maintainability - ---- - -## 5. Usage Examples - -### Example 1: Wiki Ingest Service - -```go -// In ProcessWikiIngest() method -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) - -// Usage in prompt template -summaryContent, err := s.generateWithTemplate(ctx, chatModel, agent.WikiSummaryPrompt, map[string]string{ - "Title": docTitle, - "Content": content, - "Language": lang, // e.g., "Chinese (Simplified)" -}) -``` - -### Example 2: From Context - -```go -// Using context middleware to get language name -lang := types.LanguageNameFromContext(ctx) // Already combines everything -// lang == "English", "Chinese (Simplified)", etc. -``` - -### Example 3: Direct Function Call - -```go -// Map a specific locale to language name -name := types.LanguageLocaleName("ko") // → "Korean" -name := types.LanguageLocaleName("zh-TW") // → "Chinese (Traditional)" -name := types.LanguageLocaleName("unknown") // → "unknown" -``` - ---- - -## 6. Performance Impact - -### Benchmark Results - -``` -BenchmarkLanguageLocaleName-12 288239468 ops/sec 4.315 ns/op -``` - -**Analysis:** -- Function is extremely lightweight (~4.3 nanoseconds per call) -- Simple switch statement with no allocations -- No measurable performance impact on wiki ingest -- Negligible overhead compared to LLM calls which take seconds - ---- - -## 7. Backward Compatibility - -### ✅ No Breaking Changes - -1. **Function Signature:** Same input/output types -2. **Behavior:** Identical output for all existing inputs -3. **Error Handling:** Unknown languages return as-is (same as before) -4. **API:** No changes to public interfaces -5. **Database:** No schema changes required - -### Migration Path - -**For Existing Code:** -- No action required -- Changes are transparent -- All existing code continues to work - -**For New Code:** -- Use `types.LanguageLocaleName()` for wiki language mapping -- Use `types.LanguageNameFromContext()` for request context -- Use `types.LanguageFromContext()` to get locale codes - ---- - -## 8. Monitoring & Observability - -### Logging - -The refactored code maintains the same logging: -```go -logger.Infof(ctx, "wiki ingest: completed for knowledge %s, %d pages affected", - payload.KnowledgeID, len(pagesAffected)) -``` - -### Metrics - -The language handling adds negligible overhead: -- Function call: ~4.3 ns -- Switch statement lookup: O(1) -- No allocations or I/O - -### Error Handling - -Unknown language codes are handled gracefully: -```go -types.LanguageLocaleName("xyz-ABC") // → "xyz-ABC" (returned as-is) -``` - ---- - -## 9. Future Enhancements - -### Enhancement 1: Schema Normalization (Optional) - -Currently: `WikiConfig.WikiLanguage` stores short codes ("zh", "en") - -**Consider normalizing to full locale codes:** -```go -// Migration function -func normalizeWikiLanguage(shortCode string) string { - switch shortCode { - case "zh": - return "zh-CN" - case "en": - return "en-US" - // ... etc - } -} -``` - -**Benefits:** -- Consistency with middleware (always full locale codes) -- More precise language information -- Better support for regional variants - -**Implementation Level:** Low priority, not required for current functionality - -### Enhancement 2: Language Configuration UI (Optional) - -**Current:** Only "zh" and "en" in UI -**Future:** Add support for all 9+ languages in knowledge base settings - -**Implementation:** Update frontend form and knowledge base creation handler - -### Enhancement 3: Language Autodetection (Optional) - -**Future:** Automatically detect document language from content -**Implementation:** Integrate language detection library - ---- - -## 10. Troubleshooting - -### Issue: Language not appearing correctly in LLM output - -**Debug Steps:** -```go -// Check what language name is being used -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -logger.Infof(ctx, "Language for wiki ingest: %s", lang) - -// Verify the mapping -types.LanguageLocaleName("zh") // Should be "Chinese (Simplified)" -types.LanguageLocaleName("en") // Should be "English" -``` - -### Issue: Unknown language code - -**Resolution:** -```go -// Unknown codes are returned as-is -lang := types.LanguageLocaleName("unknown") // → "unknown" - -// Ensure WikiConfig.WikiLanguage has a valid value -// Add validation in wiki configuration handler -``` - ---- - -## 11. Documentation Files - -| Document | Purpose | Location | -|----------|---------|----------| -| This File | Implementation guide | `IMPLEMENTATION_GUIDE.md` | -| Analysis | Pre-refactoring analysis | `LANGUAGE_MIDDLEWARE_ANALYSIS.md` | -| Completion Report | Post-refactoring summary | `LANGUAGE_REFACTORING_COMPLETED.md` | - ---- - -## 12. Verification Checklist - -- [x] Refactoring applied to wiki_ingest.go -- [x] Build successful (no errors) -- [x] Unit tests created and passing (30 test cases) -- [x] Benchmark tests passing -- [x] No breaking changes -- [x] Backward compatible -- [x] Documentation complete -- [x] Code review ready -- [x] Performance verified (4.3 ns/op) -- [x] Ready for deployment - ---- - -## 13. Contact & Support - -For questions about this refactoring: - -1. **Code Location:** `internal/application/service/wiki_ingest.go` (line 139) -2. **Related Code:** `internal/types/context_helpers.go` -3. **Tests:** `internal/types/context_helpers_test.go` -4. **Build:** `go build ./internal/application/service` - ---- - -## Appendix: Diff Summary - -```diff -File: internal/application/service/wiki_ingest.go -Lines: 135-141 → 135-139 - -- // Determine language -- lang := "the same language as the source document" -- if kb.WikiConfig.WikiLanguage == "zh" { -- lang = "Chinese (中文)" -- } else if kb.WikiConfig.WikiLanguage == "en" { -- lang = "English" -- } -+ // Get human-readable language name for LLM prompts -+ // Reuses language mapping from middleware infrastructure (supports 9+ languages) -+ // Maps locale codes like "zh", "en" to names like "Chinese (Simplified)", "English" -+ lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Statistics:** -- Lines removed: 7 -- Lines added: 4 -- Net reduction: 3 lines (43% less code) -- Languages supported: 2 → 9+ (350% increase) -- Code duplication: Eliminated - ---- - -**End of Implementation Guide** diff --git a/IMPLEMENTATION_SUMMARY.md b/IMPLEMENTATION_SUMMARY.md deleted file mode 100644 index 055e36f7..00000000 --- a/IMPLEMENTATION_SUMMARY.md +++ /dev/null @@ -1,216 +0,0 @@ -# WikiConfig Update Fix - Implementation Summary - -## Issue -The `wiki_config` field could not be updated when modifying a knowledge base through the `PUT /api/v1/knowledge-bases/{id}` endpoint, even though it worked correctly for knowledge base creation. - -## Root Cause -The `KnowledgeBaseConfig` struct used to deserialize PUT request bodies was missing the `WikiConfig` field. When JSON unmarshaling occurred, the `wiki_config` data was silently dropped because the target struct had no field to receive it. - -## Solution -Implemented three complementary fixes across the system layers: - -### Fix 1: Backend Types Layer -**File:** `internal/types/knowledgebase.go` (Lines 107-108) -**Change:** Added `WikiConfig` field to `KnowledgeBaseConfig` struct - -The struct now includes all configuration types: -- `ChunkingConfig` - document splitting configuration -- `ImageProcessingConfig` - image processing settings -- `FAQConfig` - FAQ-specific indexing configuration -- `WikiConfig` - wiki generation and maintenance settings ✓ NEW - -### Fix 2: Backend Service Layer -**File:** `internal/application/service/knowledgebase.go` (Lines 297-299) -**Change:** Added wiki_config persistence in `UpdateKnowledgeBase` method - -The service now applies all configuration updates: -```go -if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig -} -if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig // ✓ NEW -} -``` - -### Fix 3: Frontend API Types -**File:** `frontend/src/api/knowledge-base/index.ts` -**Changes:** Added WikiConfig type definition to both functions - -- **createKnowledgeBase()** (Lines 31-37): Added optional `wiki_config` parameter -- **updateKnowledgeBase()** (Lines 49-64): Added structured `config.wiki_config` parameter - -## Data Flow After Fix - -### KB Creation Flow -``` -Frontend: createKnowledgeBase({ - name: "...", - wiki_config: { - enabled: true, - auto_ingest: true, - synthesis_model_id: "...", - wiki_language: "en", - max_pages_per_ingest: 10 - } -}) - ↓ -POST /api/v1/knowledge-bases - ↓ -Handler: Parses to types.KnowledgeBase struct - ↓ -Service: CreateKnowledgeBase receives full KB - ↓ -Calls kb.EnsureDefaults() to validate wiki_config - ↓ -Repository: Saves to database - ↓ -Database: wiki_config stored as JSONB in knowledge_bases.wiki_config -``` - -### KB Update Flow (NOW FIXED) -``` -Frontend: updateKnowledgeBase(id, { - name: "...", - config: { - wiki_config: { - enabled: true, - auto_ingest: false, - synthesis_model_id: "...", - wiki_language: "zh", - max_pages_per_ingest: 20 - } - } -}) - ↓ -PUT /api/v1/knowledge-bases/{id} - ↓ -Handler: Parses to UpdateKnowledgeBaseRequest - ↓ -Request.Config deserializes to KnowledgeBaseConfig (NOW HAS WikiConfig field) - ↓ -Service: UpdateKnowledgeBase receives config with wiki_config - ↓ -Applies wiki_config to KB entity (lines 297-299) - ↓ -Calls kb.EnsureDefaults() to validate - ↓ -Repository: Updates database - ↓ -Database: wiki_config JSONB field updated -``` - -## Testing - -### Unit Test Example -```go -func TestUpdateKnowledgeBaseWithWikiConfig(t *testing.T) { - // Create a KB - kb := &types.KnowledgeBase{ID: "test-kb", Type: "document"} - - // Prepare config with wiki_config - config := &types.KnowledgeBaseConfig{ - WikiConfig: &types.WikiConfig{ - Enabled: true, - AutoIngest: true, - SynthesisModelID: "model-123", - WikiLanguage: "en", - MaxPagesPerIngest: 10, - }, - } - - // Update KB - updated, err := service.UpdateKnowledgeBase(ctx, kb.ID, "Updated", "...", config) - - // Assert - assert.NoError(t, err) - assert.NotNil(t, updated.WikiConfig) - assert.Equal(t, "model-123", updated.WikiConfig.SynthesisModelID) -} -``` - -### Integration Test Example -```bash -# 1. Create KB with wiki config -KB_ID=$(curl -X POST http://localhost:8080/api/v1/knowledge-bases \ - -H "Content-Type: application/json" \ - -d '{"name":"Test KB","type":"document","wiki_config":{"enabled":true}}' \ - | jq -r '.data.id') - -# 2. Update wiki config -curl -X PUT http://localhost:8080/api/v1/knowledge-bases/$KB_ID \ - -H "Content-Type: application/json" \ - -d '{ - "name":"Updated", - "config":{"wiki_config":{"enabled":false,"auto_ingest":true}} - }' - -# 3. Verify persistence -curl http://localhost:8080/api/v1/knowledge-bases/$KB_ID | jq '.data.wiki_config' -``` - -## Verification Checklist - -- [x] Code changes implemented in all three layers -- [x] Types properly defined for JSON marshaling/unmarshaling -- [x] Service logic applies wiki_config updates -- [x] Frontend types support IDE autocomplete -- [x] Backward compatibility maintained (all new fields optional) -- [x] No breaking changes to existing APIs -- [x] Git commit created with proper attribution - -## Backward Compatibility - -✓ **Existing code unaffected:** -- `wiki_config` parameter is optional in both create and update -- KnowledgeBaseConfig struct additions are backward compatible -- Service logic only processes wiki_config if provided -- No existing endpoints or behaviors changed - -✓ **Database schema compatible:** -- `wiki_config` column already exists (from migration 000032) -- Uses JSONB type with proper defaults - -✓ **API compatibility:** -- Old requests without wiki_config continue to work -- New requests with wiki_config now work (previously ignored) - -## Performance Impact - -**Minimal:** No performance degradation -- One additional null check in service layer -- One additional struct field (pointer, no allocation unless set) -- GORM handles JSONB efficiently - -## Deployment Considerations - -1. **No database migrations needed** - schema already supports wiki_config -2. **No restart required** - code-only change -3. **Safe to deploy** - fully backward compatible -4. **Monitoring** - watch for wiki_config related operations in logs - -## Files Modified - -| File | Lines | Type | Summary | -|------|-------|------|---------| -| `internal/types/knowledgebase.go` | 107-108 | Add | WikiConfig field to KnowledgeBaseConfig struct | -| `internal/application/service/knowledgebase.go` | 297-299 | Add | wiki_config persistence in UpdateKnowledgeBase | -| `frontend/src/api/knowledge-base/index.ts` | 31-37, 49-64 | Update | WikiConfig types in create/update functions | - -## Git Commit - -**Message:** `fix: Enable wiki_config updates in knowledge base configuration` - -**Details:** -- Commit hash: b09893d5 (or run `git log --oneline` to find it) -- Files changed: 3 -- Insertions: 43 -- Deletions: 20 - -## Status - -✅ **Implementation Complete** -- All code changes merged to main -- Backward compatible -- Ready for testing and deployment - diff --git a/INDEX_ALL_ANALYSIS.md b/INDEX_ALL_ANALYSIS.md deleted file mode 100644 index 8e3323e7..00000000 --- a/INDEX_ALL_ANALYSIS.md +++ /dev/null @@ -1,522 +0,0 @@ -# WeKnora Analysis Project - Complete Index - -**Project Scope:** Comprehensive analysis of WeKnora Agent architecture and infrastructure refactoring -**Sessions:** 2 (Session 1: Analysis | Session 2: Implementation) -**Total Documentation:** ~2,700 lines, ~90 KB -**Overall Status:** ✅ COMPLETE - ---- - -## Quick Navigation - -### 🚀 Start Here (5 minutes) -1. **This file** - You're reading it. Navigation hub. -2. **SESSION_2_COMPLETION_SUMMARY.md** - What was completed in Session 2 -3. **ANALYSIS_SUMMARY.md** - Questions answered + recommendations - -### 📖 Deep Dive (30 minutes) -1. **AGENT_WIKI_ANALYSIS.md** - Complete Agent ReAct engine documentation -2. **LANGUAGE_MIDDLEWARE_ANALYSIS.md** - Infrastructure discovery and opportunities -3. **REFACTORING_PLAN.md** - Detailed implementation strategy - -### ⚡ Quick Implementation (5-10 minutes) -1. **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** - Copy-paste ready code changes -2. **REFACTORING_IMPLEMENTATION_REPORT.md** - Verification and test results - ---- - -## Document Directory - -### Session 1: Agent Architecture Analysis - -#### 📄 AGENT_WIKI_ANALYSIS.md -**File Size:** 492 lines | **Read Time:** 15-20 minutes | **Complexity:** Advanced -**Purpose:** Complete technical analysis of WeKnora Agent ReAct engine - -**Contents:** -- Executive summary of ReAct (Reasoning + Acting) loop -- Agent engine main loop architecture (files, functions, code flow) -- Tool dispatch mechanism (automatic, not user-triggered) -- System prompts (Progressive RAG vs Pure Agent templates) -- Wiki tool registration (conditional, auto-detect by KB type) -- Complete tool list and filter logic -- Event-driven architecture -- Summary tables and key takeaways - -**Key Answers Provided:** -1. ✅ How does Agent dispatch tools? (Automatic via LLM response) -2. ✅ What system prompts exist? (RAG and Pure Agent templates) -3. ✅ How does Agent discover wiki tools? (Runtime KB type detection) -4. ✅ Is there a wiki-specific system prompt? (No - tools are discoverable) - -**Best For:** -- Understanding complete Agent architecture -- Learning how wiki tools are registered -- Understanding tool dispatch flow -- Reference guide for Agent ReAct implementation - ---- - -### Session 2: Language Infrastructure and Refactoring - -#### 📄 LANGUAGE_MIDDLEWARE_ANALYSIS.md -**File Size:** 349 lines | **Read Time:** 10-15 minutes | **Complexity:** Intermediate -**Purpose:** Identify existing language infrastructure and refactoring opportunities - -**Contents:** -- Language extraction middleware (`middleware/language.go`) -- Context helpers and language mapping (`types/context_helpers.go`) -- Existing LanguageLocaleName() function (9+ languages supported) -- Problem identification in wiki_ingest.go (hardcoded language logic) -- Refactoring opportunity analysis -- Impact assessment -- Code comparison (before/after) - -**Key Findings:** -- ✅ Existing centralized language function: `types.LanguageLocaleName()` -- ✅ Problem: 6 lines of duplicate hardcoded logic in wiki_ingest.go -- ✅ Solution: Replace with single-line function call -- ✅ Benefit: 83% code reduction, 9+ language support - -**Best For:** -- Understanding language infrastructure -- Identifying code reuse opportunities -- Learning about middleware patterns -- Reference for refactoring decisions - ---- - -#### 📄 REFACTORING_PLAN.md -**File Size:** 204 lines | **Read Time:** 8-12 minutes | **Complexity:** Intermediate -**Purpose:** Detailed implementation strategy with code diffs - -**Contents:** -- Problem statement and scope -- Solution architecture (single-line replacement) -- Detailed implementation steps -- Supported languages table (9+ languages with variants) -- Testing strategy -- Backward compatibility analysis -- Database migration implications (none required) -- Future enhancement phases -- Risk assessment -- Success criteria - -**Implementation Details:** -- File to modify: `/internal/application/service/wiki_ingest.go` -- Lines to change: 135-141 (6 lines → 1 line) -- Code diff provided with clear before/after -- No dependencies or breaking changes - -**Best For:** -- Planning refactoring work -- Understanding implementation approach -- Testing and QA strategies -- Deployment planning - ---- - -#### 📄 LANGUAGE_REFACTORING_QUICK_REFERENCE.md -**File Size:** 111 lines | **Read Time:** 3-5 minutes | **Complexity:** Beginner-friendly -**Purpose:** Quick start guide for developers - -**Contents:** -- Copy-paste ready code change -- Supported language mappings table -- Implementation checklist (6 steps) -- Testing instructions (unit and build) -- Backward compatibility verification -- Troubleshooting tips -- Quick links to detailed documentation - -**Quick Checklist:** -1. Open `internal/application/service/wiki_ingest.go` -2. Find lines 135-141 (language determination) -3. Replace 6 lines with: `lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage)` -4. Verify import: `types` package (line 14) -5. Run: `go test ./internal/types` -6. Commit changes - -**Best For:** -- Developers implementing the refactoring -- Quick reference during implementation -- Verification checklist -- Testing quick start - ---- - -#### 📄 REFACTORING_IMPLEMENTATION_REPORT.md -**File Size:** ~280 lines | **Read Time:** 12-15 minutes | **Complexity:** Intermediate -**Purpose:** Implementation verification and test results - -**Contents:** -- Status summary (✅ COMPLETED) -- Code refactoring documentation (before/after) -- Supported languages complete list -- Testing results (unit tests: all passing) -- Build verification (successful, no errors) -- Backward compatibility verification -- Code flow impact analysis -- Maintenance advantages -- Future enhancement opportunities -- Deployment checklist -- Rollback plan (if needed) - -**Verification Results:** -- ✅ 28 unit tests passing (all language variants covered) -- ✅ Build successful (no compilation errors) -- ✅ Backward compatible (existing configurations work) -- ✅ Ready for production deployment - -**Best For:** -- QA and verification -- Deployment confirmation -- Understanding test coverage -- Future maintenance reference - ---- - -### Cross-Cutting Analysis and Summaries - -#### 📄 ANALYSIS_SUMMARY.md -**File Size:** 319 lines | **Read Time:** 10-12 minutes | **Complexity:** Intermediate -**Purpose:** Executive summary connecting Session 1 and 2 findings - -**Contents:** -- Questions answered summary -- Key findings from both sessions -- Recommended actions by timeline - - Immediate: Language refactoring deployment - - Short-term: Extended language coverage - - Medium-term: LLM-specific optimization - - Long-term: Multi-language capabilities -- File locations and quick links -- Architecture diagrams (text-based) -- Related architecture patterns -- Next steps and deliverables - -**Organization:** -- By timeline (immediate → long-term) -- By effort (minimal → moderate → significant) -- By impact (high → medium → future) - -**Best For:** -- Executive overview -- Decision making -- Roadmap planning -- Connecting analysis findings - ---- - -#### 📄 README_ANALYSIS.md -**File Size:** ~450 lines | **Read Time:** 15-20 minutes | **Complexity:** Varies -**Purpose:** Navigation index and implementation roadmap - -**Contents:** -- Quick navigation guide -- Document index with descriptions and read time estimates -- Implementation roadmap (4 phases) -- Key findings summary -- Quick start paths: - - 2-minute path: Find specific answers - - 30-minute path: Understand refactoring opportunity - - 1+ hour path: Complete system understanding -- Document statistics -- Search reference (topics and their locations) -- Dependency map (which documents build on which) - -**Features:** -- Searchable by topic -- Time-estimate provided for each document -- Dependency relationships shown -- Multiple navigation paths based on time available - -**Best For:** -- Comprehensive navigation -- Finding specific information quickly -- Planning reading based on available time -- Understanding relationships between documents - ---- - -#### 📄 SESSION_2_COMPLETION_SUMMARY.md -**File Size:** ~400 lines | **Read Time:** 12-15 minutes | **Complexity:** Intermediate -**Purpose:** Session completion summary and final status - -**Contents:** -- Executive summary of Session 2 work -- Analysis and documentation completed (8 documents) -- Key findings from Session 2 (language infrastructure) -- Implementation checklist (all checked ✅) -- Supported language mappings (before/after comparison) -- Future enhancement roadmap (5 phases) -- Metrics and impact analysis -- Technical details and function chain analysis -- Cross-session context (Session 1 vs Session 2) -- Conclusion and next steps - -**Completion Status:** -- [x] Analysis completed (infrastructure discovered) -- [x] Refactoring implemented (code changed at line 139) -- [x] Testing verified (28/28 tests passing) -- [x] Documentation complete (8 documents created) -- [x] Ready for deployment - -**Best For:** -- Session wrap-up and completion verification -- Understanding Session 2 context -- Deployment confirmation -- Archive and reference - ---- - -#### 📄 INDEX_ALL_ANALYSIS.md -**This File** - Complete project index and navigation hub - ---- - -## Project Timeline - -### Session 1: Agent Architecture Analysis -**Duration:** Analysis session -**Deliverable:** AGENT_WIKI_ANALYSIS.md (492 lines) - -**Work Completed:** -- ✅ Traced Agent ReAct engine (engine.go main loop) -- ✅ Analyzed tool dispatch mechanism (act.go auto-trigger) -- ✅ Examined system prompts (prompts.go templates) -- ✅ Traced wiki tool registration (agent_service.go KB detection) -- ✅ Documented synthesis detection (heuristic-based in ingest pipeline) -- ✅ Created comprehensive analysis document - -**Questions Answered:** -1. How does Agent ReAct engine dispatch tools? -2. What system prompts does Agent use? -3. How does Agent discover wiki tools? -4. Is there a dedicated wiki system prompt? - ---- - -### Session 2: Language Infrastructure and Refactoring -**Duration:** Analysis and implementation session -**Deliverables:** 8 analysis and implementation documents + code refactoring - -**Work Completed:** -- ✅ Discovered language middleware infrastructure (context_helpers.go) -- ✅ Identified refactoring opportunity (wiki_ingest.go hardcoded logic) -- ✅ Implemented refactoring (6 lines → 1 line, 2 → 9+ languages) -- ✅ Verified with unit tests (28/28 passing) -- ✅ Confirmed build success (no errors) -- ✅ Documented implementation comprehensively (8 documents) - -**Documents Created:** -1. LANGUAGE_MIDDLEWARE_ANALYSIS.md - Infrastructure discovery -2. REFACTORING_PLAN.md - Implementation strategy -3. LANGUAGE_REFACTORING_QUICK_REFERENCE.md - Quick guide -4. REFACTORING_IMPLEMENTATION_REPORT.md - Verification results -5. ANALYSIS_SUMMARY.md - Executive summary -6. README_ANALYSIS.md - Navigation index (original) -7. SESSION_2_COMPLETION_SUMMARY.md - Session wrap-up -8. INDEX_ALL_ANALYSIS.md - This file - ---- - -## Document Dependency Map - -``` -INDEX_ALL_ANALYSIS.md (You are here) -├── SESSION_2_COMPLETION_SUMMARY.md (Session status & overview) -│ ├── ANALYSIS_SUMMARY.md (Findings summary) -│ ├── AGENT_WIKI_ANALYSIS.md (Session 1 results) -│ └── LANGUAGE_MIDDLEWARE_ANALYSIS.md (Session 2 infrastructure) -├── README_ANALYSIS.md (Full navigation hub) -│ └── All other documents (linked) -├── Quick Implementation Path -│ ├── LANGUAGE_REFACTORING_QUICK_REFERENCE.md (How-to) -│ └── REFACTORING_IMPLEMENTATION_REPORT.md (Verification) -└── Deep Understanding Path - ├── AGENT_WIKI_ANALYSIS.md (Agent architecture) - ├── LANGUAGE_MIDDLEWARE_ANALYSIS.md (Infrastructure) - ├── REFACTORING_PLAN.md (Strategy) - └── ANALYSIS_SUMMARY.md (Connections) -``` - ---- - -## How to Use This Documentation - -### Scenario 1: I need to understand what was done -**Time:** 10 minutes -**Path:** -1. Read: SESSION_2_COMPLETION_SUMMARY.md -2. Read: ANALYSIS_SUMMARY.md -3. Skim: REFACTORING_IMPLEMENTATION_REPORT.md - -### Scenario 2: I need to implement the refactoring -**Time:** 15 minutes -**Path:** -1. Quick read: LANGUAGE_REFACTORING_QUICK_REFERENCE.md (5 min) -2. Reference: REFACTORING_PLAN.md (5 min) -3. Implement: Code changes (5 min) -4. Verify: REFACTORING_IMPLEMENTATION_REPORT.md (pass/fail) - -### Scenario 3: I need to understand the complete system -**Time:** 60 minutes -**Path:** -1. AGENT_WIKI_ANALYSIS.md (20 min) - Agent architecture -2. LANGUAGE_MIDDLEWARE_ANALYSIS.md (15 min) - Infrastructure -3. REFACTORING_PLAN.md (10 min) - Strategy -4. README_ANALYSIS.md (10 min) - Navigation and connections -5. ANALYSIS_SUMMARY.md (5 min) - Final summary - -### Scenario 4: I'm new and need onboarding -**Time:** 90 minutes -**Path:** -1. This file: INDEX_ALL_ANALYSIS.md (5 min) -2. README_ANALYSIS.md (10 min) - Overview navigation -3. SESSION_2_COMPLETION_SUMMARY.md (15 min) - Session results -4. AGENT_WIKI_ANALYSIS.md (25 min) - Architecture deep dive -5. LANGUAGE_MIDDLEWARE_ANALYSIS.md (15 min) - Infrastructure details -6. REFACTORING_PLAN.md (10 min) - Implementation understanding -7. ANALYSIS_SUMMARY.md (5 min) - Summary & recommendations - ---- - -## Key Metrics - -### Documentation Statistics -| Metric | Value | -|--------|-------| -| Total documents | 8 | -| Total lines | ~2,700 | -| Total size | ~90 KB | -| Average doc size | 337 lines | -| Complexity range | Beginner → Advanced | -| Read time (all) | 90-120 minutes | - -### Code Changes -| Metric | Before | After | Change | -|--------|--------|-------|--------| -| Wiki ingest lang lines | 6 | 1 | -83% | -| Languages supported | 2 | 9+ | +350% | -| Tests passing | N/A | 28/28 | ✅ | -| Build status | N/A | Success | ✅ | -| Backward compat | N/A | 100% | ✅ | - ---- - -## Files in WeKnora Codebase - -### Modified Files -- `/internal/application/service/wiki_ingest.go` - Line 139 (language determination refactored) - -### Analyzed Files (Not Modified) -- `/internal/agent/engine.go` - ReAct engine main loop -- `/internal/agent/act.go` - Tool dispatch mechanism -- `/internal/agent/prompts.go` - System prompts -- `/internal/agent/prompts_wiki.go` - Wiki ingest prompts -- `/internal/agent/tools/wiki_tools.go` - Wiki tool implementations -- `/internal/agent/tools/definitions.go` - Tool definitions -- `/internal/application/service/agent_service.go` - Tool registration -- `/internal/middleware/language.go` - Language middleware -- `/internal/types/context_helpers.go` - Language infrastructure - -### Documentation Files (Root Directory) -- AGENT_WIKI_ANALYSIS.md -- LANGUAGE_MIDDLEWARE_ANALYSIS.md -- REFACTORING_PLAN.md -- LANGUAGE_REFACTORING_QUICK_REFERENCE.md -- ANALYSIS_SUMMARY.md -- README_ANALYSIS.md -- REFACTORING_IMPLEMENTATION_REPORT.md -- SESSION_2_COMPLETION_SUMMARY.md -- INDEX_ALL_ANALYSIS.md (this file) - ---- - -## Project Status Summary - -### ✅ Completed Tasks -- [x] Agent ReAct engine architecture analysis -- [x] Tool dispatch mechanism documentation -- [x] System prompts analysis -- [x] Wiki tool registration traced -- [x] Language middleware infrastructure discovered -- [x] Refactoring opportunity identified -- [x] Language refactoring implemented -- [x] Unit tests verified (28/28 passing) -- [x] Build verification completed -- [x] Backward compatibility confirmed -- [x] Comprehensive documentation created (8 documents) - -### 📋 Ready for Next Steps -- Deploy language refactoring to production -- Expand language support (Phase 2) -- Optimize for specific LLMs (Phase 3) -- Integrate language detection (Phase 4) -- Implement multi-language wiki pages (Phase 5) - -### 🚀 Deployment Status -**Status:** ✅ Ready for production -**Risk Level:** Low (single file change, 100% backward compatible) -**Testing:** Complete (unit tests + build verification) -**Documentation:** Comprehensive (8 documents) - ---- - -## Next Steps - -### Immediate (This Week) -1. Review: LANGUAGE_REFACTORING_QUICK_REFERENCE.md -2. Deploy: Language refactoring to production -3. Monitor: No configuration changes needed - -### Short-term (This Month) -1. Plan: Extended language coverage (Phase 2) -2. Design: Language-specific LLM optimization (Phase 3) -3. Implement: Italian, Dutch, Swedish support - -### Medium-term (Next Quarter) -1. Integrate: Document language detection -2. Enhance: Per-page language overrides -3. Optimize: Search ranking by language - -### Long-term (Next 6 Months) -1. Multi-language wiki pages -2. Bi-lingual content support -3. Regional dialect handling -4. Language-specific UI customization - ---- - -## Contact and Support - -For questions about: -- **Agent ReAct architecture** → See AGENT_WIKI_ANALYSIS.md -- **Language refactoring** → See LANGUAGE_REFACTORING_QUICK_REFERENCE.md -- **Implementation strategy** → See REFACTORING_PLAN.md -- **Test results** → See REFACTORING_IMPLEMENTATION_REPORT.md -- **Overall navigation** → See README_ANALYSIS.md -- **Session completion** → See SESSION_2_COMPLETION_SUMMARY.md - ---- - -## Archive Information - -**Project Created:** Session 1 & 2 (2026-04-07) -**Total Duration:** 2 analysis sessions -**Total Documentation:** 8 documents, ~2,700 lines, ~90 KB -**Status:** Complete and ready for production - -**Archival Value:** High - Comprehensive analysis suitable for: -- Onboarding new developers -- Understanding Agent architecture -- Reference for future refactoring -- Documentation of language infrastructure decisions -- Implementation verification - ---- - -**Version:** 1.0 -**Last Updated:** 2026-04-07 -**Status:** ✅ COMPLETE - Ready for Production diff --git a/KB_DATA_MODEL_COMPLETE_ANALYSIS.txt b/KB_DATA_MODEL_COMPLETE_ANALYSIS.txt deleted file mode 100644 index a96639b6..00000000 --- a/KB_DATA_MODEL_COMPLETE_ANALYSIS.txt +++ /dev/null @@ -1,439 +0,0 @@ -═══════════════════════════════════════════════════════════════════════════════ -WEKNORA KNOWLEDGE BASE DATA MODEL & DOCUMENT PROCESSING PIPELINE - COMPLETE ANALYSIS -═══════════════════════════════════════════════════════════════════════════════ - -PART 1: KNOWLEDGEBASE TYPE DEFINITION -══════════════════════════════════════ - -📁 File: internal/types/knowledgebase.go (Lines 40-98) - -📊 KnowledgeBase Struct - ALL FIELDS: - -CORE FIELDS: - • ID string - UUID primary key - • Name string - KB name (unique within tenant) - • Type string - "document", "faq", or "wiki" - • IsTemporary bool - Ephemeral flag (hidden from UI) - • Description string - KB description - • TenantID uint64 - Tenant ownership - -CHUNKING & PROCESSING: - • ChunkingConfig ChunkingConfig - Document splitting strategy - • ImageProcessingConfig ImageProcessingConfig - Image model config - • EmbeddingModelID string - Model for vectorization (CRITICAL) - • SummaryModelID string - Model for summaries - -MULTIMODAL & KNOWLEDGE EXTRACTION: - • VLMConfig VLMConfig - Vision-Language Model settings - • ASRConfig ASRConfig - Speech recognition config - • ExtractConfig *ExtractConfig - Knowledge graph extraction - -STORAGE CONFIGURATION: - • StorageProviderConfig *StorageProviderConfig - Provider selection (new) - • StorageConfig StorageConfig - Legacy COS config (deprecated) - -TYPE-SPECIFIC CONFIGURATIONS: - • FAQConfig *FAQConfig - FAQ indexing strategy - • QuestionGenerationConfig *QuestionGenerationConfig - Auto Q&A generation - • WikiConfig *WikiConfig - Wiki feature settings (KEY!) - -PINNING & TIMESTAMPS: - • IsPinned bool - • PinnedAt *time.Time - • CreatedAt time.Time - • UpdatedAt time.Time - • DeletedAt gorm.DeletedAt - -COMPUTED FIELDS (NOT in database): - • KnowledgeCount int64 - Calculated on query - • ChunkCount int64 - Calculated on query - • IsProcessing bool - FAQ import status - • ProcessingCount int64 - Items being processed - • ShareCount int64 - Org shares count - -─────────────────────────────────────────────────────────────────────────────── - -PART 2: CHUNKING CONFIGURATION -═══════════════════════════════ - -📁 File: internal/types/knowledgebase.go (Lines 118-141) - -type ChunkingConfig struct { - ChunkSize int - Chunk size (default: 512) - ChunkOverlap int - Overlap between chunks (default: 50) - Separators []string - Split points (default: ["\n\n", "\n", "。"]) - - PARENT-CHILD STRATEGY: - EnableParentChild bool - Two-level chunking strategy - ParentChunkSize int - Large chunks for context (default: 4096) - ChildChunkSize int - Small chunks for embeddings (default: 384) - - LEGACY: - EnableMultimodal bool - Deprecated (use VLMConfig) - ParserEngineRules []ParserEngineRule - Custom parser per file type -} - -💡 PARENT-CHILD STRATEGY INSIGHT: - - Parent chunks: LARGE, provide context, NOT indexed - - Child chunks: SMALL, used for vector matching, indexed - - Retrieval: match on child, return parent content - -─────────────────────────────────────────────────────────────────────────────── - -PART 3: WIKI CONFIGURATION -═══════════════════════════ - -📁 File: internal/types/wiki_page.go (Lines 91-103) - -type WikiConfig struct { - Enabled bool - Feature flag (on/off) - AutoIngest bool - Auto-generate on doc upload - SynthesisModelID string - LLM for wiki generation - MaxPagesPerIngest int - Rate limit per batch (0=unlimited) -} - -🔑 CRITICAL INSIGHT - Wiki is NOT a separate KB type: - - Wiki is an ADD-ON feature for document-type KBs - - Enabled via WikiConfig on existing KnowledgeBase - - Check: func (kb *KnowledgeBase) IsWikiEnabled() bool { - return kb != nil && kb.WikiConfig != nil && kb.WikiConfig.Enabled - } - -─────────────────────────────────────────────────────────────────────────────── - -PART 4: FAQ & QUESTION GENERATION CONFIGS -═══════════════════════════════════════════ - -FAQ Configuration (Lines 451-472): - FAQIndexMode: - • "question_only" - Index questions only - • "question_answer" - Index Q&A together - - QuestionIndexMode: - • "combined" - Q+similar questions together - • "separate" - Q+similar questions separately - -Question Generation Config (Lines 353-377): - Enabled bool - Turn on auto Q&A generation - QuestionCount int - Questions per chunk (default: 3, max: 10) - -─────────────────────────────────────────────────────────────────────────────── - -PART 5: DOCUMENT PROCESSING PIPELINE -═════════════════════════════════════ - -📁 File: internal/application/service/knowledge.go (Lines 1680-2074) - -Function: processChunks(ctx, kb, knowledge, chunks, opts) - -PROCESSING STEPS: -┌─────────────────────────────────────────────────────────────────────┐ -│ 1. DELETION CHECK (Lines 1701-1705) │ -│ - Verify knowledge is not being deleted │ -└─────────────────────────────────────────────────────────────────────┘ -│ 2. GET EMBEDDING MODEL (Lines 1708-1714) │ -│ - Fetch model from KB.EmbeddingModelID │ -│ - This model determines vectorization behavior │ -└─────────────────────────────────────────────────────────────────────┘ -│ 3. CLEANUP OLD DATA (Lines 1716-1744) │ -│ - Delete existing chunks │ -│ - Remove old index data │ -│ - Remove knowledge graph data │ -└─────────────────────────────────────────────────────────────────────┘ -│ 4. CREATE PARENT CHUNKS (Lines 1810-1839) │ -│ - If EnableParentChild: create large context chunks │ -│ - Parent chunks stored but NOT indexed │ -│ - Wire up parent↔child links │ -└─────────────────────────────────────────────────────────────────────┘ -│ 5. CREATE TEXT & IMAGE CHUNKS (Lines 1843-1906) │ -│ - Text chunks from content │ -│ - Image OCR chunks from extracted text │ -│ - Image Caption chunks from AI descriptions │ -│ - Link child chunks to parents │ -└─────────────────────────────────────────────────────────────────────┘ -│ 6. BUILD INDEX INFORMATION (Lines 1908-1928) │ -│ - Create IndexInfo only for vectorizable chunks │ -│ - Parent chunks excluded from indexing │ -│ - Prepend document title for semantic alignment │ -│ - Result: indexInfoList (ready for embedding) │ -└─────────────────────────────────────────────────────────────────────┘ -│ 7. ESTIMATE STORAGE (Lines 1932-1955) │ -│ - Calculate embedding storage required │ -│ - Check tenant quota availability │ -└─────────────────────────────────────────────────────────────────────┘ -│ 8. SAVE CHUNKS TO DB (Lines 1964-1973) │ -│ - Persist all chunks (including parents) │ -└─────────────────────────────────────────────────────────────────────┘ -│ 9. *** BATCH INDEX *** (Lines 1986-2007) │ -│ - Call: retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList) -│ - THIS IS WHERE VECTOR VS KEYWORD INDEXING IS DECIDED │ -│ - VectorStore implementation determines strategy │ -│ - If error: cleanup and mark as failed │ -└─────────────────────────────────────────────────────────────────────┘ -│ 10. ENQUEUE POST-PROCESSING (Lines 2044-2066) │ -│ - If multimodal: enqueue image processing tasks │ -│ - Else: enqueue post-process task immediately │ -└─────────────────────────────────────────────────────────────────────┘ - -ProcessChunksOptions: - struct { - EnableQuestionGeneration bool - QuestionCount int - EnableMultimodel bool - StoredImages []docparser.StoredImage - ParentChunks []types.ParsedParentChunk - Metadata map[string]string - } - -─────────────────────────────────────────────────────────────────────────────── - -PART 6: POST-PROCESSING HANDLER - WIKI TRIGGER -═══════════════════════════════════════════════ - -📁 File: internal/application/service/knowledge_post_process.go (Lines 42-128) - -KnowledgePostProcessService.Handle() orchestrates: - -1. Fetch knowledge + chunks -2. Filter text-like chunks (ChunkTypeText, ImageOCR, ImageCaption) -3. Update ParseStatus → "completed" -4. Enqueue Summary Generation -5. Enqueue Question Generation (if KB.QuestionGenerationConfig.Enabled) -6. Enqueue Graph RAG Extraction (if KB.ExtractConfig.Enabled) - -🔴 WIKI INGEST TRIGGER CONDITION (Lines 122-126): - -┌─────────────────────────────────────────────────────────────┐ -│ if kb.IsWikiEnabled() │ -│ && kb.WikiConfig.AutoIngest │ -│ && len(textChunks) > 0 { │ -│ │ -│ EnqueueWikiIngest(ctx, s.taskEnqueuer, s.redisClient, │ -│ payload.TenantID, │ -│ payload.KnowledgeBaseID, │ -│ payload.KnowledgeID) │ -│ } │ -└─────────────────────────────────────────────────────────────┘ - -TRIGGER REQUIREMENTS (ALL THREE MUST BE TRUE): - 1. kb.IsWikiEnabled() → WikiConfig != nil && WikiConfig.Enabled - 2. kb.WikiConfig.AutoIngest → User enabled auto wiki generation - 3. len(textChunks) > 0 → Document has processable text - -TIMING: After Summary + Question + Graph RAG tasks enqueued - -─────────────────────────────────────────────────────────────────────────────── - -PART 7: KNOWLEDGE BASE API / DTO TYPES -═══════════════════════════════════════ - -📁 Handler: internal/handler/knowledgebase.go (Lines 114-147) - Uses: types.KnowledgeBase directly from request body - -📁 Client: client/knowledgebase.go (Lines 15-96) - Mirrors: types.KnowledgeBase with supporting DTOs - -Request/Response: -{ - "id": "uuid", - "name": "My Knowledge Base", - "type": "document", /* or "faq" */ - "description": "...", - "embedding_model_id": "gpt-embedding-3-large", - "summary_model_id": "gpt-4-turbo", - "chunking_config": { - "chunk_size": 512, - "chunk_overlap": 50, - "separators": ["\n\n", "\n", "。"], - "enable_parent_child": true, - "parent_chunk_size": 4096, - "child_chunk_size": 384 - }, - "vlm_config": { - "enabled": true, - "model_id": "gpt-4-vision" - }, - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4-turbo", - "max_pages_per_ingest": 10 - }, - "question_generation_config": { - "enabled": true, - "question_count": 3 - }, - "faq_config": { - "index_mode": "question_answer", - "question_index_mode": "combined" - } -} - -─────────────────────────────────────────────────────────────────────────────── - -PART 8: CHUNK TYPES & INDEXING BEHAVIOR -════════════════════════════════════════ - -📁 File: internal/types/chunk.go (Lines 11-39) - -CHUNKS THAT ARE INDEXED (vectorized): - ✓ ChunkTypeText = "text" - Primary content chunks - ✓ ChunkTypeImageOCR = "image_ocr" - OCR from images - ✓ ChunkTypeImageCaption = "image_caption" - Image descriptions - -CHUNKS THAT ARE NOT INDEXED (stored only): - ✗ ChunkTypeParentText = "parent_text" - Context (parent-child) - ✗ ChunkTypeSummary = "summary" - Generated summaries - ✗ ChunkTypeEntity = "entity" - Knowledge graph nodes - ✗ ChunkTypeRelationship = "relationship" - Knowledge graph edges - ✗ ChunkTypeFAQ = "faq" - FAQ entries - ✗ ChunkTypeWikiPage = "wiki_page" - Wiki pages - -─────────────────────────────────────────────────────────────────────────────── - -PART 9: KNOWLEDGE ENTITY MODEL -═══════════════════════════════ - -📁 File: internal/types/knowledge.go (Lines 69-127) - -Knowledge entity represents a single document/knowledge item: - - • ID - UUID of knowledge item - • KnowledgeBaseID - Parent KB - • TenantID - Tenant ownership - • Type - "manual" (Markdown) or "faq" - • Title, Description - • Source - URL, file path, or "manual" - • Channel - Ingestion channel (web, api, wechat, etc.) - - STATUS FIELDS: - • ParseStatus - pending|processing|completed|failed|deleting - • SummaryStatus - none|pending|processing|completed|failed - • EnableStatus - enabled|disabled - - FILE INFO: - • FileName, FileType, FileSize, FileHash, FilePath - • StorageSize - Space used for embeddings - - • Metadata - JSON metadata - • LastFAQImportResult - FAQ import status - -─────────────────────────────────────────────────────────────────────────────── - -PART 10: COMPLETE DATA FLOW DIAGRAM -═════════════════════════════════════ - -DOCUMENT UPLOAD → INDEXING → POST-PROCESSING → WIKI INGEST - -┌──────────────────────────┐ -│ Document Upload (API) │ -└────────────┬─────────────┘ - ↓ -┌──────────────────────────┐ -│ Document Parsing │ -│ - Select ParserEngine │ -│ - Extract Content │ -│ - Split to chunks │ -└────────────┬─────────────┘ - ↓ -┌──────────────────────────────────────────────────────┐ -│ processChunks() in knowledge.go:1681 │ -│ │ -│ 1. Get Embedding Model │ -│ 2. Clean old chunks/indexes │ -│ 3. Create Chunk objects: │ -│ ├─ Parent chunks (context, no index) │ -│ ├─ Text chunks (indexed) │ -│ └─ Image chunks: OCR + Caption (indexed) │ -│ 4. Build IndexInfo (for vectorizable chunks only) │ -│ 5. Call retrieveEngine.BatchIndex() │ -│ └─> Vector/Keyword indexing decision made here │ -│ 6. Enqueue image multimodal tasks (if needed) │ -│ 7. Enqueue post-process task │ -└────────────┬─────────────────────────────────────────┘ - ↓ -┌──────────────────────────────────────────────────────┐ -│ KnowledgePostProcessService.Handle() │ -│ (knowledge_post_process.go:42) │ -│ │ -│ 1. Update Knowledge status → "completed" │ -│ 2. Enqueue Summary Generation Task │ -│ 3. Enqueue Question Generation (if enabled) │ -│ 4. Enqueue Graph RAG Extraction (if enabled) │ -│ 5. *** WIKI INGEST DECISION *** │ -│ if IsWikiEnabled() && AutoIngest && hasText: │ -│ └─> EnqueueWikiIngest() │ -└────────────┬─────────────────────────────────────────┘ - ↓ - [System Ready for Query] - -═══════════════════════════════════════════════════════════════════════════════ - -QUICK REFERENCE TABLE -═════════════════════ - -Component Configuration Default Purpose -───────────────────────────────────────────────────────────────────────────────── -Document Chunking ChunkSize 512 chars Split documents - ChunkOverlap 50 chars Overlap between chunks - Separators [\n\n,\n,。] Split points - -Parent-Child Strategy EnableParentChild false Context retrieval - ParentChunkSize 4096 chars Large context chunks - ChildChunkSize 384 chars Small embedding chunks - -Vectorization EmbeddingModelID (required) Which model vectorizes - -Multimodal VLMConfig.Enabled false Image understanding - ImageProcessingConfig (optional) Image model selection - -Auto Q&A Generation QuestionGenerationConfig.Enabled false Auto Q&A - QuestionCount 3 (default) Q's per chunk - -FAQ Indexing FAQConfig (optional) FAQ-specific strategy - -Knowledge Graph ExtractConfig.Enabled false Entity extraction - -Wiki Feature WikiConfig.Enabled false Wiki on/off - WikiConfig.AutoIngest false Auto wiki generation - SynthesisModelID (inherited) Wiki generation model - MaxPagesPerIngest 0 (unlimited) Rate limiting - -═══════════════════════════════════════════════════════════════════════════════ - -KEY FILES REFERENCE -═══════════════════ - -1. KnowledgeBase Definition - 📄 internal/types/knowledgebase.go (Lines 40-98) - -2. WikiConfig Definition - 📄 internal/types/wiki_page.go (Lines 91-103) - -3. Document Processing Pipeline - 📄 internal/application/service/knowledge.go (Lines 1680-2074) - - processChunks() function - - ProcessChunksOptions struct - - Batch indexing logic - -4. Post-Processing & Wiki Trigger - 📄 internal/application/service/knowledge_post_process.go (Lines 42-128) - - KnowledgePostProcessService.Handle() - - Wiki ingest trigger condition (Lines 122-126) - -5. API Handler - 📄 internal/handler/knowledgebase.go (Lines 114-147) - - CreateKnowledgeBase endpoint - -6. Client API Types - 📄 client/knowledgebase.go (Lines 15-96) - -7. Chunk Types - 📄 internal/types/chunk.go (Lines 11-39) - -8. Knowledge Entity - 📄 internal/types/knowledge.go (Lines 69-127) - -═══════════════════════════════════════════════════════════════════════════════ -END OF REPORT -═══════════════════════════════════════════════════════════════════════════════ diff --git a/KB_WIKI_ARCHITECTURE_ANALYSIS.md b/KB_WIKI_ARCHITECTURE_ANALYSIS.md deleted file mode 100644 index 16a449a4..00000000 --- a/KB_WIKI_ARCHITECTURE_ANALYSIS.md +++ /dev/null @@ -1,1021 +0,0 @@ -# Knowledge Base System Architecture & Wiki Feature Analysis - -## Executive Summary - -This document provides a comprehensive overview of the WeKnora knowledge base system architecture, focusing on how Wiki functionality integrates into the knowledge base ecosystem, and how agents connect to and utilize knowledge bases. - ---- - -## 1. KNOWLEDGE BASE DATA MODEL - -### 1.1 Core Knowledge Base Entity - -**File:** `internal/types/knowledgebase.go` - -```go -type KnowledgeBase struct { - ID string // UUID primary key - Name string // User-friendly name - Type string // "document", "faq", or "wiki" - IsTemporary bool // Hidden from UI if true - Description string - TenantID uint64 // Multi-tenant isolation - - // Configurations - ChunkingConfig ChunkingConfig // Doc splitting settings - ImageProcessingConfig ImageProcessingConfig // VLM settings - EmbeddingModelID string // Vector embedding model - SummaryModelID string // Summarization model - VLMConfig VLMConfig // Vision-Language Model - ASRConfig ASRConfig // Speech recognition - StorageProviderConfig *StorageProviderConfig // Storage backend (local, minio, s3, etc.) - ExtractConfig *ExtractConfig // Knowledge graph extraction - FAQConfig *FAQConfig // FAQ-specific settings - QuestionGenerationConfig *QuestionGenerationConfig // Auto-generate questions - WikiConfig *WikiConfig // Wiki-specific settings ← KEY - - // Metadata - IsPinned bool - PinnedAt *time.Time - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt gorm.DeletedAt // Soft delete - - // Computed fields (not persisted) - KnowledgeCount int64 // Total documents - ChunkCount int64 // Total chunks - IsProcessing bool // Async tasks running - ProcessingCount int64 // Docs in progress -} - -type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig - ImageProcessingConfig ImageProcessingConfig - FAQConfig *FAQConfig - WikiConfig *WikiConfig -} -``` - -### 1.2 Knowledge Base Types - -```go -const ( - KnowledgeBaseTypeDocument = "document" // Standard document KB - KnowledgeBaseTypeFAQ = "faq" // FAQ KB - KnowledgeBaseTypeWiki = "wiki" // ← NOT A TYPE! Wiki is a FEATURE -) -``` - -**CRITICAL:** Wiki is NOT a separate KB type. Instead, it's an add-on feature enabled via `WikiConfig` on document-type KBs via `IsWikiEnabled()` method. - -### 1.3 Wiki Configuration - -**File:** `internal/types/wiki_page.go` - -```go -type WikiConfig struct { - Enabled bool // Activates wiki generation for this KB - AutoIngest bool // Auto-generate wiki pages on document ingestion - SynthesisModelID string // LLM model ID for wiki page generation - MaxPagesPerIngest int // Rate limit: pages created/updated per batch (0 = unlimited) -} - -// Check if wiki is enabled -func (kb *KnowledgeBase) IsWikiEnabled() bool { - return kb != nil && kb.WikiConfig != nil && kb.WikiConfig.Enabled -} -``` - -### 1.4 Chunking Configuration (Document Processing) - -```go -type ChunkingConfig struct { - ChunkSize int // Document chunk size (default: 512) - ChunkOverlap int // Overlap between chunks (default: 20%) - Separators []string // Custom separators (e.g., "\n\n", "\n") - EnableMultimodal bool // Deprecated: use VLMConfig instead - ParserEngineRules []ParserEngineRule // Map file types to parser engines - EnableParentChild bool // Two-level parent-child chunking - ParentChunkSize int // Large context chunks (default: 4096) - ChildChunkSize int // Small embedding chunks (default: 384) -} - -type ParserEngineRule struct { - FileTypes []string // e.g., ["pdf", "docx"] - Engine string // e.g., "builtin", "ocr", "ml" -} -``` - ---- - -## 2. KNOWLEDGE ENTITY - -### 2.1 Knowledge (Document) Data Model - -**File:** `internal/types/knowledge.go` - -```go -type Knowledge struct { - ID string // UUID - TenantID uint64 - KnowledgeBaseID string // FK to KnowledgeBase - TagID string // Optional categorization - Type string // "manual" or content type - Title string - Description string - Source string // URL or "manual" - Channel string // How it was ingested (web, api, browser_extension, etc.) - - // Processing pipeline - ParseStatus string // pending, processing, completed, failed, deleting - SummaryStatus string // none, pending, processing, completed, failed - EnableStatus string - - // File metadata - FileName string - FileType string - FileSize int64 - FileHash string - FilePath string - StorageSize int64 - - // Content and metadata - Metadata JSON // Manual/FAQ metadata - LastFAQImportResult JSON // FAQ import status - EmbeddingModelID string // Model used for embedding - - // Timestamps - CreatedAt time.Time - UpdatedAt time.Time - ProcessedAt *time.Time - ErrorMessage string - DeletedAt gorm.DeletedAt // Soft delete -} -``` - -### 2.2 Parse Status Lifecycle - -``` -pending → processing → completed (success) or failed - → deleting (async deletion in progress) -``` - -### 2.3 Manual Knowledge (Markdown) - -```go -type ManualKnowledgeMetadata struct { - Content string // Markdown content - Format string // "markdown" - Status string // "draft" or "publish" - Version int // Increment on update - UpdatedAt string // RFC3339 timestamp -} -``` - ---- - -## 3. CHUNK DATA MODEL & INDEXING PIPELINE - -### 3.1 Chunk Definition - -**File:** `internal/types/chunk.go` - -Chunks are the indexed units of content used for retrieval: -- Created from splitting `Knowledge` documents using `ChunkingConfig` -- Each chunk contains: content, metadata, embeddings, keywords -- Support both vector (embedding) and keyword (BM25) indexing - -### 3.2 Indexing Types - -```go -type RetrieverType string - -const ( - VectorRetrieverType = "vector" // Semantic search via embeddings - KeywordRetrieverType = "keyword" // BM25 keyword search -) -``` - -### 3.3 Hybrid Retrieval Engine - -**File:** `internal/application/service/retriever/keywords_vector_hybrid_indexer.go` - -```go -type KeywordsVectorHybridRetrieveEngineService struct { - indexRepository interfaces.RetrieveEngineRepository - engineType types.RetrieverEngineType -} - -// Supports multiple backends: -// - Elasticsearch v7/v8 -// - Weaviate -// - Qdrant -// - Milvus -// - SQLite (local) -// - PostgreSQL -``` - -### 3.4 Index() vs BatchIndex() - -1. **Single Index()** - For individual document ingestion - - Creates embedding if VectorRetrieverType enabled - - Saves to repository (chunks + metadata) - -2. **BatchIndex()** - For bulk operations - - Batch embedding with retry logic - - Concurrent batch saving (max 5 concurrent) - - Chunk size: 40 items per batch - ---- - -## 4. WIKI PAGE DATA MODEL - -### 4.1 Wiki Page Entity - -**File:** `internal/types/wiki_page.go` - -```go -type WikiPage struct { - ID string // UUID - TenantID uint64 - KnowledgeBaseID string // FK to KnowledgeBase - Slug string // URL-friendly (e.g., "entity/acme-corp") - Title string // Human-readable name - PageType string // summary, entity, concept, index, log, synthesis, comparison - Status string // draft, published, archived - - // Content - Content string // Full markdown - Summary string // One-line summary - - // References and links - Aliases StringArray // Alt names, acronyms (JSON) - SourceRefs StringArray // Knowledge IDs that contributed (JSON) - InLinks StringArray // Pages linking TO this ([[slug]]) - OutLinks StringArray // Pages this links to (JSON) - - // Metadata and versioning - PageMetadata JSON // Custom metadata (JSON) - Version int // Increment on content change - - // Timestamps - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt gorm.DeletedAt // Soft delete -} - -// Unique constraint: (KnowledgeBaseID, Slug) -``` - -### 4.2 Wiki Page Types - -```go -const ( - WikiPageTypeSummary = "summary" // Auto-created from document - WikiPageTypeEntity = "entity" // Auto-created (person, org, place) - WikiPageTypeConcept = "concept" // Auto-created (topic, idea) - WikiPageTypeIndex = "index" // Auto-created: table of contents - WikiPageTypeLog = "log" // Auto-created: operation log - WikiPageTypeSynthesis = "synthesis" // Agent-created: cross-doc analysis - WikiPageTypeComparison = "comparison" // Agent-created: entity/concept comparison -) -``` - -### 4.3 Wiki Page Status - -```go -const ( - WikiPageStatusDraft = "draft" // In progress - WikiPageStatusPublished = "published" // Visible - WikiPageStatusArchived = "archived" // Hidden but preserved -) -``` - -### 4.4 Wiki Page Issue Tracking - -```go -type WikiPageIssue struct { - ID string - TenantID uint64 - KnowledgeBaseID string - Slug string // Which page has the issue - IssueType string // Type of issue (e.g., "missing_context") - Description string - SuspectedKnowledgeIDs StringArray // Knowledge items to fix - Status string // pending, resolved, ignored - ReportedBy string // Agent or user name - CreatedAt time.Time - UpdatedAt time.Time -} -``` - -### 4.5 Wiki Stats & Graph - -```go -type WikiStats struct { - TotalPages int64 - PagesByType map[string]int64 - TotalLinks int64 - OrphanCount int64 // Pages with no inbound links - RecentUpdates []*WikiPage - PendingTasks int64 // Docs waiting to ingest - PendingIssues int64 - IsActive bool // Wiki ingestion running -} - -type WikiGraphData struct { - Nodes []WikiGraphNode - Edges []WikiGraphEdge -} -``` - ---- - -## 5. WIKI GENERATION & INGESTION PIPELINE - -### 5.1 Wiki Ingest Service - -**File:** `internal/application/service/wiki_ingest.go` - -```go -type wikiIngestService struct { - wikiService interfaces.WikiPageService - kbService interfaces.KnowledgeBaseService - knowledgeSvc interfaces.KnowledgeService - chunkRepo interfaces.ChunkRepository - modelService interfaces.ModelService - task interfaces.TaskEnqueuer - redisClient *redis.Client // nil in Lite mode -} -``` - -### 5.2 Wiki Ingest Flow - -1. **Document Ingestion Trigger** - - User uploads document to KB with `WikiConfig.AutoIngest = true` - - Document → Knowledge entity → Chunks (normal indexing) - - Wiki ingest task enqueued (delayed 30 seconds to debounce) - -2. **Wiki Ingest Task** (Async via Asynq) - - Redis-backed pending queue: `wiki:pending:{kbID}` - - Concurrent batch prevention: `wiki:active:{kbID}` lock (5 min TTL) - - Max docs per batch: 5 (configurable via `MaxPagesPerIngest`) - -3. **Page Generation** (LLM-powered) - - For each pending document: - - Fetch chunks (max 32KB content) - - Call LLM (model from `WikiConfig.SynthesisModelID`) - - Generate/update wiki pages (summary, entities, concepts) - - Create cross-links between pages - - Update `WikiPage` with: - - Auto-generated content - - SourceRefs → Knowledge IDs - - OutLinks → Wiki links - -4. **Link Maintenance** - - Parse `[[wiki-link]]` syntax in content - - Update bidirectional links (InLinks/OutLinks) - - Rebuild index page with all pages - - Maintain link graph for visualization - -### 5.3 Wiki Ingest Payloads - -**Asynq Task Type:** `types.TypeWikiIngest` - -```go -type WikiIngestPayload struct { - TenantID uint64 - KnowledgeBaseID string - Language string // Optional language hint - LiteOps []WikiPendingOp // Fallback for Lite mode -} - -type WikiPendingOp struct { - Op string // "ingest" or "retract" - KnowledgeID string - Language string // For ingest - DocTitle string // For retract - DocSummary string - PageSlugs []string // For retract -} -``` - -### 5.4 Wiki Retraction (Document Deletion) - -**Payload:** `WikiRetractPayload` - -When a Knowledge document is deleted: -- Find all Wiki pages that reference it (SourceRefs) -- Update or archive affected pages -- Maintain referential integrity - -### 5.5 Redis Keys Used - -``` -wiki:pending:{kbID} → Redis List of pending WikiPendingOp (JSON) -wiki:active:{kbID} → Redis String "1" with 5 min TTL (lock) -``` - -In Lite mode (no Redis): operations stored in task payload `LiteOps` - ---- - -## 6. KNOWLEDGE BASE → AGENT CONNECTIONS - -### 6.1 Agent Configuration - -**File:** `internal/types/agent.go` - -```go -type AgentConfig struct { - // Knowledge access - KnowledgeBases []string // Accessible KB IDs - KnowledgeIDs []string // Specific document IDs - RetrieveKBOnlyWhenMentioned bool // Only search KB when user mentions @ - RetainRetrievalHistory bool // Keep wiki_read_page results across turns - - // Tool control - AllowedTools []string // Whitelist of tool names - MaxIterations int - Temperature float64 - - // System prompt - SystemPrompt string // Unified prompt template - UseCustomSystemPrompt bool - - // Web search - WebSearchEnabled bool - WebSearchMaxResults int - - // Multi-turn - MultiTurnEnabled bool - HistoryTurns int // How many turns to keep in context - - // Context budget - MaxContextTokens int // Default: 200k - - // Other configs... - MCPSelectionMode string - SkillsEnabled bool - // ... many more fields -} - -// Session-level override -type SessionAgentConfig struct { - AgentModeEnabled bool - WebSearchEnabled bool - KnowledgeBases []string - KnowledgeIDs []string -} -``` - -### 6.2 Knowledge Base Resolution - -When agent runs: -1. Load AgentConfig.KnowledgeBases (KB IDs) -2. Resolve full KnowledgeBase objects -3. For wiki-enabled KBs: - - Build search targets for wiki pages - - Agent can use `wiki_read_page`, `wiki_write_page` tools -4. For document KBs: - - Build search targets for chunks - - Agent can use `knowledge_search` tools - -### 6.3 Agent Tool: Wiki Tools - -**Files:** `internal/agent/tools/wiki_*.go` - -Available wiki tools: -- `wiki_read_page` - Retrieve wiki page by slug -- `wiki_write_page` - Create/update wiki page (synthesis, comparison) -- `wiki_rename_page` - Rename page slug -- `wiki_delete_page` - Archive page -- `wiki_replace_text` - Find/replace in page content -- `wiki_read_source_doc` - Get original Knowledge document -- `wiki_read_issue` - Check page issues -- `wiki_flag_issue` - Report problem with page -- `wiki_update_issue` - Resolve issue - -### 6.4 Agent Tool: Knowledge Tools - -**Files:** `internal/agent/tools/knowledge_*.go`, `internal/agent/tools/grep_chunks.go` - -- `knowledge_search` - Semantic + keyword search in KB -- `grep_chunks` - Regex search in chunks -- `list_knowledge_chunks` - List documents in KB -- `get_document_info` - Fetch document metadata - ---- - -## 7. KNOWLEDGE BASE SETTINGS PAGE ARCHITECTURE - -### 7.1 Frontend API Layer - -**File:** `frontend/src/api/knowledge-base/index.ts` - -Key endpoints for KB settings: - -```typescript -// Create KB with wiki config -createKnowledgeBase(data: { - name: string; - description?: string; - type?: 'document' | 'faq'; - chunking_config?: ChunkingConfig; - embedding_model_id?: string; - wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; - }; - vlm_config?: { enabled: boolean; model_id?: string }; - asr_config?: { enabled: boolean; model_id?: string }; - extract_config?: any; - faq_config?: FAQConfig; -}) - -// Update KB with config -updateKnowledgeBase(id: string, data: { - name: string; - description?: string; - config?: { - chunking_config?: ChunkingConfig; - image_processing_config?: ImageProcessingConfig; - faq_config?: FAQConfig; - wiki_config?: WikiConfig; - }; -}) -``` - -### 7.2 Backend Handler - -**File:** `internal/handler/knowledgebase.go` - -- `CreateKnowledgeBase` - POST /api/v1/knowledge-bases -- `UpdateKnowledgeBase` - PUT /api/v1/knowledge-bases/{id} -- Validates ExtractConfig, all sub-configs -- Calls `KnowledgeBaseService` for business logic - -### 7.3 Service Layer - -**File:** `internal/application/service/knowledgebase.go` - -```go -type knowledgeBaseService struct { - repo interfaces.KnowledgeBaseRepository - kgRepo interfaces.KnowledgeRepository - chunkRepo interfaces.ChunkRepository - shareRepo interfaces.KBShareRepository - modelService interfaces.ModelService - retrieveEngine interfaces.RetrieveEngineRegistry - // ... -} - -// CreateKnowledgeBase: -// - Generate UUID -// - Call EnsureDefaults() on KB -// - Call repo.CreateKnowledgeBase() -// - Return created KB - -// UpdateKnowledgeBase: -// - Fetch existing KB -// - Update fields -// - Validate config -// - Call repo.UpdateKnowledgeBase() -``` - -### 7.4 Wiki Settings UI Integration - -Frontend components receive WikiConfig as part of KnowledgeBase object: - -```typescript -interface KnowledgeBase { - id: string; - name: string; - type: 'document' | 'faq' | 'wiki'; - wiki_config?: { - enabled: boolean; - auto_ingest: boolean; - synthesis_model_id: string; - max_pages_per_ingest: number; - }; - // ... other fields -} -``` - -Settings page form sections: -1. **Basic Info** - name, description -2. **Document Processing** - chunking_config, embedding_model_id -3. **Advanced Features:** - - Image Processing (VLM) - - Speech Recognition (ASR) - - Knowledge Graph Extraction - - **Wiki** (if document type): - - Enable wiki - - Auto-ingest toggle - - Synthesis model selection - - Max pages per ingest limit - ---- - -## 8. DATABASE SCHEMA MAPPING - -### 8.1 Tables - -1. **knowledge_bases** (KnowledgeBase) - - Primary fields: id, name, type, tenant_id - - Configs (JSON): chunking_config, wiki_config, faq_config, extract_config, etc. - - Timestamps: created_at, updated_at, deleted_at - - Indicators: is_pinned, is_temporary, is_processing - -2. **knowledges** (Knowledge) - - FK: knowledge_base_id → knowledge_bases.id - - Parse status tracking: parse_status, summary_status - - File metadata: file_name, file_type, file_size, file_hash, file_path - - Metadata: metadata (JSON), last_faq_import_result (JSON) - -3. **chunks** (Chunk) - - FK: knowledge_id → knowledges.id - - Content and embeddings: content, embedding (vector) - - Metadata: metadata (JSON) - - Indexing: for vector and keyword retrieval - -4. **wiki_pages** (WikiPage) - - FK: knowledge_base_id → knowledge_bases.id - - Unique: (knowledge_base_id, slug) - - Content: content (text), summary, title - - Links: in_links (JSON array), out_links (JSON array) - - Versioning: version (auto-increment on content change) - -5. **wiki_page_issues** (WikiPageIssue) - - FK: knowledge_base_id, slug - - Issue tracking: issue_type, status, description - -### 8.2 Foreign Key Relationships - -``` -agents.agent_config.knowledge_bases[] → knowledge_bases.id -agents.session_agent_config.knowledge_bases[] → knowledge_bases.id - -knowledge_bases (wiki_config) ← metadata JSON - -knowledges.knowledge_base_id → knowledge_bases.id -chunks.knowledge_id → knowledges.id - -wiki_pages.knowledge_base_id → knowledge_bases.id -wiki_page_issues.knowledge_base_id → knowledge_bases.id -``` - ---- - -## 9. SERVICE LAYER INTERFACES - -### 9.1 Key Interfaces - -**File:** `internal/types/interfaces/knowledgebase.go` - -```go -type KnowledgeBaseService interface { - CreateKnowledgeBase(ctx, kb) (*KB, error) - GetKnowledgeBaseByID(ctx, id) (*KB, error) - UpdateKnowledgeBase(ctx, id, name, desc, config) (*KB, error) - ListKnowledgeBases(ctx) ([]*KB, error) - HybridSearch(ctx, id, params) (results, error) - // ... more methods -} - -type KnowledgeBaseRepository interface { - Create(ctx, kb) error - GetByID(ctx, id) (*KB, error) - Update(ctx, kb) error - List(ctx, tenantID) ([]*KB, error) - // ... more methods -} -``` - -**File:** `internal/types/interfaces/wiki_page.go` - -```go -type WikiPageService interface { - CreatePage(ctx, page) (*WikiPage, error) - UpdatePage(ctx, page) (*WikiPage, error) - GetPageBySlug(ctx, kbID, slug) (*WikiPage, error) - ListPages(ctx, req) (*WikiPageListResponse, error) - GetStats(ctx, kbID) (*WikiStats, error) - RebuildLinks(ctx, kbID) error - SearchPages(ctx, kbID, query) ([]*WikiPage, error) - CreateIssue(ctx, issue) (*WikiPageIssue, error) - // ... more methods -} - -type WikiPageRepository interface { - Create(ctx, page) error - Update(ctx, page) error - GetByID(ctx, id) (*WikiPage, error) - GetBySlug(ctx, kbID, slug) (*WikiPage, error) - List(ctx, req) ([]*WikiPage, int64, error) - ListAll(ctx, kbID) ([]*WikiPage, error) - // ... more methods -} -``` - ---- - -## 10. API ENDPOINTS - -### 10.1 Knowledge Base Endpoints - -``` -GET /api/v1/knowledge-bases - List KBs -POST /api/v1/knowledge-bases - Create KB -GET /api/v1/knowledge-bases/{id} - Get KB details -PUT /api/v1/knowledge-bases/{id} - Update KB (including wiki_config) -DELETE /api/v1/knowledge-bases/{id} - Delete KB -PUT /api/v1/knowledge-bases/{id}/pin - Pin/unpin KB -``` - -### 10.2 Wiki Endpoints - -``` -GET /api/v1/knowledgebase/{kb_id}/wiki/pages - List pages -POST /api/v1/knowledgebase/{kb_id}/wiki/pages - Create page -GET /api/v1/knowledgebase/{kb_id}/wiki/pages/*slug - Get page by slug -PUT /api/v1/knowledgebase/{kb_id}/wiki/pages/*slug - Update page -DELETE /api/v1/knowledgebase/{kb_id}/wiki/pages/*slug - Delete page -GET /api/v1/knowledgebase/{kb_id}/wiki/index - Get index page -GET /api/v1/knowledgebase/{kb_id}/wiki/log - Get log page -GET /api/v1/knowledgebase/{kb_id}/wiki/graph - Get link graph -GET /api/v1/knowledgebase/{kb_id}/wiki/stats - Get wiki stats -GET /api/v1/knowledgebase/{kb_id}/wiki/search - Search pages -POST /api/v1/knowledgebase/{kb_id}/wiki/rebuild-links - Rebuild links -GET /api/v1/knowledgebase/{kb_id}/wiki/lint - Lint pages -POST /api/v1/knowledgebase/{kb_id}/wiki/auto-fix - Auto-fix issues -GET /api/v1/knowledgebase/{kb_id}/wiki/issues - List issues -PUT /api/v1/knowledgebase/{kb_id}/wiki/issues/{id}/status - Update issue -``` - -### 10.3 Knowledge Endpoints - -``` -GET /api/v1/knowledge-bases/{kb_id}/knowledge - List knowledge -POST /api/v1/knowledge-bases/{kb_id}/knowledge/file - Upload file -POST /api/v1/knowledge-bases/{kb_id}/knowledge/url - Add from URL -POST /api/v1/knowledge-bases/{kb_id}/knowledge/manual - Create manual -GET /api/v1/knowledge/{id} - Get knowledge -PUT /api/v1/knowledge/manual/{id} - Update manual -POST /api/v1/knowledge/{id}/reparse - Reparse document -DELETE /api/v1/knowledge/{id} - Delete knowledge -GET /api/v1/chunks/{id}?page=X&page_size=Y - Get chunks -GET /api/v1/chunks/by-id/{chunk_id} - Get chunk by ID -POST /api/v1/knowledge-search - Semantic search -``` - ---- - -## 11. FLOW DIAGRAMS - -### 11.1 Document Ingestion → Wiki Generation - -``` -User uploads document - ↓ -POST /api/v1/knowledge-bases/{kb_id}/knowledge/file - ↓ -KnowledgeService.CreateKnowledge() - ├─→ Create Knowledge entity (ParseStatus=pending) - ├─→ Trigger async ingest task (chunks + embedding) - └─→ IF WikiConfig.AutoIngest: - └─→ Enqueue WikiIngest task (delayed 30s for debounce) - ↓ - Asynq Worker: ProcessWikiIngest() - ├─→ Acquire wiki:active:{kbID} lock - ├─→ Fetch pending from wiki:pending:{kbID} - ├─→ For each doc (up to MaxPagesPerIngest): - │ ├─→ Fetch chunks (max 32KB content) - │ ├─→ Call LLM (SynthesisModelID) - │ ├─→ Generate wiki pages: - │ │ ├─→ Summary page - │ │ ├─→ Entity pages - │ │ └─→ Concept pages - │ └─→ Update wiki_pages + links - ├─→ RebuildLinks: rebuild in/out links - ├─→ RebuildIndexPage - └─→ IF more pending: schedule follow-up task -``` - -### 11.2 Agent Interacting with KB + Wiki - -``` -User message in agent chat - ↓ -Agent receives accessible KnowledgeBases (from AgentConfig) - ↓ -Agent decides to search KB - ├─→ Tool: knowledge_search - │ └─→ HybridRetrievalEngine.Retrieve() - │ └─→ Returns chunks (vector + keyword match) - │ - └─→ Tool: wiki_read_page - └─→ WikiPageService.GetPageBySlug() - └─→ Returns wiki page content + links - -Agent can also: - ├─→ Tool: wiki_write_page (create synthesis/comparison) - │ └─→ WikiPageService.CreatePage() - │ - └─→ Tool: wiki_read_source_doc - └─→ Get original Knowledge document -``` - -### 11.3 KB Settings Update Flow - -``` -User opens KB Settings page - ↓ -GET /api/v1/knowledge-bases/{kb_id} - ↓ -Frontend receives KnowledgeBase with wiki_config - ↓ -User edits wiki_config: - ├─→ Toggle enabled - ├─→ Toggle auto_ingest - ├─→ Select synthesis_model_id - └─→ Set max_pages_per_ingest - ↓ -User clicks Save - ↓ -PUT /api/v1/knowledge-bases/{kb_id} - │ payload: - │ { - │ name: "...", - │ description: "...", - │ config: { - │ wiki_config: { - │ enabled: true, - │ auto_ingest: true, - │ synthesis_model_id: "model-123", - │ max_pages_per_ingest: 5 - │ } - │ } - │ } - ↓ -KnowledgeBaseHandler.UpdateKnowledgeBase() - ↓ -KnowledgeBaseService.UpdateKnowledgeBase() - ├─→ Fetch existing KB - ├─→ Merge config - ├─→ Call EnsureDefaults() - ├─→ Validate config - └─→ Repository.UpdateKnowledgeBase() - └─→ UPDATE knowledge_bases SET ... WHERE id = ? - ↓ - wiki_config column updated with new JSON -``` - ---- - -## 12. KEY FILE LOCATIONS REFERENCE - -### Backend (Go) - -| Component | File(s) | -|-----------|---------| -| KB Model | `internal/types/knowledgebase.go` | -| Knowledge Model | `internal/types/knowledge.go` | -| Wiki Page Model | `internal/types/wiki_page.go` | -| Agent Config | `internal/types/agent.go` | -| KB Service | `internal/application/service/knowledgebase.go` | -| Knowledge Service | `internal/application/service/knowledge.go` | -| Wiki Ingest Service | `internal/application/service/wiki_ingest.go`, `wiki_ingest_batch.go` | -| Wiki Page Service | `internal/application/service/wiki_page.go` | -| KB Handler | `internal/handler/knowledgebase.go` | -| Wiki Handler | `internal/handler/wiki_page.go` | -| KB Repository | `internal/application/repository/knowledgebase.go` | -| Wiki Repository | `internal/application/repository/wiki_page.go` | -| KB Interfaces | `internal/types/interfaces/knowledgebase.go` | -| Wiki Interfaces | `internal/types/interfaces/wiki_page.go` | -| Hybrid Indexer | `internal/application/service/retriever/keywords_vector_hybrid_indexer.go` | -| Wiki Tools | `internal/agent/tools/wiki_*.go` | -| Router | `internal/router/router.go` (RegisterWikiPageRoutes ~L839) | - -### Frontend (TypeScript/Vue) - -| Component | File | -|-----------|------| -| KB API | `frontend/src/api/knowledge-base/index.ts` | -| Wiki API | `frontend/src/api/wiki/index.ts` | -| Knowledge Store | `frontend/src/stores/knowledge.ts` | -| KB Hooks | `frontend/src/hooks/useKnowledgeBase.ts` | - ---- - -## 13. CONFIGURATION HIERARCHY - -``` -Tenant Level -├─→ Storage Engine Config (credentials) -├─→ Embedding Models -├─→ LLM Models -├─→ VLM Models -└─→ Agent Config (default) - -Knowledge Base Level -├─→ Type (document, faq) -├─→ Chunking Config -├─→ Embedding Model ID (override tenant) -├─→ Image Processing Config -├─→ VLM Config -├─→ ASR Config -├─→ Extract Config -├─→ FAQ Config (if type=faq) -├─→ Question Generation Config -└─→ Wiki Config (if enabled on document KB) - ├─→ Enabled (boolean) - ├─→ AutoIngest (boolean) - ├─→ SynthesisModelID (LLM for generation) - └─→ MaxPagesPerIngest (rate limit) - -Session Level -└─→ Session Agent Config - ├─→ Enabled (override) - ├─→ KnowledgeBases (override) - └─→ WebSearchEnabled (override) -``` - ---- - -## 14. CRITICAL INTEGRATION POINTS - -### 14.1 Wiki as Feature, Not Type - -- KB Type is "document" (documents can have wiki) -- Wiki is enabled via `WikiConfig.Enabled = true` -- Check with `kb.IsWikiEnabled()` method -- **Common Mistake:** Treating wiki as a separate KB type - -### 14.2 Multi-Index Pipeline - -Each Knowledge document creates two separate indices: -1. **Chunk Index** - for document retrieval - - Vector embeddings - - Keyword (BM25) - - Used by `knowledge_search` tool - -2. **Wiki Index** - for wiki retrieval - - Wiki pages stored in `wiki_pages` table - - Full-text search on wiki content - - Link graph stored in InLinks/OutLinks - - Used by `wiki_read_page` tool - -### 14.3 Agent Knowledge Resolution - -Agent receives KBIDs → Service resolves: -- KB type → document/faq/wiki -- For document KB: check WikiConfig -- Build search targets (chunks OR wiki pages) -- Populate SearchTargets used by tools - -### 14.4 Async Task Coordination - -- Document ingest triggers wiki ingest (asynq) -- Wiki ingest debounced 30s (batches rapid uploads) -- Redis lock prevents concurrent wiki batches -- Max 5 docs per batch to bound execution time -- Follow-up tasks scheduled automatically for remaining docs - ---- - -## 15. SUMMARY TABLE - -| Aspect | Details | -|--------|---------| -| **KB Types** | `document`, `faq`, `wiki` (NOT a type - wiki is feature on document) | -| **Wiki Enablement** | Via `WikiConfig` on document-type KB | -| **Indexing** | Dual pipeline: chunks (vector+keyword) + wiki pages (full-text) | -| **Wiki Page Types** | summary, entity, concept, index, log, synthesis, comparison | -| **Auto-Generation** | Via LLM when `WikiConfig.AutoIngest=true` + doc ingested | -| **LLM Model** | Specified in `WikiConfig.SynthesisModelID` | -| **Agent Access** | Via `AgentConfig.KnowledgeBases[]` → tools (knowledge_search, wiki_read_page) | -| **Link Tracking** | Bidirectional: InLinks + OutLinks on wiki pages | -| **Issue Tracking** | WikiPageIssue table for flagging problems | -| **Settings Storage** | `knowledge_bases.wiki_config` JSON column | -| **API Updates** | PUT `/api/v1/knowledge-bases/{id}` with config payload | -| **Async Queue** | Asynq with Redis backing (Lite mode in-memory) | -| **Rate Limiting** | `MaxPagesPerIngest` per batch | - ---- - -## CONCLUSION - -The WeKnora KB system is a sophisticated multi-modal architecture where: - -1. **Knowledge Bases** are the top-level container with configurable type (document/faq) -2. **Wiki Feature** is an optional add-on to document-type KBs (via WikiConfig) -3. **Documents** are ingested into a KB and processed into **Chunks** (indexed for vector/keyword search) -4. **Wiki Ingest** is an async, LLM-powered pipeline that generates and maintains wiki pages from documents -5. **Agents** access KBs through a unified interface, with tools for both document search and wiki page retrieval -6. **Settings** flow through the KB Settings page UI to backend, where WikiConfig is updated atomically with other KB configs - -The tight integration between knowledge bases, wiki pages, chunks, and agents creates a powerful knowledge management and retrieval system suitable for RAG applications, agent knowledge bases, and collaborative knowledge building. diff --git a/KB_WIKI_FILE_INDEX.md b/KB_WIKI_FILE_INDEX.md deleted file mode 100644 index bef38aac..00000000 --- a/KB_WIKI_FILE_INDEX.md +++ /dev/null @@ -1,415 +0,0 @@ -# Knowledge Base & Wiki System - File Index & Cross-Reference - -## COMPLETE FILE LISTING BY COMPONENT - -### 1. DATA MODELS (internal/types/) - -| File | Purpose | Key Types | -|------|---------|-----------| -| `knowledgebase.go` | KB data model | `KnowledgeBase`, `WikiConfig`, `ChunkingConfig`, `VLMConfig`, `ASRConfig`, `ExtractConfig`, `FAQConfig` | -| `knowledge.go` | Document/knowledge model | `Knowledge`, `ManualKnowledgeMetadata`, `Knowledge.Type` (manual, faq) | -| `wiki_page.go` | Wiki page model | `WikiPage`, `WikiPageIssue`, `WikiConfig`, `WikiStats`, `WikiGraphData` | -| `agent.go` | Agent configuration | `AgentConfig`, `SessionAgentConfig` (includes KnowledgeBases) | -| `chunk.go` | Chunk model | Indexed content units (not detailed in search but referenced) | -| `message.go` | Chat messages | Not detailed - used by sessions | -| `tag.go` | Tags/categories | For knowledge organization | - -### 2. INTERFACES (internal/types/interfaces/) - -| File | Purpose | Contracts | -|------|---------|-----------| -| `knowledgebase.go` | KB service interface | `KnowledgeBaseService`, `KnowledgeBaseRepository` | -| `knowledge.go` | Knowledge service interface | `KnowledgeService`, `KnowledgeRepository` | -| `wiki_page.go` | Wiki service interface | `WikiPageService`, `WikiPageRepository` | -| `agent.go` | Agent tool interface | Generic tool registration | -| `chunk.go` | Chunk access interface | `ChunkRepository`, `ChunkService` | - -### 3. SERVICES (internal/application/service/) - -| File | Purpose | Methods | -|------|---------|---------| -| `knowledgebase.go` | KB business logic | Create, Update, Get, List, HybridSearch | -| `knowledge.go` | Doc ingest pipeline | CreateKnowledge, UpdateKnowledge, Delete, Search | -| `wiki_ingest.go` | Wiki LLM generation | WikiIngestService, ProcessWikiIngest, ScheduleFollowUp | -| `wiki_ingest_batch.go` | Wiki batch processing | Batch LLM calls, link rebuilding | -| `wiki_page.go` | Wiki CRUD operations | CreatePage, UpdatePage, GetPageBySlug, ListPages, RebuildLinks | -| `wiki_linkify.go` | Wiki link parsing | Parse [[wiki-links]] syntax | -| `wiki_lint.go` | Wiki quality checks | Validate, find broken links, orphaned pages | -| `knowledge_post_process.go` | Post-processing docs | Summary generation, extraction | -| `chat_pipeline/search.go` | Retrieval in chat | Knowledge search during chat | -| `chat_pipeline/wiki_boost.go` | Wiki integration in chat | Boost wiki results in chat context | -| `chunk.go` | Chunk service | Chunk CRUD, retrieval | -| `retriever/keywords_vector_hybrid_indexer.go` | Hybrid search engine | Index, BatchIndex, Retrieve | - -### 4. REPOSITORIES (internal/application/repository/) - -| File | Purpose | Storage | -|------|---------|---------| -| `knowledgebase.go` | KB persistence | GORM: knowledge_bases table | -| `knowledge.go` | Knowledge persistence | GORM: knowledges table | -| `wiki_page.go` | Wiki persistence | GORM: wiki_pages, wiki_page_issues | -| `chunk.go` | Chunk persistence | GORM: chunks table | -| `chunk_sqlite_test.go` | SQLite chunk backend | For testing | -| `retriever/weaviate/repository.go` | Weaviate backend | Vector search | -| `retriever/elasticsearch/v7/repository.go` | Elasticsearch v7 | Vector + keyword | -| `retriever/elasticsearch/v8/repository.go` | Elasticsearch v8 | Vector + keyword | -| `retriever/qdrant/repository.go` | Qdrant backend | Vector search | -| `retriever/milvus/repository.go` | Milvus backend | Vector search | -| `retriever/postgres/repository.go` | PostgreSQL backend | Vector search with pgvector | -| `retriever/sqlite/repository.go` | SQLite backend | Local vector search | -| `tag.go` | Tag persistence | GORM: tags table | - -### 5. HTTP HANDLERS (internal/handler/) - -| File | Purpose | Endpoints | -|------|---------|-----------| -| `knowledgebase.go` | KB HTTP API | POST/PUT/GET/DELETE /api/v1/knowledge-bases | -| `wiki_page.go` | Wiki HTTP API | GET/POST/PUT/DELETE /api/v1/knowledgebase/{id}/wiki/* | -| `knowledge.go` | Knowledge HTTP API | File upload, URL add, manual create | -| `chunk.go` | Chunk HTTP API | Chunk retrieval, preview | -| `session/qa.go` | Session chat QA | Knowledge search in chat context | - -### 6. ROUTING (internal/router/) - -| File | Purpose | Route Registration | -|------|---------|-----------------| -| `router.go` | Main router | RegisterWikiPageRoutes (~line 839) | -| `task.go` | Task routing | Async task registration | - -### 7. AGENT TOOLS (internal/agent/tools/) - -| File | Purpose | Tool Name | -|------|---------|-----------| -| `wiki_write_page.go` | Agent creates page | `wiki_write_page` | -| `wiki_read_source_doc.go` | Agent reads original doc | `wiki_read_source_doc` | -| `wiki_tools.go` | Tool registration | WikiToolRegistry | -| `wiki_delete_page.go` | Agent deletes page | `wiki_delete_page` | -| `wiki_replace_text.go` | Agent edits page | `wiki_replace_text` | -| `wiki_rename_page.go` | Agent renames page | `wiki_rename_page` | -| `wiki_update_issue.go` | Agent resolves issue | `wiki_update_issue` | -| `wiki_read_issue.go` | Agent checks issue | `wiki_read_issue` | -| `wiki_flag_issue.go` | Agent flags problem | `wiki_flag_issue` | -| `knowledge_search.go` | Agent searches KB | `knowledge_search` | -| `grep_chunks.go` | Agent regex search | `grep_chunks` | -| `list_knowledge_chunks.go` | Agent lists docs | `list_knowledge_chunks` | -| `get_document_info.go` | Agent gets doc info | `get_document_info` | -| `web_search.go` | Agent web search | `web_search` | -| `definitions.go` | Tool definitions | Tool registry | - -### 8. AGENT CONFIG (internal/agent/) - -| File | Purpose | Content | -|------|---------|---------| -| `prompts_wiki.go` | Wiki-specific prompts | Agent instructions for wiki tools | -| `prompts.go` | General prompts | System prompt templates | -| `engine.go` | Agent loop | ReAct execution engine | -| `observe.go` | Agent observation | Tool result interpretation | - -### 9. ASYNC TASKS (internal/types/ & services) - -| Task Type | File | Handler | Payload | -|-----------|------|---------|---------| -| `TypeWikiIngest` | wiki_ingest.go | ProcessWikiIngest | WikiIngestPayload | -| (Knowledge ingest) | knowledge.go | Various | KnowledgePayload | - -### 10. FRONTEND (frontend/src/) - -| File | Purpose | Exports | -|------|---------|---------| -| `api/knowledge-base/index.ts` | KB API client | createKnowledgeBase, updateKnowledgeBase, getKnowledgeBaseById, etc. | -| `api/wiki/index.ts` | Wiki API client | listWikiPages, getWikiPage, updateWikiPage, etc. | -| `stores/knowledge.ts` | State management | Knowledge store (Pinia) | -| `stores/settings.ts` | Settings store | App settings | -| `hooks/useKnowledgeBase.ts` | KB hook | KB operations hook | -| `hooks/useKnowledgeBaseCreationNavigation.ts` | KB creation | Navigation after KB creation | - ---- - -## KEY DATA FLOWS BY FILE - -### Document Ingestion Flow -``` -1. frontend/src/api/knowledge-base/index.ts - → uploadKnowledgeFile(kbId, file) - -2. internal/handler/knowledge.go - → KnowledgeHandler.CreateKnowledge() - -3. internal/application/service/knowledge.go - → KnowledgeService.CreateKnowledge() - → Creates Knowledge entity (ParseStatus=pending) - → Enqueues ingest task - -4. Async task processed: - → Chunks created (chunks table) - → Embeddings indexed (vector DB: Weaviate, Elasticsearch, etc.) - → IF WikiConfig.AutoIngest: - → internal/application/service/wiki_ingest.go - → Enqueue WikiIngest task (30s delay) - -5. Wiki ingest task: - → internal/application/service/wiki_ingest_batch.go - → ProcessWikiIngest() - → LLM generates pages - → internal/application/service/wiki_page.go - → CreatePage() for each generated wiki page - → internal/application/repository/wiki_page.go - → Save to wiki_pages table - -6. Link maintenance: - → internal/application/service/wiki_linkify.go - → Parse [[wiki-links]] - → internal/application/service/wiki_page.go - → RebuildLinks() updates InLinks/OutLinks -``` - -### Settings Update Flow -``` -1. frontend/src/api/knowledge-base/index.ts - → updateKnowledgeBase(id, config) - -2. internal/handler/knowledgebase.go - → KnowledgeBaseHandler.UpdateKnowledgeBase() - → Validates config - -3. internal/application/service/knowledgebase.go - → KnowledgeBaseService.UpdateKnowledgeBase() - → Merges config (including wiki_config) - → Calls EnsureDefaults() - -4. internal/application/repository/knowledgebase.go - → KnowledgeBaseRepository.UpdateKnowledgeBase() - → UPDATE knowledge_bases SET wiki_config = JSON_VALUE -``` - -### Agent Using Wiki -``` -1. Session starts: - → internal/handler/session/handler.go - → Load session with agent_config - -2. Agent receives query: - → internal/types/agent.go - → AgentConfig.KnowledgeBases → resolved to KB objects - → For each wiki-enabled KB: - → Add wiki tools to available tools - -3. Agent calls wiki_read_page: - → internal/agent/tools/wiki_tools.go - → Call WikiPageService.GetPageBySlug() - → internal/application/service/wiki_page.go - → internal/application/repository/wiki_page.go - → SELECT FROM wiki_pages WHERE knowledge_base_id = ? AND slug = ? - -4. Agent calls wiki_write_page: - → internal/agent/tools/wiki_write_page.go - → Call WikiPageService.CreatePage() - → Same flow as #5-6 in document ingestion -``` - ---- - -## DIRECT FILE RELATIONSHIPS - -### KnowledgeBase ↔ WikiConfig -``` -internal/types/knowledgebase.go::KnowledgeBase - └─ WikiConfig *types.WikiConfig - └─ Stored in knowledge_bases.wiki_config (JSON) - -Update path: - PUT handler (knowledgebase.go) - → Service (knowledgebase.go) - → Repository (knowledgebase.go) - → Database: UPDATE knowledge_bases SET wiki_config = ? -``` - -### Knowledge ↔ Chunks -``` -internal/types/knowledge.go::Knowledge - └─ FK: knowledge_base_id - -internal/types/chunk.go::Chunk - └─ FK: knowledge_id → knowledge.id - └─ Indexed in multiple backends: - ├─ elasticsearch/v7/repository.go - ├─ elasticsearch/v8/repository.go - ├─ weaviate/repository.go - ├─ qdrant/repository.go - ├─ milvus/repository.go - ├─ postgres/repository.go - └─ sqlite/repository.go -``` - -### WikiPage ↔ KnowledgeBase -``` -internal/types/wiki_page.go::WikiPage - └─ FK: knowledge_base_id - └─ Unique constraint: (knowledge_base_id, slug) - └─ SourceRefs: knowledge IDs that contributed -``` - -### Agent ↔ KnowledgeBase -``` -internal/types/agent.go::AgentConfig - └─ KnowledgeBases []string (KB IDs) - └─ Resolved at runtime to KnowledgeBase objects - └─ Tool selection based on KB.IsWikiEnabled() -``` - ---- - -## SERVICE DEPENDENCY INJECTION - -### Container (internal/container/container.go) -``` -Provides instances of all services: - - KnowledgeBaseService - - KnowledgeService - - WikiPageService - - WikiLintService - - Retrieval engines - - Repositories - - HTTP handlers -``` - -### Service Constructor Dependencies - -**KnowledgeBaseService:** -```go -repo KnowledgeBaseRepository -kgRepo KnowledgeRepository -chunkRepo ChunkRepository -shareRepo KBShareRepository -kbShareService KBShareService -modelService ModelService -retrieveEngine RetrieveEngineRegistry -tenantRepo TenantRepository -fileSvc FileService -graphEngine RetrieveGraphRepository -asynqClient TaskEnqueuer -``` - -**WikiPageService:** -```go -repo WikiPageRepository -chunkRepo ChunkRepository -kbService KnowledgeBaseService -redisClient *redis.Client -``` - -**WikiIngestService:** -```go -wikiService WikiPageService -kbService KnowledgeBaseService -knowledgeSvc KnowledgeService -chunkRepo ChunkRepository -modelService ModelService -task TaskEnqueuer -redisClient *redis.Client -``` - ---- - -## CONFIGURATION FILES & ENVIRONMENT - -### Backend Config (internal/config/config.go) -``` -Reads from: - - .env file - - Environment variables - - YAML config files - -Key config sections: - - Database (PostgreSQL, MySQL, SQLite) - - Redis (for async tasks) - - Retrieval engines (Elasticsearch, Weaviate, etc.) - - LLM models (OpenAI, Claude, local, etc.) - - Storage (local, S3, Minio, etc.) -``` - -### Environment Variables (.env) -``` -# Database -DATABASE_URL=... - -# Redis -REDIS_URL=... - -# LLM -LLM_API_KEY=... -LLM_MODEL_ID=... - -# Vector DB -WEAVIATE_URL=... -ELASTICSEARCH_URL=... - -# Storage -STORAGE_PROVIDER=... -``` - ---- - -## BUILD & DEPLOYMENT - -### Binary -- `server` - Main Go binary (compiled from cmd/desktop/main.go) -- `WeKnora` - Desktop app version - -### Docker -- `Dockerfile` - Backend container -- `frontend/Dockerfile` - Frontend container -- `docker-compose.yml` - Full stack - -### Kubernetes/Helm -- `helm/` directory - Helm charts - ---- - -## SUMMARY TABLE - -| Component | Count | Key Files | -|-----------|-------|-----------| -| Models | 7+ | types/*.go | -| Services | 10+ | service/*.go | -| Repositories | 10+ | repository/*.go | -| Handlers | 5+ | handler/*.go | -| Agent Tools | 13+ | tools/wiki_*.go, knowledge_*.go | -| Retrieval Backends | 6 | retriever/*/repository.go | -| Frontend APIs | 2 | api/knowledge-base/, api/wiki/ | -| Interfaces | 5+ | types/interfaces/*.go | - ---- - -## QUICK FILE REFERENCE BY QUESTION - -**Q: Where is WikiConfig defined?** -A: `internal/types/knowledgebase.go` (line ~94-103) - -**Q: Where is wiki auto-ingest logic?** -A: `internal/application/service/wiki_ingest.go` and `wiki_ingest_batch.go` - -**Q: How are KB settings persisted?** -A: `internal/handler/knowledgebase.go` → `service/knowledgebase.go` → `repository/knowledgebase.go` - -**Q: Where do agents access KBs?** -A: `internal/types/agent.go` (AgentConfig.KnowledgeBases) → resolved in service layer - -**Q: Where is wiki page model?** -A: `internal/types/wiki_page.go` (WikiPage struct, ~line 43-84) - -**Q: How are wiki links maintained?** -A: `internal/application/service/wiki_linkify.go` and `wiki_page.go`::RebuildLinks - -**Q: Where is hybrid retrieval implemented?** -A: `internal/application/service/retriever/keywords_vector_hybrid_indexer.go` - -**Q: How does chunk embedding happen?** -A: Multiple backends in `retriever/*/repository.go` (Elasticsearch, Weaviate, etc.) - -**Q: Frontend API for KB updates?** -A: `frontend/src/api/knowledge-base/index.ts`::updateKnowledgeBase() - -**Q: Where is async task handling?** -A: Asynq queue, triggered in service layer, workers in `wiki_ingest.go` - diff --git a/KB_WIKI_QUICK_REFERENCE.md b/KB_WIKI_QUICK_REFERENCE.md deleted file mode 100644 index 9c65f45e..00000000 --- a/KB_WIKI_QUICK_REFERENCE.md +++ /dev/null @@ -1,426 +0,0 @@ -# Knowledge Base & Wiki Feature - Quick Reference - -## CRITICAL CONCEPTS - -### 1. Wiki is NOT a KB Type -```go -// WRONG: Thinking wiki is a separate KB type -type == "wiki" - -// CORRECT: Wiki is a feature enabled on document KBs -type == "document" && WikiConfig.Enabled == true -``` - -### 2. Three KB Types -| Type | Purpose | Can Have Wiki? | -|------|---------|----------------| -| `document` | Standard docs, PDFs, URLs, manual markdown | ✅ YES | -| `faq` | FAQ pairs (Q&A) | ❌ NO | -| `wiki` | ❌ DOES NOT EXIST - use document + WikiConfig | | - -### 3. WikiConfig Structure -```go -WikiConfig struct { - Enabled bool // Feature toggle - AutoIngest bool // Generate wiki pages on doc ingestion - SynthesisModelID string // LLM model for page generation - MaxPagesPerIngest int // Rate limit (pages per batch) -} -``` - ---- - -## DATA FLOW - -### Document Ingestion with Wiki -``` -1. User uploads PDF → Knowledge entity created -2. ParseStatus: pending → processing → completed -3. Chunks generated (vector + keyword indexed) -4. IF WikiConfig.AutoIngest: - 5a. Wiki ingest task queued (30s delay for debounce) - 5b. LLM generates wiki pages (summary, entities, concepts) - 5c. Wiki pages linked together ([[slug]] syntax) -``` - -### Wiki Page Types (Auto-generated) -- `summary` - Document overview -- `entity` - Person, organization, place extracted -- `concept` - Topic or idea from document -- `index` - Table of contents (auto-rebuilt) -- `log` - Operation history (auto-maintained) - -**Agent-created types:** -- `synthesis` - Agent-generated cross-document analysis -- `comparison` - Agent-generated entity/concept comparison - ---- - -## KEY FILES - -### Models -``` -internal/types/knowledgebase.go ← KnowledgeBase + WikiConfig -internal/types/knowledge.go ← Knowledge (document) -internal/types/wiki_page.go ← WikiPage + WikiPageIssue -internal/types/agent.go ← AgentConfig.KnowledgeBases -``` - -### Services -``` -internal/application/service/knowledgebase.go ← KB CRUD -internal/application/service/knowledge.go ← Doc ingest -internal/application/service/wiki_ingest.go ← Wiki generation -internal/application/service/wiki_page.go ← Wiki CRUD -``` - -### Handlers/API -``` -internal/handler/knowledgebase.go ← PUT /api/v1/knowledge-bases/{id} -internal/handler/wiki_page.go ← Wiki endpoints -``` - -### Frontend -``` -frontend/src/api/knowledge-base/index.ts ← KB API (includes wiki_config) -frontend/src/api/wiki/index.ts ← Wiki API -``` - ---- - -## SETTINGS PAGE UPDATE FLOW - -```json -// Frontend sends to PUT /api/v1/knowledge-bases/{id} -{ - "name": "My KB", - "description": "...", - "config": { - "chunking_config": { ... }, - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "model-id-123", - "max_pages_per_ingest": 5 - } - } -} - -// Stored in database -knowledge_bases.wiki_config = JSON serialized WikiConfig - -// Retrieved on GET /api/v1/knowledge-bases/{id} -{ - "id": "...", - "name": "My KB", - "wiki_config": { ... } // ← Embedded in KB object -} -``` - ---- - -## INDEXING PIPELINE - -### Two Separate Indices - -1. **Chunk Index** (from Documents) - - Created: When Knowledge document ingested - - Storage: chunks table + vector DB (Elasticsearch, Weaviate, etc.) - - Indexed: Vector embeddings + BM25 keywords - - Search Tool: `knowledge_search` - -2. **Wiki Index** (from Wiki Pages) - - Created: When auto-ingest generates pages - - Storage: wiki_pages table - - Indexed: Full-text on content, link graph in InLinks/OutLinks - - Search Tool: `wiki_read_page`, `wiki_search` - -### Hybrid Retrieval Engine -```go -internal/application/service/retriever/keywords_vector_hybrid_indexer.go - -Supports multiple backends: -- Elasticsearch (v7, v8) -- Weaviate -- Qdrant -- Milvus -- PostgreSQL -- SQLite (local) -``` - ---- - -## AGENT INTEGRATION - -### Agent Access to KB - -```go -type AgentConfig struct { - KnowledgeBases []string // KB IDs agent can access - KnowledgeIDs []string // Specific doc IDs agent can access -} - -// Agent uses these tools: -- knowledge_search → Search chunks in documents -- wiki_read_page → Read wiki page by slug -- wiki_write_page → Create/update wiki page -- wiki_replace_text → Edit page content -- wiki_delete_page → Archive page -- wiki_read_source_doc → Get original document -- wiki_flag_issue → Report problem -- wiki_update_issue → Mark resolved -``` - -### Check if Agent Can Use Wiki - -```go -kb, _ := kbService.GetKnowledgeBaseByID(ctx, kbID) -if kb.IsWikiEnabled() { - // Agent can use wiki tools -} -``` - ---- - -## ASYNC TASK QUEUE - -### Wiki Ingest Pipeline -``` -Trigger: Document added to KB with WikiConfig.AutoIngest=true - -Task Type: types.TypeWikiIngest -Payload: { - TenantID: uint64, - KnowledgeBaseID: string, - Language: string, - LiteOps: []WikiPendingOp // for Lite mode -} - -Queue: "low" priority -Timeout: 60 minutes -MaxRetry: 10 -Delay: 5 seconds (after initial 30s debounce) - -Redis Keys: -- wiki:pending:{kbID} → List of pending ops -- wiki:active:{kbID} → Lock (5 min TTL) to prevent concurrent batches - -Rate Limit: Max 5 docs per batch (configurable via MaxPagesPerIngest) -``` - -### Flow -``` -1. Document ingested -2. Task enqueued (30s delay to debounce rapid uploads) -3. Asynq picks up task -4. Try to acquire wiki:active:{kbID} lock - - If locked: retry (asynq will retry automatically) - - If acquired: proceed -5. Process up to MaxPagesPerIngest docs from wiki:pending:{kbID} -6. Generate wiki pages via LLM -7. Update InLinks/OutLinks -8. If more pending: schedule follow-up task -``` - ---- - -## COMMON OPERATIONS - -### Create KB with Wiki -```typescript -// Frontend API call -createKnowledgeBase({ - name: "My Knowledge Base", - type: "document", - wiki_config: { - enabled: true, - auto_ingest: true, - synthesis_model_id: "gpt-4", - max_pages_per_ingest: 5 - } -}) -``` - -### Update Wiki Settings -```typescript -// Frontend API call -updateKnowledgeBase("kb-id-123", { - name: "Updated KB", - config: { - wiki_config: { - enabled: true, - auto_ingest: false, // Disable auto-ingest - synthesis_model_id: "gpt-3.5", - max_pages_per_ingest: 10 - } - } -}) -``` - -### Check if KB has Wiki -```go -kb, _ := kbService.GetKnowledgeBaseByID(ctx, kbID) -if kb.IsWikiEnabled() { - // Wiki is enabled for this KB - fmt.Printf("Wiki config: %+v\n", kb.WikiConfig) -} -``` - -### List Wiki Pages -```go -pages, err := wikiService.ListPages(ctx, &WikiPageListRequest{ - KnowledgeBaseID: kbID, - PageType: "entity", - Page: 1, - PageSize: 20, -}) -``` - -### Search Wiki -```go -results, err := wikiService.SearchPages(ctx, kbID, "query text", 10) -``` - -### Manually Add Wiki Page (Agent Tool) -``` -wiki_write_page( - knowledge_base_id: "kb-id", - slug: "concept/rag-systems", - title: "RAG Systems", - content: "# RAG Systems\n...", - page_type: "synthesis" -) -``` - ---- - -## TROUBLESHOOTING - -### Problem: Wiki pages not generating -**Check:** -1. WikiConfig.Enabled = true -2. WikiConfig.AutoIngest = true -3. SynthesisModelID is valid (test model availability) -4. Asynq worker running (check logs for wiki ingest tasks) -5. Redis connectivity (if not Lite mode) - -### Problem: Wiki links broken -**Solution:** -1. Call `RebuildLinks()` endpoint -2. This re-parses all pages and rebuilds InLinks/OutLinks - -### Problem: Stale wiki content -**Solution:** -1. Call wiki ingest for specific KB -2. Or delete KB and re-add with documents - -### Problem: Wiki not appearing in agent tools -**Check:** -1. Agent has KB in config: `AgentConfig.KnowledgeBases` -2. KB has wiki enabled: `kb.IsWikiEnabled()` -3. Agent has `wiki_read_page` in allowed tools - ---- - -## SETTINGS PAGE FORM STRUCTURE - -``` -Knowledge Base Settings -├─ Basic Info -│ ├─ Name (text) -│ ├─ Description (textarea) -│ └─ Type (select: document, faq) [read-only after creation] -│ -├─ Document Processing -│ ├─ Chunking Config -│ │ ├─ Chunk Size (number) -│ │ ├─ Chunk Overlap (number) -│ │ └─ Enable Parent-Child Chunking (toggle) -│ └─ Embedding Model (select) -│ -├─ Advanced Features -│ ├─ Image Processing / VLM (toggle + model select) -│ ├─ Speech Recognition / ASR (toggle + model select) -│ ├─ Knowledge Graph Extraction (toggle + config) -│ │ -│ └─ 📌 WIKI SETTINGS (if type == "document") -│ ├─ Enable Wiki (toggle) -│ │ ├─ Auto-Ingest (toggle) [only if enabled] -│ │ ├─ Synthesis Model (select) [only if enabled] -│ │ └─ Max Pages Per Ingest (number) [only if enabled] -│ └─ [Link to Wiki management page] -│ -└─ FAQ Settings (if type == "faq") - ├─ Index Mode (select) - └─ Question Index Mode (select) -``` - ---- - -## REDIS KEYS (Advanced) - -``` -# Wiki pending operations queue (List) -wiki:pending:{kbID} - → JSON serialized WikiPendingOp[] - → TTL: 24 hours (auto-cleanup) - -# Wiki active batch lock (String) -wiki:active:{kbID} - → Value: "1" - → TTL: 5 minutes (auto-extend during processing) - -# Note: In Lite mode (no Redis), operations stored in task payload -``` - ---- - -## INTERFACES TO IMPLEMENT - -If adding new features or backends: - -```go -// KB Service -interface KnowledgeBaseService { - CreateKnowledgeBase(ctx, kb) (*KB, error) - UpdateKnowledgeBase(ctx, id, name, desc, config) (*KB, error) - GetKnowledgeBaseByID(ctx, id) (*KB, error) - ListKnowledgeBases(ctx) ([]*KB, error) -} - -// Wiki Service -interface WikiPageService { - CreatePage(ctx, page) (*WikiPage, error) - UpdatePage(ctx, page) (*WikiPage, error) - GetPageBySlug(ctx, kbID, slug) (*WikiPage, error) - ListPages(ctx, req) (*WikiPageListResponse, error) - RebuildLinks(ctx, kbID) error -} - -// Wiki Repository -interface WikiPageRepository { - Create(ctx, page) error - Update(ctx, page) error - GetBySlug(ctx, kbID, slug) (*WikiPage, error) - ListAll(ctx, kbID) ([]*WikiPage, error) -} -``` - ---- - -## SUMMARY - -| Item | Value | -|------|-------| -| **Total KB Types** | 3 (document, faq, wiki) | -| **Wiki Type Status** | Feature on document KB, not separate type | -| **Enable Wiki** | WikiConfig.Enabled = true | -| **Auto-Gen Pages** | WikiConfig.AutoIngest = true + LLM model | -| **Page Types** | 7 (summary, entity, concept, index, log, synthesis, comparison) | -| **Indices** | 2 (chunks + wiki pages) | -| **Search Tools** | knowledge_search (chunks), wiki_read_page (pages) | -| **Settings Update** | PUT /api/v1/knowledge-bases/{id} | -| **Async Task** | TypeWikiIngest via Asynq | -| **Rate Limit** | MaxPagesPerIngest per batch | -| **Storage Config** | KB → WikiConfig JSON → database | - diff --git a/KNOWLEDGE_FLOW_DETAILED.md b/KNOWLEDGE_FLOW_DETAILED.md deleted file mode 100644 index ad89e1ef..00000000 --- a/KNOWLEDGE_FLOW_DETAILED.md +++ /dev/null @@ -1,403 +0,0 @@ -# Knowledge Base Processing Flow - Detailed with Line Numbers - -## Complete Document Ingestion Flow - -``` -┌──────────────────────────────────────────────────────────────────────────────┐ -│ PHASE 1: DOCUMENT UPLOAD & CONVERSION │ -└──────────────────────────────────────────────────────────────────────────────┘ - -File: internal/application/service/knowledge.go -Function: ProcessDocument(ctx, *asynq.Task) error -Lines: 7732-8108+ - -STEP 1: Parse Task Payload (7733-7737) - ├─ Unmarshal task.Payload() → types.DocumentProcessPayload - ├─ Extract: KnowledgeID, KnowledgeBaseID, FilePath, FileURL, FileType - └─ Log context setup - -STEP 2: Idempotency Checks (7761-7801) - ├─ Line 7762: Get Knowledge by ID - │ └─ knowledgeService.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID) - ├─ Line 7773: Check if already deleted - │ └─ if knowledge.ParseStatus == types.ParseStatusDeleting → return nil - ├─ Line 7779: Check if already completed - │ └─ if knowledge.ParseStatus == types.ParseStatusCompleted → return nil - └─ Line 7814: Update status to "processing" - └─ knowledge.ParseStatus = "processing" - -STEP 3: Fetch Knowledge Base Config (7803-7812) - ├─ Line 7804: Get KB by ID - │ └─ knowledgeService.kbService.GetKnowledgeBaseByID(ctx, kbID) - ├─ Validate: EmbeddingModelID must be configured - └─ Store KB config in context - -STEP 4: Validate Multimodal Config (7821-7841) - ├─ Line 7822: Check if image file without multimodal enabled - │ └─ IsImageType(payload.FileType) && !payload.EnableMultimodel - ├─ Line 7833: Check if audio file without ASR enabled - │ └─ IsAudioType(payload.FileType) && !kb.ASRConfig.IsASREnabled() - └─ Line 7844: Reject video files (not supported) - └─ IsVideoType(payload.FileType) → fail - -STEP 5: Handle File Input (7858-7931) - ├─ If FileURL provided (7858-7921): - │ ├─ Line 7860: Validate URL for SSRF protection - │ │ └─ secutils.ValidateURLForSSRF(payload.FileURL) - │ ├─ Line 7871: Download file from URL - │ │ └─ downloadFileFromURL(ctx, url, &fileName, &fileType) - │ ├─ Line 7900: Save downloaded file - │ │ └─ fileSvc.SaveBytes(ctx, contentBytes, tenantID, fileName, true) - │ └─ Line 7915: Delegate to convert() - │ - ├─ Else if URL string provided (7922-7931): - │ └─ Call convert() directly - │ - └─ Call convert(ctx, payload, kb, knowledge, isLastRetry) - └─ Returns: types.ReadResult + error - -STEP 6: Parse Document to Chunks (after convert()) - ├─ convertResult contains: text chunks, images, OCR, etc. - ├─ Validate conversion success - └─ Proceed to chunk processing - - -┌──────────────────────────────────────────────────────────────────────────────┐ -│ PHASE 2: CHUNK CREATION & INDEXING │ -└──────────────────────────────────────────────────────────────────────────────┘ - -File: internal/application/service/knowledge.go -Function: processChunks(ctx, kb, knowledge, chunks, opts) -Lines: 1681-2074 - -STEP 1: Setup (1681-1714) - ├─ Line 1691: Create span for tracing - └─ Line 1708: Get embedding model - └─ embeddingModel = modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID) - -STEP 2: Idempotency Cleanup (1716-1744) - ├─ Line 1720: Delete old chunks - │ └─ chunkService.DeleteChunksByKnowledgeID(ctx, knowledge.ID) - ├─ Line 1729: Delete old index data - │ └─ retrieveEngine.DeleteByKnowledgeIDList(ctx, [knowledgeID], ...) - └─ Line 1739: Delete old graph data - └─ graphEngine.DelGraph(ctx, [namespace]) - -STEP 3: Setup Parent-Child Chunking (if enabled) (1810-1876) - ├─ Check: options.ParentChunks (1811) - ├─ For each parent chunk (1815-1830): - │ └─ Create types.Chunk with ChunkType = types.ChunkTypeParentText - │ └─ Parent chunks NOT set up for indexing - │ - ├─ For each text chunk (1849-1877): - │ ├─ Create types.Chunk with ChunkType = types.ChunkTypeText - │ └─ Wire ParentChunkID if parent-child mode enabled - │ └─ textChunk.ParentChunkID = parentDBChunks[...].ID - │ - └─ Result: insertChunks array contains parent + child chunks - -STEP 4: Create Index Information (1908-1928) - ├─ Line 1913: Get title prefix for semantic alignment - │ └─ titlePrefix = knowledge.Title + "\n" - │ - ├─ For each TEXT chunk (1917-1928): - │ ├─ indexContent = titlePrefix + chunk.Content - │ └─ Create IndexInfo: - │ ├─ Content: titlePrefix + chunk text - │ ├─ SourceID: chunk.ID - │ ├─ ChunkID: chunk.ID - │ ├─ KnowledgeID: knowledge.ID - │ └─ IsEnabled: true - │ - └─ Result: indexInfoList (for indexing ONLY child/text chunks) - -STEP 5: Storage Quota Check (1932-1955) - ├─ Line 1934: Estimate storage size - │ └─ totalStorageSize = retrieveEngine.EstimateStorageSize(...) - │ - └─ Line 1947: Check tenant quota - └─ if tenantInfo.StorageUsed + totalStorageSize > quota → fail - -STEP 6: Save Chunks to Database (1965-1973) - ├─ Line 1966: Insert all chunks (parent + text) - │ └─ chunkService.CreateChunks(ctx, insertChunks) - │ - └─ Result: Chunks stored but not yet indexed - -STEP 7: **CRITICAL - BATCH INDEXING** (1986-2008) - ├─ Line 1987: ★ MAIN INDEXING CALL ★ - │ └─ retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList) - │ - ├─ Key: indexInfoList contains ONLY text chunks (not parent chunks) - │ - ├─ BatchIndex() internally: - │ ├─ Gets tenant config: tenantInfo.GetEffectiveEngines() - │ │ └─ Returns: []RetrieverEngineParams - │ │ Each param: {RetrieverEngineType, RetrieverType} - │ │ - │ ├─ For EACH configured retriever type: - │ │ ├─ If "vector": creates embeddings, stores in vector DB - │ │ │ └─ Uses embeddingModel.GetDimensions() - │ │ │ - │ │ └─ If "keywords": indexes full-text/keywords - │ │ └─ Uses Elasticsearch, Postgres FTS, etc. - │ │ - │ └─ Result: Content indexed in BOTH vector + keyword if configured - │ - └─ Line 1988-2007: Error handling & cleanup if failed - -STEP 8: Enqueue Post-Processing (2044-2066) - ├─ Check: EnableMultimodel + StoredImages (2045-2046) - │ - ├─ If multimodal tasks pending (2045-2046): - │ └─ enqueueImageMultimodalTasks(ctx, knowledge, kb, images, ...) - │ └─ Chunks will be processed after multimodal tasks complete - │ └─ Those tasks will enqueue TypeKnowledgePostProcess when done - │ - ├─ Else (no multimodal): - │ ├─ Line 2050: Create KnowledgePostProcessPayload - │ ├─ Line 2057: Enqueue TypeKnowledgePostProcess task - │ │ └─ task.Enqueue(types.TypeKnowledgePostProcess, payload) - │ └─ This triggers Phase 3 immediately (no multimodal processing) - │ - └─ Result: Next phase scheduled - -STEP 9: Update Storage (2068-2073) - ├─ Line 2069: Update tenant storage usage - │ └─ tenantInfo.StorageUsed += totalStorageSize - │ - └─ Line 2070: Persist storage adjustment - └─ tenantRepo.AdjustStorageUsed(ctx, tenantID, size) - - -┌──────────────────────────────────────────────────────────────────────────────┐ -│ PHASE 3: POST-PROCESSING ORCHESTRATION │ -└──────────────────────────────────────────────────────────────────────────────┘ - -File: internal/application/service/knowledge_post_process.go -Type: KnowledgePostProcessService -Function: Handle(ctx, *asynq.Task) error -Lines: 42-128 - -STEP 1: Deserialize Input (44-54) - ├─ Line 44: Unmarshal types.KnowledgePostProcessPayload - ├─ Extract: TenantID, KnowledgeBaseID, KnowledgeID, Language - └─ Line 51-54: Setup context - -STEP 2: Fetch Knowledge & KB (57-69) - ├─ Line 57: Get knowledge - │ └─ knowledgeRepo.GetKnowledgeByIDOnly(ctx, knowledgeID) - │ - └─ Line 66: Get knowledge base - └─ kbService.GetKnowledgeBaseByIDOnly(ctx, kbID) - -STEP 3: Fetch Chunks (71-83) - ├─ Line 72: Get all chunks for knowledge - │ └─ chunkService.ListChunksByKnowledgeID(ctx, knowledgeID) - │ - ├─ Line 79-82: Filter text-like chunks - │ ├─ types.ChunkTypeText - │ ├─ types.ChunkTypeImageOCR - │ └─ types.ChunkTypeImageCaption - │ - └─ Result: textChunks array - -STEP 4: Update ParseStatus (85-103) - ├─ Line 87: Check current status (should be "processing") - ├─ Line 88: knowledge.ParseStatus = "completed" - │ - ├─ Line 92-96: Set SummaryStatus - │ ├─ If textChunks exist: - │ │ └─ knowledge.SummaryStatus = SummaryStatusPending - │ │ → Summary generation will be enqueued - │ │ - │ └─ Else: - │ └─ knowledge.SummaryStatus = SummaryStatusNone - │ → No summary needed (no content) - │ - └─ Line 98: Update knowledge in DB - -STEP 5: Enqueue Summary Generation (106-109) - ├─ Check: len(textChunks) > 0 (106) - │ - ├─ Line 107: enqueueSummaryGenerationTask(ctx, payload) - │ ├─ Creates types.SummaryGenerationPayload - │ ├─ Task type: types.TypeSummaryGeneration - │ ├─ Queue: "low" priority - │ └─ Max retries: 3 - │ - └─ Result: Summary task enqueued - -STEP 6: Enqueue Question Generation (if enabled) (106-109) - ├─ Check: kb.QuestionGenerationConfig != nil (160) - ├─ Check: kb.QuestionGenerationConfig.Enabled (160) - │ - ├─ Line 164-170: Validate & bound QuestionCount - │ ├─ Get: questionCount = kb.QuestionGenerationConfig.QuestionCount - │ ├─ Default: 3 (if <= 0) - │ └─ Max: 10 (cap at 10) - │ - ├─ Line 172-177: Create payload - │ └─ types.QuestionGenerationPayload{...} - │ - ├─ Line 185: Enqueue task - │ ├─ Task type: types.TypeQuestionGeneration - │ ├─ Queue: "low" priority - │ └─ Max retries: 3 - │ - └─ Result: Question generation task enqueued (if enabled) - -STEP 7: Enqueue Graph RAG Extract (if enabled) (112-120) - ├─ Line 112: Check kb.ExtractConfig != nil && kb.ExtractConfig.Enabled - │ - ├─ Line 113-119: For each text-like chunk - │ └─ NewChunkExtractTask(ctx, taskEnqueuer, tenantID, chunkID, summaryModelID) - │ - ├─ Uses: kb.SummaryModelID for LLM extraction - │ - └─ Result: Graph extraction tasks enqueued (one per chunk) - -STEP 8: **CRITICAL - WIKI INGEST TRIGGER** (122-126) - ├─ Line 123: ★ WIKI INGEST CONDITION ★ - │ └─ if kb.IsWikiEnabled() && kb.WikiConfig.AutoIngest && len(textChunks) > 0 - │ - ├─ Breakdown: - │ ├─ kb.IsWikiEnabled(): - │ │ └─ From knowledgebase.go:509 - │ │ └─ kb.WikiConfig != nil && kb.WikiConfig.Enabled - │ │ - │ ├─ kb.WikiConfig.AutoIngest: - │ │ └─ From wiki_page.go:98 - │ │ └─ Must be explicitly true - │ │ - │ └─ len(textChunks) > 0: - │ └─ Must have text content to ingest - │ - ├─ If condition TRUE (Line 124): - │ ├─ EnqueueWikiIngest(ctx, taskEnqueuer, redisClient, ...) - │ ├─ Task type: types.TypeWikiIngest (inferred) - │ └─ Line 125: Log success - │ - └─ If condition FALSE: - └─ Wiki ingest skipped silently (common case) - -STEP 9: Return Success (128) - └─ return nil - -┌──────────────────────────────────────────────────────────────────────────────┐ -│ PHASE 4: ASYNC POST-PROCESSING TASKS (Run in parallel) │ -└──────────────────────────────────────────────────────────────────────────────┘ - -File: internal/application/service/knowledge.go - -Task 1: Summary Generation - ├─ Function: ProcessSummaryGeneration (line 2227) - ├─ Input: types.SummaryGenerationPayload - ├─ Process: - │ ├─ Fetch chunks for knowledge - │ ├─ Get summary model: kb.SummaryModelID - │ ├─ Generate summary via LLM - │ ├─ Create summary chunk (ChunkType = ChunkTypeSummary) - │ └─ Index summary chunk: retrieveEngine.BatchIndex() - │ - └─ Result: knowledge.Description updated with summary - -Task 2: Question Generation (if enabled) - ├─ Function: ProcessQuestionGeneration (line 2416) - ├─ Input: types.QuestionGenerationPayload - ├─ Process: - │ ├─ For each text chunk - │ ├─ Use LLM to generate N questions - │ ├─ Create question chunks - │ └─ Index question chunks - │ - └─ Result: Question chunks indexed for Q&A search - -Task 3: Graph RAG Extraction (if enabled) - ├─ Function: (Via NewChunkExtractTask) - ├─ Input: ChunkID, SummaryModelID - ├─ Process: - │ ├─ Extract entities and relationships from chunk - │ ├─ Build knowledge graph - │ └─ Store graph nodes/edges - │ - └─ Result: Knowledge graph constructed from chunk content - -Task 4: Wiki Ingest (if triggered) - ├─ Function: (Via EnqueueWikiIngest) - ├─ Input: KnowledgeBaseID, KnowledgeID, TenantID - ├─ Process: - │ ├─ Fetch all chunks for knowledge - │ ├─ Use SynthesisModelID (kb.WikiConfig.SynthesisModelID) - │ ├─ Generate wiki pages from content - │ │ ├─ Summary pages (one per document) - │ │ ├─ Entity pages (auto-extracted) - │ │ ├─ Concept pages (auto-extracted) - │ │ └─ Interlinks between pages - │ │ - │ └─ Store wiki pages in wiki_pages table - │ - └─ Result: Wiki pages generated and interlinked - -``` - -## Configuration Decision Points - -### Vector vs Keyword Indexing - -**Decision Point**: Line 1987 in processChunks() -``` -retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList) -``` - -**How decided**: -1. BatchIndex() calls retrieveEngine (injected dependency) -2. retrieveEngine gets tenant config: `tenantInfo.GetEffectiveEngines()` -3. Returns: `[]RetrieverEngineParams` -4. Each param specifies: - - `RetrieverEngineType`: "postgres", "elasticsearch", etc. - - `RetrieverType`: "vector", "keywords", or both -5. Implementation creates indices for ALL configured types - -**Example Configurations**: -- Vector only: `{RetrieverEngineType: "postgres", RetrieverType: "vector"}` -- Keywords only: `{RetrieverEngineType: "elasticsearch", RetrieverType: "keywords"}` -- Hybrid: Both params included in array - -### Wiki Ingest Trigger - -**Decision Point**: Line 123 in knowledge_post_process.go -``` -if kb.IsWikiEnabled() && kb.WikiConfig.AutoIngest && len(textChunks) > 0 -``` - -**Configuration needed**: -- KB type: Any (typically "document") -- WikiConfig.Enabled: true -- WikiConfig.AutoIngest: true -- WikiConfig.SynthesisModelID: valid model ID -- At least one text chunk in document - -### Question Generation Trigger - -**Decision Point**: Line 160 in knowledge_post_process.go -``` -if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled -``` - -**Configuration needed**: -- QuestionGenerationConfig.Enabled: true -- QuestionGenerationConfig.QuestionCount: 1-10 (default 3) - -### Graph Extraction Trigger - -**Decision Point**: Line 112 in knowledge_post_process.go -``` -if kb.ExtractConfig != nil && kb.ExtractConfig.Enabled -``` - -**Configuration needed**: -- ExtractConfig.Enabled: true - -``` - diff --git a/KNOWLEDGE_MODEL_ANALYSIS.md b/KNOWLEDGE_MODEL_ANALYSIS.md deleted file mode 100644 index 1b0591f3..00000000 --- a/KNOWLEDGE_MODEL_ANALYSIS.md +++ /dev/null @@ -1,532 +0,0 @@ -# Knowledge Base Data Model and Document Processing Pipeline - Comprehensive Analysis - -## 1. KnowledgeBase Type Definition - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/knowledgebase.go` - -**Lines:** 40-98 (Main struct definition), plus related constants 12-38 - -### Full KnowledgeBase Struct (lines 40-98): - -```go -type KnowledgeBase struct { - // Unique identifier of the knowledge base - ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"` - // Name of the knowledge base - Name string `yaml:"name" json:"name"` - // Type of the knowledge base (document, faq, etc.) - Type string `yaml:"type" json:"type" gorm:"type:varchar(32);default:'document'"` - // Whether this knowledge base is temporary (ephemeral) and should be hidden from UI - IsTemporary bool `yaml:"is_temporary" json:"is_temporary" gorm:"default:false"` - // Description of the knowledge base - Description string `yaml:"description" json:"description"` - // Tenant ID - TenantID uint64 `yaml:"tenant_id" json:"tenant_id"` - // Chunking configuration - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config" gorm:"type:json"` - // Image processing configuration - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config" gorm:"type:json"` - // ID of the embedding model - EmbeddingModelID string `yaml:"embedding_model_id" json:"embedding_model_id"` - // Summary model ID - SummaryModelID string `yaml:"summary_model_id" json:"summary_model_id"` - // VLM config - VLMConfig VLMConfig `yaml:"vlm_config" json:"vlm_config" gorm:"type:json"` - // ASR config (Automatic Speech Recognition) - ASRConfig ASRConfig `yaml:"asr_config" json:"asr_config" gorm:"type:json"` - // Storage provider config (new): only stores provider selection; credentials from tenant StorageEngineConfig - StorageProviderConfig *StorageProviderConfig `yaml:"storage_provider_config" json:"storage_provider_config" gorm:"column:storage_provider_config;type:jsonb"` - // Deprecated: legacy COS config column. Kept for backward compatibility with old data. - StorageConfig StorageConfig `yaml:"-" json:"storage_config" gorm:"column:cos_config;type:json"` - // Extract config - ExtractConfig *ExtractConfig `yaml:"extract_config" json:"extract_config" gorm:"column:extract_config;type:json"` - // FAQConfig stores FAQ specific configuration such as indexing strategy - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config" gorm:"column:faq_config;type:json"` - // QuestionGenerationConfig stores question generation configuration for document knowledge bases - QuestionGenerationConfig *QuestionGenerationConfig `yaml:"question_generation_config" json:"question_generation_config" gorm:"column:question_generation_config;type:json"` - // WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases) - WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config" gorm:"column:wiki_config;type:json"` - // Whether this knowledge base is pinned to the top of the list - IsPinned bool `yaml:"is_pinned" json:"is_pinned" gorm:"default:false"` - // Time when the knowledge base was pinned (nil if not pinned) - PinnedAt *time.Time `yaml:"pinned_at" json:"pinned_at"` - // Creation time of the knowledge base - CreatedAt time.Time `yaml:"created_at" json:"created_at"` - // Last updated time of the knowledge base - UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"` - // Deletion time of the knowledge base - DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"` - // Knowledge count (not stored in database, calculated on query) - KnowledgeCount int64 `yaml:"knowledge_count" json:"knowledge_count" gorm:"-"` - // Chunk count (not stored in database, calculated on query) - ChunkCount int64 `yaml:"chunk_count" json:"chunk_count" gorm:"-"` - // IsProcessing indicates if there is a processing import task (for FAQ type knowledge bases) - IsProcessing bool `yaml:"is_processing" json:"is_processing" gorm:"-"` - // ProcessingCount indicates the number of knowledge items being processed (for document type knowledge bases) - ProcessingCount int64 `yaml:"processing_count" json:"processing_count" gorm:"-"` - // ShareCount indicates the number of organizations this knowledge base is shared with (not stored in database) - ShareCount int64 `yaml:"share_count" json:"share_count" gorm:"-"` -} -``` - -### Key Constants (lines 12-38): - -```go -// Knowledge base types -const ( - KnowledgeBaseTypeDocument = "document" - KnowledgeBaseTypeFAQ = "faq" - KnowledgeBaseTypeWiki = "wiki" -) - -// FAQ Index Modes -type FAQIndexMode string -const ( - FAQIndexModeQuestionOnly FAQIndexMode = "question_only" - FAQIndexModeQuestionAnswer FAQIndexMode = "question_answer" -) - -type FAQQuestionIndexMode string -const ( - FAQQuestionIndexModeCombined FAQQuestionIndexMode = "combined" - FAQQuestionIndexModeSeparate FAQQuestionIndexMode = "separate" -) -``` - -### Important Methods: -- **Line 508-509**: `IsWikiEnabled()` - checks if wiki feature is enabled -- **Line 515-528**: `IsMultimodalEnabled()` - checks if multimodal processing is enabled -- **Line 475-504**: `EnsureDefaults()` - ensures type-specific defaults - ---- - -## 2. WikiConfig Type Definition - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/wiki_page.go` - -**Lines:** 91-103 - -```go -type WikiConfig struct { - // Enabled activates the wiki feature for this knowledge base - Enabled bool `yaml:"enabled" json:"enabled"` - // AutoIngest triggers wiki page generation/update when new documents are added - AutoIngest bool `yaml:"auto_ingest" json:"auto_ingest"` - // SynthesisModelID is the LLM model ID used for wiki page generation and updates - SynthesisModelID string `yaml:"synthesis_model_id" json:"synthesis_model_id"` - // MaxPagesPerIngest limits pages created/updated per ingest operation (0 = no limit) - MaxPagesPerIngest int `yaml:"max_pages_per_ingest" json:"max_pages_per_ingest"` -} -``` - -**Value() and Scan() Methods:** Lines 105-120 (JSONB serialization/deserialization) - ---- - -## 3. ChunkingConfig Type Definition - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/knowledgebase.go` - -**Lines:** 118-141 - -```go -type ChunkingConfig struct { - // Chunk size - ChunkSize int `yaml:"chunk_size" json:"chunk_size"` - // Chunk overlap - ChunkOverlap int `yaml:"chunk_overlap" json:"chunk_overlap"` - // Separators - Separators []string `yaml:"separators" json:"separators"` - // EnableMultimodal (deprecated, kept for backward compatibility with old data) - EnableMultimodal bool `yaml:"enable_multimodal,omitempty" json:"enable_multimodal,omitempty"` - // ParserEngineRules configures which parser engine to use for each file type. - ParserEngineRules []ParserEngineRule `yaml:"parser_engine_rules,omitempty" json:"parser_engine_rules,omitempty"` - // EnableParentChild enables two-level parent-child chunking strategy. - EnableParentChild bool `yaml:"enable_parent_child,omitempty" json:"enable_parent_child,omitempty"` - // ParentChunkSize is the size of parent chunks (default: 4096). - ParentChunkSize int `yaml:"parent_chunk_size,omitempty" json:"parent_chunk_size,omitempty"` - // ChildChunkSize is the size of child chunks used for embedding (default: 384). - ChildChunkSize int `yaml:"child_chunk_size,omitempty" json:"child_chunk_size,omitempty"` -} -``` - ---- - -## 4. Document Processing Pipeline - -### 4.1 ProcessDocument Function - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/application/service/knowledge.go` - -**Lines:** 7732-8108+ (Main entry point for document processing) - -**Signature:** -```go -func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) error -``` - -**Key Steps in ProcessDocument (lines 7732-8108+):** - -1. **Unmarshal Task Payload** (7733-7737) - - Payload type: `types.DocumentProcessPayload` - - Includes: KnowledgeID, KnowledgeBaseID, FilePath, FileURL, FileType, etc. - -2. **Idempotency Checks** (7761-7801) - - Check knowledge existence - - Check ParseStatus (skip if already completed) - - Check if knowledge is being deleted - - Update ParseStatus to "processing" - -3. **KB Validation** (7803-7812) - - Fetch knowledge base configuration - - Validate embedding model configuration - -4. **File Processing** (7821-7931) - - Handle multimodal image processing flag - - Handle ASR (Audio Speech Recognition) configuration - - Download files from URL if needed (with SSRF protection) - - Call `s.convert()` to convert files to readable format - -5. **Chunk Processing** (8108+) - - Call `s.processChunks()` for vectorization and indexing - -### 4.2 processChunks Function - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/application/service/knowledge.go` - -**Lines:** 1681-2074 (Core chunk processing and indexing) - -**Signature:** -```go -func (s *knowledgeService) processChunks(ctx context.Context, - kb *types.KnowledgeBase, - knowledge *types.Knowledge, - chunks []types.ParsedChunk, - opts ...ProcessChunksOptions, -) -``` - -**Key Steps in processChunks:** - -1. **Get Embedding Model** (1708-1714) - - Fetch embedding model using `kb.EmbeddingModelID` - - Get model dimensions for storage estimation - -2. **Idempotency & Cleanup** (1716-1744) - - Clean up old chunks: `s.chunkService.DeleteChunksByKnowledgeID()` - - Delete old index data: `retrieveEngine.DeleteByKnowledgeIDList()` - - Delete old graph data: `s.graphEngine.DelGraph()` - -3. **Parent-Child Chunking (Optional)** (1810-1876) - - If enabled, create parent chunks first (NOT indexed for vectors) - - Create child chunks, linked to parent via `ParentChunkID` - - Parent chunks provide context, children used for matching - -4. **Create Index Information** (1908-1928) - - Only for TEXT chunks, NOT parent chunks - - Prepend document title to content for better semantic alignment - - Create `IndexInfo` objects for each text chunk - - Title prefix: `titlePrefix = knowledge.Title + "\n"` - -5. **Storage Quota Check** (1932-1955) - - Estimate storage size: `retrieveEngine.EstimateStorageSize()` - - Verify tenant has sufficient quota - -6. **Save Chunks to Database** (1965-1973) - - `s.chunkService.CreateChunks(ctx, insertChunks)` - - Includes all chunk types (parent, child, text) - -7. **Batch Indexing** (1986-2008) - - **CRITICAL**: `retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList)` - - This is where vector/keyword indexing decision is made (see Section 5 below) - -8. **Enqueue Post-Processing Tasks** (2044-2066) - - If multimodal enabled: enqueue image processing tasks - - Otherwise: enqueue `TypeKnowledgePostProcess` task immediately - -9. **Update Storage Usage** (2068-2073) - - Adjust tenant storage quota: `tenantInfo.StorageUsed += totalStorageSize` - -### Key Decision Point: Vector vs Keyword Indexing - -**Location:** Lines 1987 and retrieval engine configuration - -**How it's determined:** -- The `retrieveEngine.BatchIndex()` call does NOT take explicit parameters for vector vs keyword -- **Instead, the decision is made at the TENANT level** via `Tenant.RetrieverEngines` configuration -- The `GetEffectiveEngines()` method (tenant.go line 126-131) returns: - - Configured engines if set: `t.RetrieverEngines.Engines` - - Otherwise: system defaults via `GetDefaultRetrieverEngines()` - -**See Section 5 for detailed indexing configuration.** - ---- - -## 5. Retriever/Indexing Type Configuration - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/retriever.go` - -**Lines:** 1-101 - -### RetrieverType Constants (lines 21-26): - -```go -type RetrieverType string - -const ( - KeywordsRetrieverType RetrieverType = "keywords" // Keywords retriever - VectorRetrieverType RetrieverType = "vector" // Vector retriever - WebSearchRetrieverType RetrieverType = "websearch" // Web search retriever -) -``` - -### RetrieverEngineType Constants (lines 8-16): - -```go -const ( - PostgresRetrieverEngineType RetrieverEngineType = "postgres" - ElasticsearchRetrieverEngineType RetrieverEngineType = "elasticsearch" - InfinityRetrieverEngineType RetrieverEngineType = "infinity" - ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss" - QdrantRetrieverEngineType RetrieverEngineType = "qdrant" - MilvusRetrieverEngineType RetrieverEngineType = "milvus" - WeaviateRetrieverEngineType RetrieverEngineType = "weaviate" - SQLiteRetrieverEngineType RetrieverEngineType = "sqlite" -) -``` - -### RetrieverEngineParams (lines 56-62): - -```go -type RetrieverEngineParams struct { - // Retriever engine type - RetrieverEngineType RetrieverEngineType `yaml:"retriever_engine_type" json:"retriever_engine_type"` - // Retriever type - RetrieverType RetrieverType `yaml:"retriever_type" json:"retriever_type"` -} -``` - -### Tenant Configuration (tenant.go, lines 125-131): - -```go -func (t *Tenant) GetEffectiveEngines() []RetrieverEngineParams { - if len(t.RetrieverEngines.Engines) > 0 { - return t.RetrieverEngines.Engines - } - return GetDefaultRetrieverEngines() -} -``` - -**Key Points:** -- Indexing types are configured per TENANT, not per knowledge base -- Multiple retriever engines can be configured (e.g., Vector + Keywords) -- Each engine specifies its type (RetrieverEngineType) and retriever type(s) -- During indexing, ALL configured retriever types are used -- This enables HYBRID search (vector + keyword combined) - ---- - -## 6. Post-Processing Handler - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/application/service/knowledge_post_process.go` - -**Lines:** 1-192 (Complete file) - -### KnowledgePostProcessService.Handle Function - -**Entry Point:** Lines 42-128 - -**Key Steps:** - -1. **Fetch Knowledge and KB** (57-69) - - Get knowledge by ID: `s.knowledgeRepo.GetKnowledgeByIDOnly()` - - Get knowledge base: `s.kbService.GetKnowledgeBaseByIDOnly()` - -2. **Fetch All Chunks** (71-83) - - Get chunks by knowledge ID: `s.chunkService.ListChunksByKnowledgeID()` - - Filter text-like chunks (TEXT, OCR, CAPTION) - -3. **Update ParseStatus to Completed** (85-103) - - Change ParseStatus from "processing" to "completed" - - Set SummaryStatus based on whether text chunks exist: - - If text chunks: `SummaryStatus = SummaryStatusPending` - - Otherwise: `SummaryStatus = SummaryStatusNone` - -4. **Enqueue Summary Generation** (106-109) - - **Line 107**: `s.enqueueSummaryGenerationTask(ctx, payload)` - - Only if text chunks exist - -5. **Enqueue Question Generation (if enabled)** (106-109) - - **Line 108**: `s.enqueueQuestionGenerationIfEnabled(ctx, payload, kb)` - - Checks `kb.QuestionGenerationConfig.Enabled` - - Uses QuestionCount (default 3, max 10) - -6. **Spawn Graph RAG Tasks** (112-120) - - **Lines 112-120**: Check `kb.ExtractConfig != nil && kb.ExtractConfig.Enabled` - - For each text-like chunk, enqueue: `NewChunkExtractTask()` - - Uses `kb.SummaryModelID` for LLM - -7. **Wiki Ingest Trigger** (122-126) - - **Lines 122-126**: CRITICAL - This is where wiki ingest is triggered - - **Condition:** - ```go - if kb.IsWikiEnabled() && kb.WikiConfig.AutoIngest && len(textChunks) > 0 { - EnqueueWikiIngest(...) - } - ``` - - **Exact condition breakdown:** - - `kb.IsWikiEnabled()` = `kb.WikiConfig != nil && kb.WikiConfig.Enabled` (knowledgebase.go line 509) - - `kb.WikiConfig.AutoIngest` = must be true (wiki_page.go line 98) - - `len(textChunks) > 0` = must have text content to ingest - -### Supporting Functions: - -**enqueueSummaryGenerationTask** (lines 130-153) -- Payload: `types.SummaryGenerationPayload` -- Task type: `types.TypeSummaryGeneration` -- Queue: "low" priority -- Max retries: 3 - -**enqueueQuestionGenerationIfEnabled** (lines 155-191) -- Checks if enabled and validates question count -- Payload: `types.QuestionGenerationPayload` -- Task type: `types.TypeQuestionGeneration` -- Queue: "low" priority -- Max retries: 3 - ---- - -## 7. RetrievalConfig (Threshold Configuration) - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/retrieval_config.go` - -**Lines:** 14-27 - -```go -type RetrievalConfig struct { - // EmbeddingTopK is the maximum number of chunks returned by vector search (default: 50) - EmbeddingTopK int `json:"embedding_top_k"` - // VectorThreshold is the minimum vector similarity score (0-1, default: 0.15) - VectorThreshold float64 `json:"vector_threshold"` - // KeywordThreshold is the minimum keyword match score (0-1, default: 0.3) - KeywordThreshold float64 `json:"keyword_threshold"` - // RerankTopK is the maximum number of results after reranking (default: 10) - RerankTopK int `json:"rerank_top_k"` - // RerankThreshold is the minimum rerank score (-10 to 10, default: 0.2) - RerankThreshold float64 `json:"rerank_threshold"` - // RerankModelID is the ID of the rerank model to use (required for search) - RerankModelID string `json:"rerank_model_id"` -} -``` - -**Stored on:** `tenants.retrieval_config` (JSONB column) - -**Usage:** Controls search thresholds and result limits for both vector and keyword searches - ---- - -## 8. API/DTO Types - -**File Path:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/handler/knowledgebase.go` - -### UpdateKnowledgeBaseRequest (lines 427-431) - -```go -type UpdateKnowledgeBaseRequest struct { - Name string `json:"name" binding:"required"` - Description string `json:"description"` - Config *types.KnowledgeBaseConfig `json:"config"` -} -``` - -### KnowledgeBaseConfig (knowledgebase.go lines 100-110) - -```go -type KnowledgeBaseConfig struct { - // Chunking configuration - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"` - // Image processing configuration - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"` - // FAQ configuration (only for FAQ type knowledge bases) - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"` - // Wiki configuration (only for wiki-enabled knowledge bases) - WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config"` -} -``` - -### API Endpoints (knowledgebase.go): - -- **CreateKnowledgeBase**: POST `/knowledge-bases` (lines 114-147) - - Input: `types.KnowledgeBase` - -- **UpdateKnowledgeBase**: PUT `/knowledge-bases/{id}` (lines 446-488) - - Input: `UpdateKnowledgeBaseRequest` - - Requires admin/editor permission - -- **DeleteKnowledgeBase**: DELETE `/knowledge-bases/{id}` (lines 502-536) - - Requires owner permission - ---- - -## 9. Document Processing Flow Summary - -``` -┌─────────────────────────────────────────────────────────────────┐ -│ 1. DOCUMENT UPLOAD │ -│ ↓ │ -│ 2. ProcessDocument Task (Task Queue) │ -│ ├─ Fetch Knowledge & KB │ -│ ├─ Validate configuration (multimodal, ASR) │ -│ ├─ Download file if from URL (SSRF check) │ -│ └─ Call convert() to parse file │ -│ ↓ │ -│ 3. processChunks() │ -│ ├─ Get embedding model (kb.EmbeddingModelID) │ -│ ├─ Clean old chunks/indices │ -│ ├─ Create chunks (parent + child if enabled) │ -│ ├─ Estimate storage size │ -│ ├─ Save chunks to DB │ -│ └─ BatchIndex() ← VECTOR/KEYWORD decision here │ -│ ├─ Uses Tenant.RetrieverEngines config │ -│ ├─ Calls all configured retriever types │ -│ └─ Creates vectors + keyword indices │ -│ ├─ Enqueue multimodal tasks (if enabled) │ -│ └─ OR enqueue TypeKnowledgePostProcess (if no multimodal) │ -│ ↓ │ -│ 4. KnowledgePostProcess Task │ -│ ├─ Update ParseStatus = "completed" │ -│ ├─ Set SummaryStatus = "pending" (if text chunks) │ -│ ├─ Enqueue Summary Generation (line 107) │ -│ ├─ Enqueue Question Generation (line 108, if enabled) │ -│ ├─ Enqueue Graph RAG Extract (lines 114-119) │ -│ └─ **WIKI INGEST CHECK** (lines 123-126) │ -│ IF kb.IsWikiEnabled() AND │ -│ kb.WikiConfig.AutoIngest AND │ -│ len(textChunks) > 0 │ -│ THEN EnqueueWikiIngest() │ -│ ↓ │ -│ 5. POST-PROCESSING (Async Tasks) │ -│ ├─ Summary Generation │ -│ ├─ Question Generation │ -│ ├─ Graph RAG Extraction │ -│ └─ Wiki Ingest (if triggered) │ -└─────────────────────────────────────────────────────────────────┘ -``` - ---- - -## 10. Key File Locations Summary - -| Component | File Path | Key Lines | -|-----------|-----------|-----------| -| KnowledgeBase struct | `internal/types/knowledgebase.go` | 40-98 | -| WikiConfig struct | `internal/types/wiki_page.go` | 91-103 | -| ChunkingConfig struct | `internal/types/knowledgebase.go` | 118-141 | -| ProcessDocument | `internal/application/service/knowledge.go` | 7732-8108 | -| processChunks | `internal/application/service/knowledge.go` | 1681-2074 | -| KnowledgePostProcessService | `internal/application/service/knowledge_post_process.go` | 16-128 | -| RetrieverTypes | `internal/types/retriever.go` | 18-26 | -| Tenant.GetEffectiveEngines | `internal/types/tenant.go` | 125-131 | -| RetrievalConfig | `internal/types/retrieval_config.go` | 14-27 | -| API Handlers | `internal/handler/knowledgebase.go` | 114-488 | - diff --git a/KNOWLEDGE_MODEL_QUICK_REF.md b/KNOWLEDGE_MODEL_QUICK_REF.md deleted file mode 100644 index f1933e3e..00000000 --- a/KNOWLEDGE_MODEL_QUICK_REF.md +++ /dev/null @@ -1,167 +0,0 @@ -# Knowledge Base Data Model - Quick Reference - -## Core Structs at a Glance - -### 1. KnowledgeBase (`internal/types/knowledgebase.go:40-98`) -Main entity defining a knowledge base with configuration for: -- **Chunking**: `ChunkingConfig` (chunk size, overlap, parent-child strategy) -- **Indexing**: Determined by TENANT config via `Tenant.RetrieverEngines` -- **Multimodal**: `VLMConfig` (vision/image processing), `ASRConfig` (speech recognition) -- **Wiki**: `WikiConfig` (wiki page generation on document ingest) -- **Question Generation**: `QuestionGenerationConfig` (auto-generate Q&A from chunks) -- **Graph Extraction**: `ExtractConfig` (knowledge graph entity/relation extraction) -- **Embedding Model**: `EmbeddingModelID` (for vector search) -- **Summary Model**: `SummaryModelID` (for LLM-based summarization) - -### 2. WikiConfig (`internal/types/wiki_page.go:91-103`) -Controls wiki feature for a knowledge base: -- `Enabled`: bool - Feature toggle -- `AutoIngest`: bool - Auto-generate pages when documents added -- `SynthesisModelID`: string - LLM model for page generation -- `MaxPagesPerIngest`: int - Rate limit (0 = unlimited) - -### 3. ChunkingConfig (`internal/types/knowledgebase.go:118-141`) -Controls document chunking strategy: -- `ChunkSize`: int - Main chunk size in characters -- `ChunkOverlap`: int - Overlap between chunks -- `ParserEngineRules`: []ParserEngineRule - Parser selection per file type -- `EnableParentChild`: bool - Two-level chunking (context + matching) -- `ParentChunkSize`: int - Large chunks for context (default 4096) -- `ChildChunkSize`: int - Small chunks for embedding (default 384) - -## Processing Pipeline Steps - -### Step 1: Document Ingestion -``` -Document Upload → ProcessDocument Task (async) -``` -**File**: `internal/application/service/knowledge.go:7732` - -**Key**: -- Validates KB config (multimodal, ASR enabled) -- Downloads file from URL if provided -- Calls `convert()` to parse document - -### Step 2: Chunk Creation & Indexing -``` -processChunks() → Save chunks to DB → BatchIndex() -``` -**File**: `internal/application/service/knowledge.go:1681` - -**Key**: -- Creates chunks from parsed content -- Parent chunks stored but NOT indexed (parent-child mode) -- Child/text chunks prepared for indexing -- `retrieveEngine.BatchIndex()` uses **TENANT's RetrieverEngines** config -- Supports both vector and keyword indexing (can be combined) - -### Step 3: Post-Processing -``` -KnowledgePostProcess → Spawn async tasks -``` -**File**: `internal/application/service/knowledge_post_process.go:42` - -**Key**: -- Summary Generation (LLM summarization) -- Question Generation (if enabled) -- Graph RAG Extraction (if enabled) -- **Wiki Ingest** (if enabled AND AutoIngest=true AND has text chunks) - -## Vector vs Keyword Indexing Decision - -**Decision Location**: Tenant configuration, NOT knowledge base level - -**How it works**: -1. Tenant has `RetrieverEngines` config specifying retriever types -2. Each engine can be: `"vector"`, `"keywords"`, or both -3. During `BatchIndex()`, all configured types are used -4. Enables **hybrid search** combining results from multiple index types - -**Config Path**: -- Table: `tenants` -- Column: `retriever_engines` (JSONB) -- Type: `[]RetrieverEngineParams` -- Each param specifies: `{RetrieverEngineType, RetrieverType}` - -## Wiki Ingest Trigger - -**Exact Condition** (`knowledge_post_process.go:123-126`): -```go -if kb.IsWikiEnabled() && kb.WikiConfig.AutoIngest && len(textChunks) > 0 { - EnqueueWikiIngest(...) -} -``` - -**Breakdown**: -- `kb.IsWikiEnabled()` ⟹ `WikiConfig != nil && Enabled == true` -- `kb.WikiConfig.AutoIngest` ⟹ Must be explicitly enabled -- `len(textChunks) > 0` ⟹ Must have text content (not just images) - -**Result**: -- Enqueues `TypeWikiIngest` task -- LLM generates/updates wiki pages based on ingested content -- Uses `SynthesisModelID` from WikiConfig - -## Retrieval Configuration - -**File**: `internal/types/retrieval_config.go:14-27` -**Stored on**: `tenants.retrieval_config` (JSONB) - -Controls: -- `EmbeddingTopK` (50): Max results from vector search -- `VectorThreshold` (0.15): Min similarity score for vectors -- `KeywordThreshold` (0.3): Min score for keywords -- `RerankTopK` (10): Results after reranking -- `RerankModelID`: LLM for reranking results - -## API Endpoints - -### Create Knowledge Base -``` -POST /knowledge-bases -Body: types.KnowledgeBase -``` - -### Update Knowledge Base -``` -PUT /knowledge-bases/{id} -Body: UpdateKnowledgeBaseRequest { - Name: string - Description: string - Config: *KnowledgeBaseConfig { ChunkingConfig, WikiConfig, ... } -} -``` - -### Delete Knowledge Base -``` -DELETE /knowledge-bases/{id} -``` - -## Important Constants - -### Knowledge Base Types -- `"document"` - Regular documents with chunking/search -- `"faq"` - Q&A pairs -- `"wiki"` - Wiki pages (not a separate type, but feature on documents) - -### Retriever Types -- `"vector"` - Vector/embedding-based search -- `"keywords"` - Full-text/keyword search -- `"websearch"` - Web search - -### Chunk Types -- `"text"` - Main text content -- `"parent_text"` - Parent chunk (context, not indexed) -- `"image_ocr"` - OCR text from images -- `"image_caption"` - AI-generated image captions -- `"summary"` - Document summary chunk - -## Key Takeaways - -1. **Indexing is tenant-scoped**, not per-KB -2. **Hybrid search** uses multiple index types simultaneously -3. **Wiki ingest** requires three conditions: enabled, auto_ingest, content -4. **Parent-child chunking** splits semantic context from search terms -5. **Post-processing** is async and orchestrates multiple LLM tasks -6. **Multimodal** (images/speech) requires explicit config + KB support - diff --git a/LANGUAGE_MIDDLEWARE_ANALYSIS.md b/LANGUAGE_MIDDLEWARE_ANALYSIS.md deleted file mode 100644 index 9a36a63e..00000000 --- a/LANGUAGE_MIDDLEWARE_ANALYSIS.md +++ /dev/null @@ -1,349 +0,0 @@ -# WeKnora Language Middleware Analysis & Refactoring Guide - -## Overview - -The user mentioned that middleware already contains language determination logic that could be reused in the wiki ingest pipeline. This document identifies the existing language handling infrastructure and provides refactoring recommendations. - ---- - -## 1. Existing Language Middleware Infrastructure - -### File: `/internal/middleware/language.go` - -**Purpose:** HTTP middleware to extract and inject user language preference into request context. - -**Middleware Function:** -```go -func Language() gin.HandlerFunc -``` - -**Language Detection Priority (highest to lowest):** -1. `WEKNORA_LANGUAGE` environment variable (deployment-level override) -2. `Accept-Language` HTTP header (first tag, e.g., "zh-CN,zh;q=0.9" → "zh-CN") -3. Hardcoded fallback: "zh-CN" - -**Key Design Principle:** -- Separates UI locale (menu language) from document processing language -- A user may prefer English UI while processing Korean documents -- WEKNORA_LANGUAGE env var takes precedence because it controls document processing language globally - -**Implementation Details:** - -```go -// Language() middleware: -// 1. Check WEKNORA_LANGUAGE env var (read once at startup) -// 2. If set → inject into context and return -// 3. If not set → parse Accept-Language header -// 4. If header missing → use "zh-CN" fallback -// 5. Inject final result into both gin context and request context - -func Language() gin.HandlerFunc { - envLang := types.EnvLanguage() - return func(c *gin.Context) { - if envLang != "" { - c.Set(types.LanguageContextKey.String(), envLang) - ctx := context.WithValue(c.Request.Context(), types.LanguageContextKey, envLang) - c.Request = c.Request.WithContext(ctx) - c.Next() - return - } - // ... parse header, fallback, inject - } -} - -// Helper: parseFirstLanguageTag(header string) string -// Extracts first language tag from Accept-Language header -// e.g., "zh-CN,zh;q=0.9,en;q=0.8" → "zh-CN" -``` - -### File: `/internal/types/context_helpers.go` - -**Existing Helper Functions:** - -#### 1. `EnvLanguage() string` (line 9-12) -```go -// Returns WEKNORA_LANGUAGE environment variable value, or empty string -func EnvLanguage() string { - return strings.TrimSpace(os.Getenv("WEKNORA_LANGUAGE")) -} -``` - -#### 2. `DefaultLanguage() string` (line 14-21) -```go -// Returns configured default language locale -// Priority: WEKNORA_LANGUAGE env > "zh-CN" -func DefaultLanguage() string { - if lang := EnvLanguage(); lang != "" { - return lang - } - return "zh-CN" -} -``` - -#### 3. `LanguageFromContext(ctx context.Context) (string, bool)` (line 67-72) -```go -// Extracts language locale from context -// e.g., "zh-CN", "en-US" -// Returns ("zh-CN", false) when key is absent -func LanguageFromContext(ctx context.Context) (string, bool) { - v, ok := ctx.Value(LanguageContextKey).(string) - return v, ok && v != "" -} -``` - -#### 4. `LanguageNameFromContext(ctx context.Context) string` (line 74-83) -```go -// Returns HUMAN-READABLE language name for use in LLM prompts -// Falls back to DefaultLanguage() -// e.g., "zh-CN" -> "Chinese (Simplified)" -func LanguageNameFromContext(ctx context.Context) string { - lang, ok := LanguageFromContext(ctx) - if !ok { - lang = DefaultLanguage() - } - return LanguageLocaleName(lang) -} -``` - -#### 5. **THE KEY FUNCTION:** `LanguageLocaleName(locale string) string` (line 85-112) -```go -// Maps locale code to human-readable language name -// Comprehensive mapping of 9 languages: -func LanguageLocaleName(locale string) string { - switch locale { - case "zh-CN", "zh", "zh-Hans": - return "Chinese (Simplified)" - case "zh-TW", "zh-HK", "zh-Hant": - return "Chinese (Traditional)" - case "en-US", "en", "en-GB": - return "English" - case "ko-KR", "ko": - return "Korean" - case "ja-JP", "ja": - return "Japanese" - case "ru-RU", "ru": - return "Russian" - case "fr-FR", "fr": - return "French" - case "de-DE", "de": - return "German" - case "es-ES", "es": - return "Spanish" - case "pt-BR", "pt": - return "Portuguese" - default: - return locale // Return locale itself for unknown locales - } -} -``` - -### File: `/internal/types/const.go` (line 24-25) - -**Context Key Definition:** -```go -// LanguageContextKey is the context key for user language preference (e.g. "zh-CN", "en-US") -LanguageContextKey ContextKey = "Language" -``` - ---- - -## 2. Current Wiki Ingest Language Logic (NEEDS REFACTORING) - -### File: `/internal/application/service/wiki_ingest.go` (line 135-141) - -**Current Implementation - Hardcoded and Limited:** - -```go -// Determine language -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} -``` - -**Problems with Current Approach:** -1. **Hardcoded mapping** - Only supports 2 languages (zh, en) -2. **Limited coverage** - No support for Korean, Japanese, Russian, French, German, Spanish, Portuguese -3. **Inconsistent naming** - Uses different format than middleware ("Chinese (中文)" vs middleware's "Chinese (Simplified)") -4. **Not reusing existing infrastructure** - Duplicates logic already in `LanguageLocaleName()` -5. **Default fallback unclear** - Uses generic string "the same language as the source document" - ---- - -## 3. Refactoring Recommendations - -### Recommended Solution: Reuse `LanguageLocaleName()` - -Replace wiki_ingest.go lines 135-141 with: - -```go -// Get human-readable language name for LLM prompts -// Supports: Chinese (Simplified/Traditional), English, Korean, Japanese, Russian, French, German, Spanish, Portuguese -// Falls back to: Default language from context or WEKNORA_LANGUAGE env, or "zh-CN" -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Changes Required:** - -1. **In `wiki_ingest.go` ProcessWikiIngest() method:** - - Before (current, lines 135-141): - ```go - // Determine language - lang := "the same language as the source document" - if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" - } else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" - } - ``` - - After (refactored): - ```go - // Get human-readable language name for LLM prompts - // Reuses language mapping from middleware infrastructure (supports 9+ languages) - lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) - ``` - -2. **Bonus: Align WikiConfig.WikiLanguage naming with context middleware:** - - Consider normalizing `WikiConfig.WikiLanguage` storage: - - Currently: "zh", "en" (short codes) - - Consider: Store full locale codes like "zh-CN", "en-US" for consistency with middleware - - If changed, update migration to map old values → new values - -3. **Optional: Further enhancement - use context language:** - - ```go - // Determine language: prefer KB config, fallback to context, then env, then "zh-CN" - lang := kb.WikiConfig.WikiLanguage - if lang == "" { - lang, _ = types.LanguageFromContext(ctx) - if lang == "" { - lang = types.DefaultLanguage() - } - } - humanReadableLang := types.LanguageLocaleName(lang) - ``` - ---- - -## 4. Integration Points - -### Where `LanguageLocaleName()` is Already Used: - -1. **`/internal/types/context_helpers.go`** - Definition (line 85-112) -2. **`LanguageNameFromContext()` function** - Calls it (line 82) - -### Where to Add New Usage: - -1. **`/internal/application/service/wiki_ingest.go`** - ProcessWikiIngest() (line 137) -2. **`/internal/application/service/wiki_ingest.go`** - extractEntitiesAndConcepts() (line 305) -3. **`/internal/application/service/wiki_ingest.go`** - upsertExtractedPages() (line 317) -4. **`/internal/application/service/wiki_ingest.go`** - rebuildIndexPage() (line 416) - -All these functions currently pass language parameter to LLM prompts. - ---- - -## 5. Implementation Checklist - -- [ ] **Step 1:** Replace hardcoded language logic in `wiki_ingest.go` line 137 with `types.LanguageLocaleName(kb.WikiConfig.WikiLanguage)` -- [ ] **Step 2:** Remove duplicated language mapping code (lines 135-141) -- [ ] **Step 3:** Add import if needed: `"github.com/Tencent/WeKnora/internal/types"` (likely already imported) -- [ ] **Step 4:** Test with different language values: "zh", "en", "zh-CN", "en-US" to ensure fallback works -- [ ] **Step 5:** Update documentation/comments to reference the shared `LanguageLocaleName()` function -- [ ] **Step 6 (Optional):** Consider full locale code normalization (zh → zh-CN, en → en-US) for consistency - ---- - -## 6. Additional Observations - -### Language vs WikiLanguage - -The codebase has two language concepts: - -1. **Context Language** (middleware-driven): - - HTTP request Accept-Language header - - WEKNORA_LANGUAGE environment variable - - Used for UI rendering, document processing language - - Format: "zh-CN", "en-US" (full locale) - -2. **WikiLanguage** (KB config): - - Stored in `KnowledgeBase.WikiConfig.WikiLanguage` - - Format: Short codes "zh", "en" - - Used specifically for wiki page generation language preference - -### Recommendation: Unify Language Format - -Consider normalizing both to use full locale codes: -- Store "zh-CN" instead of "zh" -- Store "en-US" instead of "en" -- This allows direct reuse of `LanguageLocaleName()` without conversion - ---- - -## 7. Code Migration Path - -If you decide to normalize WikiLanguage format: - -```go -// Migration helper function -func normalizeWikiLanguage(shortCode string) string { - switch shortCode { - case "zh": - return "zh-CN" - case "en": - return "en-US" - default: - return shortCode - } -} - -// In wiki_ingest.go ProcessWikiIngest(): -normalizedLang := normalizeWikiLanguage(kb.WikiConfig.WikiLanguage) -lang := types.LanguageLocaleName(normalizedLang) -``` - ---- - -## Summary - -### Quick Refactoring (No Schema Changes) - -```diff -- lang := "the same language as the source document" -- if kb.WikiConfig.WikiLanguage == "zh" { -- lang = "Chinese (中文)" -- } else if kb.WikiConfig.WikiLanguage == "en" { -- lang = "English" -- } -+ lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Benefits:** -- ✅ Supports 9+ languages instead of 2 -- ✅ Reuses existing, tested infrastructure -- ✅ Eliminates code duplication -- ✅ Consistent naming with middleware -- ✅ Single line of code vs 6 lines - -### Full Refactoring (With Schema Normalization) - -1. Update `KnowledgeBase.WikiConfig.WikiLanguage` format from short codes to full locales -2. Run database migration to convert existing values -3. Use `types.LanguageLocaleName()` directly without conversion -4. All language references consistent across codebase - ---- - -## Files Modified Summary - -| File | Changes | Lines | -|------|---------|-------| -| `/internal/application/service/wiki_ingest.go` | Replace lines 135-141 with single call to `types.LanguageLocaleName()` | 135-141 | -| **Reuse** | `/internal/types/context_helpers.go` | Use existing `LanguageLocaleName()` function | 85-112 | -| **Reuse** | `/internal/middleware/language.go` | Existing language detection infrastructure | All | -| **Optional** | Database migration | Normalize WikiLanguage format (if pursuing full refactoring) | - | diff --git a/LANGUAGE_REFACTORING_COMPLETED.md b/LANGUAGE_REFACTORING_COMPLETED.md deleted file mode 100644 index 75fc86f3..00000000 --- a/LANGUAGE_REFACTORING_COMPLETED.md +++ /dev/null @@ -1,234 +0,0 @@ -# Language Refactoring Completion Report - -**Date:** 2026-04-07 -**Status:** ✅ COMPLETED - -## Summary - -Successfully refactored the wiki ingest service to reuse existing language infrastructure from the middleware layer instead of maintaining duplicated, hardcoded language mappings. - ---- - -## Changes Made - -### File: `internal/application/service/wiki_ingest.go` - -**Before (lines 135-141):** -```go -// Determine language -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} -``` - -**After (lines 135-139):** -```go -// Get human-readable language name for LLM prompts -// Reuses language mapping from middleware infrastructure (supports 9+ languages) -// Maps locale codes like "zh", "en" to names like "Chinese (Simplified)", "English" -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Impact:** -- ✅ Reduced from 7 lines to 4 lines (including improved comments) -- ✅ Removed hardcoded if-else logic -- ✅ Now supports 9+ languages instead of 2: - - Chinese (Simplified/Traditional) - - English - - Korean - - Japanese - - Russian - - French - - German - - Spanish - - Portuguese -- ✅ Consistent naming with middleware: "Chinese (Simplified)" instead of "Chinese (中文)" -- ✅ Eliminates code duplication and maintenance burden - ---- - -## Benefits - -### Before Refactoring -- ❌ Only supported 2 languages (zh, en) -- ❌ Hardcoded mapping duplicated existing `LanguageLocaleName()` function -- ❌ Inconsistent language name formatting -- ❌ Default fallback was vague ("the same language as the source document") -- ❌ 7 lines of code to maintain - -### After Refactoring -- ✅ Supports 9+ languages via existing infrastructure -- ✅ Single source of truth: `types.LanguageLocaleName()` -- ✅ Consistent naming across entire application -- ✅ Clear fallback to unknown language = return as-is -- ✅ 4 lines of clear, well-documented code -- ✅ No additional imports needed (types already imported) - ---- - -## Technical Details - -### Function Reused -**Location:** `internal/types/context_helpers.go` (lines 85-112) - -```go -func LanguageLocaleName(locale string) string { - switch locale { - case "zh-CN", "zh", "zh-Hans": - return "Chinese (Simplified)" - case "zh-TW", "zh-HK", "zh-Hant": - return "Chinese (Traditional)" - case "en-US", "en", "en-GB": - return "English" - case "ko-KR", "ko": - return "Korean" - case "ja-JP", "ja": - return "Japanese" - case "ru-RU", "ru": - return "Russian" - case "fr-FR", "fr": - return "French" - case "de-DE", "de": - return "German" - case "es-ES", "es": - return "Spanish" - case "pt-BR", "pt": - return "Portuguese" - default: - return locale // Return as-is for unknown locales - } -} -``` - -### Language Mapping Coverage - -| Locale Code | Human-Readable Name | -|-------------|-------------------| -| zh-CN, zh, zh-Hans | Chinese (Simplified) | -| zh-TW, zh-HK, zh-Hant | Chinese (Traditional) | -| en-US, en, en-GB | English | -| ko-KR, ko | Korean | -| ja-JP, ja | Japanese | -| ru-RU, ru | Russian | -| fr-FR, fr | French | -| de-DE, de | German | -| es-ES, es | Spanish | -| pt-BR, pt | Portuguese | -| *unknown* | Returns the locale code as-is | - ---- - -## Testing - -### Build Verification -```bash -go build ./internal/application/service -# ✅ Builds without errors -``` - -### Language Mapping Test Cases - -```go -// Test cases for LanguageLocaleName() with wiki language codes -types.LanguageLocaleName("zh") // → "Chinese (Simplified)" -types.LanguageLocaleName("en") // → "English" -types.LanguageLocaleName("ko") // → "Korean" -types.LanguageLocaleName("ja") // → "Japanese" -types.LanguageLocaleName("unknown") // → "unknown" -``` - ---- - -## Files Modified - -| File | Changes | Lines | Type | -|------|---------|-------|------| -| `internal/application/service/wiki_ingest.go` | Replaced hardcoded language logic with `types.LanguageLocaleName()` call | 135-139 | Refactoring | -| `internal/types/context_helpers.go` | No changes (already exists) | 85-112 | Reused | -| `internal/middleware/language.go` | No changes (existing infrastructure) | All | Reused | - ---- - -## Related Documentation - -### Background Analysis -- **File:** `LANGUAGE_MIDDLEWARE_ANALYSIS.md` -- **Content:** Comprehensive analysis of existing language middleware infrastructure and refactoring recommendations - -### Key Infrastructure Components -1. **Middleware:** `internal/middleware/language.go` - - HTTP request language detection via Accept-Language header - - Environment variable override (WEKNORA_LANGUAGE) - - Automatic context injection - -2. **Context Helpers:** `internal/types/context_helpers.go` - - `EnvLanguage()` - Read WEKNORA_LANGUAGE env var - - `DefaultLanguage()` - Get default language with fallback - - `LanguageFromContext()` - Extract locale from context - - `LanguageNameFromContext()` - Get human-readable name from context - - `LanguageLocaleName()` - **THE KEY FUNCTION USED IN THIS REFACTORING** - ---- - -## Future Improvements (Optional) - -### 1. Schema Normalization (Lower Priority) -Currently `WikiConfig.WikiLanguage` stores short codes ("zh", "en"). -Consider normalizing to full locale codes ("zh-CN", "en-US") for consistency with middleware. - -**Migration Path:** -```go -func normalizeWikiLanguage(shortCode string) string { - switch shortCode { - case "zh": - return "zh-CN" - case "en": - return "en-US" - default: - return shortCode - } -} -``` - -### 2. Context-Based Fallback (Lower Priority) -If `WikiConfig.WikiLanguage` is empty, could fallback to request language from context: - -```go -lang := kb.WikiConfig.WikiLanguage -if lang == "" { - lang, _ = types.LanguageFromContext(ctx) - if lang == "" { - lang = types.DefaultLanguage() - } -} -humanReadableLang := types.LanguageLocaleName(lang) -``` - ---- - -## Verification Checklist - -- [x] Code change applied to wiki_ingest.go -- [x] Build verification passed -- [x] Imports are correct (types already imported) -- [x] Comments updated with explanation -- [x] Language mapping covers all original cases (zh → Chinese, en → English) -- [x] Additional languages now supported (9+ languages) -- [x] No breaking changes (same function behavior) -- [x] Documentation updated - ---- - -## Summary - -This refactoring successfully eliminates code duplication by reusing the existing `LanguageLocaleName()` infrastructure from the middleware layer. The change is minimal (4 lines), low-risk (no schema changes), and provides immediate benefits: - -- **Maintainability:** Single source of truth for language mappings -- **Extensibility:** Supports 9+ languages instead of 2 -- **Consistency:** Uniform language naming across the entire application -- **Code Quality:** Cleaner, more focused code - -**Status:** Ready for deployment. No migration or additional testing required. diff --git a/LANGUAGE_REFACTORING_QUICK_REFERENCE.md b/LANGUAGE_REFACTORING_QUICK_REFERENCE.md deleted file mode 100644 index 0eebe366..00000000 --- a/LANGUAGE_REFACTORING_QUICK_REFERENCE.md +++ /dev/null @@ -1,111 +0,0 @@ -# Language Middleware Refactoring - Quick Reference - -## TL;DR - -Replace 6 lines of hardcoded language logic in `wiki_ingest.go` with 1 line that reuses tested infrastructure. - -## What to Change - -**File:** `/internal/application/service/wiki_ingest.go` -**Lines:** 135-141 -**Method:** `ProcessWikiIngest()` - -### Simple Copy-Paste Replacement - -```go -// OLD CODE (delete this): - // Determine language - lang := "the same language as the source document" - if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" - } else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" - } - -// NEW CODE (replace with this): - // Determine language - lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -## Key Benefits - -| Aspect | Before | After | -|--------|--------|-------| -| Languages Supported | 2 (zh, en) | 9+ (zh, en, ko, ja, ru, fr, de, es, pt) | -| Code Lines | 6 | 1 | -| Consistency | Varies | Unified middleware naming | -| Maintenance | Hardcoded | Centralized in `context_helpers.go` | -| Extension Cost | High | Low | - -## No Breaking Changes - -✅ Existing code works as-is -✅ No database migration needed -✅ No API changes -✅ Fully backward compatible - -## Function Reference - -**Function:** `types.LanguageLocaleName(locale string) string` -**Location:** `/internal/types/context_helpers.go` lines 85-112 -**Already imported in wiki_ingest.go:** ✅ Yes (line 14) - -**Supported Inputs:** - -``` -"zh-CN" or "zh" → "Chinese (Simplified)" -"zh-TW" or "zh-HK" → "Chinese (Traditional)" -"en-US" or "en" → "English" -"ko-KR" or "ko" → "Korean" -"ja-JP" or "ja" → "Japanese" -"ru-RU" or "ru" → "Russian" -"fr-FR" or "fr" → "French" -"de-DE" or "de" → "German" -"es-ES" or "es" → "Spanish" -"pt-BR" or "pt" → "Portuguese" -[any unknown] → returns the input as-is -``` - -## Testing - -### Quick Test -```bash -cd /Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora -go test -v ./internal/types -go test -v ./internal/application/service -``` - -### Manual Verification -```go -// In your test: -fmt.Println(types.LanguageLocaleName("zh")) // Should print: Chinese (Simplified) -fmt.Println(types.LanguageLocaleName("en")) // Should print: English -fmt.Println(types.LanguageLocaleName("ko")) // Should print: Korean -``` - -## Related Documentation - -- Full analysis: `LANGUAGE_MIDDLEWARE_ANALYSIS.md` -- Implementation plan: `REFACTORING_PLAN.md` -- Main analysis: `AGENT_WIKI_ANALYSIS.md` - -## Files Involved - -| File | Purpose | Action | -|------|---------|--------| -| `/internal/middleware/language.go` | Language extraction middleware | Reference only | -| `/internal/types/context_helpers.go` | Language mapping functions | Reuse `LanguageLocaleName()` | -| `/internal/application/service/wiki_ingest.go` | Wiki ingest service | Update lines 135-141 | - -## Implementation Checklist - -- [ ] Open `wiki_ingest.go` -- [ ] Find lines 135-141 -- [ ] Delete the 6-line language logic -- [ ] Replace with `lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage)` -- [ ] Save file -- [ ] Run tests: `go test ./internal/...` -- [ ] Commit changes - -That's it! 🎉 - diff --git a/LANGUAGE_REFACTORING_README.md b/LANGUAGE_REFACTORING_README.md deleted file mode 100644 index 8adbcf0f..00000000 --- a/LANGUAGE_REFACTORING_README.md +++ /dev/null @@ -1,287 +0,0 @@ -# Language Infrastructure Refactoring - README - -**Status:** ✅ COMPLETED & COMMITTED -**Commit Hash:** 9913fac4 -**Date:** 2026-04-07 - ---- - -## Quick Summary - -This refactoring successfully eliminated code duplication in the wiki ingest service by reusing existing language infrastructure from the middleware layer. - -### The Change in One Picture - -```go -// BEFORE: 7 lines, 2 languages supported -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} - -// AFTER: 4 lines, 9+ languages supported -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -### Key Achievements - -✅ **43% Code Reduction:** 7 lines → 4 lines -✅ **350% Language Support:** 2 → 9+ languages -✅ **100% Test Coverage:** 30 unit tests, all passing -✅ **Zero Breaking Changes:** Backward compatible -✅ **Performance Optimized:** ~4.3 nanoseconds per call -✅ **Production Ready:** Build successful, tests passing - ---- - -## What Was Changed - -### Primary Change -**File:** `internal/application/service/wiki_ingest.go` -**Line:** 139 -**Change:** Language determination now uses `types.LanguageLocaleName()` - -### New Files -1. **`internal/types/context_helpers_test.go`** - Comprehensive unit tests (30 test cases) -2. **`LANGUAGE_MIDDLEWARE_ANALYSIS.md`** - Pre-refactoring analysis -3. **`LANGUAGE_REFACTORING_COMPLETED.md`** - Completion report -4. **`IMPLEMENTATION_GUIDE.md`** - Full implementation guide -5. **`REFACTORING_SUMMARY.txt`** - Quick reference summary - ---- - -## Supported Languages - -The refactored code now supports 9+ languages: - -| Language | Code(s) | -|----------|---------| -| Chinese (Simplified) | zh-CN, zh, zh-Hans | -| Chinese (Traditional) | zh-TW, zh-HK, zh-Hant | -| English | en-US, en, en-GB | -| Korean | ko-KR, ko | -| Japanese | ja-JP, ja | -| Russian | ru-RU, ru | -| French | fr-FR, fr | -| German | de-DE, de | -| Spanish | es-ES, es | -| Portuguese | pt-BR, pt | - ---- - -## Test Results - -### Unit Tests -```bash -✅ PASS: TestLanguageLocaleName (30 test cases) - - All language families covered - - All locale variants tested - - Edge cases handled - -✅ PASS: BenchmarkLanguageLocaleName - - 288,239,468 ops/sec - - ~4.3 nanoseconds per call -``` - -### Build Verification -```bash -✅ go build ./internal/application/service (success) -✅ go build ./cmd/server (success, 243MB binary) -✅ No errors or warnings (except safe dependency warnings) -``` - ---- - -## Implementation Details - -### Core Function -**Location:** `internal/types/context_helpers.go` (lines 85-112) -**Function:** `LanguageLocaleName(locale string) string` -**Purpose:** Maps locale codes to human-readable language names - -### Related Infrastructure -- **Middleware:** `internal/middleware/language.go` - Detects language from HTTP headers -- **Context Helpers:** `internal/types/context_helpers.go` - Language extraction functions -- **Router:** `internal/router/router.go` (line 85) - Middleware registration - ---- - -## Backward Compatibility - -✅ **NO BREAKING CHANGES** - -- Same function signatures -- Same input/output types -- Identical behavior for all existing inputs -- No database schema changes -- No API changes required -- Migration: None (transparent improvement) - ---- - -## Performance Impact - -**Function Call Overhead:** ~4.3 nanoseconds per call - -**Analysis:** -- Negligible compared to LLM calls (seconds) -- Simple O(1) switch statement -- No memory allocations -- No I/O operations - -**Conclusion:** No measurable performance impact on production - ---- - -## Deployment Checklist - -✅ Code changes completed -✅ Unit tests created and passing -✅ Integration tests passing -✅ Build successful -✅ Performance verified -✅ Backward compatibility confirmed -✅ Documentation complete -✅ Code review ready -✅ No database migrations needed -✅ Ready for deployment - ---- - -## How to Verify - -### Run Tests -```bash -# Run language-specific unit tests -go test -v ./internal/types -run TestLanguageLocaleName - -# Run benchmark -go test -bench=. ./internal/types -run BenchmarkLanguageLocaleName - -# Run all tests in types package -go test ./internal/types -v -``` - -### Verify Build -```bash -# Build application -go build -o /tmp/weknora ./cmd/server - -# Build service package -go build ./internal/application/service - -# Build types package -go build ./internal/types -``` - -### Test Language Mapping -```go -// In Go code -types.LanguageLocaleName("zh") // → "Chinese (Simplified)" -types.LanguageLocaleName("en") // → "English" -types.LanguageLocaleName("ko") // → "Korean" -types.LanguageLocaleName("unknown") // → "unknown" -``` - ---- - -## Documentation Files - -| File | Purpose | Size | -|------|---------|------| -| **LANGUAGE_MIDDLEWARE_ANALYSIS.md** | Pre-refactoring analysis and recommendations | 349 KB | -| **LANGUAGE_REFACTORING_COMPLETED.md** | Post-refactoring completion report | 234 KB | -| **IMPLEMENTATION_GUIDE.md** | Complete implementation guide with examples | 410 KB | -| **REFACTORING_SUMMARY.txt** | Quick reference summary | 257 KB | -| **This File** | Quick start README | - | - ---- - -## Future Enhancements (Optional) - -### 1. Schema Normalization -- Normalize `WikiConfig.WikiLanguage` from short codes ("zh") to full locale codes ("zh-CN") -- Requires database migration -- Priority: Low - -### 2. UI Language Support -- Add all 9+ languages to knowledge base creation UI -- Update language dropdown in frontend -- Priority: Medium - -### 3. Automatic Language Detection -- Detect document language automatically -- Integrate language detection library -- Priority: Low - ---- - -## Questions & Support - -### How to Review Changes -1. Look at commit `9913fac4` -2. Focus on `internal/application/service/wiki_ingest.go` line 139 -3. Review test coverage in `internal/types/context_helpers_test.go` -4. Read `IMPLEMENTATION_GUIDE.md` for full context - -### Common Questions - -**Q: Will this break existing code?** -A: No. All existing inputs produce identical outputs. It's a transparent improvement. - -**Q: Why refactor just 4 lines?** -A: Those 4 lines represent hardcoded, duplicated logic that should be in a shared utility. The refactoring improves maintainability and consistency across the codebase. - -**Q: What about performance?** -A: Function call overhead is ~4.3 nanoseconds - negligible compared to LLM calls that take seconds. - -**Q: Do I need to migrate data?** -A: No. No schema changes. The refactoring is transparent to the database and API. - ---- - -## Commit Information - -``` -Commit: 9913fac4b386a326cb16763c9b7be248da9ea4a1 -Author: wizardchen -Date: Tue Apr 7 13:52:55 2026 +0800 - -refactor: Replace hardcoded language logic with middleware infrastructure -``` - -**Files Changed:** 6 -**Insertions:** 1,919 -**Deletions:** 0 - ---- - -## Quick Navigation - -- 🚀 **Getting Started:** Read sections: "Quick Summary", "What Was Changed" -- 📊 **Technical Details:** Read: "IMPLEMENTATION_GUIDE.md" -- 🧪 **Testing:** Run commands in "How to Verify" -- 📖 **Full Analysis:** Read: "LANGUAGE_MIDDLEWARE_ANALYSIS.md" -- ✅ **Verification:** Check: "LANGUAGE_REFACTORING_COMPLETED.md" - ---- - -## Summary - -This refactoring successfully improves code quality by: -- Eliminating duplication -- Reusing existing, tested infrastructure -- Supporting more languages -- Improving maintainability -- Maintaining backward compatibility -- Providing comprehensive test coverage - -**Status: Ready for production deployment.** ✅ - ---- - -*Last Updated: 2026-04-07* -*Version: 1.0* -*Status: Completed & Committed* diff --git a/PROJECT_COMPLETION_REPORT.md b/PROJECT_COMPLETION_REPORT.md deleted file mode 100644 index 97d1d376..00000000 --- a/PROJECT_COMPLETION_REPORT.md +++ /dev/null @@ -1,477 +0,0 @@ -# WeKnora Analysis Project - Completion Report - -**Project Status:** ✅ COMPLETE -**Completion Date:** 2026-04-07 -**Total Duration:** 2 Analysis Sessions -**Overall Quality:** Production-Ready - ---- - -## Executive Summary - -Successfully completed comprehensive analysis of WeKnora Agent architecture and implemented language infrastructure refactoring. All deliverables are documented, tested, and ready for production deployment. - -### Key Achievements - -1. **Agent Architecture Analysis** (Session 1) - - ✅ Documented complete ReAct engine implementation - - ✅ Traced automatic tool dispatch mechanism - - ✅ Analyzed system prompts and tool registration - - ✅ Answered all 4 original research questions - -2. **Language Infrastructure Discovery** (Session 2) - - ✅ Identified existing centralized language mapping - - ✅ Found code reuse opportunity (6 lines → 1 line) - - ✅ Expanded language support (2 → 9+ languages) - -3. **Refactoring Implementation** (Session 2) - - ✅ Implemented single-line refactoring - - ✅ Verified with 28 unit tests (all passing) - - ✅ Confirmed 100% backward compatibility - - ✅ Build verified with zero errors - -4. **Comprehensive Documentation** (Both Sessions) - - ✅ Created 9 detailed analysis documents - - ✅ ~3,000 lines of documentation - - ✅ ~100 KB of detailed technical guidance - - ✅ Multiple navigation paths for different scenarios - ---- - -## Deliverables Summary - -### Code Changes -``` -File Modified: internal/application/service/wiki_ingest.go -Line 139: Language determination refactored -Before: 6 lines of hardcoded if/else logic -After: 1 line calling types.LanguageLocaleName() -Impact: 83% code reduction, 9+ language support, centralized maintenance -``` - -### Documentation Files Created - -#### Core Analysis Documents (4 files) -1. **AGENT_WIKI_ANALYSIS.md** (16 KB) - - Complete Agent ReAct engine documentation - - Architecture, tool dispatch, system prompts - - Status: Complete, verified - -2. **LANGUAGE_MIDDLEWARE_ANALYSIS.md** (11 KB) - - Infrastructure discovery and analysis - - Problem identification and solution design - - Status: Complete, verified - -3. **REFACTORING_PLAN.md** (6.3 KB) - - Implementation strategy with code diffs - - Testing and deployment planning - - Status: Complete, verified - -4. **REFACTORING_IMPLEMENTATION_REPORT.md** (7.8 KB) - - Implementation verification and test results - - Deployment checklist and rollback plan - - Status: Complete, verified - -#### Quick Reference and Navigation (5 files) -5. **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** (3.0 KB) - - Quick start guide for developers - - Copy-paste ready implementation - - Status: Complete, ready to use - -6. **ANALYSIS_SUMMARY.md** (11 KB) - - Executive summary of all findings - - Recommendations by timeline - - Status: Complete, verified - -7. **README_ANALYSIS.md** (13 KB) - - Navigation index and roadmap - - Multiple quick-start paths - - Status: Complete, comprehensive - -8. **SESSION_2_COMPLETION_SUMMARY.md** (13 KB) - - Session completion summary - - Status checklist and future roadmap - - Status: Complete, verified - -9. **INDEX_ALL_ANALYSIS.md** (17 KB) - - Complete project index - - Document dependency map - - Navigation by scenario - - Status: Complete, comprehensive - -#### Additional Documentation -- **PROJECT_COMPLETION_REPORT.md** (This file) - - Final completion verification - - Quality assurance summary - - Status: Complete - ---- - -## Quality Assurance - -### Code Quality Verification -- ✅ **Build Status:** Success (go build ./internal/application/service) -- ✅ **Compilation Errors:** 0 -- ✅ **Compiler Warnings:** 0 -- ✅ **Unit Tests:** 28/28 passing -- ✅ **Test Coverage:** 100% of supported locales - -### Backward Compatibility -- ✅ **Schema Changes:** 0 (no migration needed) -- ✅ **API Changes:** 0 (no contract breaks) -- ✅ **Configuration Changes:** 0 (existing configs work) -- ✅ **Runtime Impact:** None (drop-in replacement) - -### Documentation Quality -- ✅ **Technical Accuracy:** Verified against codebase -- ✅ **Completeness:** All questions answered -- ✅ **Code Examples:** All tested and working -- ✅ **Cross-References:** Comprehensive linkage - -### Deployment Readiness -- ✅ **Risk Assessment:** Low (isolated change) -- ✅ **Testing:** Complete -- ✅ **Documentation:** Comprehensive -- ✅ **Rollback Plan:** Available if needed -- ✅ **Production Ready:** Yes - ---- - -## Project Statistics - -### Code Metrics -| Metric | Value | -|--------|-------| -| **Files Modified** | 1 | -| **Lines Changed** | 6 → 1 (-83%) | -| **Languages Supported** | 2 → 9+ (+350%) | -| **Locale Variants** | 20+ total | -| **Build Time** | < 1 second | -| **Unit Tests Passing** | 28/28 (100%) | - -### Documentation Metrics -| Metric | Value | -|--------|-------| -| **Total Documents** | 10 | -| **Total Lines** | ~3,000 | -| **Total Size** | ~100 KB | -| **Average Doc Size** | 300 lines | -| **Read Time (All)** | 90-120 minutes | -| **Navigation Paths** | 5 different scenarios | - -### Coverage Metrics -| Aspect | Coverage | -|--------|----------| -| **Code Questions** | 4/4 (100%) | -| **Languages Supported** | 9+ (95%+ of market) | -| **Test Coverage** | 28 test cases | -| **Future Phases** | 5 documented | -| **Risk Mitigation** | Complete | - ---- - -## Technical Details - -### Language Support Matrix - -**Current Implementation (Post-Refactoring):** -``` -Locale Code → Language Name -zh-CN → Chinese (Simplified) -zh → Chinese (Simplified) -zh-Hans → Chinese (Simplified) -en-US → English -en → English -en-GB → English -ko-KR → Korean -ko → Korean -ja-JP → Japanese -ja → Japanese -ru-RU → Russian -ru → Russian -fr-FR → French -fr → French -de-DE → German -de → German -es-ES → Spanish -es → Spanish -pt-BR → Portuguese -pt → Portuguese -[unknown] → [returned unchanged] -``` - -**Comparison:** -- Before: 2 languages (zh, en) - hardcoded -- After: 9+ languages - centralized, maintainable -- Expansion Capability: Add new languages in 1 location - ---- - -## Deployment Instructions - -### Prerequisites -- ✅ Go 1.18+ (project already uses this) -- ✅ types package imported (already present) -- ✅ No environment variable changes needed -- ✅ No configuration changes needed - -### Deployment Steps -```bash -# 1. Update code (already done) -git add internal/application/service/wiki_ingest.go - -# 2. Commit changes -git commit -m "refactor: consolidate language mapping to reuse middleware infrastructure - -- Replace 6 lines of hardcoded language logic in wiki_ingest.go with single-line call -- Now uses types.LanguageLocaleName() centralized function -- Expands language support from 2 to 9+ languages -- 83% code reduction, no behavior changes, 100% backward compatible -- Tested: 28 unit tests passing, build verified" - -# 3. Build verification (optional, pre-deployment) -go build ./internal/application/service - -# 4. Run tests (optional, pre-deployment) -go test ./internal/types -v - -# 5. Deploy to production (no special handling needed) -# Standard deployment process applies -``` - -### Post-Deployment Verification -```bash -# Verify function is being called correctly -grep -n "LanguageLocaleName" internal/application/service/wiki_ingest.go - -# Expected output: -# 139: lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) - -# Verify language output in logs (should see full language names in wiki prompts) -# Look for: "Chinese (Simplified)", "English", "Korean", etc. -``` - ---- - -## Testing Summary - -### Unit Test Results - -**Test Suite:** TestLanguageLocaleName -**Total Cases:** 28 -**Pass Rate:** 100% (28/28) - -**Test Coverage:** -- Chinese (Simplified): 3 variants tested ✅ -- Chinese (Traditional): 3 variants tested ✅ -- English: 3 variants tested ✅ -- Korean: 2 variants tested ✅ -- Japanese: 2 variants tested ✅ -- Russian: 2 variants tested ✅ -- French: 2 variants tested ✅ -- German: 2 variants tested ✅ -- Spanish: 2 variants tested ✅ -- Portuguese: 2 variants tested ✅ -- Edge cases: 2 tests (unknown, empty) ✅ - -### Build Verification -``` -Command: go build ./internal/application/service -Result: SUCCESS ✅ -Output: (no errors or warnings) -``` - -### Integration Points -- ✅ wiki_ingest.go line 139 - Language determination -- ✅ wiki_ingest.go lines 166, 240, 304, 413 - LLM prompt templates use language variable -- ✅ types package import verified (line 14) -- ✅ Function available in all service layers - ---- - -## Risk Assessment - -### Implementation Risk: **LOW** - -**Risk Factors:** -- [Low Risk] Single file modification (wiki_ingest.go) -- [Low Risk] Drop-in replacement (function signature compatible) -- [Low Risk] No database changes -- [Low Risk] No API changes -- [Low Risk] 100% backward compatible -- [Low Risk] Well-tested function used (28 tests) - -**Mitigation Strategies:** -- ✅ Comprehensive unit test coverage -- ✅ Build verification passes -- ✅ Rollback plan documented -- ✅ No breaking changes - -**Overall Risk Rating:** ⭐ MINIMAL - ---- - -## Future Enhancement Roadmap - -### Phase 2: Extended Language Coverage -**Timeline:** 1-2 weeks -**Effort:** Minimal -**Location:** `/internal/types/context_helpers.go` -```go -case "it-IT", "it": - return "Italian" -case "nl-NL", "nl": - return "Dutch" -case "sv-SE", "sv": - return "Swedish" -``` - -### Phase 3: Language-Specific LLM Optimization -**Timeline:** 2-4 weeks -**Effort:** Moderate -**Goal:** Optimize language names for different LLM models - -### Phase 4: Document Language Detection -**Timeline:** 1 month -**Effort:** Moderate to High -**Goal:** Automatically detect and use document language - -### Phase 5: Multi-Language Wiki Pages -**Timeline:** 6-8 weeks -**Effort:** High -**Goal:** Support bi-lingual content and per-page language overrides - ---- - -## Documentation Navigation - -### For Different Audiences - -**For Managers:** -- Read: SESSION_2_COMPLETION_SUMMARY.md (15 min) -- Then: ANALYSIS_SUMMARY.md (10 min) - -**For Developers:** -- Read: LANGUAGE_REFACTORING_QUICK_REFERENCE.md (5 min) -- Then: REFACTORING_IMPLEMENTATION_REPORT.md (10 min) -- Deploy using the quick reference - -**For Architects:** -- Read: AGENT_WIKI_ANALYSIS.md (20 min) -- Then: LANGUAGE_MIDDLEWARE_ANALYSIS.md (15 min) -- Then: REFACTORING_PLAN.md (10 min) - -**For New Team Members:** -- Start: INDEX_ALL_ANALYSIS.md (5 min) -- Then: README_ANALYSIS.md (15 min) -- Then: Follow 1-hour deep-dive path - ---- - -## Version Control - -### Files Modified -``` -internal/application/service/wiki_ingest.go - Line 139: Language determination refactored -``` - -### Files Analyzed (Not Modified) -``` -internal/agent/engine.go -internal/agent/act.go -internal/agent/prompts.go -internal/agent/prompts_wiki.go -internal/agent/tools/wiki_tools.go -internal/agent/tools/definitions.go -internal/application/service/agent_service.go -internal/middleware/language.go -internal/types/context_helpers.go -``` - -### Documentation Created (10 files) -``` -/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/ -├── AGENT_WIKI_ANALYSIS.md -├── LANGUAGE_MIDDLEWARE_ANALYSIS.md -├── REFACTORING_PLAN.md -├── LANGUAGE_REFACTORING_QUICK_REFERENCE.md -├── ANALYSIS_SUMMARY.md -├── README_ANALYSIS.md -├── REFACTORING_IMPLEMENTATION_REPORT.md -├── SESSION_2_COMPLETION_SUMMARY.md -├── INDEX_ALL_ANALYSIS.md -└── PROJECT_COMPLETION_REPORT.md (this file) -``` - ---- - -## Success Criteria - Final Verification - -✅ **All Original Questions Answered** -1. How does Agent ReAct engine dispatch tools? → Documented -2. What system prompts does Agent use? → Documented -3. How does Agent discover wiki tools? → Documented -4. Is there a dedicated wiki system prompt? → Documented - -✅ **Refactoring Complete** -- Code change implemented ✅ -- Tests passing ✅ -- Build verified ✅ -- Backward compatible ✅ - -✅ **Documentation Complete** -- 10 comprehensive documents ✅ -- Multiple navigation paths ✅ -- Code examples included ✅ -- Deployment ready ✅ - -✅ **Production Ready** -- Risk assessment: Low ✅ -- Testing: Complete ✅ -- Quality: Verified ✅ -- Documentation: Comprehensive ✅ - ---- - -## Conclusion - -### Project Status: ✅ COMPLETE - -All objectives have been achieved: - -1. **Research Phase:** Completed with comprehensive Agent architecture analysis -2. **Implementation Phase:** Refactoring completed, tested, and verified -3. **Documentation Phase:** 10 detailed documents created and organized -4. **Quality Assurance:** All tests passing, build verified, backward compatible -5. **Deployment Readiness:** Low risk, well-documented, ready for production - -The project successfully demonstrates: -- Thorough codebase analysis capabilities -- Effective refactoring opportunities identification -- Comprehensive documentation practices -- Production-ready quality standards - -### Ready for Production Deployment ✅ - -**Next Step:** Deploy refactoring and continue with Phase 2 enhanced language support. - ---- - -## Contact and Support - -**For Project Questions:** -- Architecture: See AGENT_WIKI_ANALYSIS.md -- Refactoring: See LANGUAGE_REFACTORING_QUICK_REFERENCE.md -- Strategy: See REFACTORING_PLAN.md -- Verification: See REFACTORING_IMPLEMENTATION_REPORT.md -- Navigation: See INDEX_ALL_ANALYSIS.md or README_ANALYSIS.md - ---- - -**Project Created:** 2026-04-07 -**Project Status:** ✅ COMPLETE -**Quality Level:** Production-Ready -**Last Updated:** 2026-04-07 - -**Overall Project Score:** ⭐⭐⭐⭐⭐ (5/5) diff --git a/PROJECT_INDEX.md b/PROJECT_INDEX.md deleted file mode 100644 index f5af5f6c..00000000 --- a/PROJECT_INDEX.md +++ /dev/null @@ -1,406 +0,0 @@ -# WeKnora Wiki Feature - Project Index & Navigation - -**Project Status:** ✅ COMPLETE & PRODUCTION READY -**Completion Date:** April 7, 2026 -**Last Updated:** April 7, 2026 - ---- - -## 📋 Quick Navigation Guide - -### 🚀 Getting Started -Start here if you're new to the wiki feature: -1. **[EXECUTIVE_SUMMARY.md](EXECUTIVE_SUMMARY.md)** - High-level overview and key metrics -2. **[README_WIKI_FEATURE.md](README_WIKI_FEATURE.md)** - Complete feature guide and API reference -3. **[START_HERE.md](START_HERE.md)** - Step-by-step getting started guide - -### 📚 Documentation -Detailed documentation for specific areas: -- **[DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md)** - Production deployment guide -- **[FINAL_COMPLETION_SUMMARY.md](FINAL_COMPLETION_SUMMARY.md)** - Detailed completion report -- **[LANGUAGE_REFACTORING_QUICK_REFERENCE.md](LANGUAGE_REFACTORING_QUICK_REFERENCE.md)** - Language infrastructure guide - -### 🔍 Analysis & Design -Architecture and planning documents: -- **[LANGUAGE_MIDDLEWARE_ANALYSIS.md](LANGUAGE_MIDDLEWARE_ANALYSIS.md)** - Infrastructure analysis -- **[AGENT_WIKI_ANALYSIS.md](AGENT_WIKI_ANALYSIS.md)** - Agent tool analysis -- **[REFACTORING_PLAN.md](REFACTORING_PLAN.md)** - Project planning -- **[INDEX_ALL_ANALYSIS.md](INDEX_ALL_ANALYSIS.md)** - Complete analysis index -- **[ARCHITECTURE_DIAGRAM.md](.ARCHITECTURE_DIAGRAM.md)** - System architecture - -### 💻 Source Code - -#### Backend Core (14 files) -``` -internal/ -├── types/ -│ ├── wiki_page.go (168 lines) -│ │ └── WikiPage, WikiPageStatus, WikiPageType definitions -│ └── interfaces/wiki_page.go -│ └── WikiPageService, WikiPageRepository interfaces -│ -├── application/repository/ -│ └── wiki_page.go (249 lines) -│ └── GORM repository implementation with CRUD operations -│ -├── application/service/ -│ ├── wiki_page.go (492 lines) -│ │ └── Business logic for wiki operations -│ ├── wiki_ingest.go (560 lines) -│ │ └── Automated wiki generation pipeline -│ ├── wiki_lint.go (304 lines) -│ │ └── Wiki maintenance and validation -│ └── chat_pipeline/ -│ └── wiki_boost.go (89 lines) -│ └── Chat retrieval enhancement -│ -├── handler/ -│ └── wiki_page.go (482 lines) -│ └── HTTP endpoints (GET, POST, PUT, DELETE, search) -│ -├── agent/ -│ ├── prompts_wiki.go (127 lines) -│ │ └── LLM prompt templates -│ └── tools/ -│ └── wiki_tools.go (442 lines) -│ └── Agent tools for wiki interaction -│ -├── router/router.go -│ └── Route registration -│ -└── container/container.go - └── Dependency injection setup -``` - -**Total Backend Code:** 2,464 lines - -#### Frontend (2 files) -``` -frontend/src/ -├── api/wiki/index.ts (106 lines) -│ └── Wiki API client -├── views/knowledge/wiki/ -│ └── WikiBrowser.vue (427 lines) -│ └── Wiki UI component -└── i18n/locales/ - ├── zh-CN.ts - ├── en-US.ts - ├── ko-KR.ts - └── ru-RU.ts - └── Multi-language support -``` - -#### Database -``` -migrations/versioned/ -├── 000032_wiki_pages.up.sql (57 lines) -│ └── Create wiki_pages table with indexes -└── 000032_wiki_pages.down.sql (9 lines) - └── Drop wiki_pages table -``` - -### 🧪 Tests (5 files) -- `internal/types/wiki_page_test.go` - Type tests -- `internal/types/context_helpers_test.go` - Language tests (30+ cases) -- `internal/application/service/wiki_page_test.go` - Service tests -- `internal/application/service/wiki_ingest_test.go` - Pipeline tests -- `internal/agent/tools/wiki_tools_test.go` - Agent tool tests - -**Test Summary:** -- **Total Test Cases:** 50+ -- **All Tests:** ✅ PASSING -- **Coverage:** >90% on core logic - ---- - -## 🔗 Documentation by Topic - -### API Reference -- Endpoint list: [README_WIKI_FEATURE.md - API Endpoints](README_WIKI_FEATURE.md#api-endpoints) -- Request/response examples: [README_WIKI_FEATURE.md - API Reference](README_WIKI_FEATURE.md#api-endpoints) -- Handler implementation: `internal/handler/wiki_page.go` - -### Database Schema -- Table structure: [README_WIKI_FEATURE.md - Database Schema](README_WIKI_FEATURE.md#database-schema) -- Migration files: `migrations/versioned/000032_wiki_pages.*.sql` -- Repository implementation: `internal/application/repository/wiki_page.go` - -### Data Models -- WikiPage type: `internal/types/wiki_page.go` -- WikiConfig: `internal/types/knowledgebase.go` -- Interface definitions: `internal/types/interfaces/wiki_page.go` - -### Service Layer -- WikiPageService: `internal/application/service/wiki_page.go` -- WikiIngestService: `internal/application/service/wiki_ingest.go` -- WikiLintService: `internal/application/service/wiki_lint.go` -- WikiBoostService: `internal/application/service/chat_pipeline/wiki_boost.go` - -### Agent Integration -- Wiki tools: `internal/agent/tools/wiki_tools.go` -- LLM prompts: `internal/agent/prompts_wiki.go` -- Tool definitions: `internal/agent/tools/definitions.go` - -### Language Support -- Language mapping: `internal/types/context_helpers.go` -- Language middleware: `internal/middleware/language.go` -- i18n strings: `frontend/src/i18n/locales/` -- Language refactoring guide: [LANGUAGE_REFACTORING_QUICK_REFERENCE.md](LANGUAGE_REFACTORING_QUICK_REFERENCE.md) - -### Configuration -- Container setup: `internal/container/container.go` -- Router configuration: `internal/router/router.go` -- Task handling: `internal/router/task.go` - ---- - -## 📊 Project Statistics - -### Code Metrics -| Metric | Value | -|--------|-------| -| **Backend Files** | 14 | -| **Frontend Files** | 2 | -| **Test Files** | 5 | -| **Database Migrations** | 2 | -| **Total Lines of Code** | 2,464 | -| **Documentation Files** | 15+ | - -### Feature Metrics -| Feature | Count | -|---------|-------| -| **Page Types** | 6 | -| **API Endpoints** | 8 | -| **Service Classes** | 5 | -| **Supported Languages** | 9+ | -| **Test Cases** | 50+ | - -### Quality Metrics -| Metric | Status | -|--------|--------| -| **Build** | ✅ Passing (243MB) | -| **Tests** | ✅ 50/50 Passing | -| **Coverage** | ✅ >90% on core | -| **Performance** | ✅ 4.3 ns/op | -| **Security** | ✅ No issues | -| **Documentation** | ✅ 100% coverage | - ---- - -## 🚀 Deployment Path - -### 1. Pre-Deployment -- Review: [EXECUTIVE_SUMMARY.md](EXECUTIVE_SUMMARY.md) -- Checklist: [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) - Pre-Deployment Verification - -### 2. Staging Deployment -Follow: [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) - Deployment Steps > Pre-Production - -### 3. Production Deployment -Follow: [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) - Deployment Steps > Production Deployment - -### 4. Post-Deployment -- Monitor: [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) - Post-Deployment Monitoring -- Troubleshoot: [README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#troubleshooting) - ---- - -## 📖 Reading Order by Role - -### For Project Managers -1. **[EXECUTIVE_SUMMARY.md](EXECUTIVE_SUMMARY.md)** - Overview and status -2. **[FINAL_COMPLETION_SUMMARY.md](FINAL_COMPLETION_SUMMARY.md)** - Detailed metrics -3. **[PROJECT_COMPLETION_REPORT.md](PROJECT_COMPLETION_REPORT.md)** - Full report - -### For Developers -1. **[README_WIKI_FEATURE.md](README_WIKI_FEATURE.md)** - Feature overview -2. **[internal/types/wiki_page.go](internal/types/wiki_page.go)** - Data models -3. **[internal/application/service/wiki_page.go](internal/application/service/wiki_page.go)** - Service layer -4. **[internal/application/service/wiki_ingest.go](internal/application/service/wiki_ingest.go)** - Pipeline -5. Test files - Examples and patterns - -### For DevOps/SRE -1. **[DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md)** - Deployment guide -2. **[README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#deployment)** - Deployment section -3. **[README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#troubleshooting)** - Troubleshooting - -### For QA/Testers -1. **[README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#testing)** - Testing guide -2. Test files in `internal/*/wiki_*_test.go` - Test examples -3. **[README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#api-endpoints)** - API endpoints to test - -### For Frontend Developers -1. **[frontend/src/api/wiki/index.ts](frontend/src/api/wiki/index.ts)** - API client -2. **[frontend/src/views/knowledge/wiki/WikiBrowser.vue](frontend/src/views/knowledge/wiki/WikiBrowser.vue)** - UI component -3. **[README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#api-endpoints)** - API reference - ---- - -## 🎯 Key Features at a Glance - -### Automated Wiki Generation ✅ -- Summary page generation -- Entity extraction -- Concept extraction -- Synthesis opportunity detection -- Index page rebuilding -- Log page maintenance - -### Multi-Language Support ✅ -- Chinese (Simplified/Traditional) -- English -- Korean -- Japanese -- Russian -- French -- German -- Spanish -- Portuguese - -### Smart Management ✅ -- CRUD operations -- Search and filtering -- Pagination support -- Page type organization -- Status tracking - -### User Interface ✅ -- Wiki browser component -- Knowledge base configuration -- Multi-language support -- Search functionality -- Responsive design - -### Integration ✅ -- Agent-based interaction -- Chat retrieval enhancement -- Async task processing -- Event-driven architecture -- Dependency injection - ---- - -## 🔐 Production Readiness - -### Code Quality ✅ -- [x] All tests passing -- [x] Build succeeds -- [x] No security issues -- [x] Code review requirements met -- [x] Documentation complete - -### Database ✅ -- [x] Migration files created -- [x] Schema validated -- [x] Indexes optimized -- [x] Foreign keys configured -- [x] Rollback capability verified - -### Documentation ✅ -- [x] README complete -- [x] API documentation -- [x] Deployment guide -- [x] Troubleshooting guide -- [x] Development guide - -### Testing ✅ -- [x] Unit tests: 50+ -- [x] Integration tests -- [x] Performance tests -- [x] Coverage: >90% -- [x] No critical issues - ---- - -## 📞 Support Resources - -### Quick Reference -- **API Endpoints:** [README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#api-endpoints) -- **Database Schema:** [README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#database-schema) -- **Troubleshooting:** [README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#troubleshooting) -- **Performance:** [README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#performance-metrics) - -### Detailed Guides -- **Deployment:** [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) -- **Architecture:** [LANGUAGE_MIDDLEWARE_ANALYSIS.md](LANGUAGE_MIDDLEWARE_ANALYSIS.md) -- **Development:** [README_WIKI_FEATURE.md](README_WIKI_FEATURE.md#development-guide) - -### Code Examples -- Test files: `internal/*/wiki_*_test.go` -- API handler: `internal/handler/wiki_page.go` -- Service layer: `internal/application/service/wiki_page.go` -- LLM prompts: `internal/agent/prompts_wiki.go` - ---- - -## 📊 Project Timeline - -| Date | Milestone | Status | -|------|-----------|--------| -| Session 1 | Language infrastructure refactoring | ✅ Complete | -| Session 2 | Wiki feature implementation | ✅ Complete | -| Apr 7, 2026 | Final testing and documentation | ✅ Complete | -| Apr 7, 2026 | Production deployment ready | ✅ Ready | - ---- - -## 🎓 Learning Resources - -### Architecture Patterns -- Handler → Service → Repository pattern -- Dependency Injection with container -- Async task processing with queues -- Database abstraction with GORM - -### Go Best Practices -- Interface-based design -- Error handling with context -- Comprehensive logging -- Type-safe operations - -### Testing Patterns -- Unit test organization -- Mock objects and fixtures -- Performance benchmarks -- Edge case coverage - -### Documentation Standards -- README structure -- API documentation -- Deployment guides -- Troubleshooting guides - ---- - -## 🔄 Workflow Summary - -**Development → Testing → Documentation → Deployment** - -1. **Implementation** - Backend, frontend, database -2. **Testing** - 50+ test cases, >90% coverage -3. **Documentation** - 15+ comprehensive guides -4. **Deployment** - Staging → Production - ---- - -## ✅ Final Checklist - -- [x] Code implemented -- [x] Tests passing -- [x] Build successful -- [x] Documentation complete -- [x] Deployment guide ready -- [x] Staging verified -- [x] Production ready - ---- - -## 📝 Last Update - -**Date:** April 7, 2026 -**Final Commit:** 39fab2b4 -**Status:** ✅ PROJECT COMPLETE AND PRODUCTION READY - ---- - -**For any questions or clarifications, refer to the appropriate documentation file listed above.** diff --git a/QUICK_FIX_GUIDE.md b/QUICK_FIX_GUIDE.md deleted file mode 100644 index 1457c38c..00000000 --- a/QUICK_FIX_GUIDE.md +++ /dev/null @@ -1,228 +0,0 @@ -# Quick Fix Guide: Wiki Config Update Bug - -⏱️ **Estimated Fix Time:** 5 minutes -📝 **Complexity:** Low (3 struct fields + 1 service method) -✅ **Backward Compatible:** Yes - ---- - -## The Problem - -Users can create a KB with wiki enabled, but **cannot update wiki settings** after creation. - -**Frontend sends:** `PUT /api/v1/knowledge-bases/{id} { config: { wiki_config: {...} } }` -**Backend receives:** Ignored (struct field missing) -**Result:** Changes don't save ❌ - ---- - -## The Solution: 3 Changes - -### Change 1: Add WikiConfig to KnowledgeBaseConfig - -**File:** `internal/types/knowledgebase.go` (Line 107) - -**BEFORE:** -```go -type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"` - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"` - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"` -} -``` - -**AFTER:** -```go -type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"` - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"` - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"` - WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config"` -} -``` - -**What to add:** One line after FAQConfig field ⬆️ - ---- - -### Change 2: Update UpdateKnowledgeBase Service - -**File:** `internal/application/service/knowledgebase.go` (Line 277) - -**BEFORE:** -```go -if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } -} -``` - -**AFTER:** -```go -if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig - } -} -``` - -**What to add:** 2-3 lines after FAQConfig handling ⬆️ - ---- - -### Change 3 (Optional): Update Frontend Type Hints - -**File:** `frontend/src/api/knowledge-base/index.ts` (Line 38) - -**In createKnowledgeBase function signature, add:** -```typescript -wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; -}; -``` - -**Why:** Improves IDE autocomplete for developers (not required for functionality) - ---- - -## Testing the Fix - -### Quick Test (30 seconds) - -1. Create new KB with wiki enabled -2. Edit the KB → Wiki Settings -3. Change synthesis model -4. Save -5. Reload the page -6. ✅ Model should still be changed - -### Full Test (2 minutes) - -```bash -# Run existing tests -go test ./internal/application/service/... -run TestUpdateKnowledgeBase - -# Or manually test via API: -# 1. Create KB without wiki -curl -X POST http://localhost:8080/api/v1/knowledge-bases \ - -H "Content-Type: application/json" \ - -d '{"name":"Test","type":"document"}' - -# 2. Update with wiki enabled -curl -X PUT http://localhost:8080/api/v1/knowledge-bases/{id} \ - -H "Content-Type: application/json" \ - -d '{"name":"Test","config":{"wiki_config":{"enabled":true,"synthesis_model_id":"gpt-4"}}}' - -# 3. Verify in response and DB -``` - ---- - -## Files Modified - -| File | Changes | Lines | -|------|---------|-------| -| `internal/types/knowledgebase.go` | Add 1 field | +1 | -| `internal/application/service/knowledgebase.go` | Add 2 lines | +2-3 | -| `frontend/src/api/knowledge-base/index.ts` | Add type hint | +6 (optional) | - -**Total:** ~10 LOC across 2-3 files - ---- - -## Verification Checklist - -- [ ] Go compiles without errors -- [ ] TypeScript compiles without errors (if frontend changed) -- [ ] Tests pass -- [ ] Can create KB with wiki_config -- [ ] Can update KB wiki_config -- [ ] Changes persist after page reload -- [ ] No regressions in other KB settings updates - ---- - -## Rollback (if needed) - -Simply revert your changes: -```bash -git diff internal/types/knowledgebase.go # See changes -git diff internal/application/service/knowledgebase.go # See changes -git checkout internal/types/knowledgebase.go # Undo -git checkout internal/application/service/knowledgebase.go # Undo -``` - ---- - -## Why This Happens - -The system uses two different struct types for KB operations: - -1. **Create:** Uses full `KnowledgeBase` struct → all fields work ✅ -2. **Update:** Uses `KnowledgeBaseConfig` struct → missing fields break ❌ - -Adding `WikiConfig` to `KnowledgeBaseConfig` bridges this gap. - ---- - -## References - -**For more details:** -- Full architecture: `KB_WIKI_ARCHITECTURE_ANALYSIS.md` -- Problem analysis: `WIKI_CONFIG_FLOW_ANALYSIS.md` -- Implementation plan: Plans directory - -**Related code:** -- Handler: `internal/handler/knowledgebase.go` (Lines 433-488) -- Repository: `internal/application/repository/knowledgebase.go` -- Type def: `internal/types/wiki_page.go` (WikiConfig struct) - ---- - -## Common Questions - -**Q: Will this break existing code?** -A: No, `WikiConfig` is optional (pointer), null values are valid. - -**Q: Do I need a database migration?** -A: No, the column already exists (`migrations/000032_wiki_pages.up.sql`). - -**Q: What about the frontend?** -A: The frontend already sends wiki_config; the backend just wasn't receiving it. - -**Q: Can I deploy this independently?** -A: Yes, it's backward compatible. Deploy backend first, frontend anytime. - -**Q: How do I know it's working?** -A: Edit wiki settings, save, reload page. Settings should persist. - ---- - -## Contact / Issues - -If you get compilation errors: -1. Check you added the field with correct struct tags -2. Run `go fmt` to fix formatting -3. Check imports if WikiConfig type not found - -If wiki settings still aren't saving: -1. Verify both changes were applied -2. Restart backend service -3. Check browser cache (hard refresh: Cmd+Shift+R) - ---- - -**Status:** Ready to implement ✅ -**Last Updated:** April 20, 2026 diff --git a/QUICK_REFERENCE.md b/QUICK_REFERENCE.md deleted file mode 100644 index 75b9a374..00000000 --- a/QUICK_REFERENCE.md +++ /dev/null @@ -1,154 +0,0 @@ -# Language Refactoring - Quick Reference Card - -## 📋 TL;DR - -**Refactored wiki language logic from 7 hardcoded lines to 1 function call** - -### The Change -```go -// ❌ OLD: 7 lines, 2 languages -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} - -// ✅ NEW: 4 lines, 9+ languages -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - ---- - -## 📊 Metrics at a Glance - -| Metric | Before | After | Change | -|--------|--------|-------|--------| -| **Code Lines** | 7 | 4 | -43% | -| **Languages** | 2 | 9+ | +350% | -| **Test Cases** | 0 | 30 | 100% coverage | -| **Performance** | N/A | 4.3 ns/call | Negligible | -| **Breaking Changes** | N/A | 0 | ✅ Backward compatible | - ---- - -## 🎯 What Changed - -**File:** `internal/application/service/wiki_ingest.go` (line 139) - -**From:** Hardcoded if-else logic -**To:** `types.LanguageLocaleName()` function call - ---- - -## 🗣️ Languages Supported Now - -✅ Chinese (Simplified, Traditional) -✅ English -✅ Korean -✅ Japanese -✅ Russian -✅ French -✅ German -✅ Spanish -✅ Portuguese - ---- - -## ✅ Testing & Verification - -### Run Tests -```bash -go test -v ./internal/types -run TestLanguageLocaleName -go test -bench=. ./internal/types -run BenchmarkLanguageLocaleName -``` - -### Build Check -```bash -go build ./internal/application/service -go build ./cmd/server -``` - -**Result:** ✅ All passing - ---- - -## 📂 Documentation - -| Document | Purpose | Read Time | -|----------|---------|-----------| -| **LANGUAGE_REFACTORING_README.md** | Quick start | 5 min | -| **LANGUAGE_MIDDLEWARE_ANALYSIS.md** | Full analysis | 15 min | -| **IMPLEMENTATION_GUIDE.md** | Implementation details | 20 min | -| **REFACTORING_SUMMARY.txt** | Quick reference | 10 min | - ---- - -## 💾 Commits - -``` -9913fac4 - refactor: Replace hardcoded language logic -b56b87a8 - docs: Add language refactoring README -``` - ---- - -## 🚀 Deployment Status - -✅ Code complete -✅ Tests passing -✅ Build successful -✅ Documentation done -✅ **Ready for production** - ---- - -## 🎓 Key Learning - -**Reused existing infrastructure instead of reimplementing:** -- Eliminated code duplication -- Improved consistency -- Extended functionality -- Better maintainability - ---- - -## ❓ FAQ - -**Q: Will this break anything?** -A: No. ✅ Backward compatible, no API changes. - -**Q: Do I need to migrate data?** -A: No. ✅ No database changes. - -**Q: What about performance?** -A: Negligible. ✅ ~4.3 ns/call overhead. - -**Q: Why refactor 4 lines?** -A: Code quality and consistency. ✅ Maintains DRY principle. - ---- - -## 🔗 Quick Links - -- **Main Change:** `internal/application/service/wiki_ingest.go:139` -- **Core Function:** `internal/types/context_helpers.go:85-112` -- **Tests:** `internal/types/context_helpers_test.go` -- **Middleware:** `internal/middleware/language.go` - ---- - -## 📈 Impact Summary - -- **Code Quality:** ⬆️ Improved (DRY principle) -- **Maintainability:** ⬆️ Improved (single source of truth) -- **Test Coverage:** ⬆️ Improved (30 test cases) -- **Language Support:** ⬆️ Improved (9+ languages) -- **Performance:** ➡️ Unchanged (negligible overhead) -- **Breaking Changes:** ➡️ None (backward compatible) - ---- - -**Status:** ✅ Complete & Ready -**Date:** 2026-04-07 -**Version:** 1.0 diff --git a/README_ANALYSIS.md b/README_ANALYSIS.md deleted file mode 100644 index fc6bf4d1..00000000 --- a/README_ANALYSIS.md +++ /dev/null @@ -1,427 +0,0 @@ -# WeKnora Analysis & Refactoring Documentation - -**Complete Analysis Date:** April 7, 2026 -**Total Documentation:** 1,475 lines across 5 documents -**Status:** ✅ Complete and Ready for Implementation - ---- - -## 📚 Documentation Index - -Start here to understand what's been analyzed and what to do next. - -### 🎯 Quick Navigation - -**Just want the main findings?** → Read [`ANALYSIS_SUMMARY.md`](#analysissummarymd) (5 min read) - -**Want implementation details?** → Read [`LANGUAGE_REFACTORING_QUICK_REFERENCE.md`](#language-refactoring-quick-referencemd) (2 min read) - -**Need deep technical understanding?** → Read [`AGENT_WIKI_ANALYSIS.md`](#agent-wiki-analysismd) (20 min read) - -**Planning full refactoring?** → Read [`REFACTORING_PLAN.md`](#refactoring-planmd) (10 min read) - -**Want complete language infrastructure map?** → Read [`LANGUAGE_MIDDLEWARE_ANALYSIS.md`](#language-middleware-analysismd) (15 min read) - ---- - -## 📖 Documents - -### 1. **ANALYSIS_SUMMARY.md** -**Size:** 11 KB | **Lines:** 319 | **Read Time:** 5-10 minutes - -**Overview:** Executive summary answering all four key questions about the WeKnora Agent and language infrastructure. - -**Contains:** -- Executive summary with key findings -- Document overview (purpose of each analysis doc) -- Five key questions answered: - - How does the Agent's ReAct engine dispatch tools? - - What system prompts does the Agent use? - - How does the Agent know about wiki tools? - - Is there a dedicated wiki-specific system prompt for the Agent? - - Can the wiki language logic be refactored? -- Recommended actions (immediate, short-term, medium-term, long-term) -- File locations and quick links -- Testing recommendations -- Glossary - -**Best for:** Project managers, decision makers, technical leads needing quick overview - -**Start here first if:** You need the high-level picture - ---- - -### 2. **AGENT_WIKI_ANALYSIS.md** -**Size:** 16 KB | **Lines:** 492 | **Read Time:** 15-20 minutes - -**Overview:** Complete technical deep-dive into the Agent ReAct engine architecture and wiki tool integration. - -**Sections:** -1. Agent ReAct Engine - Main Loop Architecture -2. Tool Dispatch Mechanism - Automatic, Not User-Triggered -3. System Prompts - Where Tools Are Described -4. Wiki Tool Registration - Conditional Based on KB Type -5. Wiki Tools Implementation (5 tools overview) -6. How the Agent Knows About Wiki Tools -7. Is There a Dedicated Wiki-Specific System Prompt? (NO!) -8. Synthesis Detection - Where It Actually Happens -9. Complete Tool List and Filter Logic -10. Event-Driven Architecture -11. Summary Table - -**Key Code Files:** -- `/internal/agent/engine.go` - Core ReAct engine -- `/internal/agent/act.go` - Tool execution -- `/internal/application/service/agent_service.go` - Tool registration -- `/internal/application/service/wiki_ingest.go` - Wiki ingest - -**Best for:** Developers implementing Agent features, architecture understanding - -**Start here if:** You need to understand how the Agent works internally - ---- - -### 3. **LANGUAGE_MIDDLEWARE_ANALYSIS.md** -**Size:** 11 KB | **Lines:** 349 | **Read Time:** 10-15 minutes - -**Overview:** Identifies and documents the complete language infrastructure and refactoring opportunity. - -**Sections:** -1. Existing Language Middleware Infrastructure - - HTTP middleware for language extraction - - HTTP header parsing - - Environment variable support -2. Current Wiki Ingest Language Logic (NEEDS REFACTORING) - - Shows the 6 lines of hardcoded language mapping - - Identifies problems -3. Refactoring Recommendations - - One-line solution using existing infrastructure -4. Integration Points -5. Implementation Checklist -6. Additional Observations -7. Code Migration Path -8. Files Modified Summary - -**Key Functions Identified:** -- `types.LanguageLocaleName()` - THE SOLUTION (supports 9+ languages) -- `types.LanguageFromContext()` -- `types.DefaultLanguage()` -- `types.EnvLanguage()` -- `middleware.Language()` -- `middleware.parseFirstLanguageTag()` - -**Best for:** Developers implementing language refactoring - -**Start here if:** You want to understand language handling - ---- - -### 4. **REFACTORING_PLAN.md** -**Size:** 6.3 KB | **Lines:** 204 | **Read Time:** 8-12 minutes - -**Overview:** Detailed implementation plan with code diffs, impact analysis, and testing strategy. - -**Sections:** -1. Problem Statement -2. Solution Overview -3. Implementation Details - - Change location (exact file and lines) - - Before/after code with diffs - - Verification checklist -4. Impact Analysis - - Benefits summary - - Supported languages table (9+) - - Backward compatibility -5. Testing Recommendations - - Test cases - - Integration testing -6. Future Enhancements - - Option 1: Full locale code normalization - - Option 2: Context-aware language selection -7. Implementation Steps (5 steps) -8. Rollback Plan - -**The Core Change:** -```go -// Before: 6 lines of hardcoded logic -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} - -// After: 1 line using existing infrastructure -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Best for:** Project leads planning the implementation - -**Start here if:** You're planning the refactoring sprint - ---- - -### 5. **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** -**Size:** 3.0 KB | **Lines:** 111 | **Read Time:** 2-3 minutes - -**Overview:** Quick copy-paste implementation guide for developers. - -**Sections:** -1. TL;DR Summary -2. What to Change (exact location + code) -3. Key Benefits Table -4. No Breaking Changes -5. Function Reference - - Function signature - - Location - - All supported inputs -6. Testing Instructions -7. Related Documentation -8. Files Involved Table -9. Implementation Checklist (6 steps) - -**Perfect for:** Developers ready to implement now - -**Start here if:** You want to implement immediately and don't want to read long docs - ---- - -## 🚀 Implementation Roadmap - -### Phase 1: Understanding (Completed ✅) -- [x] Agent ReAct engine architecture documented -- [x] Tool registration and dispatch mechanism documented -- [x] System prompts analyzed -- [x] Language infrastructure identified -- [x] Refactoring opportunity identified - -### Phase 2: Planning (Ready for Decision) -- [ ] Review ANALYSIS_SUMMARY.md -- [ ] Review REFACTORING_PLAN.md -- [ ] Decide on quick fix vs full refactoring -- [ ] Schedule implementation sprint - -### Phase 3: Implementation (Ready to Start) -- [ ] Use LANGUAGE_REFACTORING_QUICK_REFERENCE.md -- [ ] Make one-line change in wiki_ingest.go -- [ ] Run tests -- [ ] Verify backward compatibility -- [ ] Commit and merge - -### Phase 4: Enhancement (Optional) -- [ ] Consider full locale code normalization -- [ ] Add context-aware language fallback -- [ ] Audit for other hardcoded language mappings - ---- - -## ✅ Key Findings Summary - -### Agent Architecture -✅ **Automatic Tool Dispatch** - LLM decides tool usage, not user-driven -✅ **Conditional Registration** - Wiki tools only visible if wiki KBs detected -✅ **Event-Driven** - All actions emit events for UI feedback -✅ **Configurable** - Max iterations, knowledge bases, web search all configurable - -### System Prompts -✅ **Generic Templates** - RAG and Pure Agent modes -❌ **No Dedicated Wiki Prompt** - Wiki tools described minimally in tool definitions -❌ **wiki_write_page Not Guaranteed** - LLM must independently decide - -### Language Infrastructure -✅ **Middleware Exists** - Language extraction from HTTP headers -✅ **Reusable Functions** - `LanguageLocaleName()` supports 9+ languages -❌ **Duplicated Logic** - wiki_ingest.go has hardcoded language mapping -❌ **Limited Coverage** - Current code only supports 2 languages - -### Refactoring Opportunity -✅ **Low Risk** - Fully backward compatible -✅ **High Impact** - 6 lines → 1 line, 2 languages → 9+ -✅ **Easy Implementation** - Single one-line change -✅ **Quick Testing** - Reuses existing test infrastructure - ---- - -## 🔧 Implementation Quick Start - -### If You Have 2 Minutes -1. Read `LANGUAGE_REFACTORING_QUICK_REFERENCE.md` -2. Make the one-line change -3. Run tests -4. Done ✅ - -### If You Have 30 Minutes -1. Skim `ANALYSIS_SUMMARY.md` -2. Read `LANGUAGE_REFACTORING_QUICK_REFERENCE.md` -3. Review `REFACTORING_PLAN.md` implementation section -4. Implement change -5. Run full test suite -6. Commit with reference to documentation -7. Done ✅ - -### If You Have 1 Hour -1. Read `ANALYSIS_SUMMARY.md` (10 min) -2. Read `LANGUAGE_MIDDLEWARE_ANALYSIS.md` (15 min) -3. Read `REFACTORING_PLAN.md` (10 min) -4. Implement change (5 min) -5. Run tests and verify (15 min) -6. Document any learnings (5 min) -7. Done ✅ - -### If You Have 2+ Hours -1. Read all documents in order -2. Review source code references -3. Run tests with different configurations -4. Plan future enhancements -5. Document best practices for similar refactorings -6. Create internal wiki page on language handling -7. Done ✅ - ---- - -## 📝 Code Location Reference - -### Where to Make Changes -- **File:** `/internal/application/service/wiki_ingest.go` -- **Method:** `ProcessWikiIngest()` -- **Lines:** 135-141 - -### Where Functions Are Defined -- **Function:** `/internal/types/context_helpers.go` lines 85-112 -- **Middleware:** `/internal/middleware/language.go` lines 21-54 -- **Constants:** `/internal/types/const.go` line 25 - -### Related Files (for context) -- `/internal/agent/engine.go` - ReAct engine -- `/internal/agent/tools/wiki_tools.go` - Wiki tools -- `/internal/application/service/agent_service.go` - Tool registration - ---- - -## 🧪 Testing Strategy - -### Before Implementation -```bash -cd /Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora -go test -v ./internal/types -go test -v ./internal/application/service -``` - -### After Implementation -```bash -# Same tests should pass -go test -v ./internal/types -go test -v ./internal/application/service - -# Optionally run full suite -go test -v ./internal/... -``` - -### Manual Verification -```go -// Should print: "Chinese (Simplified)" -fmt.Println(types.LanguageLocaleName("zh")) - -// Should print: "English" -fmt.Println(types.LanguageLocaleName("en")) - -// Should print: "Korean" -fmt.Println(types.LanguageLocaleName("ko")) -``` - ---- - -## 💡 Why This Matters - -### Before Refactoring -- **Code Duplication** - Language logic repeated in multiple places -- **Limited Coverage** - Only 2 languages supported -- **Inconsistent Naming** - Different format than middleware -- **Hard to Extend** - Adding languages requires code changes -- **Maintenance Burden** - Changes needed in multiple places - -### After Refactoring -- **Single Source of Truth** - Centralized language mapping -- **Full Coverage** - 9+ languages supported -- **Consistent Naming** - Aligns with middleware conventions -- **Easy Extension** - Add languages in one place -- **Lower Maintenance** - Changes benefit all components - ---- - -## 📞 Questions & Answers - -**Q: Will this break existing code?** -A: No. The refactoring is 100% backward compatible. Existing KB configs with "zh" and "en" continue to work exactly as before. - -**Q: How long will implementation take?** -A: 2-30 minutes depending on thoroughness. The actual code change is 1 line, but testing and verification may take longer. - -**Q: Do I need to migrate the database?** -A: No. The function handles both short codes ("zh", "en") and full locales ("zh-CN", "en-US") seamlessly. - -**Q: What about new languages I might add later?** -A: Just add them to `LanguageLocaleName()` in `context_helpers.go`. No other changes needed. - -**Q: Is this high priority?** -A: Medium priority. It's a quality improvement that reduces technical debt, but doesn't block any features. - ---- - -## 📚 Related Documentation - -Additional documentation in the repository: -- `AGENT_WIKI_ANALYSIS.md` - Full Agent architecture -- `ANALYSIS_SUMMARY.md` - Executive summary -- `LANGUAGE_MIDDLEWARE_ANALYSIS.md` - Language infrastructure -- `REFACTORING_PLAN.md` - Detailed implementation plan -- `LANGUAGE_REFACTORING_QUICK_REFERENCE.md` - Quick start guide - ---- - -## ✨ Next Steps - -### Immediately -1. Review `ANALYSIS_SUMMARY.md` (executive summary) -2. Decide on quick refactoring vs full enhancement - -### Next Sprint -1. Assign implementation task -2. Use `LANGUAGE_REFACTORING_QUICK_REFERENCE.md` -3. Implement one-line change -4. Run tests -5. Merge and deploy - -### Future Enhancements -1. Consider full locale code normalization -2. Add context-aware language fallback -3. Document language handling best practices -4. Audit for other duplicate logic - ---- - -## 📄 Document Statistics - -| Document | Lines | KB | Purpose | -|----------|-------|----|---------| -| AGENT_WIKI_ANALYSIS.md | 492 | 16 | Complete Agent architecture | -| LANGUAGE_MIDDLEWARE_ANALYSIS.md | 349 | 11 | Language infrastructure | -| REFACTORING_PLAN.md | 204 | 6.3 | Implementation plan | -| LANGUAGE_REFACTORING_QUICK_REFERENCE.md | 111 | 3 | Quick start guide | -| ANALYSIS_SUMMARY.md | 319 | 11 | Executive summary | -| **README_ANALYSIS.md** | **This file** | - | Index & navigation | -| **TOTAL** | **~1,475** | **~47** | **Complete documentation** | - ---- - -**Status:** ✅ All analysis complete and documentation ready - -**Location:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/` - -**Ready to implement:** Yes, all documents in place with clear implementation path - ---- - -**Last Updated:** April 7, 2026 -**Next Review:** After implementation sprint -**Maintained By:** Analysis System diff --git a/README_WIKI_CONFIG_FIX.md b/README_WIKI_CONFIG_FIX.md deleted file mode 100644 index 6298452d..00000000 --- a/README_WIKI_CONFIG_FIX.md +++ /dev/null @@ -1,247 +0,0 @@ -# WikiConfig Update Fix - Complete Documentation Index - -**Implementation Status:** ✅ **COMPLETE AND COMMITTED** -**Commit Hash:** `b09893d5` -**Date:** April 7, 2026 15:19:53 UTC+8 - ---- - -## 📋 Documentation Files - -### 1. **START HERE: WIKI_CONFIG_FIX_COMPLETE.md** - - **Purpose:** Complete implementation overview - - **Audience:** Project managers, team leads, developers - - **Contains:** Problem statement, solution overview, testing scenarios, deployment checklist - - **Read Time:** 10-15 minutes - -### 2. **IMPLEMENTATION_SUMMARY.md** - - **Purpose:** Detailed technical implementation guide - - **Audience:** Backend developers, code reviewers - - **Contains:** Root cause analysis, data flow diagrams, testing examples, impact analysis - - **Read Time:** 15-20 minutes - -### 3. **WIKI_CONFIG_VERIFICATION.md** - - **Purpose:** Testing and verification guide - - **Audience:** QA engineers, testers, DevOps - - **Contains:** Test cases, verification checklist, curl examples, rollback plan - - **Read Time:** 10-15 minutes - -### 4. **WIKI_CONFIG_FLOW_ANALYSIS.md** (From Previous Session) - - **Purpose:** Deep technical analysis of the entire data flow - - **Audience:** Senior developers, architects - - **Contains:** Layer-by-layer analysis, why creation works but updates didn't, required fixes - - **Read Time:** 20-30 minutes - -### 5. **WIKI_CONFIG_QUICK_REFERENCE.md** (From Previous Session) - - **Purpose:** Quick developer reference - - **Audience:** Developers implementing wiki features - - **Contains:** Problem summary, broken flow, files to change, code snippets - - **Read Time:** 5-10 minutes - ---- - -## 🎯 Quick Start by Role - -### For Project Managers / Team Leads -1. Read: **WIKI_CONFIG_FIX_COMPLETE.md** (sections "Quick Summary" and "Success Criteria") -2. Reference: Deployment checklist -3. Track: Commit `b09893d5` for changes made - -### For Backend Developers -1. Read: **WIKI_CONFIG_QUICK_REFERENCE.md** (quick overview) -2. Review: Git commit `git show b09893d5` -3. Study: **IMPLEMENTATION_SUMMARY.md** (data flow sections) -4. Test: Follow Testing Scenarios in **WIKI_CONFIG_FIX_COMPLETE.md** - -### For QA / Testers -1. Read: **WIKI_CONFIG_VERIFICATION.md** (all sections) -2. Execute: Test cases 1-4 -3. Verify: Using database query and curl examples -4. Report: Any issues with rollback steps - -### For DevOps / Deployment -1. Read: **WIKI_CONFIG_FIX_COMPLETE.md** (Deployment Checklist section) -2. Reference: Rollback Plan -3. Monitor: Log patterns in Monitoring section - ---- - -## 🔍 The Fix at a Glance - -### What Was Broken -```bash -PUT /api/v1/knowledge-bases/{id} -{ - "config": { - "wiki_config": { - "enabled": true - } - } -} -# ❌ wiki_config was silently ignored and not saved -``` - -### What's Now Fixed -```bash -PUT /api/v1/knowledge-bases/{id} -{ - "config": { - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4", - "wiki_language": "en" - } - } -} -# ✅ wiki_config is now properly saved to database -``` - -### How We Fixed It - -| Layer | File | Change | Reason | -|-------|------|--------|--------| -| **Types** | `internal/types/knowledgebase.go` | Added `WikiConfig *WikiConfig` field to `KnowledgeBaseConfig` struct | Enables JSON unmarshaling of wiki_config from requests | -| **Service** | `internal/application/service/knowledgebase.go` | Added `if config.WikiConfig != nil { kb.WikiConfig = config.WikiConfig }` | Applies deserialized config to KB entity before save | -| **Frontend** | `frontend/src/api/knowledge-base/index.ts` | Added WikiConfig type hints to create/update functions | Provides IDE autocomplete and type safety | - ---- - -## ✅ Verification Checklist - -### Code Level -- [x] WikiConfig field added to KnowledgeBaseConfig struct -- [x] Service layer persistence logic added -- [x] Frontend types updated -- [x] Git commit created with proper message - -### Testing Level -- [ ] Create KB with wiki_config (Test Case 1) -- [ ] Update KB with wiki_config (Test Case 2) -- [ ] Verify persistence (Test Case 3) -- [ ] Database query verification (Test Case 4) - -### Deployment Level -- [ ] Code review approved -- [ ] All tests passing -- [ ] Deployed to staging -- [ ] Verified in staging environment -- [ ] Deployed to production -- [ ] Monitored for issues - ---- - -## 📊 Impact Summary - -**Files Modified:** 3 -**Lines Added:** 43 -**Lines Removed:** 20 -**Breaking Changes:** 0 -**Backward Compatible:** Yes ✅ -**Database Migrations:** 0 (schema already supports wiki_config) -**Deployment Downtime:** 0 (code-only change) - ---- - -## 🚀 Deployment Steps - -```bash -# 1. Review changes -git show b09893d5 - -# 2. Run tests -go test ./internal/application/service/... -npm run build # Frontend - -# 3. Deploy -git pull && git deploy b09893d5 # Your deploy process - -# 4. Verify -curl http://localhost:8080/api/v1/knowledge-bases/test-kb -``` - ---- - -## 🆘 Troubleshooting - -### Issue: "wiki_config still not saving" -**Check:** -1. Are you using correct field name `wiki_config` (snake_case)? -2. Is the field inside `config` object in PUT request? -3. Is your backend running the updated code (commit b09893d5)? - -### Issue: "TypeScript errors about WikiConfig" -**Fix:** -1. Rebuild frontend: `npm run build` -2. Clear cache: `rm -rf node_modules && npm install` -3. Restart IDE if using VS Code - -### Issue: "Database shows null wiki_config" -**Check:** -1. Verify migration 000032 ran: `SELECT * FROM knowledge_bases LIMIT 1;` -2. Check if wiki_config column exists -3. Verify KB was updated AFTER code deployment - ---- - -## 📞 Questions or Issues - -**Refer to:** -- Quick answer: Check **WIKI_CONFIG_QUICK_REFERENCE.md** -- Detailed answer: Check **IMPLEMENTATION_SUMMARY.md** -- Testing help: Check **WIKI_CONFIG_VERIFICATION.md** -- Deep dive: Check **WIKI_CONFIG_FLOW_ANALYSIS.md** - ---- - -## 🎓 Learning Resources - -### Understanding the Problem -1. Start with: "The Problem" section in WIKI_CONFIG_FIX_COMPLETE.md -2. Dive deeper: "Why Other Configs Worked" in same file -3. Full analysis: WIKI_CONFIG_FLOW_ANALYSIS.md - -### Understanding the Solution -1. Overview: "The Solution" section in WIKI_CONFIG_FIX_COMPLETE.md -2. Code: `git show b09893d5` -3. Details: IMPLEMENTATION_SUMMARY.md - -### Understanding the Testing -1. Scenarios: "Testing Scenarios" in WIKI_CONFIG_FIX_COMPLETE.md -2. Full guide: WIKI_CONFIG_VERIFICATION.md -3. Examples: Curl commands throughout all docs - ---- - -## 📝 Related Files - -**Backend Implementation:** -- `internal/types/knowledgebase.go` - Type definitions -- `internal/application/service/knowledgebase.go` - Service logic -- `internal/handler/knowledgebase.go` - HTTP handler - -**Frontend Implementation:** -- `frontend/src/api/knowledge-base/index.ts` - API functions -- `frontend/src/types/*.ts` - TypeScript types (if exists) - -**Database:** -- `migrations/versioned/000032_wiki_pages.up.sql` - Creates wiki_config column - ---- - -## 🏆 Success Metrics - -After this fix: -- ✅ Wiki configuration can be set during KB creation -- ✅ Wiki configuration can be updated after KB creation -- ✅ All wiki_config fields are properly persisted -- ✅ Frontend has full IDE support for wiki_config -- ✅ Zero breaking changes to existing code -- ✅ 100% backward compatible - ---- - -**Last Updated:** April 7, 2026 15:19:53 UTC+8 -**Status:** ✅ **READY FOR PRODUCTION** -**Commit:** b09893d5 - diff --git a/README_WIKI_FEATURE.md b/README_WIKI_FEATURE.md deleted file mode 100644 index 45e01a01..00000000 --- a/README_WIKI_FEATURE.md +++ /dev/null @@ -1,560 +0,0 @@ -# WeKnora Wiki Feature - Complete Implementation - -**Status:** ✅ PRODUCTION READY -**Date:** April 7, 2026 -**Build:** 243MB (arm64 executable) -**Tests:** 50+ passing - ---- - -## Quick Navigation - -### 📚 Documentation -- **Getting Started:** [START_HERE.md](START_HERE.md) -- **Deployment:** [DEPLOYMENT_CHECKLIST.md](DEPLOYMENT_CHECKLIST.md) -- **Completion Summary:** [FINAL_COMPLETION_SUMMARY.md](FINAL_COMPLETION_SUMMARY.md) -- **Language Infrastructure:** [LANGUAGE_REFACTORING_QUICK_REFERENCE.md](LANGUAGE_REFACTORING_QUICK_REFERENCE.md) - -### 💻 Source Code - -**Backend:** -``` -internal/ -├── types/ -│ ├── wiki_page.go # Data model -│ ├── interfaces/wiki_page.go # Interfaces -│ └── context_helpers.go # Language helpers -├── application/ -│ ├── repository/wiki_page.go # Database layer -│ ├── service/ -│ │ ├── wiki_page.go # Business logic -│ │ ├── wiki_ingest.go # Pipeline -│ │ ├── wiki_lint.go # Maintenance -│ │ └── chat_pipeline/wiki_boost.go # Chat integration -│ └── handler/wiki_page.go # HTTP endpoints -├── agent/ -│ ├── prompts_wiki.go # LLM prompts -│ └── tools/wiki_tools.go # Agent tools -├── router/router.go # Route registration -└── container/container.go # DI setup - -Database/ -├── migrations/000032_wiki_pages.up.sql -└── migrations/000032_wiki_pages.down.sql -``` - -**Frontend:** -``` -frontend/src/ -├── api/wiki/index.ts # API client -├── views/knowledge/wiki/WikiBrowser.vue # UI -└── i18n/locales/ # i18n strings -``` - -### 🧪 Tests -- `internal/types/wiki_page_test.go` - Type tests -- `internal/types/context_helpers_test.go` - Language tests (30+ cases) -- `internal/application/service/wiki_page_test.go` - Service tests -- `internal/application/service/wiki_ingest_test.go` - Pipeline tests -- `internal/agent/tools/wiki_tools_test.go` - Agent tool tests - ---- - -## Feature Overview - -### What is the Wiki Feature? - -The wiki feature enables automatic generation and management of AI-powered wiki pages for knowledge bases. When a document is uploaded, the system: - -1. **Generates a Summary Page** - High-level overview of the document -2. **Extracts Entities & Concepts** - Key topics in a single LLM call -3. **Creates Wiki Pages** - Separate pages for each entity and concept -4. **Detects Synthesis Opportunities** - Identifies pages that could be combined -5. **Maintains Index & Log** - Auto-updated table of contents and audit log - -### Key Capabilities - -✅ **Automatic Wiki Generation** - No manual entry required -✅ **Multi-Language Support** - 9+ languages out of the box -✅ **Smart Extraction** - Single LLM call for efficiency -✅ **Agent Integration** - Query wiki via agents -✅ **Chat Enhancement** - Inject wiki context into responses -✅ **Async Processing** - Non-blocking task queue -✅ **Full CRUD** - Create, read, update, delete pages -✅ **Search & Filter** - Find pages easily -✅ **Frontend UI** - Beautiful wiki browser - ---- - -## Getting Started - -### 1. Build the Project - -```bash -cd cmd/server -go build -o weknora -``` - -### 2. Run Database Migrations - -```bash -go run ./cmd/migrate/main.go up -``` - -### 3. Start the Server - -```bash -./weknora -``` - -### 4. Access the Wiki - -- **UI:** http://localhost:8080/wiki -- **API:** http://localhost:8080/api/v1/wiki/pages - ---- - -## API Endpoints - -### List Wiki Pages -```bash -GET /api/v1/wiki/pages?knowledge_base_id=kb123 - -Response: -{ - "pages": [ - { - "id": "page_123", - "slug": "entity/apple", - "title": "Apple", - "page_type": "Entity", - "status": "Published", - "summary": "An apple is a fruit..." - } - ] -} -``` - -### Get Specific Page -```bash -GET /api/v1/wiki/pages/:slug - -Response: -{ - "id": "page_123", - "slug": "entity/apple", - "title": "Apple", - "content": "# Apple\n\nAn apple is...", - "page_type": "Entity", - "status": "Published" -} -``` - -### Create Page -```bash -POST /api/v1/wiki/pages - -Body: -{ - "knowledge_base_id": "kb123", - "slug": "custom/my-page", - "title": "My Custom Page", - "content": "Page content here", - "page_type": "Entity", - "status": "Draft" -} -``` - -### Search Pages -```bash -GET /api/v1/wiki/search?q=apple&knowledge_base_id=kb123 - -Response: -{ - "results": [ - { - "id": "page_123", - "slug": "entity/apple", - "title": "Apple", - "snippet": "An apple is a fruit..." - } - ] -} -``` - ---- - -## Database Schema - -### wiki_pages Table - -```sql -CREATE TABLE wiki_pages ( - id VARCHAR(36) PRIMARY KEY, - tenant_id BIGINT NOT NULL, - knowledge_base_id VARCHAR(255) NOT NULL, - slug VARCHAR(255) NOT NULL, - title VARCHAR(255) NOT NULL, - content LONGTEXT NOT NULL, - summary TEXT, - page_type VARCHAR(50) NOT NULL, - status VARCHAR(50) NOT NULL DEFAULT 'Draft', - source_refs JSON, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - - INDEX idx_kb (knowledge_base_id), - INDEX idx_slug (slug), - INDEX idx_type (page_type), - INDEX idx_status (status), - UNIQUE KEY uk_kb_slug (knowledge_base_id, slug) -); -``` - -### Wiki Page Types - -- **Summary** - High-level overview of document -- **Entity** - Specific entity or topic -- **Concept** - Abstract concept or idea -- **Index** - Table of contents -- **Log** - Audit log of changes -- **Synthesis** - Combined/cross-document page - -### Page Status - -- **Draft** - Not yet published -- **Published** - Visible to users -- **Archived** - Hidden from view - ---- - -## Configuration - -### Knowledge Base Settings - -When creating/editing a knowledge base, configure: - -```go -type WikiConfig struct { - WikiLanguage string // "zh", "en", "ko", etc. - AutoIngest bool // Enable automatic wiki generation - SynthesisModelID string // LLM model for synthesis -} -``` - -### Supported Languages - -| Code | Language | Supported | -|------|----------|-----------| -| zh-CN | Chinese (Simplified) | ✅ | -| zh-TW | Chinese (Traditional) | ✅ | -| en-US | English | ✅ | -| ko-KR | Korean | ✅ | -| ja-JP | Japanese | ✅ | -| ru-RU | Russian | ✅ | -| fr-FR | French | ✅ | -| de-DE | German | ✅ | -| es-ES | Spanish | ✅ | - ---- - -## Testing - -### Run All Tests - -```bash -go test ./... -v -``` - -### Run Specific Test Suite - -```bash -# Wiki page type tests -go test ./internal/types -v -run TestWikiPage - -# Wiki service tests -go test ./internal/application/service -v -run TestWiki - -# Wiki agent tools tests -go test ./internal/agent/tools -v -run TestWiki - -# Language tests -go test ./internal/types -v -run TestLanguageLocaleName -``` - -### Test Coverage - -```bash -go test ./... -cover - -# Generate coverage report -go test ./... -coverprofile=coverage.out -go tool cover -html=coverage.out -``` - ---- - -## Deployment - -### Pre-Deployment Checklist - -- [ ] All tests passing -- [ ] Build succeeds -- [ ] Documentation reviewed -- [ ] Staging verification complete -- [ ] Database backup created - -### Deploy to Staging - -```bash -# Build -cd cmd/server && go build -o weknora-staging - -# Deploy -scp weknora-staging staging:/opt/weknora/ -ssh staging "systemctl restart weknora" - -# Verify -curl https://staging/api/v1/wiki/pages -``` - -### Deploy to Production - -```bash -# Build -cd cmd/server && go build -ldflags="-s -w" -o weknora-prod - -# Deploy (with zero-downtime) -for server in prod1 prod2; do - scp weknora-prod $server:/opt/weknora/ - ssh $server "systemctl restart weknora" - sleep 5 -done - -# Verify -curl https://api.weknora.com/api/v1/wiki/pages -``` - ---- - -## Troubleshooting - -### Issue: Wiki pages not created - -**Check:** -```bash -# Verify database -mysql -u root weknora -e "SELECT COUNT(*) FROM wiki_pages;" - -# Check ingest logs -grep -i "wiki" /var/log/weknora/app.log | grep -i error - -# Verify LLM connectivity -curl https://llm-service/health -``` - -### Issue: Slow wiki page creation - -**Optimize:** -```bash -# Add index -ALTER TABLE wiki_pages ADD INDEX idx_kb_type (knowledge_base_id, page_type); - -# Check LLM performance -time curl -X POST https://llm-service/complete ... - -# Increase async workers -export WIKI_INGEST_WORKERS=4 -``` - -### Issue: Memory usage high - -**Reduce:** -```bash -# Lower max content size -MAX_CONTENT_FOR_WIKI=16384 # Default 32768 - -# Limit concurrent ingest tasks -WIKI_MAX_CONCURRENT=2 # Default 5 -``` - ---- - -## Performance Metrics - -### Benchmarks - -| Operation | Time | Notes | -|-----------|------|-------| -| Create page | < 50ms | Database write only | -| Get page | < 10ms | With caching | -| List pages | < 100ms | With pagination | -| Search pages | < 200ms | Full-text search | -| Generate wiki | < 30s | Per document, with LLM | -| Extract entities | ~10s | Single LLM call | - -### Language Support Performance - -``` -LanguageLocaleName() benchmark: - - Ops/sec: 288M - - Per-op time: 4.3 nanoseconds - - Total overhead: negligible -``` - ---- - -## Architecture - -### High-Level Flow - -``` -Document Upload - ↓ -Document Parsed - ↓ -Wiki Ingest Task Enqueued - ↓ -Wiki Ingest Service - ├─→ Generate Summary (LLM) - ├─→ Extract Entities & Concepts (LLM) - ├─→ Create/Update Wiki Pages (DB) - ├─→ Detect Synthesis Opportunities - ├─→ Rebuild Index - └─→ Update Log - ↓ -Wiki Pages Ready - ↓ -User browses wiki UI -``` - -### Component Dependencies - -``` -Handler (HTTP) - ↓ -Service (Business Logic) - ├─→ Repository (Database) - ├─→ Model Service (LLM) - └─→ Task Enqueuer (Async) -``` - ---- - -## Development Guide - -### Adding a New Wiki Page Type - -1. **Update WikiPageType in types** - ```go - const ( - WikiPageTypeSummary = "Summary" - WikiPageTypeEntity = "Entity" - WikiPageTypeConcept = "Concept" - WikiPageTypeMyNewType = "MyNewType" // Add here - ) - ``` - -2. **Add LLM Prompt** - ```go - // In agent/prompts_wiki.go - const WikiMyNewTypePrompt = `...` - ``` - -3. **Update Ingest Logic** - ```go - // In service/wiki_ingest.go ProcessWikiIngest() - // Add generation step - ``` - -4. **Update Tests** - ```go - // Add test case in wiki_page_test.go - ``` - -### Adding Language Support - -1. **Update LanguageLocaleName** - ```go - // In types/context_helpers.go - case "xx-XX": - return "Language Name" - ``` - -2. **Add i18n strings** - ```json - // In frontend/src/i18n/locales/*.ts - "wiki.languageName": "Language Name" - ``` - ---- - -## Monitoring & Alerts - -### Key Metrics - -- Wiki page creation rate -- Average ingest time -- LLM API latency -- Database query performance -- Error rate - -### Alert Thresholds - -- Error rate > 5% -- API response > 1s -- Database connection pool exhausted -- Task queue backing up (>100 items) -- LLM service unavailable - ---- - -## FAQ - -**Q: Can I customize wiki page generation?** -A: Yes, modify the prompts in `agent/prompts_wiki.go` for your use case. - -**Q: Does wiki support multi-language documents?** -A: Yes, set WikiLanguage per knowledge base. Each KB gets its own wiki. - -**Q: How do I delete a wiki?** -A: Delete all pages for that knowledge base: -```bash -DELETE FROM wiki_pages WHERE knowledge_base_id = 'kb123'; -``` - -**Q: Can agents query the wiki?** -A: Yes, wiki tools are automatically registered. See `agent/tools/wiki_tools.go`. - -**Q: Is wiki data encrypted?** -A: Yes, it uses the same encryption as other KB data. - -**Q: How many wiki pages can I create?** -A: Unlimited. Performance tested up to 100k+ pages. - ---- - -## Support & Resources - -- 📖 [Complete Documentation](FINAL_COMPLETION_SUMMARY.md) -- 🚀 [Deployment Guide](DEPLOYMENT_CHECKLIST.md) -- 📊 [Architecture Diagram](ARCHITECTURE_DIAGRAM.md) -- 🧪 [Test Examples](internal/application/service/wiki_page_test.go) -- 💬 [API Reference](internal/handler/wiki_page.go) - ---- - -## Next Steps - -1. **Review** the implementation guides -2. **Deploy** to staging environment -3. **Test** with sample knowledge bases -4. **Monitor** performance metrics -5. **Gather** user feedback -6. **Deploy** to production - ---- - -**Status: ✅ READY FOR PRODUCTION** - -The wiki feature is fully implemented, tested, documented, and ready for deployment. All systems are operational! diff --git a/REFACTORING_IMPLEMENTATION_REPORT.md b/REFACTORING_IMPLEMENTATION_REPORT.md deleted file mode 100644 index b6873a81..00000000 --- a/REFACTORING_IMPLEMENTATION_REPORT.md +++ /dev/null @@ -1,273 +0,0 @@ -# Language Refactoring Implementation Report - -## Status: ✅ COMPLETED - -**Date Completed:** 2026-04-07 -**Implementation Scope:** wiki_ingest.go language handling refactoring -**Impact:** 83% code reduction, 9+ language support, centralized maintenance - ---- - -## What Was Done - -### 1. Code Refactoring - -**File Modified:** `/internal/application/service/wiki_ingest.go` -**Lines Changed:** 135-141 (previously 6 lines of hardcoded logic) - -**Before (Original Implementation):** -```go -// Get human-readable language name for LLM prompts -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} -``` - -**After (Refactored Implementation):** -```go -// Get human-readable language name for LLM prompts -// Reuses language mapping from middleware infrastructure (supports 9+ languages) -// Maps locale codes like "zh", "en" to names like "Chinese (Simplified)", "English" -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Key Benefits:** -- ✅ 83% code reduction (6 lines → 1 line) -- ✅ Support expanded from 2 languages to 9+ -- ✅ Centralized language mapping maintenance (single source of truth) -- ✅ Consistent with middleware infrastructure -- ✅ Backward compatible (existing "zh" and "en" values still work) - ---- - -## Supported Languages - -The refactored code now supports: - -| Locale Codes | Language Name | -|---|---| -| `zh-CN`, `zh`, `zh-Hans` | Chinese (Simplified) | -| `zh-TW`, `zh-HK`, `zh-Hant` | Chinese (Traditional) | -| `en-US`, `en`, `en-GB` | English | -| `ko-KR`, `ko` | Korean | -| `ja-JP`, `ja` | Japanese | -| `ru-RU`, `ru` | Russian | -| `fr-FR`, `fr` | French | -| `de-DE`, `de` | German | -| `es-ES`, `es` | Spanish | -| `pt-BR`, `pt` | Portuguese | - -**Fallback:** Unknown locales pass through unchanged (line 110: `return locale`) - ---- - -## Implementation Details - -### Function Source: `/internal/types/context_helpers.go` (lines 85-112) - -```go -// LanguageLocaleName maps a locale code to a human-readable language name for LLM prompts. -func LanguageLocaleName(locale string) string { - switch locale { - case "zh-CN", "zh", "zh-Hans": - return "Chinese (Simplified)" - case "zh-TW", "zh-HK", "zh-Hant": - return "Chinese (Traditional)" - case "en-US", "en", "en-GB": - return "English" - case "ko-KR", "ko": - return "Korean" - case "ja-JP", "ja": - return "Japanese" - case "ru-RU", "ru": - return "Russian" - case "fr-FR", "fr": - return "French" - case "de-DE", "de": - return "German" - case "es-ES", "es": - return "Spanish" - case "pt-BR", "pt": - return "Portuguese" - default: - // For unknown locales, return the locale itself - return locale - } -} -``` - -### Import Verification -✅ Package import confirmed in wiki_ingest.go line 14: `"github.com/Tencent/WeKnora/internal/types"` - ---- - -## Testing Results - -### Unit Tests: ✅ ALL PASSING - -**Test File:** `/internal/types/context_helpers.go` (assumed, based on test coverage) - -**Test Coverage:** -- ✅ Chinese (Simplified): zh-CN, zh, zh-Hans -- ✅ Chinese (Traditional): zh-TW, zh-HK, zh-Hant -- ✅ English: en-US, en, en-GB -- ✅ Korean: ko-KR, ko -- ✅ Japanese: ja-JP, ja -- ✅ Russian: ru-RU, ru -- ✅ French: fr-FR, fr -- ✅ German: de-DE, de -- ✅ Spanish: es-ES, es -- ✅ Portuguese: pt-BR, pt -- ✅ Unknown locale fallback -- ✅ Empty locale fallback -- ✅ Arbitrary locale codes - -**Test Command Output:** -``` -=== RUN TestLanguageLocaleName ---- PASS: TestLanguageLocaleName (0.00s) - --- PASS: TestLanguageLocaleName/Chinese_Simplified_zh-CN (0.00s) - --- PASS: TestLanguageLocaleName/Chinese_Simplified_zh (0.00s) - [... 26 additional test cases pass ...] - --- PASS: TestLanguageLocaleName/Arbitrary_code (0.00s) -``` - -### Build Verification: ✅ SUCCESSFUL - -**Command:** `go build ./internal/application/service` -**Result:** No compilation errors, no warnings - -### Backward Compatibility: ✅ CONFIRMED - -- ✅ Original "zh" values continue to resolve to "Chinese (Simplified)" -- ✅ Original "en" values continue to resolve to "English" -- ✅ No database schema changes required -- ✅ No API contract changes required -- ✅ Existing wiki ingest configurations remain functional - ---- - -## Code Flow Impact - -### Wiki Ingest Process (ProcessWikiIngest) - -1. **Line 139:** Language determination now uses centralized function - ```go - lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) - ``` - -2. **Usage in LLM Prompts:** - - Line 166: WikiSummaryPrompt template receives `Language: lang` - - Line 240: WikiKnowledgeExtractPrompt template receives `Content: content` - - Line 304: WikiPageUpdatePrompt template receives `Language: lang` - - Line 413: WikiIndexRebuildPrompt template receives `Language: lang` - -3. **LLM Instructions:** - All wiki generation prompts now receive human-readable language names: - - "Chinese (Simplified)" instead of hardcoded "中文" - - "English" (consistent) - - Plus 7 additional languages automatically - ---- - -## Maintenance Advantages - -### Before Refactoring -- Language mapping hardcoded in wiki_ingest.go -- Separate from middleware language infrastructure -- Manual synchronization required if middleware languages expand -- Limited to 2 languages - -### After Refactoring -- Single source of truth: `types.LanguageLocaleName()` -- Automatically available to all services using the types package -- Adding new languages: Update only `/internal/types/context_helpers.go` -- Currently supports: 9+ languages with variants (20+ locale codes) - ---- - -## Future Enhancement Opportunities - -### Phase 2: Extended Language Coverage -The infrastructure is ready to expand to additional languages: -```go -case "it-IT", "it": - return "Italian" -case "nl-NL", "nl": - return "Dutch" -case "sv-SE", "sv": - return "Swedish" -``` - -### Phase 3: Language-Specific LLM Prompt Optimization -Different LLMs perform better with different language names. The centralized function enables: -- Per-language prompt variants -- LLM model selection optimization -- Regional dialect handling - -### Phase 4: Language Detection from Document Content -Future integration with document language detection: -```go -// Automatic language detection from document content -detectedLang := s.detectDocumentLanguage(content) -lang := types.LanguageLocaleName(detectedLang) -``` - ---- - -## Deployment Checklist - -- [x] Code refactoring completed -- [x] Import verification (types package available) -- [x] Unit tests passing (LanguageLocaleName) -- [x] Build successful (no compilation errors) -- [x] Backward compatibility verified -- [x] Documentation updated -- [x] No database migrations required -- [x] No API changes required - ---- - -## Rollback Plan (if needed) - -If issues arise, the original code can be restored: - -```go -// Temporary rollback to original implementation -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} -``` - -**Note:** Rollback not recommended due to language feature loss and loss of forward compatibility. - ---- - -## Related Documentation - -- **AGENT_WIKI_ANALYSIS.md** — Agent ReAct engine and wiki tool analysis -- **LANGUAGE_MIDDLEWARE_ANALYSIS.md** — Language infrastructure documentation -- **REFACTORING_PLAN.md** — Detailed implementation strategy -- **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** — Quick implementation guide -- **ANALYSIS_SUMMARY.md** — Executive summary of findings -- **README_ANALYSIS.md** — Navigation and roadmap - ---- - -## Summary - -The language refactoring has been **successfully implemented and verified**. The code: -- Reduces from 6 lines to 1 line (83% reduction) -- Expands language support from 2 to 9+ languages -- Maintains 100% backward compatibility -- Passes all unit tests -- Builds without errors -- Positions the codebase for future language expansion - -The refactoring achieves the stated goal: **reuse existing middleware language infrastructure for wiki ingest language determination**. diff --git a/REFACTORING_PLAN.md b/REFACTORING_PLAN.md deleted file mode 100644 index 530bd28e..00000000 --- a/REFACTORING_PLAN.md +++ /dev/null @@ -1,204 +0,0 @@ -# Wiki Ingest Language Refactoring - Implementation Plan - -## Problem Statement - -The wiki ingest pipeline contains hardcoded language mapping logic (lines 135-141 in `wiki_ingest.go`) that: -- Only supports 2 languages (Chinese and English) -- Duplicates logic already available in `types.LanguageLocaleName()` -- Uses inconsistent naming compared to the existing language middleware -- Cannot be easily extended for new languages - -## Solution - -Reuse the existing `types.LanguageLocaleName()` function from `/internal/types/context_helpers.go` which: -- Supports 9+ languages (Chinese, English, Korean, Japanese, Russian, French, German, Spanish, Portuguese) -- Is already tested and used throughout the codebase -- Provides consistent language name formatting for LLM prompts -- Handles unknown languages gracefully - -## Implementation - -### Change Location - -**File:** `/internal/application/service/wiki_ingest.go` -**Method:** `ProcessWikiIngest()` -**Lines:** 135-141 - -### Before (Current Code) - -```go -135 // Determine language -136 lang := "the same language as the source document" -137 if kb.WikiConfig.WikiLanguage == "zh" { -138 lang = "Chinese (中文)" -139 } else if kb.WikiConfig.WikiLanguage == "en" { -140 lang = "English" -141 } -``` - -### After (Refactored Code) - -```go -135 // Determine language - reuse middleware infrastructure for consistent naming -136 // Supports: Chinese (Simplified/Traditional), English, Korean, Japanese, Russian, French, German, Spanish, Portuguese -137 lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -### Code Diff - -```diff -- // Determine language -- lang := "the same language as the source document" -- if kb.WikiConfig.WikiLanguage == "zh" { -- lang = "Chinese (中文)" -- } else if kb.WikiConfig.WikiLanguage == "en" { -- lang = "English" -- } -+ // Determine language - reuse middleware infrastructure for consistent naming -+ // Supports: Chinese (Simplified/Traditional), English, Korean, Japanese, Russian, French, German, Spanish, Portuguese -+ lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -### Verification - -The types package is already imported at line 14: -```go -"github.com/Tencent/WeKnora/internal/types" -``` - -No additional imports needed. - -## Impact Analysis - -### Benefits - -✅ **Code Reduction:** 6 lines → 3 lines (50% reduction) -✅ **Language Coverage:** 2 languages → 9+ languages -✅ **Consistency:** Aligns with middleware language naming conventions -✅ **Maintainability:** Centralized language mapping (single source of truth) -✅ **Extensibility:** Adding new languages only requires updating `LanguageLocaleName()` -✅ **Testing:** Reuses existing, tested function - -### Supported Languages (After Refactoring) - -| Code | Output | -|------|--------| -| `zh-CN`, `zh`, `zh-Hans` | Chinese (Simplified) | -| `zh-TW`, `zh-HK`, `zh-Hant` | Chinese (Traditional) | -| `en-US`, `en`, `en-GB` | English | -| `ko-KR`, `ko` | Korean | -| `ja-JP`, `ja` | Japanese | -| `ru-RU`, `ru` | Russian | -| `fr-FR`, `fr` | French | -| `de-DE`, `de` | German | -| `es-ES`, `es` | Spanish | -| `pt-BR`, `pt` | Portuguese | -| *unknown* | Returns the locale code as-is | - -### Backward Compatibility - -✅ **Fully Compatible** -- Existing KB configs with `WikiLanguage: "zh"` and `WikiLanguage: "en"` continue to work -- The function handles short codes: `"zh" → "Chinese (Simplified)"`, `"en" → "English"` -- No database schema changes required -- No migration needed - -## Testing Recommendations - -### Test Cases - -```go -// Test 1: Existing short code support -lang := types.LanguageLocaleName("zh") // Expected: "Chinese (Simplified)" -lang := types.LanguageLocaleName("en") // Expected: "English" - -// Test 2: Full locale code support -lang := types.LanguageLocaleName("zh-CN") // Expected: "Chinese (Simplified)" -lang := types.LanguageLocaleName("en-US") // Expected: "English" -lang := types.LanguageLocaleName("ko-KR") // Expected: "Korean" - -// Test 3: Unknown locale fallback -lang := types.LanguageLocaleName("xx-YY") // Expected: "xx-YY" -lang := types.LanguageLocaleName("") // Expected: "" -``` - -### Integration Testing - -1. Create a wiki KB with `WikiLanguage: "zh"` and verify summary pages are generated in Chinese -2. Create a wiki KB with `WikiLanguage: "en"` and verify summary pages are generated in English -3. (Optional) Create a wiki KB with `WikiLanguage: "ko"` and verify Korean language support - -## Future Enhancements - -### Option 1: Full Locale Code Normalization (Recommended) - -Store full locale codes in WikiConfig to align with middleware: - -```go -// In WikiConfig struct -type WikiConfig struct { - WikiLanguage string // Store "zh-CN" instead of "zh" - // ... -} - -// No conversion needed -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -### Option 2: Context-Aware Language Selection - -Use context language as fallback: - -```go -// Determine language: prefer KB config, fallback to context/env, then default -lang := kb.WikiConfig.WikiLanguage -if lang == "" { - // Fallback to context language - if ctxLang, ok := types.LanguageFromContext(ctx); ok { - lang = ctxLang - } else { - // Fallback to env/default - lang = types.DefaultLanguage() - } -} -humanReadableLang := types.LanguageLocaleName(lang) -``` - -## Implementation Steps - -1. **Step 1:** Open `/internal/application/service/wiki_ingest.go` -2. **Step 2:** Replace lines 135-141 with the refactored code shown above -3. **Step 3:** Save the file -4. **Step 4:** Run tests to verify: - ```bash - go test ./internal/application/service/... - go test ./internal/types/... - ``` -5. **Step 5:** (Optional) Run the wiki ingest pipeline with test documents - -## Rollback Plan - -If issues arise: -```bash -git checkout HEAD -- internal/application/service/wiki_ingest.go -``` - -## Related Files - -### Definition Location -- **File:** `/internal/types/context_helpers.go` -- **Function:** `LanguageLocaleName()` (lines 85-112) - -### Other Usage Points (Informational) -- `/internal/types/context_helpers.go` - `LanguageNameFromContext()` function (line 82) - -### Similar Patterns (For Future Refactoring) -- Search for other hardcoded language mappings in the codebase that could benefit from centralization - -## Sign-Off - -- **Requested By:** User (mentions "中间件中已经有language的判断逻辑") -- **Implementation Date:** [TBD] -- **Reviewer:** [TBD] -- **Approval:** [TBD] - diff --git a/REFACTORING_SUMMARY.txt b/REFACTORING_SUMMARY.txt deleted file mode 100644 index ad35c871..00000000 --- a/REFACTORING_SUMMARY.txt +++ /dev/null @@ -1,257 +0,0 @@ -================================================================================ - LANGUAGE REFACTORING - QUICK SUMMARY -================================================================================ - -DATE: 2026-04-07 -STATUS: ✅ COMPLETED & TESTED -VERSION: 1.0 - -================================================================================ -WHAT WAS DONE -================================================================================ - -1. ANALYSIS - ✅ Identified existing language infrastructure in middleware - ✅ Found hardcoded language logic in wiki_ingest.go - ✅ Documented reusable patterns in context_helpers.go - -2. REFACTORING - ✅ Replaced 7 lines of code with 1 line - ✅ Eliminated code duplication - ✅ Updated wiki_ingest.go lines 135-141 - -3. TESTING - ✅ Created comprehensive unit tests (30 test cases) - ✅ All tests passing - ✅ Benchmark: 288M ops/sec (~4.3 ns/op) - ✅ Build verification successful - -4. DOCUMENTATION - ✅ Created LANGUAGE_MIDDLEWARE_ANALYSIS.md - ✅ Created LANGUAGE_REFACTORING_COMPLETED.md - ✅ Created IMPLEMENTATION_GUIDE.md - ✅ Created unit tests with full coverage - -================================================================================ -KEY CHANGES -================================================================================ - -FILE: internal/application/service/wiki_ingest.go - -BEFORE (7 lines): - // Determine language - lang := "the same language as the source document" - if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" - } else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" - } - -AFTER (4 lines): - // Get human-readable language name for LLM prompts - // Reuses language mapping from middleware infrastructure (supports 9+ languages) - // Maps locale codes like "zh", "en" to names like "Chinese (Simplified)", "English" - lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) - -================================================================================ -BENEFITS -================================================================================ - -BEFORE: - ❌ Only 2 languages supported (zh, en) - ❌ Hardcoded if-else logic - ❌ Inconsistent naming - ❌ 7 lines to maintain - ❌ Duplicated logic - -AFTER: - ✅ 9+ languages supported - ✅ Uses existing infrastructure - ✅ Consistent naming - ✅ 4 lines (43% reduction) - ✅ Single source of truth - ✅ Better maintainability - -LANGUAGE SUPPORT: - Chinese (Simplified, Traditional) - English - Korean - Japanese - Russian - French - German - Spanish - Portuguese - -================================================================================ -TECHNICAL DETAILS -================================================================================ - -FUNCTION USED: - types.LanguageLocaleName(locale string) string - Location: internal/types/context_helpers.go (lines 85-112) - -SUPPORTED LOCALE CODES: - Input → Output - zh-CN, zh, zh-Hans → Chinese (Simplified) - zh-TW, zh-HK, zh-Hant → Chinese (Traditional) - en-US, en, en-GB → English - ko-KR, ko → Korean - ja-JP, ja → Japanese - ru-RU, ru → Russian - fr-FR, fr → French - de-DE, de → German - es-ES, es → Spanish - pt-BR, pt → Portuguese - *other* → returned as-is - -PERFORMANCE: - 288,239,468 ops/sec - ~4.3 nanoseconds per call - O(1) lookup - No allocations - -================================================================================ -FILES MODIFIED -================================================================================ - -1. internal/application/service/wiki_ingest.go - Line 139: Refactored language determination logic - -2. internal/types/context_helpers_test.go (NEW) - Created comprehensive unit tests - 30 test cases - Full coverage of LanguageLocaleName() - -================================================================================ -TESTING -================================================================================ - -UNIT TESTS: - ✅ PASS: TestLanguageLocaleName (30 test cases) - ✅ PASS: BenchmarkLanguageLocaleName - - Test Coverage: - - All 9 language families - - All short codes (zh, en, ko, etc.) - - All regional variants (zh-TW, en-GB, etc.) - - Unknown locales (fallback) - - Edge cases (empty strings) - -BUILD VERIFICATION: - ✅ go build ./internal/application/service (success) - ✅ go build ./cmd/server (success) - ✅ No errors or breaking changes - -================================================================================ -BACKWARD COMPATIBILITY -================================================================================ - -✅ NO BREAKING CHANGES - - - Same function signature - - Same input/output types - - Identical behavior for all existing inputs - - No API changes - - No schema changes - - Unknown languages handled gracefully - -MIGRATION: None required - transparent improvement - -================================================================================ -DEPLOYMENT CHECKLIST -================================================================================ - -Pre-Deployment: - ✅ Code review ready - ✅ All tests passing - ✅ Build successful - ✅ Documentation complete - ✅ Performance verified - ✅ Backward compatible - -Post-Deployment: - - No database migrations required - - No configuration changes required - - No API changes required - - Can be deployed immediately - -================================================================================ -DOCUMENTATION -================================================================================ - -LOCATION: /Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/ - -FILES: - 1. LANGUAGE_MIDDLEWARE_ANALYSIS.md - - Comprehensive analysis of existing infrastructure - - Before/after comparison - - Integration points - - Migration path - - 2. LANGUAGE_REFACTORING_COMPLETED.md - - Completion report - - Verification checklist - - Technical details - - Future improvements - - 3. IMPLEMENTATION_GUIDE.md (this directory) - - Complete implementation guide - - Test coverage details - - Usage examples - - Troubleshooting - - 4. context_helpers_test.go - - 30 unit test cases - - Benchmark tests - - Full test coverage - -================================================================================ -CONTACT & QUESTIONS -================================================================================ - -Code Location: - - Main change: internal/application/service/wiki_ingest.go (line 139) - - Core function: internal/types/context_helpers.go (lines 85-112) - - Tests: internal/types/context_helpers_test.go - -To verify: - $ go test -v ./internal/types -run TestLanguageLocaleName - $ go test -bench=. ./internal/types -run BenchmarkLanguageLocaleName - -================================================================================ -SUMMARY STATISTICS -================================================================================ - -Lines of Code: - - Removed: 7 lines - - Added: 4 lines - - Net: -3 lines (43% reduction) - -Language Support: - - Before: 2 languages - - After: 9+ languages - - Increase: 350% - -Code Duplication: - - Before: Duplicated logic - - After: Eliminated (single source of truth) - -Performance: - - 4.3 nanoseconds per call - - No measurable impact - - Negligible vs LLM calls (seconds) - -Test Coverage: - - 30 unit test cases - - 100% coverage of language function - - All tests passing - -Build Status: - - ✅ Successful (243MB binary) - - ✅ No errors - - ✅ Ready for deployment - -================================================================================ -END OF SUMMARY -================================================================================ diff --git a/SESSION_2_COMPLETION_SUMMARY.md b/SESSION_2_COMPLETION_SUMMARY.md deleted file mode 100644 index 05404f34..00000000 --- a/SESSION_2_COMPLETION_SUMMARY.md +++ /dev/null @@ -1,418 +0,0 @@ -# Session 2 Completion Summary: Language Middleware Refactoring - -**Completion Date:** 2026-04-07 -**Overall Status:** ✅ SUCCESSFULLY COMPLETED -**Total Work Items:** 11 (All completed) - ---- - -## Executive Summary - -Building on the comprehensive Agent ReAct engine analysis completed in Session 1, Session 2 identified and successfully implemented a strategic refactoring opportunity: **consolidating language handling in the wiki ingest service to reuse existing middleware infrastructure**. - -### Key Achievement -**Reduced wiki ingest language logic from 6 lines to 1 line while expanding language support from 2 to 9+ languages and establishing a centralized maintenance point.** - ---- - -## Analysis and Documentation Work Completed - -### 1. ✅ Language Middleware Infrastructure Discovery - -**File:** `/internal/types/context_helpers.go` -**Key Function:** `LanguageLocaleName()` (lines 85-112) - -Discovered existing, production-ready language mapping infrastructure that supports: -- 9+ languages with multiple locale variants (20+ total mappings) -- Fallback behavior for unknown locales -- Clean, switch-based implementation -- Comprehensive test coverage - -**Verification Status:** ✅ Tests passing, documented in TestLanguageLocaleName - ---- - -### 2. ✅ Problem Identification - -**File:** `/internal/application/service/wiki_ingest.go` -**Problem Location:** Lines 135-141 (previous implementation) - -Identified code duplication: -- 6 lines of hardcoded if/else language mapping -- Only supported "zh" and "en" languages -- Separate from middleware infrastructure -- Manual synchronization required for language expansions - -**Impact Analysis:** -- Duplicated code exists in single location -- No other files need refactoring -- Clean, isolated refactoring scope - ---- - -### 3. ✅ Refactoring Implementation - -**Solution:** Replace hardcoded logic with centralized function - -**Before:** -```go -lang := "the same language as the source document" -if kb.WikiConfig.WikiLanguage == "zh" { - lang = "Chinese (中文)" -} else if kb.WikiConfig.WikiLanguage == "en" { - lang = "English" -} -``` - -**After:** -```go -lang := types.LanguageLocaleName(kb.WikiConfig.WikiLanguage) -``` - -**Benefits:** -- 83% code reduction (6 → 1 line) -- 9+ languages supported (up from 2) -- Single source of truth for language mappings -- Consistent with existing infrastructure -- 100% backward compatible - ---- - -### 4. ✅ Testing and Verification - -**Unit Tests:** All passing -- 28 test cases for LanguageLocaleName() -- Coverage: All 9+ languages and variants -- Fallback behavior tested -- Unknown locale handling verified - -**Build Verification:** -``` -$ go build ./internal/application/service -# No compilation errors or warnings -``` - -**Backward Compatibility:** -- ✅ Original "zh" values → "Chinese (Simplified)" -- ✅ Original "en" values → "English" -- ✅ No database schema changes -- ✅ No API contract changes -- ✅ Existing configurations remain functional - ---- - -### 5. ✅ Comprehensive Documentation - -Created 8 detailed analysis documents: - -#### Documentation Files Created - -| Document | Lines | Focus | Status | -|----------|-------|-------|--------| -| AGENT_WIKI_ANALYSIS.md | 492 | Agent ReAct engine architecture | Complete | -| LANGUAGE_MIDDLEWARE_ANALYSIS.md | 349 | Language infrastructure discovery | Complete | -| REFACTORING_PLAN.md | 204 | Implementation strategy | Complete | -| LANGUAGE_REFACTORING_QUICK_REFERENCE.md | 111 | Quick implementation guide | Complete | -| ANALYSIS_SUMMARY.md | 319 | Executive summary of findings | Complete | -| README_ANALYSIS.md | ~450 | Navigation index and roadmap | Complete | -| REFACTORING_IMPLEMENTATION_REPORT.md | ~280 | Implementation verification report | Complete | -| SESSION_2_COMPLETION_SUMMARY.md | This file | Session completion summary | Complete | - -**Total Documentation:** ~2,200 lines, ~75 KB - ---- - -## Key Findings from Session 2 - -### Language Middleware Infrastructure (NEW) - -**Location:** `/internal/types/context_helpers.go` (lines 85-112) - -**Function Signature:** -```go -func LanguageLocaleName(locale string) string -``` - -**Supported Languages:** -- Chinese (Simplified): zh-CN, zh, zh-Hans -- Chinese (Traditional): zh-TW, zh-HK, zh-Hant -- English: en-US, en, en-GB -- Korean: ko-KR, ko -- Japanese: ja-JP, ja -- Russian: ru-RU, ru -- French: fr-FR, fr -- German: de-DE, de -- Spanish: es-ES, es -- Portuguese: pt-BR, pt - -**Related Infrastructure:** -- `middleware/language.go` - HTTP language extraction -- `types/context_helpers.go` - Language name mapping -- HTTP header language detection integrated throughout system - -### Code Architecture Patterns - -**Pattern 1: Reusable Infrastructure** -The system establishes reusable infrastructure functions that should be leveraged rather than duplicated: -- Language functions in `types` package designed for service layer reuse -- Middleware provides HTTP extraction; types package provides business logic mapping - -**Pattern 2: Centralized Maintenance** -Moving to centralized functions enables: -- Single source of truth for language mappings -- Consistent naming across all services -- Easy expansion to new languages (edit one location) -- Future optimization for LLM performance per language - -**Pattern 3: Backward Compatibility** -Refactoring maintains full backward compatibility: -- No database changes required -- No API changes required -- Existing configurations continue working -- Fallback behavior for unknown values - ---- - -## Session 1 vs Session 2: Context Building - -### Session 1: Agent Architecture Analysis -**Questions Answered:** -1. How does Agent ReAct engine dispatch tools? (Automatic via LLM decision) -2. What system prompts does Agent use? (Progressive RAG or Pure Agent templates) -3. How does Agent know about wiki tools? (Runtime detection of wiki KBs) -4. Is there a dedicated wiki system prompt? (No - tools are discoverable via registry) - -**Deliverable:** AGENT_WIKI_ANALYSIS.md (492 lines) - -### Session 2: Infrastructure Reuse Opportunity -**Discovery:** While analyzing language usage in wiki_ingest.go, identified existing centralized language mapping -**Outcome:** Documented refactoring opportunity with full implementation guidance -**Deliverable:** LANGUAGE_MIDDLEWARE_ANALYSIS.md + implementation documents (8 documents total) - ---- - -## Implementation Checklist - -### Code Changes -- [x] Refactoring completed in wiki_ingest.go (line 139) -- [x] Import verified (types package imported at line 14) -- [x] Function call syntax correct -- [x] Comment documentation added - -### Testing -- [x] Unit tests passing (TestLanguageLocaleName: 28/28 pass) -- [x] Build successful (go build ./internal/application/service) -- [x] No compilation warnings -- [x] Backward compatibility verified - -### Documentation -- [x] Implementation report created -- [x] Test results documented -- [x] Supported languages listed -- [x] Future enhancement opportunities identified -- [x] Rollback plan documented - -### Deployment Readiness -- [x] No database migrations required -- [x] No API changes required -- [x] No environment variable changes required -- [x] No deployment ordering constraints -- [x] Ready for immediate deployment - ---- - -## Supported Language Mappings - -### Current Support (Post-Refactoring) - -``` -zh-CN, zh, zh-Hans → Chinese (Simplified) -zh-TW, zh-HK, zh-Hant → Chinese (Traditional) -en-US, en, en-GB → English -ko-KR, ko → Korean -ja-JP, ja → Japanese -ru-RU, ru → Russian -fr-FR, fr → French -de-DE, de → German -es-ES, es → Spanish -pt-BR, pt → Portuguese -[unknown] → [returned unchanged] -``` - -### Previous Support (Pre-Refactoring) - -``` -zh → Chinese (中文) -en → English -[all others] → the same language as the source document [fallback] -``` - -**Migration Path:** 100% compatible. Existing configurations continue working. - ---- - -## Future Enhancement Roadmap - -### Phase 2: Extended Language Coverage -- Add: Italian, Dutch, Swedish, Thai, Vietnamese -- Modification Location: `/internal/types/context_helpers.go` -- Effort: Minimal (simple switch cases) - -### Phase 3: Language-Specific LLM Optimization -- Context-aware language name variants per LLM model -- Different names perform better with different models -- Example: Claude prefers full names; other models might prefer codes - -### Phase 4: Language Detection Automation -- Integrate document language detection -- Automatic language inference from content -- Override with KB-configured language preference - -### Phase 5: Multi-Language Wiki Pages -- Support per-page language overrides -- Bi-lingual content support -- Language-specific search ranking - ---- - -## Metrics and Impact - -### Code Metrics -| Metric | Before | After | Change | -|--------|--------|-------|--------| -| Lines in wiki_ingest (lang logic) | 6 | 1 | -83% | -| Languages supported | 2 | 9+ | +350% | -| Maintenance locations | 1 | 1 | No change | -| Code duplication | High | None | Eliminated | - -### Maintainability -| Aspect | Impact | -|--------|--------| -| Time to add new language | Minutes | Hours → Minutes | -| Risk of inconsistent naming | Eliminated | Single source of truth | -| Test coverage | Comprehensive | All variants covered | -| API changes needed | None | Zero impact | - ---- - -## Technical Details - -### Function Chain Analysis - -**Wiki Ingest Process Language Flow:** -``` -ProcessWikiIngest() [line 85] - ↓ -kb.WikiConfig.WikiLanguage [retrieved from KB config] - ↓ -types.LanguageLocaleName(locale) [line 139] - ↓ -Switches on locale code: - - Exact match: zh-CN → "Chinese (Simplified)" - - Short code: zh → "Chinese (Simplified)" - - Variant: zh-Hans → "Chinese (Simplified)" - - Unknown: pt-XX → "pt-XX" [fallback] - ↓ -Passed to LLM prompts: - - WikiSummaryPrompt [line 166] - - WikiKnowledgeExtractPrompt [line 240] - - WikiPageUpdatePrompt [line 304] - - WikiIndexRebuildPrompt [line 413] -``` - -### Test Coverage Analysis - -**Test Cases (28 total):** -- Chinese (Simplified): zh-CN, zh, zh-Hans (3 cases) -- Chinese (Traditional): zh-TW, zh-HK, zh-Hant (3 cases) -- English: en-US, en, en-GB (3 cases) -- Korean: ko-KR, ko (2 cases) -- Japanese: ja-JP, ja (2 cases) -- Russian: ru-RU, ru (2 cases) -- French: fr-FR, fr (2 cases) -- German: de-DE, de (2 cases) -- Spanish: es-ES, es (2 cases) -- Portuguese: pt-BR, pt (2 cases) -- Edge cases: empty string, unknown code (2 cases) - -**Coverage:** 100% of supported locales and edge cases - ---- - -## Related Documentation Cross-References - -### Session 1 Documentation (Preserved) -- AGENT_WIKI_ANALYSIS.md - Complete Agent architecture -- Analyzed: ReAct loop, tool dispatch, system prompts, wiki tool registration - -### Session 2 Documentation (New) -- LANGUAGE_MIDDLEWARE_ANALYSIS.md - Infrastructure discovery -- REFACTORING_PLAN.md - Implementation strategy with code diffs -- LANGUAGE_REFACTORING_QUICK_REFERENCE.md - Quick start guide -- REFACTORING_IMPLEMENTATION_REPORT.md - Verification and test results -- ANALYSIS_SUMMARY.md - Questions answered and recommendations -- README_ANALYSIS.md - Navigation index for all documentation -- SESSION_2_COMPLETION_SUMMARY.md - This file - -**Total Documentation Across Both Sessions:** ~2,700 lines, ~90 KB - ---- - -## Conclusion - -Session 2 successfully achieved its objectives: - -1. ✅ **Analyzed existing language infrastructure** - Identified `types.LanguageLocaleName()` function supporting 9+ languages - -2. ✅ **Identified refactoring opportunity** - Found 6 lines of duplicate hardcoded logic in wiki_ingest.go - -3. ✅ **Implemented refactoring** - Replaced with single-line call to centralized function - -4. ✅ **Verified correctness** - All tests pass, code builds without errors, backward compatibility confirmed - -5. ✅ **Documented comprehensively** - Created 8 detailed documents explaining findings, implementation, and future opportunities - -The refactoring achieves the goal of leveraging existing middleware infrastructure for consistent, maintainable, and expandable language handling across the system. - ---- - -## Quick Start for Next Steps - -### If deploying immediately: -```bash -# Code is ready - all changes in wiki_ingest.go completed -git add internal/application/service/wiki_ingest.go -git commit -m "refactor: consolidate language mapping to reuse middleware infrastructure" -``` - -### If expanding language support: -1. Edit `/internal/types/context_helpers.go` -2. Add new case to switch statement in `LanguageLocaleName()` -3. Run: `go test ./internal/types` -4. Language automatically available to all services - -### If optimizing for specific LLMs: -1. Reference REFACTORING_PLAN.md Phase 3 section -2. Extend LanguageLocaleName() with language-specific variants -3. Modify wiki_ingest.go to pass additional context to function - ---- - -## Files Modified - -- `/internal/application/service/wiki_ingest.go` - Line 139 (language determination) - -## Files Created (Documentation) - -- AGENT_WIKI_ANALYSIS.md -- LANGUAGE_MIDDLEWARE_ANALYSIS.md -- REFACTORING_PLAN.md -- LANGUAGE_REFACTORING_QUICK_REFERENCE.md -- ANALYSIS_SUMMARY.md -- README_ANALYSIS.md -- REFACTORING_IMPLEMENTATION_REPORT.md -- SESSION_2_COMPLETION_SUMMARY.md (this file) - ---- - -**Status: Ready for production deployment** ✅ diff --git a/START_HERE.md b/START_HERE.md deleted file mode 100644 index 978adc49..00000000 --- a/START_HERE.md +++ /dev/null @@ -1,225 +0,0 @@ -# 🚀 START HERE - WeKnora Analysis Project - -**Welcome!** This document helps you navigate the WeKnora Analysis Project documentation. - ---- - -## Quick Facts - -- **Project Status:** ✅ COMPLETE -- **Code Refactoring:** Implemented and tested -- **Documentation:** 10 comprehensive files -- **Production Ready:** YES ⭐⭐⭐⭐⭐ - ---- - -## What Was Done? - -### Analysis (Session 1) -Comprehensive analysis of the WeKnora Agent ReAct engine, answering 4 key research questions: -1. How does the Agent dispatch tools? (Automatic via LLM) -2. What system prompts exist? (Progressive RAG or Pure Agent) -3. How does Agent discover wiki tools? (Runtime KB detection) -4. Is there a wiki-specific system prompt? (No) - -### Implementation (Session 2) -Strategic refactoring of language handling: -- **File Modified:** `internal/application/service/wiki_ingest.go` (line 139) -- **Change:** 6 lines → 1 line (-83% code reduction) -- **Result:** Language support expanded 2 → 9+ languages -- **Status:** Tested and verified ✅ - ---- - -## How to Get Started - -### ⏱️ I have 5 minutes -Read: **INDEX_ALL_ANALYSIS.md** - -Quick overview of the entire project, all files, and navigation paths. - ---- - -### ⏱️ I have 15 minutes -Read in order: -1. **SESSION_2_COMPLETION_SUMMARY.md** (10 min) - - What was accomplished in Session 2 -2. **ANALYSIS_SUMMARY.md** (5 min) - - Executive summary of findings - ---- - -### ⏱️ I have 30 minutes -Read in order: -1. **INDEX_ALL_ANALYSIS.md** (5 min) - - Project overview -2. **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** (5 min) - - Quick implementation guide -3. **REFACTORING_IMPLEMENTATION_REPORT.md** (10 min) - - Verification and test results -4. **ANALYSIS_SUMMARY.md** (10 min) - - Executive summary - ---- - -### ⏱️ I have 1 hour -Complete deep dive: -1. **AGENT_WIKI_ANALYSIS.md** (20 min) - - Complete Agent architecture -2. **LANGUAGE_MIDDLEWARE_ANALYSIS.md** (15 min) - - Infrastructure discovery -3. **REFACTORING_PLAN.md** (10 min) - - Implementation strategy -4. **ANALYSIS_SUMMARY.md** (5 min) - - Summary and recommendations -5. **README_ANALYSIS.md** (10 min) - - Navigation index - ---- - -### ⏱️ I have 2 hours -Complete mastery: -Follow the 1-hour path, then read: -- **PROJECT_COMPLETION_REPORT.md** (20 min) - - Quality assurance and deployment readiness -- **SESSION_2_COMPLETION_SUMMARY.md** (20 min) - - Complete Session 2 context and next steps - ---- - -## I'm Looking For... - -### Code Implementation Details -→ **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** - -Copy-paste ready code, testing checklist, and deployment steps. - -### Agent Architecture Understanding -→ **AGENT_WIKI_ANALYSIS.md** - -Complete documentation of the ReAct engine, tool dispatch, system prompts. - -### Refactoring Strategy -→ **REFACTORING_PLAN.md** - -Detailed implementation approach with code diffs and testing strategy. - -### Test Results and Verification -→ **REFACTORING_IMPLEMENTATION_REPORT.md** - -All test results, build verification, backward compatibility confirmation. - -### Executive Summary -→ **ANALYSIS_SUMMARY.md** - -High-level findings and recommendations organized by timeline. - -### Project Navigation -→ **README_ANALYSIS.md** or **INDEX_ALL_ANALYSIS.md** - -Comprehensive navigation guides with multiple entry points. - -### Implementation Steps -→ **PROJECT_COMPLETION_REPORT.md** (Deployment Instructions section) - -Ready-to-use deployment steps. - ---- - -## Quick Navigation Map - -``` -START HERE - ↓ -Are you busy? (<15 min) - ├→ INDEX_ALL_ANALYSIS.md (5 min overview) - └→ SESSION_2_COMPLETION_SUMMARY.md (15 min status) - -Want implementation details? (15-30 min) - ├→ LANGUAGE_REFACTORING_QUICK_REFERENCE.md (5 min) - └→ REFACTORING_IMPLEMENTATION_REPORT.md (15 min) - -Want to understand architecture? (30-60 min) - ├→ AGENT_WIKI_ANALYSIS.md (20 min) - ├→ LANGUAGE_MIDDLEWARE_ANALYSIS.md (15 min) - └→ REFACTORING_PLAN.md (10 min) - -Want everything? (90+ min) - ├→ Follow 1-hour path above - ├→ PROJECT_COMPLETION_REPORT.md (20 min) - └→ SESSION_2_COMPLETION_SUMMARY.md (20 min) -``` - ---- - -## All Files Available - -### Core Analysis -- ✅ **AGENT_WIKI_ANALYSIS.md** (16 KB) - Agent architecture deep dive -- ✅ **LANGUAGE_MIDDLEWARE_ANALYSIS.md** (11 KB) - Infrastructure discovery - -### Implementation & Planning -- ✅ **REFACTORING_PLAN.md** (6.3 KB) - Strategy and approach -- ✅ **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** (3.0 KB) - Quick start guide -- ✅ **REFACTORING_IMPLEMENTATION_REPORT.md** (7.8 KB) - Verification results - -### Executive & Navigation -- ✅ **ANALYSIS_SUMMARY.md** (11 KB) - Executive summary -- ✅ **README_ANALYSIS.md** (13 KB) - Comprehensive navigation -- ✅ **INDEX_ALL_ANALYSIS.md** (17 KB) - Complete project index -- ✅ **SESSION_2_COMPLETION_SUMMARY.md** (13 KB) - Session wrap-up - -### Completion & Status -- ✅ **PROJECT_COMPLETION_REPORT.md** - Quality assurance and deployment -- ✅ **START_HERE.md** (This file) - Navigation hub - ---- - -## Key Statistics - -| Metric | Value | -|--------|-------| -| **Total Files** | 10 comprehensive documents | -| **Total Content** | ~3,000 lines, ~100 KB | -| **Code Changes** | 1 file, line 139 | -| **Impact** | 83% code reduction, 9+ languages | -| **Tests Passing** | 28/28 (100%) | -| **Risk Level** | LOW | -| **Production Ready** | YES ✅ | - ---- - -## Next Steps - -### If Deploying -1. Read: **LANGUAGE_REFACTORING_QUICK_REFERENCE.md** (5 min) -2. Follow: Deployment checklist (5 min) -3. Execute: 5-step deployment process (10 min) - -### If Understanding Code -1. Read: **AGENT_WIKI_ANALYSIS.md** (20 min) -2. Read: **LANGUAGE_MIDDLEWARE_ANALYSIS.md** (15 min) -3. Reference: **REFACTORING_PLAN.md** (10 min) - -### If Onboarding Team -1. Start: This file (2 min) -2. Navigate: **INDEX_ALL_ANALYSIS.md** (5 min) -3. Deep Dive: Choose your path (30-90 min) - ---- - -## Project Complete ✅ - -**Status:** All objectives achieved -**Quality:** Production-ready -**Documentation:** Comprehensive -**Next Phase:** Deployment ready - ---- - -**Last Updated:** 2026-04-07 -**Project Score:** ⭐⭐⭐⭐⭐ (5/5) - ---- - -### 👉 **Next Document:** INDEX_ALL_ANALYSIS.md diff --git a/WEKNORA_ANALYSIS_SUMMARY.md b/WEKNORA_ANALYSIS_SUMMARY.md deleted file mode 100644 index 4cba46e2..00000000 --- a/WEKNORA_ANALYSIS_SUMMARY.md +++ /dev/null @@ -1,537 +0,0 @@ -# WeKnora Knowledge Base System - Complete Analysis Summary - -**Date:** April 20, 2026 -**Status:** Comprehensive exploration completed with actionable findings - ---- - -## Quick Navigation - -This directory now contains three detailed analysis documents: - -1. **[KB_WIKI_ARCHITECTURE_ANALYSIS.md](./KB_WIKI_ARCHITECTURE_ANALYSIS.md)** (1000+ lines) - - Complete system architecture - - All data models (KnowledgeBase, Knowledge, Chunk, WikiPage, Agent) - - Database schema mapping - - Service layer interfaces - - All API endpoints - - Full data flow diagrams - - Configuration hierarchy - -2. **[WIKI_CONFIG_FLOW_ANALYSIS.md](./WIKI_CONFIG_FLOW_ANALYSIS.md)** (500+ lines) - - Problem identification: Wiki config updates broken - - Exact root cause analysis - - Step-by-step flow tracing - - **3 required code fixes** with exact line numbers - - Impact assessment - -3. **[IMPLEMENTATION_PLAN.md](../plans/woolly-jumping-rabin-agent-a4799b0d64a0d4f44.md)** - - Detailed fix implementation roadmap - - Testing strategy - - Risk assessment - - Success criteria - ---- - -## Executive Summary - -### What We Found - -The WeKnora system is a sophisticated **multi-tenant knowledge management platform** with integrated wiki functionality. The architecture properly supports: - -✅ Knowledge base creation with wiki configuration -✅ Document ingestion and chunking (vector + keyword indexing) -✅ Automatic wiki page generation from documents -✅ Agent integration with KB access and tools -✅ Multi-modal processing (vision, audio, text) - -### The Critical Issue - -⚠️ **Wiki configuration updates are BROKEN** - -Users can create a KB with wiki enabled, but **cannot edit wiki settings afterwards** due to a missing field in the backend struct. - -**Root Cause:** `WikiConfig` is missing from `KnowledgeBaseConfig` struct (used in update operations) - -**Impact:** Users can: -- ✅ Create KB with wiki enabled -- ❌ Cannot edit/disable wiki after creation -- ❌ Cannot change synthesis model -- ❌ Cannot change auto-ingest settings - -**Scope:** Small - only 3 backend struct fields + 1 service method need modification - ---- - -## System Architecture At a Glance - -### Data Model Hierarchy - -``` -Tenant (multi-tenant isolation) -├── KnowledgeBase (document/faq/wiki types) -│ ├── WikiConfig (optional feature on document KBs) -│ ├── ChunkingConfig (document splitting settings) -│ ├── FAQConfig (if type = faq) -│ └── Knowledge[] (documents in KB) -│ └── Chunk[] (indexed content units) -│ ├── Vector embedding -│ └── Keyword index -│ -├── WikiPage[] (generated from documents) -│ ├── SourceRefs[] (Knowledge IDs that created this page) -│ ├── InLinks/OutLinks (wiki link graph) -│ └── WikiPageIssue[] (problem tracking) -│ -└── Agent[] (RAG agents) - ├── AgentConfig.KnowledgeBases[] (KB access list) - ├── Wiki tools (read_page, write_page, etc.) - └── Knowledge tools (search, list_chunks, etc.) -``` - -### Processing Pipeline - -``` -Document Upload - ↓ -1. Parse & Split (ChunkingConfig) - ├─ Size: 100-4000 chars (default 512) - ├─ Overlap: 0-500 chars (default 100) - └─ Parent-Child: optional 2-level hierarchy - ↓ -2. Embed & Index (Hybrid) - ├─ Vector indexing (semantic search) - └─ Keyword indexing (BM25) - ↓ -3. IF WikiConfig.AutoIngest: - └─ Async Wiki Ingest (LLM-powered) - ├─ Generate summary page - ├─ Extract entities → entity pages - ├─ Extract concepts → concept pages - ├─ Build wiki link graph - └─ Rate limit: MaxPagesPerIngest per batch -``` - -### Frontend Architecture - -**Main Components:** - -| Component | Purpose | File | -|-----------|---------|------| -| **KnowledgeBaseEditorModal** | Main KB settings UI with sidebar | `frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue` | -| **KBStorageSettings** | Storage engine selection | `frontend/src/views/knowledge/settings/KBStorageSettings.vue` | -| **KBChunkingSettings** | Document chunking config | `frontend/src/views/knowledge/settings/KBChunkingSettings.vue` | -| **GraphSettings** | Knowledge graph/entity extraction | `frontend/src/views/knowledge/settings/GraphSettings.vue` | -| **KBAdvancedSettings** | Question generation config | `frontend/src/views/knowledge/settings/KBAdvancedSettings.vue` | - -**Wiki Settings:** Inline in KnowledgeBaseEditorModal.vue (lines 123-187) - -**API Client:** `frontend/src/api/knowledge-base/index.ts` - ---- - -## Backend Architecture - -### Key Services - -| Service | Location | Responsibilities | -|---------|----------|------------------| -| **KnowledgeBaseService** | `internal/application/service/knowledgebase.go` | Create, read, update, delete KBs | -| **KnowledgeService** | `internal/application/service/knowledge.go` | Document ingest, parse, chunk | -| **WikiIngestService** | `internal/application/service/wiki_ingest.go` | Async wiki page generation | -| **WikiPageService** | `internal/application/service/wiki_page.go` | Wiki CRUD, link maintenance | -| **RetrievalEngine** | `internal/application/service/retriever/` | Hybrid vector+keyword search | - -### Key Handlers - -| Handler | Route | Responsibilities | -|---------|-------|------------------| -| **KnowledgeBaseHandler** | `/api/v1/knowledge-bases` | KB CRUD | -| **KnowledgeHandler** | `/api/v1/knowledge-bases/{id}/knowledge` | Document ingest | -| **WikiPageHandler** | `/api/v1/knowledgebase/{kb_id}/wiki/pages` | Wiki page management | - -### Request/Response Types - -**CreateKnowledgeBase:** -```go -POST /api/v1/knowledge-bases -{ - "name": "My KB", - "type": "document", - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4", - "wiki_language": "en", - "max_pages_per_ingest": 5 - }, - "chunking_config": { ... }, - "embedding_model_id": "model-123" -} -``` - -**UpdateKnowledgeBase (CURRENTLY BROKEN):** -```go -PUT /api/v1/knowledge-bases/{id} -{ - "name": "Updated Name", - "description": "...", - "config": { - "chunking_config": { ... }, - "image_processing_config": { ... }, - "faq_config": { ... }, - // ❌ wiki_config CANNOT be sent here (struct field missing) - } -} -``` - ---- - -## The Bug in Detail - -### What's Wrong - -**File:** `internal/types/knowledgebase.go` - -```go -// ✅ This struct is used for creation and has all fields: -type KnowledgeBase struct { - ID string - WikiConfig *WikiConfig // ✅ PRESENT - ChunkingConfig ChunkingConfig - // ... all fields ... -} - -// ❌ This struct is used for updates and MISSING WikiConfig: -type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig - ImageProcessingConfig ImageProcessingConfig - FAQConfig *FAQConfig - // ❌ WikiConfig MISSING - no way to update it! -} -``` - -### Why It Breaks - -**Handler Layer:** `internal/handler/knowledgebase.go` - -```go -// Create handler accepts full KnowledgeBase (works fine) -func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) { - var req types.KnowledgeBase // ✅ Has WikiConfig - // ... serializes to DB with wiki_config -} - -// Update handler accepts KnowledgeBaseConfig (breaks wiki settings) -func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) { - var req struct { - Config *types.KnowledgeBaseConfig // ❌ Missing WikiConfig - } - // ... JSON unmarshaling silently ignores wiki_config in request -} -``` - -**Service Layer:** `internal/application/service/knowledgebase.go` - -```go -// Update service only updates what's in config -func (s *knowledgeBaseService) UpdateKnowledgeBase( - ctx context.Context, - id string, - name string, - description string, - config *types.KnowledgeBaseConfig, // ❌ Missing WikiConfig -) (*types.KnowledgeBase, error) { - // ... gets existing KB ... - - if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - // ❌ NO CODE: if config.WikiConfig != nil { kb.WikiConfig = config.WikiConfig } - } - - // ... saves KB with UNCHANGED wiki_config -} -``` - ---- - -## The Fix - -### 3 Simple Changes Required - -#### Fix 1: Add WikiConfig to KnowledgeBaseConfig Struct -**File:** `internal/types/knowledgebase.go` (after line 106) - -Add this line: -```go -WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config"` -``` - -#### Fix 2: Update Service Method -**File:** `internal/application/service/knowledgebase.go` (after line 275) - -Add these lines: -```go -if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig -} -``` - -#### Fix 3 (Optional): Update Frontend Types -**File:** `frontend/src/api/knowledge-base/index.ts` - -Add `wiki_config` to the type hint. - -**Result:** Users can now edit wiki settings after KB creation ✅ - ---- - -## Configuration Reference - -### Wiki Settings Available - -```typescript -{ - enabled: boolean // Enable/disable wiki feature - auto_ingest: boolean // Auto-generate pages when docs added - synthesis_model_id: string // LLM model for page generation - wiki_language: string // Preferred language (zh/en/auto) - max_pages_per_ingest: number // Rate limit per batch (0=unlimited) -} -``` - -### Chunking Settings Available - -```typescript -{ - chunkSize: number // 100-4000 (default: 512) - chunkOverlap: number // 0-500 (default: 100) - separators: string[] // Custom delimiters - enableParentChild: boolean // Two-level hierarchy - parentChunkSize: number // 512-8192 (when enabled) - childChunkSize: number // 64-2048 (when enabled) -} -``` - ---- - -## Frontend Component Map - -### Wiki Settings UI -- **Located in:** `KnowledgeBaseEditorModal.vue` lines 123-187 -- **Not in separate file** - inline implementation -- **Form fields:** - - Toggle: Enable Wiki - - Toggle: Auto Ingest - - Select: Synthesis Model (LLM) - - Input: Max Pages Per Ingest - -### Related Settings -- **Storage:** `KBStorageSettings.vue` - Choose storage backend -- **Chunking:** `KBChunkingSettings.vue` - Document split settings -- **Knowledge Graph:** `GraphSettings.vue` - Entity extraction -- **Advanced:** `KBAdvancedSettings.vue` - Question generation - -### Form Submission -- **Lines 785-792:** Submit data including wiki_config -- **But:** Backend currently ignores it due to struct bug - ---- - -## API Endpoints Reference - -### Knowledge Base Management -``` -GET /api/v1/knowledge-bases List all KBs -POST /api/v1/knowledge-bases Create KB (with wiki_config) -GET /api/v1/knowledge-bases/{id} Get KB details -PUT /api/v1/knowledge-bases/{id} Update KB (wiki_config broken) -DELETE /api/v1/knowledge-bases/{id} Delete KB -``` - -### Wiki Page Management -``` -GET /api/v1/knowledgebase/{kb_id}/wiki/pages List pages -POST /api/v1/knowledgebase/{kb_id}/wiki/pages Create page -GET /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} Get page -PUT /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} Update page -GET /api/v1/knowledgebase/{kb_id}/wiki/stats Statistics -``` - -### Document Management -``` -GET /api/v1/knowledge-bases/{kb_id}/knowledge List documents -POST /api/v1/knowledge-bases/{kb_id}/knowledge/file Upload file -POST /api/v1/knowledge-bases/{kb_id}/knowledge/url Add from URL -POST /api/v1/knowledge-bases/{kb_id}/knowledge/manual Create manual -``` - ---- - -## Key Findings by Category - -### ✅ Working Correctly - -1. **KB Creation with Wiki** - Users can create KB with wiki_config -2. **Hybrid Search** - Vector + keyword indexing works properly -3. **Document Parsing** - Chunking with parent-child support functional -4. **Wiki Page Generation** - LLM-based wiki creation from docs -5. **Agent Integration** - Agents can access KBs and wiki pages -6. **Multi-modal Support** - VLM and ASR pipelines operational - -### ⚠️ Needs Attention - -1. **Wiki Settings Update** - Cannot modify wiki config after creation (THE BUG) -2. **Type Hints** - Frontend API types missing wiki_config -3. **Storage Settings** - Need to ensure storage provider persistence - -### 📋 As Designed - -1. **Wiki as Feature** - Not a KB type, but optional add-on to document KBs -2. **Async Processing** - Document ingest triggers async wiki generation -3. **Rate Limiting** - MaxPagesPerIngest bounds wiki batch size -4. **Link Graph** - Bidirectional page linking with analytics -5. **Issue Tracking** - System for flagging wiki page problems - ---- - -## Testing the Fix - -### Before Fix (Reproduction Steps) - -1. Create KB with wiki enabled -2. Load KB in settings -3. Try to change synthesis model ID -4. Save -5. **Reload page** → Model ID hasn't changed ❌ - -### After Fix (Verification Steps) - -1. Create KB with wiki enabled ✅ -2. Load KB in settings ✅ -3. Change synthesis model ID ✅ -4. Save ✅ -5. Reload page → Model ID IS changed ✅ - ---- - -## File Summary - -### Analysis Documents Generated - -| File | Size | Content | -|------|------|---------| -| `KB_WIKI_ARCHITECTURE_ANALYSIS.md` | 1000+ lines | Complete architecture, all data models, APIs, flows | -| `WIKI_CONFIG_FLOW_ANALYSIS.md` | 500+ lines | Problem analysis, root cause, exact fixes | -| `WEKNORA_ANALYSIS_SUMMARY.md` | This file | Quick reference guide | - -### Key Source Files - -**Backend (Go)** -- `internal/types/knowledgebase.go` - Type definitions -- `internal/types/wiki_page.go` - WikiConfig struct -- `internal/application/service/knowledgebase.go` - Business logic -- `internal/handler/knowledgebase.go` - HTTP handlers -- `internal/application/repository/knowledgebase.go` - Database layer - -**Frontend (TypeScript/Vue)** -- `frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue` - Main UI -- `frontend/src/api/knowledge-base/index.ts` - API client -- `frontend/src/views/knowledge/settings/*.vue` - Settings components - ---- - -## Next Steps - -### For Fixing the Bug (Phase 1) - -1. ✅ Read this summary -2. ✅ Read the detailed analysis documents (see references above) -3. Make 3 code changes (details in WIKI_CONFIG_FLOW_ANALYSIS.md) -4. Run tests -5. Commit changes - -### For Full System Understanding (Phase 2) - -1. Study the architecture document -2. Map out the data flow -3. Understand agent-KB connections -4. Review retrieval engine (hybrid indexing) -5. Trace wiki ingest pipeline - -### For Feature Development (Phase 3) - -1. Understand configuration hierarchy -2. Review validation in EnsureDefaults() -3. Check error handling patterns -4. Study test patterns in existing tests -5. Follow commit message conventions - ---- - -## Documentation Quality - -✅ **Comprehensive** - 2000+ lines covering all aspects -✅ **Actionable** - Exact file paths and line numbers for all fixes -✅ **Detailed** - Code snippets, data models, API specs -✅ **Visual** - Flow diagrams, data hierarchies, component maps -✅ **Practical** - Testing strategies, risk assessment - ---- - -## Questions This Documentation Answers - -- ❓ What is the Knowledge Base system architecture? - → See KB_WIKI_ARCHITECTURE_ANALYSIS.md sections 1-7 - -- ❓ How does Wiki integration work? - → See KB_WIKI_ARCHITECTURE_ANALYSIS.md section 5 - -- ❓ What's wrong with wiki settings updates? - → See WIKI_CONFIG_FLOW_ANALYSIS.md (complete breakdown) - -- ❓ How do I fix the bug? - → See WIKI_CONFIG_FLOW_ANALYSIS.md "Required Fixes" section - -- ❓ What files do I need to change? - → See this file "The Fix" section with exact locations - -- ❓ How does document processing work? - → See KB_WIKI_ARCHITECTURE_ANALYSIS.md sections 3-4 - -- ❓ How do agents connect to KBs? - → See KB_WIKI_ARCHITECTURE_ANALYSIS.md section 6 - -- ❓ What are the database tables? - → See KB_WIKI_ARCHITECTURE_ANALYSIS.md section 8 - -- ❓ What API endpoints are available? - → See KB_WIKI_ARCHITECTURE_ANALYSIS.md section 10 - -- ❓ How do I test the changes? - → See implementation plan document - ---- - -## Support for Implementation - -All necessary information is provided: - -✅ Exact line numbers for each change -✅ Before/after code snippets -✅ Rationale for each change -✅ Testing strategy -✅ Risk assessment -✅ Success criteria - -**Ready to implement:** Yes, with full documentation support ✅ - ---- - -**Generated:** April 20, 2026 -**Analysis Scope:** Frontend KB settings + Backend wiki config pipeline -**Status:** Complete and actionable diff --git a/WIKI_CONFIG_FIX.md b/WIKI_CONFIG_FIX.md deleted file mode 100644 index 5c5137c1..00000000 --- a/WIKI_CONFIG_FIX.md +++ /dev/null @@ -1,328 +0,0 @@ -# Wiki Config Fix - Complete Implementation Guide - -## Problem Statement -The `wiki_config` field cannot be updated via the KB update endpoint because `KnowledgeBaseConfig` struct is missing the `WikiConfig` field. - -## Solution Overview -Add `WikiConfig` field to `KnowledgeBaseConfig` struct and update the service layer to persist it. - ---- - -## Change 1: Update Type Definition - -**File:** `internal/types/knowledgebase.go` - -**Location:** Lines 99-107 - -**Current Code:** -```go -// KnowledgeBaseConfig represents the knowledge base configuration -type KnowledgeBaseConfig struct { - // Chunking configuration - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"` - // Image processing configuration - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"` - // FAQ configuration (only for FAQ type knowledge bases) - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"` -} -``` - -**Fixed Code:** -```go -// KnowledgeBaseConfig represents the knowledge base configuration -type KnowledgeBaseConfig struct { - // Chunking configuration - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"` - // Image processing configuration - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"` - // FAQ configuration (only for FAQ type knowledge bases) - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"` - // Wiki configuration (for document type knowledge bases with wiki feature enabled) - WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config"` -} -``` - -**Changes:** -- Added `WikiConfig *WikiConfig` field with proper YAML and JSON tags - ---- - -## Change 2: Update Service Layer - -**File:** `internal/application/service/knowledgebase.go` - -**Location:** Lines 265-311 (UpdateKnowledgeBase method) - -**Current Code (Lines 288-297):** -```go - // Update the knowledge base properties - kb.Name = name - kb.Description = description - if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - } -``` - -**Fixed Code:** -```go - // Update the knowledge base properties - kb.Name = name - kb.Description = description - if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig - } - } -``` - -**Changes:** -- Added conditional check to update `kb.WikiConfig` from `config.WikiConfig` - ---- - -## Change 3: Update Frontend Type Hints (Optional but Recommended) - -**File:** `frontend/src/api/knowledge-base/index.ts` - -**Location:** Lines 11-33 (createKnowledgeBase function) - -**Current Code:** -```typescript -export function createKnowledgeBase(data: { - name: string; - description?: string; - type?: 'document' | 'faq'; - chunking_config?: any; - embedding_model_id?: string; - summary_model_id?: string; - vlm_config?: { - enabled: boolean; - model_id?: string; - }; - storage_provider_config?: { provider: string }; - storage_config?: any; // legacy, kept for backward compat (dual-write) - asr_config?: { - enabled: boolean; - model_id?: string; - language?: string; - }; - extract_config?: any; - faq_config?: { index_mode: string; question_index_mode?: string }; -}) { - return post(`/api/v1/knowledge-bases`, data); -} -``` - -**Fixed Code:** -```typescript -export function createKnowledgeBase(data: { - name: string; - description?: string; - type?: 'document' | 'faq'; - chunking_config?: any; - embedding_model_id?: string; - summary_model_id?: string; - vlm_config?: { - enabled: boolean; - model_id?: string; - }; - storage_provider_config?: { provider: string }; - storage_config?: any; // legacy, kept for backward compat (dual-write) - asr_config?: { - enabled: boolean; - model_id?: string; - language?: string; - }; - extract_config?: any; - faq_config?: { index_mode: string; question_index_mode?: string }; - wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; - }; -}) { - return post(`/api/v1/knowledge-bases`, data); -} -``` - -**Changes:** -- Added `wiki_config` property with full type definition for better IDE autocomplete - ---- - -## Testing - -### Test Case 1: Create KB with wiki_config - -```bash -curl -X POST http://localhost:8080/api/v1/knowledge-bases \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer " \ - -d '{ - "name": "Test KB with Wiki", - "type": "document", - "embedding_model_id": "text-embedding-ada-002", - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4", - "wiki_language": "en" - } - }' -``` - -**Expected Result:** -- KB created with wiki_config populated ✅ - -### Test Case 2: Update KB with wiki_config (MAIN TEST) - -```bash -# First, get the KB to see initial state -curl -X GET http://localhost:8080/api/v1/knowledge-bases/{id} \ - -H "Authorization: Bearer " - -# Then update it -curl -X PUT http://localhost:8080/api/v1/knowledge-bases/{id} \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer " \ - -d '{ - "name": "Updated KB", - "description": "Updated description", - "config": { - "wiki_config": { - "enabled": false - } - } - }' - -# Verify the update -curl -X GET http://localhost:8080/api/v1/knowledge-bases/{id} \ - -H "Authorization: Bearer " -``` - -**Expected Result (Before Fix):** -- wiki_config remains unchanged (bug) ❌ - -**Expected Result (After Fix):** -- wiki_config.enabled changed to false ✅ - -### Test Case 3: Update other config fields (Regression Test) - -```bash -curl -X PUT http://localhost:8080/api/v1/knowledge-bases/{id} \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer " \ - -d '{ - "name": "Updated KB", - "config": { - "chunking_config": { - "chunk_size": 1024, - "chunk_overlap": 100 - } - } - }' -``` - -**Expected Result:** -- Chunking config updated ✅ -- wiki_config preserved ✅ - ---- - -## Verification Checklist - -After implementing the fix, verify: - -- [ ] Type definition compiles without errors -- [ ] Backend builds successfully -- [ ] Test Case 1 passes (create with wiki_config) -- [ ] Test Case 2 passes (update with wiki_config) -- [ ] Test Case 3 passes (no regression on other configs) -- [ ] Frontend compiles without TypeScript errors -- [ ] Database column `wiki_config` contains expected JSON -- [ ] EnsureDefaults() still works correctly -- [ ] Wiki feature still functions end-to-end - ---- - -## Code Review Checklist - -- [ ] All GORM tags are consistent with other fields -- [ ] JSON marshaling/unmarshaling follows existing patterns -- [ ] Null safety handled (config can be nil) -- [ ] No breaking changes to existing API -- [ ] Backwards compatible (existing requests still work) -- [ ] Service layer properly validates wiki_config -- [ ] Repository layer properly persists changes -- [ ] EnsureDefaults() method still handles wiki_config correctly - ---- - -## Rollback Plan - -If needed, to rollback: - -1. Revert Change 1: Remove WikiConfig field from KnowledgeBaseConfig -2. Revert Change 2: Remove the wiki_config update code from service -3. Revert Change 3: Remove wiki_config from frontend type hints -4. Rebuild and redeploy - ---- - -## Impact Analysis - -### Affected Files -1. `internal/types/knowledgebase.go` - 1 line added -2. `internal/application/service/knowledgebase.go` - 3 lines added -3. `frontend/src/api/knowledge-base/index.ts` - 7 lines added - -### Backwards Compatibility -- ✅ Fully backwards compatible -- ✅ Existing requests without wiki_config still work -- ✅ Existing KBs with wiki_config unaffected -- ✅ No database migration needed - -### Performance Impact -- ✅ Negligible - only adds one more field to struct - -### Security Impact -- ✅ No security issues introduced -- ✅ Same permission checks apply -- ✅ wiki_config validated through EnsureDefaults() - ---- - -## Related Code - -### WikiConfig Struct Definition -Location: `internal/types/wiki_page.go` (Lines 89-120) - -### EnsureDefaults() Method -Location: `internal/types/knowledgebase.go` (Lines 472-508) -- Already handles wiki_config validation -- No changes needed - -### Database Column -Location: `migrations/versioned/000032_wiki_pages.up.sql` (Line 7) -- Already created as JSONB -- No changes needed - ---- - -## Timeline -- **Implementation:** ~5 minutes -- **Testing:** ~10 minutes -- **Code Review:** ~5 minutes -- **Deployment:** ~5 minutes -- **Total:** ~25 minutes diff --git a/WIKI_CONFIG_FIX_COMPLETE.md b/WIKI_CONFIG_FIX_COMPLETE.md deleted file mode 100644 index 0fdba7e5..00000000 --- a/WIKI_CONFIG_FIX_COMPLETE.md +++ /dev/null @@ -1,386 +0,0 @@ -# WikiConfig Update Fix - COMPLETE IMPLEMENTATION - -**Status:** ✅ **COMPLETE AND COMMITTED** - ---- - -## Quick Summary - -Fixed the inability to update `wiki_config` in knowledge bases through the REST API by implementing three complementary changes across the system: - -1. **Backend Types:** Added `WikiConfig` field to `KnowledgeBaseConfig` struct -2. **Backend Service:** Added wiki_config persistence logic in `UpdateKnowledgeBase` method -3. **Frontend Types:** Added WikiConfig type hints to create/update functions - -**Commit:** `b09893d5` (April 7, 2026 15:19:53) - ---- - -## The Problem - -When users tried to update a knowledge base's wiki configuration via the REST API: - -```bash -PUT /api/v1/knowledge-bases/{id} -{ - "name": "Updated KB", - "config": { - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "model-123" - } - } -} -``` - -The `wiki_config` was silently ignored and not persisted to the database. - -**Why?** The `KnowledgeBaseConfig` struct used to deserialize the request had no `WikiConfig` field, so JSON unmarshaling dropped the data. - ---- - -## The Solution - -### Layer 1: Backend Types (`internal/types/knowledgebase.go`) - -**What Changed:** -```go -type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig - ImageProcessingConfig ImageProcessingConfig - FAQConfig *FAQConfig - WikiConfig *WikiConfig // ← ADDED THIS FIELD -} -``` - -**Why:** Allows the JSON deserializer to populate `wiki_config` from request bodies. - -**Location:** Lines 107-108 - ---- - -### Layer 2: Backend Service (`internal/application/service/knowledgebase.go`) - -**What Changed:** -```go -if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig // ← ADDED THIS LOGIC - } -} -``` - -**Why:** Applies the deserialized wiki_config to the knowledge base entity before saving. - -**Location:** Lines 297-299 - ---- - -### Layer 3: Frontend API (`frontend/src/api/knowledge-base/index.ts`) - -**What Changed:** - -```typescript -// Create function now accepts wiki_config -export function createKnowledgeBase(data: { - name: string; - // ... other fields ... - wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; - }; -}) - -// Update function now has typed wiki_config in config -export function updateKnowledgeBase(id: string, data: { - name: string; - description?: string; - config?: { - chunking_config?: any; - image_processing_config?: any; - faq_config?: any; - wiki_config?: { // ← NOW TYPED - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; - }; - } -}) -``` - -**Why:** Provides IDE autocomplete and type safety for frontend developers. - -**Location:** Lines 31-37 (create) and 49-64 (update) - ---- - -## Complete Data Flow - -### Before Fix (BROKEN) -``` -Frontend sends: {name, config: {wiki_config: {...}}} - ↓ -Handler receives UpdateKnowledgeBaseRequest - ↓ -JSON unmarshals to KnowledgeBaseConfig (no WikiConfig field) - ↓ -wiki_config data DROPPED silently ✗ - ↓ -Service never sees wiki_config - ↓ -Database unchanged ✗ -``` - -### After Fix (WORKING) -``` -Frontend sends: {name, config: {wiki_config: {...}}} - ↓ -Handler receives UpdateKnowledgeBaseRequest - ↓ -JSON unmarshals to KnowledgeBaseConfig (HAS WikiConfig field) - ↓ -wiki_config data PRESERVED ✓ - ↓ -Service receives config with wiki_config - ↓ -Service applies: if config.WikiConfig != nil { kb.WikiConfig = config.WikiConfig } - ↓ -Database saves wiki_config to JSONB column ✓ -``` - ---- - -## Technical Details - -### Root Cause -- **Symptom:** `wiki_config` silently dropped on PUT request -- **Root Cause:** `KnowledgeBaseConfig` struct missing `WikiConfig` field -- **Impact:** Only affected updates (creates worked because they use full `KnowledgeBase` struct) -- **Severity:** Medium - Wiki feature broken without ability to configure - -### Why Other Configs Worked -- `ChunkingConfig`, `ImageProcessingConfig`, `FAQConfig` were already in `KnowledgeBaseConfig` -- `WikiConfig` was added later to KB creation but update struct never updated -- Asymmetry between create and update endpoints - -### Design Pattern Used -Following existing pattern for `FAQConfig`: -```go -if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig -} -``` - -Applied the same pattern to `WikiConfig` for consistency. - ---- - -## Backward Compatibility - -✅ **100% Backward Compatible** - -- `wiki_config` parameter is **optional** in both create and update -- Existing code that doesn't use `wiki_config` continues to work unchanged -- No breaking changes to existing APIs -- No database migrations required - -### Examples of Compatible Usage - -**Old code (still works):** -```bash -curl -X POST /api/v1/knowledge-bases \ - -d '{"name":"My KB", "type":"document"}' # No wiki_config -``` - -**New code (now works):** -```bash -curl -X PUT /api/v1/knowledge-bases/kb-123 \ - -d '{"name":"My KB", "config":{"wiki_config":{"enabled":true}}}' -``` - ---- - -## Testing Scenarios - -### Test 1: Create KB with wiki_config -```bash -curl -X POST http://localhost:8080/api/v1/knowledge-bases \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Wiki-enabled KB", - "type": "document", - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4", - "wiki_language": "en" - } - }' -``` -**Expected:** KB created with wiki_config populated ✓ - -### Test 2: Update KB wiki_config (NOW WORKS) -```bash -curl -X PUT http://localhost:8080/api/v1/knowledge-bases/kb-123 \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Updated KB", - "config": { - "wiki_config": { - "enabled": false, - "auto_ingest": true, - "synthesis_model_id": "gpt-3.5", - "wiki_language": "zh" - } - } - }' -``` -**Expected:** KB updated, wiki_config persisted ✓ - -### Test 3: Verify persistence -```bash -curl http://localhost:8080/api/v1/knowledge-bases/kb-123 | jq '.data.wiki_config' -``` -**Expected:** Shows current wiki_config with all updated values ✓ - -### Test 4: Database level -```sql -SELECT wiki_config FROM knowledge_bases WHERE id = 'kb-123'; -``` -**Expected:** JSONB column shows: `{"enabled":false,"auto_ingest":true,...}` ✓ - ---- - -## Files Changed - -| File | Change | Lines | -|------|--------|-------| -| `internal/types/knowledgebase.go` | Add WikiConfig field to KnowledgeBaseConfig | +2, -2 | -| `internal/application/service/knowledgebase.go` | Add wiki_config persistence in UpdateKnowledgeBase | +3 | -| `frontend/src/api/knowledge-base/index.ts` | Add WikiConfig types to functions | +20 | -| **Total** | **3 files** | **+43 / -20** | - ---- - -## Git Commit Details - -``` -commit b09893d5a388d709ac144730f5d61bbc9cf460c8 -Author: wizardchen -Date: Tue Apr 7 15:19:53 2026 +0800 - - fix: Enable wiki_config updates in knowledge base configuration - - [Full commit message in git log] - - Co-Authored-By: Claude Opus 4.6 (1M context) -``` - -**View commit:** -```bash -git show b09893d5 -``` - -**View diff:** -```bash -git diff b09893d5~1 b09893d5 -``` - ---- - -## Deployment Checklist - -- [ ] Code review completed -- [ ] Unit tests passing: `go test ./internal/application/service/...` -- [ ] Integration tests passing: `go test ./internal/handler/...` -- [ ] Frontend TypeScript build: `npm run build` (no errors) -- [ ] Manual testing completed (see Testing Scenarios above) -- [ ] Database backup before deployment (not required, but recommended) -- [ ] Deploy to staging environment -- [ ] Verify via curl tests in staging -- [ ] Deploy to production -- [ ] Monitor logs for wiki_config related operations - ---- - -## Monitoring - -**What to watch for:** -- `wiki_config` updates in application logs -- No errors related to WikiConfig unmarshaling -- Database JSONB operations completing successfully -- Frontend wiki configuration UI working correctly - -**Log examples (if applicable):** -``` -[INFO] Updating knowledge base, ID: kb-123, name: Updated KB -[INFO] Saving knowledge base update -[INFO] Knowledge base updated successfully, ID: kb-123 -``` - ---- - -## Rollback Plan - -If issues discovered: - -```bash -# Revert the commit -git revert b09893d5 - -# Or reset to previous state -git reset --hard - -# Database: No migration rollback needed (column already exists) -``` - ---- - -## Documentation Files - -This implementation includes comprehensive documentation: - -1. **WIKI_CONFIG_VERIFICATION.md** - Testing and verification guide -2. **IMPLEMENTATION_SUMMARY.md** - Detailed implementation overview -3. **WIKI_CONFIG_FIX_COMPLETE.md** - This file -4. **WIKI_CONFIG_FLOW_ANALYSIS.md** - Deep technical analysis (from previous session) -5. **WIKI_CONFIG_QUICK_REFERENCE.md** - Developer quick reference - ---- - -## Key Takeaways - -1. **The Problem:** Asymmetric handling of `wiki_config` between create and update endpoints -2. **The Root Cause:** Missing field in `KnowledgeBaseConfig` struct -3. **The Solution:** Add field, add persistence logic, add frontend types -4. **The Impact:** Users can now update wiki configuration via REST API -5. **The Benefit:** Complete wiki lifecycle management (create, read, update) - ---- - -## Success Criteria ✅ - -- [x] Code changes implemented -- [x] All three layers fixed -- [x] Backward compatibility maintained -- [x] Git commit created -- [x] Documentation generated -- [x] Ready for testing and deployment - ---- - -**Implementation completed on:** April 7, 2026 15:19:53 UTC+8 - -**Status:** ✅ **READY FOR PRODUCTION** - diff --git a/WIKI_CONFIG_FLOW_ANALYSIS.md b/WIKI_CONFIG_FLOW_ANALYSIS.md deleted file mode 100644 index d06c7eae..00000000 --- a/WIKI_CONFIG_FLOW_ANALYSIS.md +++ /dev/null @@ -1,501 +0,0 @@ -# WeKnora Wiki Config Flow Analysis - Frontend to Database - -## Executive Summary - -The `wiki_config` field **IS DEFINED** in the `KnowledgeBase` struct but **IS NOT CURRENTLY INCLUDED** in the `KnowledgeBaseConfig` struct used by the update endpoints. This means: - -- ✅ `wiki_config` is stored in the database (`knowledge_bases.wiki_config` JSONB column) -- ✅ `wiki_config` can be set during KB creation (included in full `KnowledgeBase` struct) -- ❌ `wiki_config` **CANNOT** be updated via the `/knowledge-bases/{id}` update endpoint -- ⚠️ Frontend sends `config: { wiki_config: {...} }` but backend ignores it - ---- - -## Detailed Flow Analysis - -### 1. DATABASE LAYER -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/migrations/versioned/000032_wiki_pages.up.sql` - -```sql -ALTER TABLE knowledge_bases ADD COLUMN IF NOT EXISTS wiki_config JSONB; - -COMMENT ON COLUMN knowledge_bases.wiki_config IS - 'Wiki configuration: {"auto_ingest": bool, "synthesis_model_id": string, "wiki_language": string, "max_pages_per_ingest": int}'; -``` - -**Status:** ✅ Column exists and properly typed as JSONB - ---- - -### 2. TYPE DEFINITIONS - -#### 2a. WikiConfig Struct -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/wiki_page.go` (Lines 89-120) - -```go -type WikiConfig struct { - // Enabled activates the wiki feature for this knowledge base - Enabled bool `yaml:"enabled" json:"enabled"` - - // AutoIngest triggers wiki page generation/update when new documents are added - AutoIngest bool `yaml:"auto_ingest" json:"auto_ingest"` - - // SynthesisModelID is the LLM model ID used for wiki page generation and updates - SynthesisModelID string `yaml:"synthesis_model_id" json:"synthesis_model_id"` - - // WikiLanguage is the preferred language for wiki content (zh, en, auto) - WikiLanguage string `yaml:"wiki_language" json:"wiki_language"` - - // MaxPagesPerIngest limits pages created/updated per ingest operation (0 = no limit) - MaxPagesPerIngest int `yaml:"max_pages_per_ingest" json:"max_pages_per_ingest"` -} - -// Implements driver.Valuer and sql.Scanner for GORM -func (c WikiConfig) Value() (driver.Value, error) { return json.Marshal(c) } -func (c *WikiConfig) Scan(value interface{}) error { ... } -``` - -**Status:** ✅ Properly defined with GORM marshaling - -#### 2b. KnowledgeBase Struct -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/knowledgebase.go` (Line 76) - -```go -type KnowledgeBase struct { - ID string `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - // ... other fields ... - - // WikiConfig stores wiki-specific configuration (only for wiki type knowledge bases) - WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config" gorm:"column:wiki_config;type:json"` - - // ... timestamps ... -} -``` - -**Status:** ✅ Field exists with proper GORM mapping - -#### 2c. KnowledgeBaseConfig Struct (REQUEST STRUCTURE) -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/knowledgebase.go` (Lines 99-107) - -```go -type KnowledgeBaseConfig struct { - // Chunking configuration - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"` - - // Image processing configuration - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"` - - // FAQ configuration (only for FAQ type knowledge bases) - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"` - - // ❌ MISSING: WikiConfig is NOT included here! -} -``` - -**Status:** ❌ **CRITICAL ISSUE**: WikiConfig is missing from KnowledgeBaseConfig - ---- - -### 3. HANDLER LAYER - -#### 3a. CreateKnowledgeBase Handler -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/handler/knowledgebase.go` (Lines 114-147) - -```go -func (h *KnowledgeBaseHandler) CreateKnowledgeBase(c *gin.Context) { - ctx := c.Request.Context() - - // Parse request body as full KnowledgeBase struct - var req types.KnowledgeBase - if err := c.ShouldBindJSON(&req); err != nil { - // ... error handling ... - return - } - - // Passes to service - kb, err := h.service.CreateKnowledgeBase(ctx, &req) - - // ... response ... -} -``` - -**Request Format Accepted:** -```json -{ - "name": "My KB", - "type": "document", - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4", - "wiki_language": "en" - } -} -``` - -**Status:** ✅ Can accept wiki_config during creation - -#### 3b. UpdateKnowledgeBase Handler -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/handler/knowledgebase.go` (Lines 433-488) - -```go -type UpdateKnowledgeBaseRequest struct { - Name string `json:"name" binding:"required"` - Description string `json:"description"` - Config *types.KnowledgeBaseConfig `json:"config"` // ❌ Uses KnowledgeBaseConfig, not full KnowledgeBase -} - -func (h *KnowledgeBaseHandler) UpdateKnowledgeBase(c *gin.Context) { - // Parse as UpdateKnowledgeBaseRequest - var req UpdateKnowledgeBaseRequest - if err := c.ShouldBindJSON(&req); err != nil { - // ... error handling ... - return - } - - // Calls service with config - kb, err := h.service.UpdateKnowledgeBase(ctx, id, req.Name, req.Description, req.Config) - - // ... response ... -} -``` - -**Request Format:** -```json -{ - "name": "Updated KB Name", - "description": "Updated description", - "config": { - "chunking_config": { ... }, - "image_processing_config": { ... } - // ❌ wiki_config cannot be sent here because KnowledgeBaseConfig doesn't have it - } -} -``` - -**Status:** ❌ **CRITICAL ISSUE**: Cannot pass wiki_config in update request - ---- - -### 4. SERVICE LAYER - -#### 4a. CreateKnowledgeBase Service -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/application/service/knowledgebase.go` (Lines 73-98) - -```go -func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) (*types.KnowledgeBase, error) { - // Generate UUID and set creation timestamps - if kb.ID == "" { - kb.ID = uuid.New().String() - } - kb.CreatedAt = time.Now() - kb.TenantID = types.MustTenantIDFromContext(ctx) - kb.UpdatedAt = time.Now() - kb.EnsureDefaults() // ✅ This calls EnsureDefaults which validates wiki_config - - logger.Infof(ctx, "Creating knowledge base, ID: %s, tenant ID: %d, name: %s", kb.ID, kb.TenantID, kb.Name) - - if err := s.repo.CreateKnowledgeBase(ctx, kb); err != nil { - return nil, err - } - - return kb, nil -} -``` - -**Status:** ✅ Receives full KnowledgeBase with wiki_config - -#### 4b. EnsureDefaults() Method -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/types/knowledgebase.go` (Lines 472-508) - -```go -func (kb *KnowledgeBase) EnsureDefaults() { - if kb == nil { - return - } - if kb.Type == "" { - kb.Type = KnowledgeBaseTypeDocument - } - - // Clear type-specific configs that don't belong - if kb.Type != KnowledgeBaseTypeFAQ { - kb.FAQConfig = nil - } - - // Set defaults for Wiki - if kb.IsWikiEnabled() { // Checks if WikiConfig != nil && WikiConfig.Enabled - if kb.WikiConfig.WikiLanguage == "" { - kb.WikiConfig.WikiLanguage = "auto" - } - if !kb.WikiConfig.AutoIngest { - kb.WikiConfig.AutoIngest = true - } - } - - // Set defaults for FAQ ... -} - -func (kb *KnowledgeBase) IsWikiEnabled() bool { - return kb != nil && kb.WikiConfig != nil && kb.WikiConfig.Enabled -} -``` - -**Status:** ✅ Properly sets wiki_config defaults during creation - -#### 4c. UpdateKnowledgeBase Service -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/application/service/knowledgebase.go` (Lines 265-311) - -```go -func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context, - id string, - name string, - description string, - config *types.KnowledgeBaseConfig, // ❌ Only receives KnowledgeBaseConfig -) (*types.KnowledgeBase, error) { - if id == "" { - return nil, errors.New("knowledge base ID cannot be empty") - } - - // Get existing knowledge base - kb, err := s.repo.GetKnowledgeBaseByID(ctx, id) - if err != nil { - return nil, err - } - - // Update the knowledge base properties - kb.Name = name - kb.Description = description - if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - // ❌ NO CODE TO UPDATE kb.WikiConfig - it's not in config! - } - kb.UpdatedAt = time.Now() - kb.EnsureDefaults() // ✅ But if wiki_config was passed, this would validate it - - if err := s.repo.UpdateKnowledgeBase(ctx, kb); err != nil { - return nil, err - } - - return kb, nil -} -``` - -**Status:** ❌ **CRITICAL ISSUE**: Cannot update wiki_config because it's not in the config parameter - ---- - -### 5. REPOSITORY LAYER - -#### 5a. CreateKnowledgeBase Repository -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/application/repository/knowledgebase.go` (Lines 25-28) - -```go -func (r *knowledgeBaseRepository) CreateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error { - return r.db.WithContext(ctx).Create(kb).Error // ✅ GORM will serialize all fields, including wiki_config -} -``` - -**Status:** ✅ GORM properly handles all fields - -#### 5b. UpdateKnowledgeBase Repository -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/internal/application/repository/knowledgebase.go` (Lines 115-118) - -```go -func (r *knowledgeBaseRepository) UpdateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error { - return r.db.WithContext(ctx).Save(kb).Error // ✅ GORM.Save() will update all fields, including wiki_config -} -``` - -**Status:** ✅ Repository properly saves wiki_config if it's set - ---- - -### 6. FRONTEND API LAYER - -**File:** `/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/frontend/src/api/knowledge-base/index.ts` - -#### 6a. createKnowledgeBase -```typescript -export function createKnowledgeBase(data: { - name: string; - description?: string; - type?: 'document' | 'faq'; - chunking_config?: any; - embedding_model_id?: string; - // ... other fields ... - // ❓ No wiki_config field in type hints! -}) { - return post(`/api/v1/knowledge-bases`, data); -} -``` - -**Status:** ⚠️ Type hints don't include wiki_config (but it would be accepted as any) - -#### 6b. updateKnowledgeBase -```typescript -export function updateKnowledgeBase(id: string, data: { - name: string; - description?: string; - config: any // Any config object -}) { - return put(`/api/v1/knowledge-bases/${id}`, data); -} -``` - -**Status:** ⚠️ Frontend can send `config: { wiki_config: {...} }` but backend ignores it - ---- - -## Tracing the Flow - -### Creating a KB with wiki_config ✅ -``` -Frontend: POST /api/v1/knowledge-bases { name, type, wiki_config: {...} } - ↓ -Handler.CreateKnowledgeBase: Parses as types.KnowledgeBase - ↓ -Service.CreateKnowledgeBase: Receives KnowledgeBase with wiki_config - ↓ -Service.EnsureDefaults: Validates and sets defaults for wiki_config - ↓ -Repository.CreateKnowledgeBase: GORM.Create() serializes wiki_config to JSONB - ↓ -Database: wiki_config column populated ✅ -``` - -### Updating a KB with wiki_config ❌ -``` -Frontend: PUT /api/v1/knowledge-bases/{id} { name, config: { wiki_config: {...} } } - ↓ -Handler.UpdateKnowledgeBase: Parses as UpdateKnowledgeBaseRequest - ↓ -❌ UpdateKnowledgeBaseRequest.Config is of type KnowledgeBaseConfig (NOT including WikiConfig) - ↓ -❌ JSON unmarshaling fails or ignores wiki_config field - ↓ -Service.UpdateKnowledgeBase: Receives config WITHOUT wiki_config - ↓ -❌ Code never updates kb.WikiConfig - it stays at existing value - ↓ -Repository.UpdateKnowledgeBase: GORM.Save() persists unchanged wiki_config - ↓ -Database: wiki_config column NOT updated ❌ -``` - ---- - -## Required Fixes - -### Fix 1: Add WikiConfig to KnowledgeBaseConfig Struct -**File:** `internal/types/knowledgebase.go` - -```go -type KnowledgeBaseConfig struct { - // Chunking configuration - ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"` - - // Image processing configuration - ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"` - - // FAQ configuration (only for FAQ type knowledge bases) - FAQConfig *FAQConfig `yaml:"faq_config" json:"faq_config"` - - // ADD THIS: - // Wiki configuration (for document type knowledge bases with wiki feature enabled) - WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config"` -} -``` - -### Fix 2: Update UpdateKnowledgeBase Service -**File:** `internal/application/service/knowledgebase.go` - -```go -func (s *knowledgeBaseService) UpdateKnowledgeBase(ctx context.Context, - id string, - name string, - description string, - config *types.KnowledgeBaseConfig, -) (*types.KnowledgeBase, error) { - // ... existing code ... - - if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - - // ADD THIS: - if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig - } - } - - // ... rest of code ... -} -``` - -### Fix 3: Update Frontend Type Hints -**File:** `frontend/src/api/knowledge-base/index.ts` - -```typescript -export function createKnowledgeBase(data: { - name: string; - description?: string; - type?: 'document' | 'faq'; - chunking_config?: any; - embedding_model_id?: string; - summary_model_id?: string; - vlm_config?: { enabled: boolean; model_id?: string }; - storage_provider_config?: { provider: string }; - asr_config?: { enabled: boolean; model_id?: string; language?: string }; - extract_config?: any; - faq_config?: { index_mode: string; question_index_mode?: string }; - // ADD THIS: - wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; - }; -}) { - return post(`/api/v1/knowledge-bases`, data); -} -``` - ---- - -## Summary Table - -| Component | Location | Status | Can Handle wiki_config | -|-----------|----------|--------|----------------------| -| Database Column | `migrations/000032_wiki_pages.up.sql` | ✅ Exists | ✅ Yes | -| WikiConfig Type | `internal/types/wiki_page.go` | ✅ Defined | ✅ Yes | -| KnowledgeBase Struct | `internal/types/knowledgebase.go` | ✅ Has field | ✅ Yes | -| KnowledgeBaseConfig Struct | `internal/types/knowledgebase.go` | ❌ Missing field | ❌ No | -| CreateKnowledgeBase Handler | `internal/handler/knowledgebase.go` | ✅ Full struct | ✅ Yes | -| UpdateKnowledgeBase Handler | `internal/handler/knowledgebase.go` | ⚠️ Limited struct | ❌ No | -| CreateKnowledgeBase Service | `internal/application/service/knowledgebase.go` | ✅ Receives KB | ✅ Yes | -| UpdateKnowledgeBase Service | `internal/application/service/knowledgebase.go` | ❌ Not updated | ❌ No | -| Repository Layer | `internal/application/repository/knowledgebase.go` | ✅ Works | ✅ Yes | -| Frontend API | `frontend/src/api/knowledge-base/index.ts` | ⚠️ Missing types | ⚠️ Partial | - ---- - -## Conclusion - -The infrastructure to handle `wiki_config` is almost complete, but there's a **critical gap in the update flow**: - -1. **Creation works** ✅ - Wiki config can be set when creating a KB -2. **Update broken** ❌ - Wiki config cannot be updated after creation -3. **Root cause** - `KnowledgeBaseConfig` struct is missing the `WikiConfig` field -4. **Impact** - Frontend sends wiki config updates but backend ignores them - -**3 simple code changes are needed** to fix this issue (see Required Fixes section above). diff --git a/WIKI_CONFIG_QUICK_REFERENCE.md b/WIKI_CONFIG_QUICK_REFERENCE.md deleted file mode 100644 index e610f0fd..00000000 --- a/WIKI_CONFIG_QUICK_REFERENCE.md +++ /dev/null @@ -1,201 +0,0 @@ -# Wiki Config Flow - Quick Reference - -## Critical Finding: UPDATE BROKEN ❌ - -When updating a KB via `PUT /api/v1/knowledge-bases/{id}`, the `wiki_config` is **NOT** persisted. - -## Why? - -``` -UpdateKnowledgeBaseRequest struct: -├── Name: string -├── Description: string -└── Config: KnowledgeBaseConfig ❌ Missing WikiConfig field - ├── ChunkingConfig - ├── ImageProcessingConfig - └── FAQConfig -``` - -The `KnowledgeBaseConfig` struct lacks the `WikiConfig` field, so: -- ✅ Frontend CAN send `config: { wiki_config: {...} }` -- ❌ But backend IGNORES it during unmarshaling -- ❌ Service never updates kb.WikiConfig -- ❌ Database column remains unchanged - -## Creation Works ✅ - -``` -POST /api/v1/knowledge-bases -{ - "name": "My KB", - "wiki_config": { "enabled": true, ... } ← FULL KnowledgeBase struct accepted -} - -Handler parses as types.KnowledgeBase (not KnowledgeBaseConfig) -→ Service receives wiki_config -→ EnsureDefaults() validates it -→ Repository saves it to database ✅ -``` - -## Update Broken ❌ - -``` -PUT /api/v1/knowledge-bases/{id} -{ - "name": "Updated", - "config": { - "wiki_config": { "enabled": false } ← Sent to backend - } -} - -Handler parses as UpdateKnowledgeBaseRequest -→ Config field is KnowledgeBaseConfig (no WikiConfig!) -→ JSON unmarshaling IGNORES wiki_config field -→ Service never sees it -→ Database NOT updated ❌ -``` - -## Files That Need Changes - -### 1. `/internal/types/knowledgebase.go` (Lines 99-107) -```diff - type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig - ImageProcessingConfig ImageProcessingConfig - FAQConfig *FAQConfig -+ WikiConfig *WikiConfig // ADD THIS LINE - } -``` - -### 2. `/internal/application/service/knowledgebase.go` (Lines 291-296) -```diff - if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } -+ if config.WikiConfig != nil { -+ kb.WikiConfig = config.WikiConfig -+ } - } -``` - -### 3. `/frontend/src/api/knowledge-base/index.ts` (createKnowledgeBase function) -Add wiki_config to type hints (for TypeScript completion): -```typescript -wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; -}; -``` - -## Database Path - -### Storage -- Table: `knowledge_bases` -- Column: `wiki_config` (JSONB) -- Created by: Migration `000032_wiki_pages.up.sql` - -### Data Types -- Go struct: `WikiConfig` in `/internal/types/wiki_page.go` -- Fields: `enabled`, `auto_ingest`, `synthesis_model_id`, `wiki_language`, `max_pages_per_ingest` -- GORM mapping: `gorm:"column:wiki_config;type:json"` - -## Request/Response Flow - -### Create (Works ✅) -``` -POST /api/v1/knowledge-bases -→ CreateKnowledgeBaseRequest (full KnowledgeBase) -→ Handler: c.ShouldBindJSON(&types.KnowledgeBase) -→ Service: CreateKnowledgeBase(ctx, &kb) -→ Repository: GORM.Create(kb) -→ DB: wiki_config saved ✅ -``` - -### Update (Broken ❌) -``` -PUT /api/v1/knowledge-bases/{id} -→ UpdateKnowledgeBaseRequest (Config: KnowledgeBaseConfig) -→ Handler: c.ShouldBindJSON(&UpdateKnowledgeBaseRequest) -→ Service: UpdateKnowledgeBase(ctx, id, name, desc, config) -→ Service: config.WikiConfig is nil (never set!) -→ Repository: GORM.Save(kb) with old wiki_config -→ DB: wiki_config NOT updated ❌ -``` - -## Handler Code Locations - -| Operation | Handler | File:Lines | Status | -|-----------|---------|-----------|--------| -| Create | CreateKnowledgeBase | knowledgebase.go:114-147 | ✅ | -| Read | GetKnowledgeBase | knowledgebase.go:260-284 | ✅ | -| Update | UpdateKnowledgeBase | knowledgebase.go:446-488 | ❌ | -| Delete | DeleteKnowledgeBase | knowledgebase.go:502-536 | ✅ | - -## Service Layer Locations - -| Operation | Service Method | File:Lines | Status | -|-----------|----------------|-----------|--------| -| Create | CreateKnowledgeBase | knowledgebase.go:73-98 | ✅ | -| Read | GetKnowledgeBaseByID | knowledgebase.go:101-117 | ✅ | -| Update | UpdateKnowledgeBase | knowledgebase.go:265-311 | ❌ | -| List | ListKnowledgeBases | knowledgebase.go:157-210 | ✅ | - -## Frontend Integration - -### API Functions -- `createKnowledgeBase()` - accepts any data ✅ -- `updateKnowledgeBase()` - accepts any config ✅ (but backend ignores wiki_config) -- `getKnowledgeBaseById()` - returns full KB ✅ - -### Type Hints Location -- File: `/frontend/src/api/knowledge-base/index.ts` -- Lines: 11-33 (createKnowledgeBase) -- Lines: 42-44 (updateKnowledgeBase) - -## Test Cases - -To verify the fix works: - -### Test 1: Create with wiki_config -``` -POST /api/v1/knowledge-bases -{ - "name": "Test KB", - "type": "document", - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4", - "wiki_language": "en" - } -} -→ Should persist wiki_config ✅ -``` - -### Test 2: Update wiki_config -``` -PUT /api/v1/knowledge-bases/{id} -{ - "name": "Updated", - "config": { - "wiki_config": { - "enabled": false - } - } -} -→ Before fix: wiki_config NOT updated ❌ -→ After fix: wiki_config updated ✅ -``` - -## Implementation Time Estimate -- Add WikiConfig to KnowledgeBaseConfig: 2 minutes -- Update Service layer: 3 minutes -- Update Frontend types: 2 minutes -- Testing: 5 minutes -- **Total: ~12 minutes** diff --git a/WIKI_CONFIG_TRACE_SUMMARY.md b/WIKI_CONFIG_TRACE_SUMMARY.md deleted file mode 100644 index 645fe99f..00000000 --- a/WIKI_CONFIG_TRACE_SUMMARY.md +++ /dev/null @@ -1,354 +0,0 @@ -# Wiki Config Flow - Trace Summary - -## 📋 Executive Summary - -I've completed a comprehensive trace of how `wiki_config` flows from the frontend through the backend to the database in the WeKnora codebase. - -**Key Finding:** ❌ **Wiki config UPDATE is broken** - can only be set during creation, not updated afterward. - ---- - -## 🎯 Three Documents Generated - -### 1. **WIKI_CONFIG_FLOW_ANALYSIS.md** (16 KB) -**Comprehensive technical analysis** with all file paths, struct definitions, and code snippets. - -**Sections:** -- Database layer (SQL migration) -- Type definitions (WikiConfig, KnowledgeBase, KnowledgeBaseConfig) -- Handler layer (create vs update) -- Service layer implementation -- Repository layer -- Frontend API -- Flow diagrams (works vs broken) -- Required fixes with code examples -- Summary table - -**Best for:** Full understanding of the system architecture - -### 2. **WIKI_CONFIG_QUICK_REFERENCE.md** (5.3 KB) -**Quick lookup guide** for developers implementing the fix. - -**Sections:** -- Critical finding summary -- Why it's broken (struct diagram) -- Files that need changes -- Database path info -- Request/response flows -- Handler/Service code locations -- Frontend integration -- Test cases - -**Best for:** Quick reference during implementation - -### 3. **WIKI_CONFIG_FIX.md** (8.5 KB) -**Complete implementation guide** with exact code changes. - -**Sections:** -- Problem statement -- Change 1: Type definition (code diff) -- Change 2: Service layer (code diff) -- Change 3: Frontend types (code diff) -- Testing procedures (curl examples) -- Verification checklist -- Code review checklist -- Rollback plan -- Impact analysis - -**Best for:** Actually implementing the fix - ---- - -## 🔍 Findings at a Glance - -### Database Layer ✅ -``` -CREATE TABLE knowledge_bases ( - ... - wiki_config JSONB ← EXISTS and properly typed -) -``` - -**File:** `migrations/versioned/000032_wiki_pages.up.sql` (Line 7) - -### Type Definitions - -#### WikiConfig Struct ✅ -```go -type WikiConfig struct { - Enabled bool - AutoIngest bool - SynthesisModelID string - WikiLanguage string - MaxPagesPerIngest int -} -``` -**File:** `internal/types/wiki_page.go` (Lines 89-120) - -#### KnowledgeBase Struct ✅ -```go -type KnowledgeBase struct { - // ... - WikiConfig *WikiConfig `json:"wiki_config" gorm:"column:wiki_config;type:json"` - // ... -} -``` -**File:** `internal/types/knowledgebase.go` (Line 76) - -#### KnowledgeBaseConfig Struct ❌ -```go -type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig - ImageProcessingConfig ImageProcessingConfig - FAQConfig *FAQConfig - // ❌ MISSING: WikiConfig *WikiConfig -} -``` -**File:** `internal/types/knowledgebase.go` (Lines 99-107) - -**This is the root cause!** - -### Handler Layer - -#### CreateKnowledgeBase ✅ -- **File:** `internal/handler/knowledgebase.go` (Lines 114-147) -- Accepts full `types.KnowledgeBase` struct -- wiki_config can be sent: `{ name, wiki_config: {...} }` -- **Status:** Works perfectly - -#### UpdateKnowledgeBase ❌ -- **File:** `internal/handler/knowledgebase.go` (Lines 446-488) -- Accepts `UpdateKnowledgeBaseRequest` with `Config: KnowledgeBaseConfig` -- wiki_config in request: `{ name, config: { wiki_config: {...} } }` -- **Problem:** KnowledgeBaseConfig doesn't have WikiConfig field -- **Status:** Silently ignores wiki_config - -### Service Layer - -#### CreateKnowledgeBase ✅ -- **File:** `internal/application/service/knowledgebase.go` (Lines 73-98) -- Receives full KnowledgeBase -- Calls `EnsureDefaults()` which validates wiki_config -- **Status:** Works - -#### UpdateKnowledgeBase ❌ -- **File:** `internal/application/service/knowledgebase.go` (Lines 265-311) -- Receives `config *KnowledgeBaseConfig` -- No code to update `kb.WikiConfig` -- **Status:** Cannot persist updates - -### Repository Layer ✅ -- **File:** `internal/application/repository/knowledgebase.go` -- `CreateKnowledgeBase()`: Line 26 - Uses GORM.Create() -- `UpdateKnowledgeBase()`: Line 116 - Uses GORM.Save() -- **Status:** Both correctly handle wiki_config if it's set - -### Frontend API ⚠️ -- **File:** `frontend/src/api/knowledge-base/index.ts` -- `createKnowledgeBase()`: Lines 11-33 - accepts any data ✅ -- `updateKnowledgeBase()`: Lines 42-44 - accepts any config ✅ -- **Issue:** Type hints don't include wiki_config (but data is sent) - ---- - -## 🔄 Flow Diagram - -### ✅ CREATION FLOW (Works) -``` -Frontend sends: - POST /api/v1/knowledge-bases - { name, type, wiki_config: {...} } - - ↓ -Handler: CreateKnowledgeBase - Parses as types.KnowledgeBase ✅ - - ↓ -Service: CreateKnowledgeBase - Receives KB with wiki_config ✅ - Calls EnsureDefaults() ✅ - - ↓ -Repository: CreateKnowledgeBase - GORM.Create(kb) serializes all fields ✅ - - ↓ -Database: wiki_config column populated ✅ -``` - -### ❌ UPDATE FLOW (Broken) -``` -Frontend sends: - PUT /api/v1/knowledge-bases/{id} - { name, config: { wiki_config: {...} } } - - ↓ -Handler: UpdateKnowledgeBase - Parses as UpdateKnowledgeBaseRequest ❌ - Config is KnowledgeBaseConfig (no WikiConfig!) ❌ - - ↓ -JSON Unmarshaling: - wiki_config field ignored ❌ - - ↓ -Service: UpdateKnowledgeBase - Receives config without wiki_config ❌ - Never updates kb.WikiConfig ❌ - - ↓ -Repository: UpdateKnowledgeBase - GORM.Save(kb) persists OLD wiki_config ❌ - - ↓ -Database: wiki_config NOT updated ❌ -``` - ---- - -## 🛠️ The Fix (3 Changes) - -### Change 1: Add WikiConfig to KnowledgeBaseConfig -**File:** `internal/types/knowledgebase.go` (After line 106) -```go -// Wiki configuration (for document type knowledge bases with wiki feature enabled) -WikiConfig *WikiConfig `yaml:"wiki_config" json:"wiki_config"` -``` - -### Change 2: Update Service to Persist WikiConfig -**File:** `internal/application/service/knowledgebase.go` (After line 296) -```go -if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig -} -``` - -### Change 3: Update Frontend Type Hints -**File:** `frontend/src/api/knowledge-base/index.ts` (In createKnowledgeBase) -```typescript -wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; -}; -``` - ---- - -## 📊 Component Status Matrix - -| Component | File | Lines | Current Status | Issue | -|-----------|------|-------|--------|---------| -| Database Column | `000032_wiki_pages.up.sql` | 7 | ✅ Exists | None | -| WikiConfig Type | `wiki_page.go` | 89-120 | ✅ Defined | None | -| KnowledgeBase Field | `knowledgebase.go` | 76 | ✅ Has field | None | -| KnowledgeBaseConfig Field | `knowledgebase.go` | 99-107 | ❌ Missing | **ROOT CAUSE** | -| CreateKB Handler | `knowledgebase.go` | 114-147 | ✅ Works | None | -| UpdateKB Handler | `knowledgebase.go` | 446-488 | ⚠️ Limited | Uses KnowledgeBaseConfig | -| CreateKB Service | `knowledgebase.go` | 73-98 | ✅ Works | None | -| UpdateKB Service | `knowledgebase.go` | 265-311 | ❌ Broken | No WikiConfig update | -| Repository | `repository/knowledgebase.go` | 26-118 | ✅ Works | None | -| Frontend API | `api/knowledge-base/index.ts` | Various | ⚠️ Partial | Missing types | - ---- - -## 🧪 Test Verification - -### Before Fix -- ✅ Create KB with wiki_config → Works -- ❌ Update wiki_config → Fails (not persisted) -- ❌ Fetch KB after update → Old value still there - -### After Fix -- ✅ Create KB with wiki_config → Works -- ✅ Update wiki_config → Works -- ✅ Fetch KB after update → New value correctly persisted - ---- - -## 📁 Document Files Location - -All documents saved in WeKnora root: -``` -/Users/wizard/code/go/src/git.woa.com/wxg-prc/WeKnora/ -├── WIKI_CONFIG_TRACE_SUMMARY.md ← You are here -├── WIKI_CONFIG_FLOW_ANALYSIS.md ← Full technical analysis -├── WIKI_CONFIG_QUICK_REFERENCE.md ← Developer quick reference -└── WIKI_CONFIG_FIX.md ← Implementation guide -``` - ---- - -## 🎓 Key Learnings - -### Architecture Pattern -WeKnora uses a layered architecture: -1. **Frontend API** - TypeScript functions that call HTTP endpoints -2. **Handler Layer** - Gin HTTP handlers that parse requests -3. **Service Layer** - Business logic -4. **Repository Layer** - Database operations using GORM -5. **Database** - PostgreSQL with JSON columns - -### Request Structure Design -- **Creation**: Uses full struct (`KnowledgeBase`) - more flexible -- **Update**: Uses limited struct (`KnowledgeBaseConfig`) - more controlled -- **Issue**: Limited struct was too limited for wiki_config - -### GORM Behavior -- GORM automatically serializes/deserializes JSON fields using `Value()` and `Scan()` methods -- All config structs implement these interfaces -- The repository layer is "dumb" - it trusts what the service gives it - ---- - -## ✨ Recommendations - -1. **Implement the fix immediately** - Very low risk, high impact -2. **Add integration tests** - Test both creation and update flows -3. **Update API documentation** - Document wiki_config in API docs -4. **Consider using base struct for all config updates** - Currently inconsistent between handlers - ---- - -## 📞 Questions Answered - -### 1. How does wiki_config get saved during KB creation? -Via full `KnowledgeBase` struct → Service → Repository → GORM.Create() - -### 2. How does it get updated after creation? -It **doesn't** - that's the bug! KnowledgeBaseConfig is missing the field. - -### 3. Where is it stored in the database? -`knowledge_bases.wiki_config` JSONB column - -### 4. What struct definitions are involved? -- `WikiConfig` (source) -- `KnowledgeBase` (has WikiConfig field) -- `KnowledgeBaseConfig` (missing WikiConfig field - THE BUG) - -### 5. What's the exact code path from frontend to database? -- Frontend sends HTTP request -- Handler parses request into struct -- Service updates the struct -- Repository calls GORM.Save() -- GORM serializes struct to SQL using Value() method -- Database receives JSON in wiki_config column - -### 6. How to fix it? -Add WikiConfig field to KnowledgeBaseConfig + update service layer (2 code changes) - ---- - -## 📝 Next Steps - -1. **Review** the three generated documents -2. **Implement** the changes using `WIKI_CONFIG_FIX.md` -3. **Test** using the provided test cases -4. **Deploy** and verify in production - ---- - -Generated: April 7, 2026 -Analysis Depth: Complete code trace with exact file locations and line numbers diff --git a/WIKI_CONFIG_VERIFICATION.md b/WIKI_CONFIG_VERIFICATION.md deleted file mode 100644 index ab286ff1..00000000 --- a/WIKI_CONFIG_VERIFICATION.md +++ /dev/null @@ -1,203 +0,0 @@ -# WikiConfig Update Fix - Verification Guide - -## Summary of Changes - -Three files were modified to enable `wiki_config` updates in the knowledge base management system: - -### 1. Backend: Types Layer (`internal/types/knowledgebase.go`) -**Fix:** Added `WikiConfig` field to `KnowledgeBaseConfig` struct - -```go -type KnowledgeBaseConfig struct { - ChunkingConfig ChunkingConfig - ImageProcessingConfig ImageProcessingConfig - FAQConfig *FAQConfig - WikiConfig *WikiConfig // ✓ ADDED -} -``` - -**Why:** The update handler uses this struct to deserialize PUT request bodies. Without this field, `wiki_config` data was silently dropped during JSON unmarshaling. - -### 2. Backend: Service Layer (`internal/application/service/knowledgebase.go`) -**Fix:** Added wiki_config persistence logic in `UpdateKnowledgeBase` method - -```go -if config != nil { - kb.ChunkingConfig = config.ChunkingConfig - kb.ImageProcessingConfig = config.ImageProcessingConfig - if config.FAQConfig != nil { - kb.FAQConfig = config.FAQConfig - } - if config.WikiConfig != nil { - kb.WikiConfig = config.WikiConfig // ✓ ADDED - } -} -``` - -**Why:** Even if the field deserializes correctly, the service layer must explicitly apply it to the KB entity before persistence. - -### 3. Frontend: API Types (`frontend/src/api/knowledge-base/index.ts`) -**Fix:** Added `WikiConfig` type to both create and update function signatures - -```typescript -export function createKnowledgeBase(data: { - // ... other fields ... - wiki_config?: { - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; - }; -}) - -export function updateKnowledgeBase(id: string, data: { - name: string; - description?: string; - config?: { - chunking_config?: any; - image_processing_config?: any; - faq_config?: any; - wiki_config?: { // ✓ ADDED - enabled: boolean; - auto_ingest?: boolean; - synthesis_model_id?: string; - wiki_language?: string; - max_pages_per_ingest?: number; - }; - } -}) -``` - -**Why:** Provides IDE autocompletion and type safety for frontend developers. - -## Testing - -### Test Case 1: Create Knowledge Base with Wiki Config - -```bash -curl -X POST http://localhost:8080/api/v1/knowledge-bases \ - -H "Content-Type: application/json" \ - -d '{ - "name": "My Wiki KB", - "type": "document", - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "model-123", - "wiki_language": "en", - "max_pages_per_ingest": 10 - } - }' -``` - -**Expected:** Returns KB with `wiki_config` populated in response. - -### Test Case 2: Update Knowledge Base with Wiki Config - -```bash -curl -X PUT http://localhost:8080/api/v1/knowledge-bases/{kb_id} \ - -H "Content-Type: application/json" \ - -d '{ - "name": "Updated Wiki KB", - "description": "Updated description", - "config": { - "wiki_config": { - "enabled": true, - "auto_ingest": false, - "synthesis_model_id": "model-456", - "wiki_language": "zh", - "max_pages_per_ingest": 20 - } - } - }' -``` - -**Expected:** Returns KB with updated `wiki_config`. - -### Test Case 3: Get Updated Knowledge Base - -```bash -curl http://localhost:8080/api/v1/knowledge-bases/{kb_id} -``` - -**Expected:** Response contains updated `wiki_config` with all fields persisted correctly. - -## Verification Checklist - -### Database Level -- [ ] Connect to PostgreSQL: `psql ` -- [ ] Query: `SELECT wiki_config FROM knowledge_bases WHERE id = '';` -- [ ] Verify: JSONB column contains all wiki_config fields -- [ ] Example: `{"enabled": true, "auto_ingest": true, ...}` - -### Application Level -- [ ] Run backend tests: `go test ./internal/application/service/...` -- [ ] Check for errors in service layer wiki_config handling -- [ ] Verify EnsureDefaults() properly validates wiki_config - -### Frontend Level -- [ ] TypeScript compilation: `npm run build` (no type errors) -- [ ] IDE shows autocomplete for wiki_config in createKnowledgeBase() -- [ ] IDE shows autocomplete for wiki_config in updateKnowledgeBase() - -### Integration Level -- [ ] Create KB via API with wiki_config -- [ ] Retrieve KB and verify wiki_config is populated -- [ ] Update KB with new wiki_config values -- [ ] Retrieve KB again and verify updates persisted -- [ ] Verify EnsureDefaults() sets wiki_language to "auto" if empty -- [ ] Verify EnsureDefaults() sets auto_ingest to true if false - -## Impact Analysis - -### What Works Now -✓ Creating KB with wiki_config via API: `POST /api/v1/knowledge-bases` -✓ Updating KB wiki_config via API: `PUT /api/v1/knowledge-bases/{id}` -✓ Frontend IDE autocomplete for wiki_config in both functions -✓ Type safety for wiki_config in TypeScript - -### Backward Compatibility -✓ Existing KB creation without wiki_config still works (config is optional) -✓ Existing KB updates without config.wiki_config still work (field is optional) -✓ Legacy code path unaffected - -### No Breaking Changes -- KnowledgeBaseConfig struct is internal to the service layer -- Frontend API function signatures have optional parameters -- All changes are additive, no fields removed or renamed - -## Code Locations - -| File | Line | Change | -|------|------|--------| -| `internal/types/knowledgebase.go` | 107-108 | Added WikiConfig field to KnowledgeBaseConfig | -| `internal/application/service/knowledgebase.go` | 297-299 | Added wiki_config persistence logic | -| `frontend/src/api/knowledge-base/index.ts` | 31-37 | Added wiki_config to createKnowledgeBase | -| `frontend/src/api/knowledge-base/index.ts` | 49-64 | Added wiki_config to updateKnowledgeBase | - -## Commit Information - -- **Commit Hash:** Check with `git log --oneline` -- **Files Modified:** 3 -- **Lines Added:** 43 -- **Lines Removed:** 20 -- **Co-Authored-By:** Claude Opus 4.6 (1M context) - -## Next Steps - -1. **Testing:** Run the test cases above to verify functionality -2. **Code Review:** Review the diffs to ensure quality -3. **Deployment:** Merge to main and deploy to production -4. **Monitoring:** Watch for any wiki_config related issues in logs - -## Rollback Plan - -If issues are discovered: - -```bash -git revert b09893d5 -``` - -This will cleanly revert all three changes while preserving other commits. - diff --git a/WIKI_DOCS_INDEX.md b/WIKI_DOCS_INDEX.md deleted file mode 100644 index 978e804b..00000000 --- a/WIKI_DOCS_INDEX.md +++ /dev/null @@ -1,482 +0,0 @@ -# Wiki System Documentation Index - -**Purpose:** Central reference for all wiki system documentation -**Last Updated:** April 2026 - ---- - -## Quick Navigation - -### For First-Time Readers -1. Start with **WIKI_SYSTEM_SUMMARY.md** (5 min read) - - Overview of wiki functionality - - Key architectural decisions - - Common workflows - -2. Then read **WIKI_SYSTEM_DEEP_DIVE.md** (15 min read) - - Detailed service descriptions - - Data flow diagrams - - Complete API endpoints - -### For Developers Implementing Features -1. **WIKI_IMPLEMENTATION_GUIDE.md** (primary reference) - - Common tasks with code examples - - Testing patterns - - Error handling - - Performance optimization - - Debugging techniques - -2. **WIKI_TECHNICAL_ANALYSIS.md** (deep reference) - - Architectural patterns explained - - Edge cases documented - - Operational considerations - - Known limitations - -### For Architects and Code Reviewers -1. **WIKI_TECHNICAL_ANALYSIS.md** (full read recommended) - - Part 2: Core Concepts and Patterns - - Part 3: Detailed Implementation Patterns - - Part 4: Edge Cases and Gotchas - - Part 5: Operational Considerations - - Part 7: Future Enhancements - -2. **Source Code** (in this order) - - `internal/types/wiki_page.go` — data models - - `internal/application/service/wiki_page.go` — core service - - `internal/application/service/wiki_ingest.go` — async pipeline - - `internal/application/service/wiki_ingest_batch.go` — MAP-REDUCE handler - - `internal/application/service/wiki_linkify.go` — cross-link injection - - `internal/application/service/wiki_lint.go` — health checking - ---- - -## Documentation Overview - -### WIKI_SYSTEM_SUMMARY.md -**Type:** Executive Summary -**Length:** ~470 lines -**Audience:** Everyone -**Key Sections:** -- What is wiki? -- Quick architecture map -- Core data structures -- Key services overview -- Async pipeline simplified -- Cross-link injection overview -- Retrieval integration -- Agent integration -- API endpoints quick reference -- Configuration overview -- FAQ - -**When to Read:** First introduction to wiki system - ---- - -### WIKI_SYSTEM_DEEP_DIVE.md -**Type:** Technical Reference -**Length:** ~950 lines -**Audience:** Developers, architects -**Key Sections:** -- Complete system overview -- Core data models with full struct definitions -- Service architecture with dependency graphs -- Exhaustive async pipeline documentation -- Cross-link injection algorithm details -- Wiki chunking and retrieval integration -- Agent integration with workflows -- Complete API endpoints table -- Configuration and error handling -- Performance optimization -- Common workflows and FAQ -- File structure appendix - -**When to Read:** When you need comprehensive understanding of a subsystem - ---- - -### WIKI_TECHNICAL_ANALYSIS.md -**Type:** Deep Technical Analysis -**Length:** ~1,170 lines -**Audience:** Architects, advanced developers -**Key Sections:** -- **Part 1:** Architectural Overview (1.1-1.3) - - System context and purpose - - Wiki as feature flag (key design decision) - - Core data flow diagram - - Key files and responsibilities - -- **Part 2:** Core Concepts and Patterns (2.1-2.5) - - Bidirectional link references - - Optimistic locking with version numbers - - Async batch processing with debouncing - - MAP-REDUCE pattern for extraction - - Cross-link injection with forbidden spans - -- **Part 3:** Detailed Implementation Patterns (3.1-3.4) - - Repository layer: optimistic locking - - Service layer: multi-step operations - - Async pipeline: WikiIngestService - - Linting and health monitoring - -- **Part 4:** Edge Cases and Gotchas (4.1-4.9) - - Concurrent update conflicts - - Link consistency windows - - Self-link prevention - - LLM conflict detection - - Slug reuse across updates - - CJK text handling - - Forbidden span edge cases - - Redis timing issues - - LLM parsing failures - -- **Part 5:** Operational Considerations (5.1-5.4) - - Performance scaling - - Storage considerations - - Monitoring and debugging - - Common pitfalls and solutions - -- **Part 6:** Integration Points (6.1-6.3) - - Chat pipeline integration - - Agent tool integration - - Chunk synchronization - -- **Part 7:** Future Enhancements (7.1-7.2) - - Potential improvements - - Known limitations - -**When to Read:** When designing new features or debugging complex issues - ---- - -### WIKI_IMPLEMENTATION_GUIDE.md -**Type:** Practical How-To Guide -**Length:** ~750 lines -**Audience:** Developers implementing wiki features -**Key Sections:** -- **Part 1:** Common Tasks and Patterns - - Task 1: Create a new wiki page programmatically - - Task 2: Update an existing page - - Task 3: Work with links programmatically - - Task 4: Iterate over all pages efficiently - - Task 5: Work with cross-link injection - -- **Part 2:** Testing Patterns - - Unit tests - - Integration tests - -- **Part 3:** Error Handling - - ErrWikiPageNotFound - - ErrWikiPageConflict - - LLM extraction failures - -- **Part 4:** Performance Optimization - - Batch creation - - Query optimization - - Link rebuild efficiency - -- **Part 5:** Debugging and Troubleshooting - - Check page consistency - - Monitor wiki health - -- **Part 6:** Common Mistakes - - 10 common mistakes with fixes - -- **Appendix A:** Key functions reference -- **Appendix B:** Configuration -- **Appendix C:** SQL queries for debugging - -**When to Read:** Before implementing any wiki feature - ---- - -### From Previous Sessions: Supporting Documentation - -#### KB_WIKI_ARCHITECTURE_ANALYSIS.md -**Type:** Initial architecture analysis -**Length:** ~750 lines -**Key Content:** -- High-level system design -- Data model analysis -- Service relationships -- Batch processing flow -- Integration points - -#### KB_WIKI_QUICK_REFERENCE.md -**Type:** Quick reference -**Length:** ~300 lines -**Key Content:** -- Quick navigation to common tasks -- API endpoint quick list -- Configuration quick reference -- Common errors quick lookup - -#### KB_WIKI_FILE_INDEX.md -**Type:** File directory and location reference -**Length:** ~250 lines -**Key Content:** -- All wiki-related files with locations -- File purposes and responsibilities -- Cross-references -- Updated file counts and statistics - ---- - -## Source Code Quick Reference - -### Core Data Models -**File:** `internal/types/wiki_page.go` -- `WikiPage` struct (84 lines) -- `WikiConfig` struct (12 lines) -- `WikiPageType` constants -- `WikiPageStatus` constants -- `WikiStats`, `WikiGraphNode`, `WikiGraphEdge` structs -- `WikiPageIssue` struct - -### Service Layer -**File:** `internal/application/service/wiki_page.go` -- `WikiPageService` implementation -- CreatePage, UpdatePage, UpdatePageMeta -- GetPageBySlug, GetPageByID, ListPages -- DeletePage, RebuildLinks, InjectCrossLinks -- Helper functions: parseOutLinks, normalizeSlug, updateInLinks, removeInLinks - -**File:** `internal/application/service/wiki_lint.go` -- `WikiLintService` implementation -- RunLint (comprehensive health check) -- AutoFix (automatic repair) - -### Async Pipeline -**File:** `internal/application/service/wiki_ingest.go` -- `WikiIngestService` implementation -- EnqueueWikiIngest, EnqueueWikiRetract -- Debouncing mechanism -- Redis queue management - -**File:** `internal/application/service/wiki_ingest_batch.go` -- ProcessWikiIngest handler (MAP-REDUCE) -- mapOneDocument (extraction) -- reduceSlugUpdates (synthesis) -- Post-processing steps - -### Text Processing -**File:** `internal/application/service/wiki_linkify.go` -- linkifyContent (main algorithm) -- computeForbiddenSpans (markdown structure detection) -- findFirstSafeMatch (safe occurrence finding) -- hasWordBoundary, isASCIIWordRune (boundary checking) -- Comprehensive forbidden span detection - -### Repository Layer -**File:** `internal/application/repository/wiki_page.go` -- `WikiPageRepository` implementation -- Create, Update, UpdateMeta operations -- GetByID, GetBySlug queries -- List with filtering and pagination -- Optimistic locking implementation - -### HTTP Handlers -**File:** `internal/handler/wiki_page.go` -- `WikiPageHandler` (HTTP endpoints) -- ListPages, CreatePage, GetPage, UpdatePage, DeletePage -- GetGraph, GetStats, RebuildLinks, RebuildIndexPage -- Health checking and stats endpoints - -### Integration Plugins -**File:** `internal/application/service/chat_pipeline/wiki_boost.go` -- `PluginWikiBoost` retrieval scoring plugin -- 1.3x score multiplier for wiki pages -- Ranks wiki content higher in search results - -### Agent Tools -**File:** `internal/agent/tools/wiki_write_page.go` -- `wikiWritePageTool` (create/update pages from agent) -- Parameters: slug, title, summary, content, page_type - -**File:** `internal/agent/tools/wiki_delete_page.go` -- `wikiDeletePageTool` (delete pages from agent) - -**File:** `internal/agent/tools/wiki_replace_text.go` -- `wikiReplaceTextTool` (find/replace within page) - -### LLM Prompts -**File:** `internal/agent/prompts_wiki.go` -- `WikiSummaryPrompt` (summary generation) -- `WikiKnowledgeExtractPrompt` (entity/concept extraction) -- `WikiPageModifyPrompt` (page updating) - ---- - -## Cross-Document References - -### By Topic - -**Understanding Concurrency:** -1. WIKI_TECHNICAL_ANALYSIS.md → Part 4.1 (Concurrent update conflicts) -2. WIKI_IMPLEMENTATION_GUIDE.md → Part 3 (Error handling) -3. wiki_page.go (repo) → Update method (lines 36-60) - -**Understanding Links:** -1. WIKI_TECHNICAL_ANALYSIS.md → Part 2.1 (Bidirectional links) -2. wiki_page.go (service) → updateInLinks, removeInLinks methods -3. WIKI_IMPLEMENTATION_GUIDE.md → Task 3 (Work with links) - -**Understanding Async Processing:** -1. WIKI_TECHNICAL_ANALYSIS.md → Part 2.3 & 2.4 (Debouncing and MAP-REDUCE) -2. WIKI_SYSTEM_DEEP_DIVE.md → Async pipeline section -3. wiki_ingest.go → EnqueueWikiIngest method -4. wiki_ingest_batch.go → ProcessWikiIngest handler - -**Understanding Cross-Link Injection:** -1. WIKI_TECHNICAL_ANALYSIS.md → Part 2.5 (Forbidden spans) -2. WIKI_IMPLEMENTATION_GUIDE.md → Task 5 (Cross-link injection) -3. wiki_linkify.go → Full implementation -4. wiki_linkify_test.go → Test cases (coverage) - -**Understanding Health Checking:** -1. WIKI_TECHNICAL_ANALYSIS.md → Part 3.4 (Linting) -2. wiki_lint.go → Full implementation -3. WIKI_IMPLEMENTATION_GUIDE.md → Part 5 (Monitoring) - ---- - -## Key Diagrams and Flows - -### Data Flow (ASCII) -``` -Document Upload - ↓ -EnqueueWikiIngest → Redis List (30s debounce) - ↓ -ProcessWikiIngest [Async] - ├─ MAP: Extract entities/concepts (parallel) - ├─ REDUCE: Synthesize pages (parallel) - ├─ Post-processing: Links, index, cross-link injection - └─ Schedule follow-up if pending remain - ↓ -Wiki Pages in DB - ├─ Synchronized to chunks (ChunkType="wiki_page") - ├─ Integrated in retrieval pipeline - └─ Boosted 1.3x in chat search - ↓ -Chat Integration - └─ Higher-ranked results → better answers -``` - -### Service Dependencies -``` -WikiPageService - ├─ WikiPageRepository (data access) - ├─ ChunkRepository (sync to retrieval) - ├─ KnowledgeBaseService (KB validation) - └─ Redis (pending queue, locking) - -WikiIngestService - ├─ WikiPageService (create/update pages) - ├─ KnowledgeBaseService (KB config) - ├─ KnowledgeService (fetch document chunks) - ├─ ChunkRepository (sync results) - ├─ ModelService (LLM calls) - ├─ Task queue (Asynq) - └─ Redis (debouncing, locking) - -WikiLintService - ├─ WikiPageService (get pages, graph) - ├─ KnowledgeBaseService (KB validation) - └─ No database write access (read-only) -``` - -### State Transitions -``` -WikiPage States: - draft ──→ published ──→ archived - ↑ - └─── (UpdatePage increments version) - -WikiPageIssue States: - pending ──→ acknowledged ──→ resolved - -Page Creation Flow: - 1. Create page + parse OutLinks - 2. Insert to DB - 3. Update target InLinks (async, fire-and-forget) - 4. Return to caller - -Page Update Flow: - 1. Fetch existing (get current version) - 2. Update fields + re-parse OutLinks - 3. Optimistic lock check (WHERE version = X) - 4. Update InLinks on old targets (remove) - 5. Update InLinks on new targets (add) - 6. Return updated page or ErrWikiPageConflict -``` - ---- - -## Decision Matrix: Which Document to Read - -| Question | Document | -|----------|----------| -| What is wiki and why do we have it? | WIKI_SYSTEM_SUMMARY.md | -| How do I create a new wiki page? | WIKI_IMPLEMENTATION_GUIDE.md (Task 1) | -| How does async processing work? | WIKI_TECHNICAL_ANALYSIS.md (Part 2.3-2.4) | -| What are the edge cases I should know about? | WIKI_TECHNICAL_ANALYSIS.md (Part 4) | -| How do I test my wiki feature? | WIKI_IMPLEMENTATION_GUIDE.md (Part 2) | -| What's the complete API? | WIKI_SYSTEM_DEEP_DIVE.md | -| How do I debug a broken link? | WIKI_IMPLEMENTATION_GUIDE.md (Part 5) | -| What's the data model? | internal/types/wiki_page.go | -| How does link injection work? | WIKI_TECHNICAL_ANALYSIS.md (Part 2.5) | -| How do I handle version conflicts? | WIKI_IMPLEMENTATION_GUIDE.md (Part 3) | -| What performance considerations exist? | WIKI_TECHNICAL_ANALYSIS.md (Part 5.1) | -| How is wiki integrated with chat? | WIKI_TECHNICAL_ANALYSIS.md (Part 6.1) | -| What are the LLM prompts? | internal/agent/prompts_wiki.go | -| How do I monitor wiki health? | WIKI_IMPLEMENTATION_GUIDE.md (Part 5) + wiki_lint.go | -| What's the full system architecture? | WIKI_TECHNICAL_ANALYSIS.md (Part 1) | - ---- - -## Maintenance and Updates - -This documentation set should be updated when: -- New API endpoints are added or modified -- Database schema changes -- LLM prompt templates change significantly -- Performance characteristics change -- New edge cases discovered -- Configuration options change -- Integration points change - -**To update documentation:** -1. Identify which docs are affected -2. Update in order: code first, then summaries -3. Regenerate any tables or metrics -4. Update cross-references -5. Review for accuracy and clarity - ---- - -## Feedback and Questions - -If documentation is: -- **Unclear:** Note the specific section and what's confusing -- **Incomplete:** Note what's missing -- **Outdated:** Note what's changed in the code -- **Inaccurate:** Note what's wrong and what's correct - -Post improvements as pull requests with clear descriptions. - ---- - -## Statistics - -| Metric | Value | -|--------|-------| -| Total documentation | ~3,900 lines | -| Source code (wiki only) | ~7,300 lines | -| Total wiki-related files | ~20 files | -| Test coverage | ~285 lines (wiki_linkify_test.go + wiki_page_test.go) | -| LLM prompts | 3 major templates | -| Database tables | 2 (wiki_pages, wiki_page_issues) | -| Key services | 3 (WikiPageService, WikiIngestService, WikiLintService) | -| API endpoints | 20+ (see WIKI_SYSTEM_DEEP_DIVE.md) | - diff --git a/WIKI_IMPLEMENTATION_GUIDE.md b/WIKI_IMPLEMENTATION_GUIDE.md deleted file mode 100644 index 5a510ccd..00000000 --- a/WIKI_IMPLEMENTATION_GUIDE.md +++ /dev/null @@ -1,756 +0,0 @@ -# Wiki System Implementation Guide - -**Target Audience:** Developers implementing wiki features or extending the system -**Last Updated:** April 2026 - ---- - -## Part 1: Common Tasks and Patterns - -### Task 1: Create a New Wiki Page Programmatically - -**Scenario:** Agent tool or batch process needs to create a page - -```go -import ( - "context" - "time" - "github.com/google/uuid" - "github.com/Tencent/WeKnora/internal/types" - "github.com/Tencent/WeKnora/internal/types/interfaces" -) - -func createEntityPage( - ctx context.Context, - svc interfaces.WikiPageService, - kbID string, - name string, - details string, -) (*types.WikiPage, error) { - page := &types.WikiPage{ - ID: uuid.New().String(), - KnowledgeBaseID: kbID, - Slug: slugify(name), // "Acme Corp" → "entity/acme-corp" - Title: name, - PageType: types.WikiPageTypeEntity, - Status: types.WikiPageStatusPublished, - Content: formatMarkdown(details), - Summary: firstSentence(details), - Aliases: []string{}, // Alternative names - SourceRefs: []string{}, // Knowledge IDs - Version: 1, - } - - // Service handles link parsing and inbound link updates - return svc.CreatePage(ctx, page) -} - -// Helper: normalize slug like the service does -func slugify(s string) string { - s = strings.ToLower(strings.TrimSpace(s)) - s = strings.ReplaceAll(s, " ", "-") - return "entity/" + s -} -``` - -**Key Points:** -- Service automatically parses OutLinks from content -- InLinks are updated on target pages automatically -- Version starts at 1 -- Timestamps set by service - -### Task 2: Update an Existing Page - -**Scenario:** Need to modify page content (e.g., agent synthesis) - -```go -func updatePageContent( - ctx context.Context, - svc interfaces.WikiPageService, - kbID string, - slug string, - newContent string, - newSummary string, -) (*types.WikiPage, error) { - // 1. Fetch existing page - existing, err := svc.GetPageBySlug(ctx, kbID, slug) - if err != nil { - return nil, fmt.Errorf("page not found: %w", err) - } - - // 2. Update only the fields you want to change - existing.Content = newContent - existing.Summary = newSummary - // DO NOT modify Version, OutLinks, InLinks, etc. - - // 3. Call UpdatePage - // - Service re-parses OutLinks - // - Service updates InLinks on target pages - // - Service increments version (optimistic lock) - updated, err := svc.UpdatePage(ctx, existing) - if err != nil { - // Might be ErrWikiPageConflict if version changed - // Retry with fresh fetch if needed - return nil, fmt.Errorf("update failed: %w", err) - } - - return updated, nil -} - -// INCORRECT: Do this instead -// Wrong: page.OutLinks = []string{...} // Don't manually set! -// Wrong: page.InLinks = []string{...} // Service maintains these! -``` - -**Handling Conflicts:** - -```go -// If update fails with ErrWikiPageConflict, retry -func updatePageWithRetry(ctx context.Context, svc interfaces.WikiPageService, - kbID, slug, newContent string) (*types.WikiPage, error) { - - maxRetries := 3 - for attempt := 1; attempt <= maxRetries; attempt++ { - existing, _ := svc.GetPageBySlug(ctx, kbID, slug) - existing.Content = newContent - - updated, err := svc.UpdatePage(ctx, existing) - if err == nil { - return updated, nil - } - if !strings.Contains(err.Error(), "conflict") { - return nil, err // Not a conflict, real error - } - // Conflict: retry with fresh page - } - return nil, fmt.Errorf("max retries exceeded") -} -``` - -### Task 3: Work with Links Programmatically - -**Scenario:** Need to query the link graph - -```go -func analyzePageConnections( - ctx context.Context, - svc interfaces.WikiPageService, - kbID string, - slug string, -) { - // Get the page - page, _ := svc.GetPageBySlug(ctx, kbID, slug) - - // Pages that link TO this page (backlinks) - fmt.Printf("Inbound links: %v\n", page.InLinks) // []{"page-a", "page-b"} - - // Pages this page links to (references) - fmt.Printf("Outbound links: %v\n", page.OutLinks) // []{"page-c", "page-d"} - - // Get the full graph - graph, _ := svc.GetGraph(ctx, kbID) - - // Find all pages that mention this page - incomingReferences := make(map[string]string) - for _, node := range graph.Nodes { - p, _ := svc.GetPageBySlug(ctx, kbID, node.Slug) - for _, outLink := range p.OutLinks { - if outLink == slug { - incomingReferences[node.Slug] = node.Title - } - } - } -} -``` - -**Link Consistency Guarantees:** - -```go -// If you fetch a page and it has OutLinks, those pages should exist -// (unless the link is broken) -page, _ := svc.GetPageBySlug(ctx, kbID, slug) -for _, target := range page.OutLinks { - targetPage, err := svc.GetPageBySlug(ctx, kbID, target) - if err != nil { - // Broken link! Linter would flag this - fmt.Printf("BROKEN: %s links to nonexistent %s\n", slug, target) - } -} - -// If you see page.InLinks, that page should have you in its OutLinks -// (Unless there's a race condition or bug) -page, _ := svc.GetPageBySlug(ctx, kbID, slug) -for _, inLink := range page.InLinks { - inLinkPage, _ := svc.GetPageBySlug(ctx, kbID, inLink) - if !contains(inLinkPage.OutLinks, slug) { - fmt.Printf("INCONSISTENT: %s claims to link to us, but we're not in their OutLinks\n", inLink) - } -} -``` - -### Task 4: Iterate Over All Pages Efficiently - -**Scenario:** Batch processing, statistics generation - -```go -func iterateAllPages(ctx context.Context, svc interfaces.WikiPageService, kbID string) error { - // Option 1: ListAllPages (simple, loads everything into memory) - pages, err := svc.ListAllPages(ctx, kbID) - for _, page := range pages { - processPage(page) - } - - // Option 2: Paginated List (memory-efficient, used by UI) - pageSize := 100 - for page := 1; ; page++ { - req := &types.WikiPageListRequest{ - KnowledgeBaseID: kbID, - Page: page, - PageSize: pageSize, - SortBy: "updated_at", - SortOrder: "desc", - } - resp, _ := svc.ListPages(ctx, req) - - for _, p := range resp.Pages { - processPage(p) - } - - if resp.Page * resp.PageSize >= int(resp.Total) { - break // Last page - } - } - - return nil -} - -// Filter by type -func getConceptPages(ctx context.Context, svc interfaces.WikiPageService, kbID string) ([]*types.WikiPage, error) { - pages, _ := svc.ListAllPages(ctx, kbID) - var concepts []*types.WikiPage - for _, p := range pages { - if p.PageType == types.WikiPageTypeConcept { - concepts = append(concepts, p) - } - } - return concepts, nil -} -``` - -### Task 5: Work with Cross-Link Injection - -**Scenario:** Need to understand or extend linkification - -```go -import ( - "github.com/Tencent/WeKnora/internal/application/service" -) - -// The service-level function -func injectCrossLinksExample(ctx context.Context, svc interfaces.WikiPageService, kbID string) { - // Get all pages to collect link references - allPages, _ := svc.ListAllPages(ctx, kbID) - - // Build refs from entity/concept pages - var refs []linkRef - for _, p := range allPages { - if p.PageType == types.WikiPageTypeEntity || p.PageType == types.WikiPageTypeConcept { - // Each page becomes a potential link target - ref := linkRef{ - slug: p.Slug, - matchText: p.Title, // or p.Aliases[i] - } - refs = append(refs, ref) - } - } - - // Call the service (internal function, not exported) - // Typically called by InjectCrossLinks() which batches this - for _, p := range allPages { - if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog { - continue // Don't inject into system pages - } - - // linkifyContent() is in wiki_linkify.go, NOT exported - // This is called internally by the service - } -} -``` - -**Key Implementation Detail:** - -The `linkifyContent` function is package-private (lowercase). You shouldn't call it directly. Instead: - -```go -// Correct: Use service-level InjectCrossLinks -svc.InjectCrossLinks(ctx, kbID, []string{"entity/acme"}) - -// Incorrect: Don't try to call linkifyContent directly -// content, _ := linkifyContent(page.Content, refs, page.Slug) -// (Won't compile, it's in service package not exported) -``` - ---- - -## Part 2: Testing Patterns - -### Unit Test: Page Creation and Links - -```go -package service - -import ( - "context" - "testing" - "github.com/Tencent/WeKnora/internal/types" -) - -func TestCreatePageWithLinks(t *testing.T) { - ctx := context.Background() - - // Setup - repo := NewMockWikiPageRepository() - svc := NewWikiPageService(repo, ...) - - // Create first page - page1 := &types.WikiPage{ - Slug: "entity/acme", - Title: "Acme Corp", - Content: "[[entity/bob]] founded Acme.", - } - created1, _ := svc.CreatePage(ctx, page1) - - // Verify OutLinks parsed - if len(created1.OutLinks) != 1 || created1.OutLinks[0] != "entity/bob" { - t.Fatalf("OutLinks not parsed correctly") - } - - // Create target page - page2 := &types.WikiPage{ - Slug: "entity/bob", - Title: "Bob Smith", - } - created2, _ := svc.CreatePage(ctx, page2) - - // Verify InLinks updated - // (Requires mocking updateInLinks or using integration test) - refreshed2, _ := svc.GetPageBySlug(ctx, "entity/bob") - if !contains(refreshed2.InLinks, "entity/acme") { - t.Fatalf("InLinks not updated") - } -} -``` - -### Integration Test: Full Pipeline - -```go -func TestWikiIngestToRetrieval(t *testing.T) { - // Setup: real DB, real LLM mock - ctx := context.Background() - db := setupTestDB() - modelSvc := NewMockModelService() // Mock LLM responses - - // 1. Create KB with wiki enabled - kb := &types.KnowledgeBase{ - ID: "test-kb", - WikiConfig: types.WikiConfig{ - Enabled: true, - AutoIngest: true, - SynthesisModelID: "test-model", - }, - } - // ... save to DB - - // 2. Enqueue document - ingestSvc := NewWikiIngestService(...) - ingestSvc.EnqueueWikiIngest(ctx, kb.ID, "doc1", "Document Title") - - // 3. Manually trigger batch processing (or wait + poll) - handler := NewProcessWikiIngestHandler(ingestSvc, ...) - task, _ := asynq.NewTask("wiki:ingest", payload) - handler(task) - - // 4. Verify pages created - pages, _ := pageSvc.ListAllPages(ctx, kb.ID) - if len(pages) == 0 { - t.Fatalf("No pages created") - } - - // 5. Verify chunks synchronized - chunks, _ := chunkService.GetChunks(ctx, "wp-*") // Wiki page chunks - if len(chunks) != len(pages) { - t.Fatalf("Not all pages chunked") - } - - // 6. Search and verify boost - results, _ := retriever.Search(ctx, "query") - // Wiki page chunks should rank higher due to 1.3x boost -} -``` - ---- - -## Part 3: Error Handling - -### Common Errors and Recovery - -**ErrWikiPageNotFound** - -```go -import ( - "errors" - "github.com/Tencent/WeKnora/internal/application/repository" -) - -page, err := svc.GetPageBySlug(ctx, kbID, slug) -if errors.Is(err, repository.ErrWikiPageNotFound) { - // Page doesn't exist - // Safe to create new page with this slug - return svc.CreatePage(ctx, &types.WikiPage{Slug: slug, ...}) -} -``` - -**ErrWikiPageConflict** - -```go -existing, _ := svc.GetPageBySlug(ctx, kbID, slug) -existing.Content = newContent - -updated, err := svc.UpdatePage(ctx, existing) -if errors.Is(err, repository.ErrWikiPageConflict) { - // Another process updated the page - // Retry: fetch fresh version and reapply changes - existing, _ = svc.GetPageBySlug(ctx, kbID, slug) - existing.Content = newContent - updated, _ = svc.UpdatePage(ctx, existing) // Should succeed now -} -``` - -**LLM Extraction Failures** - -```go -// During wiki ingest, if LLM call fails: -// 1. Error logged, extraction returns empty -// 2. Document marked as "processed" anyway -// 3. No automatic retry -// Recovery: Manually re-upload document - -// Check for failed extractions -for _, doc := range pendingOps { - if doc.Status == "failed" { - fmt.Printf("Document %s failed to extract\n", doc.KnowledgeID) - // Re-upload or check logs for details - } -} -``` - ---- - -## Part 4: Performance Optimization - -### Batch Creation - -**Don't do this:** - -```go -// N separate Create calls → N DB round-trips, N link updates -for _, data := range largeBatch { - page := mapToPage(data) - svc.CreatePage(ctx, &page) // Slow! -} -``` - -**Do this instead:** - -```go -// Batch in the ingest service (30s debounce) -for _, data := range largeBatch { - ingestSvc.EnqueueWikiIngest(ctx, kbID, data.KnowledgeID, data.Title) -} -// Service batches and processes in one async task -``` - -### Query Optimization - -**List with Filters** - -```go -// Good: Let repository handle filtering -req := &types.WikiPageListRequest{ - KnowledgeBaseID: kbID, - PageType: "entity", // Filter in DB - Status: "published", // Filter in DB - Query: "acme", // Full-text search in DB - PageSize: 50, -} -resp, _ := svc.ListPages(ctx, req) - -// Bad: Fetch all and filter in memory -pages, _ := svc.ListAllPages(ctx, kbID) // Loads everything! -var entities []*types.WikiPage -for _, p := range pages { - if p.PageType == "entity" { entities = append(entities, p) } -} -``` - -### Link Rebuild Efficiency - -```go -// RebuildLinks is O(n²) in worst case (all pages link to all others) -// For large wikis (>1000 pages): -// - Run in background -// - Consider scheduling off-peak -// - Monitor resource usage - -// Example: scheduled maintenance -func scheduleNightlyRebuild(svc interfaces.WikiPageService) { - go func() { - ticker := time.NewTicker(24 * time.Hour) - for range ticker.C { - if shouldRebuild() { // Check health score - svc.RebuildLinks(context.Background(), kbID) - logger.Infof(context.Background(), "nightly rebuild complete") - } - } - }() -} -``` - ---- - -## Part 5: Debugging and Troubleshooting - -### Check Page Consistency - -```go -func validatePageConsistency(ctx context.Context, - svc interfaces.WikiPageService, kbID, slug string) []string { - - var issues []string - page, _ := svc.GetPageBySlug(ctx, kbID, slug) - - // 1. Check OutLinks exist - for _, target := range page.OutLinks { - if target == page.Slug { - issues = append(issues, fmt.Sprintf("Self-link detected")) - } - tp, err := svc.GetPageBySlug(ctx, kbID, target) - if err != nil { - issues = append(issues, fmt.Sprintf("Broken OutLink: %s", target)) - } else if !contains(tp.InLinks, slug) { - issues = append(issues, fmt.Sprintf("InLink inconsistency: %s should have inbound from %s", target, slug)) - } - } - - // 2. Check InLinks reciprocal - for _, source := range page.InLinks { - sp, _ := svc.GetPageBySlug(ctx, kbID, source) - if !contains(sp.OutLinks, slug) { - issues = append(issues, fmt.Sprintf("InLink inconsistency: %s claims to link here but doesn't", source)) - } - } - - // 3. Check content matches OutLinks - foundLinks := parseLinks(page.Content) - for _, link := range foundLinks { - if !contains(page.OutLinks, link) { - issues = append(issues, fmt.Sprintf("Content has link [[%s]] not in OutLinks", link)) - } - } - - return issues -} - -// Usage -issues := validatePageConsistency(ctx, svc, kbID, "entity/acme") -if len(issues) > 0 { - logger.Warnf(ctx, "Page consistency issues: %v", issues) - // Consider running RebuildLinks to fix -} -``` - -### Monitor Wiki Health - -```go -func monitorWikiHealth(ctx context.Context, - lintSvc *service.WikiLintService, kbID string) { - - report, _ := lintSvc.RunLint(ctx, kbID) - - fmt.Printf("Health Score: %d/100\n", report.HealthScore) - fmt.Printf("Total Issues: %d\n", len(report.Issues)) - - for _, issue := range report.Issues { - fmt.Printf("[%s] %s: %s\n", - issue.Severity, issue.Type, issue.Description) - } - - if report.HealthScore < 70 { - logger.Warnf(ctx, "Wiki health below threshold: %d/100", report.HealthScore) - // Consider triggering AutoFix - fixed, _ := lintSvc.AutoFix(ctx, kbID) - logger.Infof(ctx, "AutoFix resolved %d issues", fixed) - } -} -``` - ---- - -## Part 6: Common Mistakes and How to Avoid Them - -| Mistake | Problem | Fix | -|---------|---------|-----| -| Manually setting OutLinks | Links get out of sync | Let service parse from Content | -| Manually setting InLinks | Inbound refs become stale | Let service maintain via updateInLinks | -| Calling linkifyContent directly | Package is private | Use service.InjectCrossLinks | -| Not handling ErrWikiPageConflict | Updates silently fail | Add retry logic for conflicts | -| Storing page without timestamp | Audit trail lost | Set CreatedAt/UpdatedAt before Create | -| Mixing wiki and non-wiki KBs | Feature gating fails | Check IsWikiEnabled() always | -| Assuming slug format | Future formats might change | Use parseSlug() helper | -| Long-running UpdatePage loops | Timeout/deadlock risk | Batch with EnqueueWikiIngest | -| Ignoring LLM extraction errors | Partial data persists | Log and monitor failures | -| Direct database updates | Links become inconsistent | Always use service layer | - ---- - -## Appendix A: Key Functions Reference - -### WikiPageService - -| Method | Purpose | When to Use | -|--------|---------|------------| -| CreatePage | Insert new page | Creating extracted/synthesized pages | -| UpdatePage | Update content (version bump) | Modifying page text, title, summary | -| UpdatePageMeta | Update metadata (no version bump) | Internal link maintenance | -| GetPageBySlug | Fetch by (kbID, slug) | Retrieve for display/editing | -| GetPageByID | Fetch by UUID | Less common, used internally | -| ListPages | Paginated list with filters | UI pagination, search | -| ListAllPages | All pages without pagination | Batch processing, analysis | -| SearchPages | Full-text search | User search queries | -| DeletePage | Soft delete | Remove pages | -| GetIndex | Fetch/create index page | Getting wiki directory | -| GetLog | Fetch/create log page | Getting operation history | -| GetGraph | Build link graph | Visualization, analysis | -| GetStats | Aggregate statistics | Dashboard, monitoring | -| RebuildLinks | Re-establish all references | Recovery after bugs | -| InjectCrossLinks | Auto-link pages | Post-ingest cross-linking | -| RebuildIndexPage | Regenerate index | After page changes | - -### WikiLintService - -| Method | Purpose | Returns | -|--------|---------|---------| -| RunLint | Health check | WikiLintReport (issues, score, stats) | -| AutoFix | Auto-repair issues | Number of fixed issues | - -### WikiIngestService - -| Method | Purpose | When to Use | -|--------|---------|------------| -| EnqueueWikiIngest | Queue document for processing | After document upload | -| EnqueueWikiRetract | Queue document deletion | When document deleted | - ---- - -## Appendix B: Configuration - -```yaml -# Example wiki config in knowledge base -wiki_config: - enabled: true - auto_ingest: true - synthesis_model_id: "gpt-4" # or "claude-3-opus", etc. - max_pages_per_ingest: 0 # 0 = unlimited - -# Environment-level defaults -WIKI_INGEST_DELAY: 30s # Debounce window -WIKI_MAX_DOCS_PER_BATCH: 5 # Docs per batch -WIKI_MAX_CONTENT_SIZE: 33554432 # 32 MB per document -WIKI_PENDING_TTL: 86400 # 24 hours -WIKI_LOCK_TTL: 300 # 5 minutes - -# LLM-specific settings -WIKI_SYNTHESIS_MODEL: "gpt-4-turbo" -WIKI_EXTRACTION_MODEL: "gpt-4" -WIKI_TEMPERATURE: 0.3 # Lower = more deterministic -WIKI_MAX_TOKENS: 4000 # Per LLM call -``` - ---- - -## Appendix C: SQL Queries for Debugging - -```sql --- Find all orphan pages -SELECT slug, title, page_type, updated_at -FROM wiki_pages -WHERE knowledge_base_id = 'kb123' - AND page_type NOT IN ('index', 'log') - AND JSON_LENGTH(in_links) = 0 -ORDER BY updated_at DESC; - --- Find broken links -SELECT DISTINCT p.slug, p.title, - JSON_UNQUOTE(JSON_EXTRACT(p.out_links, '$[*]')) as broken_target -FROM wiki_pages p -WHERE knowledge_base_id = 'kb123' - AND JSON_LENGTH(p.out_links) > 0 - AND NOT EXISTS ( - SELECT 1 FROM wiki_pages t - WHERE t.knowledge_base_id = p.knowledge_base_id - AND t.slug = JSON_UNQUOTE(JSON_EXTRACT(p.out_links, '$[0]')) - ); - --- Find highest-linked pages (hub pages) -SELECT slug, title, - JSON_LENGTH(in_links) as inbound_count, - JSON_LENGTH(out_links) as outbound_count -FROM wiki_pages -WHERE knowledge_base_id = 'kb123' - AND page_type NOT IN ('index', 'log') -ORDER BY JSON_LENGTH(in_links) DESC -LIMIT 20; - --- Find pages by type distribution -SELECT page_type, COUNT(*) as count, - AVG(LENGTH(content)) as avg_size, - AVG(JSON_LENGTH(in_links)) as avg_inlinks -FROM wiki_pages -WHERE knowledge_base_id = 'kb123' - AND deleted_at IS NULL -GROUP BY page_type -ORDER BY count DESC; - --- Monitor recent activity -SELECT slug, title, page_type, updated_at, version -FROM wiki_pages -WHERE knowledge_base_id = 'kb123' - AND deleted_at IS NULL -ORDER BY updated_at DESC -LIMIT 20; - --- Find pages by source knowledge -SELECT slug, title, COUNT(*) as source_count -FROM wiki_pages, JSON_TABLE( - source_refs, '$[*]' COLUMNS (ref VARCHAR(100) PATH '$') -) jt -WHERE knowledge_base_id = 'kb123' - AND knowledge_id = 'knowledgeID123' -GROUP BY slug, title; -``` - ---- - -## Summary - -This guide covers the essential patterns for working with the wiki system. Key principles: - -1. **Always use the service layer** — don't access repository directly -2. **Let the service maintain links** — don't manually set InLinks/OutLinks -3. **Handle concurrency** — retry on ErrWikiPageConflict -4. **Use the ingest pipeline** — batch operations via EnqueueWikiIngest -5. **Monitor health** — run RunLint periodically -6. **Debug with tools** — use GetGraph, GetStats, linter for troubleshooting - -For more details, see `WIKI_TECHNICAL_ANALYSIS.md` for deep dives into architecture and edge cases. - diff --git a/WIKI_README.md b/WIKI_README.md deleted file mode 100644 index 38b6c6de..00000000 --- a/WIKI_README.md +++ /dev/null @@ -1,301 +0,0 @@ -# WeKnora Wiki System - Complete Documentation - -Welcome! This directory contains comprehensive documentation of the WeKnora wiki knowledge base system. - -## Quick Start - -**New to the wiki system?** Start here: - -1. **Read WIKI_SYSTEM_SUMMARY.md** (5-10 minutes) - - Understand what the wiki system does - - Learn the key architecture concepts - - Get familiar with common workflows - -2. **Browse WIKI_DOCS_INDEX.md** (2 minutes) - - Find what you're looking for - - Navigate between documents - - Make decisions about which doc to read next - -3. **Dive into specific docs** - - **Implementing a feature?** → WIKI_IMPLEMENTATION_GUIDE.md - - **Designing changes?** → WIKI_TECHNICAL_ANALYSIS.md - - **Need complete reference?** → WIKI_SYSTEM_DEEP_DIVE.md - -## Document Overview - -| Document | Purpose | Length | Audience | -|----------|---------|--------|----------| -| **WIKI_SYSTEM_SUMMARY.md** | Executive overview of wiki functionality | 470 lines | Everyone | -| **WIKI_SYSTEM_DEEP_DIVE.md** | Comprehensive technical reference | 950 lines | Developers, Architects | -| **WIKI_TECHNICAL_ANALYSIS.md** | Deep architectural analysis with edge cases | 1,170 lines | Advanced developers, Architects | -| **WIKI_IMPLEMENTATION_GUIDE.md** | Practical how-to guide with code examples | 750 lines | Feature developers | -| **WIKI_DOCS_INDEX.md** | Navigation and cross-references | 480 lines | Everyone | -| **WIKI_README.md** | This file | - | First-time readers | - -**Total:** ~5,800 lines of documentation + ~7,300 lines of source code - -## Key Concepts at a Glance - -### What is Wiki? - -A knowledge graph system that: -- Extracts entities and concepts from uploaded documents -- Synthesizes multi-document knowledge into canonical pages -- Maintains bidirectional link references for graph traversal -- Auto-links page content via pattern matching -- Integrates with chat retrieval for enhanced results - -### Core Architecture - -``` -Document Upload - ↓ -Queue (Redis, 30s debounce) - ↓ -Async Batch Processing (MAP-REDUCE) - ├─ Extract: LLM calls for entities/concepts - ├─ Synthesize: Merge multi-document knowledge - ├─ Post-process: Inject cross-links, rebuild index - ↓ -Database Storage + Retrieval Indexing - ↓ -Chat Integration (1.3x score boost for wiki pages) -``` - -### Key Design Decisions - -1. **Wiki as Feature Flag** — Not a KB type, but an option on any KB -2. **Async with Debouncing** — Batches documents for efficiency -3. **MAP-REDUCE Pattern** — Parallel extraction and synthesis -4. **Bidirectional Links** — Automatic link maintenance for graph queries -5. **Text-Based Injection** — Pattern matching for auto-linking -6. **Optimistic Locking** — Version-based conflict detection - -## FAQ - -**Q: Is wiki enabled for my knowledge base?** -A: Check if `kb.WikiConfig.Enabled` is true. Use `GetKnowledgeBaseByID` to verify. - -**Q: Why is my page not showing in search?** -A: Pages must have status=`published`. Check `RunLint` for health issues. Wiki page chunks need to be synchronized (should happen automatically). - -**Q: How long does wiki ingestion take?** -A: Documents queue with a 30-second debounce. Typically 5-30 seconds per batch depending on LLM latency. - -**Q: Can I update a page while ingestion is running?** -A: Yes, but you might get `ErrWikiPageConflict` if concurrent updates hit the same page. Retry with fresh version. - -**Q: How do I fix broken links?** -A: Run `WikiLintService.RunLint()` to detect them. Use `AutoFix()` to repair automatically, or manually update page content. - -**Q: Can wiki pages link to each other?** -A: Yes! Links are parsed from `[[slug]]` or `[[slug|display text]]` markdown syntax in page content. - -**Q: What's the difference between UpdatePage and UpdatePageMeta?** -A: `UpdatePage` is for content changes and bumps version. `UpdatePageMeta` is for internal bookkeeping (links, status) without version bump. - -**Q: How does cross-link injection work?** -A: System scans page content for matches of entity/concept names, wraps unlinked mentions as `[[slug|name]]`. Smart enough to skip code blocks and existing links. - -**Q: What if LLM extraction fails?** -A: Document is logged as processed anyway. No automatic retry. Document can be re-uploaded if needed. - -**Q: How can I monitor wiki health?** -A: Use `WikiLintService.RunLint()` which returns a health score (0-100), statistics, and detected issues. - -## Common Tasks - -### Check if Wiki is Enabled -```go -kb, _ := kbService.GetKnowledgeBaseByID(ctx, kbID) -if kb.IsWikiEnabled() { - // Wiki is active -} -``` - -### Create a Wiki Page -```go -page := &types.WikiPage{ - Slug: "entity/acme-corp", - Title: "Acme Corporation", - Content: "[[entity/bob]] founded Acme in 2020.", - PageType: types.WikiPageTypeEntity, -} -created, _ := wikiService.CreatePage(ctx, page) -``` - -### Get All Pages -```go -pages, _ := wikiService.ListAllPages(ctx, kbID) -for _, p := range pages { - fmt.Printf("%s: %s (%d inbound, %d outbound links)\n", - p.Slug, p.Title, len(p.InLinks), len(p.OutLinks)) -} -``` - -### Check Page Health -```go -report, _ := lintService.RunLint(ctx, kbID) -fmt.Printf("Health Score: %d/100\n", report.HealthScore) -if report.HealthScore < 70 { - fixed, _ := lintService.AutoFix(ctx, kbID) - fmt.Printf("Fixed %d issues\n", fixed) -} -``` - -### Update Page Content -```go -page, _ := wikiService.GetPageBySlug(ctx, kbID, slug) -page.Content = newContent // Update content -updated, err := wikiService.UpdatePage(ctx, page) -if err != nil { - // Handle conflict retry -} -``` - -## File Structure - -``` -WeKnora/ -├── WIKI_README.md ← You are here -├── WIKI_DOCS_INDEX.md ← Navigation hub -├── WIKI_SYSTEM_SUMMARY.md ← Start here (5 min) -├── WIKI_SYSTEM_DEEP_DIVE.md ← Comprehensive reference -├── WIKI_TECHNICAL_ANALYSIS.md ← Deep architecture -├── WIKI_IMPLEMENTATION_GUIDE.md ← How-to guide -│ -├── internal/types/ -│ ├── wiki_page.go ← Data models -│ └── wiki_page_test.go ← Model tests -│ -├── internal/application/service/ -│ ├── wiki_page.go ← Core service (628 lines) -│ ├── wiki_ingest.go ← Async pipeline (1,053 lines) -│ ├── wiki_ingest_batch.go ← MAP-REDUCE handler (796 lines) -│ ├── wiki_linkify.go ← Cross-link injection (565 lines) -│ ├── wiki_lint.go ← Health checking (323 lines) -│ ├── wiki_page_test.go ← Service tests -│ ├── wiki_ingest_test.go ← Ingest tests -│ ├── wiki_linkify_test.go ← Linkify tests (285 lines) -│ ├── chat_pipeline/ -│ │ └── wiki_boost.go ← Retrieval plugin -│ └── ... -│ -├── internal/application/repository/ -│ └── wiki_page.go ← Data access layer (357 lines) -│ -├── internal/handler/ -│ └── wiki_page.go ← HTTP endpoints (560 lines) -│ -├── internal/agent/ -│ ├── prompts_wiki.go ← LLM prompts (258 lines) -│ └── tools/ -│ ├── wiki_write_page.go ← Create/update tool -│ ├── wiki_delete_page.go ← Delete tool -│ ├── wiki_replace_text.go ← Find/replace tool -│ └── ... -│ -└── ... (other WeKnora files) -``` - -## Reading Paths - -### Path 1: Quick Orientation (15 minutes) -1. WIKI_README.md (this file) — 3 min -2. WIKI_SYSTEM_SUMMARY.md — 5 min -3. WIKI_DOCS_INDEX.md → choose next doc — 5 min - -### Path 2: Implementing a Feature (90 minutes) -1. WIKI_SYSTEM_SUMMARY.md — 5 min -2. WIKI_IMPLEMENTATION_GUIDE.md → relevant task — 20 min -3. Source code reading (related service) — 30 min -4. Write tests — 20 min -5. Review WIKI_TECHNICAL_ANALYSIS.md for edge cases — 15 min - -### Path 3: Architectural Review (2-3 hours) -1. WIKI_SYSTEM_SUMMARY.md — 10 min -2. WIKI_SYSTEM_DEEP_DIVE.md (full) — 45 min -3. WIKI_TECHNICAL_ANALYSIS.md (full) — 60 min -4. Source code deep dive — 45 min - -### Path 4: Debugging (30-60 minutes) -1. WIKI_TECHNICAL_ANALYSIS.md → Part 4 (Edge Cases) — 15 min -2. WIKI_IMPLEMENTATION_GUIDE.md → Part 5 (Debugging) — 10 min -3. SQL queries in appendix — 5 min -4. Source code inspection — 20-30 min - -## Key Files to Know - -**Most Important:** -- `wiki_page.go` (service) — Core operations -- `wiki_ingest.go` — Async orchestration -- `wiki_ingest_batch.go` — Batch processor -- `wiki_linkify.go` — Link injection algorithm - -**Important:** -- `wiki_page.go` (types) — Data structures -- `wiki_lint.go` — Health checking -- `wiki_page.go` (repository) — Data access -- `wiki_page.go` (handler) — HTTP API - -**Reference:** -- `prompts_wiki.go` — LLM prompts -- `wiki_boost.go` — Retrieval integration - -## Testing - -All wiki functionality has tests: -- Unit tests: `wiki_linkify_test.go` (285 lines, 13 test functions) -- Service tests: `wiki_page_test.go` (100 lines) -- Integration tests: `wiki_ingest_test.go` - -Run tests: -```bash -go test ./internal/application/service/... -go test ./internal/application/repository/... -go test ./internal/types/... -``` - -## Performance Notes - -- **Debounce window:** 30 seconds -- **Batch size:** 5 documents per batch -- **Parallel goroutines:** 10 (extraction), 10 (synthesis) -- **Lock TTL:** 5 minutes -- **Pending operations TTL:** 24 hours -- **Typical page size:** 2-50 KB -- **Cross-link injection:** O(n*m) where n=pages, m=slug count - -## Operational Monitoring - -Key metrics to watch: -- `wiki:pending:{kbID}` list length (pending documents) -- `wiki:active:{kbID}` presence (processing running?) -- Health score from `RunLint` (0-100) -- Orphan page count (pages with no inbound links) -- Broken link count (pages linking to nonexistent targets) - -## Getting Help - -1. **API question?** → WIKI_SYSTEM_DEEP_DIVE.md (API Endpoints section) -2. **Implementation question?** → WIKI_IMPLEMENTATION_GUIDE.md -3. **Architecture question?** → WIKI_TECHNICAL_ANALYSIS.md -4. **Can't find something?** → WIKI_DOCS_INDEX.md (Navigation) -5. **Need to run SQL query?** → WIKI_IMPLEMENTATION_GUIDE.md (Appendix C) - -## Contributing to Documentation - -If you: -- Find inaccuracies → update the doc -- Find gaps → add examples or explanations -- Find unclear sections → simplify or add context -- Implement new features → document them here - -Keep all docs in `/` (root directory) for easy access. - ---- - -**Last Updated:** April 20, 2026 -**Total Documentation:** ~5,800 lines -**Total Source Code:** ~7,300 lines (wiki-related files only) - diff --git a/WIKI_SYSTEM_DEEP_DIVE.md b/WIKI_SYSTEM_DEEP_DIVE.md deleted file mode 100644 index c18e7c83..00000000 --- a/WIKI_SYSTEM_DEEP_DIVE.md +++ /dev/null @@ -1,948 +0,0 @@ -# WeKnora Wiki System - Complete Technical Deep Dive - -**Last Updated:** 2026-04-20 - -This document provides an exhaustive technical analysis of the WeKnora Wiki system, including data models, service architecture, async pipelines, API endpoints, and integration points. - ---- - -## Table of Contents - -1. [System Overview](#system-overview) -2. [Core Data Models](#core-data-models) -3. [Service Architecture](#service-architecture) -4. [Async Wiki Generation Pipeline](#async-wiki-generation-pipeline) -5. [Cross-Link Injection System](#cross-link-injection-system) -6. [Wiki Chunking & Retrieval](#wiki-chunking--retrieval) -7. [Agent Integration](#agent-integration) -8. [API Endpoints](#api-endpoints) -9. [Configuration & Settings](#configuration--settings) -10. [Error Handling & Observability](#error-handling--observability) - ---- - -## System Overview - -### What is Wiki? - -Wiki is **NOT** a knowledge base type. Instead, it is a **feature flag** (`WikiConfig.Enabled`) that can be enabled on document-type knowledge bases. When enabled, the system: - -1. **Automatically generates LLM-synthesized wiki pages** from uploaded documents -2. **Maintains bidirectional link references** between pages -3. **Provides graph visualization** of page relationships -4. **Boosts wiki page retrieval** in search results -5. **Tracks wiki health** via linting and statistics - -### Key Architectural Decisions - -| Aspect | Decision | Rationale | -|--------|----------|-----------| -| **Page Types** | 7 types (summary, entity, concept, index, log, synthesis, comparison) | Different semantic purposes for different page categories | -| **Link Representation** | Bidirectional (InLinks + OutLinks) | Enables graph traversal and orphan detection | -| **Async Processing** | Asynq + Redis with debouncing | Batches rapid uploads, prevents thundering herd | -| **Indexing** | Dual-path (chunks + wiki pages) | Preserves raw docs while adding synthesis | -| **Cross-Linking** | Pure text-based pattern matching | No LLM cost, deterministic, handles code blocks | -| **Chunk Syncing** | WikiPage → Chunk (ChunkType=wiki_page) | Reuses existing retrieval pipeline | -| **Version Control** | Optimistic locking per page | Allows concurrent edits with conflict detection | - ---- - -## Core Data Models - -### WikiPage Entity - -**Location:** `internal/types/wiki_page.go` (lines 43-84) - -```go -type WikiPage struct { - ID string // UUID - TenantID uint64 // Multi-tenant isolation - KnowledgeBaseID string // Parent KB - Slug string // URL-friendly identifier (unique per KB) - Title string // Human-readable title - PageType string // "summary" | "entity" | "concept" | "index" | "log" | "synthesis" | "comparison" - Status string // "draft" | "published" | "archived" - Content string // Full markdown content - Summary string // One-line summary for index listing - Aliases StringArray // Alternative names (JSON array) - SourceRefs StringArray // Knowledge IDs that contributed (JSON, format: "id|title") - InLinks StringArray // Backlinks (pages linking to this) - OutLinks StringArray // Outbound links (pages this links to) - PageMetadata JSON // Arbitrary key-value metadata - Version int // For optimistic locking - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt gorm.DeletedAt // Soft delete -} -``` - -**Database:** Table `wiki_pages` -- Primary Key: `id` (UUID) -- Unique Index: `(knowledge_base_id, slug)` -- Foreign Index: `knowledge_base_id`, `tenant_id` - -### WikiPageIssue Entity - -**Location:** `internal/types/wiki_page.go` (lines 176-196) - -```go -type WikiPageIssue struct { - ID string - TenantID uint64 - KnowledgeBaseID string - Slug string - IssueType string // "orphan_page" | "broken_link" | "stale_ref" | etc. - Description string - SuspectedKnowledgeIDs StringArray // Knowledge IDs related to the issue - Status string // "pending" | "resolved" | "ignored" - ReportedBy string // "linter" | "agent" | "user" - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt gorm.DeletedAt -} -``` - -### WikiConfig Structure - -**Location:** `internal/types/knowledgebase.go` (lines 94-103) - -```go -type WikiConfig struct { - Enabled bool // Feature flag - AutoIngest bool // Automatically generate wiki from documents - SynthesisModelID string // LLM model for generation (defaults to KB.SummaryModelID) - MaxPagesPerIngest int // Limit pages per batch (0 = unlimited) -} -``` - -Embedded in `KnowledgeBase`: -```go -type KnowledgeBase struct { - // ... other fields ... - WikiConfig *WikiConfig // pointer, only set if wiki is enabled - // ... -} -``` - ---- - -## Service Architecture - -### Service Dependency Graph - -``` -WikiPageService (interface) -├── repo: WikiPageRepository (database layer) -├── chunkRepo: ChunkRepository (for chunk deletion on page delete) -└── kbService: KnowledgeBaseService - -WikiIngestService (interface: TaskHandler) -├── wikiService: WikiPageService -├── kbService: KnowledgeBaseService -├── knowledgeSvc: KnowledgeService (for getting document content) -├── chunkRepo: ChunkRepository (for reading document chunks) -├── modelService: ModelService (for LLM chat models) -├── task: TaskEnqueuer (Asynq task queue) -└── redisClient: *redis.Client (for pending list & distributed lock) -``` - -### WikiPageService Interface - -**Location:** `internal/types/interfaces/wiki_page.go` (lines 12-77) - -**Implemented by:** `internal/application/service/wiki_page.go` - -**Key Methods:** - -| Method | Purpose | -|--------|---------| -| `CreatePage(ctx, page)` | Create wiki page, parse links, sync to chunks | -| `UpdatePage(ctx, page)` | Update with link re-parsing and version bump | -| `UpdatePageMeta(ctx, page)` | Update metadata-only (no version bump) | -| `GetPageBySlug(ctx, kbID, slug)` | Retrieve single page | -| `ListPages(ctx, req)` | Paginated list with filtering | -| `DeletePage(ctx, kbID, slug)` | Soft-delete and clean links | -| `GetIndex(ctx, kbID)` | Get/create index page | -| `GetLog(ctx, kbID)` | Get/create log page | -| `GetGraph(ctx, kbID)` | Build link graph for visualization | -| `GetStats(ctx, kbID)` | Aggregate statistics | -| `RebuildLinks(ctx, kbID)` | Full rebuild of all link references | -| `InjectCrossLinks(ctx, kbID, slugs)` | Auto-link mentions in specified pages | -| `RebuildIndexPage(ctx, kbID)` | Regenerate index page directory | -| `SearchPages(ctx, kbID, query, limit)` | Full-text search | -| `CreateIssue(ctx, issue)` | Flag an issue | -| `ListIssues(ctx, kbID, slug, status)` | Retrieve issues | -| `UpdateIssueStatus(ctx, issueID, status)` | Mark resolved/ignored | - ---- - -## Async Wiki Generation Pipeline - -### Architecture: MAP-REDUCE Pattern with Debouncing - -The wiki ingest pipeline uses a **debounced batch processing** model: - -``` -Document Upload Event - ↓ -EnqueueWikiIngest() called - ├─ RPush knowledge_id to Redis list: wiki:pending:{kbID} - └─ Schedule asynq task with 30s delay - -Multiple rapid uploads (within 30s window) - ├─ Each RPush adds to same list - └─ Each schedules a new task - -First task fires at t=30s - ├─ Acquires redis lock: wiki:active:{kbID} (TTL: 5 min) - ├─ Drains pending list: [doc1, doc2, doc3, ...] - ├─ Processes all in MAP-REDUCE - └─ Trims processed docs from list - -Remaining tasks fire at t=35s, t=40s, ... - ├─ Find empty pending list - └─ Return as no-op -``` - -### ProcessWikiIngest() - Main Handler - -**Location:** `internal/application/service/wiki_ingest_batch.go` (lines 46-362) - -**Flow:** - -1. **Initialization (lines 46-167)** - - Parse payload - - Inject tenant ID and language into context - - Acquire non-blocking Redis lock (`SetNX` with 5-min TTL) - - Spawn background task to refresh lock every 2 minutes - - Validate KB and fetch synthesis model - -2. **Queue Peek (lines 170-186)** - - `peekPendingList()`: Fetch up to `wikiMaxDocsPerBatch` (5) operations without removing - - Deduplicate by knowledge_id, keeping only the LAST operation per doc - - Supports both Redis mode and Lite mode (fallback for testing) - -3. **MAP Phase (lines 212-273)** - - Parallel processing: up to 10 concurrent goroutines - - For each pending operation: - - **Ingest:** Call `mapOneDocument()` to extract entities/concepts - - **Retract:** Mark page slugs for removal/cleanup - - Result: `slugUpdates` map (slug → list of updates to apply) - - Accumulate `docPreview` for logging - -4. **REDUCE Phase (lines 275-305)** - - Parallel processing: up to 10 concurrent goroutines - - For each affected slug: - - Call `reduceSlugUpdates()` to apply all accumulated changes - - Perform LLM deduplication, content synthesis, and save - - Track pages affected by ingests vs retracts separately - -5. **Post-Processing (lines 308-356)** - - **Log Entries:** Append to log page (chronological trace) - - **Index Rebuild:** Update index page with change description - - **Dead Link Cleanup:** Remove references to deleted/archived pages - - **Cross-Link Injection:** Auto-link mentions of existing pages - - **Draft Publishing:** Transition draft pages to published - - **List Trimming:** Remove processed items from Redis pending list - -6. **Follow-Up Scheduling (line 360)** - - If more items remain in pending list: schedule follow-up task - - Short delay (5s) since lock already held - -### mapOneDocument() - Extract Entities & Concepts - -**Location:** `internal/application/service/wiki_ingest_batch.go` (lines 364-532) - -**Process:** - -``` -Input: WikiPendingOp {Op: "ingest", KnowledgeID: "doc-uuid", ...} - -1. Fetch chunks for document via ChunkRepository -2. Reconstruct full content from chunks -3. Truncate to 32KB if needed (maxContentForWiki) -4. Extract document title from metadata or first chunk -5. Call LLM: "WikiKnowledgeExtractPrompt" - ├─ Input: document title, content, previous slugs - └─ Output: JSON {entities: [...], concepts: [...]} -6. Deduplicate extracted items against existing wiki pages -7. Generate summary page via "WikiSummaryPrompt" -8. Compile SlugUpdate[] for all affected pages - ├─ Summary page update - ├─ Entity pages - ├─ Concept pages - └─ Stale page retracts (pages from old ingest that aren't in new extraction) -9. Return docIngestResult {title, summary, pages affected} -``` - -**LLM Prompts Used:** -- `agent.WikiKnowledgeExtractPrompt`: Extract entities and concepts -- `agent.WikiDeduplicationPrompt`: Merge/deduplicate extracted items -- `agent.WikiSummaryPrompt`: Generate document summary page - -### reduceSlugUpdates() - Apply Changes to Page - -**Location:** `internal/application/service/wiki_ingest_batch.go` (lines 589-796) - -**Logic:** - -``` -Input: slug, updates[]SlugUpdate (summary, entities, concepts, retracts) - -For Summary Page: -├─ Create or update -├─ Set content from LLM-generated summary -└─ Add source ref - -For Entity/Concept Pages: -├─ Load existing page (or create new draft) -├─ Separate updates into: additions, retracts -├─ Call LLM: "WikiPageModifyPrompt" -│ ├─ Inputs: -│ │ ├─ HasAdditions: "1" or "" -│ │ ├─ HasRetractions: "1" or "" -│ │ ├─ ExistingContent: current page content -│ │ ├─ NewContent: new entities/concepts to add -│ │ ├─ DeletedContent: content from retracted documents -│ │ ├─ RemainingSourcesContent: other docs still referencing this page -│ │ └─ AvailableSlugs: related pages (for cross-reference suggestions) -│ └─ Output: Updated markdown content -├─ Update title, content, aliases, source_refs -├─ Save via wikiService.UpdatePage() or CreatePage() -└─ Return (changed, affectedType, err) -``` - -**Key Features:** -- **Multi-source pages:** Can reference multiple documents -- **Incremental updates:** Previous content preserved and merged -- **Stale handling:** Retracting removes document from page without deleting page -- **Content synthesis:** LLM rewrites to incorporate changes while preserving key info - -### Redis Keys Used - -| Key Pattern | Purpose | Type | TTL | -|-------------|---------|------|-----| -| `wiki:pending:{kbID}` | List of pending operations | Redis List | 24 hours | -| `wiki:active:{kbID}` | Lock for concurrent batch prevention | String | 5 minutes (refreshed every 2 min) | - -### Constants - -```go -wikiIngestDelay = 30 * time.Second // Debounce window -wikiPendingTTL = 24 * time.Hour // Stale cleanup -wikiMaxDocsPerBatch = 5 // Per-task limit -maxContentForWiki = 32768 // Rune limit for LLM input -``` - ---- - -## Cross-Link Injection System - -### Purpose - -Auto-detect mentions of existing wiki page titles in content and wrap them with `[[wiki-links]]` to establish connections. This is done via pure text processing (no LLM call) with sophisticated pattern matching. - -### Implementation: linkifyContent() - -**Location:** `internal/application/service/wiki_linkify.go` (lines 35-82) - -**Algorithm:** - -1. **Sort refs by matchText length (descending)** - - Prevents shorter substrings from shadowing longer terms - - Example: "Python" before "Python Software Foundation" - -2. **Build forbidden spans** - - Regions that must NOT be touched: - - Fenced code blocks (```/~~~) - - Inline code (backtick-delimited) - - Existing wiki links [[slug|text]] - - Markdown links [text](url) - - Images ![alt](url) - - Reference-style links [text][ref] - - Autolinks - -3. **For each ref:** - - Skip if already linked elsewhere (one link per slug per page) - - Find first safe match outside forbidden spans - - Check word boundaries (for ASCII-letter matches) - - Wrap with `[[slug|matchText]]` - - Update forbidden spans to include new link - - Mark slug as used - -4. **Return:** Modified content + changed flag - -### Forbidden Span Detection: computeForbiddenSpans() - -**Location:** `internal/application/service/wiki_linkify.go` (lines 202-296) - -**Covers:** - -- **Fenced code:** Lines starting with ``` or ~~~ (3+ chars) - - Implementation: Line-based scanning, end via matching fence - -- **Inline code:** Backtick runs - - Rules: Matching length, stops at double newline or closing backtick - -- **Reference definitions:** `[label]: url ...` - - Pattern: Optional indent (0-3 spaces), `[label]:` at line start - -- **Wiki links:** `[[slug|text]]` or `[[slug]]` - - Extraction: Parse slug portion, mark as used - -- **Markdown links:** `[text](url)` - - Balanced bracket/paren matching with escape handling - -- **Reference links:** `[text][label]` - - Two-part pattern matching - -- **Images:** `![alt](url)` - - Same logic as markdown links - -- **Autolinks:** `` or `` - -### Word Boundary Checking: hasWordBoundary() - -**Location:** `internal/application/service/wiki_linkify.go` (lines 140-154) - -**Purpose:** For ASCII-letter matches, ensure match is not mid-word - -**Rules:** -- ASCII word characters: `[a-zA-Z0-9_]` -- Non-ASCII (CJK, punctuation): Always treated as boundary -- Example: - - "Python" in "Python 3" ✓ (space is boundary) - - "Python" in "Python3" ✗ (digit is word char) - - "北京" in "北京邮电" ✓ (multi-char CJK handled by length ordering) - ---- - -## Wiki Chunking & Retrieval - -### Wiki Page → Chunk Sync - -**Location:** `internal/application/service/wiki_page.go` (lines 431-436) - -Wiki pages are synced as chunks to enable retrieval through the normal search pipeline. - -```go -// When a wiki page is deleted: -func (s *wikiPageService) deleteChunkForPage(ctx context.Context, page *types.WikiPage) { - chunkID := "wp-" + page.ID - if err := s.chunkRepo.DeleteChunk(ctx, page.TenantID, chunkID); err != nil { - logger.Warnf(ctx, "wiki: failed to delete chunk for page %s: %v", page.Slug, err) - } -} -``` - -**Chunk Structure:** - -When a wiki page is converted to a chunk: -- **ChunkID:** `"wp-" + page.ID` (prefixed for differentiation) -- **ChunkType:** `"wiki_page"` (defined in `internal/types/chunk.go`) -- **Content:** `page.Content` (full markdown) -- **Title:** `page.Title` -- **Metadata:** Includes `page.Slug`, `page.PageType`, `page.SourceRefs` -- **Embedding:** Created via standard embedding pipeline - -**Note:** Actual creation/update of wiki chunks happens during the ingest pipeline via the standard chunk indexing service, not shown explicitly in wiki_page.go. The `CreatePage()` and `UpdatePage()` methods likely trigger chunk sync via hooks or post-update callbacks (to be confirmed in chunk.go or repository layer). - -### Retrieval Boosting: WikiBoost Plugin - -**Location:** `internal/application/service/chat_pipeline/wiki_boost.go` - -**Activation:** Runs in `CHUNK_RERANK` phase (after initial retrieval and reranking) - -**Algorithm:** - -```go -const wikiBoostFactor = 1.3 - -1. Check if any chunks have ChunkType == "wiki_page" - ├─ Fast path: Return early if none found - └─ Reason: Avoid KB service call on every turn - -2. Verify at least one search target is a wiki KB - ├─ Confirm KB.IsWikiEnabled() - └─ Skip if none are wiki KBs - -3. For each wiki_page chunk in results: - ├─ Multiply score by 1.3x - └─ Boost indicates better quality/relevance - -4. Re-sort results by score (stable sort) - └─ Wiki pages move up in ranking -``` - -**Rationale:** Wiki pages contain LLM-synthesized, cross-referenced knowledge that is typically more coherent than raw document chunks, so they deserve higher retrieval score. - ---- - -## Agent Integration - -### Wiki Read & Write Tools - -**Location:** `internal/agent/tools/wiki_*.go` - -#### wiki_read_page.go - -Retrieves a wiki page for agent inspection: - -``` -Input: slug (e.g., "entity/openai") -Output: {title, content, type, summary, aliases, in_links, out_links} -Use Case: Agent wants to review/understand a page before editing -``` - -#### wiki_write_page.go - -Creates or overwrites a wiki page: - -**Location:** Lines 23-167 - -``` -Input: { - slug, // URL-friendly identifier - title, // Human-readable title - summary, // One-line summary - content, // FULL markdown (no placeholders) - page_type, // "synthesis", "comparison", "entity", etc. - aliases, // Alternative names (optional) - source_refs // Knowledge IDs that contributed (optional) -} - -Flow: -1. Validate KB has wiki enabled -2. Check if page exists (create vs update decision) -3. Resolve source_refs: UUIDs → full format "id|title" -4. Call wikiService.CreatePage() or UpdatePage() - ├─ Parses outbound links from content - └─ Updates bidirectional references -5. Inject cross-links (auto-link mentions) -6. Rebuild index page -7. Return: action, slug, title, page_type, summary -``` - -#### wiki_read_source_doc.go - -Retrieve a source document that contributed to wiki pages: - -``` -Input: knowledge_id (UUID of source document) -Output: {title, content, summary} -Use Case: Agent wants to verify facts against original source -``` - -#### wiki_delete_page.go - -Soft-delete a wiki page: - -``` -Input: slug -Flow: -1. Validate ownership -2. Call wikiService.DeletePage() - ├─ Remove inbound link references - ├─ Delete page record (soft delete) - └─ Remove associated chunks -3. Rebuild index page -4. Rebuild links (if needed) -``` - -#### wiki_update_issue.go / wiki_read_issue.go / wiki_flag_issue.go - -Issue management for flagging/tracking wiki health problems. - -#### wiki_rename_page.go - -Rename a page slug and update all references: - -``` -Input: old_slug, new_slug -Flow: -1. Get existing page -2. Update slug -3. Update outbound references in other pages -4. Create redirect (if needed) -``` - ---- - -## API Endpoints - -**Base Path:** `/api/v1/knowledgebase/{kb_id}/wiki` - -**Registered in:** `internal/router/router.go` line 839 - -### Core Endpoints - -| Method | Path | Handler | Purpose | -|--------|------|---------|---------| -| `GET` | `/pages` | ListPages | Paginated list with filtering | -| `POST` | `/pages` | CreatePage | Create new wiki page | -| `GET` | `/pages/{slug}` | GetPage | Retrieve single page | -| `PUT` | `/pages/{slug}` | UpdatePage | Update page content | -| `DELETE` | `/pages/{slug}` | DeletePage | Soft-delete page | -| `GET` | `/index` | GetIndex | Get index page (auto-create if missing) | -| `GET` | `/log` | GetLog | Get operation log (auto-create if missing) | -| `GET` | `/graph` | GetGraph | Retrieve link graph for visualization | -| `GET` | `/stats` | GetStats | Get aggregate statistics | -| `POST` | `/rebuild-links` | RebuildLinks | Force rebuild of all link references | -| `POST` | `/inject-cross-links` | InjectCrossLinks | Auto-link mentions in specified pages | -| `POST` | `/rebuild-index` | RebuildIndexPage | Regenerate index page | -| `GET` | `/search` | SearchPages | Full-text search | -| `GET` | `/lint` | RunLint | Health check and issue detection | -| `POST` | `/issues` | CreateIssue | Flag an issue on a page | -| `GET` | `/issues` | ListIssues | Retrieve issues (with optional filtering) | -| `PATCH` | `/issues/{id}` | UpdateIssueStatus | Mark issue resolved/ignored | - -**Handler Location:** `internal/handler/wiki_page.go` - -### Request/Response Examples - -**Create Page:** -```json -POST /api/v1/knowledgebase/kb-123/wiki/pages -{ - "slug": "entity/acme-corp", - "title": "ACME Corporation", - "summary": "A fictional corporation in roadrunner cartoons", - "content": "# ACME Corporation\n\nAcme Corporation is a fictional...", - "page_type": "entity", - "aliases": ["Acme", "ACME Inc"], - "source_refs": ["doc-uuid-1", "doc-uuid-2"] -} - -Response: -{ - "id": "page-uuid", - "slug": "entity/acme-corp", - "title": "ACME Corporation", - "status": "published", - "in_links": [], - "out_links": [], - "created_at": "2026-04-20T10:30:00Z", - "updated_at": "2026-04-20T10:30:00Z" -} -``` - -**List Pages:** -```json -GET /api/v1/knowledgebase/kb-123/wiki/pages?page=1&page_size=20&page_type=entity&status=published - -Response: -{ - "pages": [...], - "total": 150, - "page": 1, - "page_size": 20, - "total_pages": 8 -} -``` - -**Get Graph:** -```json -GET /api/v1/knowledgebase/kb-123/wiki/graph - -Response: -{ - "nodes": [ - {"slug": "entity/acme-corp", "title": "ACME Corp", "page_type": "entity", "link_count": 5}, - ... - ], - "edges": [ - {"source": "entity/acme-corp", "target": "concept/destruction"}, - ... - ] -} -``` - -**Get Stats:** -```json -GET /api/v1/knowledgebase/kb-123/wiki/stats - -Response: -{ - "total_pages": 150, - "pages_by_type": { - "summary": 20, - "entity": 60, - "concept": 70 - }, - "total_links": 300, - "orphan_count": 5, - "recent_updates": [...], - "pending_tasks": 3, - "pending_issues": 2, - "is_active": false -} -``` - ---- - -## Configuration & Settings - -### KB-Level WikiConfig - -**Stored in:** `knowledge_bases.wiki_config` (JSON column) - -**Frontend Form:** `frontend/src/api/knowledge-base/index.ts` - -**Fields:** - -```typescript -interface WikiConfig { - enabled: boolean; // Enable/disable wiki - auto_ingest: boolean; // Auto-generate from documents - synthesis_model_id: string; // LLM model for generation - max_pages_per_ingest: number; // Batch size limit (0 = unlimited) -} -``` - -**API Update:** -``` -PUT /api/v1/knowledgebase/{id} -{ - "wiki_config": { - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4-turbo", - "max_pages_per_ingest": 0 - } -} -``` - -### Agent Configuration - -**Related Fields in AgentConfig:** - -```go -type AgentConfig struct { - KnowledgeBases []string // KB IDs accessible to agent - KnowledgeIDs []string // Individual document IDs - RetrieveKBOnlyWhenMentioned bool // Only search when @ mentioned - RetainRetrievalHistory bool // Keep wiki_read_page results across turns -} -``` - -Agents access wiki pages through: -1. Knowledge search (if KB in `KnowledgeBases` list) -2. Direct wiki_read_page tool (if tool enabled) -3. Synthesis/comparison creation via wiki_write_page tool - ---- - -## Error Handling & Observability - -### Logging - -**Log Levels Used:** - -- `Infof()`: Normal operations (page created, docs ingested, etc.) -- `Warnf()`: Recoverable issues (failed link update, missing chunks, etc.) -- `Errorf()`: Failures in critical paths (LLM failures, database errors, etc.) - -**Key Log Events:** - -``` -"wiki ingest: batch processing %d ops for KB %s" -"wiki ingest: processing document '%s' (%s)" -"wiki ingest: failed to map knowledge %s: %v" -"wiki ingest: mapped knowledge %s title=%q generated_updates=%d" -"wiki ingest: batch completed for KB %s, %d ops, %d pages affected" -"wiki ingest stats: kb=%s ... pending_ops=%d ops(ingest=%d,retract=%d) ingest(success=%d,failed=%d)" -``` - -### Asynq Task Telemetry - -**Deferred logging in ProcessWikiIngest() (lines 67-91):** - -Captures comprehensive stats in a single log line on task completion: - -```go -defer func() { - logger.Infof(ctx, - "wiki ingest stats: kb=%s tenant=%d retry=%d/%d status=%s elapsed=%s mode=%s "+ - "lock_acquired=%v pending_ops=%d ops(ingest=%d,retract=%d) ingest(success=%d,failed=%d) "+ - "retract_handled=%d pages(total=%d) index(rebuild_attempted=%v,rebuild_succeeded=%v) "+ - "followup=%v preview=%s", - payload.KnowledgeBaseID, payload.TenantID, retryCount, maxRetry, exitStatus, - time.Since(taskStartedAt), mode, lockAcquired, pendingOpsCount, ingestOps, retractOps, - ingestSucceeded, ingestFailed, retractHandled, totalPagesAffected, - indexRebuildAttempted, indexRebuildSucceeded, followUpScheduled, previewStringSlice(docPreview, 6), - ) -}() -``` - -**Status Values:** -- `"success"`: Normal completion -- `"invalid_payload"`: Malformed task data -- `"active_lock_conflict"`: Another batch in progress (retry) -- `"kb_not_wiki_enabled"`: KB doesn't have wiki enabled -- `"auto_ingest_disabled"`: AutoIngest flag is off -- `"missing_synthesis_model"`: No LLM model configured -- `"no_pending_ops"`: Empty pending list - -### Error Handling Patterns - -**Silent Failures (log but continue):** -- Failed link updates: Continue with other links -- Failed chunk deletion: Log warning but don't fail page delete -- Failed cross-link injection: Log warning but page is still complete - -**Batch Partial Failures:** -- If one document fails in MAP phase: Continue with others (don't fail whole batch) -- Mark individual failures in stats but complete remaining work - -**Retry Logic:** -- Asynq MaxRetry: 10 (high to outlast 5-minute active lock TTL) -- Timeout: 60 minutes per task -- Queue: "low" priority (non-critical background work) - ---- - -## Wiki Linting System - -**Location:** `internal/application/service/wiki_lint.go` - -### Issue Types Detected - -| Type | Severity | AutoFixable | Description | -|------|----------|-------------|-------------| -| `orphan_page` | Warning | No | Page has no inbound links | -| `broken_link` | Error | Yes | Outbound link points to deleted page | -| `stale_ref` | Warning | No | Page references deleted document | -| `missing_cross_ref` | Info | No | Page mentions entity but doesn't link | -| `empty_content` | Warning | Yes | Page content < 50 characters | -| `duplicate_slug` | Error | No | Slug collision (shouldn't occur) | - -### Health Score Calculation - -``` -Base: 100 -Deductions: -- Each orphan: -0.5 points (if orphan% > 50: -25) -- Each broken link: -2 points -- Each stale ref: -1 point -``` - ---- - -## Performance Considerations - -### Optimization Techniques - -1. **Debouncing:** 30-second window prevents immediate task scheduling -2. **Batching:** Up to 5 docs per ingest task (wikiMaxDocsPerBatch) -3. **Parallel Processing:** - - MAP phase: 10 concurrent goroutines - - REDUCE phase: 10 concurrent goroutines -4. **Deduplication:** Single LLM call for entities + concepts (not separate) -5. **Pre-loading:** All pages fetched once at batch start (WikiBatchContext) -6. **Fast Path:** Wiki boost skips work if no wiki_page chunks exist -7. **Content Truncation:** Wiki generation limited to 32KB per document - -### Scaling Considerations - -- **Redis pending list:** 24-hour TTL prevents unbounded growth -- **Active lock:** 5-minute TTL with 2-minute refresh ensures cleanup -- **Task timeout:** 60 minutes prevents hanging tasks -- **Concurrent batches:** Lock prevents parallel processing for same KB (sequential per KB) - ---- - -## Common Workflows - -### Uploading a Document with Wiki Enabled - -``` -1. User uploads document to knowledge base -2. Document ingestion creates chunks via ChunkService -3. If WikiConfig.AutoIngest = true: - ├─ EnqueueWikiIngest() called - ├─ Knowledge ID added to redis pending list - └─ Asynq task scheduled (30s delay) -4. After 30s (or when batch fills): - ├─ ProcessWikiIngest() executes - ├─ MAP phase: Extract entities/concepts from document - ├─ REDUCE phase: Merge into wiki pages, call LLM for synthesis - ├─ Rebuild index page - ├─ Inject cross-links - └─ Publish draft pages -5. Wiki pages now appear in search results (with boost) -6. User can browse via /wiki/pages, /wiki/graph, /wiki/stats -``` - -### Agent Creating a Synthesis Page - -``` -1. Agent calls wiki_write_page tool - ├─ slug: "synthesis/multi-document-analysis" - ├─ title: "Comparison of Approaches" - ├─ content: Full markdown with [[wiki-links]] - └─ page_type: "synthesis" -2. Tool calls wikiService.CreatePage() - ├─ Parses outbound links from content - ├─ Creates bidirectional references - └─ Page created as "published" (not draft) -3. Tool calls InjectCrossLinks() - └─ Auto-links mentions in other pages -4. Tool calls RebuildIndexPage() - └─ Adds synthesis page to index -5. Result returned to agent -``` - -### Viewing Wiki Visualization - -``` -1. GET /api/v1/knowledgebase/{id}/wiki/graph -2. Response includes nodes (pages) and edges (links) -3. Frontend renders D3/Force graph -4. Nodes sized by link count -5. Edges directed (arrow indicates "links to") -6. User can click nodes to view page content -``` - ---- - -## Future Enhancements (Design Patterns) - -### Potential Improvements - -1. **Incremental indexing:** Only re-index changed pages instead of full batch -2. **Distributed locking:** Use Redlock for multi-node safety (if scaling horizontally) -3. **Caching:** Cache graph data with TTL to avoid rebuilding on every request -4. **Async search indexing:** Defer full-text index updates to background job -5. **Wiki versioning:** Maintain page version history with diffs -6. **Conflict resolution:** Smarter handling of concurrent edits -7. **Custom LLM prompts:** Allow per-KB customization of generation prompts -8. **Link scoring:** Weight links by relevance instead of binary presence -9. **Smart archiving:** Auto-archive orphaned pages after N days -10. **Wiki search autocomplete:** Suggest page slugs/titles during creation - ---- - -## Appendix: Key Files Quick Reference - -| File | Lines | Purpose | -|------|-------|---------| -| `types/wiki_page.go` | 43-84 | WikiPage entity definition | -| `types/wiki_page.go` | 94-103 | WikiConfig structure | -| `service/wiki_page.go` | 45-78 | CreatePage method | -| `service/wiki_page.go` | 81-111 | UpdatePage method | -| `service/wiki_ingest.go` | 118-177 | EnqueueWikiIngest function | -| `service/wiki_ingest_batch.go` | 46-362 | ProcessWikiIngest handler | -| `service/wiki_ingest_batch.go` | 364-532 | mapOneDocument extraction | -| `service/wiki_ingest_batch.go` | 589-796 | reduceSlugUpdates synthesis | -| `service/wiki_linkify.go` | 35-82 | linkifyContent algorithm | -| `service/wiki_lint.go` | 74-250+ | RunLint health check | -| `service/chat_pipeline/wiki_boost.go` | 1-98 | Retrieval boosting | -| `agent/tools/wiki_write_page.go` | 23-167 | Create/update pages | -| `handler/wiki_page.go` | — | HTTP endpoints | -| `router/router.go` | 839 | Route registration | - ---- - -**End of Document** - -Generated: 2026-04-20 | Based on codebase commit: latest diff --git a/WIKI_SYSTEM_SUMMARY.md b/WIKI_SYSTEM_SUMMARY.md deleted file mode 100644 index 13f47b76..00000000 --- a/WIKI_SYSTEM_SUMMARY.md +++ /dev/null @@ -1,469 +0,0 @@ -# WeKnora Wiki System - Executive Summary - -**Document:** WIKI_SYSTEM_SUMMARY.md -**Date:** 2026-04-20 -**Status:** Complete Technical Analysis - ---- - -## What is the Wiki System? - -WeKnora's Wiki is a **document synthesis and knowledge graph** feature for document-type knowledge bases. It: - -- **Automatically extracts entities and concepts** from uploaded documents using LLM -- **Generates LLM-synthesized wiki pages** that aggregate information across documents -- **Maintains bidirectional link graphs** showing relationships between concepts -- **Provides visualization and statistics** for knowledge exploration -- **Boosts retrieval** of wiki pages in search results -- **Tracks health** with linting and issue detection - -**Critical:** Wiki is **NOT a KB type** — it's a feature flag (`WikiConfig.Enabled`) on document-type KBs. - ---- - -## Quick Architecture Map - -``` -Document Upload (KB with wiki enabled) - ↓ - ChunkService (creates chunks) - ↓ - EnqueueWikiIngest() → Redis pending list + Asynq task (30s delay) - ↓ - ProcessWikiIngest (batch handler) ─────┬─ MAP Phase (extract entities/concepts) - ├─ 10 parallel goroutines │ - ├─ LLM calls for each document │ - └─ Accumulate updates │ - ├─ REDUCE Phase (merge & synthesize) - ├─ 10 parallel goroutines - ├─ LLM calls for page synthesis - └─ Save to DB - ↓ - Post-Processing - ├─ Append log entries - ├─ Rebuild index page (LLM-updated intro) - ├─ Clean dead links - ├─ Inject cross-links (pure text matching) - ├─ Publish draft pages - └─ Schedule follow-up if more pending - ↓ - Wiki pages now indexed as chunks (ChunkType="wiki_page") - ↓ - Search retrieval → WikiBoost plugin (1.3x score multiplier) - ↓ - Agents can read/write wiki pages via tools -``` - ---- - -## Core Data Structures - -### WikiPage (Database Entity) - -```go -type WikiPage struct { - ID string // UUID - KnowledgeBaseID string // Parent KB - Slug string // URL-friendly: "entity/acme-corp" - Title string // Human title - PageType string // summary|entity|concept|index|log|synthesis|comparison - Status string // draft|published|archived - Content string // Full markdown - Summary string // One-line for index - Aliases []string // Alternative names - SourceRefs []string // Knowledge IDs: "id|title" - InLinks []string // Pages linking to this - OutLinks []string // Pages this links to - Version int // Optimistic locking -} -``` - -### WikiConfig (Feature Configuration) - -```go -type WikiConfig struct { - Enabled bool // Feature flag - AutoIngest bool // Auto-generate from uploads - SynthesisModelID string // LLM model (defaults to KB.SummaryModelID) - MaxPagesPerIngest int // Batch size limit (0 = unlimited) -} -``` - ---- - -## Key Services - -### WikiPageService - -**Responsibilities:** -- CRUD operations on wiki pages -- Link parsing and bidirectional reference management -- Index/log page creation and updates -- Graph generation for visualization -- Statistics aggregation -- Cross-link injection (mentions → auto-links) - -**Key Methods:** -- `CreatePage()`, `UpdatePage()`, `DeletePage()` -- `GetPageBySlug()`, `ListPages()`, `SearchPages()` -- `GetIndex()`, `GetLog()` -- `GetGraph()` (for visualization) -- `GetStats()` (aggregate statistics) -- `RebuildLinks()` (full rebuild) -- `InjectCrossLinks()` (auto-link mentions) - -### WikiIngestService - -**Responsibilities:** -- Orchestrate async wiki generation from documents -- Manage Redis pending queue and distributed locks -- Coordinate MAP-REDUCE batch processing -- Call LLM prompts for extraction and synthesis -- Handle retract operations (document deletion) -- Maintain operation log - -**Key Methods:** -- `EnqueueWikiIngest()` (queue a document) -- `EnqueueWikiRetract()` (queue a deletion) -- `ProcessWikiIngest()` (main batch handler) -- `mapOneDocument()` (extract entities/concepts) -- `reduceSlugUpdates()` (merge and synthesize) - ---- - -## Async Pipeline Details - -### Debouncing Mechanism - -``` -Time Action -───────────────────────────────────── -0s doc1 uploaded → RPush + Enqueue(delay=30s) -5s doc2 uploaded → RPush + Enqueue(delay=30s) -10s doc3 uploaded → RPush + Enqueue(delay=30s) -30s Task 1 fires → Drains [doc1,doc2,doc3] → Process all -35s Task 2 fires → Drains [] → No-op return -40s Task 3 fires → Drains [] → No-op return -``` - -**Benefit:** Natural batching without explicit deduplication logic. - -### MAP Phase - -Parallel extraction (10 goroutines max): -- For each document: Extract entities & concepts from chunks -- Call LLM: `WikiKnowledgeExtractPrompt` -- Result: List of SlugUpdate operations - -**Per Document:** -- Read chunks from ChunkRepository -- Reconstruct content (truncated to 32KB) -- Call LLM extraction (single call for both entities + concepts) -- Deduplicate against existing pages (single LLM call for batch) -- Generate summary page -- Identify stale pages (from previous ingest) - -### REDUCE Phase - -Parallel merging (10 goroutines max): -- For each affected slug: Apply all accumulated updates -- Call LLM: `WikiPageModifyPrompt` (for entity/concept synthesis) -- Save page to DB - -**Per Slug:** -- Separate updates into: additions, retracts, summary -- Build LLM prompt with context (existing content, new info, remaining sources) -- Call LLM to synthesize merged content -- Update page record - -### Post-Processing - -``` -1. Append log entries (one per operation) -2. Rebuild index page (LLM updates intro, code rebuilds directory) -3. Clean dead links (remove [[broken-links]]) -4. Inject cross-links (auto-link mentions of other pages) -5. Publish draft pages (transition to published) -6. Trim processed items from Redis pending list -7. Schedule follow-up if more items remain -``` - ---- - -## Cross-Link Injection - -**Purpose:** Auto-detect mentions of existing wiki page titles and wrap with `[[wiki-links]]`. - -**Implementation:** Pure text processing (no LLM cost) - -**Algorithm:** -1. Sort refs by matchText length (descending) → longer strings match first -2. Compute forbidden spans → regions untouched (code blocks, existing links, etc.) -3. For each ref: - - Skip if already linked elsewhere - - Find first safe match outside forbidden spans - - Check word boundaries (for ASCII text) - - Wrap with `[[slug|matchText]]` - -**Forbidden Regions:** -- Fenced code blocks (```/~~~) -- Inline code (backticks) -- Existing wiki links -- Markdown links [text](url) -- Images ![alt](url) -- Reference-style links -- Autolinks - ---- - -## Retrieval Integration - -### ChunkType Classification - -``` -ChunkTypeWikiPage = "wiki_page" - -Used to: -1. Differentiate wiki pages from document chunks -2. Apply retrieval boost (1.3x score multiplier) -3. Filter results if needed -``` - -### WikiBoost Plugin - -**Phase:** `CHUNK_RERANK` (after initial retrieval and reranking) - -**Algorithm:** -1. Check if any chunks have `ChunkType == "wiki_page"` -2. Verify at least one search target is a wiki KB -3. Multiply wiki page scores by 1.3x -4. Re-sort results - -**Rationale:** Wiki pages are pre-synthesized and cross-referenced, making them more valuable than raw document chunks. - ---- - -## Agent Integration - -### Wiki Tools Available - -| Tool | Purpose | -|------|---------| -| `wiki_read_page` | Retrieve page content for inspection | -| `wiki_write_page` | Create or overwrite page (synthesis/comparison) | -| `wiki_delete_page` | Soft-delete page | -| `wiki_rename_page` | Rename slug and update references | -| `wiki_read_source_doc` | Verify facts against original document | -| `wiki_flag_issue` | Report problem on page | -| `wiki_read_issue` | Review flagged issues | -| `wiki_update_issue` | Mark issue resolved/ignored | - -### Common Agent Workflows - -**Creating a Synthesis Page:** -``` -1. Agent analyzes multiple documents -2. Calls wiki_write_page with: - - slug: "synthesis/..." - - page_type: "synthesis" - - content: Full markdown with [[wiki-links]] - - source_refs: Knowledge IDs of documents analyzed -3. Tool parses links from content -4. Tool calls InjectCrossLinks() (auto-link mentions) -5. Tool calls RebuildIndexPage() (add to index) -6. Page now appears in search and graph -``` - ---- - -## API Endpoints - -**Base:** `/api/v1/knowledgebase/{kb_id}/wiki` - -| Method | Path | Purpose | -|--------|------|---------| -| GET | `/pages` | List with pagination/filtering | -| POST | `/pages` | Create page | -| GET | `/pages/{slug}` | Get single page | -| PUT | `/pages/{slug}` | Update page | -| DELETE | `/pages/{slug}` | Soft-delete | -| GET | `/index` | Get index (auto-create) | -| GET | `/log` | Get log (auto-create) | -| GET | `/graph` | Link graph for visualization | -| GET | `/stats` | Aggregate statistics | -| GET | `/lint` | Health check | -| POST | `/rebuild-links` | Force rebuild | -| GET | `/search` | Full-text search | - ---- - -## Configuration - -### KB-Level Settings - -```json -{ - "enabled": true, - "auto_ingest": true, - "synthesis_model_id": "gpt-4-turbo", - "max_pages_per_ingest": 0 -} -``` - -Updated via: `PUT /api/v1/knowledgebase/{id}` with `wiki_config` field. - -### Agent Access - -```go -type AgentConfig struct { - KnowledgeBases []string // KB IDs agent can access - KnowledgeIDs []string // Individual docs - // Tools available: - // - wiki_read_page, wiki_write_page, wiki_delete_page, etc. -} -``` - ---- - -## Performance & Scaling - -### Optimization Techniques - -| Technique | Benefit | -|-----------|---------| -| **Debouncing (30s)** | Reduces task scheduling overhead | -| **Batching (5 docs)** | Amortizes LLM costs | -| **Parallel processing (10 goroutines)** | Utilizes multi-core efficiently | -| **Batch dedup (1 LLM call)** | Entities + concepts in single call | -| **Pre-loading (WikiBatchContext)** | All pages fetched once per batch | -| **Fast path (wiki boost)** | Skip work if no wiki chunks | -| **Content truncation (32KB)** | Limits LLM input size | - -### Scaling Limits - -- **Redis pending list:** 24-hour TTL (auto-cleanup) -- **Active lock:** 5-minute TTL with 2-minute refresh -- **Task timeout:** 60 minutes -- **Max retries:** 10 (outlasts lock TTL) -- **Sequential per KB:** One batch at a time per knowledge base - ---- - -## Health Monitoring - -### Linting Issues Detected - -| Issue | Severity | Fixable | -|-------|----------|---------| -| Orphan page (no inbound links) | Warning | No | -| Broken link (target deleted) | Error | Yes | -| Empty content (<50 chars) | Warning | Yes | -| Missing cross-reference (mention not linked) | Info | No | -| Stale reference (doc deleted) | Warning | No | - -### Health Score - -Base: 100 -- Each orphan (if >50%): -25 -- Each broken link: -2 -- Each stale ref: -1 - -**API:** `GET /api/v1/knowledgebase/{id}/wiki/lint` - ---- - -## Common Questions - -**Q: Is wiki a separate KB type?** -A: No. Wiki is a feature flag on document-type KBs. You enable it via `WikiConfig.Enabled`. - -**Q: What triggers wiki generation?** -A: Document upload (if `WikiConfig.AutoIngest = true`). System calls `EnqueueWikiIngest()`. - -**Q: Can I disable auto-generation?** -A: Yes. Set `AutoIngest = false`. Manual wiki_write_page tool still works. - -**Q: How is wiki content indexed?** -A: Wiki pages are converted to chunks with `ChunkType = "wiki_page"` and indexed like normal. - -**Q: How does wiki affect search results?** -A: WikiBoost plugin increases wiki page scores by 1.3x during reranking. - -**Q: Can agents create wiki pages?** -A: Yes. Use `wiki_write_page` tool. Agent decides slug, content, page type. - -**Q: What happens to wiki when I delete a document?** -A: `EnqueueWikiRetract()` is called. Pages referencing the document are updated/deleted. - -**Q: How do cross-links work?** -A: Pure text matching. System finds mentions of page titles and wraps with `[[slug|title]]`. - -**Q: What's the performance impact?** -A: Minimal. Debouncing/batching amortizes LLM costs. Boosting adds negligible overhead. - ---- - -## File Structure Overview - -``` -internal/ -├── types/ -│ ├── wiki_page.go # Data models -│ ├── chunk.go # ChunkType constants -│ └── interfaces/wiki_page.go # Service interfaces -├── application/ -│ ├── service/ -│ │ ├── wiki_page.go # WikiPageService -│ │ ├── wiki_ingest.go # EnqueueWikiIngest -│ │ ├── wiki_ingest_batch.go # ProcessWikiIngest (MAP-REDUCE) -│ │ ├── wiki_linkify.go # Cross-link injection -│ │ ├── wiki_lint.go # Health checking -│ │ ├── chat_pipeline/wiki_boost.go # Retrieval boosting -│ │ └── chunk.go # Chunk operations -│ ├── repository/ -│ │ └── wiki_page.go # Database layer -│ └── handler/ -│ └── wiki_page.go # HTTP endpoints -├── agent/ -│ ├── tools/ -│ │ ├── wiki_write_page.go # Create/update pages -│ │ ├── wiki_read_page.go # Read pages -│ │ ├── wiki_delete_page.go # Delete pages -│ │ └── ... # Other wiki tools -│ └── prompts_wiki.go # LLM prompts -└── router/router.go # Route registration -``` - ---- - -## Next Steps for Developers - -### Understanding Specific Areas - -1. **Page Creation Flow:** Read `wiki_page.go:CreatePage()` + `wiki_page.go:parseOutLinks()` -2. **Document Ingestion:** Read `wiki_ingest_batch.go:ProcessWikiIngest()` + `mapOneDocument()` -3. **Link Synthesis:** Read `wiki_ingest_batch.go:reduceSlugUpdates()` + LLM prompts -4. **Cross-linking:** Read `wiki_linkify.go:linkifyContent()` + `computeForbiddenSpans()` -5. **Retrieval Boost:** Read `chat_pipeline/wiki_boost.go` + chunk indexing flow - -### Common Modifications - -- **Change LLM prompts:** Edit `internal/agent/prompts_wiki.go` -- **Adjust batch size:** Change `wikiMaxDocsPerBatch` in `wiki_ingest.go` -- **Change boost factor:** Modify `wikiBoostFactor` in `wiki_boost.go` -- **Add issue type:** Extend `WikiLintIssueType` enum in `wiki_lint.go` -- **New agent tool:** Create `internal/agent/tools/wiki_*.go` + register - ---- - -## References - -- **Full Technical Deep Dive:** See `WIKI_SYSTEM_DEEP_DIVE.md` (948 lines) -- **Architecture Analysis:** See `KB_WIKI_ARCHITECTURE_ANALYSIS.md` (34KB) -- **File Index:** See `KB_WIKI_FILE_INDEX.md` - ---- - -**End of Summary** - -Generated: 2026-04-20 diff --git a/WIKI_TECHNICAL_ANALYSIS.md b/WIKI_TECHNICAL_ANALYSIS.md deleted file mode 100644 index c919c790..00000000 --- a/WIKI_TECHNICAL_ANALYSIS.md +++ /dev/null @@ -1,1171 +0,0 @@ -# WeKnora Wiki System: Comprehensive Technical Analysis - -**Last Updated:** April 2026 -**Scope:** WeKnora internal wiki knowledge base system with focus on architecture, patterns, and edge cases - -## Executive Summary - -The WeKnora wiki system is a sophisticated knowledge graph engine that transforms document ingestion into interlinked markdown pages. It combines: - -- **Async batch processing** with debouncing and deduplication -- **MAP-REDUCE parallel extraction** for scalable knowledge synthesis -- **Text-based cross-link injection** with sophisticated forbidden-span detection -- **Optimistic locking** for concurrent update safety -- **Bidirectional link maintenance** for graph traversal -- **Retrieval integration** via chunking and scoring plugins - -This analysis covers architectural patterns, implementation details, edge cases, and operational considerations. - ---- - -## Part 1: Architectural Overview - -### 1.1 System Context - -**Purpose:** Convert source documents into a queryable, interlinked knowledge graph that: -- Extracts entities and concepts from documents -- Synthesizes multi-document knowledge into canonical pages -- Maintains bidirectional link references for graph queries -- Injects cross-links into page content via pattern matching -- Integrates with chat pipeline for enhanced retrieval - -**Key Design Decision: Wiki as Feature Flag** - -Wiki is NOT a separate KB type. Instead: -- Wiki is a feature enabled via `WikiConfig` struct embedded in `KnowledgeBase` -- A KB can enable/disable wiki independently of KB type -- This allows wikis to coexist with traditional document-only KBs -- Enables progressive rollout and A/B testing - -```go -type WikiConfig struct { - Enabled bool // Feature flag - AutoIngest bool // Trigger on doc upload - SynthesisModelID string // LLM model for generation - MaxPagesPerIngest int // Rate limiting (0 = unlimited) -} -``` - -### 1.2 Core Data Flow - -``` -Upload Document - ↓ -Document Chunking (standard pipeline) - ↓ -EnqueueWikiIngest() → Redis List (wiki:pending:{kbID}) - ↓ -[DEBOUNCE: 30-second window] - ↓ -ProcessWikiIngest() [Async Task Handler] - ├─ Acquire Redis Lock (wiki:active:{kbID}, 5-min TTL) - ├─ MAP Phase: Extract entities/concepts from all pending docs - ├─ REDUCE Phase: Synthesize updates per slug - ├─ Post-processing: Inject links, rebuild index, update log - └─ Schedule follow-up if pending items remain - ↓ -Database Updates - ├─ Create/update WikiPage records - ├─ Update bidirectional links (InLinks/OutLinks) - └─ Version bump with optimistic locking - ↓ -Chunk Synchronization - ├─ Index each page as ChunkType="wiki_page" - ├─ Apply 1.3x score boost in retrieval (WikiBoost plugin) - └─ Integrate with existing vector/keyword search -``` - -### 1.3 Key Files and Responsibilities - -| File | Lines | Purpose | -|------|-------|---------| -| `wiki_page.go` | 628 | Core CRUD, link management, graph queries, stats | -| `wiki_ingest.go` | 1,053 | Enqueue operations, debouncing, task scheduling | -| `wiki_ingest_batch.go` | 796 | MAP-REDUCE handler, LLM calls, synthesis | -| `wiki_linkify.go` | 565 | Cross-link injection with forbidden-span detection | -| `wiki_lint.go` | 323 | Health checks, orphan detection, link validation | -| `wiki_page.go` (types) | 196 | Data models, constants, interfaces | - ---- - -## Part 2: Core Concepts and Patterns - -### 2.1 Bidirectional Link References - -**Problem:** Graph queries require knowing both "pages I link to" and "pages that link to me". - -**Solution:** Maintain dual arrays on every WikiPage: -- `OutLinks []string` — pages this page references (populated during content parsing) -- `InLinks []string` — pages that reference this page (maintained reactively) - -**Implementation:** - -```go -// When creating/updating a page with content "[[entity/acme-corp]]..." -// 1. Parse content → OutLinks = ["entity/acme-corp"] -// 2. For each target in OutLinks: -// - Fetch target page -// - Add source slug to target.InLinks -// - UpdateMeta() → no version bump - -// When deleting a page: -// 1. For each target in OutLinks: -// - Remove source slug from target.InLinks -// - UpdateMeta() → maintains referential consistency -``` - -**Correctness Mechanism:** `RebuildLinks()` operation -- Full refresh of all bidirectional links -- Useful after bugs or batch migrations -- Iterates all pages, clears InLinks, rebuilds from OutLinks - -**Edge Cases Handled:** -- Circular references (A links to B, B links to A) ✓ -- Self-links (A links to A) — explicitly prevented -- Dangling links (A links to nonexistent B) — detected by linter, broken-link issue - -### 2.2 Optimistic Locking with Version Numbers - -**Problem:** Concurrent updates to the same page could result in lost writes. - -**Solution:** Version numbers with conditional update check: - -```go -// Repository.Update() -result := db.Model(page). - Where("id = ? AND version = ?", page.ID, expectedVersion). - Updates(page) // Increments version to expectedVersion+1 - -if result.RowsAffected == 0 { - // Conflict detected — return ErrWikiPageConflict - // Caller must retry with fresh version -} -``` - -**Metadata vs. Content Updates:** -- `Update()` → increments version (user-visible content change) -- `UpdateMeta()` → does NOT increment version (internal link bookkeeping) - -**Design Rationale:** -- Content changes visible to users bump the version -- Link maintenance is transparent, doesn't count as a change -- Prevents version thrashing from routine background operations - -### 2.3 Async Batch Processing with Debouncing - -**Problem:** Many small documents might trigger expensive LLM calls individually. - -**Solution:** 30-second debounce window + natural batching: - -``` -T=0s: Document A uploaded → enqueue → schedule task @ T=30s -T=5s: Document B uploaded → enqueue → reschedule task @ T=35s -T=10s: Document C uploaded → enqueue → reschedule task @ T=40s -T=40s: Task fires with [A, B, C] batched together -``` - -**Implementation:** - -```go -// wiki_ingest.go: EnqueueWikiIngest() -// 1. Create pending op with knowledge ID + ingest/retract flag -// 2. Push to Redis list: wiki:pending:{kbID} -// 3. Schedule asynq task with 30s delay (default) -// 4. If task already scheduled, asynq updates its ETA - -// ProcessWikiIngest() [async handler] -// 1. Acquire Redis lock wiki:active:{kbID} (5-min TTL + refresh goroutine) -// 2. Peek all pending items (limit: 5 per batch by default) -// 3. Deduplicate by knowledge_id (keep last op for each) -// 4. MAP phase: extract from 10 parallel goroutines -// 5. REDUCE phase: synthesize in 10 parallel goroutines -// 6. If items remain: schedule follow-up task -``` - -**Constants:** -- `wikiIngestDelay` = 30 seconds (debounce window) -- `wikiMaxDocsPerBatch` = 5 documents per batch -- `maxContentForWiki` = 32 KB max content size per document -- `wikiPendingTTL` = 24 hours (pending operations auto-expire) - -### 2.4 MAP-REDUCE Pattern for Knowledge Extraction - -**Problem:** How to efficiently extract entities/concepts from multiple documents and synthesize cross-document knowledge? - -**Solution:** Two-phase parallel processing: - -#### MAP Phase (Document-Level Extraction) - -``` -For each pending document: - 1. Fetch document chunks (full content via knowledge service) - 2. Call LLM WikiKnowledgeExtractPrompt → {entities[], concepts[]} - 3. For each extracted item: - - Check if slug already exists in KB - - If exists and being updated: include in "additions" list - - If new: create new slug - 4. Generate slug/display name for summary page - 5. Accumulate all updates in []SlugUpdate (per document) - 6. Run in parallel (10 goroutines by default) -``` - -**Output:** `map[slug][]SlugUpdate` — accumulated updates keyed by target slug - -#### REDUCE Phase (Cross-Document Synthesis) - -``` -For each affected slug: - 1. Fetch existing page content (if exists) - 2. Group all accumulated updates: - - additions: new info from multiple documents - - retractions: deletions from removed documents - - existing sources: sources NOT being deleted - 3. Call LLM WikiPageModifyPrompt: - - Input: existing page + new info + info to remove - - Output: updated page content + new summary - 4. Increment version, update timestamps - 5. Run in parallel (10 goroutines by default) -``` - -**Deduplication Strategy:** - -``` -If Document A extracted [entity: "Acme Corp", slug: "entity/acme-corp"] -And Document B extracts [entity: "Acme Corp", slug: "entity/acme-corp"] - → Both map to the same page - → Only one REDUCE operation for this slug - → Both doc IDs end up in SourceRefs for that page -``` - -**LLM Conflict Detection:** - -WikiPageModifyPrompt includes: -``` -"CRITICAL CONFLICT CHECK: First verify that the -describes the EXACT SAME core entity/concept as this page. -If the new info clearly belongs to a DIFFERENT but related -entity, you MUST REJECT that part." -``` - -This prevents LLM from merging "Hunyuan Model" into "Qwen3 Model" page. - -### 2.5 Cross-Link Injection with Forbidden Spans - -**Problem:** Auto-linking all mentions of entity names creates false matches (e.g., "AI" inside "TRAINING") and overwrites existing structure. - -**Solution:** Sophisticated pattern matching with forbidden-zone detection: - -```go -// linkifyContent(content, refs, selfSlug) -// 1. Sort refs by matchText length (longer names first) -// → prevents "北京" from matching inside "北京邮电大学" -// 2. Compute forbidden spans: -// - Fenced code blocks (``` or ~~~) -// - Inline code (backtick-delimited) -// - Wiki links [[...]] -// - Markdown links [text](url) -// - Images ![alt](url) -// - Reference-style links [text][label] -// - Reference definitions [label]: url -// - Autolinks -// 3. For each ref: -// - Find first safe match (outside forbidden zones) -// - If ASCII-letter needle: require word boundaries -// - Skip if slug already used (first-match-only) -// - Skip if self-slug -// - Inject [[slug|matchText]] -// - Shift forbidden spans to track byte offsets -``` - -**Word Boundary Rules:** - -- ASCII-letter needles (A-Z, a-z, 0-9, _) require boundaries -- Non-ASCII (CJK, Arabic, etc.) treated as inherent boundaries -- Example: - ``` - "TRAINING" → NO match for "AI" (inside word) - "AI is cool" → MATCHES "AI" (standalone) - "北京邮电大学" → MATCHES "北京" at start (CJK boundary) - ``` - -**First-Match-Only Semantics:** - -Each slug links exactly once per page. After first injection: -- Move forbidden zone marker past the new link -- Track slug in "used" set -- Skip if same slug appears again - -**Idempotence Guarantee:** - -Running linkifyContent twice on same content: -```go -content1, changed1 := linkifyContent(input, refs, "self") // changed1 = true -content2, changed2 := linkifyContent(content1, refs, "self") // changed2 = false -// content1 == content2 (no double-wrapping) -``` - -Test case confirms: -```go -once, _ := linkifyContent(input, refs, "") -twice, changed := linkifyContent(once, refs, "") -if changed { - t.Fatalf("second run should be a no-op") -} -``` - ---- - -## Part 3: Detailed Implementation Patterns - -### 3.1 Repository Layer: Optimistic Locking - -**Methods:** - -| Method | Behavior | Version Bump | -|--------|----------|--------------| -| `Create()` | INSERT new page | No (caller sets) | -| `Update()` | Conditional update WHERE version=expected | YES (+1) | -| `UpdateMeta()` | Update only link/status/source_refs fields | NO | -| `Delete()` | Soft delete (set DeletedAt) | No | -| `GetByID()` | SELECT by ID | N/A | -| `GetBySlug()` | SELECT by (kbID, slug) | N/A | -| `List()` | Paginated SELECT with filters | N/A | -| `ListAll()` | All pages in KB | N/A | -| `ListByType()` | All pages of type X | N/A | -| `CountByType()` | Pages per type | N/A | -| `CountOrphans()` | Pages with len(InLinks)==0 | N/A | -| `Search()` | Full-text + alias search | N/A | - -**Query Details for List():** - -```go -// PostgreSQL full-text search: -WHERE (to_tsvector('simple', coalesce(title, '') || ' ' || - coalesce(content, '')) @@ plainto_tsquery('simple', ?) - OR aliases::text ILIKE ?) -// Matches title, content, and aliases -``` - -**GetBySlug Uniqueness:** -```go -WHERE knowledge_base_id = ? AND slug = ? -// Slug must be unique per KB (enforced by unique index) -``` - -### 3.2 Service Layer: Multi-Step Operations - -#### CreatePage Flow - -```go -func (s *wikiPageService) CreatePage(ctx context.Context, page *WikiPage) (*WikiPage, error) { - // 1. Validation - if page.Slug == "" { return nil, "slug required" } - if page.KnowledgeBaseID == "" { return nil, "kb_id required" } - - // 2. Parse outbound links from content - page.OutLinks = s.parseOutLinks(page.Content) - - // 3. Timestamps - now := time.Now() - page.CreatedAt = now - page.UpdatedAt = now - - // 4. Repository insert - if err := s.repo.Create(ctx, page); err != nil { - return nil, err // Duplicate slug will fail here - } - - // 5. Update inbound links on targets (async, fire-and-forget) - s.updateInLinks(ctx, page.KnowledgeBaseID, page.Slug, page.OutLinks) - - return page, nil -} -``` - -#### UpdatePage Flow - -```go -func (s *wikiPageService) UpdatePage(ctx context.Context, page *WikiPage) (*WikiPage, error) { - // 1. Fetch existing to get old links + version - existing, err := s.repo.GetBySlug(ctx, page.KnowledgeBaseID, page.Slug) - - // 2. Save old OutLinks for cleanup - oldOutLinks := existing.OutLinks - - // 3. Update fields (caller provides new values) - existing.Title = page.Title - existing.Content = page.Content - existing.Summary = page.Summary - // ... etc - - // 4. Re-parse links from new content - existing.OutLinks = s.parseOutLinks(existing.Content) - existing.UpdatedAt = time.Now() - - // 5. Optimistic lock update (increments version) - if err := s.repo.Update(ctx, existing); err != nil { - return nil, err - // If conflict: caller must retry with fresh version - } - - // 6. Update inbound links: remove old, add new - s.removeInLinks(ctx, existing.KnowledgeBaseID, existing.Slug, oldOutLinks) - s.updateInLinks(ctx, existing.KnowledgeBaseID, existing.Slug, existing.OutLinks) - - return existing, nil -} -``` - -#### UpdatePageMeta Flow - -```go -func (s *wikiPageService) UpdatePageMeta(ctx context.Context, page *WikiPage) error { - // Fire-and-forget metadata update - // Used for: link maintenance, status changes, source refs - // NO version bump - page.UpdatedAt = time.Now() - return s.repo.UpdateMeta(ctx, page) -} -``` - -### 3.3 Async Pipeline: WikiIngestService - -**Enqueue Operation:** - -```go -func (s *WikiIngestService) EnqueueWikiIngest( - ctx context.Context, - kbID string, - knowledgeID string, - title string, -) error { - // 1. Validate KB has wiki enabled - kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID) - if !kb.IsWikiEnabled() { return "wiki not enabled" } - - // 2. Create pending operation - op := WikiPendingOp{ - KnowledgeID: knowledgeID, - Title: title, - Type: "ingest", // or "retract" - EnqueuedAt: time.Now(), - } - - // 3. Push to Redis list - redisKey := fmt.Sprintf("wiki:pending:%s", kbID) - s.redisClient.RPush(ctx, redisKey, json.Marshal(op)) - - // 4. Schedule async task (30s delay, auto-rescheduled if already queued) - payload := WikiIngestPayload{KnowledgeBaseID: kbID} - task, err := asynq.NewTask("wiki:ingest", payload.Marshal()) - opts := []asynq.Option{ - asynq.ProcessIn(30 * time.Second), - asynq.Queue("wiki"), - } - s.taskClient.Enqueue(task, opts...) - - return nil -} -``` - -**Batch Processing:** - -```go -func ProcessWikiIngest(task *asynq.Task) error { - // 1. Parse payload - var payload WikiIngestPayload - json.Unmarshal(task.Payload(), &payload) - kbID := payload.KnowledgeBaseID - - // 2. Acquire Redis lock (wiki:active:{kbID}) - lock := &redis.StatusCmd{} - lock, err := redisClient.SetNX( - ctx, - fmt.Sprintf("wiki:active:%s", kbID), - "1", - 5*time.Minute, - ) - if lock.Val() == "" { - // Already running, reschedule - return asynq.SkipRetry // Task handler will retry - } - - // 3. Start refresh goroutine (extend lock every 2 min) - go func() { - ticker := time.NewTicker(2 * time.Minute) - for range ticker.C { - redisClient.Expire(ctx, lockKey, 5*time.Minute) - } - }() - - // 4. Peek pending items (dedup by knowledgeID) - pendingOps := peekPendingList(redisClient, kbID, 5) - - // 5. MAP phase (parallel extraction) - var wg sync.WaitGroup - resultChan := make(chan SlugUpdate) - for _, op := range pendingOps { - wg.Add(1) - go func(op WikiPendingOp) { - defer wg.Done() - updates := mapOneDocument(ctx, op, wikiService) - for _, u := range updates { - resultChan <- u - } - }(op) - } - wg.Wait() - close(resultChan) - - // 6. Group updates by slug - slugUpdates := make(map[string][]SlugUpdate) - for u := range resultChan { - slugUpdates[u.Slug] = append(slugUpdates[u.Slug], u) - } - - // 7. REDUCE phase (parallel synthesis) - for slug, updates := range slugUpdates { - wg.Add(1) - go func(slug string, updates []SlugUpdate) { - defer wg.Done() - reduceSlugUpdates(ctx, kbID, slug, updates, wikiService) - }(slug, updates) - } - wg.Wait() - - // 8. Post-processing - appendLogEntry(ctx, kbID, ...) // Update log page - rebuildIndexPage(ctx, kbID, ...) // Regenerate index - injectCrossLinks(ctx, kbID, changedSlugs) // Auto-link - - // 9. Cleanup & follow-up - trimPendingList(redisClient, kbID, len(pendingOps)) - - // 10. If items remain, schedule follow-up - if remaining := redisClient.LLen(ctx, fmt.Sprintf("wiki:pending:%s", kbID)); remaining > 0 { - // Reschedule with no delay (already running) - task, _ := asynq.NewTask("wiki:ingest", payload.Marshal()) - taskClient.Enqueue(task) - } - - // 11. Release lock - redisClient.Del(ctx, fmt.Sprintf("wiki:active:%s", kbID)) - - return nil -} -``` - -### 3.4 Linting and Health Monitoring - -**WikiLintService Checks:** - -1. **Orphan Pages** (warning severity) - - Pages with `len(InLinks) == 0` - - Excluded: index, log pages - - Not auto-fixable - -2. **Broken Links** (error severity) - - OutLink reference to nonexistent page - - Auto-fixable: `[[broken]]` → `broken` (plain text) - -3. **Empty Content** (warning severity) - - Page content < 50 characters - - Auto-fixable: archive the page - -4. **Missing Cross-References** (info severity) - - Entity/concept name mentioned but not linked - - Detects: `Contains(page.Content, entity.Title)` but `entity not in page.OutLinks` - - Not auto-fixable (might be intentional) - -5. **Empty Content** (warning) - - < 50 chars of content - - Auto-fixable: archive - -6. **Duplicate Slug** (not currently implemented in code) - -**Health Score Calculation:** - -``` -healthScore = 100 - -if orphanPct > 50% { - healthScore -= 25 -} else if orphanPct > 25% { - healthScore -= 10 -} - -brokenLinkCount = count of LintIssueBrokenLink -healthScore -= brokenLinkCount * 5 - -if totalLinks == 0 and totalPages > 2 { - healthScore -= 15 -} - -emptyPageCount = count of LintIssueEmptyContent -healthScore -= emptyPageCount * 3 - -if healthScore < 0 { healthScore = 0 } -``` - -**AutoFix Behavior:** - -```go -func (s *WikiLintService) AutoFix(ctx context.Context, kbID string) (int, error) { - report, _ := s.RunLint(ctx, kbID) - - fixed := 0 - for _, issue := range report.Issues { - if !issue.AutoFixable { continue } - - switch issue.Type { - case LintIssueBrokenLink: - // Replace [[broken]] with plain text - page.Content = ReplaceAll(page.Content, - "[[" + issue.TargetSlug + "]]", - issue.TargetSlug) - wikiService.UpdatePage(ctx, page) - fixed++ - - case LintIssueEmptyContent: - // Archive instead of delete - page.Status = WikiPageStatusArchived - wikiService.UpdatePage(ctx, page) - fixed++ - } - } - - if fixed > 0 { - // Rebuild links to reflect changes - wikiService.RebuildLinks(ctx, kbID) - } - - return fixed, nil -} -``` - ---- - -## Part 4: Edge Cases and Gotchas - -### 4.1 Concurrent Update Conflicts - -**Scenario:** Two agents simultaneously update the same page - -``` -Agent A: Fetch page version=5 -Agent B: Fetch page version=5 -Agent A: Update WHERE version=5 ✓ → version becomes 6 -Agent B: Update WHERE version=5 ✗ → ErrWikiPageConflict -``` - -**Caller Responsibility:** -- Must retry with fresh page fetch -- No automatic retry in service layer -- HTTP handlers should return 409 Conflict - -**Note:** UpdateMeta bypasses this check (intentional for background operations) - -### 4.2 Link Consistency Windows - -**Problem:** Between UpdatePage and updateInLinks, there's a window where link consistency is broken - -**Impact:** -- If process crashes after UPDATE but before updateInLinks -- InLinks become stale -- RebuildLinks can fix this - -**Mitigation:** -- RebuildLinks operation for emergency recovery -- Log entry tracks when link maintenance runs -- Linter detects orphan pages - -### 4.3 Self-Link Prevention - -**Code:** -```go -if r.slug == selfSlug { continue } // Skip self-links -``` - -**Test Case:** -```go -func TestLinkifyContent_SkipsSelfSlug(t *testing.T) { - refs := []linkRef{{slug: "beijing", matchText: "北京"}} - // When rendering on beijing page itself - got, changed := linkifyContent("北京是首都", refs, "beijing") - if changed { t.Fatalf("should not self-link") } -} -``` - -### 4.4 LLM Conflict Detection - -**Real Scenario:** -``` -Document A: "Hunyuan Model is an LLM from Tencent" - → Extracted as Entity: "Hunyuan Model", slug="entity/hunyuan-model" - -Later, Document B: "Qwen3 is a powerful LLM" - → Extracted as Entity: "Qwen3", slug="entity/qwen3" - -If system tries to merge B into A's page: - WikiPageModifyPrompt checks: "Does new_info describe same entity as page?" - → NO (Qwen3 ≠ Hunyuan Model) - → LLM rejects merge -``` - -### 4.5 Slug Reuse Across Updates - -**Slug Continuity Rule (in WikiKnowledgeExtractPrompt):** - -``` -If previous slugs are provided: - - If entity still exists: REUSE exact slug - - If entity gone: DO NOT include in output - - If new entity: generate new slug - -This ensures slug stability when documents are updated. -``` - -**Example:** -``` -Document v1: "Acme Corp is a 50-person startup" - → Extracted: entity/acme-corp - -Document v1 replaced with v2: "Acme Corp is now a 500-person company" - → Extracted: entity/acme-corp (SAME slug, different details) - → Triggers REDUCE for entity/acme-corp - → Updates page with new details - → SourceRefs now includes v2 instead of v1 -``` - -### 4.6 CJK Text Handling in Cross-Link Injection - -**Word Boundary Rules:** - -```go -func hasWordBoundary(s string, pos, end int) bool { - if pos > 0 { - r, _ := utf8.DecodeLastRuneInString(s[:pos]) - if isASCIIWordRune(r) { return false } // No boundary - } - if end < len(s) { - r, _ := utf8.DecodeRuneInString(s[end:]) - if isASCIIWordRune(r) { return false } // No boundary - } - return true -} -``` - -**Implication:** -- "北京邮电大学" (9 chars) → boundary after 北京 (CJK naturally ends) -- Can match "北京" even in the middle if preceded/followed by non-ASCII -- "北京" inside "北京邮电大学" WILL match if "长北京" is sorted shorter - -**Test Case (sorting matters):** -```go -func TestLinkifyContent_LongerNameWinsOverSubstring(t *testing.T) { - refs := []linkRef{ - {slug: "beijing", matchText: "北京"}, - {slug: "bupt", matchText: "北京邮电大学"}, - } - got, _ := linkifyContent("我就读于北京邮电大学", refs, "") - // Should link full university name, not partial - if !strings.Contains(got, "[[bupt|北京邮电大学]]") { - t.Fatalf("longer match not preferred") - } -} -``` - -### 4.7 Forbidden Span Edge Cases - -**Reference Definition Handling:** - -``` -[capital]: https://example.com/beijing -``` - -- Scanned in Pass 1 of `computeForbiddenSpans` -- Full line marked as forbidden -- Prevents "beijing" inside URL from being linked - -**Inline Code Edge Case:** - -``` -Running `code with '''multiple''' backticks` -``` - -- Backtick run counting: matches opening run length exactly -- "Can't" in prose won't close inline code (only 1 backtick) - -**Nested Brackets:** - -``` -[[[[nested]]]] or [[link with [brackets]]] -``` - -- `findClosingBracket` tracks depth -- Balanced tracking prevents false closes -- First `[[` opens, first `]]` closes if depth==1 - -### 4.8 Redis Timing Issues - -**Lock Acquisition:** - -``` -Task A: SetNX("wiki:active:kb1", "1", 5m) → SET -Task B: SetNX("wiki:active:kb1", "1", 5m) → NOT SET (already exists) -Task B: Reschedule with exponential backoff -``` - -**Pending List Persistence:** - -``` -Pending item expires after 24 hours (wikiPendingTTL) -If ingestion is blocked for > 24h: - - Items auto-purge from Redis - - Next task finds empty list - - Exits cleanly -``` - -**Lock Refresh Failure:** - -``` -If refresh goroutine crashes: - - Lock still has 5-min TTL from last refresh - - If process crashes too, another task can acquire lock after 5m - - Prevents permanent deadlock -``` - -### 4.9 LLM Parsing Failures - -**JSON Parsing Error:** - -In `extractEntitiesAndConceptsNoUpsert`: -```go -var result struct { - Entities []EntityJSON `json:"entities"` - Concepts []ConceptJSON `json:"concepts"` -} -if err := json.Unmarshal(response, &result); err != nil { - logger.Warnf(ctx, "failed to parse LLM response: %v", err) - return nil, nil, nil // Return empty, continue -} -``` - -- Continues with empty extraction -- Document still marked as processed -- No retry on parse failure - -**Image Handling:** - -In prompts: -``` - - - ... - https://... - - -``` - -- LLM can include images: `![caption](url)` -- Invalid URLs might cause rendering issues in frontend -- Currently no validation of image URLs - ---- - -## Part 5: Operational Considerations - -### 5.1 Performance Scaling - -**Batch Size Limits:** -- `wikiMaxDocsPerBatch` = 5 (default) -- Prevents single batch from overwhelming resources -- Follow-up tasks handle remaining items - -**Parallel Goroutines:** -- MAP phase: 10 concurrent extractions -- REDUCE phase: 10 concurrent syntheses -- Total concurrent LLM calls: 20 maximum per batch - -**LLM Cost Implications:** -- Each document extraction = 1 LLM call (50-100 tokens typically) -- Each slug synthesis = 1 LLM call (100-300 tokens typically) -- 5 documents with 10 new entities = ~15-20 LLM calls per batch - -### 5.2 Storage Considerations - -**Database Schema:** -```sql -CREATE TABLE wiki_pages ( - id VARCHAR(36) PRIMARY KEY, - tenant_id BIGINT, - knowledge_base_id VARCHAR(36), - slug VARCHAR(255), - title VARCHAR(512), - page_type VARCHAR(32), - status VARCHAR(32), - content TEXT, -- Full markdown - summary TEXT, - aliases JSON, - source_refs JSON, - in_links JSON, - out_links JSON, - page_metadata JSON, - version INT, - created_at TIMESTAMP, - updated_at TIMESTAMP, - deleted_at TIMESTAMP, - - UNIQUE INDEX idx_kb_slug (knowledge_base_id, slug), - INDEX idx_tenant, - INDEX idx_kb, - INDEX idx_page_type, - INDEX idx_status, - INDEX idx_deleted_at -); - -CREATE TABLE wiki_page_issues ( - id VARCHAR(36) PRIMARY KEY, - tenant_id BIGINT, - knowledge_base_id VARCHAR(36), - slug VARCHAR(255), - issue_type VARCHAR(50), - description TEXT, - suspected_knowledge_ids JSON, - status VARCHAR(20), - reported_by VARCHAR(100), - created_at TIMESTAMP, - updated_at TIMESTAMP, - deleted_at TIMESTAMP, - - INDEX idx_kb_slug_status (knowledge_base_id, slug, status) -); -``` - -**Typical Page Size:** -- Summary page: 5-20 KB (document summary + structure) -- Entity/Concept page: 2-10 KB (focused on single entity/concept) -- Index page: 10-50 KB (grows with number of pages) -- Log page: 5-50 KB (operation history) - -### 5.3 Monitoring and Debugging - -**Key Metrics:** -- `wiki:pending:{kbID}` list length (pending documents) -- `wiki:active:{kbID}` presence (processing active?) -- Orphan page count (from GetStats) -- Broken link count (from RunLint) -- Health score (from RunLint) - -**Logging Points:** -``` -WikiBoost: boosted N wiki page chunks by 1.3x -wiki: injected cross-links in N pages -wiki lint: KB X — health score Y/100, Z issues -wiki: failed to update in_links for slug: error -wiki: create wiki page: error -wiki auto-fix: KB X — fixed N issues -``` - -**Debug Queries:** - -```sql --- Find pages with broken links -SELECT DISTINCT kbID, slug FROM wiki_pages -WHERE JSON_LENGTH(out_links) > 0 -AND NOT EXISTS (SELECT 1 FROM wiki_pages target - WHERE target.slug IN (SELECT * FROM JSON_EXTRACT(out_links, '$[*]'))); - --- Find orphan pages -SELECT slug, title FROM wiki_pages -WHERE knowledge_base_id = ? -AND page_type NOT IN ('index', 'log') -AND JSON_LENGTH(in_links) = 0 -ORDER BY updated_at DESC; - --- Find pages by source knowledge -SELECT * FROM wiki_pages -WHERE knowledge_base_id = ? -AND source_refs LIKE '%"knowledge123"%'; -``` - -### 5.4 Common Pitfalls and Solutions - -| Issue | Cause | Solution | -|-------|-------|----------| -| Stale InLinks | Crash between UPDATE and updateInLinks | RunLint, AutoFix broken links | -| Duplicate entity pages | LLM generates new slug for same entity | Check previous_slugs in extraction prompt | -| Double-linked pages | linkifyContent called twice | Idempotence built-in; safe to re-run | -| Orphan pages | New page not added to index, no backlinks | RebuildIndexPage, manual linking | -| Broken links after retract | cleanDeadLinks not called | Re-run ProcessWikiIngest post-processing | -| High LLM costs | Too many batches | Increase wikiIngestDelay or batch size | -| Slow index rebuild | Index page has thousands of entries | Consider pagination or separate category pages | - ---- - -## Part 6: Integration Points - -### 6.1 Chat Pipeline Integration (WikiBoost) - -**Plugin Flow:** - -``` -User Query - ↓ -Vector/Keyword Search - ↓ -Initial Retrieval (mix of doc chunks + wiki pages) - ↓ -CHUNK_RERANK Event - ↓ -PluginWikiBoost.OnEvent() - ├─ Check for wiki_page chunks - ├─ Verify KB has wiki enabled - ├─ Multiply scores by 1.3x - └─ Re-sort results - ↓ -Final Ranked Results (wiki pages boost up) - ↓ -LLM Generation (prefers wiki context) -``` - -**Score Boost Logic:** - -```go -for i := range chatManage.RerankResult { - if chatManage.RerankResult[i].ChunkType == ChunkTypeWikiPage { - chatManage.RerankResult[i].Score *= 1.3 - boostedCount++ - } -} -// Re-sort after all boosts applied -sort.SliceStable(chatManage.RerankResult, func(i, j int) bool { - return chatManage.RerankResult[i].Score > chatManage.RerankResult[j].Score -}) -``` - -### 6.2 Agent Tool Integration - -**Available Tools:** -- `wiki_write_page` — Create/update pages -- `wiki_delete_page` — Delete pages -- `wiki_replace_text` — Find/replace within page -- `wiki_read_source_doc` — Read source document for agent - -**Typical Agent Flow:** - -``` -User: "Compare Hunyuan and Qwen models" - ↓ -Agent: Call wiki_read_source_doc (fetch docs mentioning both) - ↓ -Agent: Generate comparison analysis - ↓ -Agent: Call wiki_write_page (create synthesis/comparison page) - ├─ slug: "synthesis/hunyuan-vs-qwen" - ├─ page_type: "synthesis" - ├─ content: Agent-generated comparison - └─ title: "Hunyuan vs Qwen: Comparison" - ↓ -Service: InjectCrossLinks (auto-link entity/concept mentions) - ↓ -Service: RebuildIndexPage (add to index) -``` - -### 6.3 Chunk Synchronization - -**When page is created/updated:** - -``` -1. Wiki page saved to database -2. Page serialized as chunk: - - chunk_id: "wp-{page_id}" - - chunk_type: "wiki_page" - - content: page.Content - - metadata: {slug, page_type, kb_id, ...} -3. Chunk indexed in vector + keyword search -4. Chunk becomes retrievable alongside doc chunks -``` - -**Index Updates:** - -``` -CreatePage - ↓ -Service saves to wiki_pages table - ↓ -Service calls chunkService.CreateChunk() - ├─ Generate embedding - ├─ Index keyword tokens - └─ Store in vector database - ↓ -Next search includes this page -``` - ---- - -## Part 7: Future Enhancements and Recommendations - -### 7.1 Potential Improvements - -1. **Async Link Updates** - - Currently synchronous, could be queued - - Reduces latency for page creates/updates - - Risk: temporary inconsistency - -2. **Link Validation on Ingest** - - Check OutLinks point to existing pages - - Auto-generate fix suggestions - - Add to linter checks - -3. **Incremental Index Rebuild** - - Current: regenerates entire index page - - Proposed: delta updates (only add/remove changed sections) - - Benefit: O(1) instead of O(n) for large wikis - -4. **Slug Aliases for Navigation** - - Allow `[[entity/hunyuan|Hunyuan]]` to resolve via aliases - - Current: redirects only work if exact slug matches - - Benefit: more natural linking - -5. **Graph Export** - - Mermaid diagram generation from graph - - DOT format for Graphviz - - Useful for documentation - -### 7.2 Known Limitations - -1. **First-Match-Only Linking** - - Each slug links exactly once per page - - Later mentions aren't linked - - Trade-off: prevents visual clutter - -2. **LLM Dependency** - - Extraction quality depends on LLM version - - Bad extractions not auto-detected - - Mitigation: RunLint catches orphans/breaks - -3. **Content-Based Matching** - - Substring matching in cross-links - - Case-sensitive (normalized to lowercase) - - No semantic understanding of mentions - -4. **Redis Dependency** - - Debouncing/batching requires Redis - - Pending operations lost on Redis crash - - Mitigation: documents can be re-uploaded - ---- - -## Conclusion - -The WeKnora wiki system demonstrates sophisticated architectural patterns for knowledge extraction and synthesis: - -- **Resilient async processing** with debouncing and batching -- **Parallel MAP-REDUCE** for scalable LLM integration -- **Robust consistency** via optimistic locking and bidirectional link maintenance -- **Sophisticated text processing** for cross-link injection with pattern matching -- **Comprehensive health monitoring** via linting and auto-fix - -The system is production-ready with careful attention to edge cases, concurrency safety, and operational observability. Future enhancements can focus on incremental operations and graph visualization features. - diff --git a/docs/AGENT_KB_IMPLEMENTATION_PATTERNS.md b/docs/AGENT_KB_IMPLEMENTATION_PATTERNS.md deleted file mode 100644 index d83100d8..00000000 --- a/docs/AGENT_KB_IMPLEMENTATION_PATTERNS.md +++ /dev/null @@ -1,619 +0,0 @@ -# Agent/KB Integration - Implementation Patterns - -This document provides practical implementation patterns and code walkthroughs for working with the agent/KB system. - -## Table of Contents - -1. [Creating a Custom Agent](#creating-a-custom-agent) -2. [Configuring Agent Knowledge Bases](#configuring-agent-knowledge-bases) -3. [Common Configuration Scenarios](#common-configuration-scenarios) -4. [Retrieving Search Results](#retrieving-search-results) -5. [Debugging Configuration Issues](#debugging-configuration-issues) - ---- - -## Creating a Custom Agent - -### Agent Creation Flow - -```go -// From handler layer (e.g., HTTP POST /agents) -customAgent := &types.CustomAgent{ - ID: uuid.New().String(), - TenantID: tenantID, - Name: "Research Assistant", - Config: types.CustomAgentConfig{ - // KB Configuration - KBSelectionMode: "selected", - KnowledgeBases: []string{"kb-001", "kb-002"}, - - // Model Configuration - ModelID: "model-gpt4", - RerankModelID: "model-rerank", - - // Agent Mode Configuration - AgentMode: types.AgentModeSmartReasoning, - MaxIterations: 15, - Temperature: 0.7, - - // Tool Configuration - AllowedTools: []string{ - tools.ToolKnowledgeSearch, - tools.ToolGrepChunks, - tools.ToolWebSearch, - tools.ToolFinalAnswer, - }, - - // Retrieval Strategy - EmbeddingTopK: 20, - VectorThreshold: 0.4, - KeywordThreshold: 0.5, - RerankTopK: 10, - - // Multi-turn - MultiTurnEnabled: true, - HistoryTurns: 5, - - // Web Search - WebSearchEnabled: true, - WebSearchMaxResults: 8, - }, -} - -// Save to database -err := s.customAgentRepo.Create(ctx, customAgent) -``` - -### Agent Defaults - -The system automatically sets defaults for omitted fields: - -```go -// From types.CustomAgent.EnsureDefaults() -func (a *CustomAgent) EnsureDefaults() { - if a.Config.Temperature < 0 { - a.Config.Temperature = 0.7 - } - if a.Config.MaxIterations == 0 { - a.Config.MaxIterations = 10 - } - if a.Config.WebSearchMaxResults == 0 { - a.Config.WebSearchMaxResults = 5 - } - if a.Config.HistoryTurns == 0 { - a.Config.HistoryTurns = 5 - } - if a.Config.EmbeddingTopK == 0 { - a.Config.EmbeddingTopK = 10 - } - // ... more defaults -} -``` - ---- - -## Configuring Agent Knowledge Bases - -### Pattern 1: "selected" Mode - Specific KBs - -For agents with curated knowledge bases: - -```go -customAgent.Config.KBSelectionMode = "selected" -customAgent.Config.KnowledgeBases = []string{ - "sales-kb", - "product-docs-kb", - "faq-kb", -} -``` - -When a request is made: -1. `resolveKnowledgeBases()` detects mode="selected" -2. Returns `["sales-kb", "product-docs-kb", "faq-kb"]` -3. `buildSearchTargets()` creates 3 SearchTargets (KNOWLEDGE_BASE type) -4. Tool receives SearchTargets restricted to these 3 KBs -5. Agent cannot access other KBs even if @mentioned - -### Pattern 2: "all" Mode - Dynamic KB Access - -For research agents with broad KB access: - -```go -customAgent.Config.KBSelectionMode = "all" -customAgent.Config.KnowledgeBases = []string{} // Ignored when mode="all" -``` - -When a request is made: -1. `resolveKnowledgeBases()` calls `ListKnowledgeBases()` -2. For non-shared agents: also includes user's shared KBs -3. Returns ALL accessible KB IDs at request time -4. `buildSearchTargets()` creates SearchTarget for each KB -5. Agent can search any accessible KB without reconfiguration - -### Pattern 3: "none" Mode - No KB Access - -For agents that don't use knowledge bases: - -```go -customAgent.Config.KBSelectionMode = "none" -customAgent.Config.KnowledgeBases = []string{} - -// Knowledge base tools are automatically filtered out -// Only web search and other tools available -``` - -### Pattern 4: RetrieveKBOnlyWhenMentioned - Explicit Selection - -For agents where KB usage is optional: - -```go -customAgent.Config.KBSelectionMode = "selected" -customAgent.Config.KnowledgeBases = []string{"kb-001", "kb-002"} -customAgent.Config.RetrieveKBOnlyWhenMentioned = true -``` - -Behavior: -- Agent has access to kb-001 and kb-002 -- KB search only occurs if user explicitly @mentions a KB -- Without @mention: KB tools won't be called by LLM - -Example query behaviors: -``` -Query: "What is this?" - → No KB search (no @mention) - → May use web search if enabled - -Query: "What is this? @kb-001" - → KB search in kb-001 only - → Respects RetrieveKBOnlyWhenMentioned setting -``` - ---- - -## Common Configuration Scenarios - -### Scenario 1: Specialized Domain Expert - -Use case: Agent focused on specific domain (e.g., finance) - -```go -customAgent.Config = types.CustomAgentConfig{ - AgentMode: "smart-reasoning", - KBSelectionMode: "selected", - KnowledgeBases: []string{"finance-kb", "compliance-kb"}, - - AllowedTools: []string{ - tools.ToolKnowledgeSearch, - tools.ToolDatabaseQuery, - tools.ToolFinalAnswer, - }, - - MaxIterations: 20, - Temperature: 0.5, // Conservative - MultiTurnEnabled: true, - HistoryTurns: 10, - - EmbeddingTopK: 25, - VectorThreshold: 0.6, // High threshold = precise matches - - WebSearchEnabled: false, // Rely on internal KB only -} -``` - -### Scenario 2: General-Purpose Research Assistant - -Use case: Broad access, flexible retrieval - -```go -customAgent.Config = types.CustomAgentConfig{ - AgentMode: "smart-reasoning", - KBSelectionMode: "all", // All accessible KBs - - AllowedTools: []string{ - tools.ToolKnowledgeSearch, - tools.ToolGrepChunks, - tools.ToolWebSearch, - tools.ToolTodoWrite, - tools.ToolFinalAnswer, - }, - - MaxIterations: 15, - Temperature: 0.7, // Balanced - MultiTurnEnabled: true, - HistoryTurns: 5, - - EmbeddingTopK: 10, - VectorThreshold: 0.3, // Lower = broader matches - - WebSearchEnabled: true, - WebSearchMaxResults: 10, -} -``` - -### Scenario 3: FAQ-Focused Quick Responder - -Use case: Fast answers from FAQ KB only - -```go -customAgent.Config = types.CustomAgentConfig{ - AgentMode: "quick-answer", // RAG mode, not agent mode - KBSelectionMode: "selected", - KnowledgeBases: []string{"faq-kb"}, - - AllowedTools: []string{ - tools.ToolKnowledgeSearch, - tools.ToolFinalAnswer, - }, - - MaxIterations: 1, // Quick, single shot - Temperature: 0.3, // Deterministic - MultiTurnEnabled: false, - - EmbeddingTopK: 5, - VectorThreshold: 0.7, // Very high = exact matches - - FAQPriorityEnabled: true, - FAQDirectAnswerThreshold: 0.8, - FAQScoreBoost: 2.0, -} -``` - -### Scenario 4: Cross-Tenant Shared Agent - -Use case: Agent shared across organizations - -```go -// Organization A's agent (owner) -sharedAgent := &types.CustomAgent{ - ID: "shared-research-agent", - TenantID: orgAID, // ← Owner is Org A - Config: types.CustomAgentConfig{ - KBSelectionMode: "selected", - KnowledgeBases: []string{"orgA-kb-1", "orgA-kb-2"}, - // ... other config - }, -} - -// When Organization B uses this agent: -req := &types.QARequest{ - CustomAgent: sharedAgent, - Session: &types.Session{ - TenantID: orgBID, // ← User is from Org B - }, - Query: "What is...", -} - -// During buildAgentConfig(): -agentTenantID := sharedAgent.TenantID // orgAID -sessionTenantID := req.Session.TenantID // orgBID - -isSharedAgent := sessionTenantID != agentTenantID // TRUE - -// Key behavior: -// - Only Org A's KBs (orgA-kb-1, orgA-kb-2) are searched -// - Org B user CANNOT add their own KBs via @mention -// - This prevents data leak across organizations -``` - ---- - -## Retrieving Search Results - -### Pattern 1: Direct Tool Usage in Agent - -When agent calls knowledge_search tool: - -```go -// In LLM response, agent generates: -{ - "tool_name": "knowledge_search", - "arguments": { - "queries": [ - "What are the key features of our product?", - "How does the pricing model work?" - ], - "knowledge_base_ids": [] // Optional: empty = search all allowed KBs - } -} - -// Tool execution (knowledge_search.go:155) -func (t *KnowledgeSearchTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) { - var input KnowledgeSearchInput - json.Unmarshal(args, &input) - - // t.searchTargets = pre-computed targets from config - searchTargets := t.searchTargets - - // If user specifies KBs, filter further - if len(input.KnowledgeBaseIDs) > 0 { - filtered := filterTargets(searchTargets, input.KnowledgeBaseIDs) - searchTargets = filtered - } - - // Execute search using all targets - results := t.concurrentSearchByTargets( - ctx, input.Queries, searchTargets, ...) - - return &types.ToolResult{ - Success: true, - Output: formatResults(results), - Data: resultsAsJSON(results), - }, nil -} -``` - -### Pattern 2: Non-Agent KB Search (Chat Pipeline) - -```go -// Via chat pipeline for non-agent mode -chatManage := &types.ChatManage{ - Query: "Summarize Q3 results", - SearchTargets: /* pre-computed */, - VectorThreshold: 0.3, - KeywordThreshold: 0.5, - EmbeddingTopK: 10, -} - -// Pipeline plugin executes -plugin.OnEvent(ctx, types.CHUNK_SEARCH, chatManage, next) - ↓ -plugin.searchByTargets(ctx, chatManage) - ├─ Groups targets by embedding model - ├─ For full KBs: HybridSearch(all full KB IDs) - ├─ For specific files: Per-target search - └─ Returns merged SearchResults -``` - -### Pattern 3: Accessing Single SearchTarget - -```go -// When processing specific knowledge files -target := &types.SearchTarget{ - Type: types.SearchTargetTypeKnowledge, - KnowledgeBaseID: "kb-001", - TenantID: tenantID, - KnowledgeIDs: []string{"file-1", "file-2"}, -} - -// In searchSingleTarget (search.go:460) -params := types.SearchParams{ - QueryText: query, - QueryEmbedding: embedding, - KnowledgeBaseIDs: []string{target.KnowledgeBaseID}, - KnowledgeIDs: target.KnowledgeIDs, // ← Restricts to these files - VectorThreshold: 0.3, - KeywordThreshold: 0.5, - MatchCount: 10, -} - -results, _ := knowledgeBaseService.HybridSearch(ctx, target.KnowledgeBaseID, params) -// Returns chunks from kb-001 that are in file-1 or file-2 -``` - ---- - -## Debugging Configuration Issues - -### Issue 1: "No Search Targets Available" - -**Error**: Tool returns error "no knowledge bases specified and no search targets configured" - -**Diagnosis**: -```go -// In knowledge_search.go:196 -if len(searchTargets) == 0 { - logger.Errorf(ctx, "[Tool][KnowledgeSearch] No search targets available") - return &types.ToolResult{ - Success: false, - Error: "no knowledge bases specified and no search targets configured", - }, err -} -``` - -**Causes**: -1. Agent configured with KBSelectionMode="none" -2. Request has no @mentions and RetrieveKBOnlyWhenMentioned=true -3. Agent has no allowed KBs for shared agent scenario - -**Fix**: -```go -// Check agent config -if customAgent.Config.KBSelectionMode == "none" { - // Need to enable KB mode - customAgent.Config.KBSelectionMode = "selected" - customAgent.Config.KnowledgeBases = []string{"kb-id"} -} - -// Or check @mention requirement -if customAgent.Config.RetrieveKBOnlyWhenMentioned && len(req.KnowledgeBaseIDs) == 0 { - // Requires @mention - req.KnowledgeBaseIDs = []string{"kb-id"} // User needs to mention -} -``` - -### Issue 2: "Shared Agent Blocked All @Mentions" - -**Error**: @mention filtered out with warning "Blocking @mentioned KB: not in shared agent's allowed scope" - -**Diagnosis**: -```go -// In session_qa_helpers.go:231 -if !allowedSet[id] { - logger.Warnf(ctx, "Blocking @mentioned KB %s: not in shared agent's allowed scope", id) -} -``` - -**Cause**: Using shared agent from different organization, @mentioning KB outside agent's scope - -**Fix**: -```go -// Check agent's allowed KBs -allowedKBs := customAgent.Config.KnowledgeBases -userMentionedKBs := req.KnowledgeBaseIDs - -// Only use KBs that are in both lists -validKBs := make([]string, 0) -for _, kb := range userMentionedKBs { - for _, allowed := range allowedKBs { - if kb == allowed { - validKBs = append(validKBs, kb) - } - } -} - -// Or: configure agent with mode="all" to allow any KB -customAgent.Config.KBSelectionMode = "all" -``` - -### Issue 3: "Failed to Get Chat Model" - -**Error**: "Failed to get chat model: model not found" - -**Diagnosis**: -```go -// In session_agent_qa.go:88 -summaryModel, err := s.modelService.GetChatModel(ctx, effectiveModelID) -if err != nil { - logger.Warnf(ctx, "Failed to get chat model: %v", err) - return fmt.Errorf("failed to get chat model: %w", err) -} -``` - -**Causes**: -1. CustomAgent.Config.ModelID doesn't exist -2. No model configured at any level -3. Model is disabled/deleted - -**Debug**: -```go -// Check model resolution priority -effectiveModelID := "" - -// Priority 1: Request override -if req.SummaryModelID != "" { - effectiveModelID = req.SummaryModelID -} - -// Priority 2: Agent config -if effectiveModelID == "" && customAgent.Config.ModelID != "" { - effectiveModelID = customAgent.Config.ModelID -} - -// Priority 3: KB default -if effectiveModelID == "" { - effectiveModelID = s.selectChatModelID(ctx, req.Session, kbs, knowledgeIDs) -} - -// Verify model exists -model, err := s.modelService.GetChatModel(ctx, effectiveModelID) -if err != nil { - logger.Infof(ctx, "Model %s not found: %v", effectiveModelID, err) -} -``` - -### Issue 4: Knowledge Base Tools Filtered Out - -**Error**: Agent calls knowledge_search but tool not available - -**Diagnosis**: -```go -// In agent_service.go:338 -hasKnowledge := len(config.KnowledgeBases) > 0 || len(config.KnowledgeIDs) > 0 -if !hasKnowledge { - // Remove all KB-related tools - filteredTools = filterOut(allowedTools, [ - ToolKnowledgeSearch, - ToolGrepChunks, - ToolListKnowledgeChunks, - // etc - ]) -} -``` - -**Cause**: Agent has no KBs configured - -**Fix**: -```go -// Ensure at least one KB is configured -customAgent.Config.KBSelectionMode = "selected" -customAgent.Config.KnowledgeBases = []string{"kb-id"} - -// Or use "all" mode -customAgent.Config.KBSelectionMode = "all" -``` - -### Issue 5: Low Recall (Few Results) - -**Diagnosis**: -``` -Query results: 2 chunks -Expected: 10+ chunks -``` - -**Causes**: -1. VectorThreshold too high -2. EmbeddingTopK too low -3. KB doesn't contain relevant content - -**Tune Parameters**: -```go -// Lower VectorThreshold for broader matches -customAgent.Config.VectorThreshold = 0.3 // Was 0.7 - -// Increase TopK to retrieve more candidates -customAgent.Config.EmbeddingTopK = 50 // Was 10 - -// Or relax keyword matching -customAgent.Config.KeywordThreshold = 0.2 // Was 0.5 -``` - -### Issue 6: Rerank Model Missing - -**Error**: "Rerank model not configured for custom agent, but knowledge_search tool is enabled" - -**Diagnosis**: -```go -// In session_agent_qa.go:104 -hasKnowledgeSearchTool := false -for _, tool := range agentConfig.AllowedTools { - if tool == tools.ToolKnowledgeSearch { - hasKnowledgeSearchTool = true - break - } -} - -if hasKnowledgeSearchTool { - rerankModelID := req.CustomAgent.Config.RerankModelID - if rerankModelID == "" { - return errors.New("rerank model is not configured") - } -} -``` - -**Cause**: Using knowledge_search but no rerank model specified - -**Fix**: -```go -customAgent.Config.RerankModelID = "model-rerank-id" - -// Or disable knowledge_search if rerank unavailable -customAgent.Config.AllowedTools = []string{ - tools.ToolGrepChunks, // Keyword search doesn't need rerank - tools.ToolFinalAnswer, -} -``` - ---- - -## Summary - -Key patterns to remember: - -1. **Always set KBSelectionMode** - Defaults to "selected" which requires explicit KnowledgeBases -2. **SearchTargets computed once** - Set before creating agent engine -3. **Tools constrained by SearchTargets** - Cannot search outside pre-computed scope -4. **Shared agents cannot leak KBs** - isSharedAgent detection prevents cross-org data access -5. **Configuration precedence matters** - Request > Agent > Tenant > System defaults -6. **Rerank model required for knowledge_search** - Or use grep_chunks instead -7. **Use mode="all" for flexible KB access** - Resolves at request time -8. **Use RetrieveKBOnlyWhenMentioned for optional KB** - KB search only on @mention diff --git a/docs/AGENT_KB_QUICK_REFERENCE.md b/docs/AGENT_KB_QUICK_REFERENCE.md deleted file mode 100644 index 9a53b5d4..00000000 --- a/docs/AGENT_KB_QUICK_REFERENCE.md +++ /dev/null @@ -1,286 +0,0 @@ -# Agent & Knowledge Base Integration - Quick Reference - -## Core Data Structures - -### Agent Models - -``` -CustomAgent (persisted) -├── ID: agent-uuid or builtin-quick-answer -├── TenantID: owner tenant -├── Config: CustomAgentConfig -│ ├── AvailableKnowledgeBases: []string # Which KBs agent can access -│ ├── AvailableKnowledgeIDs: []string # Which documents it can access -│ ├── AllowedTools: []string # Tool whitelist -│ ├── RerankModelID: string # For search result ranking -│ ├── WebSearchEnabled: bool -│ ├── MultiTurnEnabled: bool -│ ├── RetrieveKBOnlyWhenMentioned: bool -│ └── [... more settings ...] -└── IsBuiltin: bool - -↓ (Runtime resolution) - -AgentConfig (runtime only) -├── KnowledgeBases: []string # Resolved KB IDs -├── KnowledgeIDs: []string # Resolved document IDs -├── SearchTargets: []*SearchTarget # ← UNIFIED search scope -├── AllowedTools: []string -├── RetrievalConfig params -└── [... execution config ...] -``` - -### Knowledge Base Model - -``` -KnowledgeBase -├── ID: kb-uuid -├── Type: "document" | "faq" | "wiki" # KB type -├── TenantID: owner tenant -├── EmbeddingModelID: model-id # For vector search -├── FAQConfig: FAQConfig (if Type == "faq") # FAQ indexing strategy -├── WikiConfig: WikiConfig (if Type == "wiki") # Wiki-specific config -└── ChunkingConfig: ChunkingConfig # How documents split -``` - -### Retrieval Configuration (Tenant-level) - -``` -RetrievalConfig (at Tenant) -├── EmbeddingTopK: int # Vector search: max candidates (default: 50) -├── VectorThreshold: float64 # Min similarity 0-1 (default: 0.15) -├── KeywordThreshold: float64 # Min keyword match 0-1 (default: 0.3) -├── RerankTopK: int # Final results count (default: 10) -├── RerankThreshold: float64 # Min rerank score (default: 0.2) -└── RerankModelID: string # Which reranker to use - -Tenant.EffectiveEngines: []RetrieverEngineParams -├── RetrieverEngineType: "elasticsearch" | "postgres" | "qdrant" | ... -└── RetrieverType: "vector" | "keywords" | "websearch" -``` - -## How Agents Access KBs: Step-by-Step - -### 1. Request Arrives -``` -QARequest { - Query: "user question", - Agent: CustomAgent (with Config.AvailableKnowledgeBases), - SessionAgentConfig: {KnowledgeBases: override} // optional override -} -``` - -### 2. Resolve Runtime Configuration -``` -buildAgentConfig() { - // Merge CustomAgent + SessionAgentConfig - agentConfig.KnowledgeBases = resolveKnowledgeBases(customAgent, sessionConfig) - agentConfig.KnowledgeIDs = resolveKnowledgeIDs(...) -} -``` - -### 3. Convert to Unified Search Targets -``` -buildSearchTargets(knowledgeBaseIDs, knowledgeIDs) { - // For each KB: - targets.append(SearchTarget{ - Type: "knowledge_base", // Search entire KB - KnowledgeBaseID: id, - TenantID: resolved_tenant, - KnowledgeIDs: [] // Empty = whole KB - }) - - // For specific documents: - targets.append(SearchTarget{ - Type: "knowledge", // Search specific files - KnowledgeBaseID: parent_kb, - TenantID: resolved_tenant, - KnowledgeIDs: [doc1, doc2, ...] // Only these - }) -} -// Result stored in: AgentConfig.SearchTargets -``` - -### 4. Agent Calls Retrieval Tool -``` -Agent's thought: "I need to search knowledge..." -Agent.ExecuteTool("knowledge_search", { - queries: ["What is RAG?"], - knowledge_base_ids: [] // if empty, uses SearchTargets -}) -``` - -### 5. Tool Performs Hybrid Search -``` -Tool.Execute() { - // Get query embedding - queryEmbedding = getEmbedding(query) // from KB's EmbeddingModelID - - // Call HybridSearch - results = HybridSearch(kb_id, { - QueryText: query, - Embedding: queryEmbedding, - KnowledgeIDs: target.KnowledgeIDs, // Scoped if present - VectorThreshold: retrieval_config.threshold, - KeywordThreshold: retrieval_config.threshold, - MatchCount: retrieval_config.top_k, - RetrieverType: "vector" // for vector search - }) -} -``` - -### 6. Hybrid Search Orchestrates Retrieval -``` -HybridSearch(kb_id, params) { - // 1. Create composite engine from tenant's configured backends - engine = CompositeRetrieveEngine(tenant.EffectiveEngines) - - // 2. Execute parallel retrieval - vectorResults = engine.Retrieve(RetrieveParams{ - RetrieverType: "vector", - KnowledgeBaseIDs: [kb_id], - Embedding: query_embedding, - Threshold: vector_threshold, - TopK: 5x over_retrieval - }) - - keywordResults = engine.Retrieve(RetrieveParams{ - RetrieverType: "keywords", - KnowledgeBaseIDs: [kb_id], - Query: query_text, - Threshold: keyword_threshold, - TopK: 5x over_retrieval - }) - - // 3. Merge with RRF (Reciprocal Rank Fusion) - merged = RRF(vectorResults, keywordResults) - - // 4. Rerank - final = Rerank(merged, rerank_model, top_k=10) - - return final -} -``` - -### 7. CompositeRetrieveEngine Routes to Backend -``` -CompositeRetrieveEngine.Retrieve(params) { - // params.RetrieverType = "vector" or "keywords" - - // Find engine that supports this type - for engineInfo in this.engineInfos { - if engineInfo.supports(params.RetrieverType) { - return engineInfo.engine.Retrieve(params) // Delegate - } - } -} - -// Backends that might handle it: -// - "vector" type → Elasticsearch, Qdrant, Milvus, etc. -// - "keywords" type → Elasticsearch, PostgreSQL, etc. -``` - -## Enumeration Reference - -### RetrieverType (what to search) -- `"vector"` - Semantic/embedding search -- `"keywords"` - Exact keyword/full-text search -- `"websearch"` - External web search - -### RetrieverEngineType (where to search) -- `"elasticsearch"` - ES backend (supports both vector & keywords) -- `"postgres"` - PostgreSQL (keywords) -- `"qdrant"` - Qdrant vector DB -- `"infinity"` - Infinity vector DB -- `"milvus"` - Milvus vector DB -- `"weaviate"` - Weaviate vector DB -- `"elasticfaiss"` - FAISS indices -- `"sqlite"` - SQLite (keywords) - -### SearchTargetType -- `"knowledge_base"` - Search entire KB -- `"knowledge"` - Search specific files/documents only - -### KnowledgeBase Type -- `"document"` - Standard documents -- `"faq"` - FAQ pairs -- `"wiki"` - Wiki pages - -## Tool Choices - -### Available Tools (Agents can use) -- `"knowledge_search"` → VectorRetrieverType (semantic) -- `"grep_chunks"` → KeywordsRetrieverType (exact match) -- `"list_knowledge_chunks"` → Direct doc access -- `"query_knowledge_graph"` → Graph search -- `"web_search"` → WebSearchRetrieverType -- `"wiki_search"` → Wiki search -- [... and more] - -**Agent decides which tool → System routes to right backend** - -## Configuration Precedence (lowest to highest) - -1. **System default** (hardcoded) - - `EmbeddingTopK = 50` - - `VectorThreshold = 0.15` - -2. **Knowledge Base config** - - `KB.EmbeddingModelID` (which embedding model) - - `KB.FAQConfig` (FAQ indexing strategy) - -3. **Tenant-level RetrievalConfig** - - `RetrievalConfig.EmbeddingTopK` - - `RetrievalConfig.VectorThreshold` - - `Tenant.EffectiveEngines` (which backends) - -4. **Agent-level config** - - `CustomAgentConfig.AllowedTools` - - `CustomAgentConfig.RerankModelID` - -5. **Session-level override** - - `SessionAgentConfig.KnowledgeBases` (restrict KBs) - -6. **Request-level** - - Tool parameters (e.g., explicit `knowledge_base_ids`) - -## Key Files - -| Layer | File | Key Classes | -|-------|------|-------------| -| **Model** | `internal/types/agent.go` | `AgentConfig`, `SessionAgentConfig` | -| **Model** | `internal/types/custom_agent.go` | `CustomAgent`, `CustomAgentConfig` | -| **Model** | `internal/types/knowledgebase.go` | `KnowledgeBase` | -| **Model** | `internal/types/retrieval_config.go` | `RetrievalConfig` | -| **Model** | `internal/types/retriever.go` | `RetrieverType`, `RetrieverEngineType` | -| **Model** | `internal/types/search.go` | `SearchTarget`, `SearchTargets` | -| **Service** | `internal/application/service/session_agent_qa.go` | `buildAgentConfig`, `buildSearchTargets` | -| **Service** | `internal/application/service/knowledgebase_search.go` | `HybridSearch` | -| **Service** | `internal/application/service/retriever/composite.go` | `CompositeRetrieveEngine` | -| **Tool** | `internal/agent/tools/knowledge_search.go` | Knowledge search tool impl | -| **Tool** | `internal/agent/tools/definitions.go` | Tool registry, tool names | -| **Pipeline** | `internal/application/service/chat_pipeline/search.go` | `PluginSearch` (chat pipeline) | - -## Common Scenarios - -### Q: How does an agent know which KBs to search? -**A:** `AgentConfig.SearchTargets` - pre-computed at request entry point, contains all KBs the agent has access to (after resolving CustomAgent + SessionAgentConfig + permissions) - -### Q: Can an agent search multiple KBs with one query? -**A:** Yes! If they share the same embedding model: -- `HybridSearch(kb1_id, params{KnowledgeBaseIDs: [kb1, kb2, kb3]})` -- Results are merged and reranked together - -### Q: How are vector vs keyword results combined? -**A:** RRF (Reciprocal Rank Fusion) - mathematical fusion of ranks, then reranked - -### Q: What decides: Elasticsearch vs Qdrant? -**A:** `Tenant.EffectiveEngines` - configured at tenant level, tells system which backend handles which retriever type - -### Q: Can an agent override its KB list? -**A:** Partially - `SessionAgentConfig.KnowledgeBases` can restrict (not expand) at session level - -### Q: Where is reranking configured? -**A:** -- Agent level: `CustomAgentConfig.RerankModelID` (which model) -- Tenant level: `RetrievalConfig.RerankTopK`, `RerankThreshold` (result quality thresholds) diff --git a/docs/AGENT_KB_RETRIEVAL_ARCHITECTURE.md b/docs/AGENT_KB_RETRIEVAL_ARCHITECTURE.md deleted file mode 100644 index ea81cc9e..00000000 --- a/docs/AGENT_KB_RETRIEVAL_ARCHITECTURE.md +++ /dev/null @@ -1,581 +0,0 @@ -# Agent/Bot Knowledge Base Integration Architecture - -## Overview -This document maps how agents/bots in WeKnora use knowledge bases, reference datasets, configure retrieval strategies, and execute the retrieval pipeline. - ---- - -## 1. AGENT/BOT MODEL DEFINITIONS - -### Primary Models - -#### `CustomAgent` (`internal/types/custom_agent.go`) -- **Role**: User-configurable AI agent (similar to GPTs) -- **Key Fields**: - - `ID`: Agent identifier (UUID for custom, or `builtin-*` prefix for built-in) - - `TenantID`: Owner tenant (composite primary key with ID) - - `Config`: `CustomAgentConfig` struct containing full configuration - - `IsBuiltin`: Boolean flag (built-in vs. custom) - -**Built-in Agent IDs**: -- `builtin-quick-answer`: RAG mode for Q&A -- `builtin-smart-reasoning`: ReAct mode for multi-step reasoning -- `builtin-deep-researcher`, `builtin-data-analyst`, etc. - -#### `AgentConfig` (`internal/types/agent.go`) -- **Role**: Runtime agent configuration (resolved from CustomAgent + Tenant config) -- **Key Fields**: - ```go - KnowledgeBases []string // Accessible KB IDs - KnowledgeIDs []string // Individual document IDs (within KBs) - SearchTargets SearchTargets // Pre-computed unified search targets (runtime only) - AllowedTools []string // List of tool names agent can use - WebSearchEnabled bool // Whether web search is available - MultiTurnEnabled bool // Multi-turn conversation support - RetrieveKBOnlyWhenMentioned bool // Only retrieve KB when explicitly mentioned with @ - Thinking *bool // Extended thinking mode support - LLMCallTimeout int // Single LLM call timeout in seconds - ``` - -#### `SessionAgentConfig` (`internal/types/agent.go`) -- **Role**: Session-level agent override -- **Immutable fields only**: `AgentModeEnabled`, `WebSearchEnabled`, `KnowledgeBases`, `KnowledgeIDs` -- Other configs read from Tenant at runtime - ---- - -## 2. KNOWLEDGE BASE BINDING - -### How Agents Reference Knowledge Bases - -**Path**: `internal/types/agent.go` → `AgentConfig.KnowledgeBases[]` - -1. **Agent Config Level**: - - `CustomAgentConfig.AvailableKnowledgeBases` contains KB IDs agent can access - - These are stored in the agent definition - -2. **Session Override Level**: - - `SessionAgentConfig.KnowledgeBases` can override/restrict agent's KB access - - Resolved at request entry point - -3. **Runtime Resolution** (`session_agent_qa.go:242`): - ```go - agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs = - s.resolveKnowledgeBases(ctx, req) - ``` - -### Knowledge Base Model (`internal/types/knowledgebase.go`) - -```go -type KnowledgeBase struct { - ID string // Unique identifier - Type string // "document", "faq", "wiki" - TenantID uint64 // Owner tenant - EmbeddingModelID string // Embedding model for vectors - ChunkingConfig ChunkingConfig // Document splitting strategy - FAQConfig *FAQConfig // FAQ-specific indexing options - WikiConfig *WikiConfig // Wiki-specific configuration - VLMConfig VLMConfig // Vision model for image processing - QuestionGenerationConfig *QuestionGenerationConfig // Auto-generate questions - // ... other metadata -} -``` - -**Knowledge Base Types**: -- `"document"`: Standard document-based KB -- `"faq"`: FAQ pairs (question-answer) -- `"wiki"`: Wiki pages with structured content - ---- - -## 3. RETRIEVAL STRATEGY CONFIGURATION - -### Global Retrieval Configuration (`internal/types/retrieval_config.go`) - -**Stored at**: Tenant level (JSONB column in `tenants` table) -**Managed via**: Settings UI at `/tenants/kv/retrieval-config` - -```go -type RetrievalConfig struct { - EmbeddingTopK int // Vector search result limit (default: 50) - VectorThreshold float64 // Min similarity score 0-1 (default: 0.15) - KeywordThreshold float64 // Min keyword match score 0-1 (default: 0.3) - RerankTopK int // Results after reranking (default: 10) - RerankThreshold float64 // Min rerank score (default: 0.2) - RerankModelID string // Rerank model to use -} -``` - -**Application**: Used by all chat/search operations in the tenant - -### Retriever Types (`internal/types/retriever.go`) - -```go -type RetrieverType string - -const ( - KeywordsRetrieverType RetrieverType = "keywords" // Exact/keyword matching - VectorRetrieverType RetrieverType = "vector" // Semantic/embedding search - WebSearchRetrieverType RetrieverType = "websearch" // Web search -) -``` - -### Retriever Engine Types (`internal/types/retriever.go`) - -```go -type RetrieverEngineType string - -const ( - PostgresRetrieverEngineType RetrieverEngineType = "postgres" // Native SQL - ElasticsearchRetrieverEngineType RetrieverEngineType = "elasticsearch" // ES - InfinityRetrieverEngineType RetrieverEngineType = "infinity" // Vector DB - ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss" // FAISS - QdrantRetrieverEngineType RetrieverEngineType = "qdrant" // Qdrant - MilvusRetrieverEngineType RetrieverEngineType = "milvus" // Milvus - WeaviateRetrieverEngineType RetrieverEngineType = "weaviate" // Weaviate - SQLiteRetrieverEngineType RetrieverEngineType = "sqlite" // SQLite -) -``` - -### Retriever Engine Configuration (Tenant-level) - -**Field**: `Tenant.EffectiveEngines` → `[]RetrieverEngineParams` - -```go -type RetrieverEngineParams struct { - RetrieverEngineType RetrieverEngineType // e.g., "elasticsearch" - RetrieverType RetrieverType // e.g., "vector" or "keywords" -} -``` - -**Determines**: Which physical backend (ES, Postgres, etc.) handles which retrieval type - ---- - -## 4. THE RETRIEVAL PIPELINE - -### Entry Point: Agent Execution - -**File**: `internal/application/service/session_agent_qa.go` - -**Flow**: -1. **Request arrives** with `QARequest` containing user query and agent ID -2. **Resolve Tenant**: Determine retrieval tenant (own tenant or shared agent tenant) -3. **Build AgentConfig** (line 210-298): - ```go - func (s *sessionService) buildAgentConfig(ctx context.Context, ...) { - // ... resolve KnowledgeBases and KnowledgeIDs - agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs = - s.resolveKnowledgeBases(ctx, req) - - // Build SearchTargets (next step) - searchTargets, _ := s.buildSearchTargets(ctx, agentTenantID, - agentConfig.KnowledgeBases, agentConfig.KnowledgeIDs) - agentConfig.SearchTargets = searchTargets - } - ``` - -### Stage 1: Build Search Targets (`session_knowledge_qa.go:393-486`) - -**Function**: `buildSearchTargets(ctx, tenantID, knowledgeBaseIDs, knowledgeIDs)` - -**Purpose**: Convert KnowledgeBase IDs and Knowledge IDs into unified SearchTargets - -**Output**: `SearchTargets` = `[]*SearchTarget` - -```go -type SearchTarget struct { - Type SearchTargetType // "knowledge_base" or "knowledge" - KnowledgeBaseID string // KB to search - TenantID uint64 // KB's tenant (for cross-tenant shared KBs) - KnowledgeIDs []string // Specific file IDs (only for "knowledge" type) -} -``` - -**Logic**: -``` -For each KnowledgeBaseID: - → Create SearchTarget(Type=knowledge_base, KnowledgeBaseID=id, TenantID=resolved) - -For each KnowledgeID: - → Find its parent KnowledgeBase - → If KB not already fully searched, create SearchTarget(Type=knowledge, - KnowledgeBaseID=parent, KnowledgeIDs=[kid1, kid2, ...]) -``` - -**Stored in**: `AgentConfig.SearchTargets` (runtime only, not persisted) - -### Stage 2: Agent Initialization - -**File**: `internal/application/service/agent_service.go:81-179` - -**Creates**: `AgentEngine` with: -- `AgentConfig` (with SearchTargets) -- Chat model -- Rerank model -- Event bus -- Context manager - -### Stage 3: Tool Execution - Knowledge Search - -**File**: `internal/agent/tools/knowledge_search.go` - -**Tool Definition**: -- **Name**: `"knowledge_search"` -- **Type**: `BaseTool` -- **Description**: Semantic/vector search for retrieving knowledge by meaning -- **Input**: 1-5 semantic queries (not raw text) -- **Retrieval Strategy**: Uses vector/semantic matching - -**Execution Flow** (Execute method): -1. Parse input queries -2. Get embedding model from KB -3. Compute query embeddings -4. Call HybridSearch with SearchTargets -5. Return ranked results - -### Stage 4: Hybrid Search (`knowledgebase_search.go:77-120`) - -**Function**: `HybridSearch(ctx, kbID, params)` - -**Parameters**: -- `kbID`: Primary KB (or first of multiple) -- `params.KnowledgeBaseIDs`: Override IDs (for multi-KB search with same embedding model) -- `params.QueryText`: Query string -- `params.VectorThreshold`: Min vector similarity -- `params.KeywordThreshold`: Min keyword score -- `params.MatchCount`: Desired results -- `params.DisableVectorMatch / DisableKeywordsMatch`: Optional disable flags - -**Process**: -``` -1. Determine search KBs (use params.KnowledgeBaseIDs if provided, else [kbID]) -2. Create CompositeRetrieveEngine with tenant's configured engines -3. For each KB: - a. Get embedding model - b. Compute query embedding (if vector search enabled) - c. Create vector + keyword retrieve jobs -4. Execute parallel retrieval across all engines -5. Deduplicate and merge results -6. Apply RRF (Reciprocal Rank Fusion) fusion -7. Rerank using rerank model -8. Return top results -``` - -### Stage 5: Composite Retrieval Engine (`internal/application/service/retriever/composite.go`) - -**Role**: Routes retrieval requests to correct backend based on RetrieverType - -**Structure**: -```go -type CompositeRetrieveEngine struct { - engineInfos []*engineInfo // Each maps RetrieverType to backend engine -} - -type engineInfo struct { - retrieveEngine interfaces.RetrieveEngineService - retrieverType []types.RetrieverType // "vector", "keywords", etc. -} -``` - -**Dispatch Logic** (`Retrieve` method): -```go -For each RetrieveParams: - Find first engineInfo that supports params.RetrieverType - Delegate to that engine's Retrieve method -``` - -**Created from Tenant config**: -```go -retrieveEngine, err := retriever.NewCompositeRetrieveEngine( - registry, - tenantInfo.GetEffectiveEngines() // []RetrieverEngineParams -) -``` - ---- - -## 5. SEARCH/RETRIEVAL TARGETS AT REQUEST LEVEL - -### ChatManage (Pipeline State) - -**File**: `internal/types/chat_manage.go` - -```go -type ChatManage struct { - // Immutable config (set at entry point) - PipelineRequest struct { - KnowledgeBaseIDs []string // User-selected KBs - KnowledgeIDs []string // User-selected specific files - SearchTargets SearchTargets // Pre-computed unified targets - VectorThreshold float64 // From tenant RetrievalConfig - KeywordThreshold float64 // From tenant RetrievalConfig - EmbeddingTopK int // From tenant RetrievalConfig - VectorDatabase string // Primary vector DB selection - } - // Mutable state - PipelineState struct { - SearchResult []*SearchResult // Raw search results - RerankResult []*SearchResult // After reranking - MergeResult []*SearchResult // After context merging - } -} -``` - -### SearchTargets Usage - -**Used by**: Chat pipeline plugins - -**File**: `internal/application/service/chat_pipeline/search.go` - -```go -func (p *PluginSearch) OnEvent(ctx, event, chatManage, next) error { - // Check if targets exist - if len(chatManage.SearchTargets) == 0 { - // No targets, skip KB search (unless web search enabled) - return nil - } - - // Execute KB search using SearchTargets - kbResults := p.searchByTargets(ctx, chatManage) - - // searchByTargets iterates SearchTargets and queries each - for _, target := range chatManage.SearchTargets { - // Determine which index to query based on target - results := p.knowledgeBaseService.HybridSearch( - ctx, target.KnowledgeBaseID, - types.SearchParams{ - KnowledgeBaseIDs: []string{target.KnowledgeBaseID}, - KnowledgeIDs: target.KnowledgeIDs, // Scoped if present - QueryText: chatManage.RewriteQuery, - // ... thresholds, top K from RetrievalConfig - } - ) - } -} -``` - ---- - -## 6. AGENT-LEVEL RETRIEVAL PREFERENCES - -### AgentConfig: Retrieval Preferences - -**Stored in CustomAgentConfig**: - -```go -type CustomAgentConfig struct { - // Tool selection - AllowedTools []string // e.g., ["knowledge_search", "web_search", ...] - - // Retrieval triggers - RetrieveKBOnlyWhenMentioned bool // @mention required for KB search - - // Search strategy - WebSearchEnabled bool // Enable web search tool - WebSearchMaxResults int // Max web results to return - WebSearchProviderID string // Which web search provider - - // Model selection for retrieval - RerankModelID string // Rerank model for search results - - // History management - MultiTurnEnabled bool // Use conversation history - HistoryTurns int // How many previous turns to keep - - // Context management - RetainRetrievalHistory bool // Keep wiki_read_page results across turns -} -``` - -### Agent Tool Definitions - -**File**: `internal/agent/tools/definitions.go` - -**Key Tools for Knowledge Retrieval**: - -1. **`knowledge_search`** (Semantic Search) - - Purpose: Vector/embedding-based semantic search - - Input: 1-5 semantic queries (not raw text) - - Backends: Vector retrieval engines - - RetrievalType: `VectorRetrieverType` - -2. **`grep_chunks`** (Keyword Search) - - Purpose: Exact keyword/literal matching - - Input: Keywords to find - - Backends: Keyword retrieval engines (ES, SQL) - - RetrievalType: `KeywordsRetrieverType` - -3. **`list_knowledge_chunks`** (List Chunks) - - Purpose: Browse document chunks - - Input: KB ID, document ID - - Backends: Direct document lookup - -4. **`wiki_search`** (Wiki Search) - - Purpose: Search within wiki pages - - Input: Query - - Backends: Wiki-specific retrieval - -5. **`web_search`** (Web Search) - - Purpose: Search the internet - - Input: Query - - Backends: External web search provider - - RetrievalType: `WebSearchRetrieverType` - -**Default Allowed Tools**: -```go -[]string{ - ToolThinking, - ToolTodoWrite, - ToolKnowledgeSearch, // Vector search - ToolGrepChunks, // Keyword search - ToolListKnowledgeChunks, - ToolWebSearch, - ToolWebFetch, - ToolFinalAnswer, -} -``` - ---- - -## 7. KEY DECISION FLOWS - -### Decision 1: Which KB to Search? -1. Agent has `AgentConfig.SearchTargets` -2. When agent calls tool, it optionally specifies `knowledge_base_ids` -3. If not specified, uses all SearchTargets -4. Explicit KB param overrides agent defaults - -### Decision 2: Which Retrieval Strategy? -1. Agent decides: calls `knowledge_search` (vector) or `grep_chunks` (keyword) -2. Or both sequentially with different queries -3. Or combines with `query_knowledge_graph` (graph search) -4. Tool makes the strategic choice, not the system - -### Decision 3: Which Backend? -1. `RetrieveParams.RetrieverType` set by tool -2. CompositeRetrieveEngine looks up configured engines -3. Finds engine that supports that RetrieverType -4. Delegates to that backend - -### Decision 4: Result Quality (Reranking)? -1. `RetrievalConfig.RerankModelID` specifies reranker -2. HybridSearch uses it to rerank combined results -3. Threshold applied: `RetrievalConfig.RerankThreshold` -4. Top-K applied: `RetrievalConfig.RerankTopK` - ---- - -## 8. DATA FLOW DIAGRAM - -``` -Request - ↓ -QARequest (agent ID, query, KB IDs) - ↓ -BuildAgentConfig - ├→ Resolve KnowledgeBases from agent + session override - ├→ Resolve KnowledgeIDs (individual documents) - ├→ BuildSearchTargets (converts KB IDs → SearchTargets) - └→ AgentConfig.SearchTargets = [SearchTarget{...}, ...] - ↓ -CreateAgentEngine(AgentConfig, ChatModel, RerankModel) - ├→ Register tools (knowledge_search, grep_chunks, web_search, ...) - └→ Tool registry has access to SearchTargets - ↓ -Agent Execution Loop (ReAct) - ↓ -Agent calls tool (e.g., knowledge_search) - ├→ Tool receives SearchTargets from AgentConfig - ├→ Optionally filters by knowledge_base_ids param - └→ Computes query embedding - ↓ -HybridSearch(kb_id, params) - ├→ Create CompositeRetrieveEngine with tenant engines - ├→ Parallel: Vector search + Keyword search - ├→ Both call Retrieve() which dispatches to backends - └→ Merge + Rerank + Return - ↓ -Backend (ES, Postgres, Qdrant, etc.) - ├→ Vector search via embedding DB - ├→ Keyword search via ES/SQL - └→ Return scored results - ↓ -RRF Fusion (combine vector + keyword) - ↓ -Reranker (optional) - ↓ -Top-K Results - ↓ -Tool Result → Agent Thought/Action Loop -``` - ---- - -## 9. CONFIGURATION PRECEDENCE - -For any retrieval operation: - -1. **Agent-level**: - - `CustomAgentConfig.AllowedTools` (which tools available) - - `CustomAgentConfig.RetrieveKBOnlyWhenMentioned` (when to retrieve) - - `CustomAgentConfig.KnowledgeBases` (which KBs) - -2. **Session-level override**: - - `SessionAgentConfig.KnowledgeBases` (restrict agent's KBs) - -3. **Request-level**: - - Query string, optional KB filter, images, etc. - -4. **Tenant-level**: - - `RetrievalConfig` (thresholds, top-K, reranker) - - `Tenant.EffectiveEngines` (which backends for vector/keyword) - -5. **Knowledge Base-level**: - - `KnowledgeBase.EmbeddingModelID` (which embedding model) - - `KnowledgeBase.Type` (document vs FAQ vs wiki) - - `KnowledgeBase.FAQConfig`, `WikiConfig` (type-specific config) - ---- - -## 10. KEY FILES SUMMARY - -| File | Purpose | -|------|---------| -| `internal/types/agent.go` | `AgentConfig`, `SessionAgentConfig` | -| `internal/types/custom_agent.go` | `CustomAgent`, `CustomAgentConfig` | -| `internal/types/knowledgebase.go` | `KnowledgeBase`, KB types (document/faq/wiki) | -| `internal/types/retrieval_config.go` | `RetrievalConfig` (tenant-level thresholds) | -| `internal/types/retriever.go` | `RetrieverType`, `RetrieverEngineType` enums | -| `internal/types/search.go` | `SearchTarget`, `SearchTargets`, `SearchResult` | -| `internal/application/service/session_agent_qa.go` | Agent QA entry point, `buildAgentConfig`, `buildSearchTargets` | -| `internal/application/service/knowledgebase_search.go` | `HybridSearch` orchestration | -| `internal/application/service/retriever/composite.go` | `CompositeRetrieveEngine` (backend dispatch) | -| `internal/agent/tools/knowledge_search.go` | Knowledge search tool definition | -| `internal/agent/tools/definitions.go` | Tool names and available tools list | -| `internal/application/service/chat_pipeline/search.go` | Chat pipeline search plugin | - ---- - -## Summary - -**Agents bind to KBs via**: -- `CustomAgent.Config.AvailableKnowledgeBases` + `CustomAgent.Config.AvailableKnowledgeIDs` -- Resolved to `AgentConfig.KnowledgeBases` + `AgentConfig.KnowledgeIDs` at runtime -- Converted to `AgentConfig.SearchTargets` for unified multi-KB querying - -**Retrieval strategy is determined by**: -- **Tool choice**: Agent decides to call `knowledge_search` (vector) vs `grep_chunks` (keyword) -- **Tenant config**: `RetrievalConfig` sets thresholds, top-K, and rerank model -- **Tenant engines**: `Tenant.EffectiveEngines` specifies which backends handle which retriever types -- **KB model**: `KnowledgeBase.EmbeddingModelID`, type, and type-specific configs - -**Retrieval pipeline**: -1. Agent executes and calls a retrieval tool -2. Tool computes embedding or keywords -3. Tool calls `HybridSearch` with SearchTargets -4. `HybridSearch` creates `CompositeRetrieveEngine` from tenant engines -5. `CompositeRetrieveEngine` dispatches to appropriate backend based on RetrieverType -6. Results are fused (RRF), reranked, and returned -7. Agent uses results in reasoning loop - diff --git a/docs/AGENT_KB_RETRIEVAL_FLOW_DEEP_DIVE.md b/docs/AGENT_KB_RETRIEVAL_FLOW_DEEP_DIVE.md deleted file mode 100644 index 4e20196d..00000000 --- a/docs/AGENT_KB_RETRIEVAL_FLOW_DEEP_DIVE.md +++ /dev/null @@ -1,910 +0,0 @@ -# Agent/KB Retrieval Flow - Deep Dive Analysis - -## Overview - -This document provides a technical deep-dive into how WeKnora agents use knowledge bases for information retrieval. It traces the complete flow from agent configuration through retrieval execution, showing exactly how agents dynamically select which knowledge bases to search and how retrieval strategies are applied. - -## Table of Contents - -1. [Configuration Hierarchy](#configuration-hierarchy) -2. [Request Entry Point](#request-entry-point) -3. [Search Target Resolution](#search-target-resolution) -4. [Runtime Agent Configuration](#runtime-agent-configuration) -5. [Tool Registration with SearchTargets](#tool-registration-with-searchtargets) -6. [Retrieval Pipeline Execution](#retrieval-pipeline-execution) -7. [Cross-Tenant KB Sharing](#cross-tenant-kb-sharing) -8. [Configuration Precedence](#configuration-precedence) -9. [Key Decision Points](#key-decision-points) - ---- - -## Configuration Hierarchy - -### Three-Level Configuration System - -WeKnora uses a three-tier configuration system that resolves from most specific to most general: - -``` -┌─────────────────────────────────────────────┐ -│ 1. Request-Level Override (Most Specific) │ -│ - SummaryModelID, KnowledgeBaseIDs, etc. │ -│ - Session-level web search enabled flag │ -└─────────────────────────────────────────────┘ - ↓ (if not provided) -┌─────────────────────────────────────────────┐ -│ 2. Agent-Level Configuration (CustomAgent) │ -│ - CustomAgent.Config.ModelID │ -│ - CustomAgent.Config.KBSelectionMode │ -│ - CustomAgent.Config.AllowedTools │ -│ - CustomAgent.Config.Temperature, etc. │ -└─────────────────────────────────────────────┘ - ↓ (if not provided) -┌─────────────────────────────────────────────┐ -│ 3. Tenant-Level Defaults (Most General) │ -│ - RetrievalConfig thresholds │ -│ - Tenant default models │ -│ - WebSearchConfig │ -└─────────────────────────────────────────────┘ -``` - -### Configuration Objects - -#### CustomAgent (Persistent, DB-Stored) -Located: `internal/types/custom_agent.go` - -```go -type CustomAgent struct { - ID string // UUID or builtin-* ID - Name string - TenantID uint64 // Agent owner (composite key) - Config CustomAgentConfig // JSONB configuration - CreatedAt time.Time -} - -type CustomAgentConfig struct { - // KB Selection - KBSelectionMode string // "all", "selected", or "none" - KnowledgeBases []string // IDs when mode="selected" - - // Retrieval - ModelID string - RerankModelID string - AllowedTools []string // Which tools can be called - - // Strategy - EmbeddingTopK int - VectorThreshold float64 - KeywordThreshold float64 - RerankTopK int - RerankThreshold float64 - - // Agent Mode - MaxIterations int - Temperature float64 - MultiTurnEnabled bool - HistoryTurns int - - // Advanced - RetrieveKBOnlyWhenMentioned bool // Only search KB if @mentioned - WebSearchEnabled bool - WebSearchMaxResults int -} -``` - -#### AgentConfig (Runtime Resolution) -Located: `internal/types/agent.go` - -This is built at request time from CustomAgent + TenantInfo: - -```go -type AgentConfig struct { - MaxIterations int - AllowedTools []string - Temperature float64 - KnowledgeBases []string // Resolved KB IDs - KnowledgeIDs []string // Resolved file IDs - SystemPrompt string - WebSearchEnabled bool - WebSearchMaxResults int - MultiTurnEnabled bool - HistoryTurns int - SearchTargets SearchTargets // ← Pre-computed HERE - RetrieveKBOnlyWhenMentioned bool - // ... more fields -} -``` - -#### RetrievalConfig (Tenant-Level) -Located: `internal/types/retrieval_config.go` - -Stored as JSONB on tenants table: - -```go -type RetrievalConfig struct { - EmbeddingTopK int // default: 50 - VectorThreshold float64 // default: 0.15 - KeywordThreshold float64 // default: 0.3 - RerankTopK int // default: 10 - RerankThreshold float64 // default: 0.2 - RerankModelID string -} -``` - ---- - -## Request Entry Point - -### AgentQA Handler Flow - -Located: `internal/application/service/session_agent_qa.go` - -**Key Function**: `func (s *sessionService) AgentQA(ctx context.Context, req *types.QARequest, eventBus *event.EventBus) error` - -Entry point receives: -- `req.CustomAgent` - The agent being used (required for AgentQA) -- `req.Query` - User question -- `req.KnowledgeBaseIDs` - Optional @mentions (overrides agent config) -- `req.KnowledgeIDs` - Specific file @mentions -- `req.Session.TenantID` - Session owner tenant -- `req.WebSearchEnabled` - Session-level web search override - -### Sequence of Operations - -``` -1. Validate customAgent is provided (line 36) - ↓ -2. Resolve retrieval tenant ID (line 42) - - Returns agent's tenant if agent is from different org - - Otherwise returns session tenant - ↓ -3. Load tenant info (lines 51-62) - - May fetch agent's tenant if different from session tenant - ↓ -4. Build runtime AgentConfig (line 68) - - This is where SearchTargets are computed - ↓ -5. Resolve effective model ID (line 79) - ↓ -6. Create agent engine (line 153) - - Passes AgentConfig with SearchTargets - ↓ -7. Execute agent (line 191) -``` - ---- - -## Search Target Resolution - -### What are SearchTargets? - -Located: `internal/types/search.go` - -```go -type SearchTarget struct { - Type SearchTargetType // "knowledge_base" or "knowledge" - KnowledgeBaseID string // KB to search - TenantID uint64 // Which tenant owns this KB - KnowledgeIDs []string // Specific files (only for "knowledge" type) -} - -type SearchTargets []*SearchTarget -``` - -**Two Target Types**: -- `SearchTargetTypeKnowledgeBase` ("knowledge_base"): Search entire KB -- `SearchTargetTypeKnowledge` ("knowledge"): Search specific files - -### buildSearchTargets Function - -Located: `internal/application/service/session_knowledge_qa.go:393` - -This function is **critical** - it's called once at request entry and pre-computes all search targets. - -**Inputs**: -- `knowledgeBaseIDs` - Full KB IDs to search -- `knowledgeIDs` - Specific file IDs to search - -**Logic**: - -``` -PASS 1: Full Knowledge Bases -├─ Batch-fetch KB records -├─ For each KB: -│ ├─ Resolve actual TenantID (own, shared, or agent's) -│ ├─ Check user has permission (for shared KBs) -│ └─ Create SearchTarget with Type=KNOWLEDGE_BASE -└─ Track which KBs are fully covered - -PASS 2: Specific Files (KnowledgeIDs) -├─ Batch-fetch Knowledge records -├─ For each Knowledge: -│ ├─ Find its parent KnowledgeBaseID -│ ├─ Skip if parent KB already fully covered -│ ├─ Group by KnowledgeBaseID -│ └─ Create SearchTarget with Type=KNOWLEDGE + KnowledgeIDs list -└─ Result: One SearchTarget per unique KB, with specific file lists -``` - -**Key Algorithm Detail**: - -If user passes: -``` -KnowledgeBaseIDs: ["kb-1", "kb-2"] -KnowledgeIDs: ["file-3", "file-4", "file-5"] -``` - -Where file-3 and file-4 are in kb-1, and file-5 is in kb-3: - -Result SearchTargets: -``` -[ - {Type: KNOWLEDGE_BASE, KnowledgeBaseID: "kb-1"}, // Entire kb-1 - {Type: KNOWLEDGE_BASE, KnowledgeBaseID: "kb-2"}, // Entire kb-2 - {Type: KNOWLEDGE, KnowledgeBaseID: "kb-3", KnowledgeIDs: ["file-5"]} -] -``` - -Note: file-3 and file-4 are NOT created as separate targets because kb-1 is already being fully searched. - ---- - -## Runtime Agent Configuration - -### buildAgentConfig Function - -Located: `internal/application/service/session_agent_qa.go:210` - -**Input**: `CustomAgent` + `TenantInfo` + `QARequest` - -**Output**: Runtime `AgentConfig` with pre-computed SearchTargets - -**Steps**: - -```go -1. Create base AgentConfig from CustomAgent.Config - - Copy: MaxIterations, Temperature, WebSearchEnabled, etc. - - Copy AllowedTools (or use defaults if empty) - -2. Call EnsureDefaults() (line 65) - - Sets missing values to hardcoded defaults - -3. Resolve knowledge base IDs (line 242) - agentConfig.KnowledgeBases = s.resolveKnowledgeBases(ctx, req) - - This function (session_qa_helpers.go:19) implements KB resolution priority: - - Priority 1: Explicit @mentions in request - if req.KnowledgeBaseIDs or req.KnowledgeIDs provided - └─ Use those (but validate against agent scope for shared agents) - - Priority 2: RetrieveKBOnlyWhenMentioned override - if customAgent.Config.RetrieveKBOnlyWhenMentioned && no @mention - └─ Clear the KB list (KB disabled for this request) - - Priority 3: Agent's configured KBs - else - └─ Resolve based on KBSelectionMode: - ├─ "all": List all KBs (own + shared for non-shared agents) - ├─ "selected": Use customAgent.Config.KnowledgeBases - ├─ "none": Return empty - └─ default: Fallback to KnowledgeBases for backward compat - -4. Merge with tenant config (lines 260-273) - - Set WebSearchMaxResults from tenant if not set - - Resolve web search provider ID - -5. Build SearchTargets (line 286) - searchTargets, err := s.buildSearchTargets(ctx, agentTenantID, - agentConfig.KnowledgeBases, - agentConfig.KnowledgeIDs) - agentConfig.SearchTargets = searchTargets -``` - -### resolveKnowledgeBasesFromAgent Function - -Located: `internal/application/service/session_knowledge_qa.go:320` - -This function implements the KB selection mode logic: - -```go -func (s *sessionService) resolveKnowledgeBasesFromAgent( - ctx context.Context, - customAgent *types.CustomAgent, - sessionTenantID uint64, -) []string { - switch customAgent.Config.KBSelectionMode { - - case "all": - // Fetch all KBs from agent's tenant - allKBs, _ := s.knowledgeBaseService.ListKnowledgeBases(ctx) - - // For non-shared agents: also include user's shared KBs - isSharedAgent := sessionTenantID != 0 && - sessionTenantID != customAgent.TenantID - if !isSharedAgent { - sharedList, _ := s.kbShareService.ListSharedKnowledgeBases( - ctx, userID, tenantID) - // Merge shared KBs into allKBs - } - return allKBIDs - - case "selected": - // Use explicitly configured list - return customAgent.Config.KnowledgeBases - - case "none": - return nil - - default: - // Backward compat: use configured KBs - return customAgent.Config.KnowledgeBases - } -} -``` - -**Critical Detail**: Shared agent detection (line 346) -```go -isSharedAgent := sessionTenantID != 0 && - sessionTenantID != customAgent.TenantID -``` - -When `isSharedAgent` is true: -- ONLY use agent's tenant KBs -- DO NOT include user's shared KBs (security) -- This prevents data leak across organizations - ---- - -## Tool Registration with SearchTargets - -### Where SearchTargets Flow - -The pre-computed SearchTargets from AgentConfig are passed to EVERY tool that needs to search: - -Located: `internal/application/service/agent_service.go:318` - -**Tool Registration**: - -```go -func (s *agentService) registerTools(ctx context.Context, - registry *tools.ToolRegistry, - config *types.AgentConfig, // ← Contains SearchTargets - rerankModel rerank.Reranker, - chatModel chat.Chat, - sessionID string) error { - - // ... determine allowedTools ... - - for _, toolName := range allowedTools { - switch toolName { - - case tools.ToolKnowledgeSearch: - // SearchTargets passed directly to tool - toolToRegister = tools.NewKnowledgeSearchTool( - s.knowledgeBaseService, - s.knowledgeService, - s.chunkService, - config.SearchTargets, // ← HERE - rerankModel, - chatModel, - s.cfg, - ) - - case tools.ToolGrepChunks: - toolToRegister = tools.NewGrepChunksTool( - s.db, - config.SearchTargets, // ← HERE - ) - - case tools.ToolListKnowledgeChunks: - toolToRegister = tools.NewListKnowledgeChunksTool( - s.knowledgeService, - s.chunkService, - config.SearchTargets, // ← HERE - ) - - // ... similar for other KB tools ... - } - } -} -``` - -### KnowledgeSearchTool Initialization - -Located: `internal/agent/tools/knowledge_search.go:133` - -```go -type KnowledgeSearchTool struct { - BaseTool - knowledgeBaseService interfaces.KnowledgeBaseService - knowledgeService interfaces.KnowledgeService - chunkService interfaces.ChunkService - searchTargets types.SearchTargets // ← Stored here - rerankModel rerank.Reranker - chatModel chat.Chat - config *config.Config -} - -func NewKnowledgeSearchTool(..., searchTargets types.SearchTargets, ...) { - return &KnowledgeSearchTool{ - // ... - searchTargets: searchTargets, // ← Captured at creation - // ... - } -} -``` - -### Tool Execution Uses SearchTargets - -When agent calls knowledge_search tool at runtime: - -Located: `internal/agent/tools/knowledge_search.go:155` - -```go -func (t *KnowledgeSearchTool) Execute( - ctx context.Context, - args json.RawMessage) (*types.ToolResult, error) { - - // Parse input - var input KnowledgeSearchInput - json.Unmarshal(args, &input) - - // Use pre-computed search targets - searchTargets := t.searchTargets // ← Line 180 - - // Allow user to optionally filter to specific KBs - if len(input.KnowledgeBaseIDs) > 0 { - // Filter searchTargets to only include user-specified KBs - userKBSet := make(map[string]bool) - for _, kbID := range input.KnowledgeBaseIDs { - userKBSet[kbID] = true - } - var filteredTargets types.SearchTargets - for _, target := range t.searchTargets { - if userKBSet[target.KnowledgeBaseID] { - filteredTargets = append(filteredTargets, target) - } - } - searchTargets = filteredTargets - } - - // Get all KB IDs from targets - kbIDs := searchTargets.GetAllKnowledgeBaseIDs() // Line 205 - - // Execute concurrent search using targets - allResults := t.concurrentSearchByTargets( - ctx, - input.Queries, - searchTargets, // ← Passed to search executor - topK, - vectorThreshold, - keywordThreshold, - kbTypeMap) - - // ... reranking, MMR, dedup ... - - return toolResult, nil -} -``` - ---- - -## Retrieval Pipeline Execution - -### Two Parallel Search Paths - -In the chat pipeline (non-agent mode): - -Located: `internal/application/service/chat_pipeline/search.go:61` - -```go -func (p *PluginSearch) OnEvent(ctx context.Context, - eventType types.EventType, - chatManage *types.ChatManage, - next func() *PluginError) *PluginError { - - // Run KB search and web search CONCURRENTLY - var wg sync.WaitGroup - - // Goroutine 1: Knowledge Base Search - go func() { - kbResults := p.searchByTargets(ctx, chatManage) - }() - - // Goroutine 2: Web Search - go func() { - webResults := p.searchWebIfEnabled(ctx, chatManage) - }() -} -``` - -### SearchByTargets Execution - -Located: `internal/application/service/chat_pipeline/search.go:312` - -This function orchestrates KB retrieval using SearchTargets: - -```go -func (p *PluginSearch) searchByTargets( - ctx context.Context, - chatManage *types.ChatManage) []*types.SearchResult { - - // Step 1: Group targets by embedding model (optimization) - // Targets with same embedding model share one embedding computation - groups := groupTargetsByEmbeddingModel( - ctx, - chatManage.SearchTargets, - p.knowledgeBaseService) - - // Step 2: For each model group, execute search - for modelKey, targets := range groups { - // Compute embedding once for all targets in group - queryEmbedding, _ := p.knowledgeBaseService.GetQueryEmbedding( - ctx, targets[0].KnowledgeBaseID, queryText) - - // Separate full-KB from specific-knowledge targets - var fullKBIDs []string - var knowledgeTargets []*types.SearchTarget - for _, t := range targets { - if t.Type == types.SearchTargetTypeKnowledgeBase { - fullKBIDs = append(fullKBIDs, t.KnowledgeBaseID) - } else { - knowledgeTargets = append(knowledgeTargets, t) - } - } - - // Execute combined search for full KBs (all in one call) - if len(fullKBIDs) > 0 { - params := types.SearchParams{ - QueryText: queryText, - QueryEmbedding: queryEmbedding, - KnowledgeBaseIDs: fullKBIDs, // ← Multiple KBs combined - VectorThreshold: chatManage.VectorThreshold, - KeywordThreshold: chatManage.KeywordThreshold, - MatchCount: chatManage.EmbeddingTopK, - } - res, _ := p.knowledgeBaseService.HybridSearch( - ctx, fullKBIDs[0], params) - // ← HybridSearch with multiple KBs returns unified results - } - - // Execute individual search for specific-knowledge targets - for _, target := range knowledgeTargets { - p.searchSingleTarget(ctx, chatManage, target, - queryText, queryEmbedding, ...) - } - } - - return allResults -} -``` - -### HybridSearch with Multiple KBs - -Located: `internal/application/service/knowledgebase_search.go` - -The HybridSearch function orchestrates parallel vector + keyword retrieval: - -```go -func (s *Service) HybridSearch( - ctx context.Context, - mainKBID string, - params types.SearchParams) ([]*types.SearchResult, error) { - - // params.KnowledgeBaseIDs can contain MULTIPLE KB IDs - searchKBIDs := params.KnowledgeBaseIDs - if len(searchKBIDs) == 0 { - searchKBIDs = []string{mainKBID} - } - - // Create CompositeRetrieveEngine for all KBs - engine := retriever.NewCompositeRetrieveEngine( - s.retrieverRegistry, - s.getTenantRetrieverEngines(ctx)) - - // Execute PARALLEL vector + keyword search - var wg sync.WaitGroup - - // Vector search - go func() { - vectorResults, _ := engine.Retrieve(ctx, - types.RetrieveParams{ - RetrieverType: types.VectorRetrieverType, - KnowledgeBaseIDs: searchKBIDs, // All KBs - EmbeddingTopK: params.MatchCount * 5, // Over-retrieve - QueryEmbedding: params.QueryEmbedding, - VectorThreshold: params.VectorThreshold, - }) - }() - - // Keyword search - go func() { - keywordResults, _ := engine.Retrieve(ctx, - types.RetrieveParams{ - RetrieverType: types.KeywordsRetrieverType, - KnowledgeBaseIDs: searchKBIDs, // All KBs - EmbeddingTopK: params.MatchCount * 5, - QueryText: params.QueryText, - KeywordThreshold: params.KeywordThreshold, - }) - }() - - wg.Wait() - - // Merge using RRF (Reciprocal Rank Fusion) - mergedResults := rrf(vectorResults, keywordResults) - - // Rerank - if rerankModel != nil { - rerankedResults := rerank(mergedResults, - params.QueryText, - rerankModel) - } - - return rerankedResults, nil -} -``` - ---- - -## Cross-Tenant KB Sharing - -### Shared Agent Scenario - -When `sessionTenantID != customAgent.TenantID`: - -Located: `internal/application/service/session_qa_helpers.go:37` - -```go -// When using a shared agent, restrict @mentions to the agent's allowed KB scope -// to prevent users from injecting KB/knowledge IDs outside the agent's configured range. -if customAgent != nil && - req.Session != nil && - req.Session.TenantID != customAgent.TenantID { - kbIDs, knowledgeIDs = s.restrictMentionsToAgentScope( - ctx, customAgent, req.Session.TenantID, kbIDs, knowledgeIDs) -} -``` - -### Permission Validation - -Located: `internal/application/service/session_knowledge_qa.go:393` - -In buildSearchTargets: - -```go -// For each KB in the request -kb := kbByID[kbID] -if kb == nil { - // Not found, default to session tenant - kbTenantMap[kbID] = tenantID -} else if kb.TenantID == tenantID { - // Own KB - kbTenantMap[kbID] = tenantID -} else if s.kbShareService != nil && userID != "" { - // Cross-tenant shared KB - check permission - hasAccess, _ := s.kbShareService.HasKBPermission( - ctx, kbID, userID, types.OrgRoleViewer) - if hasAccess { - kbTenantMap[kbID] = kb.TenantID // Use original owner - } else { - kbTenantMap[kbID] = tenantID // Fallback - } -} else { - kbTenantMap[kbID] = tenantID -} -``` - -### SearchTarget Tenant Tracking - -Each SearchTarget includes TenantID: - -```go -targets = append(targets, &types.SearchTarget{ - Type: types.SearchTargetTypeKnowledgeBase, - KnowledgeBaseID: kbID, - TenantID: kbTenantMap[kbID], // ← Track owner -}) -``` - -The retrieval system uses this to scope searches correctly. - ---- - -## Configuration Precedence - -### Complete Priority Chain - -``` -Request Layer - └─ req.SummaryModelID (overrides agent model) - └─ req.KnowledgeBaseIDs (overrides agent KB config) - └─ req.KnowledgeIDs (specific files) - └─ req.WebSearchEnabled (request-level override) - - ↓ (if not provided) - -Agent Layer (CustomAgent.Config) - └─ ModelID (chat model for agent) - └─ RerankModelID (rerank model) - └─ AllowedTools (which tools available) - └─ KBSelectionMode + KnowledgeBases - └─ Temperature, MaxIterations - └─ EmbeddingTopK, VectorThreshold, KeywordThreshold - └─ WebSearchEnabled, WebSearchMaxResults - └─ RetrieveKBOnlyWhenMentioned - └─ SystemPrompt, MultiTurnEnabled - - ↓ (if not provided) - -Tenant Layer (Tenant.RetrievalConfig) - └─ EmbeddingTopK (default: 50) - └─ VectorThreshold (default: 0.15) - └─ KeywordThreshold (default: 0.3) - └─ RerankTopK (default: 10) - └─ RerankThreshold (default: 0.2) - └─ RerankModelID - - ↓ (if not provided) - -System Defaults - └─ EmbeddingTopK: 50 - └─ VectorThreshold: 0.15 - └─ KeywordThreshold: 0.3 - └─ RerankTopK: 10 - └─ Temperature: 0.7 - └─ MaxIterations: 10 -``` - -### Example: KBSelectionMode Resolution - -```go -// resolveKnowledgeBases (session_qa_helpers.go:19) - -hasExplicitMention := len(kbIDs) > 0 || len(knowledgeIDs) > 0 - -if hasExplicitMention { - // Priority 1: Use request-specified targets - kbIDs, knowledgeIDs = req.KnowledgeBaseIDs, req.KnowledgeIDs -} else if customAgent.Config.RetrieveKBOnlyWhenMentioned { - // Priority 2: Mode flag disables KB for this request - kbIDs, knowledgeIDs = nil, nil -} else { - // Priority 3: Use agent's configured KBs based on mode - kbIDs = resolveKnowledgeBasesFromAgent(customAgent, sessionTenantID) -} -``` - ---- - -## Key Decision Points - -### 1. When is SearchTargets Computed? - -**Answer**: Once at request entry, in `buildAgentConfig()` (line 286) - -**Why**: Avoids recomputation on every tool call - -**Flow**: -``` -AgentQA() → buildAgentConfig() → buildSearchTargets() → agentConfig.SearchTargets - ↓ - CreateAgentEngine() → registerTools() → - All tools capture SearchTargets at init -``` - -### 2. How Does Agent Choose Which Tool to Call? - -**Answer**: The LLM decides which tool, but only allowed ones are available - -``` -// agent_service.go:328-334 -var allowedTools []string -if len(config.AllowedTools) > 0 { - allowedTools = config.AllowedTools // ← Agent specifies -} else { - allowedTools = tools.DefaultAllowedTools() -} - -// ← These are the ONLY tools available to LLM -``` - -The agent.AllowedTools directly constrains what the LLM can call. - -### 3. Can Agent Override Knowledge Bases? - -**Partially - Depends on Configuration**: - -``` -If RetrieveKBOnlyWhenMentioned == true: - └─ KB searches ONLY work if user explicitly mentions KB with @ - └─ No automatic KB retrieval - -If KBSelectionMode == "selected": - └─ Agent is LOCKED to configured KnowledgeBases - └─ @mentions outside this set are rejected - └─ Exception: Within search tool, user can filter to subset - -If KBSelectionMode == "all": - └─ Agent CAN search any KB user has access to - └─ But searchTargets still pre-computed from "all" -``` - -### 4. What if CustomAgent.Config.AllowedTools is empty? - -**Answer**: Use defaults (line 333) - -```go -if len(config.AllowedTools) > 0 { - allowedTools = config.AllowedTools -} else { - allowedTools = tools.DefaultAllowedTools() // ← USES DEFAULTS -} -``` - -Default allowed tools: `ToolThinking, ToolTodoWrite, ToolKnowledgeSearch, ToolGrepChunks, ToolListKnowledgeChunks, ToolQueryKnowledgeGraph, ToolGetDocumentInfo, ToolDatabaseQuery, ToolDataAnalysis, ToolDataSchema, ToolFinalAnswer` - -### 5. How are Multiple KBs Searched Efficiently? - -**Answer**: Group by embedding model, batch the search - -Located: `search.go:312` - -``` -1. Group SearchTargets by embedding model identity - └─ Targets with same model = one embedding computation - -2. For each group: - a. Compute query embedding ONCE - b. Separate full-KB targets from specific-knowledge targets - c. Combined search: HybridSearch(allFullKBIDs) - └─ Searches ALL KBs in ONE retrieval call - └─ Returns merged results from all KBs - d. Individual search: One HybridSearch per specific-knowledge target -``` - -**Result**: If 5 KBs use same embedding model: -- Traditional: 5 embedding computations, 5 retrieval calls -- Optimized: 1 embedding computation, 2 retrieval calls (combined full + individuals) - ---- - -## Summary - -### Configuration Resolution Flow - -``` -QARequest - ↓ -resolveKnowledgeBases() - ├─ Check: explicit @mention? → YES: use request KBs - ├─ Check: RetrieveKBOnlyWhenMentioned? → YES: clear KBs - └─ Otherwise: resolveKnowledgeBasesFromAgent() - ├─ KBSelectionMode="all" → List all (own + shared) - ├─ KBSelectionMode="selected" → Use CustomAgent.Config.KnowledgeBases - └─ KBSelectionMode="none" → Empty list - ↓ -buildSearchTargets(ctx, tenantID, kbIDs, knowledgeIDs) - ├─ PASS 1: Full KB → SearchTarget(KNOWLEDGE_BASE, kbID) - ├─ PASS 2: Specific files → SearchTarget(KNOWLEDGE, kbID, [fileIDs]) - └─ Track TenantID per target (for cross-tenant sharing) - ↓ -agentConfig.SearchTargets = results - ↓ -registerTools(..., agentConfig) - └─ Each tool receives: agentConfig.SearchTargets - ↓ -At runtime, when agent calls tool: - └─ Tool uses pre-computed SearchTargets - └─ Tool can filter by user-specified KB subset - └─ Executes HybridSearch with targets -``` - -### Key Invariants - -1. **SearchTargets computed once**: At `buildAgentConfig()` entry -2. **All KB tools constrained by SearchTargets**: Via constructor injection -3. **Permission checked at build time**: Not at retrieval time -4. **Cross-tenant sharing validated**: In `buildSearchTargets()` -5. **Shared agents cannot leak KBs**: `isSharedAgent` detection -6. **Configuration is immutable after engine creation**: No runtime config changes diff --git a/docs/README_AGENT_KB_INTEGRATION.md b/docs/README_AGENT_KB_INTEGRATION.md deleted file mode 100644 index 9dfaa726..00000000 --- a/docs/README_AGENT_KB_INTEGRATION.md +++ /dev/null @@ -1,256 +0,0 @@ -# Agent & Knowledge Base Integration Documentation - -This directory contains comprehensive documentation on how agents/bots use knowledge bases in WeKnora, including model definitions, retrieval configuration, and the complete retrieval pipeline. - -## Documents - -### 1. [AGENT_KB_RETRIEVAL_ARCHITECTURE.md](./AGENT_KB_RETRIEVAL_ARCHITECTURE.md) - **Deep Dive (581 lines)** -The comprehensive reference guide covering: -- Agent/Bot model definitions (CustomAgent, AgentConfig, SessionAgentConfig) -- Knowledge base binding mechanisms -- Retrieval strategy configuration (RetrievalConfig, RetrieverType, RetrieverEngineType) -- Complete retrieval pipeline stages (1-7) -- SearchTargets computation and usage -- Agent-level retrieval preferences -- Key decision flows -- Data flow diagram -- Configuration precedence -- Complete file manifest - -**Best for**: Understanding the complete architecture, implementation details, and data flows. - -### 2. [AGENT_KB_QUICK_REFERENCE.md](./AGENT_KB_QUICK_REFERENCE.md) - **Quick Guide (286 lines)** -A practical, scenario-focused guide including: -- Core data structures with tree diagrams -- Step-by-step KB access flow -- Enumeration reference (RetrieverType, RetrieverEngineType, etc.) -- Tool choices and routing -- Configuration precedence summary -- Key files lookup table -- Common Q&A scenarios - -**Best for**: Quick lookups, implementation decisions, and troubleshooting. - ---- - -## Key Concepts at a Glance - -### The Agent-KB Link - -**Agents reference KBs through**: -``` -CustomAgent.Config.AvailableKnowledgeBases[] - ↓ -buildAgentConfig() resolves to - ↓ -AgentConfig.KnowledgeBases[] - ↓ -buildSearchTargets() converts to - ↓ -AgentConfig.SearchTargets[] (unified search scope) - ↓ -Used by retrieval tools at execution time -``` - -### Retrieval Strategy Decision Path - -1. **Which KBs?** → `AgentConfig.SearchTargets` (pre-computed) -2. **Which retrieval type?** → Agent decides (tool choice: knowledge_search vs grep_chunks) -3. **Which backend?** → `Tenant.EffectiveEngines` routes RetrieverType to engine -4. **Result quality?** → `RetrievalConfig` (thresholds, reranking) - -### Search Pipeline Overview - -``` -Agent Tool Call - ↓ -HybridSearch (orchestration) - ├→ Vector search (via embedding model) - ├→ Keyword search (via full-text index) - ├→ RRF fusion - └→ Reranking - ↓ -CompositeRetrieveEngine (backend dispatch) - ├→ "vector" type → Qdrant/Milvus/Weaviate/Elasticsearch - ├→ "keywords" type → Elasticsearch/PostgreSQL/SQLite - └→ "websearch" type → External provider - ↓ -Backend-specific retrieval - ↓ -Results merged, fused, reranked - ↓ -Agent uses in reasoning loop -``` - ---- - -## File Organization - -### Core Model Files - -| Path | Purpose | Key Classes | -|------|---------|-------------| -| `internal/types/agent.go` | Agent runtime config | `AgentConfig`, `SessionAgentConfig` | -| `internal/types/custom_agent.go` | Agent definition | `CustomAgent`, `CustomAgentConfig` | -| `internal/types/knowledgebase.go` | KB model & types | `KnowledgeBase` (document/faq/wiki) | -| `internal/types/retrieval_config.go` | Tenant retrieval settings | `RetrievalConfig` | -| `internal/types/retriever.go` | Retriever type enums | `RetrieverType`, `RetrieverEngineType` | -| `internal/types/search.go` | Search models | `SearchTarget`, `SearchTargets`, `SearchResult` | - -### Service/Pipeline Files - -| Path | Purpose | Key Functions | -|------|---------|----------------| -| `internal/application/service/session_agent_qa.go` | Agent QA entry point | `buildAgentConfig()`, `buildSearchTargets()` | -| `internal/application/service/knowledgebase_search.go` | Search orchestration | `HybridSearch()` | -| `internal/application/service/retriever/composite.go` | Backend dispatcher | `CompositeRetrieveEngine` | -| `internal/agent/tools/knowledge_search.go` | Vector search tool | Knowledge search implementation | -| `internal/agent/tools/definitions.go` | Tool registry | Tool names and availability | -| `internal/application/service/chat_pipeline/search.go` | Chat pipeline search | `PluginSearch` | - ---- - -## Enumerations Quick Ref - -### RetrieverType (What) -- `"vector"` - Semantic/embedding search -- `"keywords"` - Exact keyword/full-text search -- `"websearch"` - External web search - -### RetrieverEngineType (Where) -- `"elasticsearch"` - Elasticsearch backend -- `"postgres"` - PostgreSQL backend -- `"qdrant"` - Qdrant vector DB -- `"milvus"` - Milvus vector DB -- `"weaviate"` - Weaviate vector DB -- `"infinity"` - Infinity vector DB -- `"elasticfaiss"` - FAISS backend -- `"sqlite"` - SQLite backend - -### SearchTargetType -- `"knowledge_base"` - Search entire KB -- `"knowledge"` - Search specific files within KB - -### KnowledgeBase.Type -- `"document"` - Standard document-based -- `"faq"` - Question-answer pairs -- `"wiki"` - Wiki pages - ---- - -## Configuration Hierarchy - -From lowest to highest priority: - -1. **System defaults** (hardcoded in code) -2. **Knowledge Base config** (EmbeddingModelID, FAQConfig, etc.) -3. **Tenant-level RetrievalConfig** (thresholds, top-K, reranker) -4. **Agent-level config** (AllowedTools, RerankModelID) -5. **Session-level override** (KnowledgeBases restriction) -6. **Request/Tool-level** (explicit parameters) - ---- - -## Common Implementation Patterns - -### Pattern 1: Agent Access to Multiple KBs -```go -// If KBs share embedding model: -HybridSearch(kb1_id, params{ - KnowledgeBaseIDs: [kb1, kb2, kb3], // Search all 3 - QueryText: query, - // ... results merged and reranked together -}) -``` - -### Pattern 2: Scoped Document Search -```go -// Search only specific documents within a KB: -SearchTarget{ - Type: "knowledge", - KnowledgeBaseID: kb_id, - KnowledgeIDs: [doc1, doc2], // Only these files -} -``` - -### Pattern 3: Backend Selection -```go -// CompositeRetrieveEngine routes automatically: -// RetrrieverType="vector" → Qdrant (if configured) -// RetrieverType="keywords" → Elasticsearch (if configured) -``` - -### Pattern 4: Result Fusion -```go -// Vector + Keyword results merged via RRF: -vectorScores = [query1: 0.9, query2: 0.8] -keywordScores = [query2: 0.85, query3: 0.7] -fusedScores = RRF(vectorScores, keywordScores) -// Then reranked -``` - ---- - -## Related Documentation - -- **Agent Architecture**: See `docs/AGENT_ARCHITECTURE.md` (if exists) -- **Chat Pipeline**: See `docs/CHAT_PIPELINE.md` (if exists) -- **Knowledge Base Management**: See `docs/KNOWLEDGE_BASE.md` (if exists) -- **API Documentation**: See `docs/api/` directory - ---- - -## Quick Start: Adding a New Retrieval Strategy - -1. **Create retriever type**: Add constant to `RetrieverType` enum in `internal/types/retriever.go` -2. **Register backend**: Implement `RetrieveEngineService` interface -3. **Configure at tenant level**: Update `Tenant.EffectiveEngines` to include new type -4. **Agent tool**: Create tool that sets `params.RetrieverType` to new type -5. **CompositeRetrieveEngine**: Automatically routes based on type - ---- - -## FAQ - -**Q: Where is KB access control enforced?** -A: Multiple places: -- `buildSearchTargets()` checks permissions via `kbShareService` -- Session initialization validates agent access -- Request handler validates user/session authorization - -**Q: How are cross-tenant shared KBs handled?** -A: -- `SearchTarget.TenantID` tracks which tenant owns each KB -- HybridSearch handles tenant isolation -- Permissions resolved at buildSearchTargets time - -**Q: Can I change retrieval strategy per-agent?** -A: Indirectly - via `AllowedTools` (which tools agent can use) and tool implementation - -**Q: How does reranking work?** -A: -- Tenant specifies `RetrievalConfig.RerankModelID` -- HybridSearch applies after RRF fusion -- Results filtered by `RerankThreshold` -- Limited to `RerankTopK` results - -**Q: What's the difference between vector and keyword search?** -A: -- **Vector**: Semantic/conceptual similarity (embeddings) -- **Keyword**: Exact text matching/full-text search (BM25, ES) - ---- - -## Contributing - -When modifying agent or KB integration: -1. Update relevant section in both documents -2. Keep Quick Reference as 1-page reference, Architecture as comprehensive guide -3. Update files list if adding new source files -4. Document new enumerations/types -5. Test configuration precedence scenarios - ---- - -Generated: 2026-04-20 -Last Updated: See git history