π The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
fix(graph): report k-hop relation and depth limitations
Rudy Celekli72d2c10c7842
diff --git a/v3/@claude-flow/cli/__tests__/graph-query-3202.test.ts b/v3/@claude-flow/cli/__tests__/graph-query-3202.test.tsnew file mode 100644index 0000000000..330f601005--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/graph-query-3202.test.ts@@ -0,0 +1,100 @@+/** Regression for #3202: k-hop relation and depth must describe the executed query. */+import { beforeEach, describe, expect, it, vi } from 'vitest';++const backend = vi.hoisted(() => ({+ available: vi.fn(async () => true),+ neighbors: vi.fn(async () => ['unfiltered-neighbor']),+ getBridgeDb: vi.fn(),+ prepare: vi.fn(),+}));++vi.mock('../src/ruvector/graph-backend.js', () => ({+ isGraphBackendAvailable: backend.available,+ getNeighbors: backend.neighbors,+}));+vi.mock('../src/memory/graph-edge-writer.js', () => ({ getBridgeDb: backend.getBridgeDb }));+vi.mock('../src/mcp-tools/validate-input.js', () => ({+ validateIdentifier: () => ({ valid: true }),+ validateText: (value: unknown) => value,+}));++import { agentdbGraphQuery } from '../src/mcp-tools/agentdb-tools.js';++type Result = {+ success: boolean;+ error?: string;+ unsupported?: string;+ depth?: number;+ appliedDepth?: number;+ truncated?: boolean;+ backend?: string;+ results?: Array<{ nodeId: string; depth?: number }>;+};++async function query(params: Record<string, unknown>): Promise<Result> {+ return agentdbGraphQuery.handler({ nodeId: 'start', mode: 'k-hop', ...params }) as Promise<Result>;+}++describe('#3202 graph k-hop execution contract', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ backend.available.mockResolvedValue(true);+ backend.neighbors.mockResolvedValue(['unfiltered-neighbor']);+ backend.prepare.mockImplementation(() => ({ raw: () => ({ all: () => [['filtered-neighbor', 3]] }) }));+ backend.getBridgeDb.mockResolvedValue({ prepare: backend.prepare });+ });++ it('uses native graph at the requested depth for an unfiltered query', async () => {+ const result = await query({ depth: 5 });+ expect(backend.neighbors).toHaveBeenCalledWith('start', 5);+ expect(backend.getBridgeDb).not.toHaveBeenCalled();+ expect(result).toMatchObject({ success: true, backend: 'graph-node', depth: 5, appliedDepth: 5 });+ expect(result.truncated).not.toBe(true);+ });++ it('refuses a relation filter on native graph rather than silently returning unfiltered neighbors', async () => {+ const result = await query({ depth: 5, relation: 'depends-on' });+ expect(backend.neighbors).not.toHaveBeenCalled();+ expect(backend.getBridgeDb).not.toHaveBeenCalled();+ expect(result).toMatchObject({ success: false, backend: 'graph-node', unsupported: 'relation' });+ expect(result.error).toMatch(/does not support relation filtering/i);+ });++ it('filters on SQL when native graph is unavailable and discloses the depth-3 bound', async () => {+ backend.available.mockResolvedValue(false);+ const result = await query({ depth: 5, relation: 'depends-on' });+ expect(backend.neighbors).not.toHaveBeenCalled();+ expect(backend.prepare).toHaveBeenCalledTimes(1);+ const sql = backend.prepare.mock.calls[0][0] as string;+ expect(sql).toContain("e.relation = 'depends-on'");+ expect(sql).toContain('k.hop_depth < 3');+ expect(result).toMatchObject({+ success: true, backend: 'sql-cte', depth: 5, appliedDepth: 3, truncated: true,+ results: [{ nodeId: 'filtered-neighbor', depth: 3 }],+ });+ });++ it('does not claim a relation-filtered success when neither backend can answer', async () => {+ backend.available.mockResolvedValue(false);+ backend.getBridgeDb.mockResolvedValue(null);+ const result = await query({ relation: 'depends-on' });+ expect(backend.neighbors).not.toHaveBeenCalled();+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/relation-filtered.*SQL graph_edges/i);+ });++ it('discloses SQL depth truncation even without a relation filter', async () => {+ backend.available.mockResolvedValue(false);+ const result = await query({ depth: 5 });+ expect(result).toMatchObject({ success: true, backend: 'sql-cte', depth: 5, appliedDepth: 3, truncated: true });+ });++ it('reports no truncation when SQL runs the full requested depth', async () => {+ backend.available.mockResolvedValue(false);+ const result = await query({ depth: 2 });+ const sql = backend.prepare.mock.calls[0][0] as string;+ expect(sql).toContain('k.hop_depth < 2');+ expect(result).toMatchObject({ success: true, backend: 'sql-cte', depth: 2, appliedDepth: 2 });+ expect(result.truncated).not.toBe(true);+ });+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.tsindex de015c9222..c421b5674a 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts@@ -1027,7 +1027,7 @@ interface ComplexityBudget {export const agentdbGraphQuery: MCPTool = {name: 'agentdb_graph-query',- description: 'Unified graph traversal across the knowledge graph (ADR-130). Dispatches to the most capable backend: graph-node native for k-hop, sql.js CTE for fallback, HNSW cosine for semantic, ruflo-graph-intelligence PageRank for pagerank mode. Use when you need structured graph traversal beyond flat memory search.',+ description: 'Unified graph traversal across the knowledge graph (ADR-130). Native graph-node k-hop cannot filter by relation and returns an explicit unsupported error for that request; the SQL fallback can filter by relation. Inspect appliedDepth/truncated because SQL is bounded at 3 hops. Semantic and PageRank modes use their own backends. Use when you need structured graph traversal beyond flat memory search.',inputSchema: {type: 'object',properties: {@@ -1037,7 +1037,7 @@ export const agentdbGraphQuery: MCPTool = {enum: ['k-hop', 'semantic', 'pagerank'],description: 'Query mode: k-hop neighbor expansion, semantic cosine search, or PageRank scoring',},- depth: { type: 'number', description: 'Hop depth for k-hop mode (default 2, max 5)' },+ depth: { type: 'number', description: 'Requested k-hop depth (default 2, max 5); SQL responses report appliedDepth and truncated when limited to 3' },topK: { type: 'number', description: 'Max results for semantic and pagerank modes (default 10)' },relation: { type: 'string', description: 'Optional edge relation filter' },complexityBudget: {@@ -1079,34 +1079,43 @@ export const agentdbGraphQuery: MCPTool = {// ββ k-hop mode ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif (mode === 'k-hop') {- // Try graph-node native first+ // graph-node's kHopNeighbors API has no relation parameter. Its graph+ // and the SQL graph are separate stores, and SQL writes can be async;+ // switching stores here could report a false negative. Refuse the+ // unsupported native query instead of silently widening it.try {const graphBackend = await getGraphBackend();if (await graphBackend.isGraphBackendAvailable()) {+ if (relation) {+ return { success: false, error: 'Native graph-node k-hop does not support relation filtering', unsupported: 'relation', mode, nodeId, relation, backend: 'graph-node' };+ }const neighbors = await graphBackend.getNeighbors(nodeId, depth);return {- success: true, mode, nodeId, depth,+ success: true, mode, nodeId, depth, appliedDepth: depth,results: neighbors.map(id => ({ nodeId: id })),count: neighbors.length,backend: 'graph-node',elapsedMs: Date.now() - t0,};}- } catch { /* fall through to sql.js */ }+ } catch { /* fall through to SQL */ }- // SQL CTE fallback for k-hop up to depth 3+ // SQL CTE fallback is bounded at depth 3. Report that bound so callers+ // cannot mistake an incomplete depth-5 cycle check for a complete one.try {const { getBridgeDb } = await getGraphEdgeWriter();const db = await getBridgeDb();if (db) {- const cteSql = buildKHopCTE(nodeId, Math.min(depth, 3), relation, budget.maxNodesVisited);+ const appliedDepth = Math.min(depth, 3);+ const cteSql = buildKHopCTE(nodeId, appliedDepth, relation, budget.maxNodesVisited);// graph-edge-writer returns a better-sqlite3 Database after #2431.// `db.exec(sql, params)` (sql.js style) is a runner with no result// on better-sqlite3 β use `prepare(sql).raw().all(...)` to get the// same array-of-arrays shape the downstream code expects.const rows = db.prepare(cteSql).raw().all() as unknown[][];return {- success: true, mode, nodeId, depth,+ success: true, mode, nodeId, depth, appliedDepth,+ ...(appliedDepth < depth ? { truncated: true } : {}),results: rows.map((r: unknown[]) => ({ nodeId: r[0], depth: r[1] })),count: rows.length,backend: 'sql-cte',@@ -1115,6 +1124,9 @@ export const agentdbGraphQuery: MCPTool = {}} catch { /* db unavailable */ }+ if (relation) {+ return { success: false, error: 'Relation-filtered k-hop query requires the SQL graph_edges backend', mode, nodeId, relation };+ }return { success: false, error: 'No graph backend available for k-hop query', mode, nodeId };}