feat: Implement comprehensive wiki feature for knowledge bases

This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:

**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
  * Summary page generation using LLM
  * Entity and concept extraction in a single LLM call
  * Synthesis opportunity detection
  * Index page rebuilding
  * Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts

**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces

**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks

**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking

**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers

**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
wizardchen
2026-04-07 13:56:13 +08:00
parent e066f808b6
commit e147209e77
44 changed files with 7375 additions and 31 deletions
+2
View File
@@ -34,6 +34,8 @@ const (
ChunkTypeTableSummary ChunkType = "table_summary"
// ChunkTypeTableColumn 表示数据表列描述的 Chunk
ChunkTypeTableColumn ChunkType = "table_column"
// ChunkTypeWikiPage 表示 Wiki 页面同步的 Chunk,用于将 wiki 页面接入现有检索管线
ChunkTypeWikiPage ChunkType = "wiki_page"
)
// ChunkStatus 定义了不同状态的 Chunk
+94
View File
@@ -0,0 +1,94 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// WikiPageService defines the wiki page service interface.
// Provides high-level operations for wiki page CRUD, link management,
// and chunk synchronization.
type WikiPageService interface {
// CreatePage creates a new wiki page, parses outbound links, updates
// bidirectional link references, and syncs to chunks for retrieval.
CreatePage(ctx context.Context, page *types.WikiPage) (*types.WikiPage, error)
// UpdatePage updates an existing wiki page, re-parses links,
// updates bidirectional references, increments version, and re-syncs chunks.
UpdatePage(ctx context.Context, page *types.WikiPage) (*types.WikiPage, error)
// GetPageBySlug retrieves a wiki page by its slug within a knowledge base.
GetPageBySlug(ctx context.Context, kbID string, slug string) (*types.WikiPage, error)
// GetPageByID retrieves a wiki page by its unique ID.
GetPageByID(ctx context.Context, id string) (*types.WikiPage, error)
// ListPages lists wiki pages with optional filtering and pagination.
ListPages(ctx context.Context, req *types.WikiPageListRequest) (*types.WikiPageListResponse, error)
// DeletePage soft-deletes a wiki page and removes its chunk sync.
DeletePage(ctx context.Context, kbID string, slug string) error
// GetIndex returns the index page for a knowledge base.
// Creates a default one if it doesn't exist.
GetIndex(ctx context.Context, kbID string) (*types.WikiPage, error)
// GetLog returns the log page for a knowledge base.
// Creates a default one if it doesn't exist.
GetLog(ctx context.Context, kbID string) (*types.WikiPage, error)
// GetGraph returns the link graph data for visualization.
GetGraph(ctx context.Context, kbID string) (*types.WikiGraphData, error)
// GetStats returns aggregate statistics about the wiki.
GetStats(ctx context.Context, kbID string) (*types.WikiStats, error)
// RebuildLinks re-parses all pages and rebuilds bidirectional link references.
RebuildLinks(ctx context.Context, kbID string) error
// SearchPages performs full-text search over wiki pages.
SearchPages(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error)
}
// WikiPageRepository defines the wiki page data persistence interface.
type WikiPageRepository interface {
// Create inserts a new wiki page record.
Create(ctx context.Context, page *types.WikiPage) error
// Update updates an existing wiki page record.
Update(ctx context.Context, page *types.WikiPage) error
// GetByID retrieves a wiki page by its unique ID.
GetByID(ctx context.Context, id string) (*types.WikiPage, error)
// GetBySlug retrieves a wiki page by slug within a knowledge base.
GetBySlug(ctx context.Context, kbID string, slug string) (*types.WikiPage, error)
// List retrieves wiki pages with filtering and pagination.
List(ctx context.Context, req *types.WikiPageListRequest) ([]*types.WikiPage, int64, error)
// ListByType retrieves all wiki pages of a given type within a knowledge base.
ListByType(ctx context.Context, kbID string, pageType string) ([]*types.WikiPage, error)
// ListBySourceRef retrieves all wiki pages that reference a given source knowledge ID.
ListBySourceRef(ctx context.Context, kbID string, sourceKnowledgeID string) ([]*types.WikiPage, error)
// ListAll retrieves all wiki pages in a knowledge base (for link rebuilding, graph generation).
ListAll(ctx context.Context, kbID string) ([]*types.WikiPage, error)
// Delete soft-deletes a wiki page by knowledge base ID and slug.
Delete(ctx context.Context, kbID string, slug string) error
// DeleteByID soft-deletes a wiki page by ID.
DeleteByID(ctx context.Context, id string) error
// Search performs full-text search on wiki pages within a knowledge base.
Search(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error)
// CountByType returns page counts grouped by type for a knowledge base.
CountByType(ctx context.Context, kbID string) (map[string]int64, error)
// CountOrphans returns the number of pages with no inbound links.
CountOrphans(ctx context.Context, kbID string) (int64, error)
}
+35 -11
View File
@@ -14,6 +14,10 @@ const (
// KnowledgeBaseTypeDocument represents the document knowledge base type
KnowledgeBaseTypeDocument = "document"
KnowledgeBaseTypeFAQ = "faq"
// KnowledgeBaseTypeWiki represents the wiki knowledge base type.
// Wiki KBs use LLM to build and maintain a persistent, interlinked wiki
// from ingested documents instead of just raw RAG chunks.
KnowledgeBaseTypeWiki = "wiki"
)
// FAQIndexMode represents the FAQ index mode: only index questions or index questions and answers
@@ -79,6 +83,8 @@ type KnowledgeBase struct {
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)
@@ -481,22 +487,40 @@ func (kb *KnowledgeBase) EnsureDefaults() {
if kb.Type == "" {
kb.Type = KnowledgeBaseTypeDocument
}
// Clear type-specific configs that don't belong
if kb.Type != KnowledgeBaseTypeFAQ {
kb.FAQConfig = nil
return
}
if kb.FAQConfig == nil {
kb.FAQConfig = &FAQConfig{
IndexMode: FAQIndexModeQuestionAnswer,
QuestionIndexMode: FAQQuestionIndexModeCombined,
if kb.Type != KnowledgeBaseTypeWiki {
kb.WikiConfig = nil
}
// Set defaults for FAQ
if kb.Type == KnowledgeBaseTypeFAQ {
if kb.FAQConfig == nil {
kb.FAQConfig = &FAQConfig{
IndexMode: FAQIndexModeQuestionAnswer,
QuestionIndexMode: FAQQuestionIndexModeCombined,
}
return
}
if kb.FAQConfig.IndexMode == "" {
kb.FAQConfig.IndexMode = FAQIndexModeQuestionAnswer
}
if kb.FAQConfig.QuestionIndexMode == "" {
kb.FAQConfig.QuestionIndexMode = FAQQuestionIndexModeCombined
}
return
}
if kb.FAQConfig.IndexMode == "" {
kb.FAQConfig.IndexMode = FAQIndexModeQuestionAnswer
}
if kb.FAQConfig.QuestionIndexMode == "" {
kb.FAQConfig.QuestionIndexMode = FAQQuestionIndexModeCombined
// Set defaults for Wiki
if kb.Type == KnowledgeBaseTypeWiki {
if kb.WikiConfig == nil {
kb.WikiConfig = &WikiConfig{
AutoIngest: true,
WikiLanguage: "auto",
}
}
if kb.WikiConfig.WikiLanguage == "" {
kb.WikiConfig.WikiLanguage = "auto"
}
}
}
+1
View File
@@ -16,6 +16,7 @@ const (
TypeKnowledgePostProcess = "knowledge:post_process" // 知识后处理任务(统一调度)
TypeManualProcess = "manual:process" // 手工知识更新任务(cleanup + 重新索引)
TypeDataSourceSync = "datasource:sync" // 数据源同步任务
TypeWikiIngest = "wiki:ingest" // Wiki 页面同步任务
)
// ExtractChunkPayload represents the extract chunk task payload
+168
View File
@@ -0,0 +1,168 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
)
// WikiPageType constants define the types of wiki pages
const (
// WikiPageTypeSummary represents a document summary page
WikiPageTypeSummary = "summary"
// WikiPageTypeEntity represents an entity page (person, organization, place, etc.)
WikiPageTypeEntity = "entity"
// WikiPageTypeConcept represents a concept/topic page
WikiPageTypeConcept = "concept"
// WikiPageTypeIndex represents the wiki index page (index.md)
WikiPageTypeIndex = "index"
// WikiPageTypeLog represents the operation log page (log.md)
WikiPageTypeLog = "log"
// WikiPageTypeSynthesis represents a synthesis/analysis page.
// NOT auto-created by ingest — Agent creates these via wiki_write_page tool
// when it generates cross-document analysis, trends, or insights during conversations.
WikiPageTypeSynthesis = "synthesis"
// WikiPageTypeComparison represents a comparison page.
// NOT auto-created by ingest — Agent creates these via wiki_write_page tool
// when the user asks to compare entities, concepts, or approaches.
WikiPageTypeComparison = "comparison"
)
// WikiPageStatus constants
const (
// WikiPageStatusDraft indicates the page is a draft
WikiPageStatusDraft = "draft"
// WikiPageStatusPublished indicates the page is published and visible
WikiPageStatusPublished = "published"
// WikiPageStatusArchived indicates the page is archived
WikiPageStatusArchived = "archived"
)
// WikiPage represents a single wiki page in a wiki knowledge base.
// Wiki pages are LLM-generated, interlinked markdown documents that form
// a persistent, compounding knowledge artifact.
type WikiPage struct {
// Unique identifier (UUID)
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID for multi-tenant isolation
TenantID uint64 `json:"tenant_id" gorm:"index"`
// Knowledge base this page belongs to
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`
// URL-friendly slug for addressing, e.g. "entity/acme-corp", "concept/rag"
// Unique within a knowledge base
Slug string `json:"slug" gorm:"type:varchar(255);uniqueIndex:idx_kb_slug"`
// Human-readable title
Title string `json:"title" gorm:"type:varchar(512)"`
// Page type: summary, entity, concept, index, log, synthesis, comparison
PageType string `json:"page_type" gorm:"type:varchar(32);index"`
// Page status: draft, published, archived
Status string `json:"status" gorm:"type:varchar(32);default:'published'"`
// Full markdown content
Content string `json:"content" gorm:"type:text"`
// One-line summary for index listing
Summary string `json:"summary" gorm:"type:text"`
// References to source knowledge IDs that contributed to this page
SourceRefs StringArray `json:"source_refs" gorm:"type:json"`
// Slugs of pages that link TO this page (backlinks)
InLinks StringArray `json:"in_links" gorm:"type:json"`
// Slugs of pages this page links to (outbound links)
OutLinks StringArray `json:"out_links" gorm:"type:json"`
// Arbitrary metadata (tags, categories, dates, etc.)
PageMetadata JSON `json:"page_metadata" gorm:"column:page_metadata;type:json"`
// Version number, incremented on each update
Version int `json:"version" gorm:"default:1"`
// Creation time
CreatedAt time.Time `json:"created_at"`
// Last update time
UpdatedAt time.Time `json:"updated_at"`
// Soft delete
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// TableName specifies the database table name
func (WikiPage) TableName() string {
return "wiki_pages"
}
// WikiConfig stores wiki-specific configuration for a knowledge base.
// Only applicable when KnowledgeBase.Type == "wiki".
type WikiConfig struct {
// 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"`
}
// Value implements the driver.Valuer interface
func (c WikiConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface
func (c *WikiConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// WikiPageListRequest represents a request to list wiki pages with filtering
type WikiPageListRequest struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
PageType string `json:"page_type,omitempty"` // filter by type
Status string `json:"status,omitempty"` // filter by status
Query string `json:"query,omitempty"` // full-text search
Page int `json:"page,omitempty"` // pagination page (1-based)
PageSize int `json:"page_size,omitempty"` // pagination size
SortBy string `json:"sort_by,omitempty"` // "updated_at", "created_at", "title"
SortOrder string `json:"sort_order,omitempty"` // "asc" or "desc"
}
// WikiPageListResponse represents a paginated list of wiki pages
type WikiPageListResponse struct {
Pages []*WikiPage `json:"pages"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalPages int `json:"total_pages"`
}
// WikiGraphData represents the link graph structure for visualization
type WikiGraphData struct {
Nodes []WikiGraphNode `json:"nodes"`
Edges []WikiGraphEdge `json:"edges"`
}
// WikiGraphNode represents a node in the wiki link graph
type WikiGraphNode struct {
Slug string `json:"slug"`
Title string `json:"title"`
PageType string `json:"page_type"`
// Number of inbound + outbound links
LinkCount int `json:"link_count"`
}
// WikiGraphEdge represents a directed edge in the wiki link graph
type WikiGraphEdge struct {
Source string `json:"source"` // source slug
Target string `json:"target"` // target slug
}
// WikiStats provides aggregate statistics about the wiki
type WikiStats struct {
TotalPages int64 `json:"total_pages"`
PagesByType map[string]int64 `json:"pages_by_type"`
TotalLinks int64 `json:"total_links"`
OrphanCount int64 `json:"orphan_count"` // pages with no inbound links
RecentUpdates []*WikiPage `json:"recent_updates"` // last N updated pages
}
+226
View File
@@ -0,0 +1,226 @@
package types
import (
"encoding/json"
"testing"
)
func TestWikiPageTypes(t *testing.T) {
// Verify all page type constants are non-empty and unique
pageTypes := []string{
WikiPageTypeSummary,
WikiPageTypeEntity,
WikiPageTypeConcept,
WikiPageTypeIndex,
WikiPageTypeLog,
WikiPageTypeSynthesis,
WikiPageTypeComparison,
}
seen := make(map[string]bool)
for _, pt := range pageTypes {
if pt == "" {
t.Errorf("WikiPageType constant is empty")
}
if seen[pt] {
t.Errorf("Duplicate WikiPageType: %s", pt)
}
seen[pt] = true
}
}
func TestWikiConfigValueScan(t *testing.T) {
// Test Value (serialize)
config := WikiConfig{
AutoIngest: true,
SynthesisModelID: "model-123",
WikiLanguage: "zh",
MaxPagesPerIngest: 20,
}
val, err := config.Value()
if err != nil {
t.Fatalf("WikiConfig.Value() error: %v", err)
}
// Test Scan (deserialize)
var restored WikiConfig
b, ok := val.([]byte)
if !ok {
t.Fatal("WikiConfig.Value() did not return []byte")
}
if err := restored.Scan(b); err != nil {
t.Fatalf("WikiConfig.Scan() error: %v", err)
}
if restored.AutoIngest != true {
t.Error("AutoIngest mismatch")
}
if restored.SynthesisModelID != "model-123" {
t.Error("SynthesisModelID mismatch")
}
if restored.WikiLanguage != "zh" {
t.Error("WikiLanguage mismatch")
}
if restored.MaxPagesPerIngest != 20 {
t.Error("MaxPagesPerIngest mismatch")
}
}
func TestWikiConfigScanNil(t *testing.T) {
var config WikiConfig
if err := config.Scan(nil); err != nil {
t.Fatalf("Scan(nil) should not error: %v", err)
}
}
func TestStringArrayValueScan(t *testing.T) {
arr := StringArray{"a", "b", "c"}
val, err := arr.Value()
if err != nil {
t.Fatalf("StringArray.Value() error: %v", err)
}
var restored StringArray
b, ok := val.([]byte)
if !ok {
t.Fatal("StringArray.Value() did not return []byte")
}
if err := restored.Scan(b); err != nil {
t.Fatalf("StringArray.Scan() error: %v", err)
}
if len(restored) != 3 || restored[0] != "a" || restored[1] != "b" || restored[2] != "c" {
t.Errorf("StringArray round-trip failed: got %v", restored)
}
}
func TestStringArrayEmpty(t *testing.T) {
// nil StringArray marshals to JSON null via json.Marshal
var arr StringArray
val, err := arr.Value()
if err != nil {
t.Fatalf("nil StringArray.Value() error: %v", err)
}
// json.Marshal(nil) returns "null", which is valid
if val == nil {
// Some implementations return nil for nil slices
return
}
b, ok := val.([]byte)
if !ok {
t.Fatalf("unexpected type: %T", val)
}
s := string(b)
if s != "null" && s != "[]" {
t.Errorf("nil StringArray.Value() should return 'null' or '[]', got %q", s)
}
}
func TestKnowledgeBaseEnsureDefaultsWiki(t *testing.T) {
kb := &KnowledgeBase{Type: KnowledgeBaseTypeWiki}
kb.EnsureDefaults()
if kb.WikiConfig == nil {
t.Fatal("EnsureDefaults should create default WikiConfig for wiki type")
}
if kb.WikiConfig.AutoIngest != true {
t.Error("Default AutoIngest should be true")
}
if kb.WikiConfig.WikiLanguage != "auto" {
t.Errorf("Default WikiLanguage should be 'auto', got '%s'", kb.WikiConfig.WikiLanguage)
}
if kb.FAQConfig != nil {
t.Error("Wiki KB should not have FAQConfig")
}
}
func TestKnowledgeBaseEnsureDefaultsDocumentClearsWikiConfig(t *testing.T) {
kb := &KnowledgeBase{
Type: KnowledgeBaseTypeDocument,
WikiConfig: &WikiConfig{AutoIngest: true},
}
kb.EnsureDefaults()
if kb.WikiConfig != nil {
t.Error("Document KB should not have WikiConfig after EnsureDefaults")
}
}
func TestWikiPageJSON(t *testing.T) {
page := WikiPage{
ID: "test-id",
Slug: "entity/test",
Title: "Test Entity",
PageType: WikiPageTypeEntity,
Content: "# Test\n\nSome content with [[concept/related]]",
Summary: "A test entity page",
SourceRefs: StringArray{"source-1", "source-2"},
OutLinks: StringArray{"concept/related"},
InLinks: StringArray{"summary/doc1"},
Version: 3,
}
// Serialize
data, err := json.Marshal(page)
if err != nil {
t.Fatalf("Marshal error: %v", err)
}
// Deserialize
var restored WikiPage
if err := json.Unmarshal(data, &restored); err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
if restored.Slug != "entity/test" {
t.Errorf("Slug mismatch: got %s", restored.Slug)
}
if restored.Version != 3 {
t.Errorf("Version mismatch: got %d", restored.Version)
}
if len(restored.OutLinks) != 1 || restored.OutLinks[0] != "concept/related" {
t.Errorf("OutLinks mismatch: got %v", restored.OutLinks)
}
if len(restored.SourceRefs) != 2 {
t.Errorf("SourceRefs mismatch: got %v", restored.SourceRefs)
}
}
func TestWikiGraphDataJSON(t *testing.T) {
graph := WikiGraphData{
Nodes: []WikiGraphNode{
{Slug: "entity/a", Title: "A", PageType: "entity", LinkCount: 2},
{Slug: "concept/b", Title: "B", PageType: "concept", LinkCount: 1},
},
Edges: []WikiGraphEdge{
{Source: "entity/a", Target: "concept/b"},
},
}
data, err := json.Marshal(graph)
if err != nil {
t.Fatalf("Marshal error: %v", err)
}
var restored WikiGraphData
if err := json.Unmarshal(data, &restored); err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
if len(restored.Nodes) != 2 {
t.Errorf("Nodes count mismatch: got %d", len(restored.Nodes))
}
if len(restored.Edges) != 1 {
t.Errorf("Edges count mismatch: got %d", len(restored.Edges))
}
if restored.Edges[0].Source != "entity/a" || restored.Edges[0].Target != "concept/b" {
t.Errorf("Edge mismatch: got %v", restored.Edges[0])
}
}
func TestChunkTypeWikiPage(t *testing.T) {
if ChunkTypeWikiPage != "wiki_page" {
t.Errorf("ChunkTypeWikiPage should be 'wiki_page', got '%s'", ChunkTypeWikiPage)
}
}