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
+127
View File
@@ -0,0 +1,127 @@
package agent
// Wiki ingest prompt templates for LLM-powered wiki page generation.
// These prompts are used by the wiki ingest pipeline to extract structured
// knowledge from raw documents and build/update wiki pages.
// WikiSummaryPrompt generates a summary page for a newly ingested document.
const WikiSummaryPrompt = `You are a wiki editor. Given the following document content, create a structured wiki summary page in Markdown format.
## Document Info
- Title: {{.Title}}
- File Name: {{.FileName}}
- File Type: {{.FileType}}
## Document Content
{{.Content}}
## Instructions
1. Write a comprehensive summary of the document in Markdown format.
2. Include the key facts, arguments, and conclusions.
3. Use proper heading hierarchy (## for sections, ### for subsections).
4. Where relevant, use [[wiki-link]] syntax to reference entities and concepts that might have their own wiki pages. Use lowercase slugs with hyphens, e.g. [[entity/company-name]] or [[concept/machine-learning]].
5. At the end, include a "## Key Takeaways" section with bullet points.
6. Write in {{.Language}}.
7. Keep the summary concise but thorough (500-1500 words depending on document length).
Output ONLY the Markdown content for the wiki page. Do not include any preamble or explanation.`
// WikiKnowledgeExtractPrompt extracts both entities and concepts in a single LLM call.
// Returns a JSON object with "entities" and "concepts" arrays.
// This replaces the former separate WikiEntityExtractPrompt and WikiConceptExtractPrompt.
const WikiKnowledgeExtractPrompt = `You are a knowledge extraction system. Analyze the following document and extract all significant entities AND key concepts.
## Document Info
- Title: {{.Title}}
## Document Content
{{.Content}}
## Instructions
Return a JSON object with two arrays: "entities" and "concepts".
### Entities (people, organizations, products, places, technologies, events, etc.)
Each entity should have:
- "name": The entity name (human-readable)
- "slug": URL-friendly slug, format "entity/<lowercase-hyphenated-name>"
- "description": A one-sentence description based on what the document says
- "details": A 2-5 sentence summary of key facts from the document
Only include entities that are substantively discussed (mentioned at least twice or described in detail). Do NOT include generic terms.
### Concepts (topics, themes, methodologies, theories, etc.)
Each concept should have:
- "name": The concept name (human-readable)
- "slug": URL-friendly slug, format "concept/<lowercase-hyphenated-name>"
- "description": A one-sentence definition or description
- "details": A 2-5 sentence explanation as discussed in the document
Only include concepts that are substantively discussed. Skip trivial or overly generic concepts.
### Deduplication Rules
- If something is a specific named thing (person, company, product, place), put it ONLY in "entities".
- If something is an abstract idea, methodology, or theory, put it ONLY in "concepts".
- Never duplicate items across the two arrays.
Output ONLY valid JSON. Example:
{
"entities": [
{
"name": "Acme Corp",
"slug": "entity/acme-corp",
"description": "A technology company specializing in AI solutions.",
"details": "Acme Corp was founded in 2020 and has grown to 500 employees. They focus on enterprise AI products and recently launched their flagship RAG platform."
}
],
"concepts": [
{
"name": "Retrieval-Augmented Generation",
"slug": "concept/retrieval-augmented-generation",
"description": "A technique that combines information retrieval with language model generation.",
"details": "RAG works by first retrieving relevant documents from a knowledge base using vector similarity search, then feeding those documents as context to an LLM for answer generation."
}
]
}`
// WikiPageUpdatePrompt incrementally updates an existing wiki page with new information.
const WikiPageUpdatePrompt = `You are a wiki editor tasked with updating an existing wiki page with new information from a recently ingested document.
## Existing Page Content
{{.ExistingContent}}
## New Information from Document "{{.NewDocTitle}}"
{{.NewContent}}
## Instructions
1. Merge the new information into the existing page content.
2. Preserve all existing information that is still valid.
3. If the new information contradicts existing content, note the contradiction explicitly: "> **Note:** This contradicts earlier information from [source]. [old claim] vs [new claim]."
4. Add new facts, details, and context from the new document.
5. Update cross-references: add new [[wiki-link]] references where appropriate.
6. Maintain the existing page structure and formatting style.
7. Add a source reference to the new document at the bottom.
8. Write in {{.Language}}.
Output ONLY the updated Markdown content. Do not include any preamble or explanation.`
// WikiIndexRebuildPrompt generates the index page content from a list of all pages.
const WikiIndexRebuildPrompt = `You are a wiki editor. Generate an index page (table of contents) for a wiki based on the following page listing.
## Pages
{{.PageListing}}
## Instructions
1. Organize pages by category (Summaries, Entities, Concepts, Analyses, etc.).
2. For each page, include: [[slug]] — one-line summary
3. Within each category, sort alphabetically.
4. Include a brief introduction at the top explaining what this wiki covers.
5. Write in {{.Language}}.
Output ONLY the Markdown content for the index page.`
// WikiLogEntryTemplate is a simple template for log entries (not LLM-generated).
const WikiLogEntryTemplate = `## [{{.Date}}] {{.Operation}} | {{.Title}}
- **Source**: {{.SourceInfo}}
- **Pages affected**: {{.PagesAffected}}
- **Summary**: {{.Summary}}
`
+11
View File
@@ -22,6 +22,12 @@ const (
// Skills-related tools (only available when skills are enabled)
ToolExecuteSkillScript = "execute_skill_script"
ToolReadSkill = "read_skill"
// Wiki-related tools (only available when wiki KBs are in scope)
ToolWikiReadPage = "wiki_read_page"
ToolWikiWritePage = "wiki_write_page"
ToolWikiSearch = "wiki_search"
ToolWikiReadIndex = "wiki_read_index"
ToolWikiLint = "wiki_lint"
)
// AvailableTool defines a simple tool metadata used by settings APIs.
@@ -48,6 +54,11 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolReadSkill, Label: "读取技能", Description: "按需读取技能内容以学习专业能力"},
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
{Name: ToolFinalAnswer, Label: "提交最终回答", Description: "提交最终回答给用户"},
{Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},
{Name: ToolWikiWritePage, Label: "写入Wiki页面", Description: "创建或更新Wiki页面"},
{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
{Name: ToolWikiReadIndex, Label: "读取Wiki索引", Description: "读取Wiki索引目录"},
{Name: ToolWikiLint, Label: "Wiki健康检查", Description: "检查Wiki健康状况"},
}
}
+442
View File
@@ -0,0 +1,442 @@
package tools
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// ---- wiki_read_page ----
type wikiReadPageTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiReadPageTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiReadPageTool{
BaseTool: NewBaseTool(
ToolWikiReadPage,
`Read a wiki page by its slug. Returns the full markdown content, metadata, and links.
Use this to read specific wiki pages when you know their slug (e.g. "entity/acme-corp", "concept/rag", "summary/document-title").`,
json.RawMessage(`{
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "The wiki page slug to read (e.g. 'entity/acme-corp', 'concept/rag')"
},
"knowledge_base_id": {
"type": "string",
"description": "Optional: specific knowledge base ID. If omitted, searches all wiki KBs."
}
},
"required": ["slug"]
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Slug string `json:"slug"`
KnowledgeBaseID string `json:"knowledge_base_id"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Invalid parameters: " + err.Error()}, nil
}
kbIDs := t.kbIDs
if params.KnowledgeBaseID != "" {
kbIDs = []string{params.KnowledgeBaseID}
}
for _, kbID := range kbIDs {
page, err := t.wikiService.GetPageBySlug(ctx, kbID, params.Slug)
if err == nil && page != nil {
output := fmt.Sprintf("# %s\n**Type**: %s | **Version**: %d | **Updated**: %s\n**Links to**: %s\n**Linked from**: %s\n\n---\n\n%s",
page.Title, page.PageType, page.Version, page.UpdatedAt.Format("2006-01-02"),
strings.Join(page.OutLinks, ", "),
strings.Join(page.InLinks, ", "),
page.Content,
)
return &types.ToolResult{Success: true, Output: output}, nil
}
}
return &types.ToolResult{Success: false, Error: fmt.Sprintf("Wiki page '%s' not found", params.Slug)}, nil
}
// ---- wiki_write_page ----
type wikiWritePageTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
tenantID uint64
}
func NewWikiWritePageTool(wikiService interfaces.WikiPageService, kbIDs []string, tenantID uint64) types.Tool {
return &wikiWritePageTool{
BaseTool: NewBaseTool(
ToolWikiWritePage,
`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.`,
json.RawMessage(`{
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "Page slug (e.g. 'synthesis/quarterly-review', 'comparison/tool-a-vs-tool-b')"
},
"title": {
"type": "string",
"description": "Human-readable page title"
},
"content": {
"type": "string",
"description": "Full Markdown content of the page. Use [[slug]] for wiki links."
},
"page_type": {
"type": "string",
"enum": ["summary", "entity", "concept", "synthesis", "comparison"],
"description": "Type of wiki page"
},
"knowledge_base_id": {
"type": "string",
"description": "Target knowledge base ID. Required if multiple wiki KBs are available."
}
},
"required": ["slug", "title", "content", "page_type"]
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
tenantID: tenantID,
}
}
func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Slug string `json:"slug"`
Title string `json:"title"`
Content string `json:"content"`
PageType string `json:"page_type"`
KnowledgeBaseID string `json:"knowledge_base_id"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Invalid parameters: " + err.Error()}, nil
}
kbID := params.KnowledgeBaseID
if kbID == "" && len(t.kbIDs) > 0 {
kbID = t.kbIDs[0]
}
if kbID == "" {
return &types.ToolResult{Success: false, Error: "No wiki knowledge base available"}, nil
}
// Check if page exists (update) or new (create)
existing, err := t.wikiService.GetPageBySlug(ctx, kbID, params.Slug)
if err == nil && existing != nil {
existing.Title = params.Title
existing.Content = params.Content
existing.PageType = params.PageType
existing.Summary = truncateForSummary(params.Content, 200)
if _, err := t.wikiService.UpdatePage(ctx, existing); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to update page: " + err.Error()}, nil
}
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("Updated wiki page [[%s]] (v%d)", params.Slug, existing.Version),
}, nil
}
// Create new page
page := &types.WikiPage{
ID: uuid.New().String(),
TenantID: t.tenantID,
KnowledgeBaseID: kbID,
Slug: params.Slug,
Title: params.Title,
Content: params.Content,
PageType: params.PageType,
Status: types.WikiPageStatusPublished,
Summary: truncateForSummary(params.Content, 200),
}
if _, err := t.wikiService.CreatePage(ctx, page); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to create page: " + err.Error()}, nil
}
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("Created wiki page [[%s]] — %s", params.Slug, params.Title),
}, nil
}
// ---- wiki_search ----
type wikiSearchTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiSearchTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiSearchTool{
BaseTool: NewBaseTool(
ToolWikiSearch,
`Search wiki pages by keyword. Returns matching pages with titles, slugs, and summaries.
Use this to find relevant wiki pages when you don't know the exact slug.`,
json.RawMessage(`{
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query (keywords or phrase)"
},
"limit": {
"type": "integer",
"description": "Max results to return (default 10)"
}
},
"required": ["query"]
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Query string `json:"query"`
Limit int `json:"limit"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Invalid parameters: " + err.Error()}, nil
}
if params.Limit <= 0 {
params.Limit = 10
}
var allPages []*types.WikiPage
for _, kbID := range t.kbIDs {
pages, err := t.wikiService.SearchPages(ctx, kbID, params.Query, params.Limit)
if err == nil {
allPages = append(allPages, pages...)
}
}
if len(allPages) == 0 {
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("No wiki pages found matching '%s'", params.Query),
}, nil
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Found %d wiki pages:\n\n", len(allPages)))
for _, p := range allPages {
fmt.Fprintf(&sb, "- **[[%s]]** (%s) — %s\n", p.Slug, p.PageType, p.Summary)
}
return &types.ToolResult{Success: true, Output: sb.String()}, nil
}
// ---- wiki_read_index ----
type wikiReadIndexTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiReadIndexTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiReadIndexTool{
BaseTool: NewBaseTool(
ToolWikiReadIndex,
`Read the wiki index page. The index lists all wiki pages organized by category.
Use this first to understand what knowledge is available in the wiki before searching or reading specific pages.`,
json.RawMessage(`{
"type": "object",
"properties": {
"knowledge_base_id": {
"type": "string",
"description": "Optional: specific knowledge base ID"
}
}
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiReadIndexTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
}
_ = json.Unmarshal(args, &params)
kbIDs := t.kbIDs
if params.KnowledgeBaseID != "" {
kbIDs = []string{params.KnowledgeBaseID}
}
var output strings.Builder
for _, kbID := range kbIDs {
indexPage, err := t.wikiService.GetIndex(ctx, kbID)
if err == nil && indexPage != nil {
if len(kbIDs) > 1 {
fmt.Fprintf(&output, "## Wiki Index (KB: %s)\n\n", kbID)
}
output.WriteString(indexPage.Content)
output.WriteString("\n\n")
}
}
if output.Len() == 0 {
return &types.ToolResult{Success: true, Output: "No wiki index found. The wiki may be empty."}, nil
}
return &types.ToolResult{Success: true, Output: output.String()}, nil
}
// ---- wiki_lint ----
type wikiLintTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiLintTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiLintTool{
BaseTool: NewBaseTool(
ToolWikiLint,
`Check the health of the wiki. Reports issues like orphan pages, broken links, and provides statistics.
Use this to identify maintenance tasks and ensure wiki quality.`,
json.RawMessage(`{
"type": "object",
"properties": {
"knowledge_base_id": {
"type": "string",
"description": "Optional: specific knowledge base ID"
}
}
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiLintTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
}
_ = json.Unmarshal(args, &params)
kbIDs := t.kbIDs
if params.KnowledgeBaseID != "" {
kbIDs = []string{params.KnowledgeBaseID}
}
var output strings.Builder
for _, kbID := range kbIDs {
stats, err := t.wikiService.GetStats(ctx, kbID)
if err != nil {
fmt.Fprintf(&output, "## Wiki Health Check (KB: %s)\nError: %v\n\n", kbID, err)
continue
}
graph, _ := t.wikiService.GetGraph(ctx, kbID)
fmt.Fprintf(&output, "## Wiki Health Check (KB: %s)\n\n", kbID)
fmt.Fprintf(&output, "### Statistics\n")
fmt.Fprintf(&output, "- **Total pages**: %d\n", stats.TotalPages)
for pt, count := range stats.PagesByType {
fmt.Fprintf(&output, " - %s: %d\n", pt, count)
}
fmt.Fprintf(&output, "- **Total links**: %d\n", stats.TotalLinks)
fmt.Fprintf(&output, "- **Orphan pages** (no inbound links): %d\n", stats.OrphanCount)
// Health score (simple heuristic)
healthScore := 100
if stats.TotalPages > 0 {
orphanPct := float64(stats.OrphanCount) / float64(stats.TotalPages) * 100
if orphanPct > 50 {
healthScore -= 30
} else if orphanPct > 25 {
healthScore -= 15
}
}
if stats.TotalLinks == 0 && stats.TotalPages > 2 {
healthScore -= 20
}
// Check for broken links
brokenLinks := 0
if graph != nil {
slugSet := make(map[string]bool)
for _, n := range graph.Nodes {
slugSet[n.Slug] = true
}
for _, e := range graph.Edges {
if !slugSet[e.Target] {
brokenLinks++
}
}
}
if brokenLinks > 0 {
healthScore -= brokenLinks * 5
fmt.Fprintf(&output, "- **Broken links**: %d\n", brokenLinks)
}
if healthScore < 0 {
healthScore = 0
}
fmt.Fprintf(&output, "\n### Health Score: %d/100\n\n", healthScore)
// Suggestions
fmt.Fprintf(&output, "### Suggestions\n")
if stats.OrphanCount > 0 {
fmt.Fprintf(&output, "- Link orphan pages from related entity/concept pages\n")
}
if brokenLinks > 0 {
fmt.Fprintf(&output, "- Fix or remove %d broken [[wiki-link]] references\n", brokenLinks)
}
if stats.TotalPages < 3 {
fmt.Fprintf(&output, "- Wiki is sparse — consider ingesting more documents\n")
}
output.WriteString("\n")
}
return &types.ToolResult{Success: true, Output: output.String()}, nil
}
// --- Helper ---
func truncateForSummary(content string, maxLen int) string {
// Take first paragraph or first maxLen chars
lines := strings.SplitN(content, "\n\n", 2)
summary := strings.TrimSpace(lines[0])
summary = strings.TrimPrefix(summary, "# ")
summary = strings.TrimPrefix(summary, "## ")
runes := []rune(summary)
if len(runes) > maxLen {
return string(runes[:maxLen]) + "..."
}
return summary
}
+103
View File
@@ -0,0 +1,103 @@
package tools
import (
"testing"
)
func TestTruncateForSummary(t *testing.T) {
tests := []struct {
name string
content string
maxLen int
want string
}{
{
name: "short content",
content: "Hello world",
maxLen: 50,
want: "Hello world",
},
{
name: "strips heading prefix",
content: "# My Title\n\nSome content",
maxLen: 50,
want: "My Title",
},
{
name: "strips h2 prefix",
content: "## Section\n\nContent here",
maxLen: 50,
want: "Section",
},
{
name: "truncates long content",
content: "This is a very long paragraph that should be truncated at some point because it exceeds the maximum length",
maxLen: 20,
want: "This is a very long ..."},
{
name: "takes first paragraph",
content: "First paragraph.\n\nSecond paragraph.",
maxLen: 100,
want: "First paragraph.",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := truncateForSummary(tt.content, tt.maxLen)
if got != tt.want {
t.Errorf("truncateForSummary() = %q, want %q", got, tt.want)
}
})
}
}
func TestWikiToolConstants(t *testing.T) {
// Verify all wiki tool constants are defined and unique
names := []string{
ToolWikiReadPage,
ToolWikiWritePage,
ToolWikiSearch,
ToolWikiReadIndex,
ToolWikiLint,
}
seen := make(map[string]bool)
for _, name := range names {
if name == "" {
t.Error("Wiki tool constant is empty")
}
if seen[name] {
t.Errorf("Duplicate wiki tool constant: %s", name)
}
seen[name] = true
// Verify name length is within OpenAI limit
if len(name) > maxFunctionNameLength {
t.Errorf("Wiki tool name too long: %s (%d chars, max %d)", name, len(name), maxFunctionNameLength)
}
}
}
func TestWikiToolsInAvailableDefinitions(t *testing.T) {
defs := AvailableToolDefinitions()
wikiTools := map[string]bool{
ToolWikiReadPage: false,
ToolWikiWritePage: false,
ToolWikiSearch: false,
ToolWikiReadIndex: false,
ToolWikiLint: false,
}
for _, def := range defs {
if _, ok := wikiTools[def.Name]; ok {
wikiTools[def.Name] = true
}
}
for name, found := range wikiTools {
if !found {
t.Errorf("Wiki tool %s missing from AvailableToolDefinitions()", name)
}
}
}
@@ -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))
}
}
+7
View File
@@ -150,6 +150,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewWebSearchStateService))
must(container.Provide(repository.NewDataSourceRepository))
must(container.Provide(repository.NewSyncLogRepository))
must(container.Provide(repository.NewWikiPageRepository))
// MCP manager for managing MCP client connections
logger.Debugf(ctx, "[Container] Registering MCP manager...")
@@ -182,6 +183,9 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewMCPServiceService))
must(container.Provide(service.NewCustomAgentService))
must(container.Provide(memoryService.NewMemoryService))
must(container.Provide(service.NewWikiPageService))
must(container.Provide(service.NewWikiIngestService, dig.Name("wikiIngest")))
must(container.Provide(service.NewWikiLintService))
// Web search service (needed by AgentService)
logger.Debugf(ctx, "[Container] Registering web search registry and providers...")
@@ -250,6 +254,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(chatpipeline.NewPluginExtractEntity))
must(container.Invoke(chatpipeline.NewPluginSearchEntity))
must(container.Invoke(chatpipeline.NewPluginSearchParallel))
must(container.Invoke(chatpipeline.NewPluginWikiBoost))
must(container.Invoke(chatpipeline.NewMemoryPlugin))
logger.Debugf(ctx, "[Container] Chat pipeline plugins registered")
@@ -279,6 +284,8 @@ func BuildContainer(container *dig.Container) *dig.Container {
// Data source handler
must(container.Provide(handler.NewDataSourceHandler))
// Wiki page handler
must(container.Provide(handler.NewWikiPageHandler))
// IM integration
logger.Debugf(ctx, "[Container] Registering IM integration...")
must(container.Provide(imPkg.NewService))
+482
View File
@@ -0,0 +1,482 @@
package handler
import (
stderrors "errors"
"fmt"
"net/http"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
)
// WikiPageHandler handles HTTP requests for wiki page operations
type WikiPageHandler struct {
wikiService interfaces.WikiPageService
kbService interfaces.KnowledgeBaseService
lintService *service.WikiLintService
}
// NewWikiPageHandler creates a new wiki page handler
func NewWikiPageHandler(
wikiService interfaces.WikiPageService,
kbService interfaces.KnowledgeBaseService,
lintService *service.WikiLintService,
) *WikiPageHandler {
return &WikiPageHandler{
wikiService: wikiService,
kbService: kbService,
lintService: lintService,
}
}
// validateWikiKB validates that the KB exists and is a wiki type
func (h *WikiPageHandler) validateWikiKB(c *gin.Context) (string, uint64, error) {
ctx := c.Request.Context()
kbID := secutils.SanitizeForLog(c.Param("kb_id"))
tenantID := c.GetUint64(types.TenantIDContextKey.String())
if kbID == "" {
return "", 0, errors.NewBadRequestError("Knowledge base ID is required")
}
kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
return "", 0, errors.NewNotFoundError("Knowledge base not found")
}
if kb.Type != types.KnowledgeBaseTypeWiki {
return "", 0, errors.NewBadRequestError("Knowledge base is not a wiki type")
}
return kbID, tenantID, nil
}
// getSlugParam extracts and cleans the slug from gin's wildcard path param
func getSlugParam(c *gin.Context) string {
slug := getSlugParam(c)
// gin wildcard params include a leading "/"
slug = strings.TrimPrefix(slug, "/")
return strings.TrimSpace(slug)
}
// ListPages godoc
// @Summary List wiki pages
// @Description List wiki pages with optional filtering and pagination
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param page_type query string false "Filter by page type"
// @Param status query string false "Filter by status"
// @Param query query string false "Full-text search"
// @Param page query int false "Page number"
// @Param page_size query int false "Page size"
// @Param sort_by query string false "Sort field"
// @Param sort_order query string false "Sort order (asc/desc)"
// @Success 200 {object} types.WikiPageListResponse
// @Failure 400 {object} errors.AppError
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages [get]
func (h *WikiPageHandler) ListPages(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
req := &types.WikiPageListRequest{
KnowledgeBaseID: kbID,
PageType: c.Query("page_type"),
Status: c.Query("status"),
Query: c.Query("query"),
Page: page,
PageSize: pageSize,
SortBy: c.DefaultQuery("sort_by", "updated_at"),
SortOrder: c.DefaultQuery("sort_order", "desc"),
}
resp, err := h.wikiService.ListPages(c.Request.Context(), req)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, resp)
}
// CreatePage godoc
// @Summary Create a wiki page
// @Description Create a new wiki page in the knowledge base
// @Tags Wiki
// @Accept json
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param page body types.WikiPage true "Wiki page data"
// @Success 201 {object} types.WikiPage
// @Failure 400 {object} errors.AppError
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages [post]
func (h *WikiPageHandler) CreatePage(c *gin.Context) {
kbID, tenantID, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var page types.WikiPage
if err := c.ShouldBindJSON(&page); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
return
}
page.KnowledgeBaseID = kbID
page.TenantID = tenantID
created, err := h.wikiService.CreatePage(c.Request.Context(), &page)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusCreated, created)
}
// GetPage godoc
// @Summary Get a wiki page by slug
// @Description Retrieve a wiki page by its slug
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param slug path string true "Page slug"
// @Success 200 {object} types.WikiPage
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [get]
func (h *WikiPageHandler) GetPage(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
slug := getSlugParam(c)
if slug == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
return
}
page, err := h.wikiService.GetPageBySlug(c.Request.Context(), kbID, slug)
if err != nil {
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, page)
}
// UpdatePage godoc
// @Summary Update a wiki page
// @Description Update an existing wiki page by slug
// @Tags Wiki
// @Accept json
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param slug path string true "Page slug"
// @Param page body types.WikiPage true "Updated wiki page data"
// @Success 200 {object} types.WikiPage
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [put]
func (h *WikiPageHandler) UpdatePage(c *gin.Context) {
kbID, tenantID, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
slug := getSlugParam(c)
if slug == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
return
}
var page types.WikiPage
if err := c.ShouldBindJSON(&page); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
return
}
page.KnowledgeBaseID = kbID
page.TenantID = tenantID
page.Slug = slug
updated, err := h.wikiService.UpdatePage(c.Request.Context(), &page)
if err != nil {
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, updated)
}
// DeletePage godoc
// @Summary Delete a wiki page
// @Description Soft-delete a wiki page by slug
// @Tags Wiki
// @Param kb_id path string true "Knowledge base ID"
// @Param slug path string true "Page slug"
// @Success 204
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [delete]
func (h *WikiPageHandler) DeletePage(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
slug := getSlugParam(c)
if slug == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
return
}
if err := h.wikiService.DeletePage(c.Request.Context(), kbID, slug); err != nil {
if stderrors.Is(err, repository.ErrWikiPageNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Status(http.StatusNoContent)
}
// GetIndex godoc
// @Summary Get wiki index page
// @Description Returns the wiki index page (creates default if not exists)
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Success 200 {object} types.WikiPage
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/index [get]
func (h *WikiPageHandler) GetIndex(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
page, err := h.wikiService.GetIndex(c.Request.Context(), kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, page)
}
// GetLog godoc
// @Summary Get wiki operation log
// @Description Returns the wiki operation log page (creates default if not exists)
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Success 200 {object} types.WikiPage
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/log [get]
func (h *WikiPageHandler) GetLog(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
page, err := h.wikiService.GetLog(c.Request.Context(), kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, page)
}
// GetGraph godoc
// @Summary Get wiki link graph
// @Description Returns the wiki link graph data for visualization
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Success 200 {object} types.WikiGraphData
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/graph [get]
func (h *WikiPageHandler) GetGraph(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
graph, err := h.wikiService.GetGraph(c.Request.Context(), kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, graph)
}
// GetStats godoc
// @Summary Get wiki statistics
// @Description Returns aggregate statistics about the wiki
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Success 200 {object} types.WikiStats
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/stats [get]
func (h *WikiPageHandler) GetStats(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
stats, err := h.wikiService.GetStats(c.Request.Context(), kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, stats)
}
// SearchPages godoc
// @Summary Search wiki pages
// @Description Full-text search over wiki pages
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param q query string true "Search query"
// @Param limit query int false "Max results (default 10)"
// @Success 200 {array} types.WikiPage
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/search [get]
func (h *WikiPageHandler) SearchPages(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
query := c.Query("q")
if query == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Search query 'q' is required"})
return
}
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
pages, err := h.wikiService.SearchPages(c.Request.Context(), kbID, query, limit)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"pages": pages})
}
// RebuildLinks godoc
// @Summary Rebuild wiki links
// @Description Re-parse all pages and rebuild bidirectional link references
// @Tags Wiki
// @Param kb_id path string true "Knowledge base ID"
// @Success 200 {object} map[string]string
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/rebuild-links [post]
func (h *WikiPageHandler) RebuildLinks(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := h.wikiService.RebuildLinks(c.Request.Context(), kbID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Links rebuilt successfully"})
}
// Lint godoc
// @Summary Run wiki lint
// @Description Perform a comprehensive health check on the wiki
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Success 200 {object} service.WikiLintReport
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/lint [get]
func (h *WikiPageHandler) Lint(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
report, err := h.lintService.RunLint(c.Request.Context(), kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, report)
}
// AutoFix godoc
// @Summary Auto-fix wiki issues
// @Description Automatically fix fixable wiki issues (broken links, etc.)
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Success 200 {object} map[string]interface{}
// @Security Bearer
// @Router /api/v1/knowledgebase/{kb_id}/wiki/auto-fix [post]
func (h *WikiPageHandler) AutoFix(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
fixed, err := h.lintService.AutoFix(c.Request.Context(), kbID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"fixed": fixed, "message": fmt.Sprintf("Auto-fixed %d issues", fixed)})
}
+29
View File
@@ -64,6 +64,7 @@ type RouterParams struct {
IMHandler *handler.IMHandler
DataSourceHandler *handler.DataSourceHandler
WeKnoraCloudHandler *handler.WeKnoraCloudHandler
WikiPageHandler *handler.WikiPageHandler
}
// NewRouter 创建新的路由
@@ -148,6 +149,7 @@ func NewRouter(params RouterParams) *gin.Engine {
RegisterIMChannelRoutes(v1, params.IMHandler)
RegisterDataSourceRoutes(v1, params.DataSourceHandler)
RegisterWeKnoraCloudRoutes(v1, params.WeKnoraCloudHandler)
RegisterWikiPageRoutes(v1, params.WikiPageHandler)
}
return r
@@ -833,3 +835,30 @@ func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraClou
r.POST("/weknoracloud/credentials", handler.SaveCredentials)
r.GET("/models/weknoracloud/status", handler.Status)
}
// RegisterWikiPageRoutes registers wiki page related routes
func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler) {
wiki := r.Group("/knowledgebase/:kb_id/wiki")
{
// Page CRUD
wiki.GET("/pages", wikiHandler.ListPages)
wiki.POST("/pages", wikiHandler.CreatePage)
wiki.GET("/pages/*slug", wikiHandler.GetPage)
wiki.PUT("/pages/*slug", wikiHandler.UpdatePage)
wiki.DELETE("/pages/*slug", wikiHandler.DeletePage)
// Special pages
wiki.GET("/index", wikiHandler.GetIndex)
wiki.GET("/log", wikiHandler.GetLog)
// Graph and stats
wiki.GET("/graph", wikiHandler.GetGraph)
wiki.GET("/stats", wikiHandler.GetStats)
// Search and maintenance
wiki.GET("/search", wikiHandler.SearchPages)
wiki.POST("/rebuild-links", wikiHandler.RebuildLinks)
wiki.GET("/lint", wikiHandler.Lint)
wiki.POST("/auto-fix", wikiHandler.AutoFix)
}
}
+2
View File
@@ -80,6 +80,7 @@ type SyncTaskParams struct {
DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`
ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`
KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"`
WikiIngest interfaces.TaskHandler `name:"wikiIngest"`
}
// RegisterSyncHandlers registers all task handlers on the SyncTaskExecutor.
@@ -100,5 +101,6 @@ func RegisterSyncHandlers(params SyncTaskParams) {
params.Executor.RegisterHandler(types.TypeImageMultimodal, params.ImageMultimodal.Handle)
params.Executor.RegisterHandler(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)
params.Executor.RegisterHandler(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)
params.Executor.RegisterHandler(types.TypeWikiIngest, params.WikiIngest.Handle)
logger.Infof(context.Background(), "[SyncTask] All task handlers registered (Lite mode, no Redis)")
}
+4
View File
@@ -24,6 +24,7 @@ type AsynqTaskParams struct {
DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"`
ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"`
KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"`
WikiIngest interfaces.TaskHandler `name:"wikiIngest"`
}
func getAsynqRedisClientOpt() *asynq.RedisClientOpt {
@@ -116,6 +117,9 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux {
// Register data source sync handler
mux.HandleFunc(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)
// Register wiki ingest handler
mux.HandleFunc(types.TypeWikiIngest, params.WikiIngest.Handle)
go func() {
// Start the server
if err := params.Server.Run(mux); err != nil {
+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)
}
}