WeKnora/internal/application/service/agent_tool_surface_test.go

164 lines
6.2 KiB
Go
Raw Normal View History

refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents (#3381) * refactor(agent): consolidate knowledge retrieval tools into search_knowledge, read_document, list_documents The agent's retrieval surface had grown to five overlapping tools whose behaviour was scattered across long descriptions, interleaved "tips" in tool output (most of which modelcontext discarded before the model saw them), and a grep_chunks implementation that ran an unindexed regex scan over the chunks table ordered by created_at, so large knowledge bases lost recall and paid a full-table scan on every call. Tool surface - search_knowledge replaces knowledge_search and grep_chunks: one query, mode = hybrid | semantic | keyword, optional knowledge_base_ids, limit. Keyword mode runs through the retrieval engine's keyword index instead of the DB regex scan. Modes unavailable for the scope are refused with a reason. Rerank, MMR and de-duplication are kept; already_seen markers, retrieval_statistics and the zero-result "CRITICAL" block are gone. - read_document replaces list_knowledge_chunks, get_document_info and wiki_read_source_doc: id accepts a dN or cN handle, always returns the document header, pages by exact offset (fixing the old floor-to-page bug), finds passages with query (literal by default, regex opt-in) and reads neighbours around a chunk with context. - list_documents pages through one knowledge base, honouring @file/@tag scope. - wiki_search takes a single query plus regex, knowledge_base_ids, limit; literal queries are escaped so the model never reasons about JSON escaping. Legacy queries / knowledge_base_id are still accepted. - query_knowledge_graph is registered only when a graph-enabled KB is in scope and its description/tips were trimmed. Compatibility - Retired names in stored allowlists, presets and API calls are mapped to their successors by NormalizeAllowedTools at registration time; no data migration. Stored histories with old names still decode, render and redact. Calls to retired names return a replacement hint. - modelcontext gains an "id" key space that decodes against both the chunk and document handle tables (decode-only), plus rendering for the document header, chunk roles, in-document matches and next_offset. Prompts and surfaces - The RAG, wiki researcher and hybrid templates now name the tools and the search -> read -> cite order; tool descriptions are short and contain no workflow instructions. - Engine display names, history redaction, grounding prompt, IM rendering, the built-in MCP server (search_knowledge gains mode/limit, grep_chunks becomes keyword search, read_document gains query, wiki_search gains regex), frontend editor/renderers/i18n, presets, website docs and the changelog are updated accordingly. Tests cover name mapping, mode validation and refusal, output shape, read_document paging/context/query/scope, list_documents, wiki_search escaping and legacy arguments, modelcontext decoding and rendering, and registration-time aliasing and graph gating. * fix(agent): address review findings on read_document, list_documents and model rendering - read_document: fetch the second page whenever the first page did not reach the end of the document, so an unaligned window near the end no longer drops the trailing chunks (also fixes context windows around a chunk near the end); a query passed together with a cN handle now searches the owning document instead of being ignored; query mode stops collecting once the output budget is nearly spent and reports truncated; the document row is authorized in place instead of being fetched twice; the context read takes the total from the window fetch instead of a separate count query. - list_documents: resolve the page's document scope in one batched tag lookup instead of one call per row. - modelcontext: render read_document output once and read next_offset through the existing intValue helper. - search_knowledge: point title/file-name lookups at list_documents. - Tests for the boundary window, chunk context near the end, cN + query, and budget-bound query results. * fix(agent): close compatibility gaps in the consolidated retrieval tools - Wiki-only scopes: read_document and list_documents are registered whenever a wiki KB is in scope, since every KB stores chunks. Their capability requirement includes wiki but is marked auxiliary, so they do not widen a RAG agent's derived "all knowledge bases" filter to wiki-only bases (Go and frontend derivations both honour it). - search_knowledge resolves the retrieval mode per knowledge base instead of refusing the call: FAQ and vector-only bases answer keyword requests semantically, keyword-only bases answer semantic requests by keyword. Results carry requested_mode and mode_fallbacks, the empty-result text names the fallback, and the call is refused only when no base in scope has a chunk index. - The model rendering uses the mode the search actually ran with (it was always labelled semantic) and emits <mode_fallback> per degraded base. - list_documents applies the @file/@tag scope before paging: tags are pushed into the database filter, pinned documents are loaded by ID, and total/next_page count only readable documents. - read_document resolves chunk context by chunk_index through a new ChunkRepository.ListChunkNeighbors, so parent, summary and image chunks sharing the index sequence no longer shift the neighbourhood; offset is documented as a reading-order position, not a chunk index. - wiki_search (agent and MCP) keeps its regular-expression default and only matches literally when the text is not a valid expression; regex=false forces a literal match and regex=true rejects invalid input. - MCP grep_chunks keeps grep semantics: literal terms from the pattern fetch candidates from the keyword index (semantic for bases without one), and every returned chunk is verified against the pattern. * docs(changelog): align the consolidation entry with regex wiki_search and grep_chunks semantics * docs(mcp): note that grep_chunks recall is bounded by index candidates
2026-09-18 06:12:22 +00:00
package service
import (
"context"
"testing"
"github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
)
type toolSurfaceKBService struct {
fakeAgentKnowledgeBaseService
}
func (s *toolSurfaceKBService) GetKnowledgeBaseByIDOnly(context.Context, string) (*types.KnowledgeBase, error) {
return s.kb, nil
}
func newToolSurfaceService(kb *types.KnowledgeBase) *agentService {
return &agentService{
knowledgeBaseService: &toolSurfaceKBService{fakeAgentKnowledgeBaseService{kb: kb}},
knowledgeService: &fakeAgentKnowledgeService{},
}
}
func toolSurfaceConfig(allowed ...string) *types.AgentConfig {
return &types.AgentConfig{
KnowledgeBases: []string{"kb"},
SearchTargets: types.SearchTargets{&types.SearchTarget{
Type: types.SearchTargetTypeKnowledgeBase, KnowledgeBaseID: "kb", TenantID: 7,
}},
AllowedTools: allowed,
}
}
// A stored allowlist that still names the retired retrieval tools registers
// their successors, so agents saved before the consolidation keep working
// without a data migration.
func TestRegisterToolsMapsRetiredRetrievalToolsToSuccessors(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb"}
kb.IndexingStrategy.VectorEnabled = true
svc := newToolSurfaceService(kb)
registry := tools.NewToolRegistry()
cfg := toolSurfaceConfig(
tools.LegacyToolKnowledgeSearch, tools.LegacyToolGrepChunks,
tools.LegacyToolListKnowledgeChunks, tools.LegacyToolGetDocumentInfo,
tools.LegacyToolWikiReadSourceDoc, tools.ToolThinking,
)
require.NoError(t, svc.registerTools(t.Context(), registry, cfg, nil, nil, "session"))
names := registry.ListTools()
require.Contains(t, names, tools.ToolSearchKnowledge)
require.Contains(t, names, tools.ToolReadDocument)
require.Contains(t, names, tools.ToolThinking)
for _, retired := range []string{
tools.LegacyToolKnowledgeSearch, tools.LegacyToolGrepChunks, tools.LegacyToolListKnowledgeChunks,
tools.LegacyToolGetDocumentInfo, tools.LegacyToolWikiReadSourceDoc,
} {
require.NotContains(t, names, retired)
}
require.Equal(t, 1, countName(names, tools.ToolSearchKnowledge), "duplicates collapse to one registration")
require.Equal(t, 1, countName(names, tools.ToolReadDocument))
}
// The graph tool follows the graph capability of the scope, not the checkbox.
func TestRegisterToolsOffersGraphToolOnlyWithGraphEnabledKB(t *testing.T) {
plain := &types.KnowledgeBase{ID: "kb"}
plain.IndexingStrategy.VectorEnabled = true
registry := tools.NewToolRegistry()
require.NoError(t, newToolSurfaceService(plain).registerTools(
t.Context(), registry, toolSurfaceConfig(tools.ToolSearchKnowledge, tools.ToolQueryKnowledgeGraph),
nil, nil, "s",
))
require.Contains(t, registry.ListTools(), tools.ToolSearchKnowledge)
require.NotContains(t, registry.ListTools(), tools.ToolQueryKnowledgeGraph)
graph := &types.KnowledgeBase{ID: "kb", ExtractConfig: &types.ExtractConfig{Enabled: true}}
graph.IndexingStrategy.VectorEnabled = true
graph.IndexingStrategy.GraphEnabled = true
registry = tools.NewToolRegistry()
require.NoError(t, newToolSurfaceService(graph).registerTools(
t.Context(), registry, toolSurfaceConfig(tools.ToolSearchKnowledge, tools.ToolQueryKnowledgeGraph),
nil, nil, "s",
))
require.Contains(t, registry.ListTools(), tools.ToolQueryKnowledgeGraph)
}
// Default agents get the consolidated read surface.
func TestRegisterToolsDefaultSurface(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb"}
kb.IndexingStrategy.KeywordEnabled = true
registry := tools.NewToolRegistry()
require.NoError(t, newToolSurfaceService(kb).registerTools(
t.Context(), registry, toolSurfaceConfig(), nil, nil, "s",
))
names := registry.ListTools()
for _, want := range []string{tools.ToolSearchKnowledge, tools.ToolReadDocument, tools.ToolListDocuments} {
require.Contains(t, names, want)
}
}
func countName(names []string, want string) int {
n := 0
for _, name := range names {
if name == want {
n++
}
}
return n
}
// A wiki-only knowledge base has no chunk index but still stores chunks, so
// the document readers the wiki agents use to check sources stay available
// while chunk search is dropped.
func TestRegisterToolsKeepsDocumentReadersForWikiOnlyScope(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb"}
kb.IndexingStrategy.WikiEnabled = true
registry := tools.NewToolRegistry()
cfg := toolSurfaceConfig(
tools.ToolWikiSearch, tools.ToolWikiReadPage, tools.ToolReadDocument,
tools.ToolListDocuments, tools.ToolSearchKnowledge, tools.LegacyToolWikiReadSourceDoc,
)
require.NoError(t, newToolSurfaceService(kb).registerTools(t.Context(), registry, cfg, nil, nil, "s"))
names := registry.ListTools()
for _, want := range []string{
tools.ToolWikiSearch, tools.ToolWikiReadPage, tools.ToolReadDocument, tools.ToolListDocuments,
} {
require.Contains(t, names, want)
}
require.NotContains(t, names, tools.ToolSearchKnowledge, "chunk search needs a vector or keyword index")
}
fix(security): close cross-workspace access paths in shared spaces (#3408) * fix(security): close cross-workspace access paths in shared spaces A review of how shared-space (organization) members reach each other's resources found six paths that bypass the org-share permission model: - presigned-preview signed any resource handle or storage path, turning a known resource:// handle into an anonymous /r/ URL that outlives share revocation. It now requires the path to belong to the caller's tenant, like /files. - POST /initialization/initialize let a shared-KB editor rewrite the owner workspace's models (base URL, API key) in place. Only the KB's own workspace may call it, and rewriting a stored model needs the same authority as PUT /models/:id. - KB JSON carried the legacy inline credentials (storage_config secret_id/secret_key, which initialization fills with the MinIO env keys, and vlm_config api_key) to every share receiver. They are withheld from JSON; their DB columns are unchanged. - A chat without agent_source_tenant_id resolved shares before the caller's own agent, so a member sharing a same-ID built-in agent took over other workspaces' default agent. Own agents now win, built-in agents can no longer be shared (existing such shares no longer resolve), and embed channels drop a visitor-supplied source workspace. - Any org-admin tenant (even a tenant Viewer inside it) could raise another workspace's KB share to editor/admin, and the route guard was bypassable via an unrelated :id. Share management is now: the sharer from the source tenant (Contributor+), source-tenant Admin+, or an org-admin tenant's Admin+ that may only remove or lower. share_id must belong to :id. - Wiki write tools were registered for every wiki KB in the search targets, which only need read access, so a viewer share (e.g. via the built-in wiki fixer) could edit or delete another workspace's wiki pages. They now act only on KBs the caller may edit. * fix(security): close the KB settings path and owner details for share receivers Follow-up to the shared-space review: - PUT /initialization/config shares the route guard that admits share editors, so an editor could still rebind the owner's KB models, chunking and storage, and storage backends resolved against the caller's workspace let it bind the owner's KB to its own backend. Another workspace now needs an admin share (the only share level the frontend offers settings to) and may not change the storage binding at all. - GET /initialization/config showed model base URLs and bucket locations to any admin of the caller's own workspace, including share receivers. They now only see whether credentials are configured. - Wiki write tools on the caller's own KBs had no role floor, so a tenant Viewer (and the IM, embed and MCP endpoint principals that run as Viewer) could write through an agent what the HTTP routes deny. Writes now need Contributor+, or the ingest capability for a scoped API key, following the RBAC rollout switch. - resolveAgent logs the share lookup error instead of a nil own-agent error when a shared selector fails. * fix(security): close the medium shared-space access findings Follow-up to the high-risk fixes, from the same review: - Wiki fixer moved into a shared KB's workspace ran with the caller's own config there: an unset MCP mode registered all of the owner's MCP services, and an "all" KB scope reached the owner's other KBs. The scoped run now uses the built-in config pinned to that one KB, without MCP, skills, sandbox or web search, and falls back to the KB's own model. - An unset MCP mode means "all" at runtime but is shown as none in the share scope; shared runs now treat it as none. - Quick-answer mode used the request's web_search_enabled alone, so a receiver could turn on search the agent disables and spend the owner's provider quota. It now requires the agent setting too, as agent mode does. - summary_model_id picked any model of the workspace a run executes in. It is ignored for shared agents and the relocated wiki fixer. - A workspace that left or was removed from an organization kept sharing its KBs and agents. Its shares are revoked on departure, and share queries and permission checks require the source workspace's membership and a live organization, which also covers rows left behind earlier. - Sharing an agent exposes its KB scope to all members, so a Contributor could share colleagues' KBs (or "all") through an agent. The sharer must now be able to share each KB directly (creator or Admin+; "all" needs Admin+), also when a shared agent's scope is widened later. - A scoped API key with manage_channels could mint an MCP endpoint token wider than itself. Endpoints it creates, updates or rotates must stay within its KB allow-list and capabilities. - A shared agent's run indexed the receiver's Q&A into the owner's chat history KB; indexing now uses the session owner's configuration. - Sharing an agent with skills keeps injecting the owner's skill environment values (product decision); the share panel now warns that members can read them. Preview of originals through read-only shares is kept as designed and documented.
2026-09-18 14:00:02 +00:00
// Search targets only need read access, so wiki mutation tools are registered
// only when a wiki KB in scope is writable for this caller.
func TestRegisterToolsOffersWikiWritesOnlyForWritableKBs(t *testing.T) {
kb := &types.KnowledgeBase{ID: "kb"}
kb.IndexingStrategy.WikiEnabled = true
writeTools := []string{
tools.ToolWikiWritePage, tools.ToolWikiReplaceText, tools.ToolWikiRenamePage,
tools.ToolWikiDeletePage, tools.ToolWikiFlagIssue, tools.ToolWikiUpdateIssue,
}
allowed := append([]string{tools.ToolWikiReadPage, tools.ToolWikiReadIssue}, writeTools...)
readOnly := toolSurfaceConfig(allowed...)
registry := tools.NewToolRegistry()
require.NoError(t, newToolSurfaceService(kb).registerTools(t.Context(), registry, readOnly, nil, nil, "s"))
names := registry.ListTools()
require.Contains(t, names, tools.ToolWikiReadPage)
require.Contains(t, names, tools.ToolWikiReadIssue)
for _, name := range writeTools {
require.NotContains(t, names, name)
}
writable := toolSurfaceConfig(allowed...)
writable.WritableKBIDs = []string{"kb"}
registry = tools.NewToolRegistry()
require.NoError(t, newToolSurfaceService(kb).registerTools(t.Context(), registry, writable, nil, nil, "s"))
names = registry.ListTools()
for _, name := range writeTools {
require.Contains(t, names, name)
}
}