RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agentic_rag): keep compiled knowledge tools inside the turn's document scope (#21658)
ciel9a260fbee0ac
diff --git a/internal/agentic_rag/tool_doc_outline.go b/internal/agentic_rag/tool_doc_outline.goindex 09e96937f3..bf85204674 100644--- a/internal/agentic_rag/tool_doc_outline.go+++ b/internal/agentic_rag/tool_doc_outline.go@@ -146,6 +146,10 @@ func (g *GraphDocOutlineTool) invokableRun(ctx context.Context, argumentsInJSONif err != nil {return "", fmt.Errorf("graph_doc_outline: %w", err)}+ docScope, err := resolveDocumentScope(ctx, docIDs)+ if err != nil {+ return "", fmt.Errorf("graph_doc_outline: %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.@@ -156,7 +160,10 @@ func (g *GraphDocOutlineTool) invokableRun(ctx context.Context, argumentsInJSON// it. Locating here costs one BM25 pass and saves the model a whole search// call plus a second outline call carrying the doc_ids that search returned.if len(docIDs) == 0 {- docIDs = locateDocIDsForOutline(ctx, g.tenantID, datasetIDs, query)+ if docScope != nil && len(docScope) == 0 {+ return renderKgDocOutlineLocateMiss(ctx, query), nil+ }+ docIDs = locateDocIDsForOutline(ctx, g.tenantID, datasetIDs, docScope, query)if len(docIDs) == 0 {return renderKgDocOutlineLocateMiss(ctx, query), nil}@@ -242,10 +249,11 @@ func renderKgDocOutline(ctx context.Context, docIDs []string, result KgExploreRe// the model reach the compiled graph before it holds any doc_id. The pass is// lexical on purpose - that keeps the entry working on a corpus whose// embedding backend is unavailable.-func locateDocIDsForOutline(ctx context.Context, tenantID string, datasetIDs []string, query string) []string {+func locateDocIDsForOutline(ctx context.Context, tenantID string, datasetIDs, docScope []string, query string) []string {chunks, err := runtime.GetBm25Service().SearchBm25(ctx, runtime.Bm25Request{Queries: []string{query},DatasetIDs: datasetIDs,+ DocScope: docScope,TopN: graphDocOutlineLocateTopN,TenantID: tenantID,})diff --git a/internal/agentic_rag/tool_doc_outline_test.go b/internal/agentic_rag/tool_doc_outline_test.gonew file mode 100644index 0000000000..6e11875501--- /dev/null+++ b/internal/agentic_rag/tool_doc_outline_test.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 (+ "strings"+ "testing"++ "ragflow/internal/agent/runtime"+)++func TestGraphDocOutlineToolRejectsDocumentOutsideBoundScope(t *testing.T) {+ fake := &fakeKgService{}+ installFakeKgService(t, fake)++ tool := NewGraphDocOutlineTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(kgExploreContext(t), []string{"d1"})+ out, err := tool.InvokableRun(ctx, `{"query":"q","doc_ids":["d2"]}`)+ if err != nil {+ t.Fatalf("out-of-scope document must not abort the loop: %v", err)+ }+ if !strings.Contains(out, toolErrorMarker) || !strings.Contains(out, "outside the conversation") {+ t.Errorf("expected a <tool_error> naming the bound scope, got:\n%s", out)+ }+ if fake.gotOutline.DocIDs != nil {+ t.Errorf("the outline must not read for an out-of-scope document, got %+v", fake.gotOutline)+ }+}++func TestGraphDocOutlineToolKeepsInScopeDocIDs(t *testing.T) {+ fake := &fakeKgService{}+ installFakeKgService(t, fake)++ tool := NewGraphDocOutlineTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(kgExploreContext(t), []string{"d1", "d2"})+ if _, err := tool.InvokableRun(ctx, `{"query":"q","doc_ids":["d2"]}`); err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if len(fake.gotOutline.DocIDs) != 1 || fake.gotOutline.DocIDs[0] != "d2" {+ t.Errorf("outline doc ids = %v, want [d2]", fake.gotOutline.DocIDs)+ }+}++func TestGraphDocOutlineToolLocatesWithinBoundScope(t *testing.T) {+ fake := &fakeKgService{}+ installFakeKgService(t, fake)++ stub := &bm25StubService{}+ runtime.SetBm25Service(stub)+ defer runtime.SetBm25Service(nil)++ tool := NewGraphDocOutlineTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(kgExploreContext(t), []string{"d1"})+ if _, err := tool.InvokableRun(ctx, `{"query":"q"}`); err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if len(stub.lastReq.DocScope) != 1 || stub.lastReq.DocScope[0] != "d1" {+ t.Errorf("locate doc scope = %v, want [d1]", stub.lastReq.DocScope)+ }+ if fake.gotOutline.DocIDs != nil {+ t.Errorf("the outline must not read documents the locate pass did not return, got %+v", fake.gotOutline)+ }+}diff --git a/internal/agentic_rag/tool_graph_explore.go b/internal/agentic_rag/tool_graph_explore.goindex 9615bb80fd..6862edd9be 100644--- a/internal/agentic_rag/tool_graph_explore.go+++ b/internal/agentic_rag/tool_graph_explore.go@@ -132,6 +132,13 @@ func (g *GraphExploreTool) invokableRun(ctx context.Context, argumentsInJSON strif err != nil {return "", fmt.Errorf("graph_explore: %w", err)}+ docScope, err := resolveDocumentScope(ctx, args.DocScope)+ if err != nil {+ return "", fmt.Errorf("graph_explore: %w", err)+ }+ if docScope != nil && len(docScope) == 0 {+ return renderKgExplore(ctx, query, KgExploreResult{}), nil+ }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.@@ -141,7 +148,7 @@ func (g *GraphExploreTool) invokableRun(ctx context.Context, argumentsInJSON strresult, err := GetKgService().Explore(ctx, KgExploreRequest{TenantID: g.tenantID,DatasetIDs: datasetIDs,- DocScope: args.DocScope,+ DocScope: docScope,Query: query,})if err != nil {@@ -162,6 +169,7 @@ func (g *GraphExploreTool) invokableRun(ctx context.Context, argumentsInJSON strcommon.InfoCtx(ctx, "agentic_rag: graph_explore",zap.String("query", query),zap.Int("datasets", len(datasetIDs)),+ zap.Int("doc_scope", len(docScope)),zap.Int("entities", len(result.Entities)),zap.Int("relations", len(result.Relations)),zap.Int("passages", len(result.Passages)))diff --git a/internal/agentic_rag/tool_graph_explore_test.go b/internal/agentic_rag/tool_graph_explore_test.goindex 0e8dfdc9da..3a5905dd2b 100644--- a/internal/agentic_rag/tool_graph_explore_test.go+++ b/internal/agentic_rag/tool_graph_explore_test.go@@ -28,9 +28,10 @@ import (// fakeKgService records the request and returns a canned walk result.type fakeKgService struct {- gotReq KgExploreRequest- result KgExploreResult- err error+ gotReq KgExploreRequest+ gotOutline KgDocOutlineRequest+ result KgExploreResult+ err error}func (f *fakeKgService) Explore(_ context.Context, req KgExploreRequest) (KgExploreResult, error) {@@ -41,7 +42,8 @@ func (f *fakeKgService) Explore(_ context.Context, req KgExploreRequest) (KgExpl// DocOutline completes KgService. This fake only ever backs the explore tool's// tests, so it carries the fake's canned error (nil by default) and returns no// skeleton.-func (f *fakeKgService) DocOutline(context.Context, KgDocOutlineRequest) (KgExploreResult, error) {+func (f *fakeKgService) DocOutline(_ context.Context, req KgDocOutlineRequest) (KgExploreResult, error) {+ f.gotOutline = reqreturn KgExploreResult{}, f.err}@@ -552,3 +554,56 @@ func TestKgAdapterDocOutlineProbeFailureIsNotAbsence(t *testing.T) {t.Errorf("error = %v, want the probe failure", err)}}++func TestGraphExploreToolAppliesBoundDocumentScope(t *testing.T) {+ fake := &fakeKgService{}+ installFakeKgService(t, fake)++ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(kgExploreContext(t), []string{"d1"})+ if _, err := tool.InvokableRun(ctx, `{"query":"q"}`); err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if len(fake.gotReq.DocScope) != 1 || fake.gotReq.DocScope[0] != "d1" {+ t.Errorf("walk doc scope = %v, want [d1]", fake.gotReq.DocScope)+ }+}++func TestGraphExploreToolRejectsDocumentOutsideBoundScope(t *testing.T) {+ fake := &fakeKgService{}+ installFakeKgService(t, fake)++ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(kgExploreContext(t), []string{"d1"})+ out, err := tool.InvokableRun(ctx, `{"query":"q","doc_scope":["d2"]}`)+ if err != nil {+ t.Fatalf("out-of-scope document must not abort the loop: %v", err)+ }+ if !strings.Contains(out, toolErrorMarker) || !strings.Contains(out, "outside the conversation") {+ t.Errorf("expected a <tool_error> naming the bound scope, got:\n%s", out)+ }+ if fake.gotReq.Query != "" {+ t.Errorf("the walk must not run for an out-of-scope document, got %+v", fake.gotReq)+ }+}++func TestGraphExploreToolWithEmptyDocumentScopeSkipsTheWalk(t *testing.T) {+ fake := &fakeKgService{}+ installFakeKgService(t, fake)++ tool := NewGraphExploreTool("tenant-1", []string{"kb1"})+ ctx := WithConversationKey(withDocumentScope(kgExploreContext(t), []string{}), "test-graph-empty-doc-scope")+ out, err := tool.InvokableRun(ctx, `{"query":"q"}`)+ if err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if fake.gotReq.Query != "" {+ t.Errorf("an empty document scope must not reach the backend, got %+v", fake.gotReq)+ }+ if !strings.Contains(out, "<note") {+ t.Errorf("empty document scope must render an empty walk, got:\n%s", out)+ }+ if !navToolEnabled(ctx, graphExploreToolName) {+ t.Error("an empty document scope must NOT disable graph_explore")+ }+}diff --git a/internal/agentic_rag/tool_navigate_structure.go b/internal/agentic_rag/tool_navigate_structure.goindex 9311ae9866..c13da6fbad 100644--- a/internal/agentic_rag/tool_navigate_structure.go+++ b/internal/agentic_rag/tool_navigate_structure.go@@ -52,7 +52,7 @@ const navigateStructureToolName = "navigate_structure"const navigateStructureToolDescription = `Drill into documents' 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 with just a query: it routes the query over the datasets' compiled navigation trees itself, so no prior navigate_tree call is needed. To drill ONE document the model already chose, pass the doc_id from a <tree_navigation> result; that path returns the document's internal structure (entities and how they relate).Returns an XML <structure_navigation> document: one <doc> element per readable structure, each with a <structure> outline of lines "- name (type): description [chunks: c1,c2]". Feed the chunk pointers to list_chunks (anchor_chunk_ids).-An empty result (<structure_navigation count="0" error="...">) means the routed documents have NO compiled structure of the requested kind - the error attribute says which: "route first with navigate_tree" (no doc_id), or "no compiled structure for this kind" (absent in THOSE documents - fall back to grep_chunks / search_*_chunks; the verdict is per document, so the tool stays available for other documents).`+An empty result (<structure_navigation count="0" error="...">) is a verdict, and the error attribute says which: "route first with navigate_tree" (no doc_id), "no documents in the conversation scope" (the turn is restricted to no documents), or "no compiled structure for this kind" (absent in THOSE documents - 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 {@@ -102,20 +102,21 @@ const navQueryRouteDocs = 3// navStructureRoute resolves candidate doc_ids for a query when the caller// supplied no doc_id. It is the same navigation-tree router navigate_tree uses,// so a query-only call and the explicit two-step path rank documents identically.-var navStructureRoute = func(ctx context.Context, tenantID, kbID, query string, limit int) ([][2]string, error) {- return nav.NewNavServiceRouter().Route(ctx, tenantID, kbID, query, nil, limit)+var navStructureRoute = func(ctx context.Context, tenantID, kbID, query string, docScope []string, limit int) ([][2]string, error) {+ return nav.NewNavServiceRouter().Route(ctx, tenantID, kbID, query, docScope, limit)}// routeDocIDsForQuery routes the query across the bound datasets and returns the-// top doc_ids, deduped across datasets and capped at limit.-func routeDocIDsForQuery(ctx context.Context, tenantID, query string, datasetIDs []string, limit int) []string {+// top doc_ids, deduped across datasets and capped at limit. docScope is pushed+// into the route so the ranking budget is spent inside the turn's documents.+func routeDocIDsForQuery(ctx context.Context, tenantID, query string, datasetIDs, docScope []string, limit int) []string {if limit <= 0 {limit = navQueryRouteDocs}seen := map[string]bool{}var out []stringfor _, kbID := range datasetIDs {- routed, err := navStructureRoute(ctx, tenantID, kbID, query, limit)+ routed, err := navStructureRoute(ctx, tenantID, kbID, query, docScope, limit)if err != nil {common.DebugCtx(ctx, "navigate_structure: query route failed",zap.String("kb_id", kbID), zap.Error(err))@@ -994,13 +995,24 @@ func (g *NavigateStructureTool) invokableRun(ctx context.Context, argumentsInJSOif len(docIDs) == 0 && args.DocID != "" {docIDs = []string{args.DocID}}+ if len(docIDs) > 0 {+ docIDs, err = resolveDocumentScope(ctx, docIDs)+ if err != nil {+ return "", fmt.Errorf("navigate_structure: %w", err)+ }+ }+ // An empty scope allows no documents at all, and the route reads a nil/empty+ // docScope as "the whole dataset", so answer before touching the backend.+ docScope, _ := resolveDocumentScope(ctx, nil)+ if docScope != nil && len(docScope) == 0 {+ return navStructEmpty("no documents in the conversation scope"), nil+ }// A doc_id is optional: with none, route the query ourselves so the tool is- // usable in one call.+ // usable in one call. The route carries the scope so the ranking budget is+ // spent inside the turn's documents.routedByQuery := falseif len(docIDs) == 0 {- // The router ranks the whole bound corpus, so a turn restricted to a set- // of documents must intersect here.- docIDs = intersectDocumentScope(ctx, routeDocIDsForQuery(ctx, g.tenantID, text, datasetIDs, navQueryRouteDocs))+ docIDs = routeDocIDsForQuery(ctx, g.tenantID, text, datasetIDs, docScope, navQueryRouteDocs)if len(docIDs) == 0 {return navStructEmpty("route first with navigate_tree"), nil}diff --git a/internal/agentic_rag/tool_navigate_structure_test.go b/internal/agentic_rag/tool_navigate_structure_test.goindex cb7dfb4f28..c0fc623ce3 100644--- a/internal/agentic_rag/tool_navigate_structure_test.go+++ b/internal/agentic_rag/tool_navigate_structure_test.go@@ -362,13 +362,55 @@ func TestClaimOutlineLineCarriesHandle(t *testing.T) {// --- Query-only route (the tool must be usable in one call) ----func installFakeStructureRoute(t *testing.T, docs [][2]string) {+func installFakeStructureRoute(t *testing.T, docs [][2]string) *[]string {t.Helper()+ var gotScope []stringprev := navStructureRoute- navStructureRoute = func(context.Context, string, string, string, int) ([][2]string, error) {+ navStructureRoute = func(_ context.Context, _, _, _ string, docScope []string, _ int) ([][2]string, error) {+ gotScope = docScopereturn docs, nil}t.Cleanup(func() { navStructureRoute = prev })+ return &gotScope+}++// TestNavigateStructureQueryOnlyAppliesBoundDocumentScope: a query-only call must+// rank inside the turn's documents, so the router has to receive the scope. An+// in-memory intersect after the route cannot recover a slot spent on an+// out-of-scope document.+func TestNavigateStructureQueryOnlyAppliesBoundDocumentScope(t *testing.T) {+ scope := installFakeStructureRoute(t, [][2]string{{"d1", ""}})+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]structureRow{"d1": {graphRow()}}})++ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(context.Background(), []string{"d1"})+ if _, err := tool.InvokableRun(ctx, `{"query":"q"}`); err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if len(*scope) != 1 || (*scope)[0] != "d1" {+ t.Errorf("route doc scope = %v, want [d1]", *scope)+ }+}++// TestNavigateStructureQueryOnlyWithEmptyDocumentScopeSkipsTheRoute: an empty+// scope allows no documents, so the call must answer before touching the router+// (the router reads an empty scope as "the whole dataset").+func TestNavigateStructureQueryOnlyWithEmptyDocumentScopeSkipsTheRoute(t *testing.T) {+ scope := installFakeStructureRoute(t, [][2]string{{"d1", ""}})+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]structureRow{"d1": {graphRow()}}})++ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})+ ctx := WithConversationKey(withDocumentScope(context.Background(), []string{}), "test-nav-structure-empty-doc-scope")+ out, err := tool.InvokableRun(ctx, `{"query":"q"}`)+ if err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if *scope != nil {+ t.Error("an empty document scope must not reach the router")+ }+ if !strings.Contains(out, `count="0"`) || !strings.Contains(out, "no documents in the conversation scope") {+ t.Errorf("empty document scope must report the scope, got:\n%s", out)+ }}// TestNavigateStructureQueryOnlyNoRouteKeepsTheOldHint: when routing finds nothing@@ -523,3 +565,38 @@ func TestParseClaimSupport(t *testing.T) {t.Errorf("reply without a supported field must fail open, got %+v", missingField)}}++func TestNavigateStructureToolRejectsDocumentOutsideBoundScope(t *testing.T) {+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]structureRow{+ "d1": {graphRow()},+ }})++ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(context.Background(), []string{"d1"})+ out, err := tool.InvokableRun(ctx, `{"query":"q","doc_ids":["d2"]}`)+ if err != nil {+ t.Fatalf("out-of-scope document must not abort the loop: %v", err)+ }+ if !strings.Contains(out, toolErrorMarker) || !strings.Contains(out, "outside the conversation") {+ t.Errorf("expected a <tool_error> naming the bound scope, got:\n%s", out)+ }+ if strings.Contains(out, "<structure_navigation") {+ t.Errorf("an out-of-scope document must not be read, got:\n%s", out)+ }+}++func TestNavigateStructureToolReadsOnlyTheBoundDocument(t *testing.T) {+ installFakeStructureReader(t, fakeStructureReader{byDoc: map[string][]structureRow{+ "d1": {graphRow()},+ }})++ tool := NewNavigateStructureTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(context.Background(), []string{"d1"})+ out, err := tool.InvokableRun(ctx, `{"query":"q","doc_ids":["d1"]}`)+ if err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if !strings.Contains(out, "Alpha (section)") {+ t.Errorf("the bound document must still be readable, got:\n%s", out)+ }+}diff --git a/internal/agentic_rag/tool_navigate_tree.go b/internal/agentic_rag/tool_navigate_tree.goindex 99eb64c47b..174a7a4de6 100644--- a/internal/agentic_rag/tool_navigate_tree.go+++ b/internal/agentic_rag/tool_navigate_tree.go@@ -148,6 +148,13 @@ func (g *NavigateTreeTool) invokableRun(ctx context.Context, argumentsInJSON strcommon.DebugCtx(ctx, "navigate_tree: marked unavailable; skipping backend (no compiled navigation tree)")return navTreeEmpty(navTreeReasonNoStructure, "no compiled navigation tree"), nil}+ docScope, err := resolveDocumentScope(ctx, args.DocScope)+ if err != nil {+ return "", fmt.Errorf("navigate_tree: %w", err)+ }+ if docScope != nil && len(docScope) == 0 {+ return navTreeEmpty(navTreeReasonNoDoc, ""), nil+ }if len(datasetIDs) == 0 {// Bound scope is empty: report no structure rather than reading outside// the conversation's allowed datasets.@@ -167,7 +174,7 @@ func (g *NavigateTreeTool) invokableRun(ctx context.Context, argumentsInJSON stranyError error)for _, kbID := range datasetIDs {- routed, rerr := router.Route(ctx, g.tenantID, kbID, full, args.DocScope, navSearchMaxDocs)+ routed, rerr := router.Route(ctx, g.tenantID, kbID, full, docScope, navSearchMaxDocs)if rerr != nil {anyError = rerrcommon.DebugCtx(ctx, "navigate_tree: nav-tree descent failed",@@ -222,6 +229,7 @@ func (g *NavigateTreeTool) invokableRun(ctx context.Context, argumentsInJSON strcommon.InfoCtx(ctx, "agentic_rag: navigate_tree",zap.String("query", query),zap.Int("datasets", len(datasetIDs)),+ zap.Int("doc_scope", len(docScope)),zap.Int("docs", len(ordered)),zap.Strings("names", names))parts := []string{fmt.Sprintf(`<tree_navigation count="%d" query="%s">`, len(ordered), xmlEscape(query))}diff --git a/internal/agentic_rag/tool_navigate_tree_test.go b/internal/agentic_rag/tool_navigate_tree_test.goindex 0e50bcf01a..37874d9c21 100644--- a/internal/agentic_rag/tool_navigate_tree_test.go+++ b/internal/agentic_rag/tool_navigate_tree_test.go@@ -185,3 +185,65 @@ func TestNavigateTreeToolRequiresQuery(t *testing.T) {t.Errorf("missing query must produce a <tool_error>, got:\n%s", out)}}++func TestNavigateTreeToolAppliesBoundDocumentScope(t *testing.T) {+ var gotDocScope []string+ installFakeNavService(t, fakeNavService{search: func(_ context.Context, _ string, _ string, _ string, _ []float32, docScope []string, _ int) ([]nav.NavHit, error) {+ gotDocScope = docScope+ return []nav.NavHit{{Type: nav.TypeNavDoc, DocID: "d1", Name: "Annual Report"}}, nil+ }})++ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(context.Background(), []string{"d1"})+ if _, err := tool.InvokableRun(ctx, `{"query":"q"}`); err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if len(gotDocScope) != 1 || gotDocScope[0] != "d1" {+ t.Errorf("route doc scope = %v, want [d1]", gotDocScope)+ }+}++func TestNavigateTreeToolRejectsDocumentOutsideBoundScope(t *testing.T) {+ called := false+ installFakeNavService(t, fakeNavService{search: func(_ context.Context, _ string, _ string, _ string, _ []float32, _ []string, _ int) ([]nav.NavHit, error) {+ called = true+ return nil, nil+ }})++ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})+ ctx := withDocumentScope(context.Background(), []string{"d1"})+ out, err := tool.InvokableRun(ctx, `{"query":"q","doc_scope":["d2"]}`)+ if err != nil {+ t.Fatalf("out-of-scope document must not abort the loop: %v", err)+ }+ if !strings.Contains(out, toolErrorMarker) || !strings.Contains(out, "outside the conversation") {+ t.Errorf("expected a <tool_error> naming the bound scope, got:\n%s", out)+ }+ if called {+ t.Error("the route must not run for an out-of-scope document")+ }+}++func TestNavigateTreeToolWithEmptyDocumentScopeSkipsTheRoute(t *testing.T) {+ called := false+ installFakeNavService(t, fakeNavService{search: func(_ context.Context, _ string, _ string, _ string, _ []float32, _ []string, _ int) ([]nav.NavHit, error) {+ called = true+ return []nav.NavHit{{Type: nav.TypeNavDoc, DocID: "d1"}}, nil+ }})++ tool := NewNavigateTreeTool("tenant-1", []string{"kb1"})+ ctx := WithConversationKey(withDocumentScope(context.Background(), []string{}), "test-nav-tree-empty-doc-scope")+ out, err := tool.InvokableRun(ctx, `{"query":"q"}`)+ if err != nil {+ t.Fatalf("InvokableRun: %v", err)+ }+ if called {+ t.Error("an empty document scope must not reach the router")+ }+ if !strings.Contains(out, `<tree_navigation count="0"`) {+ t.Errorf("empty document scope must render count=0, got:\n%s", out)+ }+ if !navToolEnabled(ctx, navigateTreeToolName) {+ t.Error("an empty document scope must NOT disable navigate_tree")+ }+}