refactor(agent): fix grep scope loss and consolidate per-turn @mention scoping

- Fix grep_chunks dropping the full-KB scope when a turn mixes @KB with
  @tag/@file: extract scopeClause and OR knowledge-ID and (kb,tenant)
  predicates together, matching knowledge_search's fan-out.
- Consolidate the three scattered per-request @Skill/@MCP scope blocks in
  buildAgentConfig into applyPerRequestSkillScope / applyPerRequestMCPScope,
  each narrowing the whitelist and computing the must_use pin in one place.
- Dedupe the two identical selection-mode normalizers in Input-field.vue.
- Fix knowledge_create_test passing "" for the tagIDs []string parameter,
  which made the whole service test package fail to compile.
- Add unit tests for scopeClause and the per-request scope helpers.
This commit is contained in:
wizardchen
2026-06-29 17:17:38 +08:00
committed by lyingbug
parent b86efe3f92
commit d24e830c85
6 changed files with 203 additions and 83 deletions
+34 -19
View File
@@ -319,6 +319,31 @@ func (t *GrepChunksTool) listKnowledgeIDsByTags(
return ids, err
}
// scopeClause builds the SQL predicate restricting chunks to the active scope.
// Specific knowledge IDs and full-KB (kb, tenant) pairs are OR'd together so a
// turn that mentions both an entire KB and a tag/file in another KB searches
// every requested scope. Returns ("", nil) when no usable scope exists.
func scopeClause(kbIDs, knowledgeIDs []string, kbTenantMap map[string]uint64) (string, []interface{}) {
var clauses []string
var args []interface{}
if len(knowledgeIDs) > 0 {
clauses = append(clauses, "chunks.knowledge_id IN ?")
args = append(args, knowledgeIDs)
}
for _, kbID := range kbIDs {
tenantID := kbTenantMap[kbID]
if tenantID == 0 {
continue
}
clauses = append(clauses, "(chunks.knowledge_base_id = ? AND chunks.tenant_id = ?)")
args = append(args, kbID, tenantID)
}
if len(clauses) == 0 {
return "", nil
}
return "(" + strings.Join(clauses, " OR ") + ")", args
}
// searchChunks performs the database search using regex queries.
func (t *GrepChunksTool) searchChunks(
ctx context.Context,
@@ -343,26 +368,16 @@ func (t *GrepChunksTool) searchChunks(
Where("chunks.deleted_at IS NULL").
Where("knowledges.deleted_at IS NULL")
if len(knowledgeIDs) > 0 {
query = query.Where("chunks.knowledge_id IN ?", knowledgeIDs)
logger.Infof(ctx, "[Tool][GrepChunks] Filtering by %d specific knowledge IDs", len(knowledgeIDs))
} else if len(kbIDs) > 0 {
var conditions []string
var args []interface{}
for _, kbID := range kbIDs {
tenantID := kbTenantMap[kbID]
if tenantID > 0 {
conditions = append(conditions, "(chunks.knowledge_base_id = ? AND chunks.tenant_id = ?)")
args = append(args, kbID, tenantID)
}
}
if len(conditions) > 0 {
query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
} else {
logger.Warnf(ctx, "[Tool][GrepChunks] No valid KB-tenant pairs found")
return nil, nil
}
// Combine specific knowledge IDs (incl. tag-resolved docs) and full-KB scopes
// with OR so that mixing @KB with @tag/@file searches BOTH, mirroring
// knowledge_search's concurrent fan-out instead of dropping one side.
scopeSQL, scopeArgs := scopeClause(kbIDs, knowledgeIDs, kbTenantMap)
if scopeSQL == "" {
logger.Warnf(ctx, "[Tool][GrepChunks] No valid scope (kb-tenant pairs / knowledge IDs)")
return nil, nil
}
logger.Infof(ctx, "[Tool][GrepChunks] Scope: %d knowledge IDs, %d KBs", len(knowledgeIDs), len(kbIDs))
query = query.Where(scopeSQL, scopeArgs...)
// For MySQL/SQLite REGEXP case-insensitivity we rely on the column's default
// collation (utf8mb4_general_ci etc.) OR the driver's REGEXP implementation,
@@ -0,0 +1,49 @@
package tools
import (
"strings"
"testing"
)
func TestScopeClause_KnowledgeAndFullKBOredTogether(t *testing.T) {
sql, args := scopeClause(
[]string{"kb-1"},
[]string{"doc-9"},
map[string]uint64{"kb-1": 7},
)
if !strings.Contains(sql, "chunks.knowledge_id IN ?") {
t.Fatalf("expected knowledge-id predicate, got %q", sql)
}
if !strings.Contains(sql, "chunks.knowledge_base_id = ? AND chunks.tenant_id = ?") {
t.Fatalf("expected kb-tenant predicate, got %q", sql)
}
if !strings.Contains(sql, " OR ") {
t.Fatalf("expected the two scopes to be OR'd, got %q", sql)
}
// args: knowledgeIDs slice + kbID + tenantID
if len(args) != 3 {
t.Fatalf("expected 3 args, got %d: %v", len(args), args)
}
}
func TestScopeClause_SkipsKBWithoutTenant(t *testing.T) {
sql, args := scopeClause(
[]string{"kb-1", "kb-2"},
nil,
map[string]uint64{"kb-1": 7}, // kb-2 has no tenant mapping
)
if strings.Contains(sql, "kb-2") {
t.Fatalf("kb-2 has no tenant and must be skipped, got %q", sql)
}
if len(args) != 2 {
t.Fatalf("expected only kb-1 (2 args), got %d: %v", len(args), args)
}
}
func TestScopeClause_EmptyWhenNoUsableScope(t *testing.T) {
sql, args := scopeClause([]string{"kb-1"}, nil, map[string]uint64{})
if sql != "" || args != nil {
t.Fatalf("expected empty scope, got sql=%q args=%v", sql, args)
}
}