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
@@ -0,0 +1,249 @@
package repository
import (
"context"
"errors"
"fmt"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"gorm.io/gorm"
)
// ErrWikiPageNotFound is returned when a wiki page is not found
var ErrWikiPageNotFound = errors.New("wiki page not found")
// wikiPageRepository implements the WikiPageRepository interface
type wikiPageRepository struct {
db *gorm.DB
}
// NewWikiPageRepository creates a new wiki page repository
func NewWikiPageRepository(db *gorm.DB) interfaces.WikiPageRepository {
return &wikiPageRepository{db: db}
}
// Create inserts a new wiki page record
func (r *wikiPageRepository) Create(ctx context.Context, page *types.WikiPage) error {
return r.db.WithContext(ctx).Create(page).Error
}
// Update updates an existing wiki page record
func (r *wikiPageRepository) Update(ctx context.Context, page *types.WikiPage) error {
result := r.db.WithContext(ctx).Save(page)
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrWikiPageNotFound
}
return nil
}
// GetByID retrieves a wiki page by its unique ID
func (r *wikiPageRepository) GetByID(ctx context.Context, id string) (*types.WikiPage, error) {
var page types.WikiPage
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&page).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWikiPageNotFound
}
return nil, err
}
return &page, nil
}
// GetBySlug retrieves a wiki page by slug within a knowledge base
func (r *wikiPageRepository) GetBySlug(ctx context.Context, kbID string, slug string) (*types.WikiPage, error) {
var page types.WikiPage
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND slug = ?", kbID, slug).
First(&page).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWikiPageNotFound
}
return nil, err
}
return &page, nil
}
// List retrieves wiki pages with filtering and pagination
func (r *wikiPageRepository) List(ctx context.Context, req *types.WikiPageListRequest) ([]*types.WikiPage, int64, error) {
query := r.db.WithContext(ctx).Model(&types.WikiPage{}).
Where("knowledge_base_id = ?", req.KnowledgeBaseID)
if req.PageType != "" {
query = query.Where("page_type = ?", req.PageType)
}
if req.Status != "" {
query = query.Where("status = ?", req.Status)
}
if req.Query != "" {
// Use PostgreSQL full-text search
query = query.Where(
"to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(content, '')) @@ plainto_tsquery('simple', ?)",
req.Query,
)
}
var total int64
if err := query.Count(&total).Error; err != nil {
return nil, 0, err
}
// Sort
sortBy := "updated_at"
if req.SortBy != "" {
switch req.SortBy {
case "title", "created_at", "updated_at", "page_type":
sortBy = req.SortBy
}
}
sortOrder := "DESC"
if req.SortOrder == "asc" {
sortOrder = "ASC"
}
query = query.Order(fmt.Sprintf("%s %s", sortBy, sortOrder))
// Pagination
page := req.Page
if page < 1 {
page = 1
}
pageSize := req.PageSize
if pageSize < 1 {
pageSize = 20
}
if pageSize > 100 {
pageSize = 100
}
offset := (page - 1) * pageSize
query = query.Offset(offset).Limit(pageSize)
var pages []*types.WikiPage
if err := query.Find(&pages).Error; err != nil {
return nil, 0, err
}
return pages, total, nil
}
// ListByType retrieves all wiki pages of a given type within a knowledge base
func (r *wikiPageRepository) ListByType(ctx context.Context, kbID string, pageType string) ([]*types.WikiPage, error) {
var pages []*types.WikiPage
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND page_type = ?", kbID, pageType).
Order("updated_at DESC").
Find(&pages).Error; err != nil {
return nil, err
}
return pages, nil
}
// ListBySourceRef retrieves all wiki pages that reference a given source knowledge ID
func (r *wikiPageRepository) ListBySourceRef(ctx context.Context, kbID string, sourceKnowledgeID string) ([]*types.WikiPage, error) {
var pages []*types.WikiPage
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND source_refs @> ?", kbID, fmt.Sprintf(`["%s"]`, sourceKnowledgeID)).
Find(&pages).Error; err != nil {
return nil, err
}
return pages, nil
}
// ListAll retrieves all wiki pages in a knowledge base
func (r *wikiPageRepository) ListAll(ctx context.Context, kbID string) ([]*types.WikiPage, error) {
var pages []*types.WikiPage
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ?", kbID).
Order("page_type ASC, title ASC").
Find(&pages).Error; err != nil {
return nil, err
}
return pages, nil
}
// Delete soft-deletes a wiki page by knowledge base ID and slug
func (r *wikiPageRepository) Delete(ctx context.Context, kbID string, slug string) error {
result := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND slug = ?", kbID, slug).
Delete(&types.WikiPage{})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrWikiPageNotFound
}
return nil
}
// DeleteByID soft-deletes a wiki page by ID
func (r *wikiPageRepository) DeleteByID(ctx context.Context, id string) error {
result := r.db.WithContext(ctx).
Where("id = ?", id).
Delete(&types.WikiPage{})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrWikiPageNotFound
}
return nil
}
// Search performs full-text search on wiki pages within a knowledge base
func (r *wikiPageRepository) Search(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error) {
if limit <= 0 {
limit = 10
}
if limit > 50 {
limit = 50
}
var pages []*types.WikiPage
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ?", kbID).
Where("to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(content, '')) @@ plainto_tsquery('simple', ?)", query).
Order("ts_rank(to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(content, '')), plainto_tsquery('simple', ?)) DESC").
Limit(limit).
Find(&pages, query).Error; err != nil {
return nil, err
}
return pages, nil
}
// CountByType returns page counts grouped by type for a knowledge base
func (r *wikiPageRepository) CountByType(ctx context.Context, kbID string) (map[string]int64, error) {
type result struct {
PageType string
Count int64
}
var results []result
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Select("page_type, count(*) as count").
Where("knowledge_base_id = ?", kbID).
Group("page_type").
Scan(&results).Error; err != nil {
return nil, err
}
counts := make(map[string]int64)
for _, r := range results {
counts[r.PageType] = r.Count
}
return counts, nil
}
// CountOrphans returns the number of pages with no inbound links
func (r *wikiPageRepository) CountOrphans(ctx context.Context, kbID string) (int64, error) {
var count int64
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Where("knowledge_base_id = ?", kbID).
Where("(in_links IS NULL OR in_links = '[]'::JSONB)").
// Exclude index and log pages as they are naturally root pages
Where("page_type NOT IN ?", []string{types.WikiPageTypeIndex, types.WikiPageTypeLog}).
Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
@@ -40,6 +40,7 @@ type agentService struct {
chunkService interfaces.ChunkService
duckdb *sql.DB
webSearchStateService interfaces.WebSearchStateService
wikiPageService interfaces.WikiPageService
}
// NewAgentService creates a new agent service
@@ -57,6 +58,7 @@ func NewAgentService(
webSearchService interfaces.WebSearchService,
duckdb *sql.DB,
webSearchStateService interfaces.WebSearchStateService,
wikiPageService interfaces.WikiPageService,
) interfaces.AgentService {
return &agentService{
cfg: cfg,
@@ -72,6 +74,7 @@ func NewAgentService(
webSearchService: webSearchService,
duckdb: duckdb,
webSearchStateService: webSearchStateService,
wikiPageService: wikiPageService,
}
}
@@ -366,6 +369,27 @@ func (s *agentService) registerTools(
allowedTools = append(allowedTools, tools.ToolWebFetch)
}
// If any search target is a wiki KB, add wiki tools automatically
var wikiKBIDs []string
var wikiTenantID uint64
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 len(wikiKBIDs) > 0 {
allowedTools = append(allowedTools,
tools.ToolWikiReadPage,
tools.ToolWikiWritePage,
tools.ToolWikiSearch,
tools.ToolWikiReadIndex,
tools.ToolWikiLint,
)
logger.Infof(ctx, "Wiki KBs detected (%d), wiki tools added", len(wikiKBIDs))
}
logger.Infof(ctx, "Registering tools: %v, webSearchEnabled: %v", allowedTools, config.WebSearchEnabled)
allowedTools = append(allowedTools, tools.ToolFinalAnswer)
// Register each allowed tool
@@ -425,6 +449,19 @@ func (s *agentService) registerTools(
case tools.ToolFinalAnswer:
toolToRegister = tools.NewFinalAnswerTool()
logger.Infof(ctx, "Registered final_answer tool")
// Wiki tools — only registered when wiki KBs are detected
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)
default:
logger.Warnf(ctx, "Unknown tool: %s", toolName)
}
@@ -0,0 +1,89 @@
package chatpipeline
import (
"context"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// wikiBoostFactor is the score multiplier applied to wiki page chunks.
// Wiki pages contain LLM-synthesized, cross-referenced knowledge and should
// be preferred over raw document chunks when both are available.
const wikiBoostFactor = 1.3
// PluginWikiBoost boosts the relevance score of wiki page chunks in search results.
// Wiki pages contain pre-synthesized knowledge that is more coherent and
// cross-referenced than raw document chunks, so they should rank higher.
//
// This plugin runs in the CHUNK_RERANK phase, after initial retrieval and reranking.
// It identifies chunks with ChunkType == "wiki_page" and multiplies their score.
type PluginWikiBoost struct {
kbService interfaces.KnowledgeBaseService
}
// NewPluginWikiBoost creates and registers the wiki boost plugin
func NewPluginWikiBoost(eventManager *EventManager, kbService interfaces.KnowledgeBaseService) *PluginWikiBoost {
p := &PluginWikiBoost{
kbService: kbService,
}
eventManager.Register(p)
return p
}
// ActivationEvents returns the event types this plugin handles
func (p *PluginWikiBoost) ActivationEvents() []types.EventType {
return []types.EventType{types.CHUNK_RERANK}
}
// OnEvent boosts wiki page chunk scores after reranking
func (p *PluginWikiBoost) OnEvent(
ctx context.Context,
eventType types.EventType,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
// Run the normal reranking first
if err := next(); err != nil {
return err
}
// Check if any search target is a wiki KB
hasWikiKB := false
for _, target := range chatManage.SearchTargets {
kb, err := p.kbService.GetKnowledgeBaseByIDOnly(ctx, target.KnowledgeBaseID)
if err == nil && kb.Type == types.KnowledgeBaseTypeWiki {
hasWikiKB = true
break
}
}
if !hasWikiKB {
return nil
}
// Boost wiki page chunks in RerankResult
boostedCount := 0
for i := range chatManage.RerankResult {
if chatManage.RerankResult[i].ChunkType == types.ChunkTypeWikiPage {
chatManage.RerankResult[i].Score *= wikiBoostFactor
boostedCount++
}
}
if boostedCount > 0 {
logger.Infof(ctx, "WikiBoost: boosted %d wiki page chunks by %.1fx", boostedCount, wikiBoostFactor)
// Re-sort by score after boosting
for i := 0; i < len(chatManage.RerankResult); i++ {
for j := i + 1; j < len(chatManage.RerankResult); j++ {
if chatManage.RerankResult[j].Score > chatManage.RerankResult[i].Score {
chatManage.RerankResult[i], chatManage.RerankResult[j] = chatManage.RerankResult[j], chatManage.RerankResult[i]
}
}
}
}
return nil
}
@@ -83,7 +83,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
if knowledge.ParseStatus == types.ParseStatusProcessing {
knowledge.ParseStatus = types.ParseStatusCompleted
knowledge.UpdatedAt = time.Now()
// Setup summary status
if len(textChunks) > 0 {
knowledge.SummaryStatus = types.SummaryStatusPending
@@ -115,6 +115,11 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
}
}
// 6. Spawn Wiki Ingest Task for wiki-type knowledge bases
if kb.Type == types.KnowledgeBaseTypeWiki && len(textChunks) > 0 {
EnqueueWikiIngest(ctx, s.taskEnqueuer, payload.TenantID, payload.KnowledgeBaseID, payload.KnowledgeID)
logger.Infof(ctx, "[KnowledgePostProcess] Enqueued wiki ingest task for %s", payload.KnowledgeID)
}
return nil
}
@@ -0,0 +1,108 @@
package service
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestSlugify(t *testing.T) {
tests := []struct {
input string
want string
}{
{"Hello World", "hello-world"},
{"Acme Corp", "acme-corp"},
{" spaces ", "spaces"},
{"under_score", "under-score"},
{"Already-Good", "already-good"},
{"Special!@#Chars", "specialchars"},
{"CamelCase", "camelcase"},
{"", ""},
{"a/b/c", "a/b/c"}, // preserve slashes for hierarchical slugs
{"中文标题", "中文标题"}, // preserve CJK
{"Mix 中英文 Test", "mix-中英文-test"}, // mixed
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
got := slugify(tt.input)
if got != tt.want {
t.Errorf("slugify(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}
func TestTruncateString(t *testing.T) {
tests := []struct {
input string
maxLen int
want string
}{
{"hello world", 20, "hello world"},
{"hello world", 5, "hello..."},
{"", 10, ""},
{"abc", 3, "abc"},
{"abcd", 3, "abc..."},
{"中文测试", 2, "中文..."},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
got := truncateString(tt.input, tt.maxLen)
if got != tt.want {
t.Errorf("truncateString(%q, %d) = %q, want %q", tt.input, tt.maxLen, got, tt.want)
}
})
}
}
func TestAppendUnique(t *testing.T) {
arr := types.StringArray{"a", "b"}
// Add new
result := appendUnique(arr, "c")
if len(result) != 3 {
t.Errorf("Expected 3 items, got %d", len(result))
}
// Add duplicate
result = appendUnique(result, "b")
if len(result) != 3 {
t.Errorf("Expected 3 items (no dup), got %d", len(result))
}
}
func TestReconstructContent(t *testing.T) {
chunks := []*types.Chunk{
{ChunkIndex: 2, ChunkType: types.ChunkTypeText, Content: "Third paragraph."},
{ChunkIndex: 0, ChunkType: types.ChunkTypeText, Content: "First paragraph."},
{ChunkIndex: 1, ChunkType: types.ChunkTypeText, Content: "Second paragraph."},
{ChunkIndex: 3, ChunkType: types.ChunkTypeImageOCR, Content: "OCR text should be excluded."},
}
content := reconstructContent(chunks)
// Should be sorted by ChunkIndex and exclude non-text chunks
if content == "" {
t.Fatal("reconstructContent should not be empty")
}
// Verify order: first, second, third
if len(content) == 0 {
t.Fatal("empty content")
}
// The first characters should be "First"
if content[:5] != "First" {
t.Errorf("Expected content to start with 'First', got: %s", content[:20])
}
}
func TestReconstructContentEmpty(t *testing.T) {
content := reconstructContent(nil)
if content != "" {
t.Errorf("Empty chunks should produce empty content, got %q", content)
}
}
+304
View File
@@ -0,0 +1,304 @@
package service
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// WikiLintIssueType defines the type of lint issue
type WikiLintIssueType string
const (
LintIssueOrphanPage WikiLintIssueType = "orphan_page"
LintIssueBrokenLink WikiLintIssueType = "broken_link"
LintIssueStaleRef WikiLintIssueType = "stale_ref"
LintIssueMissingCrossRef WikiLintIssueType = "missing_cross_ref"
LintIssueEmptyContent WikiLintIssueType = "empty_content"
LintIssueDuplicateSlug WikiLintIssueType = "duplicate_slug"
)
// WikiLintIssueSeverity defines the severity of a lint issue
type WikiLintIssueSeverity string
const (
SeverityInfo WikiLintIssueSeverity = "info"
SeverityWarning WikiLintIssueSeverity = "warning"
SeverityError WikiLintIssueSeverity = "error"
)
// WikiLintIssue represents a single lint finding
type WikiLintIssue struct {
Type WikiLintIssueType `json:"type"`
Severity WikiLintIssueSeverity `json:"severity"`
PageSlug string `json:"page_slug"`
Description string `json:"description"`
AutoFixable bool `json:"auto_fixable"`
}
// WikiLintReport is the complete lint report for a wiki KB
type WikiLintReport struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
Issues []WikiLintIssue `json:"issues"`
HealthScore int `json:"health_score"` // 0-100
Stats *types.WikiStats `json:"stats"`
Summary string `json:"summary"`
}
// WikiLintService provides wiki health checking capabilities
type WikiLintService struct {
wikiService interfaces.WikiPageService
kbService interfaces.KnowledgeBaseService
}
// NewWikiLintService creates a new wiki lint service
func NewWikiLintService(
wikiService interfaces.WikiPageService,
kbService interfaces.KnowledgeBaseService,
) *WikiLintService {
return &WikiLintService{
wikiService: wikiService,
kbService: kbService,
}
}
// RunLint performs a comprehensive health check on a wiki knowledge base
func (s *WikiLintService) RunLint(ctx context.Context, kbID string) (*WikiLintReport, error) {
// Validate KB
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
if err != nil {
return nil, fmt.Errorf("get KB: %w", err)
}
if kb.Type != types.KnowledgeBaseTypeWiki {
return nil, fmt.Errorf("KB %s is not a wiki type", kbID)
}
// Get stats
stats, err := s.wikiService.GetStats(ctx, kbID)
if err != nil {
return nil, fmt.Errorf("get stats: %w", err)
}
// Get graph for link analysis
graph, err := s.wikiService.GetGraph(ctx, kbID)
if err != nil {
return nil, fmt.Errorf("get graph: %w", err)
}
// Get all pages for detailed analysis
resp, err := s.wikiService.ListPages(ctx, &types.WikiPageListRequest{
KnowledgeBaseID: kbID,
PageSize: 500,
})
if err != nil {
return nil, fmt.Errorf("list pages: %w", err)
}
var issues []WikiLintIssue
healthScore := 100
// Build slug set for link validation
slugSet := make(map[string]bool)
for _, node := range graph.Nodes {
slugSet[node.Slug] = true
}
// Check 1: Orphan pages (no inbound links, excluding index/log)
for _, page := range resp.Pages {
if page.PageType == types.WikiPageTypeIndex || page.PageType == types.WikiPageTypeLog {
continue
}
if len(page.InLinks) == 0 {
issues = append(issues, WikiLintIssue{
Type: LintIssueOrphanPage,
Severity: SeverityWarning,
PageSlug: page.Slug,
Description: fmt.Sprintf("Page '%s' has no inbound links — it's disconnected from the wiki", page.Title),
AutoFixable: false,
})
}
}
// Check 2: Broken links
for _, page := range resp.Pages {
for _, outLink := range page.OutLinks {
if !slugSet[outLink] {
issues = append(issues, WikiLintIssue{
Type: LintIssueBrokenLink,
Severity: SeverityError,
PageSlug: page.Slug,
Description: fmt.Sprintf("Page '%s' links to [[%s]] which does not exist", page.Title, outLink),
AutoFixable: true,
})
}
}
}
// Check 3: Empty content
for _, page := range resp.Pages {
content := strings.TrimSpace(page.Content)
if len(content) < 50 {
issues = append(issues, WikiLintIssue{
Type: LintIssueEmptyContent,
Severity: SeverityWarning,
PageSlug: page.Slug,
Description: fmt.Sprintf("Page '%s' has very little content (%d chars)", page.Title, len(content)),
AutoFixable: false,
})
}
}
// Check 4: Missing cross-references (entities mentioned in content but not linked)
entitySlugs := make(map[string]string) // slug -> title
for _, page := range resp.Pages {
if page.PageType == types.WikiPageTypeEntity || page.PageType == types.WikiPageTypeConcept {
entitySlugs[page.Slug] = page.Title
}
}
for _, page := range resp.Pages {
for slug, title := range entitySlugs {
if slug == page.Slug {
continue
}
// Check if title is mentioned in content but not linked
if strings.Contains(strings.ToLower(page.Content), strings.ToLower(title)) {
linked := false
for _, l := range page.OutLinks {
if l == slug {
linked = true
break
}
}
if !linked {
issues = append(issues, WikiLintIssue{
Type: LintIssueMissingCrossRef,
Severity: SeverityInfo,
PageSlug: page.Slug,
Description: fmt.Sprintf("Page '%s' mentions '%s' but doesn't link to [[%s]]", page.Title, title, slug),
AutoFixable: true,
})
}
}
}
}
// Calculate health score
if stats.TotalPages > 0 {
// Penalize for orphans
orphanPct := float64(stats.OrphanCount) / float64(stats.TotalPages) * 100
if orphanPct > 50 {
healthScore -= 25
} else if orphanPct > 25 {
healthScore -= 10
}
// Penalize for broken links
brokenCount := 0
for _, issue := range issues {
if issue.Type == LintIssueBrokenLink {
brokenCount++
}
}
healthScore -= brokenCount * 5
// Penalize for no links at all
if stats.TotalLinks == 0 && stats.TotalPages > 2 {
healthScore -= 15
}
// Penalize for empty pages
emptyCount := 0
for _, issue := range issues {
if issue.Type == LintIssueEmptyContent {
emptyCount++
}
}
healthScore -= emptyCount * 3
}
if healthScore < 0 {
healthScore = 0
}
// Generate summary
var summary strings.Builder
errorCount := 0
warningCount := 0
infoCount := 0
for _, issue := range issues {
switch issue.Severity {
case SeverityError:
errorCount++
case SeverityWarning:
warningCount++
case SeverityInfo:
infoCount++
}
}
if len(issues) == 0 {
summary.WriteString("Wiki is healthy! No issues found.")
} else {
fmt.Fprintf(&summary, "Found %d issues: %d errors, %d warnings, %d suggestions.",
len(issues), errorCount, warningCount, infoCount)
}
report := &WikiLintReport{
KnowledgeBaseID: kbID,
Issues: issues,
HealthScore: healthScore,
Stats: stats,
Summary: summary.String(),
}
logger.Infof(ctx, "wiki lint: KB %s — health score %d/100, %d issues", kbID, healthScore, len(issues))
return report, nil
}
// AutoFix attempts to automatically fix fixable issues
func (s *WikiLintService) AutoFix(ctx context.Context, kbID string) (int, error) {
report, err := s.RunLint(ctx, kbID)
if err != nil {
return 0, err
}
fixed := 0
for _, issue := range report.Issues {
if !issue.AutoFixable {
continue
}
switch issue.Type {
case LintIssueBrokenLink:
// Remove broken links from page content
page, err := s.wikiService.GetPageBySlug(ctx, kbID, issue.PageSlug)
if err != nil {
continue
}
// Extract the broken slug from the description
parts := strings.Split(issue.Description, "[[")
if len(parts) < 2 {
continue
}
brokenSlug := strings.Split(parts[1], "]]")[0]
// Remove the [[broken-link]] from content
page.Content = strings.ReplaceAll(page.Content, "[["+brokenSlug+"]]", brokenSlug)
if _, err := s.wikiService.UpdatePage(ctx, page); err == nil {
fixed++
}
}
}
// Rebuild links after fixes
if fixed > 0 {
_ = s.wikiService.RebuildLinks(ctx, kbID)
}
logger.Infof(ctx, "wiki auto-fix: KB %s — fixed %d issues", kbID, fixed)
return fixed, nil
}
+492
View File
@@ -0,0 +1,492 @@
package service
import (
"context"
"errors"
"fmt"
"regexp"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// wikiLinkRegex matches [[wiki-link]] syntax in markdown content
var wikiLinkRegex = regexp.MustCompile(`\[\[([^\]]+)\]\]`)
// wikiPageService implements the WikiPageService interface
type wikiPageService struct {
repo interfaces.WikiPageRepository
chunkRepo interfaces.ChunkRepository
kbService interfaces.KnowledgeBaseService
}
// NewWikiPageService creates a new wiki page service
func NewWikiPageService(
repo interfaces.WikiPageRepository,
chunkRepo interfaces.ChunkRepository,
kbService interfaces.KnowledgeBaseService,
) interfaces.WikiPageService {
return &wikiPageService{
repo: repo,
chunkRepo: chunkRepo,
kbService: kbService,
}
}
// CreatePage creates a new wiki page
func (s *wikiPageService) CreatePage(ctx context.Context, page *types.WikiPage) (*types.WikiPage, error) {
if page.ID == "" {
page.ID = uuid.New().String()
}
if page.Slug == "" {
return nil, errors.New("wiki page slug is required")
}
if page.KnowledgeBaseID == "" {
return nil, errors.New("knowledge_base_id is required")
}
if page.Status == "" {
page.Status = types.WikiPageStatusPublished
}
if page.Version == 0 {
page.Version = 1
}
// Parse outbound links from content
page.OutLinks = s.parseOutLinks(page.Content)
now := time.Now()
page.CreatedAt = now
page.UpdatedAt = now
if err := s.repo.Create(ctx, page); err != nil {
return nil, fmt.Errorf("create wiki page: %w", err)
}
// Update inbound links on target pages
s.updateInLinks(ctx, page.KnowledgeBaseID, page.Slug, page.OutLinks)
// Sync to chunks for retrieval pipeline integration
if err := s.syncToChunk(ctx, page); err != nil {
logger.Warnf(ctx, "wiki: failed to sync page %s to chunks: %v", page.Slug, err)
}
return page, nil
}
// UpdatePage updates an existing wiki page
func (s *wikiPageService) UpdatePage(ctx context.Context, page *types.WikiPage) (*types.WikiPage, error) {
existing, err := s.repo.GetBySlug(ctx, page.KnowledgeBaseID, page.Slug)
if err != nil {
return nil, fmt.Errorf("get existing page: %w", err)
}
oldOutLinks := existing.OutLinks
// Update fields
existing.Title = page.Title
existing.Content = page.Content
existing.Summary = page.Summary
existing.PageType = page.PageType
existing.SourceRefs = page.SourceRefs
existing.PageMetadata = page.PageMetadata
existing.Status = page.Status
existing.Version++
existing.UpdatedAt = time.Now()
// Re-parse outbound links
existing.OutLinks = s.parseOutLinks(existing.Content)
if err := s.repo.Update(ctx, existing); err != nil {
return nil, fmt.Errorf("update wiki page: %w", err)
}
// Update inbound links: remove old, add new
s.removeInLinks(ctx, existing.KnowledgeBaseID, existing.Slug, oldOutLinks)
s.updateInLinks(ctx, existing.KnowledgeBaseID, existing.Slug, existing.OutLinks)
// Re-sync to chunks
if err := s.syncToChunk(ctx, existing); err != nil {
logger.Warnf(ctx, "wiki: failed to sync page %s to chunks: %v", existing.Slug, err)
}
return existing, nil
}
// GetPageBySlug retrieves a wiki page by its slug
func (s *wikiPageService) GetPageBySlug(ctx context.Context, kbID string, slug string) (*types.WikiPage, error) {
return s.repo.GetBySlug(ctx, kbID, slug)
}
// GetPageByID retrieves a wiki page by its ID
func (s *wikiPageService) GetPageByID(ctx context.Context, id string) (*types.WikiPage, error) {
return s.repo.GetByID(ctx, id)
}
// ListPages lists wiki pages with optional filtering and pagination
func (s *wikiPageService) ListPages(ctx context.Context, req *types.WikiPageListRequest) (*types.WikiPageListResponse, error) {
pages, total, err := s.repo.List(ctx, req)
if err != nil {
return nil, err
}
pageSize := req.PageSize
if pageSize < 1 {
pageSize = 20
}
page := req.Page
if page < 1 {
page = 1
}
totalPages := int(total) / pageSize
if int(total)%pageSize > 0 {
totalPages++
}
return &types.WikiPageListResponse{
Pages: pages,
Total: total,
Page: page,
PageSize: pageSize,
TotalPages: totalPages,
}, nil
}
// DeletePage soft-deletes a wiki page
func (s *wikiPageService) DeletePage(ctx context.Context, kbID string, slug string) error {
page, err := s.repo.GetBySlug(ctx, kbID, slug)
if err != nil {
return err
}
// Remove inbound link references from pages this page links to
s.removeInLinks(ctx, kbID, slug, page.OutLinks)
// Delete the page
if err := s.repo.Delete(ctx, kbID, slug); err != nil {
return err
}
// Delete synced chunk
s.deleteChunkForPage(ctx, page)
return nil
}
// GetIndex returns the index page for a knowledge base
func (s *wikiPageService) GetIndex(ctx context.Context, kbID string) (*types.WikiPage, error) {
page, err := s.repo.GetBySlug(ctx, kbID, "index")
if err != nil {
if errors.Is(err, repository.ErrWikiPageNotFound) {
// Create default index page
return s.createDefaultPage(ctx, kbID, "index", "Index", types.WikiPageTypeIndex,
"# Wiki Index\n\nThis is the index page. It will be automatically updated as pages are added.\n")
}
return nil, err
}
return page, nil
}
// GetLog returns the log page for a knowledge base
func (s *wikiPageService) GetLog(ctx context.Context, kbID string) (*types.WikiPage, error) {
page, err := s.repo.GetBySlug(ctx, kbID, "log")
if err != nil {
if errors.Is(err, repository.ErrWikiPageNotFound) {
return s.createDefaultPage(ctx, kbID, "log", "Log", types.WikiPageTypeLog,
"# Wiki Operation Log\n\nChronological record of wiki operations.\n")
}
return nil, err
}
return page, nil
}
// GetGraph returns the link graph data for visualization
func (s *wikiPageService) GetGraph(ctx context.Context, kbID string) (*types.WikiGraphData, error) {
pages, err := s.repo.ListAll(ctx, kbID)
if err != nil {
return nil, err
}
nodeMap := make(map[string]*types.WikiGraphNode)
var edges []types.WikiGraphEdge
// Build nodes
for _, p := range pages {
linkCount := len(p.InLinks) + len(p.OutLinks)
nodeMap[p.Slug] = &types.WikiGraphNode{
Slug: p.Slug,
Title: p.Title,
PageType: p.PageType,
LinkCount: linkCount,
}
}
// Build edges from outbound links
for _, p := range pages {
for _, target := range p.OutLinks {
if _, exists := nodeMap[target]; exists {
edges = append(edges, types.WikiGraphEdge{
Source: p.Slug,
Target: target,
})
}
}
}
nodes := make([]types.WikiGraphNode, 0, len(nodeMap))
for _, n := range nodeMap {
nodes = append(nodes, *n)
}
return &types.WikiGraphData{
Nodes: nodes,
Edges: edges,
}, nil
}
// GetStats returns aggregate statistics about the wiki
func (s *wikiPageService) GetStats(ctx context.Context, kbID string) (*types.WikiStats, error) {
counts, err := s.repo.CountByType(ctx, kbID)
if err != nil {
return nil, err
}
var total int64
for _, c := range counts {
total += c
}
orphans, err := s.repo.CountOrphans(ctx, kbID)
if err != nil {
return nil, err
}
// Count total links
pages, err := s.repo.ListAll(ctx, kbID)
if err != nil {
return nil, err
}
var totalLinks int64
for _, p := range pages {
totalLinks += int64(len(p.OutLinks))
}
// Get recent updates (last 10)
listReq := &types.WikiPageListRequest{
KnowledgeBaseID: kbID,
Page: 1,
PageSize: 10,
SortBy: "updated_at",
SortOrder: "desc",
}
recentPages, _, err := s.repo.List(ctx, listReq)
if err != nil {
return nil, err
}
return &types.WikiStats{
TotalPages: total,
PagesByType: counts,
TotalLinks: totalLinks,
OrphanCount: orphans,
RecentUpdates: recentPages,
}, nil
}
// RebuildLinks re-parses all pages and rebuilds bidirectional link references
func (s *wikiPageService) RebuildLinks(ctx context.Context, kbID string) error {
pages, err := s.repo.ListAll(ctx, kbID)
if err != nil {
return err
}
// Build slug-to-page map
pageMap := make(map[string]*types.WikiPage)
for _, p := range pages {
pageMap[p.Slug] = p
}
// Clear all inbound links first
for _, p := range pages {
p.InLinks = types.StringArray{}
}
// Re-parse outbound links and rebuild inbound links
for _, p := range pages {
p.OutLinks = s.parseOutLinks(p.Content)
for _, target := range p.OutLinks {
if tp, exists := pageMap[target]; exists {
tp.InLinks = append(tp.InLinks, p.Slug)
}
}
}
// Save all pages
for _, p := range pages {
p.UpdatedAt = time.Now()
if err := s.repo.Update(ctx, p); err != nil {
logger.Warnf(ctx, "wiki: failed to update links for page %s: %v", p.Slug, err)
}
}
return nil
}
// SearchPages performs full-text search over wiki pages
func (s *wikiPageService) SearchPages(ctx context.Context, kbID string, query string, limit int) ([]*types.WikiPage, error) {
return s.repo.Search(ctx, kbID, query, limit)
}
// --- Internal helpers ---
// parseOutLinks extracts [[wiki-link]] slugs from markdown content
func (s *wikiPageService) parseOutLinks(content string) types.StringArray {
matches := wikiLinkRegex.FindAllStringSubmatch(content, -1)
seen := make(map[string]bool)
var links types.StringArray
for _, match := range matches {
if len(match) > 1 {
slug := strings.TrimSpace(match[1])
// Handle [[Title|slug]] format
if parts := strings.SplitN(slug, "|", 2); len(parts) == 2 {
slug = strings.TrimSpace(parts[1])
}
slug = normalizeSlug(slug)
if slug != "" && !seen[slug] {
seen[slug] = true
links = append(links, slug)
}
}
}
return links
}
// normalizeSlug normalizes a wiki link slug
func normalizeSlug(slug string) string {
slug = strings.ToLower(strings.TrimSpace(slug))
slug = strings.ReplaceAll(slug, " ", "-")
return slug
}
// updateInLinks adds the source slug to the in_links of target pages
func (s *wikiPageService) updateInLinks(ctx context.Context, kbID string, sourceSlug string, targets types.StringArray) {
for _, targetSlug := range targets {
targetPage, err := s.repo.GetBySlug(ctx, kbID, targetSlug)
if err != nil {
continue // target page may not exist yet
}
if !containsString(targetPage.InLinks, sourceSlug) {
targetPage.InLinks = append(targetPage.InLinks, sourceSlug)
targetPage.UpdatedAt = time.Now()
if err := s.repo.Update(ctx, targetPage); err != nil {
logger.Warnf(ctx, "wiki: failed to update in_links for %s: %v", targetSlug, err)
}
}
}
}
// removeInLinks removes the source slug from the in_links of target pages
func (s *wikiPageService) removeInLinks(ctx context.Context, kbID string, sourceSlug string, targets types.StringArray) {
for _, targetSlug := range targets {
targetPage, err := s.repo.GetBySlug(ctx, kbID, targetSlug)
if err != nil {
continue
}
newInLinks := removeString(targetPage.InLinks, sourceSlug)
if len(newInLinks) != len(targetPage.InLinks) {
targetPage.InLinks = newInLinks
targetPage.UpdatedAt = time.Now()
if err := s.repo.Update(ctx, targetPage); err != nil {
logger.Warnf(ctx, "wiki: failed to update in_links for %s: %v", targetSlug, err)
}
}
}
}
// syncToChunk syncs a wiki page to the chunk table for retrieval pipeline integration.
// Each wiki page maps to a single chunk with ChunkType = "wiki_page".
// The chunk's KnowledgeID is set to the wiki page ID for tracking.
func (s *wikiPageService) syncToChunk(ctx context.Context, page *types.WikiPage) error {
// Build content for the chunk: title + summary + content
chunkContent := fmt.Sprintf("# %s\n\n%s\n\n%s", page.Title, page.Summary, page.Content)
chunk := &types.Chunk{
ID: "wp-" + page.ID, // prefix to avoid collision with regular chunks
TenantID: page.TenantID,
KnowledgeID: page.ID, // link back to wiki page
KnowledgeBaseID: page.KnowledgeBaseID,
Content: chunkContent,
ChunkType: types.ChunkTypeWikiPage,
IsEnabled: page.Status == types.WikiPageStatusPublished,
Status: int(types.ChunkStatusStored),
}
// Try to create; if it already exists, update
err := s.chunkRepo.CreateChunks(ctx, []*types.Chunk{chunk})
if err != nil {
// Fallback: update existing chunk
return s.chunkRepo.UpdateChunk(ctx, chunk)
}
return nil
}
// deleteChunkForPage removes the synced chunk for a wiki page
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)
}
}
// createDefaultPage creates a default system page (index, log)
func (s *wikiPageService) createDefaultPage(ctx context.Context, kbID string, slug string, title string, pageType string, content string) (*types.WikiPage, error) {
// Get KB to get tenant ID
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, kbID)
if err != nil {
return nil, fmt.Errorf("get knowledge base: %w", err)
}
page := &types.WikiPage{
ID: uuid.New().String(),
TenantID: kb.TenantID,
KnowledgeBaseID: kbID,
Slug: slug,
Title: title,
PageType: pageType,
Status: types.WikiPageStatusPublished,
Content: content,
Summary: title,
Version: 1,
}
if err := s.repo.Create(ctx, page); err != nil {
return nil, fmt.Errorf("create default %s page: %w", slug, err)
}
return page, nil
}
// containsString checks if a string slice contains a given string
func containsString(slice []string, s string) bool {
for _, v := range slice {
if v == s {
return true
}
}
return false
}
// removeString removes a string from a slice
func removeString(slice []string, s string) types.StringArray {
result := make(types.StringArray, 0, len(slice))
for _, v := range slice {
if v != s {
result = append(result, v)
}
}
return result
}
@@ -0,0 +1,125 @@
package service
import (
"testing"
"github.com/Tencent/WeKnora/internal/types"
)
func TestParseOutLinks(t *testing.T) {
svc := &wikiPageService{}
tests := []struct {
name string
content string
want []string
}{
{
name: "single link",
content: "See [[entity/acme-corp]] for details.",
want: []string{"entity/acme-corp"},
},
{
name: "multiple links",
content: "See [[entity/acme-corp]] and [[concept/rag]] for details.",
want: []string{"entity/acme-corp", "concept/rag"},
},
{
name: "duplicate links deduplicated",
content: "See [[entity/acme-corp]] and also [[entity/acme-corp]] again.",
want: []string{"entity/acme-corp"},
},
{
name: "pipe syntax: title|slug",
content: "See [[Acme Corp|entity/acme-corp]] for details.",
want: []string{"entity/acme-corp"},
},
{
name: "no links",
content: "Just plain text without any links.",
want: nil,
},
{
name: "empty content",
content: "",
want: nil,
},
{
name: "link with spaces normalized",
content: "See [[Entity/Acme Corp]] for details.",
want: []string{"entity/acme-corp"},
},
{
name: "nested brackets ignored",
content: "Not a link: [not [a] link]",
want: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := svc.parseOutLinks(tt.content)
if len(got) != len(tt.want) {
t.Errorf("parseOutLinks() = %v (len %d), want %v (len %d)", got, len(got), tt.want, len(tt.want))
return
}
for i := range got {
if got[i] != tt.want[i] {
t.Errorf("parseOutLinks()[%d] = %q, want %q", i, got[i], tt.want[i])
}
}
})
}
}
func TestNormalizeSlug(t *testing.T) {
tests := []struct {
input string
want string
}{
{"Entity/Acme Corp", "entity/acme-corp"},
{" hello ", "hello"},
{"UPPER-CASE", "upper-case"},
{"already-ok", "already-ok"},
{"", ""},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
got := normalizeSlug(tt.input)
if got != tt.want {
t.Errorf("normalizeSlug(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}
func TestContainsString(t *testing.T) {
slice := []string{"a", "b", "c"}
if !containsString(slice, "b") {
t.Error("should contain 'b'")
}
if containsString(slice, "d") {
t.Error("should not contain 'd'")
}
if containsString(nil, "a") {
t.Error("nil slice should not contain anything")
}
}
func TestRemoveString(t *testing.T) {
slice := types.StringArray{"a", "b", "c", "b"}
result := removeString(slice, "b")
if len(result) != 2 {
t.Errorf("Expected 2 items after removing 'b', got %d: %v", len(result), result)
}
if result[0] != "a" || result[1] != "c" {
t.Errorf("Unexpected result: %v", result)
}
// Remove non-existing
result2 := removeString(slice, "z")
if len(result2) != 4 {
t.Errorf("Expected 4 items (nothing removed), got %d", len(result2))
}
}