feat(wiki): implement folder management features in wiki API

Add new API functions for managing wiki folders, including creating, updating, deleting, and listing folders. Introduce a new WikiFolder interface to represent folder structure and enhance the WikiBrowser component with folder actions. Update internationalization strings for folder-related actions in English, Korean, Russian, and Chinese locales. Refactor existing code to accommodate folder hierarchy and improve user experience in the wiki browser.
This commit is contained in:
wizardchen
2026-06-16 23:48:35 +08:00
committed by lyingbug
parent 83eeec0ddf
commit e76738d054
24 changed files with 1903 additions and 399 deletions
+157 -106
View File
@@ -109,10 +109,8 @@ func (r *wikiPageRepository) UpdateMeta(ctx context.Context, page *types.WikiPag
"chunk_refs": page.ChunkRefs,
"page_metadata": page.PageMetadata,
"parent_slug": page.ParentSlug,
"folder_id": page.FolderID,
"category_path": page.CategoryPath,
"category_l1": page.CategoryL1,
"category_l2": page.CategoryL2,
"category_l3": page.CategoryL3,
"wiki_path": page.WikiPath,
"depth": page.Depth,
"sort_order": page.SortOrder,
@@ -180,6 +178,9 @@ func (r *wikiPageRepository) List(ctx context.Context, req *types.WikiPageListRe
// whose stored text is json.Marshal of the cleaned path, so we compare
// against the same encoding. Postgres needs an explicit jsonb cast for array
// equality; SQLite stores JSON as TEXT and compares directly.
if req.FolderID != nil {
query = query.Where("folder_id = ?", *req.FolderID)
}
if req.CategoryDepth != nil {
query = query.Where("depth = ?", *req.CategoryDepth)
}
@@ -414,13 +415,11 @@ func (r *wikiPageRepository) ListBySlugs(
return out, nil
}
// ListDistinctCategoryPaths returns the distinct non-empty category paths used
// by entity/concept pages. The distinctness is pushed entirely to SQL over the
// flat category_l1/l2/l3 columns (indexed by idx_wiki_pages_category_levels),
// so the cost scales with the number of distinct folders — not the page count —
// and there is no full-table scan to bound. maxPaths caps the returned folder
// count. Used by the batch taxonomy planner as the candidate pool of existing
// folders to reuse (similarity preprocessing then narrows it per batch).
// ListDistinctCategoryPaths returns the materialized paths of existing wiki
// folders (split into segments), ordered by path and capped at maxPaths. Used
// by the batch taxonomy planner as the candidate pool of folders to reuse
// (similarity preprocessing then narrows it per batch). The folder tree is the
// single source of truth, so this no longer scans page rows.
func (r *wikiPageRepository) ListDistinctCategoryPaths(
ctx context.Context,
kbID string,
@@ -429,123 +428,175 @@ func (r *wikiPageRepository) ListDistinctCategoryPaths(
if maxPaths <= 0 {
maxPaths = 150
}
type row struct {
L1 string `gorm:"column:category_l1"`
L2 string `gorm:"column:category_l2"`
L3 string `gorm:"column:category_l3"`
}
var rows []row
var paths []string
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Distinct("category_l1", "category_l2", "category_l3").
Where("knowledge_base_id = ? AND page_type IN ? AND status <> ? AND category_l1 <> ?",
kbID,
[]string{types.WikiPageTypeEntity, types.WikiPageTypeConcept},
types.WikiPageStatusArchived,
"",
).
Order("category_l1 ASC").
Order("category_l2 ASC").
Order("category_l3 ASC").
Model(&types.WikiFolder{}).
Where("knowledge_base_id = ? AND path <> ?", kbID, "").
Order("path ASC").
Limit(maxPaths).
Scan(&rows).Error; err != nil {
Pluck("path", &paths).Error; err != nil {
return nil, err
}
out := make([][]string, 0, len(rows))
for _, rw := range rows {
path := make([]string, 0, 3)
for _, label := range []string{rw.L1, rw.L2, rw.L3} {
if label == "" {
break // levels are contiguous; an empty level ends the path
}
path = append(path, label)
}
if len(path) > 0 {
out = append(out, path)
out := make([][]string, 0, len(paths))
for _, p := range paths {
if seg := types.CleanWikiCategoryPath(strings.Split(p, "/")); len(seg) > 0 {
out = append(out, seg)
}
}
return out, nil
}
// wikiCategoryLevelColumns maps a parent depth (0/1/2) to the flat level column
// holding that depth's direct child. Depth >= WikiCategoryMaxDepth has no child.
var wikiCategoryLevelColumns = []string{"category_l1", "category_l2", "category_l3"}
// --- Folder tree (wiki_folders) ---
// ListDistinctCategoryPathsByType returns the DIRECT child folders of
// parentPath for the given page types, with the page count under each child,
// paginated. Grouping and pagination are pushed entirely to SQL over the flat
// category_l1/l2/l3 columns (kept in sync by normalizeWikiHierarchy), so this
// is cheap, indexable, and identical across Postgres and SQLite — no JSON
// parsing and no full in-memory scan. The second return value is the total
// number of distinct child folders (before pagination).
func (r *wikiPageRepository) ListDistinctCategoryPathsByType(
ctx context.Context,
kbID string,
pageTypes []string,
parentPath []string,
page, pageSize int,
) ([]types.WikiCategoryPath, int, error) {
if len(pageTypes) == 0 {
return nil, 0, nil
}
parent := types.CleanWikiCategoryPath(parentPath)
if len(parent) >= len(wikiCategoryLevelColumns) {
return nil, 0, nil // no level deeper than the cap can exist
}
childCol := wikiCategoryLevelColumns[len(parent)]
// ErrWikiFolderNotFound is returned when a wiki folder is not found.
var ErrWikiFolderNotFound = errors.New("wiki folder not found")
// Build the shared WHERE as a closure so the count and the page query each
// start from a fresh statement (GORM chains mutate in place otherwise).
scoped := func() *gorm.DB {
q := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Where("knowledge_base_id = ? AND page_type IN ? AND status <> ?",
kbID, pageTypes, types.WikiPageStatusArchived).
Where(childCol+" <> ?", "")
for i, label := range parent {
q = q.Where(wikiCategoryLevelColumns[i]+" = ?", label)
// ErrWikiFolderConflict is returned when a sibling folder with the same name
// already exists under the same parent.
var ErrWikiFolderConflict = errors.New("wiki folder name conflict")
func (r *wikiPageRepository) CreateFolder(ctx context.Context, folder *types.WikiFolder) error {
return r.db.WithContext(ctx).Create(folder).Error
}
func (r *wikiPageRepository) GetFolderByID(ctx context.Context, kbID string, id string) (*types.WikiFolder, error) {
var folder types.WikiFolder
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND id = ?", kbID, id).
First(&folder).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWikiFolderNotFound
}
return q
return nil, err
}
return &folder, nil
}
var total int64
if err := scoped().Distinct(childCol).Count(&total).Error; err != nil {
return nil, 0, err
}
if total == 0 {
return nil, 0, nil
func (r *wikiPageRepository) GetChildFolderByName(
ctx context.Context, kbID string, parentID string, name string,
) (*types.WikiFolder, error) {
var folder types.WikiFolder
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND parent_id = ? AND name = ?", kbID, parentID, name).
First(&folder).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, ErrWikiFolderNotFound
}
return nil, err
}
return &folder, nil
}
if page < 1 {
page = 1
}
if pageSize < 1 {
pageSize = 2000
func (r *wikiPageRepository) ListChildFolders(
ctx context.Context, kbID string, parentID string,
) ([]*types.WikiFolder, error) {
var folders []*types.WikiFolder
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND parent_id = ?", kbID, parentID).
Order("sort_order ASC").
Order("name ASC").
Find(&folders).Error; err != nil {
return nil, err
}
return folders, nil
}
type row struct {
Label string `gorm:"column:label"`
Cnt int64 `gorm:"column:cnt"`
}
var rows []row
if err := scoped().
Select(childCol + " AS label, COUNT(*) AS cnt").
Group(childCol).
Order("label ASC").
Offset((page - 1) * pageSize).
Limit(pageSize).
Scan(&rows).Error; err != nil {
return nil, 0, err
func (r *wikiPageRepository) ListAllFolders(ctx context.Context, kbID string) ([]*types.WikiFolder, error) {
var folders []*types.WikiFolder
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ?", kbID).
Order("depth ASC").
Order("path ASC").
Find(&folders).Error; err != nil {
return nil, err
}
return folders, nil
}
out := make([]types.WikiCategoryPath, 0, len(rows))
for _, rw := range rows {
full := append(append([]string(nil), parent...), rw.Label)
out = append(out, types.WikiCategoryPath{Path: full, Count: rw.Cnt})
func (r *wikiPageRepository) UpdateFolder(ctx context.Context, folder *types.WikiFolder) error {
result := r.db.WithContext(ctx).
Model(&types.WikiFolder{}).
Where("id = ?", folder.ID).
Updates(map[string]interface{}{
"parent_id": folder.ParentID,
"name": folder.Name,
"path": folder.Path,
"depth": folder.Depth,
"sort_order": folder.SortOrder,
"updated_at": folder.UpdatedAt,
})
if result.Error != nil {
return result.Error
}
return out, int(total), nil
if result.RowsAffected == 0 {
return ErrWikiFolderNotFound
}
return nil
}
func (r *wikiPageRepository) DeleteFolder(ctx context.Context, kbID string, id string) error {
result := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND id = ?", kbID, id).
Delete(&types.WikiFolder{})
if result.Error != nil {
return result.Error
}
if result.RowsAffected == 0 {
return ErrWikiFolderNotFound
}
return nil
}
func (r *wikiPageRepository) CountPagesInFolder(ctx context.Context, kbID string, folderID string) (int64, error) {
var count int64
if err := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Where("knowledge_base_id = ? AND folder_id = ? AND status <> ?",
kbID, folderID, types.WikiPageStatusArchived).
Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
func (r *wikiPageRepository) CountPagesByFolder(
ctx context.Context, kbID string, pageTypes []string,
) (map[string]int64, error) {
type folderCount struct {
FolderID string
Cnt int64
}
var rows []folderCount
q := r.db.WithContext(ctx).
Model(&types.WikiPage{}).
Select("folder_id, COUNT(*) as cnt").
Where("knowledge_base_id = ? AND status <> ?", kbID, types.WikiPageStatusArchived)
if len(pageTypes) > 0 {
q = q.Where("page_type IN ?", pageTypes)
}
if err := q.Group("folder_id").Scan(&rows).Error; err != nil {
return nil, err
}
out := make(map[string]int64, len(rows))
for _, row := range rows {
out[row.FolderID] = row.Cnt
}
return out, nil
}
func (r *wikiPageRepository) ListPagesByFolderIDs(
ctx context.Context, kbID string, folderIDs []string,
) ([]*types.WikiPage, error) {
if len(folderIDs) == 0 {
return nil, nil
}
var pages []*types.WikiPage
if err := r.db.WithContext(ctx).
Where("knowledge_base_id = ? AND folder_id IN ?", kbID, folderIDs).
Find(&pages).Error; err != nil {
return nil, err
}
return pages, nil
}
// ListSummariesByKnowledgeIDs returns summary-page content keyed by the
@@ -30,13 +30,11 @@ CREATE TABLE IF NOT EXISTS wiki_pages (
content TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
parent_slug VARCHAR(255) NOT NULL DEFAULT '',
folder_id VARCHAR(36) NOT NULL DEFAULT '',
category_path TEXT DEFAULT '[]',
wiki_path VARCHAR(1024) NOT NULL DEFAULT '',
depth INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
category_l1 VARCHAR(255) NOT NULL DEFAULT '',
category_l2 VARCHAR(255) NOT NULL DEFAULT '',
category_l3 VARCHAR(255) NOT NULL DEFAULT '',
source_refs TEXT DEFAULT '[]',
chunk_refs TEXT DEFAULT '[]',
in_links TEXT DEFAULT '[]',
@@ -50,11 +48,29 @@ CREATE TABLE IF NOT EXISTS wiki_pages (
);
`
// wikiFoldersTestDDL mirrors the production wiki_folders DDL for SQLite.
const wikiFoldersTestDDL = `
CREATE TABLE IF NOT EXISTS wiki_folders (
id VARCHAR(36) PRIMARY KEY,
tenant_id INTEGER NOT NULL DEFAULT 0,
knowledge_base_id VARCHAR(36) NOT NULL,
parent_id VARCHAR(36) NOT NULL DEFAULT '',
name VARCHAR(255) NOT NULL,
path VARCHAR(1024) NOT NULL DEFAULT '',
depth INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
deleted_at DATETIME
);
`
func setupWikiPagesTestDB(t *testing.T) *gorm.DB {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
require.NoError(t, err)
require.NoError(t, db.Exec(wikiPagesTestDDL).Error)
require.NoError(t, db.Exec(wikiFoldersTestDDL).Error)
return db
}
@@ -89,9 +105,6 @@ func makeCategorizedWikiPage(kbID, slug, pageType, status string, categoryPath .
if len(categoryPath) > 0 {
page.WikiPath = pageType + "/" + strings.Join(categoryPath, "/") + "/" + page.Title
page.Depth = len(categoryPath)
// Mirror the flat level columns the directory query groups on, the same
// way normalizeWikiHierarchy would on a real write.
page.CategoryL1, page.CategoryL2, page.CategoryL3 = types.WikiCategoryLevels(categoryPath)
}
return page
}
@@ -130,57 +143,68 @@ func TestList_WikiPathSortReturnsCategorizedPagesFirst(t *testing.T) {
assert.Equal(t, "entity/001-root", got[2].Slug)
}
// TestListDistinctCategoryPathsByType_GroupsAndPaginatesInSQL verifies the
// directory listing groups direct child folders, counts pages under each
// (including deeper pages), and paginates — all pushed to SQL over the flat
// level columns, so it must behave identically on SQLite.
func TestListDistinctCategoryPathsByType_GroupsAndPaginatesInSQL(t *testing.T) {
// TestFolderTree_CRUDAndChildListing exercises the wiki_folders repository:
// child listing ordered by sort_order/name, find-by-name, page counting under
// a folder, and that ListDistinctCategoryPaths reflects the folder paths.
func TestFolderTree_CRUDAndChildListing(t *testing.T) {
db := setupWikiPagesTestDB(t)
repo := NewWikiPageRepository(db)
ctx := context.Background()
pages := []*types.WikiPage{
makeCategorizedWikiPage("kb-c", "entity/a1", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI"),
makeCategorizedWikiPage("kb-c", "entity/a2", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI"),
makeCategorizedWikiPage("kb-c", "entity/a3", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI", "LLM"),
makeCategorizedWikiPage("kb-c", "entity/p1", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "人物"),
makeWikiPage("kb-c", "entity/root", types.WikiPageTypeEntity, types.WikiPageStatusPublished),
makeCategorizedWikiPage("kb-c", "entity/arch", types.WikiPageTypeEntity, types.WikiPageStatusArchived, "AI"),
mk := func(id, parentID, name, path string, depth int) *types.WikiFolder {
return &types.WikiFolder{
ID: id, TenantID: 1, KnowledgeBaseID: "kb-f",
ParentID: parentID, Name: name, Path: path, Depth: depth,
CreatedAt: time.Now(), UpdatedAt: time.Now(),
}
}
for _, p := range pages {
ai := mk("f-ai", types.WikiFolderRootID, "AI", "AI", 1)
people := mk("f-people", types.WikiFolderRootID, "人物", "人物", 1)
llm := mk("f-llm", "f-ai", "LLM", "AI/LLM", 2)
for _, f := range []*types.WikiFolder{ai, people, llm} {
require.NoError(t, repo.CreateFolder(ctx, f))
}
// Root children: AI, 人物 (ordered by name within equal sort_order).
roots, err := repo.ListChildFolders(ctx, "kb-f", types.WikiFolderRootID)
require.NoError(t, err)
require.Len(t, roots, 2)
// Direct child of AI is LLM.
child, err := repo.GetChildFolderByName(ctx, "kb-f", "f-ai", "LLM")
require.NoError(t, err)
assert.Equal(t, "f-llm", child.ID)
// Missing child surfaces the typed not-found error.
_, err = repo.GetChildFolderByName(ctx, "kb-f", "f-ai", "Nope")
assert.ErrorIs(t, err, ErrWikiFolderNotFound)
// Pages filed into folders are counted (archived excluded).
pAI := makeCategorizedWikiPage("kb-f", "entity/a1", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI")
pAI.FolderID = "f-ai"
pLLM := makeCategorizedWikiPage("kb-f", "entity/a2", types.WikiPageTypeEntity, types.WikiPageStatusPublished, "AI", "LLM")
pLLM.FolderID = "f-llm"
pArch := makeCategorizedWikiPage("kb-f", "entity/a3", types.WikiPageTypeEntity, types.WikiPageStatusArchived, "AI")
pArch.FolderID = "f-ai"
for _, p := range []*types.WikiPage{pAI, pLLM, pArch} {
require.NoError(t, repo.Create(ctx, p))
}
types4 := []string{types.WikiPageTypeEntity}
// Root level: two folders (AI, 人物); the loose root page and archived page
// are excluded. AI counts all 3 non-archived pages whose first level is AI.
roots, total, err := repo.ListDistinctCategoryPathsByType(ctx, "kb-c", types4, nil, 1, 100)
aiCount, err := repo.CountPagesInFolder(ctx, "kb-f", "f-ai")
require.NoError(t, err)
assert.Equal(t, 2, total)
require.Len(t, roots, 2)
byLabel := map[string]int64{}
for _, p := range roots {
require.Len(t, p.Path, 1)
byLabel[p.Path[0]] = p.Count
}
assert.Equal(t, int64(3), byLabel["AI"])
assert.Equal(t, int64(1), byLabel["人物"])
assert.Equal(t, int64(1), aiCount, "archived page excluded; LLM page is under f-llm, not f-ai")
// Child of [AI]: only the [AI, LLM] page.
children, total, err := repo.ListDistinctCategoryPathsByType(ctx, "kb-c", types4, []string{"AI"}, 1, 100)
// ListDistinctCategoryPaths returns the folder paths split into segments.
paths, err := repo.ListDistinctCategoryPaths(ctx, "kb-f", 100)
require.NoError(t, err)
assert.Equal(t, 1, total)
require.Len(t, children, 1)
assert.Equal(t, []string{"AI", "LLM"}, children[0].Path)
assert.Equal(t, int64(1), children[0].Count)
assert.Contains(t, paths, []string{"AI"})
assert.Contains(t, paths, []string{"AI", "LLM"})
assert.Contains(t, paths, []string{"人物"})
// Pagination: page size 1 over the two root folders returns one row but the
// total still reflects both distinct folders.
firstPage, total, err := repo.ListDistinctCategoryPathsByType(ctx, "kb-c", types4, nil, 1, 1)
// Pages can be fetched by their folder ids for subtree recompute.
pages, err := repo.ListPagesByFolderIDs(ctx, "kb-f", []string{"f-ai", "f-llm"})
require.NoError(t, err)
assert.Equal(t, 2, total)
require.Len(t, firstPage, 1)
assert.Len(t, pages, 3)
}
// TestListByTypeLight_ProjectsNarrowColumnsAndExcludesArchived verifies
+9 -6
View File
@@ -659,12 +659,15 @@ type WikiBatchContext struct {
// three valid values.
ExtractionGranularity types.WikiExtractionGranularity
// PlannedCategory holds the per-slug directory path assigned by the batch
// taxonomy planning pass (planBatchTaxonomy), keyed by page slug. Reduce
// applies it only to pages that don't already have a category, so the whole
// batch lands on one coherent tree without churning user-curated pages.
// Populated before the reduce phase and read-only during it.
PlannedCategory map[string][]string
// PlannedFolderID holds the per-slug wiki_folders.id assigned by the batch
// taxonomy planning pass (planBatchTaxonomy + folder resolution), keyed by
// page slug. Reduce applies it only to pages that aren't already filed
// (FolderID == ""), so the whole batch lands on one coherent tree without
// churning user-curated placements. The folders themselves are created
// sequentially before reduce, so the parallel reduce phase only assigns
// pre-resolved ids and never races on folder creation. Read-only during
// reduce.
PlannedFolderID map[string]string
}
// SlugUpdate represents a single update operation for a specific slug
@@ -490,7 +490,8 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
// single pass assigns every new entity/concept slug a coherent category_path
// that reuses existing folders. Reduce then only applies the plan to pages
// that don't already have a category (user-curated pages are never churned).
batchCtx.PlannedCategory = s.planBatchTaxonomy(ctx, chatModel, kb, slugUpdates, lang)
batchCtx.PlannedFolderID = s.resolvePlannedFolders(ctx, kb,
s.planBatchTaxonomy(ctx, chatModel, kb, slugUpdates, lang))
// 2. REDUCE PHASE (Parallel upserting grouped by Slug)
egReduce, reduceCtx := errgroup.WithContext(ctx)
@@ -1637,13 +1638,14 @@ func (s *wikiIngestService) reduceSlugUpdates(
}
}
// Apply the batch taxonomy plan, but only to pages that don't already have a
// category — so brand-new pages get filed coherently while previously-filed
// or user-curated categories are preserved (manual edits are authoritative).
if len(page.CategoryPath) == 0 && batchCtx != nil {
if planned := types.CleanWikiCategoryPath(batchCtx.PlannedCategory[slug]); len(planned) > 0 {
page.CategoryPath = types.StringArray(planned)
page.WikiPath = ""
// Apply the batch taxonomy plan, but only to pages that aren't already
// filed — so brand-new pages get a coherent folder while previously-filed
// or user-moved pages keep their placement (manual edits are authoritative).
// The page's category_path cache is derived from folder_id downstream by
// CreatePage/UpdatePage, so assigning the folder id is sufficient here.
if page.FolderID == "" && batchCtx != nil {
if fid := batchCtx.PlannedFolderID[slug]; fid != "" {
page.FolderID = fid
}
}
@@ -101,6 +101,44 @@ func (s *wikiIngestService) planBatchTaxonomy(
return result
}
// resolvePlannedFolders reifies the planner's per-slug paths into real
// wiki_folders rows and returns a slug -> folder id map. Folder creation is
// done here, sequentially and before the parallel reduce phase, so reduce only
// assigns pre-resolved ids and never races two goroutines into creating the
// same folder. Distinct paths are resolved once and cached. Blank paths (and
// any resolution failure) map to the root and are simply omitted.
func (s *wikiIngestService) resolvePlannedFolders(
ctx context.Context, kb *types.KnowledgeBase, planned map[string][]string,
) map[string]string {
if kb == nil || len(planned) == 0 || s.wikiService == nil {
return nil
}
pathCache := make(map[string]string) // "a/b" -> folder id
out := make(map[string]string, len(planned))
for slug, path := range planned {
clean := types.CleanWikiCategoryPath(path)
if len(clean) == 0 {
continue
}
key := strings.Join(clean, "/")
fid, ok := pathCache[key]
if !ok {
resolved, _, err := s.wikiService.FindOrCreateFolderPath(ctx, kb.ID, kb.TenantID, clean)
if err != nil {
logger.Warnf(ctx, "wiki ingest: resolve folder %q failed: %v", key, err)
pathCache[key] = "" // negative-cache so we don't retry per slug
continue
}
fid = resolved
pathCache[key] = fid
}
if fid != "" {
out[slug] = fid
}
}
return out
}
// selectRelevantFolders narrows the existing folder pool to the subset worth
// showing the planner for THIS batch. A healthy navigation directory is small,
// so it is fed whole (perfect reuse recall, no embedding cost). Only once folders
+395 -15
View File
@@ -67,6 +67,9 @@ func (s *wikiPageService) CreatePage(ctx context.Context, page *types.WikiPage)
// Parse outbound links from content
page.OutLinks = s.parseOutLinks(page.Content)
if err := s.applyFolderToPage(ctx, page); err != nil {
return nil, err
}
normalizeWikiHierarchy(page)
now := time.Now()
@@ -117,13 +120,17 @@ func (s *wikiPageService) UpdatePage(ctx context.Context, page *types.WikiPage)
existing.ChunkRefs = page.ChunkRefs
existing.PageMetadata = page.PageMetadata
existing.ParentSlug = page.ParentSlug
existing.CategoryPath = page.CategoryPath
existing.WikiPath = page.WikiPath
existing.Depth = page.Depth
existing.FolderID = page.FolderID
existing.SortOrder = page.SortOrder
existing.Status = page.Status
existing.UpdatedAt = time.Now()
// CategoryPath is a derived cache of FolderID — recompute it from the
// folder chain rather than trusting whatever the caller sent.
if err := s.applyFolderToPage(ctx, existing); err != nil {
return nil, err
}
// Outbound links are a pure derivative of content, so they only shift
// when content shifts. Re-parse unconditionally to stay consistent with
// the stored body.
@@ -831,21 +838,12 @@ func (s *wikiPageService) FindSimilarPages(ctx context.Context, kbID string, que
return s.repo.FindSimilarPages(ctx, kbID, query, pageTypes, limit)
}
// ListDistinctCategoryPaths returns unique category_path folders already used
// by entity/concept pages. Used by wiki ingest to ground extraction prompts.
// ListDistinctCategoryPaths returns the existing wiki folder paths. Used by
// wiki ingest's taxonomy planner to ground folder reuse.
func (s *wikiPageService) ListDistinctCategoryPaths(ctx context.Context, kbID string, maxPaths int) ([][]string, error) {
return s.repo.ListDistinctCategoryPaths(ctx, kbID, maxPaths)
}
// ListDistinctCategoryPathsByType returns the direct child folders of
// parentPath across the given page types, paginated, plus the total distinct
// child count. The browser uses this to expand the directory tree level by
// level; passing several types lets one tab (e.g. the merged knowledge tab)
// build a single directory skeleton server-side.
func (s *wikiPageService) ListDistinctCategoryPathsByType(ctx context.Context, kbID string, pageTypes []string, parentPath []string, page, pageSize int) ([]types.WikiCategoryPath, int, error) {
return s.repo.ListDistinctCategoryPathsByType(ctx, kbID, pageTypes, parentPath, page, pageSize)
}
// CountByType is a service-layer pass-through over the repo. Used by
// the index intro path to frame the LLM prompt's "showing N of M" hint.
func (s *wikiPageService) CountByType(ctx context.Context, kbID string) (map[string]int64, error) {
@@ -969,7 +967,6 @@ func normalizeWikiHierarchy(page *types.WikiPage) {
cleanPath := types.StringArray(types.CleanWikiCategoryPath(page.CategoryPath))
page.CategoryPath = cleanPath
page.Depth = len(cleanPath)
page.CategoryL1, page.CategoryL2, page.CategoryL3 = types.WikiCategoryLevels(cleanPath)
display := strings.TrimSpace(page.Title)
if display == "" {
@@ -1050,6 +1047,389 @@ func (s *wikiPageService) UpdateIssueStatus(ctx context.Context, issueID string,
return s.repo.UpdateIssueStatus(ctx, issueID, status)
}
// --- Folder tree (wiki_folders) ---
// wikiFolderSegments splits a materialized folder path ("AI/RAG") into cleaned
// segments. Empty/blank path yields nil (the wiki root).
func wikiFolderSegments(path string) []string {
if strings.TrimSpace(path) == "" {
return nil
}
return types.CleanWikiCategoryPath(strings.Split(path, "/"))
}
// applyFolderToPage refreshes a page's derived category_path cache from its
// authoritative FolderID. Root ("") clears the path. A folder id that does not
// resolve is treated as a hard error so we never silently misplace a page.
func (s *wikiPageService) applyFolderToPage(ctx context.Context, page *types.WikiPage) error {
if page == nil {
return nil
}
if strings.TrimSpace(page.FolderID) == "" {
page.FolderID = ""
page.CategoryPath = nil
return nil
}
folder, err := s.repo.GetFolderByID(ctx, page.KnowledgeBaseID, page.FolderID)
if err != nil {
if errors.Is(err, repository.ErrWikiFolderNotFound) {
return fmt.Errorf("wiki page references unknown folder %q", page.FolderID)
}
return fmt.Errorf("resolve page folder: %w", err)
}
page.CategoryPath = types.StringArray(wikiFolderSegments(folder.Path))
return nil
}
// GetFolder retrieves a single folder by id.
func (s *wikiPageService) GetFolder(ctx context.Context, kbID string, id string) (*types.WikiFolder, error) {
return s.repo.GetFolderByID(ctx, kbID, id)
}
// ListChildFolders returns the direct children of parentID for a tree view
// scoped to pageTypes. PageCount is recursive (the folder's whole subtree) so
// a parent reflects everything filed beneath it, and a folder is only shown
// when its subtree holds a page of pageTypes or it is entirely empty — which
// keeps, say, the summary tab from listing folders that only hold entity pages.
func (s *wikiPageService) ListChildFolders(
ctx context.Context, kbID string, parentID string, pageTypes []string,
) ([]types.WikiFolderNode, error) {
all, err := s.repo.ListAllFolders(ctx, kbID)
if err != nil {
return nil, err
}
scopedDirect, err := s.repo.CountPagesByFolder(ctx, kbID, pageTypes)
if err != nil {
return nil, err
}
allDirect := scopedDirect
if len(pageTypes) > 0 {
allDirect, err = s.repo.CountPagesByFolder(ctx, kbID, nil)
if err != nil {
return nil, err
}
}
recScoped := recursiveFolderCounts(all, scopedDirect)
recAll := recursiveFolderCounts(all, allDirect)
// A folder belongs in this view if it (recursively) contains a page of the
// requested types, or if it is a completely empty container (no pages of
// any type anywhere underneath).
relevant := func(id string) bool { return recScoped[id] > 0 || recAll[id] == 0 }
out := make([]types.WikiFolderNode, 0)
for _, f := range all {
if f.ParentID != parentID || !relevant(f.ID) {
continue
}
hasChildren := false
for _, g := range all {
if g.ParentID == f.ID && relevant(g.ID) {
hasChildren = true
break
}
}
out = append(out, types.WikiFolderNode{
WikiFolder: *f,
PageCount: recScoped[f.ID],
HasChildren: hasChildren,
})
}
return out, nil
}
// recursiveFolderCounts maps each folder id to the sum of `direct` page counts
// over the folder and all of its descendants, using the materialized path so a
// single pass over the (navigation-sized) folder set suffices.
func recursiveFolderCounts(all []*types.WikiFolder, direct map[string]int64) map[string]int64 {
res := make(map[string]int64, len(all))
for _, f := range all {
sum := direct[f.ID]
prefix := f.Path + "/"
for _, g := range all {
if g.ID != f.ID && strings.HasPrefix(g.Path, prefix) {
sum += direct[g.ID]
}
}
res[f.ID] = sum
}
return res
}
// validateFolderName trims and rejects blank names or names carrying directory
// separators (a folder name is a single tree level).
func validateFolderName(name string) (string, error) {
name = strings.TrimSpace(name)
if name == "" {
return "", errors.New("folder name is required")
}
if strings.ContainsAny(name, "/||/") {
return "", fmt.Errorf("folder name %q must not contain a path separator", name)
}
return name, nil
}
// CreateFolder creates a new empty folder under parentID.
func (s *wikiPageService) CreateFolder(
ctx context.Context, kbID string, tenantID uint64, parentID string, name string,
) (*types.WikiFolder, error) {
name, err := validateFolderName(name)
if err != nil {
return nil, err
}
parentPath := ""
depth := 1
if parentID != types.WikiFolderRootID {
parent, err := s.repo.GetFolderByID(ctx, kbID, parentID)
if err != nil {
return nil, err
}
parentPath = parent.Path
depth = parent.Depth + 1
}
if _, err := s.repo.GetChildFolderByName(ctx, kbID, parentID, name); err == nil {
return nil, repository.ErrWikiFolderConflict
} else if !errors.Is(err, repository.ErrWikiFolderNotFound) {
return nil, err
}
path := name
if parentPath != "" {
path = parentPath + "/" + name
}
now := time.Now()
folder := &types.WikiFolder{
ID: uuid.New().String(),
TenantID: tenantID,
KnowledgeBaseID: kbID,
ParentID: parentID,
Name: name,
Path: path,
Depth: depth,
CreatedAt: now,
UpdatedAt: now,
}
if err := s.repo.CreateFolder(ctx, folder); err != nil {
return nil, fmt.Errorf("create wiki folder: %w", err)
}
return folder, nil
}
// FindOrCreateFolderPath resolves a category path to a leaf folder id, creating
// any missing intermediate folders along the way. Concurrency-safe against the
// unique (kb, parent, name) constraint via a re-fetch on create conflict.
func (s *wikiPageService) FindOrCreateFolderPath(
ctx context.Context, kbID string, tenantID uint64, path []string,
) (string, []string, error) {
clean := types.CleanWikiCategoryPath(path)
if len(clean) == 0 {
return types.WikiFolderRootID, nil, nil
}
parentID := types.WikiFolderRootID
parentPath := ""
for depth, name := range clean {
child, err := s.repo.GetChildFolderByName(ctx, kbID, parentID, name)
if err != nil {
if !errors.Is(err, repository.ErrWikiFolderNotFound) {
return "", nil, err
}
fp := name
if parentPath != "" {
fp = parentPath + "/" + name
}
now := time.Now()
child = &types.WikiFolder{
ID: uuid.New().String(),
TenantID: tenantID,
KnowledgeBaseID: kbID,
ParentID: parentID,
Name: name,
Path: fp,
Depth: depth + 1,
CreatedAt: now,
UpdatedAt: now,
}
if cerr := s.repo.CreateFolder(ctx, child); cerr != nil {
// Lost a create race (or unique violation): the sibling must
// now exist — re-fetch it rather than failing the whole plan.
child, err = s.repo.GetChildFolderByName(ctx, kbID, parentID, name)
if err != nil {
return "", nil, fmt.Errorf("create wiki folder %q: %w", fp, cerr)
}
}
}
parentID = child.ID
parentPath = child.Path
}
return parentID, clean, nil
}
// MovePage relocates a page into folderID ("" = root) and refreshes its cached
// category path. Bookkeeping-only write (no version bump).
func (s *wikiPageService) MovePage(
ctx context.Context, kbID string, slug string, folderID string,
) (*types.WikiPage, error) {
page, err := s.repo.GetBySlug(ctx, kbID, slug)
if err != nil {
return nil, err
}
page.FolderID = strings.TrimSpace(folderID)
if err := s.applyFolderToPage(ctx, page); err != nil {
return nil, err
}
page.UpdatedAt = time.Now()
normalizeWikiHierarchy(page)
if err := s.repo.UpdateMeta(ctx, page); err != nil {
return nil, fmt.Errorf("move wiki page: %w", err)
}
return page, nil
}
// RenameOrMoveFolder renames and/or reparents a folder, then recomputes the
// materialized path/depth of the entire subtree and the cached category path of
// every page underneath. Guards against cycles (moving a folder into itself or
// one of its descendants) and sibling name collisions.
func (s *wikiPageService) RenameOrMoveFolder(
ctx context.Context, kbID string, id string, newName string, newParentID string, moveParent bool,
) (*types.WikiFolder, error) {
folder, err := s.repo.GetFolderByID(ctx, kbID, id)
if err != nil {
return nil, err
}
name := folder.Name
if strings.TrimSpace(newName) != "" {
if name, err = validateFolderName(newName); err != nil {
return nil, err
}
}
targetParent := folder.ParentID
if moveParent {
targetParent = newParentID
}
parentPath := ""
depthBase := 0
if targetParent != types.WikiFolderRootID {
if targetParent == folder.ID {
return nil, errors.New("cannot move a folder into itself")
}
parent, err := s.repo.GetFolderByID(ctx, kbID, targetParent)
if err != nil {
return nil, err
}
if parent.Path == folder.Path || strings.HasPrefix(parent.Path, folder.Path+"/") {
return nil, errors.New("cannot move a folder into its own descendant")
}
parentPath = parent.Path
depthBase = parent.Depth
}
if existing, err := s.repo.GetChildFolderByName(ctx, kbID, targetParent, name); err == nil {
if existing.ID != folder.ID {
return nil, repository.ErrWikiFolderConflict
}
} else if !errors.Is(err, repository.ErrWikiFolderNotFound) {
return nil, err
}
oldPath := folder.Path
newPath := name
if parentPath != "" {
newPath = parentPath + "/" + name
}
if newPath == oldPath && targetParent == folder.ParentID {
return folder, nil // no-op
}
all, err := s.repo.ListAllFolders(ctx, kbID)
if err != nil {
return nil, err
}
now := time.Now()
affected := make([]string, 0)
var updated *types.WikiFolder
for _, f := range all {
switch {
case f.ID == folder.ID:
f.ParentID = targetParent
f.Name = name
f.Path = newPath
f.Depth = depthBase + 1
case strings.HasPrefix(f.Path, oldPath+"/"):
f.Path = newPath + f.Path[len(oldPath):]
f.Depth = len(wikiFolderSegments(f.Path))
default:
continue
}
f.UpdatedAt = now
if err := s.repo.UpdateFolder(ctx, f); err != nil {
return nil, err
}
affected = append(affected, f.ID)
if f.ID == folder.ID {
updated = f
}
}
if err := s.recomputePagesForFolders(ctx, kbID, affected); err != nil {
return nil, err
}
if updated == nil {
updated = folder
}
return updated, nil
}
// recomputePagesForFolders refreshes the cached category_path/wiki_path/depth of
// every page filed under any of the given folder ids (used after a folder
// subtree is moved/renamed). Bookkeeping-only writes (no version bump).
func (s *wikiPageService) recomputePagesForFolders(ctx context.Context, kbID string, folderIDs []string) error {
if len(folderIDs) == 0 {
return nil
}
pages, err := s.repo.ListPagesByFolderIDs(ctx, kbID, folderIDs)
if err != nil {
return err
}
for _, page := range pages {
if err := s.applyFolderToPage(ctx, page); err != nil {
return err
}
page.UpdatedAt = time.Now()
normalizeWikiHierarchy(page)
if err := s.repo.UpdateMeta(ctx, page); err != nil {
logger.Warnf(ctx, "wiki: recompute folder path for page %s failed: %v", page.Slug, err)
}
}
return nil
}
// DeleteFolder removes a folder that has no pages and no child folders. The UI
// must relocate contents first; this keeps deletion non-destructive.
func (s *wikiPageService) DeleteFolder(ctx context.Context, kbID string, id string) error {
if _, err := s.repo.GetFolderByID(ctx, kbID, id); err != nil {
return err
}
children, err := s.repo.ListChildFolders(ctx, kbID, id)
if err != nil {
return err
}
if len(children) > 0 {
return errors.New("folder is not empty: it still has sub-folders")
}
pages, err := s.repo.ListPagesByFolderIDs(ctx, kbID, []string{id})
if err != nil {
return err
}
if len(pages) > 0 {
return errors.New("folder is not empty: it still contains pages")
}
return s.repo.DeleteFolder(ctx, kbID, id)
}
// InjectCrossLinks scans affected pages and injects [[wiki-links]] for mentions
// of other wiki page titles in the content. Pure text replacement, no LLM call.
// Shares the linkifyContent helper with the ingest pipeline so both paths honor
+175 -40
View File
@@ -98,6 +98,13 @@ func (h *WikiPageHandler) ListPages(c *gin.Context) {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
categoryPath := parseWikiCategoryPath(c.Query("category_path"))
// folder_id is an exact placement filter. An explicitly-present but empty
// value means "root" (folder_id = ''); an absent param means "no filter".
var folderID *string
if raw, ok := c.GetQuery("folder_id"); ok {
raw = strings.TrimSpace(raw)
folderID = &raw
}
var categoryDepth *int
if raw := c.Query("category_depth"); raw != "" {
if depth, parseErr := strconv.Atoi(raw); parseErr == nil && depth >= 0 {
@@ -110,6 +117,7 @@ func (h *WikiPageHandler) ListPages(c *gin.Context) {
PageType: c.Query("page_type"),
Status: c.Query("status"),
Query: c.Query("query"),
FolderID: folderID,
CategoryPath: types.StringArray(categoryPath),
CategoryDepth: categoryDepth,
Page: page,
@@ -127,63 +135,190 @@ func (h *WikiPageHandler) ListPages(c *gin.Context) {
c.JSON(http.StatusOK, resp)
}
// ListCategories godoc
// @Summary List wiki category paths
// @Description Retrieve direct child directories for a wiki page type and optional parent_path
// ListFolders godoc
// @Summary List wiki folders
// @Description Retrieve the direct child folders of a parent folder (parent_id empty = root level), each with its page count and a has-children flag for the directory tree.
// @Tags Wiki
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param page_type query string true "Wiki page type; comma-separated for multiple (e.g. entity,concept)"
// @Param parent_path query string false "Parent category path, slash-separated"
// @Param page query int false "Page number (1-based)"
// @Param page_size query int false "Page size"
// @Success 200 {object} types.WikiCategoryPathListResponse
// @Param parent_id query string false "Parent folder id (empty = root)"
// @Success 200 {object} types.WikiFolderListResponse
// @Failure 400 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/categories [get]
func (h *WikiPageHandler) ListCategories(c *gin.Context) {
// @Router /knowledgebase/{kb_id}/wiki/folders [get]
func (h *WikiPageHandler) ListFolders(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
pageTypes := types.SplitWikiPageTypes(c.Query("page_type"))
if len(pageTypes) == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "page_type is required"})
return
parentID := strings.TrimSpace(c.Query("parent_id"))
var pageTypes []string
if raw := strings.TrimSpace(c.Query("page_types")); raw != "" {
for _, part := range strings.Split(raw, ",") {
if p := strings.TrimSpace(part); p != "" {
pageTypes = append(pageTypes, p)
}
}
}
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
if page < 1 {
page = 1
}
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "2000"))
if pageSize <= 0 {
pageSize = 2000
}
parentPath := parseWikiCategoryPath(c.Query("parent_path"))
// Grouping and pagination are pushed to SQL; the service returns just the
// requested page of child folders plus the total distinct count.
paths, total, err := h.wikiService.ListDistinctCategoryPathsByType(c.Request.Context(), kbID, pageTypes, parentPath, page, pageSize)
folders, err := h.wikiService.ListChildFolders(c.Request.Context(), kbID, parentID, pageTypes)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if paths == nil {
paths = []types.WikiCategoryPath{}
}
totalPages := 0
if pageSize > 0 {
totalPages = (total + pageSize - 1) / pageSize
if folders == nil {
folders = []types.WikiFolderNode{}
}
c.JSON(http.StatusOK, types.WikiFolderListResponse{ParentID: parentID, Folders: folders})
}
c.JSON(http.StatusOK, types.WikiCategoryPathListResponse{
Paths: paths,
Total: total,
Page: page,
PageSize: pageSize,
TotalPages: totalPages,
})
// CreateFolder godoc
// @Summary Create a wiki folder
// @Description Create a new (initially empty) directory node under parent_id
// @Tags Wiki
// @Accept json
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param folder body types.WikiFolderCreateRequest true "Folder data"
// @Success 201 {object} types.WikiFolder
// @Failure 400 {object} errors.AppError
// @Failure 409 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/folders [post]
func (h *WikiPageHandler) CreateFolder(c *gin.Context) {
kbID, tenantID, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var req types.WikiFolderCreateRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
return
}
folder, err := h.wikiService.CreateFolder(c.Request.Context(), kbID, tenantID, strings.TrimSpace(req.ParentID), req.Name)
if err != nil {
writeWikiFolderError(c, err)
return
}
c.JSON(http.StatusCreated, folder)
}
// UpdateFolder godoc
// @Summary Rename or move a wiki folder
// @Description Rename and/or reparent a folder; the whole subtree's paths and the affected pages' cached paths are recomputed
// @Tags Wiki
// @Accept json
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param folder_id path string true "Folder ID"
// @Param folder body types.WikiFolderUpdateRequest true "Folder update"
// @Success 200 {object} types.WikiFolder
// @Failure 400 {object} errors.AppError
// @Failure 404 {object} errors.AppError
// @Failure 409 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/folders/{folder_id} [put]
func (h *WikiPageHandler) UpdateFolder(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
folderID := secutils.SanitizeForLog(c.Param("folder_id"))
if folderID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Folder ID is required"})
return
}
var req types.WikiFolderUpdateRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
return
}
folder, err := h.wikiService.RenameOrMoveFolder(
c.Request.Context(), kbID, folderID, req.Name, strings.TrimSpace(req.ParentID), req.MoveParent)
if err != nil {
writeWikiFolderError(c, err)
return
}
c.JSON(http.StatusOK, folder)
}
// DeleteFolder godoc
// @Summary Delete an empty wiki folder
// @Description Delete a folder that has no pages and no child folders
// @Tags Wiki
// @Param kb_id path string true "Knowledge base ID"
// @Param folder_id path string true "Folder ID"
// @Success 204
// @Failure 400 {object} errors.AppError
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/folders/{folder_id} [delete]
func (h *WikiPageHandler) DeleteFolder(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
folderID := secutils.SanitizeForLog(c.Param("folder_id"))
if folderID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Folder ID is required"})
return
}
if err := h.wikiService.DeleteFolder(c.Request.Context(), kbID, folderID); err != nil {
writeWikiFolderError(c, err)
return
}
c.Status(http.StatusNoContent)
}
// MovePage godoc
// @Summary Move a wiki page into a folder
// @Description Relocate a page (identified by slug in the body) into a folder (folder_id empty = root); the page's cached category path is recomputed
// @Tags Wiki
// @Accept json
// @Produce json
// @Param kb_id path string true "Knowledge base ID"
// @Param move body types.WikiPageMoveRequest true "Move target"
// @Success 200 {object} types.WikiPage
// @Failure 404 {object} errors.AppError
// @Security Bearer
// @Router /knowledgebase/{kb_id}/wiki/move-page [put]
func (h *WikiPageHandler) MovePage(c *gin.Context) {
kbID, _, err := h.validateWikiKB(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
var req types.WikiPageMoveRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()})
return
}
slug := strings.TrimSpace(req.Slug)
if slug == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"})
return
}
page, err := h.wikiService.MovePage(c.Request.Context(), kbID, slug, strings.TrimSpace(req.FolderID))
if err != nil {
writeWikiFolderError(c, err)
return
}
c.JSON(http.StatusOK, page)
}
// writeWikiFolderError maps folder/page service errors to HTTP status codes.
func writeWikiFolderError(c *gin.Context, err error) {
switch {
case stderrors.Is(err, repository.ErrWikiFolderNotFound), stderrors.Is(err, repository.ErrWikiPageNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
case stderrors.Is(err, repository.ErrWikiFolderConflict):
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
default:
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
}
func parseWikiCategoryPath(raw string) []string {
+7 -1
View File
@@ -1748,12 +1748,18 @@ func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHan
{
// Page CRUD
wiki.GET("/pages", g.Viewer(), wikiHandler.ListPages)
wiki.GET("/categories", g.Viewer(), wikiHandler.ListCategories)
wiki.POST("/pages", g.OwnedWikiKBOrAdmin(), wikiHandler.CreatePage)
wiki.PUT("/move-page", g.OwnedWikiKBOrAdmin(), wikiHandler.MovePage)
wiki.GET("/pages/*slug", g.Viewer(), wikiHandler.GetPage)
wiki.PUT("/pages/*slug", g.OwnedWikiKBOrAdmin(), wikiHandler.UpdatePage)
wiki.DELETE("/pages/*slug", g.OwnedWikiKBOrAdmin(), wikiHandler.DeletePage)
// Folder tree (directory nodes)
wiki.GET("/folders", g.Viewer(), wikiHandler.ListFolders)
wiki.POST("/folders", g.OwnedWikiKBOrAdmin(), wikiHandler.CreateFolder)
wiki.PUT("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), wikiHandler.UpdateFolder)
wiki.DELETE("/folders/:folder_id", g.OwnedWikiKBOrAdmin(), wikiHandler.DeleteFolder)
// Special pages
wiki.GET("/index", g.Viewer(), wikiHandler.GetIndex)
wiki.GET("/log", g.Viewer(), wikiHandler.GetLog)
+68 -15
View File
@@ -156,17 +156,43 @@ type WikiPageService interface {
// merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
// ListDistinctCategoryPaths returns unique non-empty category_path
// values from entity/concept pages. Used by wiki ingest to inject
// established folder taxonomy into extraction prompts.
// ListDistinctCategoryPaths returns the existing wiki folder paths (split
// into segments), capped at maxPaths. Used by wiki ingest's taxonomy
// planner as the pool of folders to reuse.
ListDistinctCategoryPaths(ctx context.Context, kbID string, maxPaths int) ([][]string, error)
// ListDistinctCategoryPathsByType returns the direct child folders of
// parentPath for the given page types (with per-child page counts),
// paginated. The second return value is the total number of distinct
// child folders before pagination. Used by the wiki browser to render the
// directory tree level by level.
ListDistinctCategoryPathsByType(ctx context.Context, kbID string, pageTypes []string, parentPath []string, page, pageSize int) ([]types.WikiCategoryPath, int, error)
// --- Folder tree (wiki_folders) ---
// ListChildFolders returns the direct child folders of parentID ("" =
// root) relevant to the given page types, each enriched with a recursive
// page count (the folder's whole subtree, restricted to pageTypes) and
// whether it has relevant sub-folders. A folder is shown when its subtree
// holds at least one page of pageTypes, or when it is entirely empty (a
// user-created container with no pages of any type). When pageTypes is
// empty every type counts.
ListChildFolders(
ctx context.Context, kbID string, parentID string, pageTypes []string,
) ([]types.WikiFolderNode, error)
// GetFolder retrieves a single folder by id.
GetFolder(ctx context.Context, kbID string, id string) (*types.WikiFolder, error)
// CreateFolder creates a new (initially empty) folder under parentID and
// returns it. Fails if a sibling with the same name already exists.
CreateFolder(ctx context.Context, kbID string, tenantID uint64, parentID string, name string) (*types.WikiFolder, error)
// RenameOrMoveFolder renames and/or reparents a folder, recomputing the
// materialized path/depth of the whole subtree and the cached paths of
// every page underneath. Returns the updated folder.
RenameOrMoveFolder(ctx context.Context, kbID string, id string, newName string, newParentID string, moveParent bool) (*types.WikiFolder, error)
// DeleteFolder removes an empty folder. Fails if it still contains pages
// or child folders (the UI must move or delete contents first).
DeleteFolder(ctx context.Context, kbID string, id string) error
// FindOrCreateFolderPath resolves a category path (e.g. ["AI","RAG"]) to a
// folder id, creating any missing intermediate folders. Returns the leaf
// folder id and the canonical (cleaned) path. An empty/blank path resolves
// to the root ("").
FindOrCreateFolderPath(ctx context.Context, kbID string, tenantID uint64, path []string) (string, []string, error)
// MovePage relocates a page into folderID ("" = root), recomputing its
// cached category path. Returns the updated page.
MovePage(ctx context.Context, kbID string, slug string, folderID string) (*types.WikiPage, error)
// CountByType returns page counts grouped by type for a knowledge
// base. Re-exposed at the service layer so the index intro
@@ -276,14 +302,41 @@ type WikiPageRepository interface {
// surface candidate merge targets server-side.
FindSimilarPages(ctx context.Context, kbID string, query string, pageTypes []string, limit int) ([]*types.WikiPageLite, error)
// ListDistinctCategoryPaths scans entity/concept pages and returns
// unique non-empty category_path values for wiki ingest prompts.
// ListDistinctCategoryPaths returns the materialized paths of existing
// wiki folders (split into segments), capped at maxPaths. Used by the
// wiki ingest taxonomy planner as the pool of folders to reuse.
ListDistinctCategoryPaths(ctx context.Context, kbID string, maxPaths int) ([][]string, error)
// ListDistinctCategoryPathsByType returns the direct child folders of
// parentPath for the given page types (with per-child page counts),
// paginated, plus the total number of distinct child folders.
ListDistinctCategoryPathsByType(ctx context.Context, kbID string, pageTypes []string, parentPath []string, page, pageSize int) ([]types.WikiCategoryPath, int, error)
// --- Folder tree (wiki_folders) ---
// CreateFolder inserts a new directory node.
CreateFolder(ctx context.Context, folder *types.WikiFolder) error
// GetFolderByID retrieves a folder by id within a knowledge base.
GetFolderByID(ctx context.Context, kbID string, id string) (*types.WikiFolder, error)
// GetChildFolderByName returns the live child folder of parentID with the
// given name, or ErrWikiFolderNotFound. Used by find-or-create.
GetChildFolderByName(ctx context.Context, kbID string, parentID string, name string) (*types.WikiFolder, error)
// ListChildFolders returns the direct child folders of parentID, ordered
// by sort_order then name.
ListChildFolders(ctx context.Context, kbID string, parentID string) ([]*types.WikiFolder, error)
// ListAllFolders returns every folder in the knowledge base.
ListAllFolders(ctx context.Context, kbID string) ([]*types.WikiFolder, error)
// UpdateFolder rewrites a folder's mutable fields (name, parent_id, path,
// depth, sort_order, updated_at).
UpdateFolder(ctx context.Context, folder *types.WikiFolder) error
// DeleteFolder soft-deletes a folder by id.
DeleteFolder(ctx context.Context, kbID string, id string) error
// CountPagesInFolder returns the number of live (non-archived) pages
// directly in the folder (folder_id = id).
CountPagesInFolder(ctx context.Context, kbID string, folderID string) (int64, error)
// CountPagesByFolder returns live (non-archived) page counts grouped by
// folder_id. When pageTypes is non-empty the count is restricted to those
// page types; otherwise all types are counted. Pages at the wiki root carry
// the empty-string key.
CountPagesByFolder(ctx context.Context, kbID string, pageTypes []string) (map[string]int64, error)
// ListPagesByFolderIDs returns all pages whose folder_id is in the set.
// Used to recompute cached paths when a folder subtree is moved/renamed.
ListPagesByFolderIDs(ctx context.Context, kbID string, folderIDs []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)
+77 -39
View File
@@ -88,21 +88,6 @@ func SplitWikiPageTypes(raw string) []string {
return out
}
// WikiCategoryLevels flattens a (already cleaned) category path into the three
// fixed level columns used for SQL grouping. Missing levels yield "".
func WikiCategoryLevels(path []string) (l1, l2, l3 string) {
if len(path) > 0 {
l1 = path[0]
}
if len(path) > 1 {
l2 = path[1]
}
if len(path) > 2 {
l3 = path[2]
}
return l1, l2, l3
}
func isWikiTypeCategoryLabel(label string) bool {
normalized := strings.ToLower(strings.TrimSpace(label))
normalized = strings.TrimSuffix(normalized, "s")
@@ -182,11 +167,17 @@ type WikiPage struct {
Aliases StringArray `json:"aliases" gorm:"type:json"`
// ParentSlug optionally points at the wiki page that should act as this
// page's semantic parent in the directory tree. The parent may be empty
// when the page is grouped only by CategoryPath.
// when the page is grouped only by FolderID.
ParentSlug string `json:"parent_slug,omitempty" gorm:"type:varchar(255);index"`
// FolderID is the single source of truth for where this page sits in the
// directory tree — a reference to wiki_folders.id ("" = wiki root). The
// CategoryPath / WikiPath / Depth fields below are denormalized caches
// recomputed from this folder's chain on every write so list/index/search
// queries don't have to join wiki_folders.
FolderID string `json:"folder_id,omitempty" gorm:"column:folder_id;type:varchar(36);index;default:''"`
// CategoryPath is the directory breadcrumb that groups this page in the
// wiki browser, e.g. ["AI", "LLM 应用", "RAG"]. It is intentionally
// label-based so intermediate directory nodes do not need to be real pages.
// wiki browser, e.g. ["AI", "LLM 应用", "RAG"]. Derived cache of the
// folder chain identified by FolderID.
CategoryPath StringArray `json:"category_path,omitempty" gorm:"type:json"`
// WikiPath is a normalized, sortable path derived from page_type,
// category_path, and title. It keeps large directory listings cheap to sort.
@@ -196,13 +187,6 @@ type WikiPage struct {
// SortOrder allows generated or manually edited pages to control sibling
// ordering before falling back to title.
SortOrder int `json:"sort_order,omitempty" gorm:"default:0;index"`
// CategoryL1/L2/L3 mirror CategoryPath[0..2] as flat columns. They exist
// solely so the directory-listing query can GROUP BY / paginate folders in
// plain, cross-dialect SQL (no JSON parsing). They are NOT part of the API
// surface (hence json:"-") and are kept in sync by normalizeWikiHierarchy.
CategoryL1 string `json:"-" gorm:"column:category_l1;type:varchar(255);default:''"`
CategoryL2 string `json:"-" gorm:"column:category_l2;type:varchar(255);default:''"`
CategoryL3 string `json:"-" gorm:"column:category_l3;type:varchar(255);default:''"`
// References to source knowledge IDs that contributed to this page.
// Format matches the legacy "<knowledge_id>|<doc_title>" convention used
// across the ingest pipeline, so retract / display code can split on `|`
@@ -241,6 +225,73 @@ func (WikiPage) TableName() string {
return "wiki_pages"
}
// WikiFolderRootID is the sentinel parent/folder id meaning "the wiki root"
// (a page or folder directly under the top level, with no parent folder).
const WikiFolderRootID = ""
// WikiFolder is a first-class directory node in the wiki browser. Folders
// exist independently of pages — an empty folder persists so users can lay
// out a skeleton and file pages into it later. The tree is an adjacency list
// (ParentID, "" = root); Path is the materialized "/"-joined name chain kept
// purely for cheap display/sort. A wiki page's placement is WikiPage.FolderID.
type WikiFolder struct {
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
TenantID uint64 `json:"tenant_id" gorm:"index"`
KnowledgeBaseID string `json:"knowledge_base_id" gorm:"type:varchar(36);index"`
ParentID string `json:"parent_id" gorm:"column:parent_id;type:varchar(36);index;default:''"`
Name string `json:"name" gorm:"type:varchar(255)"`
Path string `json:"path" gorm:"type:varchar(1024)"`
Depth int `json:"depth" gorm:"default:0"`
SortOrder int `json:"sort_order" gorm:"default:0"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// TableName specifies the database table name
func (WikiFolder) TableName() string {
return "wiki_folders"
}
// WikiFolderNode is one directory node returned to the browser, enriched with
// the live page count directly under it and whether it has child folders so
// the UI can render an expand affordance without a second round-trip.
type WikiFolderNode struct {
WikiFolder
PageCount int64 `json:"page_count"`
HasChildren bool `json:"has_children"`
}
// WikiFolderListResponse is the payload for listing the direct children of a
// folder (parent_id="" = root level).
type WikiFolderListResponse struct {
ParentID string `json:"parent_id"`
Folders []WikiFolderNode `json:"folders"`
}
// WikiFolderCreateRequest creates a new (initially empty) folder under ParentID.
type WikiFolderCreateRequest struct {
ParentID string `json:"parent_id"`
Name string `json:"name"`
}
// WikiFolderUpdateRequest renames and/or reparents a folder. ParentID is
// applied only when MoveParent is true so a pure rename doesn't have to
// re-send the (possibly root "") parent and risk an accidental move.
type WikiFolderUpdateRequest struct {
Name string `json:"name,omitempty"`
ParentID string `json:"parent_id,omitempty"`
MoveParent bool `json:"move_parent,omitempty"`
}
// WikiPageMoveRequest relocates the page identified by Slug into FolderID
// ("" = root). Slug is carried in the body (not the path) because wiki slugs
// are hierarchical ("entity/acme") and would collide with gin's catch-all.
type WikiPageMoveRequest struct {
Slug string `json:"slug" binding:"required"`
FolderID string `json:"folder_id"`
}
// WikiExtractionGranularity controls how aggressive Pass 0 (candidate slug
// extraction) is. Higher granularity = more slugs, lower = tighter focus on
// the document's main subjects.
@@ -368,6 +419,7 @@ type WikiPageListRequest struct {
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
FolderID *string `json:"folder_id,omitempty"` // exact folder placement ("" = root)
CategoryPath StringArray `json:"category_path,omitempty"` // exact directory path
CategoryDepth *int `json:"category_depth,omitempty"` // exact directory depth, including 0 for root
Page int `json:"page,omitempty"` // pagination page (1-based)
@@ -385,20 +437,6 @@ type WikiPageListResponse struct {
TotalPages int `json:"total_pages"`
}
// WikiCategoryPathListResponse returns the directory skeleton for wiki pages.
type WikiCategoryPathListResponse struct {
Paths []WikiCategoryPath `json:"paths"`
Total int `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
TotalPages int `json:"total_pages"`
}
// WikiCategoryPath is one directory node in the wiki sidebar skeleton.
type WikiCategoryPath struct {
Path []string `json:"path"`
Count int64 `json:"count"`
}
// WikiGraphMode enumerates the graph query modes exposed to the API.
const (