perf(wiki): move ingest log to event table and index to on-demand API
Fixes O(n²) write amplification during wiki ingest on large KBs. Previously
every ingest/retract op re-wrote the single `slug='log'` row end-to-end and
every batch re-wrote the entire `slug='index'` directory markdown. On a 40k-
doc KB the log row grew to tens of MB and the index row to several MB, so
each batch triggered giant TOAST updates that dominated ingest wall time.
Log: new `wiki_log_entries` event table (`id DESC` indexed per KB) replaces
the single TEXT row. Batch ingest now collects entries and flushes them
once per batch via `AppendBatch`. Each entry stores `pages_affected` as
JSONB `[{slug,title}]` so the UI can render real titles; custom Scan falls
back to legacy `[]string` so older rows still deserialize.
Index: `wiki_pages[slug=index].content` keeps only the LLM-generated intro
(a few KB). The directory is now served by a structured paginated API
(`GetIndexView`) that reads `slug/title/summary` per type with cursor
pagination, so the agent and the frontend only pull the slice they need.
`RebuildIndexPage` degrades to a no-op; agent `wiki_read_page('index')`
synthesizes a small top-K overview and points callers at `wiki_search`.
Ingest resilience: LLM calls wrap with 3-attempt exponential backoff on
transient errors (5xx/408/429, transport resets/timeouts). Summary/extract
failures now bubble up so the batch's failed-op requeue path runs instead
of silently dropping the doc.
Frontend: sidebar Index/Log entries switch to dedicated views. Index view
streams intro → Summary → Entity → Concept → Synthesis → Comparison via
IntersectionObserver (with a nextTick re-check so small KBs still load
every section). Log view uses cursor pagination; pages_affected renders
titles with slug tooltip.
- new migration: migrations/versioned/000040_wiki_log_entries.{up,down}.sql
- tests: log repo pagination + legacy Scan, ListByTypeLight windowing,
renderIndexOverviewForAgent output, isTransientLLMError classifier
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -97,6 +97,17 @@ const (
|
||||
// tick (GC pause, Redis blip) doesn't let the lock slip out from under a
|
||||
// live handler.
|
||||
wikiActiveLockRenew = 20 * time.Second
|
||||
|
||||
// wikiLLMMaxAttempts is the total attempt count (initial + retries) for
|
||||
// every LLM call routed through generateWithTemplate. 3 was chosen to
|
||||
// absorb transient 504/timeouts from upstream gateways without
|
||||
// materially prolonging task runtime when the remote is genuinely down.
|
||||
wikiLLMMaxAttempts = 3
|
||||
|
||||
// wikiLLMBackoffBase is the base delay for the exponential backoff
|
||||
// between retry attempts. The nth retry waits base << (n-1) — so with
|
||||
// a 2s base we wait 2s, 4s, 8s between attempts.
|
||||
wikiLLMBackoffBase = 2 * time.Second
|
||||
)
|
||||
|
||||
// WikiDeletedTombstoneKey returns the Redis key used to mark a knowledge as
|
||||
@@ -156,6 +167,7 @@ type wikiIngestService struct {
|
||||
chunkRepo interfaces.ChunkRepository
|
||||
modelService interfaces.ModelService
|
||||
task interfaces.TaskEnqueuer
|
||||
logEntrySvc interfaces.WikiLogEntryService
|
||||
redisClient *redis.Client // nil in Lite mode (no Redis)
|
||||
// liteLocks provides per-KB mutual exclusion in Lite mode (no Redis).
|
||||
// Keys are kbID strings; values are unused (presence = locked).
|
||||
@@ -170,6 +182,7 @@ func NewWikiIngestService(
|
||||
chunkRepo interfaces.ChunkRepository,
|
||||
modelService interfaces.ModelService,
|
||||
task interfaces.TaskEnqueuer,
|
||||
logEntrySvc interfaces.WikiLogEntryService,
|
||||
redisClient *redis.Client,
|
||||
) interfaces.TaskHandler {
|
||||
svc := &wikiIngestService{
|
||||
@@ -179,6 +192,7 @@ func NewWikiIngestService(
|
||||
chunkRepo: chunkRepo,
|
||||
modelService: modelService,
|
||||
task: task,
|
||||
logEntrySvc: logEntrySvc,
|
||||
redisClient: redisClient,
|
||||
}
|
||||
return svc
|
||||
@@ -427,8 +441,11 @@ func (s *wikiIngestService) requeueFailedOps(ctx context.Context, payload WikiIn
|
||||
type docIngestResult struct {
|
||||
KnowledgeID string
|
||||
DocTitle string
|
||||
Summary string // one-line summary of the document (from summary page)
|
||||
Pages []string // affected page slugs
|
||||
Summary string // one-line summary of the document (from summary page)
|
||||
// Pages records the wiki pages this document touched, carrying both
|
||||
// the slug (for navigation / retract lookups) and the human-readable
|
||||
// title captured at ingest time (for the log feed's display layer).
|
||||
Pages []types.WikiLogPageRef
|
||||
}
|
||||
|
||||
// WikiBatchContext holds shared data across Map and Reduce phases
|
||||
@@ -695,62 +712,72 @@ type combinedExtraction struct {
|
||||
Concepts []extractedItem `json:"concepts"`
|
||||
}
|
||||
|
||||
// rebuildIndexPage regenerates the index page.
|
||||
// rebuildIndexPage refreshes the LLM-generated intro that sits on the
|
||||
// index wiki_pages row.
|
||||
//
|
||||
// Strategy: Index = LLM-generated intro (stored in Summary field) + code-generated directory.
|
||||
// - Intro: stored in indexPage.Summary. First time: generated from document summaries.
|
||||
// Subsequent: incrementally updated with changeDescription.
|
||||
// - Directory: pure code, rebuilt every time. O(N) string concat, no LLM.
|
||||
// History: the index page used to store "intro + full directory listing" as
|
||||
// a single multi-MB markdown blob in content. Every ingest batch rewrote
|
||||
// the whole column, which on KBs with tens of thousands of pages caused
|
||||
// O(N) TOAST writes per batch. The directory was lifted out into the
|
||||
// structured GET /wiki/index endpoint (see wikiPageService.GetIndexView),
|
||||
// and this method now only maintains the intro.
|
||||
//
|
||||
// Intro lifecycle:
|
||||
// - First time (empty or legacy placeholder): generate from all document
|
||||
// summaries via WikiIndexIntroPrompt.
|
||||
// - Subsequent calls with a change description: incremental update via
|
||||
// WikiIndexIntroUpdatePrompt so the intro reflects what just landed.
|
||||
// - No change description: keep the existing intro untouched.
|
||||
//
|
||||
// The new intro is written to both Content and Summary so readers that
|
||||
// still fall back to Summary (older clients, legacy migrations) stay in
|
||||
// sync with the column the view actually renders.
|
||||
func (s *wikiIngestService) rebuildIndexPage(ctx context.Context, chatModel chat.Chat, payload WikiIngestPayload, changeDesc, lang string) error {
|
||||
indexPage, _ := s.wikiService.GetIndex(ctx, payload.KnowledgeBaseID)
|
||||
if indexPage == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// List all live pages
|
||||
allPages, err := s.wikiService.ListAllPages(ctx, payload.KnowledgeBaseID)
|
||||
// Gather just the Summary-type pages the LLM needs for intro framing.
|
||||
// We do NOT load or iterate every wiki page here — the directory is
|
||||
// now assembled on demand by GetIndexView, which is the only reader
|
||||
// that needs the full enumeration.
|
||||
summaries, err := s.wikiService.ListByType(ctx, payload.KnowledgeBaseID, types.WikiPageTypeSummary)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
typeOrder := []string{
|
||||
types.WikiPageTypeSummary, types.WikiPageTypeEntity, types.WikiPageTypeConcept,
|
||||
types.WikiPageTypeSynthesis, types.WikiPageTypeComparison,
|
||||
}
|
||||
typeLabels := map[string]string{
|
||||
types.WikiPageTypeSummary: "Summary", types.WikiPageTypeEntity: "Entity",
|
||||
types.WikiPageTypeConcept: "Concept", types.WikiPageTypeSynthesis: "Synthesis",
|
||||
types.WikiPageTypeComparison: "Comparison",
|
||||
}
|
||||
|
||||
grouped := make(map[string][]*types.WikiPage)
|
||||
totalPages := 0
|
||||
for _, p := range allPages {
|
||||
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {
|
||||
continue
|
||||
}
|
||||
if p.Status == types.WikiPageStatusArchived {
|
||||
continue
|
||||
}
|
||||
grouped[p.PageType] = append(grouped[p.PageType], p)
|
||||
totalPages++
|
||||
}
|
||||
|
||||
// Build document summaries listing (only summary-type pages — they represent documents)
|
||||
var docSummaries strings.Builder
|
||||
for _, p := range grouped[types.WikiPageTypeSummary] {
|
||||
for _, p := range summaries {
|
||||
if p == nil || p.Status == types.WikiPageStatusArchived {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&docSummaries, "<document>\n<title>%s</title>\n<summary>%s</summary>\n</document>\n\n", p.Title, p.Summary)
|
||||
}
|
||||
if docSummaries.Len() == 0 {
|
||||
docSummaries.WriteString("(no documents yet)")
|
||||
}
|
||||
|
||||
// Generate or update intro
|
||||
existingIntro := indexPage.Summary
|
||||
var intro string
|
||||
// The intro lives on both Content and Summary. Prefer Content since
|
||||
// that's what the new index view returns; fall back to Summary for
|
||||
// rows written before this refactor so the incremental-update prompt
|
||||
// has something to work with.
|
||||
existingIntro := strings.TrimSpace(indexPage.Content)
|
||||
if existingIntro == "" {
|
||||
existingIntro = strings.TrimSpace(indexPage.Summary)
|
||||
}
|
||||
// Detect the legacy "intro + directory" payload. Such rows embed the
|
||||
// fence-separated "## Summary" sections right after the intro, so we
|
||||
// clip everything from the first directory heading onward to keep the
|
||||
// intro length bounded when we feed it back into the update prompt.
|
||||
if idx := strings.Index(existingIntro, "\n## "); idx >= 0 {
|
||||
existingIntro = strings.TrimSpace(existingIntro[:idx])
|
||||
}
|
||||
|
||||
if existingIntro == "" || existingIntro == "Wiki index - table of contents" {
|
||||
// First time — generate intro from scratch
|
||||
var intro string
|
||||
switch {
|
||||
case existingIntro == "" || existingIntro == "Wiki index - table of contents":
|
||||
// First time — generate intro from scratch.
|
||||
generatedIntro, genErr := s.generateWithTemplate(ctx, chatModel, agent.WikiIndexIntroPrompt, map[string]string{
|
||||
"DocumentSummaries": docSummaries.String(),
|
||||
"Language": lang,
|
||||
@@ -760,8 +787,8 @@ func (s *wikiIngestService) rebuildIndexPage(ctx context.Context, chatModel chat
|
||||
} else {
|
||||
intro = strings.TrimSpace(generatedIntro)
|
||||
}
|
||||
} else if changeDesc != "" {
|
||||
// Incremental update — tell LLM what changed
|
||||
case changeDesc != "":
|
||||
// Incremental update — tell the LLM what changed.
|
||||
updatedIntro, genErr := s.generateWithTemplate(ctx, chatModel, agent.WikiIndexIntroUpdatePrompt, map[string]string{
|
||||
"ExistingIntro": existingIntro,
|
||||
"ChangeDescription": changeDesc,
|
||||
@@ -773,45 +800,23 @@ func (s *wikiIngestService) rebuildIndexPage(ctx context.Context, chatModel chat
|
||||
} else {
|
||||
intro = strings.TrimSpace(updatedIntro)
|
||||
}
|
||||
} else {
|
||||
intro = existingIntro // no change description, keep as-is
|
||||
default:
|
||||
// No change description and an existing intro: leave it as-is so
|
||||
// we don't bump the version for a no-op.
|
||||
intro = existingIntro
|
||||
}
|
||||
|
||||
// Build directory (pure code, no LLM)
|
||||
var dir strings.Builder
|
||||
for _, pt := range typeOrder {
|
||||
pages := grouped[pt]
|
||||
if len(pages) == 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", typeLabels[pt], len(pages))
|
||||
for _, p := range pages {
|
||||
summary := p.Summary
|
||||
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, summary)
|
||||
}
|
||||
}
|
||||
for pt, pages := range grouped {
|
||||
inOrder := false
|
||||
for _, o := range typeOrder {
|
||||
if o == pt {
|
||||
inOrder = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if inOrder || len(pages) == 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", pt, len(pages))
|
||||
for _, p := range pages {
|
||||
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, p.Summary)
|
||||
}
|
||||
}
|
||||
if totalPages == 0 {
|
||||
dir.WriteString("\n*No wiki pages yet. Upload documents to get started.*\n")
|
||||
// Defensive: some LLM outputs occasionally bleed into a directory-
|
||||
// like section even when the intro prompt doesn't ask for one. If
|
||||
// the freshly-generated intro starts to look like a legacy payload,
|
||||
// clip it at the first "\n## " just like we did on the read path
|
||||
// above. This keeps indexPage.Content a bounded intro-only blob.
|
||||
if idx := strings.Index(intro, "\n## "); idx >= 0 {
|
||||
intro = strings.TrimSpace(intro[:idx])
|
||||
}
|
||||
|
||||
indexPage.Content = intro + "\n" + dir.String()
|
||||
indexPage.Summary = intro // persist intro for next incremental update
|
||||
indexPage.Content = intro
|
||||
indexPage.Summary = intro
|
||||
_, err = s.wikiService.UpdatePage(ctx, indexPage)
|
||||
return err
|
||||
}
|
||||
@@ -834,34 +839,31 @@ func splitSummaryLine(raw string) (summary string, content string) {
|
||||
return "", raw
|
||||
}
|
||||
|
||||
// appendLogEntry appends a structured, grep-parseable entry to the log page.
|
||||
// Format: ## [2026-04-07 19:50:02] action | title
|
||||
// Followed by key-value metadata lines. No sub-headings — keeps `grep "^## \[" log.md` clean.
|
||||
func (s *wikiIngestService) appendLogEntry(ctx context.Context, kbID string, action, knowledgeID, docTitle, summary string, pagesAffected []string) {
|
||||
logPage, _ := s.wikiService.GetLog(ctx, kbID)
|
||||
if logPage == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
fmt.Fprintf(&sb, "\n## [%s] %s | %s\n",
|
||||
time.Now().Format("2006-01-02 15:04:05"),
|
||||
action,
|
||||
docTitle,
|
||||
)
|
||||
if knowledgeID != "" {
|
||||
fmt.Fprintf(&sb, "- **KnowledgeID**: %s\n", knowledgeID)
|
||||
}
|
||||
if summary != "" {
|
||||
fmt.Fprintf(&sb, "- **Summary**: %s\n", summary)
|
||||
}
|
||||
// buildLogEntry builds a WikiLogEntry struct for the current batch. It is
|
||||
// pure (no DB access) so callers can accumulate entries cheaply under their
|
||||
// lock and flush them in a single AppendBatch call at the end of the batch.
|
||||
//
|
||||
// Historically this was a per-event `GetLog + UpdatePage` round trip, which
|
||||
// rewrote the entire log page's TEXT column on every ingest/retract op —
|
||||
// O(n^2) write amplification as the log grew. The batch writer now uses
|
||||
// wikiLogEntryService.AppendBatch instead; see ProcessWikiIngest.
|
||||
func (s *wikiIngestService) buildLogEntry(tenantID uint64, kbID, action, knowledgeID, docTitle, summary string, pagesAffected []types.WikiLogPageRef) *types.WikiLogEntry {
|
||||
// Copy pagesAffected so the entry does not alias caller-owned slices.
|
||||
// The batch accumulates SlugUpdate results that may be reused downstream.
|
||||
var pages types.WikiLogPageRefs
|
||||
if len(pagesAffected) > 0 {
|
||||
fmt.Fprintf(&sb, "- **Pages affected**: %d (%s)\n", len(pagesAffected), strings.Join(pagesAffected, ", "))
|
||||
pages = make(types.WikiLogPageRefs, len(pagesAffected))
|
||||
copy(pages, pagesAffected)
|
||||
}
|
||||
|
||||
logPage.Content = logPage.Content + sb.String()
|
||||
if _, err := s.wikiService.UpdatePage(ctx, logPage); err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: failed to update log page: %v", err)
|
||||
return &types.WikiLogEntry{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
Action: action,
|
||||
KnowledgeID: knowledgeID,
|
||||
DocTitle: docTitle,
|
||||
Summary: summary,
|
||||
PagesAffected: pages,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1017,7 +1019,23 @@ func (s *wikiIngestService) deduplicateExtractedBatch(
|
||||
return entities, concepts
|
||||
}
|
||||
|
||||
// generateWithTemplate executes a prompt template and calls the LLM
|
||||
// generateWithTemplate executes a prompt template and calls the LLM with
|
||||
// bounded exponential-backoff retries for transient infrastructure errors.
|
||||
//
|
||||
// Retry policy:
|
||||
// - Up to wikiLLMMaxAttempts total attempts (initial + retries).
|
||||
// - Only retry errors classified as transient by isTransientLLMError:
|
||||
// HTTP 408/429/5xx, context deadline exceeded (when the parent ctx is
|
||||
// still alive), or generic "timeout"/"connection reset" wording.
|
||||
// 4xx (except 408/429) is a caller-side fault and fails fast.
|
||||
// - Backoff is exponential base 2s: 2s, 4s, 8s — roughly wikiLLMBackoffBase
|
||||
// * 2^(attempt-1). Honors ctx cancellation so the task can abort.
|
||||
//
|
||||
// This exists because wiki ingest makes several independent LLM calls per
|
||||
// document (extraction, summary, dedup, citations, intro) and a single
|
||||
// transient 504 from the upstream gateway used to drop the document's
|
||||
// summary page permanently. Retries plus failedOps requeuing (see
|
||||
// mapOneDocument) turn those events into at-most-a-few-minute hiccups.
|
||||
func (s *wikiIngestService) generateWithTemplate(ctx context.Context, chatModel chat.Chat, promptTpl string, data map[string]string) (string, error) {
|
||||
tmpl, err := template.New("wiki").Parse(promptTpl)
|
||||
if err != nil {
|
||||
@@ -1031,17 +1049,98 @@ func (s *wikiIngestService) generateWithTemplate(ctx context.Context, chatModel
|
||||
|
||||
prompt := buf.String()
|
||||
thinking := false
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
{Role: "user", Content: prompt},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("LLM call failed: %w", err)
|
||||
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= wikiLLMMaxAttempts; attempt++ {
|
||||
response, err := chatModel.Chat(ctx, []chat.Message{
|
||||
{Role: "user", Content: prompt},
|
||||
}, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
Thinking: &thinking,
|
||||
})
|
||||
if err == nil {
|
||||
return response.Content, nil
|
||||
}
|
||||
lastErr = err
|
||||
|
||||
// Abort immediately on non-retryable errors (4xx except 408/429,
|
||||
// parse/marshal failures, tool-side bugs, etc.). Retrying a
|
||||
// hard "invalid arguments" error just wastes the model's budget.
|
||||
if !isTransientLLMError(ctx, err) {
|
||||
return "", fmt.Errorf("LLM call failed: %w", err)
|
||||
}
|
||||
if attempt == wikiLLMMaxAttempts {
|
||||
break
|
||||
}
|
||||
|
||||
backoff := wikiLLMBackoffBase << (attempt - 1)
|
||||
logger.Warnf(ctx, "wiki ingest: LLM call failed (attempt %d/%d), retrying in %s: %v",
|
||||
attempt, wikiLLMMaxAttempts, backoff, err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", fmt.Errorf("LLM call aborted during backoff: %w", ctx.Err())
|
||||
case <-time.After(backoff):
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("LLM call failed after %d attempts: %w", wikiLLMMaxAttempts, lastErr)
|
||||
}
|
||||
|
||||
// isTransientLLMError reports whether an error from the chat provider
|
||||
// looks like an infrastructure hiccup worth retrying. Classification is
|
||||
// intentionally conservative: the truthful "could not tell, assume
|
||||
// permanent" choice keeps retries cheap and avoids masking real bugs.
|
||||
//
|
||||
// We treat the following as transient:
|
||||
// - HTTP 408 (client request timeout — upstream usually didn't process),
|
||||
// 429 (rate-limited — retry after backoff may succeed), 5xx (any
|
||||
// server-side fault, including the 504 "Remote error, timeout with
|
||||
// 60" we see from the gateway in front of several LLM providers).
|
||||
// - Wrapped context.DeadlineExceeded when the parent ctx is still alive
|
||||
// (nested per-call timeouts).
|
||||
// - Substring matches on the error text for common transport failures
|
||||
// ("timeout", "connection reset", "EOF") that providers surface
|
||||
// without a structured status code.
|
||||
func isTransientLLMError(ctx context.Context, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
// Never retry after the parent ctx itself expired — the task is
|
||||
// being cancelled and the next attempt would just fail again.
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
return response.Content, nil
|
||||
msg := err.Error()
|
||||
// Providers that bubble HTTP status up formatted as
|
||||
// "API request failed with status NNN: ..." — match that first.
|
||||
for _, s := range []string{
|
||||
"status 408", "status 429",
|
||||
"status 500", "status 501", "status 502", "status 503", "status 504",
|
||||
"status 520", "status 521", "status 522", "status 523", "status 524",
|
||||
} {
|
||||
if strings.Contains(msg, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
lower := strings.ToLower(msg)
|
||||
for _, s := range []string{
|
||||
"timeout",
|
||||
"timed out",
|
||||
"connection reset",
|
||||
"connection refused",
|
||||
"broken pipe",
|
||||
"no such host", // DNS hiccup
|
||||
"i/o timeout",
|
||||
"unexpected eof",
|
||||
"tls handshake",
|
||||
"context deadline exceeded", // nested per-call deadline
|
||||
} {
|
||||
if strings.Contains(lower, s) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
@@ -392,14 +392,42 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
||||
|
||||
totalPagesAffected = len(allPagesAffected)
|
||||
|
||||
// Append log entries — one per operation for chronological traceability
|
||||
// Collect log entries for this batch and flush them in a single INSERT.
|
||||
// Historically each op triggered its own `GetLog + UpdatePage` round
|
||||
// trip, which rewrote the entire log page TEXT column and caused O(n^2)
|
||||
// write amplification as the log grew. AppendBatch writes one row per
|
||||
// event into wiki_log_entries instead.
|
||||
//
|
||||
// slugsToRefs resolves each retract slug against the batch-start
|
||||
// snapshot (batchCtx.SlugTitleMap) so the log feed carries titles for
|
||||
// pages that existed when the batch began. Pages created or renamed
|
||||
// during this batch fall through the map lookup and log as slug-only
|
||||
// refs, which the frontend renders as the slug itself — a sensible
|
||||
// fallback given retracts only touch pre-existing pages.
|
||||
slugsToRefs := func(slugs []string) []types.WikiLogPageRef {
|
||||
if len(slugs) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make([]types.WikiLogPageRef, 0, len(slugs))
|
||||
for _, slug := range slugs {
|
||||
title := batchCtx.SlugTitleMap[slug]
|
||||
out = append(out, types.WikiLogPageRef{Slug: slug, Title: title})
|
||||
}
|
||||
return out
|
||||
}
|
||||
logEntries := make([]*types.WikiLogEntry, 0, len(pendingOps)+len(docResults))
|
||||
for _, op := range pendingOps {
|
||||
if op.Op == WikiOpRetract {
|
||||
s.appendLogEntry(ctx, payload.KnowledgeBaseID, "retract", op.KnowledgeID, op.DocTitle, op.DocSummary, op.PageSlugs)
|
||||
logEntries = append(logEntries, s.buildLogEntry(payload.TenantID, payload.KnowledgeBaseID, "retract", op.KnowledgeID, op.DocTitle, op.DocSummary, slugsToRefs(op.PageSlugs)))
|
||||
}
|
||||
}
|
||||
for _, r := range docResults {
|
||||
s.appendLogEntry(ctx, payload.KnowledgeBaseID, "ingest", r.KnowledgeID, r.DocTitle, r.Summary, r.Pages)
|
||||
logEntries = append(logEntries, s.buildLogEntry(payload.TenantID, payload.KnowledgeBaseID, "ingest", r.KnowledgeID, r.DocTitle, r.Summary, r.Pages))
|
||||
}
|
||||
if len(logEntries) > 0 && s.logEntrySvc != nil {
|
||||
if err := s.logEntrySvc.AppendBatch(ctx, logEntries); err != nil {
|
||||
logger.Warnf(ctx, "wiki ingest: failed to append %d log entries: %v", len(logEntries), err)
|
||||
}
|
||||
}
|
||||
|
||||
// Build change description for the Index Intro LLM prompt
|
||||
@@ -625,9 +653,18 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
}
|
||||
}
|
||||
|
||||
extractedPages := make([]string, 0, len(slugItems)+1)
|
||||
for slug := range slugItems {
|
||||
extractedPages = append(extractedPages, slug)
|
||||
// extractedPages records every wiki page this document materialized
|
||||
// (entities, concepts, plus the summary page appended below). The
|
||||
// slug is used for link/retract bookkeeping; the title is captured
|
||||
// for the log feed so the user sees "提供本学位在线验证报告查询…"
|
||||
// rather than "entity/xue-xin-wang".
|
||||
extractedPages := make([]types.WikiLogPageRef, 0, len(slugItems)+1)
|
||||
for slug, item := range slugItems {
|
||||
title := item.Name
|
||||
if title == "" {
|
||||
title = slug
|
||||
}
|
||||
extractedPages = append(extractedPages, types.WikiLogPageRef{Slug: slug, Title: title})
|
||||
}
|
||||
|
||||
// Count total distinct chunks cited across all slugs for logging.
|
||||
@@ -647,32 +684,44 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
var docSummary string
|
||||
|
||||
if summaryErr != nil {
|
||||
logger.Errorf(ctx, "wiki ingest: generate summary failed for %s: %v", knowledgeID, summaryErr)
|
||||
} else {
|
||||
sumLine, sumBody := splitSummaryLine(summaryContent)
|
||||
if sumBody == "" {
|
||||
sumBody = summaryContent
|
||||
}
|
||||
if sumLine == "" {
|
||||
sumLine = docTitle
|
||||
}
|
||||
docSummaryLine = sumLine
|
||||
docSummary = sumBody
|
||||
if strings.TrimSpace(docSummary) == "" {
|
||||
docSummary = sumLine
|
||||
}
|
||||
updates = append(updates, SlugUpdate{
|
||||
Slug: summarySlug,
|
||||
Type: types.WikiPageTypeSummary,
|
||||
DocTitle: docTitle,
|
||||
KnowledgeID: knowledgeID,
|
||||
SourceRef: sourceRef,
|
||||
Language: lang,
|
||||
SummaryLine: sumLine,
|
||||
SummaryBody: sumBody,
|
||||
})
|
||||
extractedPages = append(extractedPages, summarySlug)
|
||||
// Summary is the headline artifact of an ingested document — a
|
||||
// document with no summary page is half-ingested and leaves the
|
||||
// entity/concept updates hanging without a root to link back to
|
||||
// from the index. Historically we just logged and moved on,
|
||||
// which meant a single transient 504 permanently dropped the
|
||||
// summary page for that document.
|
||||
//
|
||||
// Returning an error here sends the op to failedOps (see the
|
||||
// map-phase loop in ProcessWikiIngest), which requeueFailedOps
|
||||
// appends back onto the pending list so the next batch retries.
|
||||
// The internal retries in generateWithTemplate already exhaust
|
||||
// the LLM's own transient-error budget before we give up here.
|
||||
logger.Errorf(ctx, "wiki ingest: generate summary failed for %s, will requeue: %v", knowledgeID, summaryErr)
|
||||
return nil, nil, fmt.Errorf("generate summary: %w", summaryErr)
|
||||
}
|
||||
sumLine, sumBody := splitSummaryLine(summaryContent)
|
||||
if sumBody == "" {
|
||||
sumBody = summaryContent
|
||||
}
|
||||
if sumLine == "" {
|
||||
sumLine = docTitle
|
||||
}
|
||||
docSummaryLine = sumLine
|
||||
docSummary = sumBody
|
||||
if strings.TrimSpace(docSummary) == "" {
|
||||
docSummary = sumLine
|
||||
}
|
||||
updates = append(updates, SlugUpdate{
|
||||
Slug: summarySlug,
|
||||
Type: types.WikiPageTypeSummary,
|
||||
DocTitle: docTitle,
|
||||
KnowledgeID: knowledgeID,
|
||||
SourceRef: sourceRef,
|
||||
Language: lang,
|
||||
SummaryLine: sumLine,
|
||||
SummaryBody: sumBody,
|
||||
})
|
||||
extractedPages = append(extractedPages, types.WikiLogPageRef{Slug: summarySlug, Title: docTitle})
|
||||
|
||||
// Entities
|
||||
for _, item := range extractedEntities {
|
||||
@@ -740,7 +789,7 @@ func (s *wikiIngestService) mapOneDocument(
|
||||
|
||||
newSlugSet := make(map[string]bool, len(extractedPages))
|
||||
for _, ns := range extractedPages {
|
||||
newSlugSet[ns] = true
|
||||
newSlugSet[ns.Slug] = true
|
||||
}
|
||||
|
||||
var reparseOverlap, staleCount int
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestIsTransientLLMError_HTTPStatuses covers the status codes we know
|
||||
// the generic REST chat provider bubbles up as "API request failed with
|
||||
// status NNN: ...". The status-code arm of the classifier is the one
|
||||
// that actually fires for the 504 gateway timeouts the upstream LLM
|
||||
// vendors throw most often.
|
||||
func TestIsTransientLLMError_HTTPStatuses(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cases := []struct {
|
||||
msg string
|
||||
want bool
|
||||
}{
|
||||
{"API request failed with status 504: Remote error, timeout with 60", true},
|
||||
{"API request failed with status 503: service unavailable", true},
|
||||
{"API request failed with status 502: bad gateway", true},
|
||||
{"API request failed with status 500: internal server error", true},
|
||||
{"API request failed with status 429: rate limited", true},
|
||||
{"API request failed with status 408: request timeout", true},
|
||||
{"API request failed with status 520: Web server returned unknown", true},
|
||||
{"API request failed with status 524: timeout (Cloudflare)", true},
|
||||
// 4xx permanent: a retry will just fail the same way.
|
||||
{"API request failed with status 400: bad request", false},
|
||||
{"API request failed with status 401: unauthorized", false},
|
||||
{"API request failed with status 403: forbidden (quota exhausted)", false},
|
||||
{"API request failed with status 404: model not found", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := isTransientLLMError(ctx, errors.New(tc.msg))
|
||||
if got != tc.want {
|
||||
t.Errorf("isTransientLLMError(%q) = %v, want %v", tc.msg, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsTransientLLMError_TransportSubstrings covers providers (and Go
|
||||
// stdlib errors) that surface transient conditions as free-form text
|
||||
// without a numeric status code — DNS blips, TLS handshake failures,
|
||||
// broken pipes during an in-flight body read, etc.
|
||||
func TestIsTransientLLMError_TransportSubstrings(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cases := []struct {
|
||||
msg string
|
||||
want bool
|
||||
}{
|
||||
{"send request: dial tcp: lookup api.example.com: no such host", true},
|
||||
{"send request: read tcp 10.0.0.1: i/o timeout", true},
|
||||
{"send request: Post \"...\": context deadline exceeded", true},
|
||||
{"send request: connection reset by peer", true},
|
||||
{"send request: connection refused", true},
|
||||
{"send request: broken pipe", true},
|
||||
{"send request: tls handshake timeout", true},
|
||||
{"send request: unexpected EOF", true},
|
||||
// Not transient: the error is actionable (missing model id,
|
||||
// malformed tool call, etc.) — retry is just wasted budget.
|
||||
{"model not configured for tool use", false},
|
||||
{"invalid JSON in tool arguments", false},
|
||||
{"parse template: syntax error", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got := isTransientLLMError(ctx, errors.New(tc.msg))
|
||||
if got != tc.want {
|
||||
t.Errorf("isTransientLLMError(%q) = %v, want %v", tc.msg, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsTransientLLMError_AbortsWhenParentCtxDone ensures a cancelled
|
||||
// outer context short-circuits the retry decision. Without this guard
|
||||
// an ingest task that was interrupted (asynq shutdown, deletion race,
|
||||
// parent timeout) would keep retrying the LLM during its teardown
|
||||
// window and waste the remainder of the backoff budget.
|
||||
func TestIsTransientLLMError_AbortsWhenParentCtxDone(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
// This exact error would normally be classified transient (see
|
||||
// TestIsTransientLLMError_HTTPStatuses), but a cancelled ctx must
|
||||
// override that so the task can unwind promptly.
|
||||
err := errors.New("API request failed with status 504: Remote error")
|
||||
if isTransientLLMError(ctx, err) {
|
||||
t.Fatal("cancelled ctx should short-circuit to non-transient")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsTransientLLMError_NilError is a sanity check — nil should never
|
||||
// be treated as retryable, otherwise callers that forget to handle the
|
||||
// happy path would spin forever.
|
||||
func TestIsTransientLLMError_NilError(t *testing.T) {
|
||||
if isTransientLLMError(context.Background(), nil) {
|
||||
t.Fatal("nil error should not be transient")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
// wikiLogEntryService is a thin wrapper over WikiLogEntryRepository. The
|
||||
// event layer carries no business rules today, so the service just
|
||||
// forwards to the repo — the indirection exists so handlers / ingest
|
||||
// batch code depend on an interface rather than a concrete repo type.
|
||||
type wikiLogEntryService struct {
|
||||
repo interfaces.WikiLogEntryRepository
|
||||
}
|
||||
|
||||
// NewWikiLogEntryService constructs a WikiLogEntryService backed by the
|
||||
// given repository.
|
||||
func NewWikiLogEntryService(repo interfaces.WikiLogEntryRepository) interfaces.WikiLogEntryService {
|
||||
return &wikiLogEntryService{repo: repo}
|
||||
}
|
||||
|
||||
// AppendBatch records the given events in one database round trip. Empty
|
||||
// batches are a no-op (the repo handles that).
|
||||
func (s *wikiLogEntryService) AppendBatch(ctx context.Context, entries []*types.WikiLogEntry) error {
|
||||
return s.repo.AppendBatch(ctx, entries)
|
||||
}
|
||||
|
||||
// List paginates the per-KB event feed. See repo.List for cursor semantics.
|
||||
func (s *wikiLogEntryService) List(ctx context.Context, kbID string, cursor string, limit int) (*types.WikiLogEntryListResponse, error) {
|
||||
entries, nextCursor, err := s.repo.List(ctx, kbID, cursor, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if entries == nil {
|
||||
// Normalise to an empty slice so clients don't need to
|
||||
// distinguish `null` from `[]`.
|
||||
entries = []*types.WikiLogEntry{}
|
||||
}
|
||||
return &types.WikiLogEntryListResponse{
|
||||
Entries: entries,
|
||||
NextCursor: nextCursor,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// DeleteByKB removes the log feed for a KB. Called when the KB itself is
|
||||
// being deleted, so no further reads happen.
|
||||
func (s *wikiLogEntryService) DeleteByKB(ctx context.Context, kbID string) error {
|
||||
return s.repo.DeleteByKB(ctx, kbID)
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -246,13 +247,125 @@ func (s *wikiPageService) GetIndex(ctx context.Context, kbID string) (*types.Wik
|
||||
return page, nil
|
||||
}
|
||||
|
||||
// GetLog returns the log page for a knowledge base
|
||||
// wikiIndexContentPageTypes enumerates the page types that make up a wiki's
|
||||
// user-visible directory. System pages (index/log) are excluded; any
|
||||
// LLM-created type we do not recognize surfaces under a generic "other"
|
||||
// bucket.
|
||||
var wikiIndexContentPageTypes = []string{
|
||||
types.WikiPageTypeSummary,
|
||||
types.WikiPageTypeEntity,
|
||||
types.WikiPageTypeConcept,
|
||||
types.WikiPageTypeSynthesis,
|
||||
types.WikiPageTypeComparison,
|
||||
}
|
||||
|
||||
// GetIndexView builds the structured index response without ever
|
||||
// materializing a multi-MB directory markdown string. Intro is read from
|
||||
// the index wiki_page row (which now carries only intro text — see
|
||||
// rebuildIndexPage). Each requested page_type is paginated independently
|
||||
// with ListByTypeLight so reads stay O(page_size) rather than O(total
|
||||
// pages in the KB).
|
||||
//
|
||||
// `pageTypes` narrows which groups to include; empty = all content types.
|
||||
// `limit` is the per-group window size (defaults to 50, capped at 200).
|
||||
// `cursor` is an opaque offset string; currently we use the stringified
|
||||
// offset so clients can resume where they left off. Because different
|
||||
// page_types paginate independently, `cursor` applies uniformly to every
|
||||
// group — if the caller wants per-group cursors it should request one
|
||||
// type at a time via `pageTypes`. That simplifies the wire format and
|
||||
// matches the frontend's tabbed UX.
|
||||
func (s *wikiPageService) GetIndexView(
|
||||
ctx context.Context,
|
||||
kbID string,
|
||||
pageTypes []string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (*types.WikiIndexResponse, error) {
|
||||
indexPage, err := s.GetIndex(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load index page: %w", err)
|
||||
}
|
||||
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
offset := 0
|
||||
if cursor != "" {
|
||||
v, parseErr := strconv.Atoi(cursor)
|
||||
if parseErr != nil || v < 0 {
|
||||
return nil, fmt.Errorf("invalid cursor %q", cursor)
|
||||
}
|
||||
offset = v
|
||||
}
|
||||
|
||||
// Default to every known content type when the caller passes no
|
||||
// filter. Any unknown request-time type is passed through verbatim so
|
||||
// future page types (declared in types/wiki_page.go) start showing
|
||||
// up in the index the moment the LLM starts creating them, without a
|
||||
// handler change.
|
||||
selected := pageTypes
|
||||
if len(selected) == 0 {
|
||||
selected = append([]string{}, wikiIndexContentPageTypes...)
|
||||
}
|
||||
|
||||
groups := make([]types.WikiIndexGroup, 0, len(selected))
|
||||
for _, pt := range selected {
|
||||
entries, total, listErr := s.repo.ListByTypeLight(ctx, kbID, pt, limit, offset)
|
||||
if listErr != nil {
|
||||
return nil, fmt.Errorf("list %s pages: %w", pt, listErr)
|
||||
}
|
||||
if entries == nil {
|
||||
entries = []types.WikiIndexEntry{}
|
||||
}
|
||||
next := ""
|
||||
// Only emit a cursor when a full page was returned AND more rows
|
||||
// remain past `offset + limit`. A short page or one that exactly
|
||||
// consumed the remainder should signal end-of-feed.
|
||||
if len(entries) == limit && int64(offset+len(entries)) < total {
|
||||
next = strconv.Itoa(offset + limit)
|
||||
}
|
||||
groups = append(groups, types.WikiIndexGroup{
|
||||
Type: pt,
|
||||
Total: total,
|
||||
Items: entries,
|
||||
NextCursor: next,
|
||||
})
|
||||
}
|
||||
|
||||
// The intro used to be stored on indexPage.Summary while
|
||||
// indexPage.Content held intro + directory markdown. After the
|
||||
// directory was lifted out of wiki_pages the content column holds
|
||||
// only the intro. Fall back to Summary for KBs that haven't been
|
||||
// re-ingested since the change so the response is never blank.
|
||||
intro := indexPage.Content
|
||||
if strings.TrimSpace(intro) == "" {
|
||||
intro = indexPage.Summary
|
||||
}
|
||||
|
||||
return &types.WikiIndexResponse{
|
||||
Intro: intro,
|
||||
Version: indexPage.Version,
|
||||
Groups: groups,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetLog returns the wiki_pages row for slug='log' if it exists.
|
||||
//
|
||||
// Log events are now stored in the dedicated `wiki_log_entries` table and
|
||||
// paginated via wikiLogEntryService — the per-KB log is no longer a single
|
||||
// TEXT column on a wiki_pages row (that model caused O(n^2) write
|
||||
// amplification as logs grew). This method is retained for callers that
|
||||
// still probe the legacy row (wiki_lint, knowledge delete, etc.), but it
|
||||
// no longer auto-creates the placeholder page on miss; a missing row is a
|
||||
// normal state and the helper returns `nil, nil`.
|
||||
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, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
@@ -619,6 +732,13 @@ func (s *wikiPageService) ListAllPages(ctx context.Context, kbID string) ([]*typ
|
||||
return s.repo.ListAll(ctx, kbID)
|
||||
}
|
||||
|
||||
// ListByType returns every wiki page of a given type for a KB. Exposed so
|
||||
// callers like intro regeneration can load only the page type they need
|
||||
// (summaries) instead of paying for the full ListAll scan.
|
||||
func (s *wikiPageService) ListByType(ctx context.Context, kbID string, pageType string) ([]*types.WikiPage, error) {
|
||||
return s.repo.ListByType(ctx, kbID, pageType)
|
||||
}
|
||||
|
||||
// ListPagesBySourceRef exposes the repository's source-ref lookup so higher
|
||||
// layers (delete flow, retract reconciliation) can re-query the current wiki
|
||||
// state without depending on a stale caller-captured slug list.
|
||||
@@ -821,79 +941,23 @@ func (s *wikiPageService) InjectCrossLinks(ctx context.Context, kbID string, aff
|
||||
}
|
||||
}
|
||||
|
||||
// RebuildIndexPage regenerates the index page directory.
|
||||
// RebuildIndexPage was historically called by agent write/rename tools to
|
||||
// refresh the index page's directory listing after a page mutation.
|
||||
//
|
||||
// The directory is no longer persisted in wiki_pages.content — it is
|
||||
// assembled on demand by GetIndexView from the lightweight ListByTypeLight
|
||||
// projection, so individual page writes don't need to redo O(N) string
|
||||
// concatenation and rewrite a multi-MB TEXT column anymore. Keeping the
|
||||
// method name lets existing agent tool call sites (wiki_write_page,
|
||||
// wiki_rename_page) compile unchanged; the body is now intentionally a
|
||||
// no-op.
|
||||
//
|
||||
// The intro that still lives on the index row is managed separately by
|
||||
// the ingest pipeline (see wikiIngestService.rebuildIndexPage) on batch
|
||||
// completion, which is where we actually have the LLM + change description
|
||||
// context needed to rewrite it.
|
||||
func (s *wikiPageService) RebuildIndexPage(ctx context.Context, kbID string) error {
|
||||
indexPage, err := s.GetIndex(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
allPages, err := s.ListAllPages(ctx, kbID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
typeOrder := []string{
|
||||
types.WikiPageTypeSummary, types.WikiPageTypeEntity, types.WikiPageTypeConcept,
|
||||
types.WikiPageTypeSynthesis, types.WikiPageTypeComparison,
|
||||
}
|
||||
typeLabels := map[string]string{
|
||||
types.WikiPageTypeSummary: "Summary", types.WikiPageTypeEntity: "Entity",
|
||||
types.WikiPageTypeConcept: "Concept", types.WikiPageTypeSynthesis: "Synthesis",
|
||||
types.WikiPageTypeComparison: "Comparison",
|
||||
}
|
||||
|
||||
grouped := make(map[string][]*types.WikiPage)
|
||||
totalPages := 0
|
||||
for _, p := range allPages {
|
||||
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {
|
||||
continue
|
||||
}
|
||||
if p.Status == types.WikiPageStatusArchived {
|
||||
continue
|
||||
}
|
||||
grouped[p.PageType] = append(grouped[p.PageType], p)
|
||||
totalPages++
|
||||
}
|
||||
|
||||
var dir strings.Builder
|
||||
for _, pt := range typeOrder {
|
||||
pages := grouped[pt]
|
||||
if len(pages) == 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", typeLabels[pt], len(pages))
|
||||
for _, p := range pages {
|
||||
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, p.Summary)
|
||||
}
|
||||
}
|
||||
for pt, pages := range grouped {
|
||||
inOrder := false
|
||||
for _, o := range typeOrder {
|
||||
if o == pt {
|
||||
inOrder = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if inOrder || len(pages) == 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&dir, "\n## %s (%d)\n\n", pt, len(pages))
|
||||
for _, p := range pages {
|
||||
fmt.Fprintf(&dir, "[[%s]] — %s\n", p.Slug, p.Summary)
|
||||
}
|
||||
}
|
||||
if totalPages == 0 {
|
||||
dir.WriteString("\n*No wiki pages yet. Upload documents to get started.*\n")
|
||||
}
|
||||
|
||||
intro := indexPage.Summary
|
||||
if intro == "" {
|
||||
intro = "# Wiki Index\n\nThis wiki contains knowledge extracted from uploaded documents.\n"
|
||||
indexPage.Summary = intro
|
||||
}
|
||||
|
||||
indexPage.Content = intro + "\n" + dir.String()
|
||||
_, err = s.UpdatePage(ctx, indexPage)
|
||||
return err
|
||||
_ = ctx
|
||||
_ = kbID
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user