WeKnora/internal/agent/tools/wiki_source_refs.go

127 lines
3.9 KiB
Go
Raw Normal View History

refactor(modelcontext): consolidate source_refs parsing, fixed data_analysis table, and identifier leak report (#3372) * refactor(wiki): consolidate source_refs parsing and resolution source_refs entries ("uuid" or "uuid|title") were parsed by ten independent implementations that disagreed on whitespace handling, on whether a model-supplied title could be trusted, and on how a leading pipe was treated. The scope-enforced and legacy agent resolvers also duplicated the lookup and the routing step looked every document up a second time. - types.ParseWikiSourceRef / FormatWikiSourceRef / WikiSourceRefMatchesKnowledge are now the only readers and writer of the format. - resolveWikiSourceDocuments replaces resolveAuthorizedSourceRefs, resolveSourceRefs and wikiKnowledgeBasesForSourceRefs: one lookup per document, titles always rebuilt from server data, dedupe by canonical ID, unknown documents fail closed in every mode. - removeSourceRef now matches padded or titled refs of a deleted document. * refactor(data_analysis): expose the selected document as a fixed table name The tool required the document ID inside the SQL text and blindly string-replaced it with the physical DuckDB table name, which forced the model-context codec to rewrite handles inside quoted SQL and let the UUID-derived k_<uuid> table name reach the model through stored schema summaries. The document is now selected only by knowledge_id. Every query runs on a dedicated connection where "dataset" is a temporary view over the physical table (DuckDB temporary objects are connection-local, so concurrent sessions stay isolated). The physical name remains accepted for internal callers; any other table fails validation with an error naming the table the model should use. Schema summaries, the schema tool, the analyst prompt and the tool schema all name the same table, so data_analysis.sql no longer carries source handles and its text codec policy is removed. * feat(modelcontext): report raw identifiers that survive encoding Text-level compaction exists because raw UUIDs reach model context through producers the registry never sees: error strings, slugs, results of unknown shape. Retiring it requires knowing where those producers are. Registry.LeakedIdentifiers scans an encoded message list for UUID-shaped values in every application-composed field (user messages are skipped), classifies each as registered (codec missed a rewrite) or unregistered (producer emitted a raw ID), and SummarizeLeaks renders one line per field. The agent engine and the three RAG pipeline call sites log the report as a warning after EncodeMessages. * fix(chat_pipeline): align RAG data analysis with the fixed table contract The RAG data-analysis plugin still asked the planning model to fill in knowledge_id and to write SQL from a prompt that exposed the raw knowledge UUID, then passed the model's JSON straight to Execute. Under the new data_analysis contract a query that names anything but the dataset table is rejected, and the plugin logged that rejection at error level and moved on, so the analysis vanished without any signal. A "no analysis needed" plan took the same error path. The pipeline now owns document selection: the model returns only needs_analysis and sql, the prompt names the dataset table and never shows the knowledge ID or physical table, and the plugin builds the tool input itself. A rejected query is fed back to the model once for repair; a query that still fails is reported through pipelineWarn with the SQL and the tool error, and "not needed" is logged as such instead of as a failure. Covered by unit tests with a scripted model and executor: not-needed, pipeline-owned knowledge_id, one-shot repair, persistent failure surfaced, unparseable plan rejected.
2026-09-17 14:08:16 +00:00
package tools
import (
"context"
"fmt"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
// wikiSourceDocument is a source document named by a model-supplied
// source_refs entry, resolved once against server data. Every Wiki mutation
// tool derives both the stored "uuid|title" refs and any KB routing hints from
// this single resolution, so the model-supplied title suffix is never trusted
// and each document is looked up exactly once.
type wikiSourceDocument struct {
ID string
Title string
KnowledgeBaseID string
}
// resolveWikiSourceDocuments parses model-supplied source_refs (bare IDs or
// legacy "uuid|title" entries), deduplicates them, and rebuilds each entry
// from the knowledge record. With enforceScope the document must also lie
// inside the Agent's SearchTargets. Without a knowledge service the IDs are
// kept as given (bare, trimmed); this is only reachable when scope
// enforcement is off, which production wiring never does.
func resolveWikiSourceDocuments(
ctx context.Context,
refs []string,
knowledgeService interfaces.KnowledgeService,
searchTargets types.SearchTargets,
enforceScope bool,
) ([]wikiSourceDocument, error) {
resolved := make([]wikiSourceDocument, 0, len(refs))
seen := make(map[string]struct{}, len(refs))
for _, ref := range refs {
knowledgeID, _ := types.ParseWikiSourceRef(ref)
if knowledgeID == "" {
continue
}
var knowledge *types.Knowledge
switch {
case enforceScope:
var err error
knowledge, err = authorizeKnowledgeInSearchTargets(ctx, searchTargets, knowledgeID, knowledgeService)
if err != nil {
return nil, err
}
case knowledgeService != nil:
var err error
knowledge, err = knowledgeService.GetKnowledgeByIDOnly(ctx, knowledgeID)
if err != nil || knowledge == nil {
if err == nil {
err = fmt.Errorf("empty result")
}
return nil, fmt.Errorf("document %s not found: %w", knowledgeID, err)
}
default:
knowledge = &types.Knowledge{ID: knowledgeID}
}
if _, exists := seen[knowledge.ID]; exists {
continue
}
seen[knowledge.ID] = struct{}{}
title := strings.TrimSpace(knowledge.Title)
if title == "" {
title = strings.TrimSpace(knowledge.FileName)
}
resolved = append(resolved, wikiSourceDocument{
ID: knowledge.ID,
Title: title,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
})
}
return resolved, nil
}
// wikiSourceRefs renders resolved documents as stored source_refs entries.
func wikiSourceRefs(docs []wikiSourceDocument) []string {
refs := make([]string, 0, len(docs))
for _, doc := range docs {
if ref := types.FormatWikiSourceRef(doc.ID, doc.Title); ref != "" {
refs = append(refs, ref)
}
}
return refs
}
// wikiSourceKnowledgeIDs returns the bare IDs of resolved documents.
func wikiSourceKnowledgeIDs(docs []wikiSourceDocument) []string {
ids := make([]string, 0, len(docs))
for _, doc := range docs {
ids = append(ids, doc.ID)
}
return ids
}
// wikiKnowledgeBasesForSourceDocuments returns the distinct knowledge bases
// owning the resolved documents, as routing hints for a new page. A document
// outside the allowed Wiki KBs fails closed; a document whose KB is unknown
// (no knowledge service) contributes no hint.
func wikiKnowledgeBasesForSourceDocuments(docs []wikiSourceDocument, allowedKBIDs []string) ([]string, error) {
if len(docs) == 0 {
return nil, nil
}
allowed := make(map[string]struct{}, len(allowedKBIDs))
for _, kbID := range dedupNonEmptyStrings(allowedKBIDs) {
allowed[kbID] = struct{}{}
}
var kbIDs []string
for _, doc := range docs {
if doc.KnowledgeBaseID == "" {
continue
}
if _, ok := allowed[doc.KnowledgeBaseID]; !ok {
return nil, fmt.Errorf(
"source document %s belongs to knowledge base %s, which is outside the Wiki scope",
doc.ID, doc.KnowledgeBaseID,
)
}
kbIDs = append(kbIDs, doc.KnowledgeBaseID)
}
return dedupNonEmptyStrings(kbIDs), nil
}