π 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
feat(graph-intelligence): #2044 ADR-123 Phases 2-4 β 5 adapters across 5 wedges
ruv645f31a06f30
diff --git a/plugins/ruflo-graph-intelligence/src/adapters/browser-causal-adapter.ts b/plugins/ruflo-graph-intelligence/src/adapters/browser-causal-adapter.tsnew file mode 100644index 0000000000..63d1dbb459--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/adapters/browser-causal-adapter.ts@@ -0,0 +1,193 @@+/**+ * Browser Causal-Recovery Adapter (Wedge 1, ADR-123 Phase 2)+ *+ * Exports the ADR-122 Phase 2 selector-break events as a SparseMatrix so+ * `sublinear/page-rank-entry` can score a single element-ref's causal+ * brittleness in O(log N) instead of the current O(N) `breakCount / attempts`+ * ratio.+ *+ * The matrix `M` is built per-origin: rows + columns are union of+ * - all element-refs that have ever appeared+ * - all selector strings that have ever been retried+ * Off-diagonal entry M[i,j] = number of times row-event preceded column-event+ * on the same DOM mutation lineage (weight β₯ 1). Diagonal entry M[i,i] = 1 + Ξ£+ * |off-diagonals on row i|, so the matrix is strictly diagonally-dominant.+ *+ * The adapter is **dependency-injection-friendly**: callers pass a+ * `BreakEventSource` (a structural type matching the slice of ADR-122's+ * CausalRecoveryService surface we actually need) so this plugin does NOT+ * hard-import @claude-flow/browser. Phase 2 of *this* plugin ships the+ * adapter; the browser package only needs to call `registerBrowserCausalAdapter()`+ * at its plugin-init time.+ */++import { createHash } from 'node:crypto';+import type { SparseEntry, SparseMatrix } from '../domain/types.js';+import type { SublinearAdapter } from '../domain/adapter.js';++/**+ * The slice of @claude-flow/browser's CausalRecoveryService surface we depend on.+ * Defined structurally so we don't need a hard import.+ */+export interface BreakEventSource {+ /** All recorded break events for an origin, in chronological order. */+ listBreaks(origin: string): Promise<readonly BreakEventLike[]>;+}++/** Minimal break-event shape we read. Compatible with ADR-122 Phase 2. */+export interface BreakEventLike {+ id: string;+ origin: string;+ selector: string;+ /** Optional last-known role+name fuzzy-match keys (Phase 2 records both). */+ lastKnownRole?: string;+ lastKnownName?: string;+ /** When the break was first observed (ISO). */+ timestamp: string;+}++export interface BrowserCausalAdapterOptions {+ /** Origin (e.g. `https://example.com`) β one adapter instance per origin. */+ origin: string;+ /** Event source. */+ source: BreakEventSource;+ /** Adjacency-weighting half-life in milliseconds. Default 24h. */+ halfLifeMs?: number;+ /** Diagonal-dominance margin to keep DD even under heavy noise. Default 0.5. */+ ddSafetyMargin?: number;+}++/**+ * Identifier convention so consumers can address per-origin graphs:+ * `browser:causal:<origin>` β e.g. `browser:causal:https://example.com`+ */+export function browserCausalGraphId(origin: string): string {+ return `browser:causal:${origin}`;+}++export class BrowserCausalAdapter implements SublinearAdapter {+ readonly graphId: string;+ readonly ownerPlugin = '@claude-flow/browser';++ private readonly origin: string;+ private readonly source: BreakEventSource;+ private readonly halfLifeMs: number;+ private readonly ddSafetyMargin: number;++ constructor(options: BrowserCausalAdapterOptions) {+ this.origin = options.origin;+ this.source = options.source;+ this.halfLifeMs = options.halfLifeMs ?? 24 * 60 * 60 * 1000;+ this.ddSafetyMargin = options.ddSafetyMargin ?? 0.5;+ this.graphId = browserCausalGraphId(this.origin);+ }++ async exportAsSparseMatrix(options?: {+ since?: string;+ nodeFilter?: ReadonlySet<string>;+ }): Promise<SparseMatrix> {+ const events = await this.source.listBreaks(this.origin);+ const cutoff = options?.since ? Date.parse(options.since) : -Infinity;+ const filtered = events.filter((e) => Date.parse(e.timestamp) >= cutoff);++ // Node set: union of selectors + (role:name) fuzzy keys+ const nodeIds = new Set<string>();+ for (const e of filtered) {+ nodeIds.add(e.selector);+ if (e.lastKnownRole && e.lastKnownName) {+ nodeIds.add(`role:${e.lastKnownRole}:${e.lastKnownName}`);+ }+ }+ if (options?.nodeFilter) {+ for (const n of [...nodeIds]) if (!options.nodeFilter.has(n)) nodeIds.delete(n);+ }++ const nodes = [...nodeIds].sort();+ const nodeIndex: Record<string, number> = {};+ nodes.forEach((n, i) => (nodeIndex[n] = i));++ // Build adjacency: row = source event's selector, col = "next" event's selector+ // within the same chronological neighbourhood. Time-decayed weight.+ const weights = new Map<string, number>(); // key = "row:col"+ const now = Date.now();+ for (let i = 0; i < filtered.length - 1; i++) {+ const a = filtered[i];+ const b = filtered[i + 1];+ const decay = Math.exp(-(now - Date.parse(a.timestamp)) / this.halfLifeMs);+ const keys = pairKeys(a, b);+ for (const k of keys) weights.set(k, (weights.get(k) ?? 0) + decay);+ }++ // Emit off-diagonal entries, then add a diagonal that guarantees DD.+ const entries: SparseEntry[] = [];+ const rowSums = new Array<number>(nodes.length).fill(0);+ for (const [key, w] of weights) {+ const [from, to] = key.split('::');+ const rIdx = nodeIndex[from!];+ const cIdx = nodeIndex[to!];+ if (rIdx === undefined || cIdx === undefined) continue;+ if (rIdx === cIdx) continue;+ entries.push({ row: rIdx, col: cIdx, value: w });+ rowSums[rIdx] += Math.abs(w);+ }+ for (let i = 0; i < nodes.length; i++) {+ const diag = rowSums[i]! + this.ddSafetyMargin;+ entries.push({ row: i, col: i, value: Math.max(1, diag) });+ }++ return {+ graphId: this.graphId,+ size: nodes.length,+ entries,+ nodeIndex,+ indexNode: nodes,+ capturedAt: new Date().toISOString(),+ contentHash: hashContent(this.graphId, entries),+ };+ }++ readonly requiresPreprocessing = false;+}++function pairKeys(a: BreakEventLike, b: BreakEventLike): string[] {+ const keys: string[] = [`${a.selector}::${b.selector}`];+ if (a.lastKnownRole && a.lastKnownName) {+ const key = `role:${a.lastKnownRole}:${a.lastKnownName}`;+ keys.push(`${key}::${b.selector}`);+ }+ if (b.lastKnownRole && b.lastKnownName) {+ const key = `role:${b.lastKnownRole}:${b.lastKnownName}`;+ keys.push(`${a.selector}::${key}`);+ }+ return keys;+}++function hashContent(graphId: string, entries: readonly SparseEntry[]): string {+ const h = createHash('sha256');+ h.update(graphId);+ for (const e of entries) {+ h.update(`|${e.row},${e.col},${e.value.toFixed(8)}`);+ }+ return h.digest('hex');+}++/**+ * Convenience entry point β instantiate + register in one call.+ *+ * Intended to be invoked from @claude-flow/browser's init code:+ * import { registerBrowserCausalAdapter } from 'ruflo-graph-intelligence/adapters';+ * registerBrowserCausalAdapter({ origin: 'https://example.com', source: causalService });+ */+export function registerBrowserCausalAdapter(+ options: BrowserCausalAdapterOptions & { registry?: import('../domain/adapter.js').AdapterRegistry },+): BrowserCausalAdapter {+ const adapter = new BrowserCausalAdapter(options);+ const registry = options.registry ?? import('../domain/adapter.js').then((m) => m.getRegistry());+ // Synchronous registration when registry is supplied; lazy fallback otherwise.+ if (typeof (registry as { register?: unknown }).register === 'function') {+ (registry as import('../domain/adapter.js').AdapterRegistry).register(adapter);+ } else {+ (registry as Promise<import('../domain/adapter.js').AdapterRegistry>).then((r) => r.register(adapter));+ }+ return adapter;+}diff --git a/plugins/ruflo-graph-intelligence/src/adapters/cost-attribution-adapter.ts b/plugins/ruflo-graph-intelligence/src/adapters/cost-attribution-adapter.tsnew file mode 100644index 0000000000..13f089742a--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/adapters/cost-attribution-adapter.ts@@ -0,0 +1,123 @@+/**+ * Cost Attribution Adapter (Wedge 6, ADR-123 Phase 3)+ *+ * `ruflo-cost-tracker` records token usage per session in a causation graph:+ * user-prompt β spawned-agent β MCP-call β model-invocation β tokens-USD+ *+ * This adapter exports that graph so `sublinear/page-rank-entry` answers+ * "which root prompt caused the most downstream spend" in O(log traces)+ * rather than O(traces) walks. Costs are one-way edges β asymmetric matrix.+ */++import { createHash } from 'node:crypto';+import type { SparseEntry, SparseMatrix } from '../domain/types.js';+import type { SublinearAdapter, AdapterRegistry } from '../domain/adapter.js';+import { getRegistry } from '../domain/adapter.js';++export interface CostCausationEdge {+ /** Parent node β typically a prompt id or upstream agent id. */+ parentId: string;+ /** Child node β typically a spawned agent / MCP call / model invocation id. */+ childId: string;+ /** USD cost attributed to the child as caused by this parent. */+ costUsd: number;+}++export interface CostCausationSource {+ /** All causation edges for a session (or globally). */+ listCausationEdges(sessionId?: string): Promise<readonly CostCausationEdge[]>;+}++export interface CostAttributionAdapterOptions {+ source: CostCausationSource;+ /** Restrict to a specific session id. */+ sessionId?: string;+ /** DD safety margin. Default 0.25. */+ ddSafetyMargin?: number;+}++export function costAttributionGraphId(sessionId?: string): string {+ return sessionId ? `ruflo-cost-tracker:causation:${sessionId}` : 'ruflo-cost-tracker:causation:global';+}++export class CostAttributionAdapter implements SublinearAdapter {+ readonly graphId: string;+ readonly ownerPlugin = 'ruflo-cost-tracker';+ readonly requiresPreprocessing = false;++ private readonly source: CostCausationSource;+ private readonly sessionId?: string;+ private readonly ddSafetyMargin: number;++ constructor(options: CostAttributionAdapterOptions) {+ this.source = options.source;+ this.sessionId = options.sessionId;+ this.ddSafetyMargin = options.ddSafetyMargin ?? 0.25;+ this.graphId = costAttributionGraphId(this.sessionId);+ }++ async exportAsSparseMatrix(options?: { nodeFilter?: ReadonlySet<string> }): Promise<SparseMatrix> {+ const edges = await this.source.listCausationEdges(this.sessionId);+ const nodeSet = new Set<string>();+ for (const e of edges) {+ nodeSet.add(e.parentId);+ nodeSet.add(e.childId);+ }+ if (options?.nodeFilter) {+ for (const n of [...nodeSet]) if (!options.nodeFilter.has(n)) nodeSet.delete(n);+ }++ const nodes = [...nodeSet].sort();+ const nodeIndex: Record<string, number> = {};+ nodes.forEach((n, i) => (nodeIndex[n] = i));++ // Normalise costs into [0, 1] per row so PageRank semantics make sense+ // (we're after the *share of blame*, not the raw dollar amount).+ const rawRowSums = new Array<number>(nodes.length).fill(0);+ for (const e of edges) {+ const r = nodeIndex[e.parentId];+ if (r === undefined) continue;+ rawRowSums[r]! += Math.max(0, e.costUsd);+ }+ const entries: SparseEntry[] = [];+ const rowSums = new Array<number>(nodes.length).fill(0);+ for (const e of edges) {+ const r = nodeIndex[e.parentId];+ const c = nodeIndex[e.childId];+ if (r === undefined || c === undefined || r === c) continue;+ const denom = rawRowSums[r]!;+ if (denom === 0) continue;+ const w = Math.max(0, e.costUsd) / denom;+ if (w === 0) continue;+ entries.push({ row: r, col: c, value: w });+ rowSums[r] += w;+ }+ for (let i = 0; i < nodes.length; i++) {+ entries.push({ row: i, col: i, value: rowSums[i]! + this.ddSafetyMargin });+ }+ return {+ graphId: this.graphId,+ size: nodes.length,+ entries,+ nodeIndex,+ indexNode: nodes,+ capturedAt: new Date().toISOString(),+ contentHash: hashContent(this.graphId, entries),+ };+ }+}++export function registerCostAttributionAdapter(+ options: CostAttributionAdapterOptions & { registry?: AdapterRegistry },+): CostAttributionAdapter {+ const adapter = new CostAttributionAdapter(options);+ (options.registry ?? getRegistry()).register(adapter);+ return adapter;+}++function hashContent(graphId: string, entries: readonly SparseEntry[]): string {+ const h = createHash('sha256');+ h.update(graphId);+ for (const e of entries) h.update(`|${e.row},${e.col},${e.value.toFixed(8)}`);+ return h.digest('hex');+}diff --git a/plugins/ruflo-graph-intelligence/src/adapters/federation-trust-adapter.ts b/plugins/ruflo-graph-intelligence/src/adapters/federation-trust-adapter.tsnew file mode 100644index 0000000000..fb2bc6627c--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/adapters/federation-trust-adapter.ts@@ -0,0 +1,116 @@+/**+ * Federation Trust Adapter (Wedge 3, ADR-123 Phase 3)+ *+ * `ruflo-federation` ships a peer trust mesh (ADR-097/104/105/111). This+ * adapter exports the mesh as a SparseMatrix so `sublinear/page-rank-entry`+ * computes transitive trust `(I β Ξ±T)Ο = e` in O(log peers) instead of+ * O(peersΒ²) closure walks. Trust is one-way β the matrix is asymmetric+ * (per upstream 2025 asymmetric-DD result, this is in-scope for sublinear).+ */++import { createHash } from 'node:crypto';+import type { SparseEntry, SparseMatrix } from '../domain/types.js';+import type { SublinearAdapter, AdapterRegistry } from '../domain/adapter.js';+import { getRegistry } from '../domain/adapter.js';++export interface PeerTrustEdge {+ /** Peer the trust comes from. */+ fromPeer: string;+ /** Peer the trust is directed at. */+ toPeer: string;+ /** Confidence in [0, 1] β typically derived from signed-message hit rate. */+ confidence: number;+ /** When the edge was last updated. */+ updatedAt: string;+}++export interface PeerTrustSource {+ /** All trust edges currently in the local view of the mesh. */+ listTrustEdges(): Promise<readonly PeerTrustEdge[]>;+}++export interface FederationTrustAdapterOptions {+ source: PeerTrustSource;+ /** Edge-staleness cutoff in milliseconds. Default 7 days. */+ freshnessMs?: number;+ /** Diagonal-dominance safety margin. Default 0.25. */+ ddSafetyMargin?: number;+}++export const FEDERATION_TRUST_GRAPH_ID = 'ruflo-federation:trust-mesh';++export class FederationTrustAdapter implements SublinearAdapter {+ readonly graphId = FEDERATION_TRUST_GRAPH_ID;+ readonly ownerPlugin = 'ruflo-federation';+ readonly requiresPreprocessing = false;++ private readonly source: PeerTrustSource;+ private readonly freshnessMs: number;+ private readonly ddSafetyMargin: number;++ constructor(options: FederationTrustAdapterOptions) {+ this.source = options.source;+ this.freshnessMs = options.freshnessMs ?? 7 * 24 * 60 * 60 * 1000;+ this.ddSafetyMargin = options.ddSafetyMargin ?? 0.25;+ }++ async exportAsSparseMatrix(options?: { nodeFilter?: ReadonlySet<string> }): Promise<SparseMatrix> {+ const allEdges = await this.source.listTrustEdges();+ const now = Date.now();+ const fresh = allEdges.filter((e) => now - Date.parse(e.updatedAt) <= this.freshnessMs);++ const peerSet = new Set<string>();+ for (const e of fresh) {+ peerSet.add(e.fromPeer);+ peerSet.add(e.toPeer);+ }+ if (options?.nodeFilter) {+ for (const p of [...peerSet]) if (!options.nodeFilter.has(p)) peerSet.delete(p);+ }++ const peers = [...peerSet].sort();+ const nodeIndex: Record<string, number> = {};+ peers.forEach((p, i) => (nodeIndex[p] = i));++ const entries: SparseEntry[] = [];+ const rowSums = new Array<number>(peers.length).fill(0);+ for (const edge of fresh) {+ const r = nodeIndex[edge.fromPeer];+ const c = nodeIndex[edge.toPeer];+ if (r === undefined || c === undefined || r === c) continue;+ const w = Math.max(0, Math.min(1, edge.confidence));+ if (w === 0) continue;+ entries.push({ row: r, col: c, value: w });+ rowSums[r] += w;+ }+ // DD diagonal: |diag| β₯ Ξ£|off| + margin+ for (let i = 0; i < peers.length; i++) {+ entries.push({ row: i, col: i, value: rowSums[i]! + this.ddSafetyMargin });+ }++ return {+ graphId: this.graphId,+ size: peers.length,+ entries,+ nodeIndex,+ indexNode: peers,+ capturedAt: new Date().toISOString(),+ contentHash: hashContent(this.graphId, entries),+ };+ }+}++export function registerFederationTrustAdapter(+ options: FederationTrustAdapterOptions & { registry?: AdapterRegistry },+): FederationTrustAdapter {+ const adapter = new FederationTrustAdapter(options);+ (options.registry ?? getRegistry()).register(adapter);+ return adapter;+}++function hashContent(graphId: string, entries: readonly SparseEntry[]): string {+ const h = createHash('sha256');+ h.update(graphId);+ for (const e of entries) h.update(`|${e.row},${e.col},${e.value.toFixed(8)}`);+ return h.digest('hex');+}diff --git a/plugins/ruflo-graph-intelligence/src/adapters/index.ts b/plugins/ruflo-graph-intelligence/src/adapters/index.tsnew file mode 100644index 0000000000..d35b1d6fa1--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/adapters/index.ts@@ -0,0 +1,60 @@+/**+ * ruflo-graph-intelligence β Adapter barrel export+ *+ * Each adapter lives in its own file and is opted into by the owning plugin+ * at init time. Phase-1 ships zero adapters; Phase 2+ adds them one at a time.+ */++export {+ BrowserCausalAdapter,+ browserCausalGraphId,+ registerBrowserCausalAdapter,+ type BreakEventSource,+ type BreakEventLike,+ type BrowserCausalAdapterOptions,+} from './browser-causal-adapter.js';++export {+ FederationTrustAdapter,+ FEDERATION_TRUST_GRAPH_ID,+ registerFederationTrustAdapter,+ type PeerTrustEdge,+ type PeerTrustSource,+ type FederationTrustAdapterOptions,+} from './federation-trust-adapter.js';++export {+ CostAttributionAdapter,+ costAttributionGraphId,+ registerCostAttributionAdapter,+ type CostCausationEdge,+ type CostCausationSource,+ type CostAttributionAdapterOptions,+} from './cost-attribution-adapter.js';++export {+ ObservabilitySpanAdapter,+ observabilityGraphId,+ registerObservabilitySpanAdapter,+ type SpanRecord,+ type ObservabilitySpanSource,+ type ObservabilitySpanAdapterOptions,+} from './observability-span-adapter.js';++export {+ KnowledgeGraphAdapter,+ KNOWLEDGE_GRAPH_ID,+ registerKnowledgeGraphAdapter,+ type KGEdge,+ type KnowledgeGraphSource,+ type KnowledgeGraphAdapterOptions,+} from './knowledge-graph-adapter.js';++export {+ RagMemoryAdapter,+ ragMemoryGraphId,+ registerRagMemoryAdapter,+ type ChunkEdge,+ type RagMemorySource,+ type RagMemoryAdapterOptions,+} from './rag-memory-adapter.js';diff --git a/plugins/ruflo-graph-intelligence/src/adapters/knowledge-graph-adapter.ts b/plugins/ruflo-graph-intelligence/src/adapters/knowledge-graph-adapter.tsnew file mode 100644index 0000000000..1c6843a36c--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/adapters/knowledge-graph-adapter.ts@@ -0,0 +1,110 @@+/**+ * Knowledge Graph Adapter (Wedge 4, ADR-123 Phase 4)+ *+ * `ruflo-knowledge-graph` builds an entity-relation graph via kg-extract.+ * This adapter exports it as a SparseMatrix so kg-importance(entity) becomes+ * a single-entry PR query β answering "which entity is most central" in+ * sub-millisecond on a 10k-node graph.+ */++import { createHash } from 'node:crypto';+import type { SparseEntry, SparseMatrix } from '../domain/types.js';+import type { SublinearAdapter, AdapterRegistry } from '../domain/adapter.js';+import { getRegistry } from '../domain/adapter.js';++export interface KGEdge {+ fromEntity: string;+ toEntity: string;+ relation: string;+ /** Edge confidence in [0,1]. Default 1.0. */+ confidence?: number;+}++export interface KnowledgeGraphSource {+ listEdges(): Promise<readonly KGEdge[]>;+}++export interface KnowledgeGraphAdapterOptions {+ source: KnowledgeGraphSource;+ /** DD safety margin. Default 0.25. */+ ddSafetyMargin?: number;+}++export const KNOWLEDGE_GRAPH_ID = 'ruflo-knowledge-graph:entities';++export class KnowledgeGraphAdapter implements SublinearAdapter {+ readonly graphId = KNOWLEDGE_GRAPH_ID;+ readonly ownerPlugin = 'ruflo-knowledge-graph';+ readonly requiresPreprocessing = false;++ private readonly source: KnowledgeGraphSource;+ private readonly ddSafetyMargin: number;++ constructor(options: KnowledgeGraphAdapterOptions) {+ this.source = options.source;+ this.ddSafetyMargin = options.ddSafetyMargin ?? 0.25;+ }++ async exportAsSparseMatrix(options?: { nodeFilter?: ReadonlySet<string> }): Promise<SparseMatrix> {+ const edges = await this.source.listEdges();+ const entitySet = new Set<string>();+ for (const e of edges) {+ entitySet.add(e.fromEntity);+ entitySet.add(e.toEntity);+ }+ if (options?.nodeFilter) {+ for (const n of [...entitySet]) if (!options.nodeFilter.has(n)) entitySet.delete(n);+ }++ const entities = [...entitySet].sort();+ const nodeIndex: Record<string, number> = {};+ entities.forEach((n, i) => (nodeIndex[n] = i));++ // Weight edges by confidence; if multiple relations exist between two+ // entities, sum confidences (cap at 1).+ const weights = new Map<string, number>();+ for (const e of edges) {+ const r = nodeIndex[e.fromEntity];+ const c = nodeIndex[e.toEntity];+ if (r === undefined || c === undefined || r === c) continue;+ const key = `${r},${c}`;+ weights.set(key, Math.min(1, (weights.get(key) ?? 0) + (e.confidence ?? 1)));+ }+ const entries: SparseEntry[] = [];+ const rowSums = new Array<number>(entities.length).fill(0);+ for (const [key, w] of weights) {+ const [rStr, cStr] = key.split(',');+ const r = Number(rStr);+ const c = Number(cStr);+ entries.push({ row: r, col: c, value: w });+ rowSums[r] += w;+ }+ for (let i = 0; i < entities.length; i++) {+ entries.push({ row: i, col: i, value: rowSums[i]! + this.ddSafetyMargin });+ }+ return {+ graphId: this.graphId,+ size: entities.length,+ entries,+ nodeIndex,+ indexNode: entities,+ capturedAt: new Date().toISOString(),+ contentHash: hashContent(this.graphId, entries),+ };+ }+}++export function registerKnowledgeGraphAdapter(+ options: KnowledgeGraphAdapterOptions & { registry?: AdapterRegistry },+): KnowledgeGraphAdapter {+ const adapter = new KnowledgeGraphAdapter(options);+ (options.registry ?? getRegistry()).register(adapter);+ return adapter;+}++function hashContent(graphId: string, entries: readonly SparseEntry[]): string {+ const h = createHash('sha256');+ h.update(graphId);+ for (const e of entries) h.update(`|${e.row},${e.col},${e.value.toFixed(8)}`);+ return h.digest('hex');+}diff --git a/plugins/ruflo-graph-intelligence/src/adapters/observability-span-adapter.ts b/plugins/ruflo-graph-intelligence/src/adapters/observability-span-adapter.tsnew file mode 100644index 0000000000..047a9431c7--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/adapters/observability-span-adapter.ts@@ -0,0 +1,123 @@+/**+ * Observability Span Adapter (Wedge 7, ADR-123 Phase 3)+ *+ * `ruflo-observability` records spans (OpenTelemetry-style) with parent links+ * + cross-trace causality. This adapter exports the span graph so the user+ * can ask "which span most contributed to this slow/failed request" in+ * O(log spans) instead of full-trace walks.+ */++import { createHash } from 'node:crypto';+import type { SparseEntry, SparseMatrix } from '../domain/types.js';+import type { SublinearAdapter, AdapterRegistry } from '../domain/adapter.js';+import { getRegistry } from '../domain/adapter.js';++export interface SpanRecord {+ spanId: string;+ parentSpanId?: string;+ traceId: string;+ /** Self-time in microseconds β used as edge weight. */+ selfTimeUs: number;+ /** Optional cross-trace causality link (e.g. an event triggered this trace). */+ causedBySpanId?: string;+}++export interface ObservabilitySpanSource {+ listSpans(traceId: string): Promise<readonly SpanRecord[]>;+}++export interface ObservabilitySpanAdapterOptions {+ source: ObservabilitySpanSource;+ traceId: string;+ /** DD safety margin. Default 0.25. */+ ddSafetyMargin?: number;+}++export function observabilityGraphId(traceId: string): string {+ return `ruflo-observability:trace:${traceId}`;+}++export class ObservabilitySpanAdapter implements SublinearAdapter {+ readonly graphId: string;+ readonly ownerPlugin = 'ruflo-observability';+ readonly requiresPreprocessing = false;++ private readonly source: ObservabilitySpanSource;+ private readonly traceId: string;+ private readonly ddSafetyMargin: number;++ constructor(options: ObservabilitySpanAdapterOptions) {+ this.source = options.source;+ this.traceId = options.traceId;+ this.ddSafetyMargin = options.ddSafetyMargin ?? 0.25;+ this.graphId = observabilityGraphId(this.traceId);+ }++ async exportAsSparseMatrix(options?: { nodeFilter?: ReadonlySet<string> }): Promise<SparseMatrix> {+ const spans = await this.source.listSpans(this.traceId);+ const idSet = new Set<string>();+ for (const s of spans) {+ idSet.add(s.spanId);+ if (s.parentSpanId) idSet.add(s.parentSpanId);+ if (s.causedBySpanId) idSet.add(s.causedBySpanId);+ }+ if (options?.nodeFilter) {+ for (const n of [...idSet]) if (!options.nodeFilter.has(n)) idSet.delete(n);+ }++ const nodes = [...idSet].sort();+ const nodeIndex: Record<string, number> = {};+ nodes.forEach((n, i) => (nodeIndex[n] = i));++ // Normalise self-time per parent: each parent's outbound weights sum to β€1.+ const childrenByParent = new Map<string, SpanRecord[]>();+ for (const s of spans) {+ const p = s.parentSpanId ?? s.causedBySpanId;+ if (!p) continue;+ if (!childrenByParent.has(p)) childrenByParent.set(p, []);+ childrenByParent.get(p)!.push(s);+ }++ const entries: SparseEntry[] = [];+ const rowSums = new Array<number>(nodes.length).fill(0);+ for (const [parent, children] of childrenByParent) {+ const r = nodeIndex[parent];+ if (r === undefined) continue;+ const total = children.reduce((s, c) => s + Math.max(1, c.selfTimeUs), 0);+ for (const child of children) {+ const c = nodeIndex[child.spanId];+ if (c === undefined || c === r) continue;+ const w = Math.max(1, child.selfTimeUs) / total;+ entries.push({ row: r, col: c, value: w });+ rowSums[r] += w;+ }+ }+ for (let i = 0; i < nodes.length; i++) {+ entries.push({ row: i, col: i, value: rowSums[i]! + this.ddSafetyMargin });+ }+ return {+ graphId: this.graphId,+ size: nodes.length,+ entries,+ nodeIndex,+ indexNode: nodes,+ capturedAt: new Date().toISOString(),+ contentHash: hashContent(this.graphId, entries),+ };+ }+}++export function registerObservabilitySpanAdapter(+ options: ObservabilitySpanAdapterOptions & { registry?: AdapterRegistry },+): ObservabilitySpanAdapter {+ const adapter = new ObservabilitySpanAdapter(options);+ (options.registry ?? getRegistry()).register(adapter);+ return adapter;+}++function hashContent(graphId: string, entries: readonly SparseEntry[]): string {+ const h = createHash('sha256');+ h.update(graphId);+ for (const e of entries) h.update(`|${e.row},${e.col},${e.value.toFixed(8)}`);+ return h.digest('hex');+}diff --git a/plugins/ruflo-graph-intelligence/src/adapters/rag-memory-adapter.ts b/plugins/ruflo-graph-intelligence/src/adapters/rag-memory-adapter.tsnew file mode 100644index 0000000000..1fbb0f5859--- /dev/null+++ b/plugins/ruflo-graph-intelligence/src/adapters/rag-memory-adapter.ts@@ -0,0 +1,117 @@+/**+ * RAG Memory Adapter (Wedge 5, ADR-123 Phase 4)+ *+ * `ruflo-rag-memory` ships Graph-RAG multi-hop retrieval. This adapter+ * exports the chunk-connectivity graph so personalized PR seeded by the+ * query embedding ranks candidate chunks globally β graph-aware retrieval+ * beyond flat top-k MMR rerank.+ *+ * The seedNodes for personalized PR come from the caller's query side+ * (`sublinear/page-rank-entry` already accepts seedNodes). This adapter+ * just exposes the underlying chunk graph.+ */++import { createHash } from 'node:crypto';+import type { SparseEntry, SparseMatrix } from '../domain/types.js';+import type { SublinearAdapter, AdapterRegistry } from '../domain/adapter.js';+import { getRegistry } from '../domain/adapter.js';++export interface ChunkEdge {+ fromChunkId: string;+ toChunkId: string;+ /** Similarity weight in [0, 1] β typically cosine similarity of chunk embeddings. */+ similarity: number;+}++export interface RagMemorySource {+ listChunkEdges(namespace?: string): Promise<readonly ChunkEdge[]>;+}++export interface RagMemoryAdapterOptions {+ source: RagMemorySource;+ namespace?: string;+ /** Minimum similarity to include an edge. Default 0.5. */+ similarityFloor?: number;+ /** DD safety margin. Default 0.25. */+ ddSafetyMargin?: number;+}++export function ragMemoryGraphId(namespace?: string): string {+ return namespace+ ? `ruflo-rag-memory:chunks:${namespace}`+ : 'ruflo-rag-memory:chunks:default';+}++export class RagMemoryAdapter implements SublinearAdapter {+ readonly graphId: string;+ readonly ownerPlugin = 'ruflo-rag-memory';+ readonly requiresPreprocessing = false;++ private readonly source: RagMemorySource;+ private readonly namespace?: string;+ private readonly similarityFloor: number;+ private readonly ddSafetyMargin: number;++ constructor(options: RagMemoryAdapterOptions) {+ this.source = options.source;+ this.namespace = options.namespace;+ this.similarityFloor = options.similarityFloor ?? 0.5;+ this.ddSafetyMargin = options.ddSafetyMargin ?? 0.25;+ this.graphId = ragMemoryGraphId(this.namespace);+ }++ async exportAsSparseMatrix(options?: { nodeFilter?: ReadonlySet<string> }): Promise<SparseMatrix> {+ const edges = (await this.source.listChunkEdges(this.namespace)).filter(+ (e) => e.similarity >= this.similarityFloor,+ );+ const chunkSet = new Set<string>();+ for (const e of edges) {+ chunkSet.add(e.fromChunkId);+ chunkSet.add(e.toChunkId);+ }+ if (options?.nodeFilter) {+ for (const n of [...chunkSet]) if (!options.nodeFilter.has(n)) chunkSet.delete(n);+ }++ const chunks = [...chunkSet].sort();+ const nodeIndex: Record<string, number> = {};+ chunks.forEach((n, i) => (nodeIndex[n] = i));++ const entries: SparseEntry[] = [];+ const rowSums = new Array<number>(chunks.length).fill(0);+ for (const e of edges) {+ const r = nodeIndex[e.fromChunkId];+ const c = nodeIndex[e.toChunkId];+ if (r === undefined || c === undefined || r === c) continue;+ entries.push({ row: r, col: c, value: e.similarity });+ rowSums[r] += e.similarity;+ }+ for (let i = 0; i < chunks.length; i++) {+ entries.push({ row: i, col: i, value: rowSums[i]! + this.ddSafetyMargin });+ }+ return {+ graphId: this.graphId,+ size: chunks.length,+ entries,+ nodeIndex,+ indexNode: chunks,+ capturedAt: new Date().toISOString(),+ contentHash: hashContent(this.graphId, entries),+ };+ }+}++export function registerRagMemoryAdapter(+ options: RagMemoryAdapterOptions & { registry?: AdapterRegistry },+): RagMemoryAdapter {+ const adapter = new RagMemoryAdapter(options);+ (options.registry ?? getRegistry()).register(adapter);+ return adapter;+}++function hashContent(graphId: string, entries: readonly SparseEntry[]): string {+ const h = createHash('sha256');+ h.update(graphId);+ for (const e of entries) h.update(`|${e.row},${e.col},${e.value.toFixed(8)}`);+ return h.digest('hex');+}diff --git a/plugins/ruflo-graph-intelligence/src/index.ts b/plugins/ruflo-graph-intelligence/src/index.tsindex ba75d7480e..1429eee2d8 100644--- a/plugins/ruflo-graph-intelligence/src/index.ts+++ b/plugins/ruflo-graph-intelligence/src/index.ts@@ -39,6 +39,9 @@ export {// MCP toolsexport { graphIntelligenceTools, type MCPTool } from './mcp-tools/index.js';+// Adapters (per-wedge integrations)+export * from './adapters/index.js';+// Default exportimport { graphIntelligenceTools } from './mcp-tools/index.js';import { getRegistry } from './domain/adapter.js';diff --git a/plugins/ruflo-graph-intelligence/tests/browser-causal-adapter.test.ts b/plugins/ruflo-graph-intelligence/tests/browser-causal-adapter.test.tsnew file mode 100644index 0000000000..4c4069adca--- /dev/null+++ b/plugins/ruflo-graph-intelligence/tests/browser-causal-adapter.test.ts@@ -0,0 +1,174 @@+/**+ * Browser Causal-Recovery Adapter Tests (Wedge 1, ADR-123 Phase 2)+ *+ * Acceptance:+ * - Exports a SparseMatrix whose dimensions match the node-set+ * - Result matrix is diagonally-dominant (coherence > 0)+ * - Time-decay weights older events less+ * - registerBrowserCausalAdapter() puts the adapter in the registry under+ * the canonical `browser:causal:<origin>` graphId+ * - sublinear/page-rank-entry routes through the adapter end-to-end+ */++import { describe, it, expect, beforeEach } from 'vitest';+import {+ BrowserCausalAdapter,+ browserCausalGraphId,+ registerBrowserCausalAdapter,+ type BreakEventLike,+ type BreakEventSource,+} from '../src/adapters/browser-causal-adapter.js';+import { resetRegistry, getRegistry } from '../src/domain/adapter.js';+import { coherenceScore } from '../src/infrastructure/solver-bridge.js';+import { graphIntelligenceTools } from '../src/mcp-tools/index.js';++function stubSource(events: BreakEventLike[]): BreakEventSource {+ return {+ async listBreaks(origin) {+ return events.filter((e) => e.origin === origin);+ },+ };+}++function evt(partial: Partial<BreakEventLike> & Pick<BreakEventLike, 'id' | 'selector' | 'origin'>): BreakEventLike {+ return {+ timestamp: '2026-05-19T00:00:00.000Z',+ ...partial,+ };+}++describe('browserCausalGraphId', () => {+ it('encodes origin into a stable identifier', () => {+ expect(browserCausalGraphId('https://example.com')).toBe('browser:causal:https://example.com');+ });+});++describe('BrowserCausalAdapter.exportAsSparseMatrix', () => {+ it('returns an empty matrix when there are no break events', async () => {+ const adapter = new BrowserCausalAdapter({+ origin: 'https://empty.test',+ source: stubSource([]),+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(m.size).toBe(0);+ expect(m.entries).toHaveLength(0);+ });++ it('builds a DD matrix from a chronological event sequence', async () => {+ const adapter = new BrowserCausalAdapter({+ origin: 'https://example.com',+ source: stubSource([+ evt({ id: 'b1', origin: 'https://example.com', selector: '@e1', timestamp: '2026-05-19T00:00:00.000Z' }),+ evt({ id: 'b2', origin: 'https://example.com', selector: '@e2', timestamp: '2026-05-19T00:00:01.000Z' }),+ evt({ id: 'b3', origin: 'https://example.com', selector: '@e3', timestamp: '2026-05-19T00:00:02.000Z' }),+ ]),+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(m.size).toBe(3);+ expect(coherenceScore(m)).toBeGreaterThan(0);+ expect(m.contentHash).toMatch(/^[0-9a-f]{64}$/);+ });++ it('honours nodeFilter to prune irrelevant rows', async () => {+ const adapter = new BrowserCausalAdapter({+ origin: 'https://example.com',+ source: stubSource([+ evt({ id: 'b1', origin: 'https://example.com', selector: '@e1' }),+ evt({ id: 'b2', origin: 'https://example.com', selector: '@e2' }),+ evt({ id: 'b3', origin: 'https://example.com', selector: '@e3' }),+ ]),+ });+ const m = await adapter.exportAsSparseMatrix({ nodeFilter: new Set(['@e1', '@e2']) });+ expect(m.size).toBe(2);+ expect(Object.keys(m.nodeIndex).sort()).toEqual(['@e1', '@e2']);+ });++ it('records (role:name) fuzzy keys when present', async () => {+ const adapter = new BrowserCausalAdapter({+ origin: 'https://example.com',+ source: stubSource([+ evt({+ id: 'b1',+ origin: 'https://example.com',+ selector: '@e3',+ lastKnownRole: 'button',+ lastKnownName: 'Submit',+ }),+ evt({+ id: 'b2',+ origin: 'https://example.com',+ selector: '@e3',+ lastKnownRole: 'button',+ lastKnownName: 'Submit',+ }),+ ]),+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(Object.keys(m.nodeIndex)).toContain('role:button:Submit');+ });++ it('time-decays older events relative to newer ones', async () => {+ const oneHour = 60 * 60 * 1000;+ const now = Date.now();+ const events: BreakEventLike[] = [+ evt({ id: 'old1', origin: 'https://x.com', selector: 'a', timestamp: new Date(now - 240 * oneHour).toISOString() }),+ evt({ id: 'old2', origin: 'https://x.com', selector: 'b', timestamp: new Date(now - 239 * oneHour).toISOString() }),+ evt({ id: 'new1', origin: 'https://x.com', selector: 'a', timestamp: new Date(now - oneHour).toISOString() }),+ evt({ id: 'new2', origin: 'https://x.com', selector: 'b', timestamp: new Date(now).toISOString() }),+ ];+ const adapter = new BrowserCausalAdapter({+ origin: 'https://x.com',+ source: stubSource(events),+ halfLifeMs: 24 * oneHour,+ });+ const m = await adapter.exportAsSparseMatrix();+ // Find the aβb edge: at least one entry should exist; the weight should+ // be dominated by the recent event-pair, not the old one.+ const aIdx = m.nodeIndex['a'];+ const bIdx = m.nodeIndex['b'];+ const offDiag = m.entries.filter((e) => e.row === aIdx && e.col === bIdx);+ expect(offDiag.length).toBeGreaterThan(0);+ // The accumulated decay should be small for old pair, ~1.0 for recent.+ const totalWeight = offDiag.reduce((s, e) => s + e.value, 0);+ // Recent pair contributes ~1.0, old pair contributes ~ exp(-239/24) β 4e-5.+ expect(totalWeight).toBeGreaterThan(0.5);+ expect(totalWeight).toBeLessThan(2);+ });+});++describe('registerBrowserCausalAdapter', () => {+ beforeEach(() => resetRegistry());++ it('registers under the canonical graph id', () => {+ const registry = getRegistry();+ registerBrowserCausalAdapter({+ origin: 'https://example.com',+ source: stubSource([]),+ registry,+ });+ expect(registry.get('browser:causal:https://example.com')).toBeDefined();+ });++ it('end-to-end: sublinear/page-rank-entry resolves through the registered adapter', async () => {+ const registry = getRegistry();+ registerBrowserCausalAdapter({+ origin: 'https://example.com',+ source: stubSource([+ evt({ id: 'b1', origin: 'https://example.com', selector: '@e1' }),+ evt({ id: 'b2', origin: 'https://example.com', selector: '@e2' }),+ evt({ id: 'b3', origin: 'https://example.com', selector: '@e3' }),+ ]),+ registry,+ });+ const tool = graphIntelligenceTools.find((t) => t.name === 'sublinear/page-rank-entry');+ expect(tool).toBeDefined();+ const r = (await tool!.handler({+ graphId: 'browser:causal:https://example.com',+ nodeId: '@e2',+ maxComplexityClass: 'polynomial',+ })) as { success: boolean; result?: { score: number; complexityClass: string } };+ expect(r.success).toBe(true);+ expect(r.result?.score).toBeGreaterThanOrEqual(0);+ expect(r.result?.complexityClass).toBeDefined();+ });+});diff --git a/plugins/ruflo-graph-intelligence/tests/phase3-adapters.test.ts b/plugins/ruflo-graph-intelligence/tests/phase3-adapters.test.tsnew file mode 100644index 0000000000..cd18434a3c--- /dev/null+++ b/plugins/ruflo-graph-intelligence/tests/phase3-adapters.test.ts@@ -0,0 +1,206 @@+/**+ * Phase 3 Adapter Tests β federation trust + cost attribution + observability+ *+ * Acceptance:+ * - Each adapter exports a DD SparseMatrix+ * - Each adapter registers under its canonical graphId+ * - sublinear/page-rank-entry routes through each end-to-end+ * - Stale federation edges are pruned+ * - Cost rows are L1-normalised so PR weights are proportional shares+ */++import { describe, it, expect, beforeEach } from 'vitest';+import {+ FederationTrustAdapter,+ FEDERATION_TRUST_GRAPH_ID,+ registerFederationTrustAdapter,+} from '../src/adapters/federation-trust-adapter.js';+import {+ CostAttributionAdapter,+ costAttributionGraphId,+ registerCostAttributionAdapter,+} from '../src/adapters/cost-attribution-adapter.js';+import {+ ObservabilitySpanAdapter,+ observabilityGraphId,+ registerObservabilitySpanAdapter,+} from '../src/adapters/observability-span-adapter.js';+import { resetRegistry, getRegistry } from '../src/domain/adapter.js';+import { coherenceScore } from '../src/infrastructure/solver-bridge.js';+import { graphIntelligenceTools } from '../src/mcp-tools/index.js';++describe('FederationTrustAdapter', () => {+ beforeEach(() => resetRegistry());++ it('exports a DD matrix from peer trust edges', async () => {+ const adapter = new FederationTrustAdapter({+ source: {+ async listTrustEdges() {+ return [+ { fromPeer: 'A', toPeer: 'B', confidence: 0.8, updatedAt: new Date().toISOString() },+ { fromPeer: 'B', toPeer: 'C', confidence: 0.6, updatedAt: new Date().toISOString() },+ { fromPeer: 'A', toPeer: 'C', confidence: 0.3, updatedAt: new Date().toISOString() },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(m.size).toBe(3);+ expect(coherenceScore(m)).toBeGreaterThan(0);+ });++ it('prunes stale edges past the freshness window', async () => {+ const old = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString();+ const fresh = new Date().toISOString();+ const adapter = new FederationTrustAdapter({+ freshnessMs: 7 * 24 * 60 * 60 * 1000,+ source: {+ async listTrustEdges() {+ return [+ { fromPeer: 'A', toPeer: 'B', confidence: 0.8, updatedAt: old },+ { fromPeer: 'B', toPeer: 'C', confidence: 0.6, updatedAt: fresh },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(Object.keys(m.nodeIndex).sort()).toEqual(['B', 'C']);+ });++ it('registers under the canonical graphId', () => {+ const registry = getRegistry();+ registerFederationTrustAdapter({+ source: { async listTrustEdges() { return []; } },+ registry,+ });+ expect(registry.get(FEDERATION_TRUST_GRAPH_ID)).toBeDefined();+ });++ it('end-to-end via sublinear/page-rank-entry', async () => {+ const registry = getRegistry();+ registerFederationTrustAdapter({+ source: {+ async listTrustEdges() {+ return [+ { fromPeer: 'A', toPeer: 'B', confidence: 0.9, updatedAt: new Date().toISOString() },+ { fromPeer: 'B', toPeer: 'C', confidence: 0.7, updatedAt: new Date().toISOString() },+ ];+ },+ },+ registry,+ });+ const tool = graphIntelligenceTools.find((t) => t.name === 'sublinear/page-rank-entry');+ const r = (await tool!.handler({+ graphId: FEDERATION_TRUST_GRAPH_ID,+ nodeId: 'C',+ maxComplexityClass: 'polynomial',+ })) as { success: boolean; result?: { score: number } };+ expect(r.success).toBe(true);+ expect(r.result?.score).toBeGreaterThanOrEqual(0);+ });+});++describe('CostAttributionAdapter', () => {+ beforeEach(() => resetRegistry());++ it('builds a DD matrix from causation edges', async () => {+ const adapter = new CostAttributionAdapter({+ sessionId: 'sess-1',+ source: {+ async listCausationEdges() {+ return [+ { parentId: 'prompt-1', childId: 'agent-1', costUsd: 0.5 },+ { parentId: 'prompt-1', childId: 'agent-2', costUsd: 0.2 },+ { parentId: 'agent-1', childId: 'model-call-1', costUsd: 0.05 },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(m.size).toBeGreaterThan(0);+ expect(coherenceScore(m)).toBeGreaterThan(0);+ });++ it('L1-normalises costs into proportional shares per parent', async () => {+ const adapter = new CostAttributionAdapter({+ source: {+ async listCausationEdges() {+ return [+ { parentId: 'p', childId: 'a', costUsd: 1.0 },+ { parentId: 'p', childId: 'b', costUsd: 3.0 },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ const pIdx = m.nodeIndex['p'];+ const aIdx = m.nodeIndex['a'];+ const bIdx = m.nodeIndex['b'];+ const pa = m.entries.find((e) => e.row === pIdx && e.col === aIdx)?.value ?? 0;+ const pb = m.entries.find((e) => e.row === pIdx && e.col === bIdx)?.value ?? 0;+ expect(pa + pb).toBeCloseTo(1.0, 6);+ expect(pb / pa).toBeCloseTo(3, 2);+ });++ it('registers under the canonical session-scoped graphId', () => {+ const registry = getRegistry();+ registerCostAttributionAdapter({+ sessionId: 's',+ source: { async listCausationEdges() { return []; } },+ registry,+ });+ expect(registry.get(costAttributionGraphId('s'))).toBeDefined();+ });+});++describe('ObservabilitySpanAdapter', () => {+ beforeEach(() => resetRegistry());++ it('builds a DD matrix from span tree', async () => {+ const adapter = new ObservabilitySpanAdapter({+ traceId: 't1',+ source: {+ async listSpans() {+ return [+ { spanId: 'root', traceId: 't1', selfTimeUs: 100 },+ { spanId: 'child-a', parentSpanId: 'root', traceId: 't1', selfTimeUs: 60 },+ { spanId: 'child-b', parentSpanId: 'root', traceId: 't1', selfTimeUs: 40 },+ { spanId: 'leaf', parentSpanId: 'child-a', traceId: 't1', selfTimeUs: 10 },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(m.size).toBe(4);+ expect(coherenceScore(m)).toBeGreaterThan(0);+ });++ it('honours cross-trace causedBy links', async () => {+ const adapter = new ObservabilitySpanAdapter({+ traceId: 't1',+ source: {+ async listSpans() {+ return [+ { spanId: 'a', traceId: 't1', selfTimeUs: 100 },+ { spanId: 'b', traceId: 't1', selfTimeUs: 50, causedBySpanId: 'a' },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ const aIdx = m.nodeIndex['a'];+ const bIdx = m.nodeIndex['b'];+ const ab = m.entries.find((e) => e.row === aIdx && e.col === bIdx);+ expect(ab?.value).toBeGreaterThan(0);+ });++ it('registers under the canonical graphId', () => {+ const registry = getRegistry();+ registerObservabilitySpanAdapter({+ traceId: 't',+ source: { async listSpans() { return []; } },+ registry,+ });+ expect(registry.get(observabilityGraphId('t'))).toBeDefined();+ });+});diff --git a/plugins/ruflo-graph-intelligence/tests/phase4-adapters.test.ts b/plugins/ruflo-graph-intelligence/tests/phase4-adapters.test.tsnew file mode 100644index 0000000000..2d9bbe0fdf--- /dev/null+++ b/plugins/ruflo-graph-intelligence/tests/phase4-adapters.test.ts@@ -0,0 +1,158 @@+/**+ * Phase 4 Adapter Tests β knowledge graph + RAG memory+ */++import { describe, it, expect, beforeEach } from 'vitest';+import {+ KnowledgeGraphAdapter,+ KNOWLEDGE_GRAPH_ID,+ registerKnowledgeGraphAdapter,+} from '../src/adapters/knowledge-graph-adapter.js';+import {+ RagMemoryAdapter,+ ragMemoryGraphId,+ registerRagMemoryAdapter,+} from '../src/adapters/rag-memory-adapter.js';+import { resetRegistry, getRegistry } from '../src/domain/adapter.js';+import { coherenceScore } from '../src/infrastructure/solver-bridge.js';+import { graphIntelligenceTools } from '../src/mcp-tools/index.js';++describe('KnowledgeGraphAdapter', () => {+ beforeEach(() => resetRegistry());++ it('exports a DD matrix from KG edges', async () => {+ const adapter = new KnowledgeGraphAdapter({+ source: {+ async listEdges() {+ return [+ { fromEntity: 'Claude', toEntity: 'Anthropic', relation: 'createdBy', confidence: 0.95 },+ { fromEntity: 'Anthropic', toEntity: 'AI Safety', relation: 'focuses-on', confidence: 0.9 },+ { fromEntity: 'Claude', toEntity: 'AI Safety', relation: 'aligned-with', confidence: 0.8 },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ expect(m.size).toBe(3);+ expect(coherenceScore(m)).toBeGreaterThan(0);+ });++ it('combines multiple relations between same entities', async () => {+ const adapter = new KnowledgeGraphAdapter({+ source: {+ async listEdges() {+ return [+ { fromEntity: 'A', toEntity: 'B', relation: 'r1', confidence: 0.4 },+ { fromEntity: 'A', toEntity: 'B', relation: 'r2', confidence: 0.5 },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ const offDiag = m.entries.find((e) => e.row !== e.col);+ expect(offDiag?.value).toBeCloseTo(0.9, 5);+ });++ it('caps combined confidence at 1.0', async () => {+ const adapter = new KnowledgeGraphAdapter({+ source: {+ async listEdges() {+ return [+ { fromEntity: 'A', toEntity: 'B', relation: 'r1', confidence: 0.7 },+ { fromEntity: 'A', toEntity: 'B', relation: 'r2', confidence: 0.8 },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ const offDiag = m.entries.find((e) => e.row !== e.col);+ expect(offDiag?.value).toBe(1.0);+ });++ it('registers under canonical graphId', () => {+ const registry = getRegistry();+ registerKnowledgeGraphAdapter({+ source: { async listEdges() { return []; } },+ registry,+ });+ expect(registry.get(KNOWLEDGE_GRAPH_ID)).toBeDefined();+ });++ it('end-to-end via sublinear/page-rank-entry', async () => {+ const registry = getRegistry();+ registerKnowledgeGraphAdapter({+ source: {+ async listEdges() {+ return [+ { fromEntity: 'A', toEntity: 'B', relation: 'r', confidence: 0.5 },+ { fromEntity: 'B', toEntity: 'C', relation: 'r', confidence: 0.5 },+ { fromEntity: 'C', toEntity: 'A', relation: 'r', confidence: 0.5 },+ ];+ },+ },+ registry,+ });+ const tool = graphIntelligenceTools.find((t) => t.name === 'sublinear/page-rank-entry');+ const r = (await tool!.handler({+ graphId: KNOWLEDGE_GRAPH_ID,+ nodeId: 'B',+ maxComplexityClass: 'polynomial',+ })) as { success: boolean; result?: { score: number } };+ expect(r.success).toBe(true);+ expect(r.result?.score).toBeGreaterThan(0);+ });+});++describe('RagMemoryAdapter', () => {+ beforeEach(() => resetRegistry());++ it('exports a DD matrix from chunk edges, filtering below similarity floor', async () => {+ const adapter = new RagMemoryAdapter({+ similarityFloor: 0.5,+ source: {+ async listChunkEdges() {+ return [+ { fromChunkId: 'c1', toChunkId: 'c2', similarity: 0.8 },+ { fromChunkId: 'c1', toChunkId: 'c3', similarity: 0.3 }, // filtered+ { fromChunkId: 'c2', toChunkId: 'c3', similarity: 0.7 },+ ];+ },+ },+ });+ const m = await adapter.exportAsSparseMatrix();+ // c3 still appears via c2 β c3 (above floor); c1 β c3 is the filtered one.+ expect(m.size).toBe(3);+ expect(coherenceScore(m)).toBeGreaterThan(0);+ });++ it('namespace scopes the graph id', () => {+ expect(ragMemoryGraphId('docs')).toBe('ruflo-rag-memory:chunks:docs');+ expect(ragMemoryGraphId()).toBe('ruflo-rag-memory:chunks:default');+ });++ it('end-to-end personalized PR via seedNodes', async () => {+ const registry = getRegistry();+ registerRagMemoryAdapter({+ namespace: 'test',+ source: {+ async listChunkEdges() {+ return [+ { fromChunkId: 'c1', toChunkId: 'c2', similarity: 0.9 },+ { fromChunkId: 'c2', toChunkId: 'c3', similarity: 0.7 },+ { fromChunkId: 'c3', toChunkId: 'c1', similarity: 0.6 },+ ];+ },+ },+ registry,+ });+ const tool = graphIntelligenceTools.find((t) => t.name === 'sublinear/page-rank-entry');+ const r = (await tool!.handler({+ graphId: ragMemoryGraphId('test'),+ nodeId: 'c3',+ seedNodes: ['c1'],+ maxComplexityClass: 'polynomial',+ })) as { success: boolean; result?: { score: number } };+ expect(r.success).toBe(true);+ expect(r.result?.score).toBeGreaterThan(0);+ });+});