Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

Feat/migrates navigation tools form old mode to agentic mode (#20735)

Caobaining125481cdff35a
diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.go
index 1ca4614fbb..862e4859a8 100644
--- a/cmd/ragflow_server.go
+++ b/cmd/ragflow_server.go
@@ -1175,6 +1175,13 @@ func startServer(ctx context.Context, serverName string, arguments *serverArgs)
runtime.SetBm25Service(bm25Adapter)
common.Info("agent: smart-reasoning corpus services installed (grep + bm25)")
+ // The compiled-knowledge graph walk (graph_explore) resolves its service per
+ // call the same way. Without this registration GetKgService() returns the
+ // failing stub, so the tool could only ever report an infrastructure error.
+ // The seed encoder is left unset: the walk then seeds by keyword match on the
+ // entity rows, the documented fallback on a deployment without an embedder.
+ smartagentic.SetKgService(smartagentic.NewKgAdapter(docEngine))
+ common.Info("agent: smart-reasoning compiled-knowledge graph service installed")
// Wire the agentic-RAG runtime as the Go chat pipeline's evidence engine
// (internal/service/chat_pipeline.retrieveViaHarness): it runs each request on a
// model resolved from the caller's ModelID and searches through the adapter
diff --git a/conf/agentic_rag.yaml b/conf/agentic_rag.yaml
index d2a1542e6c..66db98fd4d 100644
--- a/conf/agentic_rag.yaml
+++ b/conf/agentic_rag.yaml
@@ -27,6 +27,7 @@ templates:
- **grep_chunks:** locate by pattern - ONE POSIX regex over chunk content, case-insensitive (like grep -E -i). Pack the key people, objects and verbs into ONE broad alternation, and do NOT anchor it to a subject/verb chain: the same event often appears with the actor as the grammatical object, and a broad alternation matches regardless of role.
- **search_bm25_chunks** (when the deployment supplies it): lexical recall - 1-5 keyword queries ranked by BM25 over tokenized chunk fields.
- **search_semantic_chunks** (when supplied): the semantic bridge - 1-5 queries ranked purely by word meaning (pure vector, no keyword leg). Use it when the corpus likely words things differently from the question.
+ - **search_metadata** (when the deployment supplies it): Document-metadata SELECTOR - given metadata conditions, return the document ids (doc_ids) whose metadata matches; it runs NO content retrieval of its own. Use it to narrow the corpus to the documents that satisfy a metadata predicate (e.g. author = "X", year contains "2024", doc_type in ["report","memo"]) before reading them: pass the returned doc_ids as search_chunks' "doc_scope" to search ONLY inside those documents, or as list_chunks' "doc_id" for a deep read.
- **list_chunks:** the deep reader, and the authoritative source for corpus-backed claims. Pass ONE document's doc_id plus 1-20 chunk_ids from locate output (anchor_chunk_ids); set number_neighbors to N to widen each anchor with the N chunks before AND after it, and cover a long document by chaining anchored calls (each reply's doc_chunks_total tells you what is still uncovered). Corpus search snippets locate; only the deep read proves.
- **todo_write** (optional): track multi-step research (worth it from 3+ retrieval steps).
- **think** (optional): plan and reflect on what you have retrieved.
diff --git a/internal/agentic_rag/agent.go b/internal/agentic_rag/agent.go
index dfabff5eec..a09c3710de 100644
--- a/internal/agentic_rag/agent.go
+++ b/internal/agentic_rag/agent.go
@@ -24,6 +24,7 @@ import (
"regexp"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/cloudwego/eino/adk"
@@ -73,6 +74,14 @@ type Input struct {
// DocIDs is the server-bound document scope. Nil leaves retrieval unrestricted;
// a non-nil empty slice restricts all corpus tools to no documents.
DocIDs []string
+ // ConversationKey is the conversation's stable identifier (the chat id). When
+ // set, the compiled-knowledge tools (navigate_tree / graph_explore) record a
+ // dataset-level absence once and drop themselves from the tool list until the
+ // 30-minute mark expires, so the agent stops spending calls on a tool the
+ // corpus cannot satisfy. When empty, a per-run key scopes the decision to this
+ // single ReAct turn. The chat pipeline sets it from the conversation id; see
+ // nav_tool_enablement.go.
+ ConversationKey string
// Tools are the eino tools the agent may call. When empty, the tool set of
// the resolved template (TemplateID, else the config's default) is used.
// The web_search tool is NOT passed here: it is injected from the run's
@@ -115,6 +124,11 @@ const defaultMaxIterations = 120
var errNilModel = errors.New("agentic_rag: model is required")
+// runSeq issues a unique key for each Run that carries no ConversationKey, so a
+// disable decision is scoped to that turn and does not collide with a concurrent
+// one.
+var runSeq uint64
+
// llmRetryMax bounds retry attempts per model call on top of the initial one
// (adk semantics: MaxRetries=1 → up to 2 calls). With the backoff below the
// worst-case added latency per call is ~2s.
@@ -299,6 +313,23 @@ func Run(ctx context.Context, in Input) (string, error) {
ctx = withDocumentScope(ctx, in.DocIDs)
}
+ // Conversation identity for per-conversation compiled-knowledge tool
+ // availability: the chat pipeline passes the chat id; when absent, a unique
+ // per-run key keeps any availability decision scoped to this turn and
+ // isolated from concurrent runs.
+ convKey := in.ConversationKey
+ generatedKey := convKey == ""
+ if generatedKey {
+ convKey = fmt.Sprintf("run-%d", atomic.AddUint64(&runSeq, 1))
+ }
+ ctx = WithConversationKey(ctx, convKey)
+ if generatedKey {
+ // The generated key belongs to this turn alone: no later run reuses it,
+ // so release its availability marks on the way out instead of leaking
+ // one dead entry per keyless run into the process-wide map.
+ defer forgetConversation(convKey)
+ }
+
tmpl, errT := resolveTemplateFor(in.TemplateID)
if errT != nil {
common.ErrorCtx(ctx, "agentic_rag: resolve template", errT)
@@ -314,6 +345,14 @@ func Run(ctx context.Context, in Input) (string, error) {
// With no explicit tools, use the requested template. The config reloads
// when its mtime changes so operators can change the tool list and prompt.
tools := toolsFor(ctx, tmpl, in.TenantID, in.DatasetIDs, in.Tools)
+ // The compiled-knowledge tools are injected, never declared: they only make
+ // sense when the bound datasets have produced knowledge-compilation products
+ // (navigation tree / compiled structure / knowledge graph), so an uncompiled
+ // corpus never offers - or pays for - them. A caller that passes explicit
+ // tools owns its own set and is left untouched.
+ if len(in.Tools) == 0 && datasetsHaveCompiledKnowledge(ctx, in.TenantID, in.DatasetIDs) {
+ tools = append(tools, compiledKnowledgeTools(in.TenantID, in.DatasetIDs)...)
+ }
agentModel, err := modelForTools(ctx, in.Model, tools, in.DatasetIDs)
if err != nil {
return "", err
@@ -342,6 +381,21 @@ func Run(ctx context.Context, in Input) (string, error) {
}
tools = wrapped
+ // Drop compiled-knowledge tools this conversation has already proven
+ // unusable (dataset-level absence), so the model cannot keep calling them
+ // and wasting turns. The tool still short-circuits on its own for any call
+ // that slips through, but removing it from the list is the clean stop.
+ if unavailable := navUnavailableToolSet(ctx); len(unavailable) > 0 {
+ kept := tools[:0]
+ for _, t := range tools {
+ if info, ierr := t.Info(ctx); ierr == nil && info != nil && unavailable[info.Name] {
+ continue
+ }
+ kept = append(kept, t)
+ }
+ tools = kept
+ }
+
common.DebugCtx(ctx, "agentic_rag: run start",
zap.Int("max_iterations", maxIter),
zap.Int("messages", len(in.Messages)),
diff --git a/internal/agentic_rag/compiled_knowledge.go b/internal/agentic_rag/compiled_knowledge.go
new file mode 100644
index 0000000000..7af9d93bb5
--- /dev/null
+++ b/internal/agentic_rag/compiled_knowledge.go
@@ -0,0 +1,77 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+
+ "github.com/cloudwego/eino/components/tool"
+
+ "ragflow/internal/engine"
+ enginetypes "ragflow/internal/engine/types"
+)
+
+// compiledKnowledgeToolNames are the tools that only make sense on a corpus that
+// has produced knowledge-compilation products (a navigation tree, a compiled
+// structure, a knowledge graph). They are INJECTED, never declared in a
+// template's tool list: Run adds them only when the bound datasets actually hold
+// compiled products, so an uncompiled corpus never offers - or pays for - them.
+var compiledKnowledgeToolNames = []string{
+ navigateTreeToolName,
+ navigateStructureToolName,
+ graphExploreToolName,
+}
+
+// compiledKnowledgeTools builds the injected compiled-knowledge tool set scoped
+// to the given tenant/datasets.
+func compiledKnowledgeTools(tenantID string, datasetIDs []string) []tool.BaseTool {
+ reg := toolRegistry()
+ out := make([]tool.BaseTool, 0, len(compiledKnowledgeToolNames))
+ for _, name := range compiledKnowledgeToolNames {
+ if f, ok := reg[name]; ok {
+ out = append(out, f(tenantID, datasetIDs))
+ }
+ }
+ return out
+}
+
+// datasetsHaveCompiledKnowledge reports whether any bound dataset carries a
+// knowledge-compilation product. Compiled products are exactly the rows that
+// carry compile_kwd; ordinary chunks do not (that is what the default retriever
+// excludes with must_not/exists compile_kwd), so a single existence read answers
+// it. A missing engine or an empty scope is false, leaving the tools undeclared.
+func datasetsHaveCompiledKnowledge(ctx context.Context, tenantID string, datasetIDs []string) bool {
+ if len(datasetIDs) == 0 {
+ return false
+ }
+ de := engine.Get()
+ if de == nil {
+ return false
+ }
+ res, err := de.Search(ctx, &enginetypes.SearchRequest{
+ IndexNames: []string{indexNameFor(tenantID, "")},
+ KbIDs: datasetIDs,
+ SelectFields: []string{"id"},
+ Filter: map[string]interface{}{"exists": "compile_kwd"},
+ Limit: 1,
+ IncludeUnavailable: true,
+ })
+ if err != nil || res == nil {
+ return false
+ }
+ return len(res.Chunks) > 0
+}
diff --git a/internal/agentic_rag/config.go b/internal/agentic_rag/config.go
index 1e198199e1..abc2e2d467 100644
--- a/internal/agentic_rag/config.go
+++ b/internal/agentic_rag/config.go
@@ -83,6 +83,18 @@ func toolRegistry() map[string]toolFactory {
"search_semantic_chunks": func(t string, d []string) tool.BaseTool { return NewSearchSemanticChunksTool(t, d) },
"list_chunks": func(t string, d []string) tool.BaseTool { return NewListChunksTool(t, d) },
"search_metadata": func(t string, d []string) tool.BaseTool { return NewMetadataSearchTool(t, d) },
+ // The compiled-knowledge-graph walk. Registered always; a template that
+ // omits it simply never offers it to the model.
+ "graph_explore": func(t string, d []string) tool.BaseTool { return NewGraphExploreTool(t, d) },
+ // The compiled-navigation-tree router. Registered always; a template that
+ // omits it simply never offers it to the model (same pattern as
+ // graph_explore).
+ "navigate_tree": func(t string, d []string) tool.BaseTool { return NewNavigateTreeTool(t, d) },
+ // The compiled-structure drilldown: given a doc_id (from navigate_tree),
+ // reads that document's compiled entity/relation outline and returns a
+ // query-focused TOC the model feeds to list_chunks. Registered always; a
+ // template that omits it never offers it to the model.
+ "navigate_structure": func(t string, d []string) tool.BaseTool { return NewNavigateStructureTool(t, d) },
}
}
diff --git a/internal/agentic_rag/config_test.go b/internal/agentic_rag/config_test.go
index c528f1339d..5156402464 100644
--- a/internal/agentic_rag/config_test.go
+++ b/internal/agentic_rag/config_test.go
@@ -159,13 +159,16 @@ func TestTemplateTemperatureComesFromConfig(t *testing.T) {
}
}
-// TestShippedConfigIsASingleDirectAnswerTemplate guards conf/agentic_rag.yaml
-// end to end: exactly one template (smart-reasoning), the toolset the code and
-// the prompt agree on, and a DIRECT-ANSWER prompt - no question-decomposition
-// stage, no intermediate deliverable format, no auditor, and the mechanical
-// provenance contract (`chunk_id: <id>`) the chat pipeline turns into
-// citation markers.
-func TestShippedConfigIsASingleDirectAnswerTemplate(t *testing.T) {
+// TestShippedConfigIsADirectAnswerTemplate guards conf/agentic_rag.yaml end to
+// end: exactly one template (smart-reasoning) carrying the direct-answer prompt
+// and the baseline locate/deep-read toolset. The compiled-knowledge tools
+// (navigate_tree / navigate_structure / graph_explore) are intentionally NOT
+// listed here - Run injects them when the bound datasets carry compilation
+// products (see compiled_knowledge.go). The prompt is the direct-answer rewrite
+// - no question-decomposition stage, no intermediate deliverable format, no
+// auditor - and carries the mechanical provenance contract (`[ID:n]`) the chat
+// pipeline turns into citation markers.
+func TestShippedConfigIsADirectAnswerTemplate(t *testing.T) {
t.Setenv("AGENTIC_RAG_CONFIG", filepath.Join("..", "..", "conf", "agentic_rag.yaml"))
configMu.Lock()
cachedFile = nil
@@ -187,6 +190,9 @@ func TestShippedConfigIsASingleDirectAnswerTemplate(t *testing.T) {
if tmpl.ID != "smart-reasoning" {
t.Fatalf("template id = %q, want smart-reasoning", tmpl.ID)
}
+ // The compiled-knowledge tools (navigate_tree / navigate_structure /
+ // graph_explore) are NOT declared here: Run injects them only when the bound
+ // datasets actually carry compilation products (see compiled_knowledge.go).
wantTools := []string{
"think", "todo_write", "grep_chunks", "search_bm25_chunks",
"search_semantic_chunks", "list_chunks", "run_javascript", "search_metadata",
diff --git a/internal/agentic_rag/kg_service.go b/internal/agentic_rag/kg_service.go
new file mode 100644
index 0000000000..61fdb6046a
--- /dev/null
+++ b/internal/agentic_rag/kg_service.go
@@ -0,0 +1,681 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+
+ "ragflow/internal/engine"
+ enginetypes "ragflow/internal/engine/types"
+)
+
+// Knowledge-graph walk backing the graph_explore tool. It is the agentic-RAG
+// port of the harness walk (internal/rag/agentic-rag/runtime/tool_exploration.go):
+// seed entity rows for the query, hop out over relation rows, and hand the
+// subgraph plus the source passages behind it back to the model.
+//
+// Deliberate deviation from the harness original: there the walk asks the chat
+// model whether the subgraph answers the question and short-circuits with a
+// bare answer when it does. This port never calls a model. In this ReAct loop
+// the model is already the judge of its own evidence, a tool holds no chat
+// model, and an answer-only result would strip the passages the answer has to
+// cite. The walk therefore always returns the subgraph and its passages.
+
+// Error returned when no KgService was installed at boot.
+var ErrKgServiceMissing = errors.New(
+ "kg service not registered — call agentic_rag.SetKgService(...) at boot",
+)
+
+// Kg row scopes and walk limits, mirroring the harness constants.
+const (
+ kgScopeDataset = "dataset"
+ kgScopeDoc = "doc"
+
+ kgSeeds = 2 // top-N entities matched directly to the question
+ kgSeedPool = 64 // KNN candidate pool before the mention_count re-sort
+ kgSeedSim = 0.8 // dense seed similarity floor
+ kgHops = 2 // relation hops out from the seeds
+ kgNeighbors = 128 // cap on neighbour entity rows resolved per hop
+ kgRelLimit = 32 // relations fetched per endpoint filter
+ kgMaxPassages = 6 // source passages returned per walk
+ kgPassageRunes = 1500
+)
+
+// KgEntity is one entity row of the compiled graph.
+type KgEntity struct {
+ Name string
+ Type string
+ Description string
+ Aliases []string
+ SourceChunkIDs []string
+ DocID string
+}
+
+// KgRelation is one relation (edge) row of the compiled graph.
+type KgRelation struct {
+ ID string
+ From string
+ To string
+ Type string
+ SourceChunkIDs []string
+ DocID string
+}
+
+// KgPassage is one source chunk behind a graph node or edge.
+type KgPassage struct {
+ ChunkID string
+ DocID string
+ DocName string
+ DatasetID string
+ Content string
+}
+
+// KgExploreRequest is one graph walk request. DatasetIDs is the conversation's
+// server-bound scope; DocScope, when non-empty, pins the walk to those docs.
+type KgExploreRequest struct {
+ TenantID string
+ DatasetIDs []string
+ DocScope []string
+ Query string
+}
+
+// KgExploreResult is the walk output: the seeded + hopped subgraph and the
+// passages behind it, in first-seen order.
+type KgExploreResult struct {
+ Entities []KgEntity
+ Relations []KgRelation
+ Passages []KgPassage
+ // GraphAbsent is true ONLY when the bound scope provably holds no compiled
+ // entity rows at all - a dataset-level fact that does not change within a
+ // conversation, which is what lets the tool disable itself. An empty walk
+ // with GraphAbsent false is a query-level miss (the graph exists but this
+ // query seeded nothing) or an infrastructure failure: neither may disable
+ // the tool, because a better-phrased query may still hit.
+ GraphAbsent bool
+}
+
+// KgService walks the compiled knowledge graph. The tools resolve it per call
+// so the server can install the engine-backed adapter at boot.
+type KgService interface {
+ Explore(ctx context.Context, req KgExploreRequest) (KgExploreResult, error)
+}
+
+var (
+ kgServiceMu sync.RWMutex
+ kgServiceImpl KgService = stubKgService{}
+)
+
+// SetKgService installs the graph-walk service. nil restores the stub.
+func SetKgService(svc KgService) {
+ kgServiceMu.Lock()
+ defer kgServiceMu.Unlock()
+ if svc == nil {
+ kgServiceImpl = stubKgService{}
+ return
+ }
+ kgServiceImpl = svc
+}
+
+// GetKgService returns the installed graph-walk service (a failing stub when
+// none was installed).
+func GetKgService() KgService {
+ kgServiceMu.RLock()
+ defer kgServiceMu.RUnlock()
+ return kgServiceImpl
+}
+
+type stubKgService struct{}
+
+func (stubKgService) Explore(context.Context, KgExploreRequest) (KgExploreResult, error) {
+ return KgExploreResult{}, ErrKgServiceMissing
+}
+
+// KgAdapter walks the compiled graph rows through the document engine. It is
+// stateless and safe to share across goroutines.
+type KgAdapter struct {
+ docEngine engine.DocEngine
+ // seedEncoder embeds the query for the dense seed search. nil (or a nil
+ // vector) degrades the seed search to a keyword match on the entity rows,
+ // so the walk still works on a deployment without a tenant embedder.
+ seedEncoder func(ctx context.Context, tenantID, text string) []float64
+}
+
+// NewKgAdapter wraps a doc engine behind the KgService interface.
+func NewKgAdapter(docEngine engine.DocEngine) *KgAdapter {
+ return &KgAdapter{docEngine: docEngine}
+}
+
+// SetSeedEncoder installs the query-side embedder used by the dense seed
+// search. Pass nil to fall back to keyword seeding.
+func (a *KgAdapter) SetSeedEncoder(fn func(ctx context.Context, tenantID, text string) []float64) {
+ if a == nil {
+ return
+ }
+ a.seedEncoder = fn
+}
+
+// Explore seeds entities for the query, hops kgHops out over their relations,
+// and returns the subgraph with the passages behind it.
+func (a *KgAdapter) Explore(ctx context.Context, req KgExploreRequest) (KgExploreResult, error) {
+ empty := KgExploreResult{}
+ if a == nil || a.docEngine == nil {
+ return empty, ErrKgServiceMissing
+ }
+ query := strings.TrimSpace(req.Query)
+ datasetIDs := nonEmptyStrings(req.DatasetIDs)
+ if query == "" || len(datasetIDs) == 0 {
+ return empty, nil
+ }
+
+ // Encode the seed text ONCE: one embedding request serves every dataset.
+ seedVec := a.seedVector(ctx, req.TenantID, query)
+
+ var entities []KgEntity
+ var relations []KgRelation
+ seenNames := map[string]bool{}
+
+ addEntities := func(found []KgEntity, kbID string) []string {
+ var added []string
+ for _, e := range found {
+ key := kbID + ":" + strings.ToLower(e.Name)
+ if seenNames[key] {
+ continue
+ }
+ seenNames[key] = true
+ entities = append(entities, e)
+ added = append(added, e.Name)
+ }
+ return added
+ }
+
+ docs := nonEmptyStrings(req.DocScope)
+ // Whole-dataset walk: no scope filter. The compacted rows of this corpus
+ // live at scope_kwd=doc, so filtering by scope_kwd=dataset would read the
+ // graph as empty; the harness's dataset default is not carried over.
+ scopeKwd := ""
+ if len(docs) > 0 {
+ scopeKwd = kgScopeDoc
+ }
+
+ for _, kbID := range datasetIDs {
+ seedRows := a.seedSearch(ctx, req.TenantID, kbID, docs, query, scopeKwd, seedVec)
+ var seeds []KgEntity
+ for _, row := range seedRows {
+ if e, ok := kgParseEntity(row); ok {
+ seeds = append(seeds, e)
+ }
+ }
+ frontier := addEntities(seeds, kbID)
+
+ for hop := 0; hop < kgHops; hop++ {
+ if len(frontier) == 0 {
+ break
+ }
+ terms := kgEndpointTerms(frontier)
+ relRows := a.kgSearch(ctx, req.TenantID, kbID, docs, "relation", "", kgRelLimit, scopeKwd,
+ map[string]interface{}{"from_entity_kwd": terms}, "", 0)
+ relRows = append(relRows, a.kgSearch(ctx, req.TenantID, kbID, docs, "relation", "", kgRelLimit, scopeKwd,
+ map[string]interface{}{"to_entity_kwd": terms}, "", 0)...)
+
+ // Dedup on the row id so the same endpoint pair from different rows
+ // survives; fall back to the from|to|type triple when the engine
+ // returned no id.
+ seenRel := map[string]bool{}
+ var hopRelations []KgRelation
+ for _, row := range relRows {
+ rel, ok := kgParseRelation(row)
+ if !ok {
+ continue
+ }
+ key := rel.ID
+ if key == "" {
+ key = rel.From + "|" + rel.To + "|" + rel.Type
+ }
+ if seenRel[key] {
+ continue
+ }
+ seenRel[key] = true
+ hopRelations = append(hopRelations, rel)
+ }
+ relations = append(relations, hopRelations...)
+
+ seenLower := map[string]bool{}
+ for key := range seenNames {
+ if strings.HasPrefix(key, kbID+":") {
+ seenLower[strings.TrimPrefix(key, kbID+":")] = true
+ }
+ }
+ neighSet := map[string]string{}
+ for _, rel := range hopRelations {
+ for _, name := range []string{rel.From, rel.To} {
+ name = strings.TrimSpace(name)
+ if name == "" || seenLower[strings.ToLower(name)] {
+ continue
+ }
+ neighSet[strings.ToLower(name)] = name
+ }
+ }
+ if len(neighSet) == 0 {
+ break
+ }
+ neighbours := make([]string, 0, len(neighSet))
+ for _, name := range neighSet {
+ neighbours = append(neighbours, name)
+ }
+ limit := kgNeighbors
+ if len(neighbours) < limit {
+ limit = len(neighbours)
+ }
+ neighRows := a.kgSearch(ctx, req.TenantID, kbID, docs, "entity", "", limit, scopeKwd,
+ map[string]interface{}{"name_kwd": kgEndpointTerms(neighbours)}, "", 0)
+ var found []KgEntity
+ for _, row := range neighRows {
+ if e, ok := kgParseEntity(row); ok {
+ found = append(found, e)
+ }
+ }
+ frontier = addEntities(found, kbID)
+ }
+ }
+
+ if len(entities) == 0 && len(relations) == 0 {
+ // A doc-scoped walk (the model passed doc_scope) can only ever prove
+ // that THOSE documents hold no entity row - it says nothing about the
+ // dataset, so it must not report a dataset-level absence: that would
+ // disable graph_explore for the whole conversation on a single scoped
+ // miss. Report a plain empty result instead, which the tool treats as a
+ // query miss.
+ if len(docs) > 0 {
+ return empty, nil
+ }
+ // An unscoped empty walk is still ambiguous: the dataset may hold a
+ // graph that this query seeded nothing from, or no compiled graph at
+ // all. Probe the entity rows to tell them apart - and propagate a probe
+ // failure rather than misreading an infrastructure error as "no graph".
+ // Only a probe that succeeded and found nothing is a dataset-level
+ // absence.
+ for _, kbID := range datasetIDs {
+ has, probeErr := a.graphRowsExist(ctx, req.TenantID, kbID, nil, "")
+ if probeErr != nil {
+ return empty, probeErr
+ }
+ if has {
+ return empty, nil
+ }
+ }
+ return KgExploreResult{GraphAbsent: true}, nil
+ }
+ return KgExploreResult{
+ Entities: entities,
+ Relations: relations,
+ Passages: a.evidencePassages(ctx, req.TenantID, datasetIDs, entities, relations),
+ }, nil
+}
+
+// seedVector encodes the query for the dense seed search. A nil result (no
+// encoder, or an encoding failure) sends the caller to the keyword fallback.
+func (a *KgAdapter) seedVector(ctx context.Context, tenantID, text string) []float64 {
+ if a.seedEncoder == nil {
+ return nil
+ }
+ defer func() {
+ // A misconfigured embedding service must degrade to keyword seeding,
+ // never take the turn down.
+ _ = recover()
+ }()
+ vec := a.seedEncoder(ctx, tenantID, text)
+ if len(vec) == 0 {
+ return nil
+ }
+ return vec
+}
+
+// seedSearch resolves the seed entity rows: dense KNN over the entity rows
+// re-ranked by mention_count desc, or a keyword match when no vector is
+// available.
+func (a *KgAdapter) seedSearch(ctx context.Context, tenantID, kbID string, docs []string, text, scopeKwd string, seedVec []float64) []map[string]interface{} {
+ if len(seedVec) > 0 {
+ dense := &enginetypes.MatchDenseExpr{
+ VectorColumnName: fmt.Sprintf("q_%d_vec", len(seedVec)),
+ EmbeddingData: seedVec,
+ EmbeddingDataType: "float",
+ DistanceType: "cosine",
+ TopN: kgSeedPool,
+ ExtraOptions: map[string]interface{}{"similarity": kgSeedSim},
+ }
+ rows := a.kgSearchRaw(ctx, tenantID, kbID, docs, "entity", scopeKwd, nil, []interface{}{dense}, "mention_count_int", kgSeedPool)
+ return kgTopMentionCount(rows, kgSeeds)
+ }
+ return a.kgSearch(ctx, tenantID, kbID, docs, "entity", text, kgSeeds, scopeKwd, nil, "mention_count_int", kgSeedPool)
+}
+
+// graphRowsExist reports whether one dataset holds ANY compiled entity row in
+// the given scope. Unlike kgSearchRaw it PROPAGATES the engine error: the caller
+// uses the answer to decide whether an empty walk is a dataset-level absence
+// (which disables the tool) or a transient backend failure (which must not), and
+// a swallowed error would silently turn the latter into the former.
+func (a *KgAdapter) graphRowsExist(ctx context.Context, tenantID, kbID string, docs []string, scopeKwd string) (bool, error) {
+ condition := map[string]interface{}{"knowledge_graph_kwd": "entity"}
+ if scopeKwd != "" {
+ condition["scope_kwd"] = scopeKwd
+ }
+ if len(docs) > 0 {
+ condition["doc_id"] = docs
+ }
+ res, err := a.docEngine.Search(ctx, &enginetypes.SearchRequest{
+ IndexNames: []string{kgIndexName(tenantID)},
+ KbIDs: []string{kbID},
+ SelectFields: []string{"id"},
+ Filter: condition,
+ Limit: 1,
+ IncludeUnavailable: true,
+ })
+ if err != nil {
+ return false, err
+ }
+ return res != nil && len(res.Chunks) > 0, nil
+}
+
+// kgSearchRaw is the low-level KG row search over one dataset.
+func (a *KgAdapter) kgSearchRaw(ctx context.Context, tenantID, kbID string, docs []string, kind, scopeKwd string, extra map[string]interface{}, matchExprs []interface{}, orderDesc string, limit int) []map[string]interface{} {
+ condition := map[string]interface{}{"knowledge_graph_kwd": kind}
+ if scopeKwd != "" {
+ condition["scope_kwd"] = scopeKwd
+ }
+ if len(docs) > 0 {
+ condition["doc_id"] = docs
+ }
+ for key, value := range extra {
+ condition[key] = value
+ }
+ req := &enginetypes.SearchRequest{
+ IndexNames: []string{kgIndexName(tenantID)},
+ KbIDs: []string{kbID},
+ SelectFields: []string{
+ "id", "content_with_weight", "source_chunk_ids", "doc_id", "docnm_kwd",
+ "name_kwd", "mention_count_int", "from_entity_kwd", "to_entity_kwd",
+ },
+ Filter: condition,
+ Limit: limit,
+ // KG rows are compiled products: an available_int=1 default would hide
+ // every one of them on an engine with equality semantics.
+ IncludeUnavailable: true,
+ MatchExprs: matchExprs,
+ }
+ if orderDesc != "" {
+ req.OrderBy = &enginetypes.OrderByExpr{}
+ req.OrderBy.Desc(orderDesc)
+ }
+ res, err := a.docEngine.Search(ctx, req)
+ if err != nil {
+ return nil
+ }
+ return res.Chunks
+}
+
+// kgSearch searches the KG rows of one dataset with a text match expression.
+func (a *KgAdapter) kgSearch(ctx context.Context, tenantID, kbID string, docs []string, kind, text string, topN int, scopeKwd string, extra map[string]interface{}, orderDesc string, pool int) []map[string]interface{} {
+ var matchExprs []interface{}
+ if text != "" {
+ candidates := topN
+ if pool > candidates {
+ candidates = pool
+ }
+ matchExprs = []interface{}{&enginetypes.MatchTextExpr{
+ Fields: []string{"content_ltks", "content_sm_ltks"},
+ MatchingText: text,
+ TopN: candidates,
+ }}
+ }
+ return a.kgSearchRaw(ctx, tenantID, kbID, docs, kind, scopeKwd, extra, matchExprs, orderDesc, topN)
+}
+
+// evidencePassages loads the source chunks behind the subgraph, in first-seen
+// doc order, capped at kgMaxPassages.
+func (a *KgAdapter) evidencePassages(ctx context.Context, tenantID string, datasetIDs []string, entities []KgEntity, relations []KgRelation) []KgPassage {
+ type evidence struct {
+ docID string
+ ids []string
+ }
+ var groups []evidence
+ index := map[string]int{}
+ seen := map[string]bool{}
+ add := func(docID string, ids []string) {
+ for _, chunkID := range ids {
+ if chunkID == "" {
+ continue
+ }
+ key := docID + "|" + chunkID
+ if seen[key] {
+ continue
+ }
+ seen[key] = true
+ i, ok := index[docID]
+ if !ok {
+ i = len(groups)
+ index[docID] = i
+ groups = append(groups, evidence{docID: docID})
+ }
+ groups[i].ids = append(groups[i].ids, chunkID)
+ }
+ }
+ for _, e := range entities {
+ add(e.DocID, e.SourceChunkIDs)
+ }
+ for _, r := range relations {
+ add(r.DocID, r.SourceChunkIDs)
+ }
+
+ out := make([]KgPassage, 0, kgMaxPassages)
+ for _, group := range groups {
+ if len(out) >= kgMaxPassages {
+ break
+ }
+ remaining := kgMaxPassages - len(out)
+ for _, p := range a.loadPassages(ctx, tenantID, datasetIDs, group.ids, remaining) {
+ out = append(out, p)
+ }
+ }
+ return out
+}
+
+// loadPassages reads the given chunk ids back from the tenant index.
+func (a *KgAdapter) loadPassages(ctx context.Context, tenantID string, datasetIDs, chunkIDs []string, limit int) []KgPassage {
+ chunkIDs = nonEmptyStrings(chunkIDs)
+ if len(chunkIDs) == 0 || limit <= 0 {
+ return nil
+ }
+ if len(chunkIDs) > limit {
+ chunkIDs = chunkIDs[:limit]
+ }
+ res, err := a.docEngine.Search(ctx, &enginetypes.SearchRequest{
+ IndexNames: []string{kgIndexName(tenantID)},
+ KbIDs: datasetIDs,
+ Filter: map[string]interface{}{"id": chunkIDs},
+ SelectFields: []string{"content_with_weight", "doc_id", "docnm_kwd", "kb_id"},
+ Limit: len(chunkIDs),
+ })
+ if err != nil || res == nil {
+ return nil
+ }
+ out := make([]KgPassage, 0, len(res.Chunks))
+ for _, row := range res.Chunks {
+ content := kgStr(row["content_with_weight"])
+ if strings.TrimSpace(content) == "" {
+ continue
+ }
+ out = append(out, KgPassage{
+ ChunkID: kgStr(row["id"]),
+ DocID: kgStr(row["doc_id"]),
+ DocName: kgStr(row["docnm_kwd"]),
+ DatasetID: kgStr(row["kb_id"]),
+ Content: truncateRunes(content, kgPassageRunes),
+ })
+ }
+ return out
+}
+
+// kgIndexName is the chunk index of a tenant.
+func kgIndexName(tenantID string) string {
+ return "ragflow_" + tenantID
+}
+
+// kgTopMentionCount re-ranks rows by mention_count desc and returns the top N.
+func kgTopMentionCount(rows []map[string]interface{}, topN int) []map[string]interface{} {
+ sort.SliceStable(rows, func(i, j int) bool {
+ return kgMentionCount(rows[i]) > kgMentionCount(rows[j])
+ })
+ if len(rows) > topN {
+ rows = rows[:topN]
+ }
+ return rows
+}
+
+func kgMentionCount(row map[string]interface{}) int {
+ switch v := row["mention_count_int"].(type) {
+ case int:
+ return v
+ case int64:
+ return int(v)
+ case float64:
+ return int(v)
+ case float32:
+ return int(v)
+ }
+ return 0
+}
+
+// kgParseEntity projects an entity row into a KgEntity. Rows without a usable
+// name are dropped rather than rendered as an anonymous node.
+func kgParseEntity(row map[string]interface{}) (KgEntity, bool) {
+ payload := map[string]interface{}{}
+ if s := kgStr(row["content_with_weight"]); s != "" {
+ _ = json.Unmarshal([]byte(s), &payload)
+ }
+ name := ""
+ for _, key := range []string{"name", "term", "title"} {
+ if v := kgStr(payload[key]); v != "" {
+ name = v
+ break
+ }
+ }
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return KgEntity{}, false
+ }
+ e := KgEntity{
+ Name: name,
+ Type: kgStrOr(payload["type"], "other"),
+ Description: kgStrOr(payload["description"], ""),
+ SourceChunkIDs: kgStrSlice(row["source_chunk_ids"]),
+ DocID: kgStr(row["doc_id"]),
+ }
+ if aliases, ok := payload["aliases"].([]interface{}); ok {
+ for _, alias := range aliases {
+ if s := strings.TrimSpace(kgStr(alias)); s != "" {
+ e.Aliases = append(e.Aliases, s)
+ }
+ }
+ }
+ return e, true
+}
+
+// kgParseRelation projects a relation row into a KgRelation. A row with an
+// incomplete endpoint pair is dropped: an edge "A ->" carries no fact.
+func kgParseRelation(row map[string]interface{}) (KgRelation, bool) {
+ from := strings.TrimSpace(kgStr(row["from_entity_kwd"]))
+ to := strings.TrimSpace(kgStr(row["to_entity_kwd"]))
+ if from == "" || to == "" {
+ return KgRelation{}, false
+ }
+ typ := "related"
+ if payload := kgStr(row["content_with_weight"]); payload != "" {
+ var p map[string]interface{}
+ if json.Unmarshal([]byte(payload), &p) == nil {
+ if t := kgStr(p["type"]); t != "" {
+ typ = t
+ } else if t := kgStr(p["relation"]); t != "" {
+ typ = t
+ }
+ }
+ }
+ return KgRelation{
+ ID: kgStr(row["id"]),
+ From: from,
+ To: to,
+ Type: typ,
+ SourceChunkIDs: kgStrSlice(row["source_chunk_ids"]),
+ DocID: kgStr(row["doc_id"]),
+ }, true
+}
+
+// kgEndpointTerms returns the original and lowercased forms of every name, so a
+// hop query matches both compacted (lowercased) and per-document endpoint
+// fields.
+func kgEndpointTerms(names []string) []string {
+ set := map[string]bool{}
+ for _, name := range names {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ continue
+ }
+ set[name] = true
+ set[strings.ToLower(name)] = true
+ }
+ out := make([]string, 0, len(set))
+ for name := range set {
+ out = append(out, name)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func kgStr(v interface{}) string {
+ if s, ok := v.(string); ok {
+ return s
+ }
+ return ""
+}
+
+func kgStrOr(v interface{}, fallback string) string {
+ if s, ok := v.(string); ok && s != "" {
+ return s
+ }
+ return fallback
+}
+
+func kgStrSlice(v interface{}) []string {
+ switch x := v.(type) {
+ case []string:
+ return x
+ case []interface{}:
+ out := make([]string, 0, len(x))
+ for _, item := range x {
+ if s, ok := item.(string); ok && s != "" {
+ out = append(out, s)
+ }
+ }
+ return out
+ }
+ return nil
+}
diff --git a/internal/agentic_rag/nav_tool_enablement.go b/internal/agentic_rag/nav_tool_enablement.go
new file mode 100644
index 0000000000..4051a3b5b8
--- /dev/null
+++ b/internal/agentic_rag/nav_tool_enablement.go
@@ -0,0 +1,156 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+ "sync"
+ "time"
+)
+
+// conversationKey carries the per-conversation identifier through the request
+// context so the compiled-knowledge tools (navigate_tree / navigate_structure /
+// graph_explore) can record, and later honor, a per-conversation availability
+// decision without changing their constructors or the tool registry. The caller
+// (the chat pipeline) sets it from the conversation id; when it is absent Run
+// assigns a unique per-run key so availability still holds within a single ReAct
+// turn.
+type conversationKeyT struct{}
+
+// WithConversationKey returns a copy of ctx carrying the conversation id. An empty
+// key is a no-op (a stable identity is what makes the availability tracking
+// meaningful).
+func WithConversationKey(ctx context.Context, key string) context.Context {
+ if key == "" {
+ return ctx
+ }
+ return context.WithValue(ctx, conversationKeyT{}, key)
+}
+
+// conversationKeyFrom returns the conversation id carried by ctx, or "".
+func conversationKeyFrom(ctx context.Context) string {
+ if k, ok := ctx.Value(conversationKeyT{}).(string); ok {
+ return k
+ }
+ return ""
+}
+
+// navAvailabilityStore records, per conversation, which compiled-knowledge tools
+// have been PROVEN unavailable for the bound datasets, so the agent stops
+// spending calls on them until the mark expires. Every tool starts out enabled;
+// a tool leaves that set only on evidence.
+//
+// A tool is marked unavailable only on a DATASET-LEVEL absence - navigate_tree
+// reporting "no compiled navigation tree" and graph_explore "no compiled
+// knowledge graph" - which is a fact that does not change within a conversation.
+// A query-level miss (the structure exists, but THIS query reached nothing) is
+// NOT a trigger: a better-phrased query may still hit. navigate_structure is
+// never marked: its "no structure" verdict is per DOCUMENT, so skipping one
+// document must not remove the tool for the others.
+//
+// The mark lives until the TTL expires, not for the whole conversation: after it
+// lapses the tool is offered again and re-detects with one cheap backend read.
+// The store is process-local and best-effort - a process restart has the same
+// effect as an expiry, and neither is a correctness regression.
+type navAvailabilityStore struct {
+ mu sync.Mutex
+ unavail map[string]map[string]time.Time // convKey -> tool -> unavailable-until
+ ttl time.Duration
+}
+
+var navAvailability = &navAvailabilityStore{
+ unavail: map[string]map[string]time.Time{},
+ ttl: 30 * time.Minute,
+}
+
+// markNavToolUnavailable records tool as unavailable for the conversation carried
+// by ctx. A missing/empty conversation key or tool is a no-op.
+func markNavToolUnavailable(ctx context.Context, tool string) {
+ key := conversationKeyFrom(ctx)
+ if key == "" || tool == "" {
+ return
+ }
+ navAvailability.mu.Lock()
+ defer navAvailability.mu.Unlock()
+ if navAvailability.unavail[key] == nil {
+ navAvailability.unavail[key] = map[string]time.Time{}
+ }
+ navAvailability.unavail[key][tool] = time.Now().Add(navAvailability.ttl)
+}
+
+// navToolEnabled reports whether tool is still usable for the conversation
+// carried by ctx: true unless it was marked unavailable and that mark has not yet
+// expired. A missing/empty conversation key leaves every tool enabled.
+func navToolEnabled(ctx context.Context, tool string) bool {
+ key := conversationKeyFrom(ctx)
+ if key == "" || tool == "" {
+ return true
+ }
+ navAvailability.mu.Lock()
+ defer navAvailability.mu.Unlock()
+ until, ok := navAvailability.unavail[key][tool]
+ if !ok {
+ return true
+ }
+ if time.Now().After(until) {
+ delete(navAvailability.unavail[key], tool)
+ return true
+ }
+ return false
+}
+
+// forgetConversation drops every availability mark recorded for a conversation
+// key. Run uses it to release the per-run key it generated for a keyless run, so
+// the process-wide map does not accumulate one dead entry per such run.
+func forgetConversation(key string) {
+ if key == "" {
+ return
+ }
+ navAvailability.mu.Lock()
+ defer navAvailability.mu.Unlock()
+ delete(navAvailability.unavail, key)
+}
+
+// navUnavailableToolSet returns the set of compiled-knowledge tools proven
+// unavailable for the conversation carried by ctx (honoring the TTL). It is used
+// to drop those tools from the agent's tool list so the model cannot keep calling
+// them.
+func navUnavailableToolSet(ctx context.Context) map[string]bool {
+ key := conversationKeyFrom(ctx)
+ if key == "" {
+ return nil
+ }
+ navAvailability.mu.Lock()
+ defer navAvailability.mu.Unlock()
+ raw, ok := navAvailability.unavail[key]
+ if !ok {
+ return nil
+ }
+ now := time.Now()
+ out := make(map[string]bool, len(raw))
+ for tool, until := range raw {
+ if now.After(until) {
+ delete(navAvailability.unavail[key], tool)
+ continue
+ }
+ out[tool] = true
+ }
+ if len(out) == 0 {
+ delete(navAvailability.unavail, key)
+ }
+ return out
+}
diff --git a/internal/agentic_rag/nav_tool_enablement_test.go b/internal/agentic_rag/nav_tool_enablement_test.go
new file mode 100644
index 0000000000..6177b8762d
--- /dev/null
+++ b/internal/agentic_rag/nav_tool_enablement_test.go
@@ -0,0 +1,66 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+ "testing"
+)
+
+// TestNavToolAvailabilityScopedToConversation proves the core invariant: a
+// dataset-level absence is recorded per conversation and only blocks the single
+// tool that reported it, never spilling into other conversations or other tools.
+func TestNavToolAvailabilityScopedToConversation(t *testing.T) {
+ ctxA := WithConversationKey(context.Background(), "convA")
+ ctxB := WithConversationKey(context.Background(), "convB")
+ ctxNone := context.Background()
+
+ if !navToolEnabled(ctxNone, navigateTreeToolName) {
+ t.Fatal("empty conversation key must leave every tool enabled")
+ }
+
+ markNavToolUnavailable(ctxA, navigateTreeToolName)
+
+ if navToolEnabled(ctxA, navigateTreeToolName) {
+ t.Fatal("expected navigate_tree unavailable for convA")
+ }
+ if !navToolEnabled(ctxB, navigateTreeToolName) {
+ t.Fatal("convB must not be affected by convA's mark")
+ }
+ if !navToolEnabled(ctxA, navigateStructureToolName) {
+ t.Fatal("only navigate_tree was marked, not navigate_structure")
+ }
+ if !navToolEnabled(ctxA, graphExploreToolName) {
+ t.Fatal("only navigate_tree was marked, not graph_explore")
+ }
+
+ set := navUnavailableToolSet(ctxA)
+ if !set[navigateTreeToolName] {
+ t.Fatal("navUnavailableToolSet must contain the marked tool")
+ }
+ if set[navigateStructureToolName] {
+ t.Fatal("navUnavailableToolSet must not contain tools that are still available")
+ }
+}
+
+// TestNavUnavailableToolSetEmpty covers the no-op branch used by Run's tool-list
+// filter when a conversation has nothing marked unavailable yet.
+func TestNavUnavailableToolSetEmpty(t *testing.T) {
+ if s := navUnavailableToolSet(context.Background()); s != nil {
+ t.Fatalf("expected nil set for an empty conversation, got %v", s)
+ }
+}
diff --git a/internal/agentic_rag/tool_graph_explore.go b/internal/agentic_rag/tool_graph_explore.go
new file mode 100644
index 0000000000..a298b00032
--- /dev/null
+++ b/internal/agentic_rag/tool_graph_explore.go
@@ -0,0 +1,218 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ einotool "github.com/cloudwego/eino/components/tool"
+ "github.com/cloudwego/eino/schema"
+ "github.com/eino-contrib/jsonschema"
+
+ "ragflow/internal/common"
+)
+
+// graphExploreToolName is the tool the model calls to walk the compiled
+// knowledge graph.
+const graphExploreToolName = "graph_explore"
+
+const graphExploreToolDescription = `Explore the COMPILED KNOWLEDGE GRAPH of the bound datasets: it seeds the entities most relevant to your query, hops along their RELATIONS, and returns the subgraph (entities + relations) plus the source passages behind the relevant nodes.
+USE IT for RELATIONAL and MULTI-HOP questions - "who is connected to X", "which person/place/thing links A to B", "what does A have to do with B" - where the answer depends on an EDGE between entities rather than on one passage. It complements the text tools: the text tools prove what a document SAYS, the graph walk proves what the corpus CONNECTS.
+Returns an XML <kg_explore> document: a <subgraph> element whose <entity name type/> and <relation from to type/> children are the walk result, then one <passage chunk_id doc_id doc_name ref> element per source chunk, each with a <content> body. The ref attribute is the [ID:n] handle to cite; cite only passages you actually read here or with list_chunks.
+An empty result (<note> with no subgraph) means this query seeded no graph entity. Read the note's error attribute: error="no compiled knowledge graph" is a DATASET-level absence (do not retry this tool; go back to grep_chunks / search_bm25_chunks / search_semantic_chunks), while a note WITHOUT that attribute is a QUERY-level miss - rephrase with the corpus's own entity names and try again.`
+
+// graphExploreArgs is the JSON the model sends into InvokableRun.
+type graphExploreArgs struct {
+ Query string `json:"query"`
+ DatasetIDs []string `json:"dataset_ids,omitempty"`
+ DocScope []string `json:"doc_scope,omitempty"`
+}
+
+// Rendering caps: a walk can surface hundreds of nodes and the model reads a
+// bounded payload, not the whole graph.
+const (
+ graphExploreMaxEntities = 40
+ graphExploreMaxRelations = 60
+ graphExploreMaxPassages = 6
+)
+
+// GraphExploreTool walks the compiled knowledge graph via KgService. It is
+// stateless: the tenant and dataset scope are injected at construction from the
+// session.
+type GraphExploreTool struct {
+ tenantID string
+ datasetIDs []string
+}
+
+// NewGraphExploreTool returns a GraphExploreTool scoped to the given tenant and
+// datasets, implementing eino's runtime.InvokableTool.
+func NewGraphExploreTool(tenantID string, datasetIDs []string) *GraphExploreTool {
+ return &GraphExploreTool{tenantID: tenantID, datasetIDs: datasetIDs}
+}
+
+// Info returns the tool's metadata for the chat model.
+func (g *GraphExploreTool) Info(_ context.Context) (*schema.ToolInfo, error) {
+ schemaJSON := `{
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "REQUIRED: the relational question to walk the graph for, phrased as entities plus the relation between them (e.g. \\\"which organization connects Marie Curie to the Radium Institute\\\"). Use the question's own proper nouns."
+ },
+ "dataset_ids": {
+ "type": "array",
+ "description": "Optional dataset ids to restrict the walk to (at most 10). When omitted, the current conversation's bound datasets are used.",
+ "items": { "type": "string" },
+ "maxItems": 10
+ },
+ "doc_scope": {
+ "type": "array",
+ "description": "Optional document ids to restrict the walk to (at most 10).",
+ "items": { "type": "string" },
+ "maxItems": 10
+ }
+ },
+ "required": ["query"]
+}`
+ s := &jsonschema.Schema{}
+ if err := json.Unmarshal([]byte(schemaJSON), s); err != nil {
+ return nil, fmt.Errorf("graph_explore: parse schema: %w", err)
+ }
+ return &schema.ToolInfo{
+ Name: graphExploreToolName,
+ Desc: graphExploreToolDescription,
+ ParamsOneOf: schema.NewParamsOneOfByJSONSchema(s),
+ }, nil
+}
+
+// InvokableRun walks the graph and returns the XML <kg_explore> document.
+func (g *GraphExploreTool) InvokableRun(ctx context.Context, argumentsInJSON string, _ ...einotool.Option) (string, error) {
+ return guardedToolRun(ctx, graphExploreToolName, g.invokableRun, argumentsInJSON)
+}
+
+func (g *GraphExploreTool) invokableRun(ctx context.Context, argumentsInJSON string) (string, error) {
+ var args graphExploreArgs
+ if err := json.Unmarshal([]byte(argumentsInJSON), &args); err != nil {
+ return "", fmt.Errorf("graph_explore: parse arguments: %w", err)
+ }
+ query := strings.TrimSpace(args.Query)
+ if query == "" {
+ return "", fmt.Errorf("graph_explore: query is required and must be a non-empty string")
+ }
+ if !navToolEnabled(ctx, graphExploreToolName) {
+ // Marked unavailable for this conversation (bound datasets have no
+ // compiled knowledge graph): skip the backend and return the same
+ // "no graph" note the caller falls back from.
+ common.DebugCtx(ctx, "graph_explore: marked unavailable; skipping backend (no compiled knowledge graph)")
+ return renderKgExplore(ctx, query, KgExploreResult{GraphAbsent: true}), nil
+ }
+ datasetIDs, err := resolveDatasetScope(g.datasetIDs, args.DatasetIDs)
+ if err != nil {
+ return "", fmt.Errorf("graph_explore: %w", err)
+ }
+ if len(datasetIDs) == 0 {
+ // Bound scope is empty: short-circuit before touching the backend so the
+ // tool never reads outside the conversation's allowed datasets.
+ return renderKgExplore(ctx, query, KgExploreResult{GraphAbsent: true}), nil
+ }
+
+ result, err := GetKgService().Explore(ctx, KgExploreRequest{
+ TenantID: g.tenantID,
+ DatasetIDs: datasetIDs,
+ DocScope: args.DocScope,
+ Query: query,
+ })
+ if err != nil {
+ return "", fmt.Errorf("graph_explore: %w", err)
+ }
+ if result.GraphAbsent {
+ // A DATASET-level absence (the scope holds no compiled entity rows at
+ // all): disable the tool so the agent stops spending calls on it and
+ // falls back to the text tools. An empty walk WITHOUT this flag is a
+ // query-level miss (or a walk that found nothing) - rephrasing may
+ // still hit, so it must not disable anything.
+ markNavToolUnavailable(ctx, graphExploreToolName)
+ common.DebugCtx(ctx, "graph_explore: marking unavailable for conversation (no compiled knowledge graph)")
+ }
+ return renderKgExplore(ctx, query, result), nil
+}
+
+// renderKgExplore serialises one walk result. Passages carry the same `ref`
+// handles the locate/deep-read tools stamp, so a fact read from the graph is
+// citable exactly like one read from a chunk.
+func renderKgExplore(ctx context.Context, query string, result KgExploreResult) string {
+ entities := result.Entities
+ if len(entities) > graphExploreMaxEntities {
+ entities = entities[:graphExploreMaxEntities]
+ }
+ relations := result.Relations
+ if len(relations) > graphExploreMaxRelations {
+ relations = relations[:graphExploreMaxRelations]
+ }
+ passages := result.Passages
+ if len(passages) > graphExploreMaxPassages {
+ passages = passages[:graphExploreMaxPassages]
+ }
+
+ var b strings.Builder
+ b.WriteString(fmt.Sprintf(
+ "<kg_explore query=\"%s\" entities=\"%d\" relations=\"%d\" passages=\"%d\">\n",
+ xmlEscape(query), len(entities), len(relations), len(passages)))
+
+ if len(entities) == 0 && len(relations) == 0 {
+ if result.GraphAbsent {
+ b.WriteString("<note error=\"no compiled knowledge graph\">This dataset has NO compiled knowledge graph (or none in the given scope). graph_explore is unavailable here - do not retry it; use grep_chunks / search_bm25_chunks / search_semantic_chunks / list_chunks instead.</note>\n")
+ } else {
+ b.WriteString("<note>No compiled-graph entity matched THIS query. The graph may exist - rephrase with the question's own proper nouns (entities, not verbs), or go back to grep_chunks / search_bm25_chunks / search_semantic_chunks.</note>\n")
+ }
+ b.WriteString("</kg_explore>")
+ return b.String()
+ }
+
+ b.WriteString("<subgraph>\n")
+ for _, e := range entities {
+ b.WriteString(fmt.Sprintf("<entity name=\"%s\" type=\"%s\"", xmlEscape(e.Name), xmlEscape(e.Type)))
+ if e.Description != "" {
+ b.WriteString(fmt.Sprintf(" description=\"%s\"", xmlEscape(truncateRunes(e.Description, 300))))
+ }
+ b.WriteString("/>\n")
+ }
+ for _, r := range relations {
+ b.WriteString(fmt.Sprintf("<relation from=\"%s\" to=\"%s\" type=\"%s\"/>\n",
+ xmlEscape(r.From), xmlEscape(r.To), xmlEscape(r.Type)))
+ }
+ b.WriteString("</subgraph>\n")
+
+ // Passages are stamped on serve so a citation names a handle the model saw.
+ reg := evidenceRegistryFrom(ctx)
+ for _, p := range passages {
+ b.WriteString(fmt.Sprintf(
+ "<passage chunk_id=\"%s\" doc_id=\"%s\" doc_name=\"%s\" dataset_id=\"%s\"%s>\n",
+ xmlEscape(p.ChunkID), xmlEscape(p.DocID), xmlEscape(p.DocName), xmlEscape(p.DatasetID),
+ refAttrOf(reg, p.ChunkID)))
+ b.WriteString(fmt.Sprintf("<content>%s</content>\n", xmlEscape(p.Content)))
+ b.WriteString("</passage>\n")
+ }
+ if len(passages) == 0 {
+ b.WriteString("<note>The subgraph has no source passages in scope. Treat the nodes and edges above as a map of what the corpus connects, and read the documents the nodes name with grep_chunks / list_chunks before answering.</note>\n")
+ }
+ b.WriteString("</kg_explore>")
+ return b.String()
+}
diff --git a/internal/agentic_rag/tool_graph_explore_test.go b/internal/agentic_rag/tool_graph_explore_test.go
new file mode 100644
index 0000000000..a2e920421a
--- /dev/null
+++ b/internal/agentic_rag/tool_graph_explore_test.go
@@ -0,0 +1,375 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+
+ "ragflow/internal/engine"
+ enginetypes "ragflow/internal/engine/types"
+)
+
+// fakeKgService records the request and returns a canned walk result.
+type fakeKgService struct {
+ gotReq KgExploreRequest
+ result KgExploreResult
+ err error
+}
+
+func (f *fakeKgService) Explore(_ context.Context, req KgExploreRequest) (KgExploreResult, error) {
+ f.gotReq = req
+ return f.result, f.err
+}
+
+func installFakeKgService(t *testing.T, svc KgService) {
+ t.Helper()
+ previous := GetKgService()
+ SetKgService(svc)
+ t.Cleanup(func() { SetKgService(previous) })
+}
+
+func kgExploreContext(t *testing.T) context.Context {
+ t.Helper()
+ return WithEvidenceRegistry(context.Background(), NewEvidenceRegistry())
+}
+
+// TestGraphExploreToolRendersSubgraphAndPassages pins the payload contract: the
+// subgraph (entities + relations) plus source passages, with each passage
+// carrying the [ID:n] handle the answer cites.
+func TestGraphExploreToolRendersSubgraphAndPassages(t *testing.T) {
+ fake := &fakeKgService{result: KgExploreResult{
+ Entities: []KgEntity{
+ {Name: "Marie Curie", Type: "person", Description: "physicist"},
+ {Name: "Radium Institute", Type: "org"},
+ },
+ Relations: []KgRelation{{From: "Marie Curie", To: "Radium Institute", Type: "part_of"}},
+ Passages: []KgPassage{
+ {ChunkID: "c1", DocID: "d1", DocName: "Curie.md", DatasetID: "kb1", Content: "Curie founded the institute."},
+ },
+ }}
+ installFakeKgService(t, fake)
+
+ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(kgExploreContext(t), `{"query":"what connects Curie to the Radium Institute"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ for _, want := range []string{
+ `<entity name="Marie Curie" type="person"`,
+ `<relation from="Marie Curie" to="Radium Institute" type="part_of"/>`,
+ `<passage chunk_id="c1" doc_id="d1" doc_name="Curie.md" dataset_id="kb1" ref="0">`,
+ `<content>Curie founded the institute.</content>`,
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("output must contain %q, got:\n%s", want, out)
+ }
+ }
+ if fake.gotReq.TenantID != "tenant-1" || len(fake.gotReq.DatasetIDs) != 1 || fake.gotReq.DatasetIDs[0] != "kb1" {
+ t.Errorf("walk scope = %+v, want tenant-1 / [kb1]", fake.gotReq)
+ }
+ if fake.gotReq.Query != "what connects Curie to the Radium Institute" {
+ t.Errorf("walk query = %q", fake.gotReq.Query)
+ }
+}
+
+// TestGraphExploreToolWithoutBindingsDoesNotCallTheWalk: an empty bound scope
+// must short-circuit - the tool never reads outside the conversation's scope.
+func TestGraphExploreToolWithoutBindingsDoesNotCallTheWalk(t *testing.T) {
+ fake := &fakeKgService{}
+ installFakeKgService(t, fake)
+
+ tool := NewGraphExploreTool("tenant-1", nil)
+ out, err := tool.InvokableRun(kgExploreContext(t), `{"query":"anything"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, "<note") {
+ t.Errorf("empty scope must render the unavailable note, got:\n%s", out)
+ }
+ if fake.gotReq.Query != "" {
+ t.Errorf("the walk must not run with no bound dataset, got %+v", fake.gotReq)
+ }
+}
+
+// TestGraphExploreToolRejectsOutOfScopeDataset: a model-supplied dataset id must
+// stay inside the conversation's bound scope. The failure becomes a
+// model-readable <tool_error>, not a Go error that would abort the ReAct loop.
+func TestGraphExploreToolRejectsOutOfScopeDataset(t *testing.T) {
+ installFakeKgService(t, &fakeKgService{})
+
+ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(kgExploreContext(t), `{"query":"q","dataset_ids":["kb2"]}`)
+ if err != nil {
+ t.Fatalf("out-of-scope dataset must not abort the loop: %v", err)
+ }
+ if !strings.Contains(out, toolErrorMarker) {
+ t.Errorf("expected a <tool_error> result, got:\n%s", out)
+ }
+}
+
+// TestGraphExploreToolNoCompiledGraphDisables: a DATASET-level absence
+// (GraphAbsent) is a dead end the model must read, and it disables the tool for
+// the conversation so later rounds stop spending calls on it.
+func TestGraphExploreToolNoCompiledGraphDisables(t *testing.T) {
+ installFakeKgService(t, &fakeKgService{result: KgExploreResult{GraphAbsent: true}})
+
+ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})
+ ctx := WithConversationKey(kgExploreContext(t), "test-graph-absent")
+ out, err := tool.InvokableRun(ctx, `{"query":"q"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if strings.Contains(out, "<subgraph>") {
+ t.Errorf("an empty walk must not render a subgraph, got:\n%s", out)
+ }
+ if !strings.Contains(out, `error="no compiled knowledge graph"`) {
+ t.Errorf("dataset-level absence must be marked in the note, got:\n%s", out)
+ }
+ if navToolEnabled(ctx, graphExploreToolName) {
+ t.Error("a proven dataset-level absence must disable graph_explore for the conversation")
+ }
+}
+
+// TestGraphExploreToolQueryMissDoesNotDisable: an empty walk WITHOUT the
+// dataset-level marker is a query-level miss - a better-phrased query may still
+// hit, so it must not disable the tool and must tell the model to rephrase.
+func TestGraphExploreToolQueryMissDoesNotDisable(t *testing.T) {
+ installFakeKgService(t, &fakeKgService{result: KgExploreResult{}})
+
+ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})
+ ctx := WithConversationKey(kgExploreContext(t), "test-graph-query-miss")
+ out, err := tool.InvokableRun(ctx, `{"query":"q"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if strings.Contains(out, `error="no compiled knowledge graph"`) {
+ t.Errorf("a query miss must not claim the dataset has no graph, got:\n%s", out)
+ }
+ if !strings.Contains(out, "matched THIS query") {
+ t.Errorf("a query miss must tell the model to rephrase, got:\n%s", out)
+ }
+ if !navToolEnabled(ctx, graphExploreToolName) {
+ t.Error("a query-level miss must NOT disable graph_explore")
+ }
+}
+
+// TestGraphExploreToolRequiresQuery pins the argument contract.
+func TestGraphExploreToolRequiresQuery(t *testing.T) {
+ installFakeKgService(t, &fakeKgService{})
+
+ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(kgExploreContext(t), `{"query":" "}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, toolErrorMarker) {
+ t.Errorf("missing query must produce a <tool_error>, got:\n%s", out)
+ }
+}
+
+// TestGraphExploreToolPropagatesWalkFailure: an infrastructure failure surfaces
+// as a tool error (the loop continues) rather than a silent empty graph.
+func TestGraphExploreToolPropagatesWalkFailure(t *testing.T) {
+ installFakeKgService(t, &fakeKgService{err: errors.New("engine down")})
+
+ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(kgExploreContext(t), `{"query":"q"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, toolErrorMarker) || !strings.Contains(out, "engine down") {
+ t.Errorf("walk failure must surface as a tool error, got:\n%s", out)
+ }
+}
+
+// TestGraphExploreToolIsRegisteredAndBuildableByTemplate pins the wiring a
+// template needs: the name must be in the registry, and toolsFor must turn it
+// into the graph tool with the session scope injected.
+func TestGraphExploreToolIsRegisteredAndBuildableByTemplate(t *testing.T) {
+ if _, ok := toolRegistry()[graphExploreToolName]; !ok {
+ t.Fatalf("%s must be registered so a template can select it", graphExploreToolName)
+ }
+ tools := toolsFor(context.Background(), Template{ID: "kg", Tools: []string{graphExploreToolName}}, "tenant-1", []string{"kb1"}, nil)
+ if len(tools) != 1 {
+ t.Fatalf("toolsFor returned %d tools, want 1", len(tools))
+ }
+ tool, ok := tools[0].(*GraphExploreTool)
+ if !ok {
+ t.Fatalf("toolsFor built %T, want *GraphExploreTool", tools[0])
+ }
+ info, err := tool.Info(context.Background())
+ if err != nil || info.Name != graphExploreToolName {
+ t.Fatalf("tool info = %+v err=%v", info, err)
+ }
+ if tool.tenantID != "tenant-1" || len(tool.datasetIDs) != 1 || tool.datasetIDs[0] != "kb1" {
+ t.Errorf("scope = %q/%v, want tenant-1/[kb1]", tool.tenantID, tool.datasetIDs)
+ }
+}
+
+func TestKgParseEntityReadsPayloadAndRowFields(t *testing.T) {
+ row := map[string]interface{}{
+ "content_with_weight": `{"name":"吕布","type":"person","description":"武将","aliases":["吕奉先"]}`,
+ "source_chunk_ids": []interface{}{"c1", "c2"},
+ "doc_id": "d1",
+ }
+ e, ok := kgParseEntity(row)
+ if !ok {
+ t.Fatal("entity row must parse")
+ }
+ if e.Name != "吕布" || e.Type != "person" || e.Description != "武将" || e.DocID != "d1" {
+ t.Errorf("entity = %+v", e)
+ }
+ if len(e.Aliases) != 1 || e.Aliases[0] != "吕奉先" {
+ t.Errorf("aliases = %v", e.Aliases)
+ }
+ if len(e.SourceChunkIDs) != 2 {
+ t.Errorf("source chunks = %v", e.SourceChunkIDs)
+ }
+ if _, ok := kgParseEntity(map[string]interface{}{"content_with_weight": "{}"}); ok {
+ t.Error("a nameless row must be dropped")
+ }
+}
+
+func TestKgParseRelationRequiresBothEndpoints(t *testing.T) {
+ row := map[string]interface{}{
+ "id": "r1",
+ "from_entity_kwd": "A",
+ "to_entity_kwd": "B",
+ "content_with_weight": `{"type":"owns"}`,
+ "source_chunk_ids": []string{"c9"},
+ "doc_id": "d2",
+ }
+ r, ok := kgParseRelation(row)
+ if !ok || r.From != "A" || r.To != "B" || r.Type != "owns" || r.ID != "r1" || r.DocID != "d2" {
+ t.Fatalf("relation = %+v ok=%v", r, ok)
+ }
+ if _, ok := kgParseRelation(map[string]interface{}{"from_entity_kwd": "A"}); ok {
+ t.Error("a half-open edge must be dropped")
+ }
+}
+
+func TestKgEndpointTermsKeepsOriginalAndLowercase(t *testing.T) {
+ got := kgEndpointTerms([]string{" Marie Curie ", "marie curie", ""})
+ want := map[string]bool{"Marie Curie": true, "marie curie": true}
+ if len(got) != len(want) {
+ t.Fatalf("terms = %v, want one original + one lowercase form", got)
+ }
+ for _, term := range got {
+ if !want[term] {
+ t.Errorf("unexpected term %q", term)
+ }
+ }
+}
+
+func TestKgTopMentionCountRanksAndCaps(t *testing.T) {
+ rows := []map[string]interface{}{
+ {"name_kwd": "low", "mention_count_int": 1},
+ {"name_kwd": "high", "mention_count_int": 9},
+ {"name_kwd": "mid", "mention_count_int": 4},
+ }
+ got := kgTopMentionCount(rows, 2)
+ if len(got) != 2 || got[0]["name_kwd"] != "high" || got[1]["name_kwd"] != "mid" {
+ t.Fatalf("ranked rows = %v, want high, mid", got)
+ }
+}
+
+// kgProbeFakeEngine answers the existence probe (a single "id" select field with
+// no match expression) from entityRows, and returns nothing for the walk's seed
+// / hop searches - which is exactly the "graph exists, this query seeded
+// nothing" shape the absence detection must not mistake for an empty dataset.
+type kgProbeFakeEngine struct {
+ engine.DocEngine
+ entityRows []map[string]interface{}
+ probeErr error
+ probeCalled bool
+}
+
+func (e *kgProbeFakeEngine) Search(_ context.Context, req *enginetypes.SearchRequest) (*enginetypes.SearchResult, error) {
+ if len(req.SelectFields) == 1 && req.SelectFields[0] == "id" {
+ e.probeCalled = true
+ if e.probeErr != nil {
+ return nil, e.probeErr
+ }
+ return &enginetypes.SearchResult{Chunks: e.entityRows}, nil
+ }
+ return &enginetypes.SearchResult{}, nil
+}
+
+// TestKgAdapterExploreMarksAbsenceOnlyWithoutEntityRows pins the disable trigger:
+// an empty walk over a scope that holds NO entity row is a dataset-level absence
+// (GraphAbsent), while an empty walk over a scope that DOES hold one is a
+// query-level miss and must stay non-absent.
+func TestKgAdapterExploreMarksAbsenceOnlyWithoutEntityRows(t *testing.T) {
+ req := KgExploreRequest{TenantID: "t1", DatasetIDs: []string{"kb1"}, Query: "who links A to B"}
+
+ absentEng := &kgProbeFakeEngine{}
+ got, err := NewKgAdapter(absentEng).Explore(context.Background(), req)
+ if err != nil {
+ t.Fatalf("Explore: %v", err)
+ }
+ if !absentEng.probeCalled {
+ t.Error("an empty walk must probe for entity rows before deciding absence")
+ }
+ if !got.GraphAbsent {
+ t.Error("no entity rows in scope must set GraphAbsent")
+ }
+
+ presentEng := &kgProbeFakeEngine{entityRows: []map[string]interface{}{{"id": "e1"}}}
+ got, err = NewKgAdapter(presentEng).Explore(context.Background(), req)
+ if err != nil {
+ t.Fatalf("Explore: %v", err)
+ }
+ if got.GraphAbsent {
+ t.Error("entity rows exist: an empty walk is a query miss, not a dataset absence")
+ }
+}
+
+// TestKgAdapterExploreDocScopedEmptyIsNotAbsence: a walk the model scoped to
+// specific documents proves nothing about the dataset as a whole, so an empty
+// result must not be reported as a dataset-level absence - that would disable
+// graph_explore for the entire conversation on one scoped miss.
+func TestKgAdapterExploreDocScopedEmptyIsNotAbsence(t *testing.T) {
+ eng := &kgProbeFakeEngine{}
+ got, err := NewKgAdapter(eng).Explore(context.Background(), KgExploreRequest{
+ TenantID: "t1", DatasetIDs: []string{"kb1"}, DocScope: []string{"d1"}, Query: "q",
+ })
+ if err != nil {
+ t.Fatalf("Explore: %v", err)
+ }
+ if got.GraphAbsent {
+ t.Error("a doc-scoped empty walk must not report a dataset-level absence")
+ }
+ if eng.probeCalled {
+ t.Error("a doc-scoped walk must not probe: its scope cannot answer a dataset-level question")
+ }
+}
+
+// TestKgAdapterExploreProbeFailureIsAnError: a failed existence probe must be
+// surfaced, not swallowed into a false "no graph" verdict that would disable the
+// tool for the whole conversation.
+func TestKgAdapterExploreProbeFailureIsAnError(t *testing.T) {
+ eng := &kgProbeFakeEngine{probeErr: errors.New("engine down")}
+ _, err := NewKgAdapter(eng).Explore(context.Background(), KgExploreRequest{
+ TenantID: "t1", DatasetIDs: []string{"kb1"}, Query: "q",
+ })
+ if err == nil || !strings.Contains(err.Error(), "engine down") {
+ t.Fatalf("probe failure must surface as an error, got %v", err)
+ }
+}
diff --git a/internal/agentic_rag/tool_navigate_structure.go b/internal/agentic_rag/tool_navigate_structure.go
new file mode 100644
index 0000000000..7fba9f6d8b
--- /dev/null
+++ b/internal/agentic_rag/tool_navigate_structure.go
@@ -0,0 +1,1131 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package agentic_rag
+
+// navigate_structure: drill into ONE document's compiled structure (the
+// entity/relation outline built at compile time) and return a query-focused
+// <structure_navigation> outline with chunk pointers the model can feed to
+// list_chunks.
+//
+// This is the experiment-grade port of the harness navigate_structure
+// (internal/rag/agentic-rag/runtime/tool_navigation.go). The harness version
+// was never wired to a Go-side structure reader in production, so this tool
+// reads the compiled-structure rows directly from the doc-store and reuses the
+// harness's keyword-relevance beam drill (its documented no-vector fallback).
+// The dense-vector seed and claim-recall legs are intentionally omitted here;
+// they are additive and can be layered on without changing the tool's contract.
+//
+// Typical use: call navigate_tree first to route to a document, take its
+// doc_id, then call navigate_structure with that doc_id to see where the answer
+// sits inside the document.
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+
+ einotool "github.com/cloudwego/eino/components/tool"
+ "github.com/cloudwego/eino/schema"
+ "github.com/eino-contrib/jsonschema"
+ "go.uber.org/zap"
+
+ "ragflow/internal/common"
+ "ragflow/internal/engine"
+ enginetypes "ragflow/internal/engine/types"
+)
+
+const navigateStructureToolName = "navigate_structure"
+
+const navigateStructureToolDescription = `Drill into ONE document's COMPILED STRUCTURE (the entity/relation outline built at compile time) and return a query-focused outline of where the answer sits, with chunk pointers you can pass to list_chunks to deep-read.
+CALL IT AFTER navigate_tree has routed you to a document: take a doc_id from the <tree_navigation> result and pass it as doc_id. It shows the document's internal structure (entities and how they relate) instead of scanning chunks blindly.
+Returns an XML <structure_navigation> document: one <doc> element per readable structure, each with a <structure> outline of "name (type): description [chunks: c1,c2]" lines and optional <claims_sufficient/>. Feed the chunk pointers to list_chunks (anchor_chunk_ids).
+An empty result (<structure_navigation count="0" error="...">) means this document has NO compiled structure of the requested kind - the error attribute says which: "no compiled navigation tree" (route first with navigate_tree), "no document located" (no doc_id), or "no structure" (structure absent for this kind in THAT document - fall back to grep_chunks / search_*_chunks; the verdict is per document, so the tool stays available for other documents).`
+
+// navigateStructureArgs is the JSON the model sends into InvokableRun.
+type navigateStructureArgs struct {
+ Query string `json:"query"`
+ DocID string `json:"doc_id,omitempty"`
+ DocIDs []string `json:"doc_ids,omitempty"`
+ Kind string `json:"kind,omitempty"`
+ Keywords string `json:"keywords,omitempty"`
+ DatasetIDs []string `json:"dataset_ids,omitempty"`
+}
+
+// Compiled-structure shape / kind constants, mirroring the harness navigation
+// contract so the model sees the same signal shape.
+var (
+ // catalogKinds is the default structure-kind set read when kind is omitted.
+ // It accepts the catalog/timeline shapes AND the raw graph/entity/relation
+ // shapes so the default "show me this document's structure" reads every
+ // compiled-shape row instead of silently dropping graph blobs.
+ catalogKinds = map[string]bool{
+ "tree": true, "timeline": true, "page_index": true, "pageindex": true,
+ "graph": true, "entity": true, "relation": true, "knowledge_graph": true,
+ }
+ mindmapKinds = map[string]bool{"mindmap": true, "mind_map": true}
+ // shapeKwds are the knowledge_graph_kwd ROW SHAPES a compiled structure can
+ // be written as. Reading BOTH the compact "graph" blob and the per-entity /
+ // per-relation rows is required: otherwise navigation silently returns EMPTY
+ // for datasets compiled into per-entity/relation rows rather than a graph blob.
+ shapeKwds = []string{"graph", "entity", "relation"}
+)
+
+// Empty-reason constants, mirroring the harness navigation contract.
+const (
+ navStructReasonBadArgs = "bad_args"
+ navStructReasonNoStructure = "no_structure"
+ navStructReasonNoDoc = "no_doc"
+)
+
+// Drill-down bounds (mirroring the harness _STRUCT_* limits).
+const (
+ structMaxDepth = 3 // max TOC levels drilled
+ structMaxNodes = 10 // cap on nodes rendered in the outline
+ structBranchK = 2 // keep top-K most relevant nodes per level
+ structRelevanceMin = 1 // a node must match at least this many query terms to descend
+ structDescSnippet = 180 // cap on a node's description snippet
+ structMaxChunks = 4 // cap on chunk snippets returned in the outline
+)
+
+// structureRel is a parent->child relation of a compiled structure hierarchy.
+type structureRel struct {
+ from string
+ to string
+ relType string
+}
+
+// structureNode is a node of a compiled structure hierarchy during drill-down.
+type structureNode struct {
+ name string
+ nodeType string
+ desc string
+ sourceChunkIDs []string
+ vec []float64
+}
+
+// chunkWithText pairs a chunk id with its text for structure snippet ranking.
+type chunkWithText struct {
+ id string
+ text string
+}
+
+// structureDrillout is the per-document result of the TOC drill-down.
+type structureDrillout struct {
+ outline string
+ nodes int
+ chunkPtrs int
+ topScore float64
+ chunkPaths map[string]string
+ selector string
+}
+
+// StructureRow is one compiled-structure row: the doc-store fields the structure
+// reader reads.
+type StructureRow struct {
+ CompileKwd string
+ TemplateKind string
+ KnowledgeGraphKwd string
+ Content string
+ Vec []float64
+}
+
+// structureReader reads a document's compiled structure rows. The production
+// implementation reads from the doc-store; tests install a fake. Until a reader
+// is installed (or the engine is available) navigate_structure reports
+// EMPTY/no_structure, falling through to the text tools.
+type structureReader interface {
+ ReadStructure(ctx context.Context, tenantID, kbID, docID string) ([]StructureRow, error)
+}
+
+var structReaderInst structureReader
+
+// SetStructureReader installs the (production or test) structure reader.
+func SetStructureReader(r structureReader) {
+ structReaderInst = r
+}
+
+func getStructureReader() structureReader {
+ if structReaderInst != nil {
+ return structReaderInst
+ }
+ return &engineStructureReader{}
+}
+
+// engineStructureReader reads compiled-structure rows directly from the
+// doc-store via engine.Get(). It mirrors the harness loadStructureGraph, but is
+// scoped to ONE document (the tool already knows which document to drill).
+type engineStructureReader struct{}
+
+func (engineStructureReader) ReadStructure(ctx context.Context, tenantID, kbID, docID string) ([]StructureRow, error) {
+ de := engine.Get()
+ if de == nil {
+ return nil, nil
+ }
+ req := &enginetypes.SearchRequest{
+ IndexNames: []string{indexNameFor(tenantID, "")},
+ KbIDs: []string{kbID},
+ SelectFields: []string{"content_with_weight", "compile_kwd", "compilation_template_kind_kwd", "type_kwd", "knowledge_graph_kwd"},
+ Filter: map[string]interface{}{"doc_id": []string{docID}, "knowledge_graph_kwd": shapeKwds},
+ Limit: 3000,
+ IncludeUnavailable: true,
+ }
+ res, err := de.Search(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+ rows := make([]StructureRow, 0, len(res.Chunks))
+ for _, row := range res.Chunks {
+ kg, _ := row["type_kwd"].(string)
+ if kg == "" {
+ kg, _ = row["knowledge_graph_kwd"].(string)
+ }
+ sr := StructureRow{
+ CompileKwd: fmt.Sprint(row["compile_kwd"]),
+ TemplateKind: fmt.Sprint(row["compilation_template_kind_kwd"]),
+ KnowledgeGraphKwd: kg,
+ Content: fmt.Sprint(row["content_with_weight"]),
+ }
+ rows = append(rows, sr)
+ }
+ return rows, nil
+}
+
+// indexNameFor resolves the document/structure search index: the tenant's
+// default "ragflow_<tenant_id>" unless a tenant overrides index_name.
+func indexNameFor(tenantID, configured string) string {
+ if configured != "" {
+ return configured
+ }
+ return "ragflow_" + tenantID
+}
+
+// normalizeKindKey applies the API's kind normalization (page_index / graph ->
+// timeline, mind_map -> mindmap).
+func normalizeKindKey(kind string) string {
+ switch strings.ToLower(kind) {
+ case "page_index", "graph":
+ return "timeline"
+ case "mind_map":
+ return "mindmap"
+ }
+ return strings.ToLower(kind)
+}
+
+func normalizeKind(row map[string]interface{}) string {
+ return normalizeKindKey(compilationKind(row))
+}
+
+func compilationKind(row map[string]interface{}) string {
+ if v, ok := row["compilation_template_kind_kwd"].(string); ok && v != "" {
+ return v
+ }
+ return fmt.Sprint(row["knowledge_graph_kwd"])
+}
+
+// rowKind derives the normalized structure kind from a compiled-structure row,
+// using its knowledge_graph_kwd (the row SHAPE: graph / entity / relation) or,
+// failing that, its compilation template kind. This is what keeps a "graph"
+// blob from being filtered out as the wrong kind.
+func rowKind(row StructureRow) string {
+ kind := row.KnowledgeGraphKwd
+ if kind == "" {
+ kind = row.TemplateKind
+ }
+ return normalizeKindKey(kind)
+}
+
+// ParseCompiledStructure merges the two row shapes (graph blob / per-entity /
+// per-relation) into entities / relations, mirroring _query in navigation.py.
+func ParseCompiledStructure(rows []StructureRow, kinds []string) ([]map[string]any, []map[string]any) {
+ want := map[string]bool{}
+ for _, k := range kinds {
+ if k != "" {
+ // Normalize the requested kind the same way rowKind normalizes the
+ // row's own: without this "graph" (which rowKind maps to "timeline")
+ // would be filtered out before its entities/relations are parsed.
+ want[normalizeKindKey(k)] = true
+ }
+ }
+ var entities, relations []map[string]any
+ for _, row := range rows {
+ kind := rowKind(row)
+ if len(want) > 0 && !want[kind] {
+ continue
+ }
+ graph, ok := decodeJSONObject(row.Content)
+ if !ok {
+ continue
+ }
+ attachVec := func(list []map[string]any) {
+ if len(row.Vec) == 0 {
+ return
+ }
+ for _, m := range list {
+ m["_vec"] = row.Vec
+ }
+ }
+ switch row.KnowledgeGraphKwd {
+ case "graph":
+ es := objectList(graph["entities"])
+ rs := objectList(graph["relations"])
+ attachVec(es)
+ attachVec(rs)
+ entities = append(entities, es...)
+ relations = append(relations, rs...)
+ case "entity":
+ attachVec([]map[string]any{graph})
+ entities = append(entities, graph)
+ case "relation":
+ attachVec([]map[string]any{graph})
+ relations = append(relations, graph)
+ }
+ }
+ return entities, relations
+}
+
+// structureGraphFromRaw maps what ParseCompiledStructure returns onto the typed
+// nodes/relations the drill-down consumes (entity -> node conversion included so
+// the drill-down only ever sees structureNode).
+func structureGraphFromRaw(rawEntities, rawRels []map[string]any) ([]structureNode, []structureRel) {
+ var out []structureNode
+ for _, e := range rawEntities {
+ name, _ := e["name"].(string)
+ if strings.TrimSpace(name) == "" {
+ continue
+ }
+ typ, _ := e["type"].(string)
+ desc, _ := e["description"].(string)
+ n := structureNode{name: name, nodeType: typ, desc: desc}
+ if v, ok := e["_vec"].([]float64); ok {
+ n.vec = v
+ }
+ if ids, ok := e["source_chunk_ids"].([]interface{}); ok {
+ for _, id := range ids {
+ if s, ok := id.(string); ok && s != "" {
+ n.sourceChunkIDs = append(n.sourceChunkIDs, s)
+ }
+ }
+ }
+ out = append(out, n)
+ }
+ var rels []structureRel
+ for _, r := range rawRels {
+ pRaw, _ := r["from"].(string)
+ cRaw, _ := r["to"].(string)
+ p := strings.TrimSpace(pRaw)
+ c := strings.TrimSpace(cRaw)
+ if p == "" || c == "" || p == c {
+ continue
+ }
+ relType, _ := r["type"].(string)
+ rels = append(rels, structureRel{from: p, to: c, relType: relType})
+ }
+ return out, rels
+}
+
+// queryTerms mirrors navigation.py's regex tokenizer: lowercase coarse word
+// tokens of length >= 2 (the BM25-ish keyword signal).
+func queryTerms(q string) []string {
+ if q == "" {
+ return nil
+ }
+ lower := strings.ToLower(q)
+ var out []string
+ var cur []byte
+ for i := 0; i < len(lower); i++ {
+ c := lower[i]
+ if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
+ cur = append(cur, c)
+ continue
+ }
+ if len(cur) >= 2 {
+ out = append(out, string(cur))
+ }
+ cur = cur[:0]
+ }
+ if len(cur) >= 2 {
+ out = append(out, string(cur))
+ }
+ return out
+}
+
+// nodeRelevance mirrors _node_relevance: how many query terms occur in a node's
+// name+description.
+func nodeRelevance(terms []string, name, desc string) int {
+ if len(terms) == 0 {
+ return 0
+ }
+ text := strings.ToLower(name + " " + desc)
+ n := 0
+ for _, t := range terms {
+ if strings.Contains(text, t) {
+ n++
+ }
+ }
+ return n
+}
+
+// nodeScore mirrors _node_score: cosine when a query vector and the node
+// embedding both exist, else keyword relevance. This port leaves nodes
+// vector-less, so it always uses keyword relevance.
+func nodeScore(qvec []float64, terms []string, n structureNode) float64 {
+ if len(qvec) > 0 && len(n.vec) > 0 {
+ return cosine(qvec, n.vec)
+ }
+ return float64(nodeRelevance(terms, n.name, n.desc))
+}
+
+func cosine(a, b []float64) float64 {
+ if len(a) == 0 || len(b) == 0 || len(a) != len(b) {
+ return 0
+ }
+ var dot, na, nb float64
+ for i := range a {
+ dot += a[i] * b[i]
+ na += a[i] * a[i]
+ nb += b[i] * b[i]
+ }
+ if na == 0 || nb == 0 {
+ return 0
+ }
+ return dot / (sqrt(na) * sqrt(nb))
+}
+
+func sqrt(x float64) float64 {
+ if x < 0 {
+ return 0
+ }
+ r := x
+ for i := 0; i < 16; i++ {
+ if r == 0 {
+ break
+ }
+ r = 0.5 * (r + x/r)
+ }
+ return r
+}
+
+func sliceContains(s []string, v string) bool {
+ for _, x := range s {
+ if x == v {
+ return true
+ }
+ }
+ return false
+}
+
+// buildTocTree mirrors _build_toc_tree: a name->node map, the parent->children
+// map, the child->parent map (single parent, last-wins) and the root names.
+func buildTocTree(nodes []structureNode, rels []structureRel) (map[string]structureNode, map[string][]string, map[string]string, []string) {
+ byName := map[string]structureNode{}
+ for _, n := range nodes {
+ if n.name != "" {
+ byName[n.name] = n
+ }
+ }
+ children := map[string][]string{}
+ parents := map[string]string{}
+ for _, r := range rels {
+ p, c := r.from, r.to
+ if p == "" || c == "" || p == c {
+ continue
+ }
+ if _, ok := children[p]; !ok {
+ children[p] = []string{}
+ }
+ dup := false
+ for _, x := range children[p] {
+ if x == c {
+ dup = true
+ break
+ }
+ }
+ if !dup {
+ children[p] = append(children[p], c)
+ }
+ parents[c] = p
+ }
+ var roots []string
+ for n := range byName {
+ if _, has := parents[n]; !has {
+ roots = append(roots, n)
+ }
+ }
+ if len(roots) == 0 {
+ for n := range byName {
+ if _, has := children[n]; !has {
+ roots = append(roots, n)
+ }
+ }
+ }
+ if len(roots) == 0 {
+ for n := range byName {
+ roots = append(roots, n)
+ }
+ }
+ return byName, children, parents, roots
+}
+
+// chunkPtrs mirrors _chunk_ptrs: a bounded, deduped comma-joined slice of an
+// item's source chunk ids (<=8, the anchors the model sees).
+func chunkPtrs(ids []string) string {
+ if len(ids) == 0 {
+ return ""
+ }
+ var seen []string
+ for _, c := range ids {
+ if c == "" {
+ continue
+ }
+ if !sliceContains(seen, c) {
+ seen = append(seen, c)
+ if len(seen) >= 8 {
+ break
+ }
+ }
+ }
+ return strings.Join(seen, ",")
+}
+
+// collectChunkIDs mirrors _collect_chunk_ids: a deduped, capped union of source
+// chunk ids across a set of nodes.
+func collectChunkIDs(nodes []structureNode, capN int) []string {
+ if capN <= 0 {
+ capN = 32
+ }
+ var out []string
+ for _, n := range nodes {
+ for _, c := range n.sourceChunkIDs {
+ if c == "" {
+ continue
+ }
+ if sliceContains(out, c) {
+ continue
+ }
+ out = append(out, c)
+ if len(out) >= capN {
+ return out
+ }
+ }
+ }
+ return out
+}
+
+// sortedKeptNames returns a kept-name set as a sorted slice (map iteration is
+// randomised per process in Go, so sorting gives a stable, reproducible order).
+func sortedKeptNames(names map[string]bool) []string {
+ out := make([]string, 0, len(names))
+ for n := range names {
+ out = append(out, n)
+ }
+ sort.Strings(out)
+ return out
+}
+
+// drillWithAncestors pulls the ancestors of names into the kept set so a path
+// renders as root -> ... -> node.
+func drillWithAncestors(names map[string]bool, parents map[string]string) map[string]bool {
+ for name := range names {
+ cur := parents[name]
+ guard := 0
+ for cur != "" && !names[cur] && guard < structMaxDepth {
+ names[cur] = true
+ cur = parents[cur]
+ guard++
+ }
+ }
+ return names
+}
+
+// drillKeptNodes mirrors _drill_kept_nodes: vector-beam BFS descent from the TOC
+// roots, keeping top-K children per level by keyword relevance (this port has no
+// node vectors, so it always uses the keyword path), returning the kept nodes,
+// the single-parent map, the kept-name set and the overall best score.
+func drillKeptNodes(qvec []float64, terms []string, nodes []structureNode, rels []structureRel) ([]structureNode, map[string]string, map[string]bool, float64) {
+ byName, children, parents, roots := buildTocTree(nodes, rels)
+ if len(roots) == 0 {
+ return nil, nil, nil, 0.0
+ }
+ frontier := roots
+ keptNames := map[string]bool{}
+ depth := 0
+ bestOverall := 0.0
+ for len(frontier) > 0 && depth <= structMaxDepth {
+ type scored struct {
+ score float64
+ name string
+ }
+ var scoredList []scored
+ for _, n := range frontier {
+ if e, ok := byName[n]; ok {
+ scoredList = append(scoredList, scored{nodeScore(qvec, terms, e), n})
+ }
+ }
+ if len(scoredList) == 0 {
+ break
+ }
+ sort.SliceStable(scoredList, func(i, j int) bool { return scoredList[i].score > scoredList[j].score })
+ best := scoredList[0].score
+ if best > bestOverall {
+ bestOverall = best
+ }
+ if len(qvec) == 0 && best < float64(structRelevanceMin) {
+ break
+ }
+ var top []scored
+ for _, s := range scoredList {
+ if s.score >= float64(structRelevanceMin) {
+ top = append(top, s)
+ if len(top) >= structBranchK {
+ break
+ }
+ }
+ }
+ if len(top) == 0 {
+ break
+ }
+ var next []string
+ for _, s := range top {
+ if !keptNames[s.name] {
+ keptNames[s.name] = true
+ }
+ next = append(next, children[s.name]...)
+ }
+ frontier = next
+ depth++
+ }
+ for name := range keptNames {
+ cur := parents[name]
+ guard := 0
+ for cur != "" && !keptNames[cur] && guard < structMaxDepth {
+ keptNames[cur] = true
+ cur = parents[cur]
+ guard++
+ }
+ }
+ var kept []structureNode
+ for _, n := range sortedKeptNames(keptNames) {
+ if e, ok := byName[n]; ok {
+ kept = append(kept, e)
+ }
+ }
+ return kept, parents, keptNames, bestOverall
+}
+
+// outlineStats mirrors _outline_stats: the entity / chunk-pointer counts for the
+// flat fallback outline (no drill happened => top_score 0).
+func outlineStats(nodes []structureNode) (nodeCount, ptrCount int) {
+ count := len(nodes)
+ if count > structMaxNodes {
+ count = structMaxNodes
+ }
+ ptrs := 0
+ for _, n := range nodes[:count] {
+ ptrs += len(collectChunkIDs([]structureNode{n}, 32))
+ }
+ return count, ptrs
+}
+
+// navTypeOr returns a node type, defaulting to "other" (a missing key reads as
+// absent, not "<nil>").
+func navTypeOr(t string) string {
+ if t == "" {
+ return "other"
+ }
+ return t
+}
+
+// navOutlineLine renders one "- name (type): desc [chunks: c1,c2]" line.
+func navOutlineLine(indent, name, nodeType, desc string, chunks []string) string {
+ line := indent + "- " + name + " (" + navTypeOr(nodeType) + ")"
+ if desc != "" {
+ line += ": " + Snippet(desc, structDescSnippet)
+ }
+ if c := chunkPtrs(chunks); c != "" {
+ line += " [chunks: " + c + "]"
+ }
+ return line
+}
+
+// renderOutline mirrors _render_outline: a compact flat outline of entities then
+// relations (fallback when no query terms are usable).
+func renderOutline(nodes []structureNode, rels []structureRel) string {
+ var lines []string
+ capE, capR := 40, 40
+ for i, n := range nodes {
+ if i >= capE || n.name == "" {
+ continue
+ }
+ lines = append(lines, navOutlineLine("", n.name, n.nodeType, n.desc, n.sourceChunkIDs))
+ }
+ for i, r := range rels {
+ if i >= capR || r.from == "" || r.to == "" {
+ continue
+ }
+ rt := r.relType
+ if rt == "" {
+ rt = "related_to"
+ }
+ lines = append(lines, "- "+r.from+" -["+rt+"]-> "+r.to)
+ }
+ return strings.Join(lines, "\n")
+}
+
+// renderTocDrilldown mirrors _render_toc_drilldown's flat + beam paths: when no
+// terms/vector it falls back to the flat outline; otherwise it vector-beam
+// descends toward the query by keyword relevance. loader, when non-nil, fetches
+// chunk texts so short snippets can be appended; a nil loader skips the snippet
+// pass.
+func renderTocDrilldown(query string, qvec []float64, nodes []structureNode, rels []structureRel, loader func(ids []string) []chunkWithText) structureDrillout {
+ flat := func() structureDrillout {
+ out := renderOutline(nodes, rels)
+ n, p := outlineStats(nodes)
+ return structureDrillout{outline: out, nodes: n, chunkPtrs: p, topScore: 0.0, chunkPaths: map[string]string{}, selector: "flat"}
+ }
+ terms := queryTerms(query)
+ if len(terms) == 0 && len(qvec) == 0 {
+ return flat()
+ }
+ kept, parents, keptNames, best := drillKeptNodes(qvec, terms, nodes, rels)
+ if len(kept) == 0 {
+ out := flat()
+ out.selector = "beam"
+ return out
+ }
+ // depth_of: node -> number of kept ancestors (rendering indentation).
+ depthOf := map[string]int{}
+ for n := range keptNames {
+ d := 0
+ cur := parents[n]
+ for cur != "" && keptNames[cur] {
+ d++
+ cur = parents[cur]
+ }
+ depthOf[n] = d
+ }
+ chunkPaths := map[string]string{}
+ for _, e := range kept {
+ name := strings.TrimSpace(e.name)
+ if name == "" {
+ continue
+ }
+ var segs []string
+ segs = append(segs, name)
+ cur := parents[name]
+ guard := 0
+ for cur != "" && guard < structMaxDepth {
+ segs = append(segs, cur)
+ cur = parents[cur]
+ guard++
+ }
+ for i, j := 0, len(segs)-1; i < j; i, j = i+1, j-1 {
+ segs[i], segs[j] = segs[j], segs[i]
+ }
+ path := strings.Join(segs, " -> ")
+ for _, cid := range e.sourceChunkIDs {
+ if cid != "" {
+ if _, seen := chunkPaths[cid]; !seen {
+ chunkPaths[cid] = path
+ }
+ }
+ }
+ }
+ var lines []string
+ count := len(kept)
+ if count > structMaxNodes {
+ count = structMaxNodes
+ }
+ for _, e := range kept[:count] {
+ name := strings.TrimSpace(e.name)
+ if name == "" {
+ continue
+ }
+ indent := strings.Repeat(" ", depthOf[name])
+ lines = append(lines, navOutlineLine(indent, name, e.nodeType, e.desc, e.sourceChunkIDs))
+ }
+ if len(kept) > 0 && loader != nil {
+ wanted := collectChunkIDs(kept, 32)
+ if len(wanted) > 0 {
+ chunks := loader(wanted)
+ capN := len(chunks)
+ if capN > structMaxChunks {
+ capN = structMaxChunks
+ }
+ for _, c := range chunks[:capN] {
+ text := strings.TrimSpace(c.text)
+ if text == "" {
+ continue
+ }
+ lines = append(lines, "- [chunk "+c.id+"]: "+Snippet(text, 300))
+ }
+ }
+ }
+ return structureDrillout{
+ outline: strings.Join(lines, "\n"),
+ nodes: len(kept),
+ chunkPtrs: len(kept),
+ topScore: best,
+ chunkPaths: chunkPaths,
+ selector: "beam",
+ }
+}
+
+// structureDocSegment renders one <doc> element (doc_id / entities / relations
+// plus the <structure> outline).
+func structureDocSegment(docID, query, kind string, rank int, nodes []structureNode, rels []structureRel, drill structureDrillout) string {
+ esc := func(s string) string { return xmlEscape(s) }
+ var b strings.Builder
+ fmt.Fprintf(&b, ` <doc rank="%d" doc_id="%s" entities="%d" relations="%d">`, rank, esc(docID), len(nodes), len(rels))
+ if drill.outline != "" {
+ b.WriteString("\n <structure>" + esc(drill.outline) + "</structure>")
+ }
+ b.WriteString("\n </doc>")
+ return b.String()
+}
+
+// emptyReasonLabel maps an empty-reason constant to the XML error label.
+func emptyReasonLabel(reason string) string {
+ switch reason {
+ case navStructReasonBadArgs:
+ return "query is required"
+ case navStructReasonNoDoc:
+ return "no document located"
+ default:
+ return "no structure"
+ }
+}
+
+// navigateStructures renders the compiled structures of the given documents into
+// a single <structure_navigation> with one <doc> per readable structure. A
+// document without a compiled structure of the requested kind is skipped; an
+// empty result (no doc carried a structure) reports no_structure.
+func navigateStructures(ctx context.Context, tenantID string, query string, docIDs, datasetIDs []string, kind string, reader structureReader) (string, string) {
+ if len(docIDs) == 0 {
+ return navStructEmpty(navStructReasonNoDoc, "route first with navigate_tree"), navStructReasonNoDoc
+ }
+ kinds := structureKindsFor(kind)
+ var segs []string
+ var docIDsSeen []string
+ for _, did := range docIDs {
+ drill, nodes, rels, empty := readStructureDocCore(ctx, tenantID, query, did, kind, kinds, datasetIDs, reader)
+ if empty != "" {
+ continue
+ }
+ segs = append(segs, structureDocSegment(did, query, kind, len(segs)+1, nodes, rels, drill))
+ docIDsSeen = append(docIDsSeen, did)
+ }
+ if len(segs) == 0 {
+ return navStructEmpty(navStructReasonNoStructure, "no compiled structure for this kind"), navStructReasonNoStructure
+ }
+ esc := func(s string) string { return xmlEscape(s) }
+ parts := append([]string{
+ fmt.Sprintf(`<structure_navigation count="%d" query="%s" kind="%s">`, len(segs), esc(query), esc(kind)),
+ }, segs...)
+ parts = append(parts, "</structure_navigation>")
+ return strings.Join(parts, "\n"), ""
+}
+
+// readStructureDocCore reads ONE document's compiled structure of the requested
+// kind and drills it toward the query. It returns the per-document drill data,
+// the nodes/rels, and an empty-reason ("" means read succeeded).
+func readStructureDocCore(ctx context.Context, tenantID, query, docID, kind string, kinds map[string]bool, datasetIDs []string, reader structureReader) (structureDrillout, []structureNode, []structureRel, string) {
+ none := structureDrillout{chunkPaths: map[string]string{}}
+ switch {
+ case query == "":
+ return none, nil, nil, navStructReasonBadArgs
+ case docID == "":
+ return none, nil, nil, navStructReasonNoDoc
+ }
+ var nodes []structureNode
+ var rels []structureRel
+ anyStruct := false
+ for _, kbID := range datasetIDs {
+ rows, err := reader.ReadStructure(ctx, tenantID, kbID, docID)
+ if err != nil {
+ common.DebugCtx(ctx, "navigate_structure: read failed",
+ zap.String("kb_id", kbID), zap.String("doc_id", docID), zap.Error(err))
+ continue
+ }
+ if len(rows) == 0 {
+ continue
+ }
+ anyStruct = true
+ var kindList []string
+ for k := range kinds {
+ kindList = append(kindList, k)
+ }
+ sort.Strings(kindList)
+ entities, relations := ParseCompiledStructure(rows, kindList)
+ es, rs := structureGraphFromRaw(entities, relations)
+ nodes = append(nodes, es...)
+ rels = append(rels, rs...)
+ }
+ if !anyStruct || len(nodes) == 0 {
+ return none, nil, nil, navStructReasonNoStructure
+ }
+ loader := func(ids []string) []chunkWithText { return structureNodeLoader(ctx, tenantID, ids) }
+ drill := renderTocDrilldown(query, nil, nodes, rels, loader)
+ return drill, nodes, rels, ""
+}
+
+// structureNodeLoader fetches chunk texts by id for the drill-down snippet pass.
+func structureNodeLoader(ctx context.Context, tenantID string, ids []string) []chunkWithText {
+ de := engine.Get()
+ if de == nil || len(ids) == 0 {
+ return nil
+ }
+ req := &enginetypes.SearchRequest{
+ IndexNames: []string{indexNameFor(tenantID, "")},
+ SelectFields: []string{"content_with_weight", "docnm_kwd", "doc_id", "id"},
+ Filter: map[string]interface{}{"id": ids},
+ Limit: len(ids),
+ }
+ res, err := de.Search(ctx, req)
+ if err != nil {
+ return nil
+ }
+ out := make([]chunkWithText, 0, len(res.Chunks))
+ for _, c := range res.Chunks {
+ id := fmt.Sprint(c["id"])
+ if id == "" {
+ continue
+ }
+ out = append(out, chunkWithText{id: id, text: fmt.Sprint(c["content_with_weight"])})
+ }
+ return out
+}
+
+// structureKindsFor maps a navigate_structure kind string to the compiled-kinds
+// set to read, mirroring navigation.py _structure_kinds_for. Defaults to catalog.
+func structureKindsFor(kind string) map[string]bool {
+ k := strings.TrimSpace(strings.ToLower(kind))
+ if k == "" {
+ k = "catalog"
+ }
+ switch k {
+ case "mindmap", "mind_map", "concept":
+ out := make(map[string]bool, len(mindmapKinds))
+ for kk := range mindmapKinds {
+ out[kk] = true
+ }
+ return out
+ case "graph", "kg", "entity", "ontology":
+ return map[string]bool{"graph": true, "ontology": true, "entity": true, "raptor": true}
+ default:
+ out := make(map[string]bool, len(catalogKinds))
+ for kk := range catalogKinds {
+ out[kk] = true
+ }
+ return out
+ }
+}
+
+func decodeJSONObject(s string) (map[string]any, bool) {
+ v := ExtractJSON(s)
+ m, ok := v.(map[string]any)
+ return m, ok
+}
+
+// ExtractJSON finds the first JSON object in s (tolerating surrounding prose or
+// code fences) and returns it decoded.
+func ExtractJSON(s string) any {
+ start := strings.Index(s, "{")
+ if start < 0 {
+ return nil
+ }
+ depth := 0
+ inStr := false
+ escaped := false
+ for i := start; i < len(s); i++ {
+ c := s[i]
+ if inStr {
+ // Inside a string literal a backslash escapes the next byte, so a
+ // `\"` must not be read as the closing quote (which would flip the
+ // in-string state and corrupt the brace depth - observed with entity
+ // descriptions that carry escaped quotes).
+ switch {
+ case escaped:
+ escaped = false
+ case c == '\\':
+ escaped = true
+ case c == '"':
+ inStr = false
+ }
+ continue
+ }
+ switch c {
+ case '"':
+ inStr = true
+ case '{':
+ depth++
+ case '}':
+ depth--
+ if depth == 0 {
+ raw := s[start : i+1]
+ var v any
+ if err := json.Unmarshal([]byte(raw), &v); err == nil {
+ return v
+ }
+ return nil
+ }
+ }
+ }
+ return nil
+}
+
+func objectList(v any) []map[string]any {
+ list, _ := v.([]any)
+ out := make([]map[string]any, 0, len(list))
+ for _, item := range list {
+ if m, ok := item.(map[string]any); ok {
+ out = append(out, m)
+ }
+ }
+ return out
+}
+
+// Snippet truncates s to at most n runes, appending an ellipsis when cut.
+func Snippet(s string, n int) string {
+ r := []rune(s)
+ if len(r) <= n {
+ return s
+ }
+ return string(r[:n]) + "…"
+}
+
+// navStructEmpty returns the empty <structure_navigation count="0"> XML carrying
+// an optional error="..." attribute, mirroring the harness navigation contract.
+func navStructEmpty(reason, label string) string {
+ attr := ""
+ if label != "" {
+ attr = ` error="` + xmlEscape(label) + `"`
+ }
+ return "<structure_navigation count=\"0\"" + attr + ">\n</structure_navigation>"
+}
+
+// NavigateStructureTool drills a document's compiled structure. It is stateless:
+// the tenant and dataset scope are injected at construction from the session.
+type NavigateStructureTool struct {
+ tenantID string
+ datasetIDs []string
+}
+
+// NewNavigateStructureTool returns a NavigateStructureTool scoped to the given
+// tenant and datasets, implementing eino's runtime.InvokableTool.
+func NewNavigateStructureTool(tenantID string, datasetIDs []string) *NavigateStructureTool {
+ return &NavigateStructureTool{tenantID: tenantID, datasetIDs: datasetIDs}
+}
+
+// Info returns the tool's metadata for the chat model.
+func (g *NavigateStructureTool) Info(_ context.Context) (*schema.ToolInfo, error) {
+ schemaJSON := `{
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "REQUIRED: the question (or topic) to focus the structure drill on. Phrase it as the subject you are investigating."
+ },
+ "doc_id": {
+ "type": "string",
+ "description": "The document to drill. Take it from a navigate_tree <doc doc_id> result. Required unless doc_ids is given."
+ },
+ "doc_ids": {
+ "type": "array",
+ "description": "Optional explicit document ids to drill (at most 10). When omitted, doc_id is used.",
+ "items": { "type": "string" },
+ "maxItems": 10
+ },
+ "kind": {
+ "type": "string",
+ "description": "Optional structure kind to read: \"catalog\" (default, tree/page_index/timeline), \"mindmap\", or \"graph\"/\"kg\"/\"entity\"/\"ontology\"."
+ },
+ "keywords": {
+ "type": "string",
+ "description": "Optional extra keywords that enrich the drill query without being required to match."
+ },
+ "dataset_ids": {
+ "type": "array",
+ "description": "Optional dataset ids to restrict to (at most 10). When omitted, the current conversation's bound datasets are used.",
+ "items": { "type": "string" },
+ "maxItems": 10
+ }
+ },
+ "required": ["query"]
+}`
+ s := &jsonschema.Schema{}
+ if err := json.Unmarshal([]byte(schemaJSON), s); err != nil {
+ return nil, fmt.Errorf("navigate_structure: parse schema: %w", err)
+ }
+ return &schema.ToolInfo{
+ Name: navigateStructureToolName,
+ Desc: navigateStructureToolDescription,
+ ParamsOneOf: schema.NewParamsOneOfByJSONSchema(s),
+ }, nil
+}
+
+// InvokableRun drills the document structure and returns the XML
+// <structure_navigation> document.
+func (g *NavigateStructureTool) InvokableRun(ctx context.Context, argumentsInJSON string, _ ...einotool.Option) (string, error) {
+ return guardedToolRun(ctx, navigateStructureToolName, g.invokableRun, argumentsInJSON)
+}
+
+func (g *NavigateStructureTool) invokableRun(ctx context.Context, argumentsInJSON string) (string, error) {
+ var args navigateStructureArgs
+ if err := json.Unmarshal([]byte(argumentsInJSON), &args); err != nil {
+ return "", fmt.Errorf("navigate_structure: parse arguments: %w", err)
+ }
+ query := strings.TrimSpace(args.Query)
+ if query == "" {
+ return "", fmt.Errorf("navigate_structure: query is required and must be a non-empty string")
+ }
+ if !navToolEnabled(ctx, navigateStructureToolName) {
+ // Marked unavailable for this conversation (bound datasets have no
+ // compiled structure): skip the backend and return the same verdict the
+ // caller falls back from.
+ common.DebugCtx(ctx, "navigate_structure: marked unavailable; skipping backend (no structure)")
+ return navStructEmpty(navStructReasonNoStructure, "no structure"), nil
+ }
+ datasetIDs, err := resolveDatasetScope(g.datasetIDs, args.DatasetIDs)
+ if err != nil {
+ return "", fmt.Errorf("navigate_structure: %w", err)
+ }
+ if len(datasetIDs) == 0 {
+ return navStructEmpty(navStructReasonNoStructure, "no bound datasets"), nil
+ }
+
+ docIDs := args.DocIDs
+ if len(docIDs) == 0 && args.DocID != "" {
+ docIDs = []string{args.DocID}
+ }
+ if len(docIDs) == 0 {
+ return navStructEmpty(navStructReasonNoDoc, "route first with navigate_tree"), nil
+ }
+ if len(docIDs) > 10 {
+ docIDs = docIDs[:10]
+ }
+
+ reader := getStructureReader()
+ if reader == nil {
+ return navStructEmpty(navStructReasonNoStructure, "no structure reader installed"), nil
+ }
+
+ text := strings.TrimSpace(query + " " + strings.TrimSpace(args.Keywords))
+ out, reason := navigateStructures(ctx, g.tenantID, text, docIDs, datasetIDs, args.Kind, reader)
+ _ = reason
+ return out, nil
+}
diff --git a/internal/agentic_rag/tool_navigate_structure_test.go b/internal/agentic_rag/tool_navigate_structure_test.go
new file mode 100644
index 0000000000..8b09fe78f9
--- /dev/null
+++ b/internal/agentic_rag/tool_navigate_structure_test.go
@@ -0,0 +1,284 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package agentic_rag
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+// fakeStructureReader returns canned compiled-structure rows per document.
+type fakeStructureReader struct {
+ byDoc map[string][]StructureRow
+}
+
+func (f fakeStructureReader) ReadStructure(_ context.Context, _ string, _ string, docID string) ([]StructureRow, error) {
+ return f.byDoc[docID], nil
+}
+
+func installFakeStructureReader(t *testing.T, r structureReader) {
+ t.Helper()
+ prev := getStructureReader()
+ SetStructureReader(r)
+ t.Cleanup(func() { SetStructureReader(prev) })
+}
+
+// TestNavigateStructureToolIsRegisteredAndBuildableByTemplate pins the wiring:
+// the name must be in the registry and toolsFor must build it with scope injected.
+func TestNavigateStructureToolIsRegisteredAndBuildableByTemplate(t *testing.T) {
+ if _, ok := toolRegistry()[navigateStructureToolName]; !ok {
+ t.Fatalf("%s must be registered so a template can select it", navigateStructureToolName)
+ }
+ tools := toolsFor(context.Background(), Template{ID: "nav", Tools: []string{navigateStructureToolName}}, "tenant-1", []string{"kb1"}, nil)
+ if len(tools) != 1 {
+ t.Fatalf("toolsFor returned %d tools, want 1", len(tools))
+ }
+ tool, ok := tools[0].(*NavigateStructureTool)
+ if !ok {
+ t.Fatalf("toolsFor built %T, want *NavigateStructureTool", tools[0])
+ }
+ info, err := tool.Info(context.Background())
+ if err != nil || info.Name != navigateStructureToolName {
+ t.Fatalf("tool info = %+v err=%v", info, err)
+ }
+ if tool.tenantID != "tenant-1" || len(tool.datasetIDs) != 1 || tool.datasetIDs[0] != "kb1" {
+ t.Errorf("scope = %q/%v, want tenant-1/[kb1]", tool.tenantID, tool.datasetIDs)
+ }
+}
+
+// graphRow is a canned compiled-structure "graph" blob for the drill tests.
+func graphRow() StructureRow {
+ content, _ := json.Marshal(map[string]any{
+ "entities": []map[string]any{
+ {"name": "Alpha", "type": "section", "description": "first topic", "source_chunk_ids": []string{"c1", "c2"}},
+ {"name": "Beta", "type": "subsection", "description": "second topic", "source_chunk_ids": []string{"c3"}},
+ },
+ "relations": []map[string]any{
+ {"from": "Alpha", "to": "Beta", "type": "contains"},
+ },
+ })
+ return StructureRow{KnowledgeGraphKwd: "graph", Content: string(content)}
+}
+
+// TestNavigateStructureToolDrillsStructure pins the payload: a routed document's
+// compiled structure renders as a query-focused outline with chunk pointers.
+func TestNavigateStructureToolDrillsStructure(t *testing.T) {
+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]StructureRow{
+ "d1": {graphRow()},
+ }})
+
+ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"first topic","doc_id":"d1"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ for _, want := range []string{
+ `<structure_navigation count="1" query="first topic" kind="">`,
+ `<doc rank="1" doc_id="d1"`,
+ `<structure>`,
+ "Alpha (section)",
+ "[chunks: c1,c2]",
+ `</structure>`,
+ `</structure_navigation>`,
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("output must contain %q, got:\n%s", want, out)
+ }
+ }
+}
+
+// TestNavigateStructureToolFlatFallback renders the whole outline when the query
+// carries no usable terms (the documented no-keyword fallback).
+func TestNavigateStructureToolFlatFallback(t *testing.T) {
+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]StructureRow{
+ "d1": {graphRow()},
+ }})
+
+ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"...","doc_id":"d1"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, "Alpha (section)") || !strings.Contains(out, "Beta (subsection)") {
+ t.Errorf("flat fallback must list every entity, got:\n%s", out)
+ }
+}
+
+// TestNavigateStructureToolNoDocIsAHintNotAnError: a call without a doc_id is a
+// usage-level dead end the model reads and routes first with navigate_tree.
+func TestNavigateStructureToolNoDocIsAHintNotAnError(t *testing.T) {
+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]StructureRow{}})
+
+ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"q"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, `count="0"`) {
+ t.Fatalf("missing doc_id must report count=0, got:\n%s", out)
+ }
+ if !strings.Contains(out, `error="route first with navigate_tree"`) {
+ t.Errorf("missing doc_id must explain the next step, got:\n%s", out)
+ }
+}
+
+// TestNavigateStructureToolNoStructureIsAHintNotAnError: a document without a
+// compiled structure of the requested kind is a dead end, not an abort.
+func TestNavigateStructureToolNoStructureIsAHintNotAnError(t *testing.T) {
+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]StructureRow{
+ "d1": nil, // no structure rows
+ }})
+
+ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"q","doc_id":"d1"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, `count="0"`) {
+ t.Fatalf("no structure must report count=0, got:\n%s", out)
+ }
+ if !strings.Contains(out, `error="no compiled structure for this kind"`) {
+ t.Errorf("no structure must explain the absence, got:\n%s", out)
+ }
+}
+
+// TestNavigateStructureToolRequiresQuery pins the argument contract.
+func TestNavigateStructureToolRequiresQuery(t *testing.T) {
+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]StructureRow{}})
+ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":" "}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, toolErrorMarker) {
+ t.Errorf("missing query must produce a <tool_error>, got:\n%s", out)
+ }
+}
+
+// TestNavigateStructureToolRespectsDatasetScope: an out-of-scope dataset_id is
+// rejected before any read.
+func TestNavigateStructureToolRespectsDatasetScope(t *testing.T) {
+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]StructureRow{}})
+ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"q","doc_id":"d1","dataset_ids":["rogue"]}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, toolErrorMarker) {
+ t.Errorf("out-of-scope dataset_id must produce a <tool_error>, got:\n%s", out)
+ }
+}
+
+// --- Pure-function tests (no engine, no reader) ---
+
+func TestQueryTermsTokenizes(t *testing.T) {
+ got := queryTerms("The 2023 Revenue, by Segment!")
+ want := []string{"the", "2023", "revenue", "by", "segment"}
+ if strings.Join(got, ",") != strings.Join(want, ",") {
+ t.Errorf("queryTerms = %v, want %v", got, want)
+ }
+ if len(queryTerms("a x")) != 0 { // sub-2-char tokens dropped
+ t.Errorf("sub-2-char tokens must be dropped")
+ }
+}
+
+func TestExtractJSONObjectToleratesProse(t *testing.T) {
+ v := ExtractJSON("here is the blob: {\"a\": 1, \"b\": [2,3]} trailing text")
+ m, ok := v.(map[string]any)
+ if !ok || m["a"] != float64(1) {
+ t.Errorf("ExtractJSON = %#v ok=%v", v, ok)
+ }
+ if ExtractJSON("no json here") != nil {
+ t.Errorf("ExtractJSON must return nil when no object is present")
+ }
+}
+
+// TestExtractJSONHandlesEscapedQuotes: a description carrying an escaped quote
+// (and braces) must not corrupt the brace depth and silently drop the row.
+func TestExtractJSONHandlesEscapedQuotes(t *testing.T) {
+ v := ExtractJSON(`{"a": "say \"hi\" {ok}", "b": 1}`)
+ m, ok := v.(map[string]any)
+ if !ok {
+ t.Fatalf("escaped quotes must still parse, got %#v", v)
+ }
+ if m["a"] != `say "hi" {ok}` || m["b"] != float64(1) {
+ t.Errorf("parsed = %#v", m)
+ }
+}
+
+func TestParseCompiledStructureMergesGraphBlob(t *testing.T) {
+ row := graphRow()
+ entities, relations := ParseCompiledStructure([]StructureRow{row}, nil)
+ if len(entities) != 2 || len(relations) != 1 {
+ t.Fatalf("parsed entities=%d relations=%d, want 2/1", len(entities), len(relations))
+ }
+ if entities[0]["name"] != "Alpha" || relations[0]["from"] != "Alpha" {
+ t.Errorf("unexpected parse: %v / %v", entities[0], relations[0])
+ }
+}
+
+// TestParseCompiledStructureNormalizesRequestedKind pins the filter symmetry: a
+// caller asking for kind "graph" must still match a "graph" row, even though
+// rowKind normalizes that row shape to "timeline" (and a plain string compare
+// would drop every row before parsing).
+func TestParseCompiledStructureNormalizesRequestedKind(t *testing.T) {
+ entities, relations := ParseCompiledStructure([]StructureRow{graphRow()}, []string{"graph"})
+ if len(entities) != 2 || len(relations) != 1 {
+ t.Fatalf("kind=graph must not filter out the graph row: entities=%d relations=%d", len(entities), len(relations))
+ }
+ if entities, relations := ParseCompiledStructure([]StructureRow{graphRow()}, []string{"mind_map"}); len(entities) != 0 || len(relations) != 0 {
+ t.Fatalf("an unrelated kind must still filter the row out: %d/%d", len(entities), len(relations))
+ }
+}
+
+func TestStructureGraphFromRawBuildsNodesAndRels(t *testing.T) {
+ entities, relations := ParseCompiledStructure([]StructureRow{graphRow()}, nil)
+ nodes, rels := structureGraphFromRaw(entities, relations)
+ if len(nodes) != 2 || len(rels) != 1 {
+ t.Fatalf("nodes=%d rels=%d, want 2/1", len(nodes), len(rels))
+ }
+ if nodes[0].name != "Alpha" || len(nodes[0].sourceChunkIDs) != 2 {
+ t.Errorf("node = %+v", nodes[0])
+ }
+ if rels[0].from != "Alpha" || rels[0].to != "Beta" {
+ t.Errorf("rel = %+v", rels[0])
+ }
+}
+
+func TestBuildTocTreeAndOutline(t *testing.T) {
+ entities, relations := ParseCompiledStructure([]StructureRow{graphRow()}, nil)
+ nodes, rels := structureGraphFromRaw(entities, relations)
+ byName, children, parents, roots := buildTocTree(nodes, rels)
+ if len(roots) != 1 || roots[0] != "Alpha" {
+ t.Errorf("roots = %v, want [Alpha] (Beta is a child of Alpha)", roots)
+ }
+ if len(children["Alpha"]) != 1 || children["Alpha"][0] != "Beta" {
+ t.Errorf("children[Alpha] = %v, want [Beta]", children["Alpha"])
+ }
+ if parents["Beta"] != "Alpha" {
+ t.Errorf("parents[Beta] = %q, want Alpha", parents["Beta"])
+ }
+ out := renderOutline(nodes, rels)
+ if !strings.Contains(out, "Alpha (section)") || !strings.Contains(out, "Beta (subsection)") {
+ t.Errorf("renderOutline = %q", out)
+ }
+ if !strings.Contains(out, "- Alpha -[contains]-> Beta") {
+ t.Errorf("relations must render, got:\n%s", out)
+ }
+ _ = byName
+}
diff --git a/internal/agentic_rag/tool_navigate_tree.go b/internal/agentic_rag/tool_navigate_tree.go
new file mode 100644
index 0000000000..359d9b5c48
--- /dev/null
+++ b/internal/agentic_rag/tool_navigate_tree.go
@@ -0,0 +1,235 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "strings"
+
+ einotool "github.com/cloudwego/eino/components/tool"
+ "github.com/cloudwego/eino/schema"
+ "github.com/eino-contrib/jsonschema"
+ "go.uber.org/zap"
+
+ "ragflow/internal/common"
+ "ragflow/internal/service/nav"
+)
+
+// navigateTreeToolName is the tool the model calls to route a question to the
+// documents most likely to hold the answer by descending the dataset's compiled
+// navigation tree.
+const navigateTreeToolName = "navigate_tree"
+
+const navigateTreeToolDescription = `Route a question to the documents most likely to hold the answer by descending the bound datasets' COMPILED NAVIGATION TREE (a topic->document outline built at compile time), then return the routed documents with their overall summaries.
+USE IT EARLY, before grep_chunks / search_*_chunks, when the corpus is large or you only have a TOPIC (not a distinctive verbatim phrase) — it points you at the right document(s) in ONE cheap call instead of scanning the whole corpus. It ROUTES; it does not read document content.
+Returns an XML <tree_navigation> document: a count attribute plus one <doc rank doc_id> element per routed document, each with a <summary> of that document's overall content. Feed those doc_ids to list_chunks (anchor_chunk_ids) to deep-read the routed documents.
+An empty result (<tree_navigation count="0" error="...">) means this dataset has NO compiled navigation tree (or this query routed to nothing) - the error attribute says which: "no compiled navigation tree" (structure absent - fall back to grep_chunks / search_bm25_chunks / search_semantic_chunks and do NOT retry it this round) or no attribute (structure exists, this query just missed - rephrase and retry, or fall back to the text tools).`
+
+// navigateTreeArgs is the JSON the model sends into InvokableRun.
+type navigateTreeArgs struct {
+ Query string `json:"query"`
+ Keywords string `json:"keywords,omitempty"`
+ DatasetIDs []string `json:"dataset_ids,omitempty"`
+ DocScope []string `json:"doc_scope,omitempty"`
+}
+
+// Routing/drill caps. Mirrors the harness NavigateTree bounds.
+const (
+ navTreeMaxDocs = 8 // navTreeMaxDocs: documents surfaced by navigate_tree
+ navSearchMaxDocs = 12 // navSearchMaxDocs: how many documents the router is asked for per dataset
+)
+
+// Empty-reason constants, mirroring the harness navigation contract so the model
+// sees the same signal shape it does there.
+const (
+ navTreeReasonInfra = "infra"
+ navTreeReasonBadArgs = "bad_args"
+ navTreeReasonNoStructure = "no_structure"
+ navTreeReasonNoDoc = "no_doc"
+)
+
+// NavigateTreeTool routes a question to documents via the compiled navigation
+// tree. It is stateless: the tenant and dataset scope are injected at
+// construction from the session, and the routing backend is the production
+// nav-tree service (nav.NavServiceRouter).
+type NavigateTreeTool struct {
+ tenantID string
+ datasetIDs []string
+}
+
+// NewNavigateTreeTool returns a NavigateTreeTool scoped to the given tenant and
+// datasets, implementing eino's runtime.InvokableTool.
+func NewNavigateTreeTool(tenantID string, datasetIDs []string) *NavigateTreeTool {
+ return &NavigateTreeTool{tenantID: tenantID, datasetIDs: datasetIDs}
+}
+
+// Info returns the tool's metadata for the chat model.
+func (g *NavigateTreeTool) Info(_ context.Context) (*schema.ToolInfo, error) {
+ schemaJSON := `{
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": "REQUIRED: the question (or topic) to route. Phrase it as the subject you are investigating (e.g. \"the company's 2023 revenue by segment\")."
+ },
+ "keywords": {
+ "type": "string",
+ "description": "Optional extra keywords that enrich the routing query without being required to match (free-form, comma-or-space separated)."
+ },
+ "dataset_ids": {
+ "type": "array",
+ "description": "Optional dataset ids to restrict routing to (at most 10). When omitted, the current conversation's bound datasets are used.",
+ "items": { "type": "string" },
+ "maxItems": 10
+ },
+ "doc_scope": {
+ "type": "array",
+ "description": "Optional document ids to restrict routing to (at most 10).",
+ "items": { "type": "string" },
+ "maxItems": 10
+ }
+ },
+ "required": ["query"]
+}`
+ s := &jsonschema.Schema{}
+ if err := json.Unmarshal([]byte(schemaJSON), s); err != nil {
+ return nil, fmt.Errorf("navigate_tree: parse schema: %w", err)
+ }
+ return &schema.ToolInfo{
+ Name: navigateTreeToolName,
+ Desc: navigateTreeToolDescription,
+ ParamsOneOf: schema.NewParamsOneOfByJSONSchema(s),
+ }, nil
+}
+
+// InvokableRun routes the query over the navigation tree and returns the XML
+// <tree_navigation> document.
+func (g *NavigateTreeTool) InvokableRun(ctx context.Context, argumentsInJSON string, _ ...einotool.Option) (string, error) {
+ return guardedToolRun(ctx, navigateTreeToolName, g.invokableRun, argumentsInJSON)
+}
+
+func (g *NavigateTreeTool) invokableRun(ctx context.Context, argumentsInJSON string) (string, error) {
+ var args navigateTreeArgs
+ if err := json.Unmarshal([]byte(argumentsInJSON), &args); err != nil {
+ return "", fmt.Errorf("navigate_tree: parse arguments: %w", err)
+ }
+ query := strings.TrimSpace(args.Query)
+ if query == "" {
+ return "", fmt.Errorf("navigate_tree: query is required and must be a non-empty string")
+ }
+ datasetIDs, err := resolveDatasetScope(g.datasetIDs, args.DatasetIDs)
+ if err != nil {
+ return "", fmt.Errorf("navigate_tree: %w", err)
+ }
+ if !navToolEnabled(ctx, navigateTreeToolName) {
+ // Marked unavailable for this conversation (bound datasets have no
+ // compiled navigation tree): skip the backend and return the same verdict
+ // the caller falls back from.
+ common.DebugCtx(ctx, "navigate_tree: marked unavailable; skipping backend (no compiled navigation tree)")
+ return navTreeEmpty(navTreeReasonNoStructure, "no compiled navigation tree"), nil
+ }
+ if len(datasetIDs) == 0 {
+ // Bound scope is empty: report no structure rather than reading outside
+ // the conversation's allowed datasets.
+ return navTreeEmpty(navTreeReasonNoStructure, "no bound datasets"), nil
+ }
+
+ // The router IS the retrieval backend for this tool; it is always non-nil,
+ // and reports "no compiled tree" by returning a nil slice when no NavService
+ // is installed (treated exactly like a dataset without a tree).
+ router := nav.NewNavServiceRouter()
+ full := strings.TrimSpace(query + " " + strings.TrimSpace(args.Keywords))
+
+ var (
+ ordered [][2]string
+ seen = map[string]bool{}
+ anyTree bool
+ anyError error
+ )
+ for _, kbID := range datasetIDs {
+ routed, rerr := router.Route(ctx, g.tenantID, kbID, full, args.DocScope, navSearchMaxDocs)
+ if rerr != nil {
+ anyError = rerr
+ common.DebugCtx(ctx, "navigate_tree: nav-tree descent failed",
+ zap.String("kb_id", kbID), zap.Error(rerr))
+ continue
+ }
+ if routed == nil {
+ // No compiled tree for this dataset (distinct from "routed to
+ // nothing", which is a non-nil empty slice).
+ continue
+ }
+ anyTree = true
+ for _, pair := range routed {
+ did := strings.TrimSpace(pair[0])
+ if did == "" || seen[did] {
+ continue
+ }
+ seen[did] = true
+ ordered = append(ordered, [2]string{did, strings.TrimSpace(pair[1])})
+ }
+ }
+ if !anyTree {
+ if anyError != nil {
+ // A backend failure is an INFRASTRUCTURE error, not a dataset
+ // verdict: no read succeeded, so "no structure" would be drawn from
+ // zero evidence.
+ return navTreeEmpty(navTreeReasonInfra, "nav tree descent failed"), nil
+ }
+ // No compiled tree in any bound dataset: a DATASET-level fact, so the
+ // caller falls back to the text tools. No retrieval fallback here. Record
+ // it so this conversation stops spending calls on the tool.
+ markNavToolUnavailable(ctx, navigateTreeToolName)
+ common.DebugCtx(ctx, "navigate_tree: marking unavailable for conversation (no compiled navigation tree)")
+ return navTreeEmpty(navTreeReasonNoStructure, "no compiled navigation tree"), nil
+ }
+ if len(ordered) == 0 {
+ // Structure exists but THIS query reached nothing: a query-level miss,
+ // carrying no error attribute (unlike infra/bad_args).
+ return navTreeEmpty(navTreeReasonNoDoc, ""), nil
+ }
+
+ if len(ordered) > navTreeMaxDocs {
+ ordered = ordered[:navTreeMaxDocs]
+ }
+ parts := []string{fmt.Sprintf(`<tree_navigation count="%d" query="%s">`, len(ordered), xmlEscape(query))}
+ for i, pair := range ordered {
+ if pair[1] != "" {
+ parts = append(parts,
+ fmt.Sprintf(` <doc rank="%d" doc_id="%s">`, i+1, xmlEscape(pair[0])),
+ fmt.Sprintf(" <summary>%s</summary>", xmlEscape(pair[1])),
+ " </doc>")
+ } else {
+ parts = append(parts, fmt.Sprintf(` <doc rank="%d" doc_id="%s"/>`, i+1, xmlEscape(pair[0])))
+ }
+ }
+ parts = append(parts, "</tree_navigation>")
+ return strings.Join(parts, "\n"), nil
+}
+
+// navTreeEmpty returns the empty <tree_navigation count="0"> XML carrying an
+// optional error="..." attribute, mirroring the harness navigation contract.
+func navTreeEmpty(reason, label string) string {
+ _ = reason // reason is carried semantically by the label; kept for parity with the harness constants
+ attr := ""
+ if label != "" {
+ attr = ` error="` + xmlEscape(label) + `"`
+ }
+ return "<tree_navigation count=\"0\"" + attr + ">\n</tree_navigation>"
+}
diff --git a/internal/agentic_rag/tool_navigate_tree_test.go b/internal/agentic_rag/tool_navigate_tree_test.go
new file mode 100644
index 0000000000..7cb9f592df
--- /dev/null
+++ b/internal/agentic_rag/tool_navigate_tree_test.go
@@ -0,0 +1,180 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package agentic_rag
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "ragflow/internal/service/nav"
+)
+
+// fakeNavService records the routing request and returns canned nav hits. Only
+// Search is exercised by navigate_tree; the rest satisfy the interface.
+type fakeNavService struct {
+ search func(ctx context.Context, tenantID, kbID, query string, embd []float32, docScope []string, topK int) ([]nav.NavHit, error)
+}
+
+func (f fakeNavService) UpsertDoc(context.Context, nav.UpsertDocInput) error { return nil }
+func (f fakeNavService) RemoveDoc(context.Context, string, string, string) error {
+ return nil
+}
+func (f fakeNavService) Search(ctx context.Context, tenantID, kbID, query string, embd []float32, docScope []string, topK int) ([]nav.NavHit, error) {
+ if f.search != nil {
+ return f.search(ctx, tenantID, kbID, query, embd, docScope, topK)
+ }
+ return nil, nil
+}
+func (f fakeNavService) ListClusters(context.Context, string, string, string, int, int) ([]nav.NavNode, int64, error) {
+ return nil, 0, nil
+}
+func (f fakeNavService) ListChildren(context.Context, string, string, string, string, int, int) ([]nav.NavNode, int64, error) {
+ return nil, 0, nil
+}
+func (f fakeNavService) SummariesByDocIDs(context.Context, string, string, []string) map[string]string {
+ return nil
+}
+
+func installFakeNavService(t *testing.T, svc nav.NavService) {
+ t.Helper()
+ prev := nav.GetNavService()
+ nav.SetNavService(svc)
+ t.Cleanup(func() { nav.SetNavService(prev) })
+}
+
+// TestNavigateTreeToolIsRegisteredAndBuildableByTemplate pins the wiring a
+// template needs: the name must be in the registry, and toolsFor must turn it
+// into the navigate tool with the session scope injected.
+func TestNavigateTreeToolIsRegisteredAndBuildableByTemplate(t *testing.T) {
+ if _, ok := toolRegistry()[navigateTreeToolName]; !ok {
+ t.Fatalf("%s must be registered so a template can select it", navigateTreeToolName)
+ }
+ tools := toolsFor(context.Background(), Template{ID: "nav", Tools: []string{navigateTreeToolName}}, "tenant-1", []string{"kb1"}, nil)
+ if len(tools) != 1 {
+ t.Fatalf("toolsFor returned %d tools, want 1", len(tools))
+ }
+ tool, ok := tools[0].(*NavigateTreeTool)
+ if !ok {
+ t.Fatalf("toolsFor built %T, want *NavigateTreeTool", tools[0])
+ }
+ info, err := tool.Info(context.Background())
+ if err != nil || info.Name != navigateTreeToolName {
+ t.Fatalf("tool info = %+v err=%v", info, err)
+ }
+ if tool.tenantID != "tenant-1" || len(tool.datasetIDs) != 1 || tool.datasetIDs[0] != "kb1" {
+ t.Errorf("scope = %q/%v, want tenant-1/[kb1]", tool.tenantID, tool.datasetIDs)
+ }
+}
+
+// TestNavigateTreeToolRoutesDocuments pins the payload contract: the routed
+// documents with their summaries, ordered and capped.
+func TestNavigateTreeToolRoutesDocuments(t *testing.T) {
+ installFakeNavService(t, fakeNavService{search: func(_ context.Context, _ string, _ string, _ string, _ []float32, _ []string, _ int) ([]nav.NavHit, error) {
+ return []nav.NavHit{
+ {Type: nav.TypeNavDoc, DocID: "d1", Name: "Annual Report"},
+ {Type: nav.TypeNavDoc, DocID: "d2", Name: "Quarterly Summary"},
+ }, nil
+ }})
+
+ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"2023 revenue by segment"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ for _, want := range []string{
+ `<tree_navigation count="2" query="2023 revenue by segment">`,
+ `<doc rank="1" doc_id="d1">`,
+ `<summary>Annual Report</summary>`,
+ `<doc rank="2" doc_id="d2">`,
+ `<summary>Quarterly Summary</summary>`,
+ `</tree_navigation>`,
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("output must contain %q, got:\n%s", want, out)
+ }
+ }
+}
+
+// TestNavigateTreeToolSkipsClusters: only nav_doc leaves route; a nav_cluster
+// row must never become a routed "document".
+func TestNavigateTreeToolSkipsClusters(t *testing.T) {
+ installFakeNavService(t, fakeNavService{search: func(_ context.Context, _ string, _ string, _ string, _ []float32, _ []string, _ int) ([]nav.NavHit, error) {
+ return []nav.NavHit{
+ {Type: nav.TypeNavCluster, DocID: "kb1", Name: "Finance"},
+ {Type: nav.TypeNavDoc, DocID: "d1", Name: "Annual Report"},
+ }, nil
+ }})
+
+ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"finance"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, `count="1"`) || strings.Contains(out, `doc_id="kb1"`) {
+ t.Errorf("clusters must not route, got:\n%s", out)
+ }
+}
+
+// TestNavigateTreeToolNoTreeIsAHintNotAnError: a dataset without a compiled
+// navigation tree (no NavService installed at all) is a dataset-level dead end
+// the model reads and moves on from - not a Go error that would abort the ReAct
+// loop.
+func TestNavigateTreeToolNoTreeIsAHintNotAnError(t *testing.T) {
+ installFakeNavService(t, nil) // no NavService installed -> Route returns (nil,nil)
+
+ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"q"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, `count="0"`) || !strings.Contains(out, `error="no compiled navigation tree"`) {
+ t.Errorf("no-tree must explain the absence, got:\n%s", out)
+ }
+}
+
+// TestNavigateTreeToolNoDocOnEmptyRoute: a structure that exists but routes to
+// nothing is a query-level miss carrying no error attribute.
+func TestNavigateTreeToolNoDocOnEmptyRoute(t *testing.T) {
+ installFakeNavService(t, fakeNavService{search: func(_ context.Context, _ string, _ string, _ string, _ []float32, _ []string, _ int) ([]nav.NavHit, error) {
+ return []nav.NavHit{}, nil // structure exists, nothing routed
+ }})
+
+ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":"q"}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, `count="0"`) {
+ t.Fatalf("empty route must report count=0, got:\n%s", out)
+ }
+ if strings.Contains(out, `error="`) {
+ t.Errorf("a query-level miss must carry no error attribute, got:\n%s", out)
+ }
+}
+
+// TestNavigateTreeToolRequiresQuery pins the argument contract.
+func TestNavigateTreeToolRequiresQuery(t *testing.T) {
+ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})
+ out, err := tool.InvokableRun(context.Background(), `{"query":" "}`)
+ if err != nil {
+ t.Fatalf("InvokableRun: %v", err)
+ }
+ if !strings.Contains(out, toolErrorMarker) {
+ t.Errorf("missing query must produce a <tool_error>, got:\n%s", out)
+ }
+}
diff --git a/internal/service/agentic_pipeline.go b/internal/service/agentic_pipeline.go
index 28ad09b9f5..febb9041f6 100644
--- a/internal/service/agentic_pipeline.go
+++ b/internal/service/agentic_pipeline.go
@@ -170,16 +170,17 @@ func (s *ChatPipelineService) agenticRag(
thinking := false
var reasoning strings.Builder
final, runErr := agentic_rag.Run(runCtx, agentic_rag.Input{
- Model: model,
- SynthModel: synth,
- Messages: agentMessages,
- TemplateID: mode,
- TenantID: chat.TenantID,
- DatasetIDs: chatDatasetIDs(chat),
- DocIDs: docIDs,
- Stream: stream,
- ToolCallCounts: toolCounts,
- ToolCallErrors: toolErrors,
+ Model: model,
+ SynthModel: synth,
+ Messages: agentMessages,
+ TemplateID: mode,
+ TenantID: chat.TenantID,
+ DatasetIDs: chatDatasetIDs(chat),
+ DocIDs: docIDs,
+ ConversationKey: chat.ID,
+ Stream: stream,
+ ToolCallCounts: toolCounts,
+ ToolCallErrors: toolErrors,
OnDelta: func(contentDelta, thinkingDelta string) {
reasoning.WriteString(thinkingDelta)
startToThink, endToThink := false, false