π 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): query retained SQL relationships for k-hop
Rudy Celeklie88ce4702fb1
diff --git a/v3/@claude-flow/cli/__tests__/graph-query-3202.test.ts b/v3/@claude-flow/cli/__tests__/graph-query-3202.test.tsindex 330f601005..fcbe432d3e 100644--- a/v3/@claude-flow/cli/__tests__/graph-query-3202.test.ts+++ b/v3/@claude-flow/cli/__tests__/graph-query-3202.test.ts@@ -44,20 +44,19 @@ describe('#3202 graph k-hop execution contract', () => {backend.getBridgeDb.mockResolvedValue({ prepare: backend.prepare });});- it('uses native graph at the requested depth for an unfiltered query', async () => {+ it('reads retained SQL even when the separate native graph is available', 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);+ expect(backend.neighbors).not.toHaveBeenCalled();+ expect(backend.getBridgeDb).toHaveBeenCalled();+ expect(result).toMatchObject({ success: true, backend: 'sql-cte', depth: 5, appliedDepth: 3, truncated: true });});- it('refuses a relation filter on native graph rather than silently returning unfiltered neighbors', async () => {+ it('applies a relation filter to retained SQL regardless of native availability', 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);+ expect(backend.getBridgeDb).toHaveBeenCalled();+ expect(result).toMatchObject({ success: true, backend: 'sql-cte' });+ expect(backend.prepare.mock.calls[0][0]).toContain("e.relation = 'depends-on'");});it('filters on SQL when native graph is unavailable and discloses the depth-3 bound', async () => {@@ -80,7 +79,7 @@ describe('#3202 graph k-hop execution contract', () => {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);+ expect(result.error).toMatch(/retained SQL graph_edges/i);});it('discloses SQL depth truncation even without a relation filter', async () => {diff --git a/v3/@claude-flow/cli/__tests__/graph-retained-sql-3315.test.ts b/v3/@claude-flow/cli/__tests__/graph-retained-sql-3315.test.tsnew file mode 100644index 0000000000..3c6b345156--- /dev/null+++ b/v3/@claude-flow/cli/__tests__/graph-retained-sql-3315.test.ts@@ -0,0 +1,72 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import initSqlJs from 'sql.js';+const mocks = vi.hoisted(() => ({ getDb: vi.fn(), available: vi.fn(), neighbors: vi.fn() }));+vi.mock('../src/memory/graph-edge-writer.js', () => ({ getBridgeDb: mocks.getDb }));+vi.mock('../src/ruvector/graph-backend.js', () => ({ isGraphBackendAvailable: mocks.available, getNeighbors: mocks.neighbors }));+import { agentdbGraphQuery } from '../src/mcp-tools/agentdb-tools.js';+// The default suite uses required sql.js. Set RUFLO_TEST_SQLITE_DRIVER=native+// to run the same contract against optional better-sqlite3, without silent skips.+let createDb: () => any;+let db: any;+beforeAll(async () => {+ if (process.env.RUFLO_TEST_SQLITE_DRIVER === 'native') {+ const { default: Database } = await import('better-sqlite3');+ createDb = () => {+ const native = new Database(':memory:');+ return { run: (sql: string) => native.exec(sql), exec: (sql: string) => [{ values: native.prepare(sql).raw().all() }], close: () => native.close() };+ };+ } else {+ const SQL = await initSqlJs();+ createDb = () => new SQL.Database();+ }+});+beforeEach(() => {+ vi.clearAllMocks();+ db = createDb();+ db.run('CREATE TABLE graph_edges(source_id TEXT, target_id TEXT, relation TEXT)');+ db.run("INSERT INTO graph_edges VALUES ('a','b','depends-on'),('a','c','related'),('b','d','depends-on'),('d','a','depends-on'),('c','e','related')");+ mocks.getDb.mockResolvedValue({ prepare: (sql: string) => ({ raw: () => ({ all: () => db.exec(sql)[0]?.values ?? [] }) }) });+ mocks.available.mockResolvedValue(true);+ mocks.neighbors.mockResolvedValue(['a']);+});+afterEach(() => db.close());+const query = (params = {}) => agentdbGraphQuery.handler({ nodeId: 'a', mode: 'k-hop', ...params }) as Promise<any>;++describe('retained SQL k-hop graph (#3315)', () => {+ it.each([{ native: [] }, { native: ['a'] }, { native: ['unrelated-native-node'] }])('does not let native contents $native hide retained relationships', async ({ native }) => {+ mocks.neighbors.mockResolvedValue(native);+ const before = db.exec('SELECT * FROM graph_edges');+ const result = await query();+ expect(result).toMatchObject({ success: true, backend: 'sql-cte', results: [+ { nodeId: 'b', depth: 1 }, { nodeId: 'c', depth: 1 }, { nodeId: 'd', depth: 2 }, { nodeId: 'e', depth: 2 },+ ] });+ expect(mocks.available).not.toHaveBeenCalled();+ expect(mocks.neighbors).not.toHaveBeenCalled();+ expect(db.exec('SELECT * FROM graph_edges')).toEqual(before);+ });+ it('applies the relation on every hop and excludes the seed in a cycle', async () => {+ const result = await query({ relation: 'depends-on', depth: 3 });+ expect(result.results).toEqual([{ nodeId: 'b', depth: 1 }, { nodeId: 'd', depth: 2 }]);+ });+ it('discloses depth and returned-row bounds', async () => {+ const result = await query({ depth: 5, complexityBudget: { maxNodesVisited: 1 } });+ expect(result).toMatchObject({ success: true, requestedDepth: 5, appliedDepth: 3, depthLimited: true, resultLimitReached: true, truncated: true, count: 1 });+ });+ it('escapes exact relation values and bounds invalid budgets', async () => {+ db.run("INSERT INTO graph_edges VALUES ('a','quoted','isn''t-related')");+ const result = await query({ relation: "isn't-related", complexityBudget: { maxNodesVisited: -1, maxDepth: -1 } });+ expect(result).toMatchObject({ success: true, resultLimit: 10000, appliedDepth: 2, truncated: false, results: [{ nodeId: 'quoted', depth: 1 }] });+ });+ it('returns empty for an empty SQL graph rather than fabricating the seed', async () => {+ db.run('DELETE FROM graph_edges');+ expect(await query()).toMatchObject({ success: true, results: [], count: 0 });+ });+ it.each(['missing', 'unreadable'])('fails explicitly when retained SQL is %s', async (failure) => {+ if (failure === 'missing') mocks.getDb.mockResolvedValue(null);+ else mocks.getDb.mockRejectedValue(new Error('database unreadable'));+ const result = await query();+ expect(result.success).toBe(false);+ expect(result.error).toMatch(/SQL|retained/i);+ expect(mocks.neighbors).not.toHaveBeenCalled();+ });+});diff --git a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.tsindex c421b5674a..89206836a4 100644--- a/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts+++ b/v3/@claude-flow/cli/src/mcp-tools/agentdb-tools.ts@@ -72,11 +72,6 @@ async function getBridge() {// Lazy-cached modules used by graph-query / graph-pathfinder dispatch.// Caching the resolved namespace avoids per-call dynamic-import overhead// in the ADR-130 hot path (smoke harness measures elapsedMs of every call).-let graphBackendMod: typeof import('../ruvector/graph-backend.js') | null = null;-async function getGraphBackend() {- if (!graphBackendMod) graphBackendMod = await import('../ruvector/graph-backend.js');- return graphBackendMod;-}let graphEdgeWriterMod: typeof import('../memory/graph-edge-writer.js') | null = null;async function getGraphEdgeWriter() {if (!graphEdgeWriterMod) graphEdgeWriterMod = await import('../memory/graph-edge-writer.js');@@ -1027,7 +1022,7 @@ interface ComplexityBudget {export const agentdbGraphQuery: MCPTool = {name: 'agentdb_graph-query',- 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.',+ description: 'Unified graph traversal across the knowledge graph (ADR-130). K-hop queries read committed graph_edges relationships through SQL; a separately populated native graph is not evidence of retained-history coverage. Inspect appliedDepth/truncated because SQL is bounded at 3 hops. maxNodesVisited bounds returned rows, not traversal work or elapsed time. Semantic and PageRank modes use their own backends.',inputSchema: {type: 'object',properties: {@@ -1068,66 +1063,49 @@ export const agentdbGraphQuery: MCPTool = {const budgetRaw = (params.complexityBudget ?? {}) as ComplexityBudget;const budget: Required<ComplexityBudget> = {- maxNodesVisited: budgetRaw.maxNodesVisited ?? 10_000,- maxDepth: budgetRaw.maxDepth ?? 5,+ maxNodesVisited: validatePositiveInt(budgetRaw.maxNodesVisited, 10_000, 10_000),+ maxDepth: validatePositiveInt(budgetRaw.maxDepth, 5, 5),maxMillis: budgetRaw.maxMillis ?? 50,maxMemoryMB: budgetRaw.maxMemoryMB ?? 32,};- const depth = Math.min(validatePositiveInt(params.depth, 2, budget.maxDepth), budget.maxDepth);+ const requestedDepth = validatePositiveInt(params.depth, 2, 5);+ const depth = Math.min(requestedDepth, budget.maxDepth);const topK = validatePositiveInt(params.topK, 10, MAX_TOP_K);const relation = validateString(params.relation, 'relation', 200) ?? undefined;// ββ k-hop mode ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββif (mode === 'k-hop') {- // 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, appliedDepth: depth,- results: neighbors.map(id => ({ nodeId: id })),- count: neighbors.length,- backend: 'graph-node',- elapsedMs: Date.now() - t0,- };- }- } catch { /* fall through to SQL */ }-- // 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.+ // #3315: graph-node and retained SQL are populated independently.+ // Native availability does not establish historical coverage. Query+ // the committed relationship source, and fail if it cannot be read.try {const { getBridgeDb } = await getGraphEdgeWriter();const db = await getBridgeDb();if (db) {const appliedDepth = Math.min(depth, 3);- const cteSql = buildKHopCTE(nodeId, appliedDepth, relation, budget.maxNodesVisited);+ const cteSql = buildKHopCTE(nodeId, appliedDepth, relation, budget.maxNodesVisited + 1);// 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[][];+ const allRows = db.prepare(cteSql).raw().all() as unknown[][];+ const resultLimitReached = allRows.length > budget.maxNodesVisited;+ const rows = allRows.slice(0, budget.maxNodesVisited);+ const depthLimited = appliedDepth < requestedDepth;return {- success: true, mode, nodeId, depth, appliedDepth,- ...(appliedDepth < depth ? { truncated: true } : {}),+ success: true, mode, nodeId, depth, requestedDepth, appliedDepth,+ depthLimited, resultLimitReached, truncated: depthLimited || resultLimitReached,+ resultLimit: budget.maxNodesVisited,results: rows.map((r: unknown[]) => ({ nodeId: r[0], depth: r[1] })),count: rows.length,backend: 'sql-cte',elapsedMs: Date.now() - t0,};}- } catch { /* db unavailable */ }-- if (relation) {- return { success: false, error: 'Relation-filtered k-hop query requires the SQL graph_edges backend', mode, nodeId, relation };+ } catch (error) {+ return { success: false, error: `Retained SQL graph query failed: ${sanitizeError(error)}`, mode, nodeId };}- return { success: false, error: 'No graph backend available for k-hop query', mode, nodeId };+ return { success: false, error: 'Retained SQL graph_edges backend is unavailable for k-hop query', mode, nodeId };}// ββ semantic mode ββββββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/v3/docs/adr/ADR-130-graph-intelligence-integration.md b/v3/docs/adr/ADR-130-graph-intelligence-integration.mdindex f4feec357d..665d5d0d2d 100644--- a/v3/docs/adr/ADR-130-graph-intelligence-integration.md+++ b/v3/docs/adr/ADR-130-graph-intelligence-integration.md@@ -2,6 +2,7 @@**Status**: Proposed (2026-05-24)**Date**: 2026-05-24+**Updated**: 2026-09-26 β k-hop implementation reads retained SQL relationships (#3315); the broader ADR remains Proposed.**Authors**: claude (drafted with rUv)**Related**: ADR-087 (graph-node native backend), ADR-123 (sublinear integration / graph intelligence engine), ADR-053 (AgentDB MCP tools), ADR-097 (federation budget circuit breaker), ADR-103 (witness temporal history), ADR-121 (embeddings RuVector upgrade), issues #2047 (witness manifest drift), #1872 (integration test bugs), #1907 (ADR-113 strategic gaps)**Supersedes**: nothing β consolidates graph surfaces established by ADR-087 and ADR-123@@ -155,8 +156,8 @@ agentdb_graph-query({```Dispatch logic (in order of capability):-1. If `mode === "k-hop"` and graph-node native is available: call `db.kHopNeighbors(nodeId, depth)`.-2. If `mode === "k-hop"` and graph-node unavailable: SQL `SELECT target_id FROM graph_edges WHERE source_id = ?` recursively (CTE up to depth 3).+1. If `mode === "k-hop"`: read committed `graph_edges` recursively through the managed SQL accessor (CTE up to depth 3), regardless of native graph availability. A separate native graph may be empty or only partially populated (#3315).+2. If the retained SQL source is missing or unreadable, return an explicit failure. Report requested/applied depth and returned-row truncation. The row limit is not a work, elapsed-time, or memory bound; pending writes and native-only edges are outside this retained-SQL contract.3. If `mode === "semantic"`: cosine search over `graph_edges.embedding` column via the HNSW index.4. If `mode === "pagerank"`: load edges from `graph_edges` into a `SparseMatrix`, call `runPageRank` from `ruflo-graph-intelligence`'s `solver-bridge.ts`. This is the integration point where the sublinear solver reads from the unified schema.@@ -164,12 +165,12 @@ The `KnowledgeGraphSource` interface in `plugins/ruflo-graph-intelligence/src/ad**Acceptance criteria**-1. `agentdb_graph-query({ nodeId: "agent:abc", mode: "k-hop", depth: 2 })` returns neighbor IDs without error when graph-node is available.-2. Same call with graph-node unavailable returns results from SQL CTE fallback.+1. `agentdb_graph-query({ nodeId: "agent:abc", mode: "k-hop", depth: 2 })` returns retained SQL neighbor IDs even when the native graph is empty or partially populated.+2. The same call with graph-node unavailable returns identical retained SQL results; SQL failures never become empty native success.3. `agentdb_graph-query({ nodeId: "entity:xyz", mode: "pagerank", topK: 5 })` returns ranked node list using ruflo-graph-intelligence's `runPageRank`. Requires `ruflo-graph-intelligence` to be importable (optional dependency; graceful error if absent).4. `mode === "semantic"` returns nodes ranked by embedding cosine similarity.-**CI smoke**: `scripts/smoke-graph-query-dispatch.mjs` β tests all three modes against a seeded `graph_edges` table. Native-backend mode tests are guarded by `isGraphBackendAvailable()` and skipped if unavailable.+**CI smoke**: `scripts/smoke-graph-query-dispatch.mjs` β tests all three modes against a seeded `graph_edges` table. K-hop regression tests cover retained SQL while native availability and contents vary.---@@ -337,7 +338,7 @@ For the comparator angle: target graph query latency < 10ms at 1,000 nodes, whic### 1. Schema migration of existing causal-edge data (HIGH)-Existing `agentdb_causal-edge` data lives in three places: graph-node native `.claude-flow/graph/agents.db`, AgentDB bridge SQL tables, and the pilot "double-write" rows added by `agentdb-tools.ts:351β353`. Phase 1 adds a fourth table (`graph_edges`). Without a migration, data is split across all four locations and the unified query in Phase 2 will miss historical edges. Mitigation: Phase 1 must include a one-time migration that reads existing bridge rows and inserts them into `graph_edges`. The graph-node native database lacks an enumeration API (no `listAllEdges()` confirmed in `graph-backend.ts`), so native-only edges cannot be automatically migrated β this is an acknowledged gap. Users who rely on native-only k-hop queries will not lose data, but those edges will not be queryable via `agentdb_graph-query` mode "semantic" or "pagerank" until Phase 4's adapter registers them.+Existing `agentdb_causal-edge` data lives in three places: graph-node native `.claude-flow/graph/agents.db`, AgentDB bridge SQL tables, and the pilot "double-write" rows added by `agentdb-tools.ts:351β353`. Phase 1 adds a fourth table (`graph_edges`). Without a migration, data is split across all four locations and the unified query in Phase 2 will miss historical edges. Mitigation: Phase 1 must include a one-time migration that reads existing bridge rows and inserts them into `graph_edges`. The graph-node native database lacks an enumeration API (no `listAllEdges()` confirmed in `graph-backend.ts`), so native-only edges cannot be automatically migrated β this is an acknowledged gap. Native-only edges remain stored, but the retained-SQL `agentdb_graph-query` k-hop contract does not include them; the other query modes also require their own populated sources. No native-edge migration is included in the #3315 read fix.### 2. Double-write cost during transition (MEDIUM)