🌊 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
Checkpoint: File edits
rUvd82119b9e91a
diff --git a/v3/@claude-flow/memory/src/memory-graph.ts b/v3/@claude-flow/memory/src/memory-graph.tsindex 134b1d7280..e40f987b2c 100644--- a/v3/@claude-flow/memory/src/memory-graph.ts+++ b/v3/@claude-flow/memory/src/memory-graph.ts@@ -5,11 +5,9 @@* detects communities via label propagation, and provides* graph-aware ranking for search results.*- * Pure TypeScript implementation - no external graph libraries.- *+ * Pure TypeScript - no external graph libraries.* @module v3/memory/memory-graph*/-import { EventEmitter } from 'node:events';import type { IMemoryBackend, MemoryEntry, SearchResult } from './types.js';@@ -18,20 +16,13 @@ import type { IMemoryBackend, MemoryEntry, SearchResult } from './types.js';export type EdgeType = 'reference' | 'similar' | 'temporal' | 'co-accessed' | 'causal';export interface MemoryGraphConfig {- /** Auto-edge similarity threshold (default: 0.8) */- similarityThreshold?: number;- /** PageRank damping factor (default: 0.85) */- pageRankDamping?: number;- /** Maximum PageRank iterations (default: 50) */- pageRankIterations?: number;- /** PageRank convergence threshold (default: 1e-6) */- pageRankConvergence?: number;- /** Maximum graph node count (default: 5000) */- maxNodes?: number;- /** Auto-create edges from similarity search (default: true) */- enableAutoEdges?: boolean;- /** Community detection algorithm (default: 'label-propagation') */- communityAlgorithm?: 'louvain' | 'label-propagation';+ similarityThreshold?: number; // Auto-edge threshold (default: 0.8)+ pageRankDamping?: number; // Damping factor (default: 0.85)+ pageRankIterations?: number; // Max iterations (default: 50)+ pageRankConvergence?: number; // Convergence threshold (default: 1e-6)+ maxNodes?: number; // Cap graph size (default: 5000)+ enableAutoEdges?: boolean; // Auto-create edges from similarity (default: true)+ communityAlgorithm?: 'louvain' | 'label-propagation'; // default: label-propagation}export interface GraphNode {@@ -66,8 +57,6 @@ export interface GraphStats {minPageRank: number;}-// ===== Default Configuration =====-const DEFAULT_CONFIG: Required<MemoryGraphConfig> = {similarityThreshold: 0.8,pageRankDamping: 0.85,@@ -78,14 +67,10 @@ const DEFAULT_CONFIG: Required<MemoryGraphConfig> = {communityAlgorithm: 'label-propagation',};-// ===== MemoryGraph Class =====-/*** Knowledge graph built from memory entry references.- *- * Supports PageRank computation, community detection via label propagation,- * and graph-aware result ranking that blends vector similarity with- * structural importance.+ * Supports PageRank, community detection (label propagation),+ * and graph-aware result ranking blending vector similarity with structural importance.*/export class MemoryGraph extends EventEmitter {private nodes: Map<string, GraphNode> = new Map();@@ -101,76 +86,48 @@ export class MemoryGraph extends EventEmitter {this.config = { ...DEFAULT_CONFIG, ...config };}- // ===== Graph Construction =====-- /**- * Build the graph from all entries in a backend.- * Queries entries up to maxNodes, creates nodes and reference edges.- */+ /** Build graph from all entries in a backend. Creates nodes and reference edges. */async buildFromBackend(backend: IMemoryBackend, namespace?: string): Promise<void> {const entries = await backend.query({- type: namespace ? 'hybrid' : 'hybrid',+ type: 'hybrid',namespace,limit: this.config.maxNodes,});-for (const entry of entries) {this.addNode(entry);}-for (const entry of entries) {for (const refId of entry.references) {this.addEdge(entry.id, refId, 'reference');}}-this.dirty = true;this.emit('graph:built', { nodeCount: this.nodes.size });}- /**- * Add a node to the graph from a MemoryEntry.- * Silently skips if the graph has reached maxNodes capacity.- */+ /** Add a node from a MemoryEntry. Skips silently at maxNodes capacity. */addNode(entry: MemoryEntry): void {if (this.nodes.size >= this.config.maxNodes && !this.nodes.has(entry.id)) {return;}-- const node: GraphNode = {+ this.nodes.set(entry.id, {id: entry.id,category: (entry.metadata?.category as string) || 'general',confidence: (entry.metadata?.confidence as number) || 0.5,accessCount: entry.accessCount,createdAt: entry.createdAt,- };-- this.nodes.set(entry.id, node);-- if (!this.edges.has(entry.id)) {- this.edges.set(entry.id, []);- }- if (!this.reverseEdges.has(entry.id)) {- this.reverseEdges.set(entry.id, new Set());- }-+ });+ if (!this.edges.has(entry.id)) this.edges.set(entry.id, []);+ if (!this.reverseEdges.has(entry.id)) this.reverseEdges.set(entry.id, new Set());this.dirty = true;}- /**- * Add a directed edge between two existing nodes.- * Silently skips if either node is missing from the graph.- * Updates weight to the maximum if an edge already exists.- */+ /** Add a directed edge. Skips if either node missing. Updates weight to max if exists. */addEdge(sourceId: string, targetId: string, type: EdgeType, weight: number = 1.0): void {- if (!this.nodes.has(sourceId) || !this.nodes.has(targetId)) {- return;- }+ if (!this.nodes.has(sourceId) || !this.nodes.has(targetId)) return;const edgeList = this.edges.get(sourceId) || [];- if (!this.edges.has(sourceId)) {- this.edges.set(sourceId, edgeList);- }+ if (!this.edges.has(sourceId)) this.edges.set(sourceId, edgeList);const existing = edgeList.find((e) => e.targetId === targetId);if (existing) {@@ -179,64 +136,40 @@ export class MemoryGraph extends EventEmitter {edgeList.push({ targetId, type, weight });}- // Update reverse edge index- if (!this.reverseEdges.has(targetId)) {- this.reverseEdges.set(targetId, new Set());- }+ if (!this.reverseEdges.has(targetId)) this.reverseEdges.set(targetId, new Set());this.reverseEdges.get(targetId)!.add(sourceId);-this.dirty = true;}- /**- * Remove a node and all its associated edges from the graph.- */+ /** Remove a node and all associated edges (both directions). */removeNode(id: string): void {- if (!this.nodes.has(id)) {- return;- }+ if (!this.nodes.has(id)) return;// Remove outgoing edges and their reverse entries- const outgoing = this.edges.get(id) || [];- for (const edge of outgoing) {- const revSet = this.reverseEdges.get(edge.targetId);- if (revSet) {- revSet.delete(id);- }+ for (const edge of this.edges.get(id) || []) {+ this.reverseEdges.get(edge.targetId)?.delete(id);}this.edges.delete(id);- // Remove incoming edges (where this node is a target)+ // Remove incoming edges pointing to this nodeconst incoming = this.reverseEdges.get(id);if (incoming) {for (const sourceId of incoming) {- const sourceEdges = this.edges.get(sourceId);- if (sourceEdges) {- const filtered = sourceEdges.filter((e) => e.targetId !== id);- this.edges.set(sourceId, filtered);- }+ const srcEdges = this.edges.get(sourceId);+ if (srcEdges) this.edges.set(sourceId, srcEdges.filter((e) => e.targetId !== id));}}this.reverseEdges.delete(id);-this.nodes.delete(id);this.pageRanks.delete(id);this.communities.delete(id);-this.dirty = true;}- // ===== Similarity Edges =====-- /**- * Add similarity edges for an entry by searching the backend for similar entries.- * Returns the number of edges added.- */+ /** Add similarity edges by searching backend. Returns count of edges added. */async addSimilarityEdges(backend: IMemoryBackend, entryId: string): Promise<number> {const entry = await backend.get(entryId);- if (!entry || !entry.embedding) {- return 0;- }+ if (!entry || !entry.embedding) return 0;const results = await backend.search(entry.embedding, {k: 20,@@ -245,28 +178,19 @@ export class MemoryGraph extends EventEmitter {let added = 0;for (const result of results) {- if (result.entry.id === entryId) {- continue;- }+ if (result.entry.id === entryId) continue;if (result.score >= this.config.similarityThreshold) {const hadEdge = this.hasEdge(entryId, result.entry.id);this.addEdge(entryId, result.entry.id, 'similar', result.score);- if (!hadEdge) {- added++;- }+ if (!hadEdge) added++;}}-return added;}- // ===== PageRank =====-/**- * Compute PageRank scores using the power iteration method.- * Handles dangling nodes (no outgoing edges) by redistributing their- * rank mass equally across all nodes.- * Returns a map of node ID to PageRank score.+ * Compute PageRank via power iteration with dangling node redistribution.+ * Returns map of node ID to PageRank score.*/computePageRank(): Map<string, number> {const N = this.nodes.size;@@ -277,20 +201,15 @@ export class MemoryGraph extends EventEmitter {}const d = this.config.pageRankDamping;- const initialRank = 1 / N;-- // Initialize ranksfor (const nodeId of this.nodes.keys()) {- this.pageRanks.set(nodeId, initialRank);+ this.pageRanks.set(nodeId, 1 / N);}// Identify dangling nodes (no outgoing edges)const danglingNodes: string[] = [];for (const nodeId of this.nodes.keys()) {- const outEdges = this.edges.get(nodeId);- if (!outEdges || outEdges.length === 0) {- danglingNodes.push(nodeId);- }+ const out = this.edges.get(nodeId);+ if (!out || out.length === 0) danglingNodes.push(nodeId);}let iterations = 0;@@ -298,7 +217,6 @@ export class MemoryGraph extends EventEmitter {let maxDelta = 0;const newRanks = new Map<string, number>();- // Compute dangling node rank sum for redistributionlet danglingSum = 0;for (const nodeId of danglingNodes) {danglingSum += this.pageRanks.get(nodeId) || 0;@@ -313,8 +231,6 @@ export class MemoryGraph extends EventEmitter {sum += (this.pageRanks.get(sourceId) || 0) / outDegree;}}-- // Redistribute dangling rank mass equallyconst newRank = (1 - d) / N + d * (sum + danglingSum / N);newRanks.set(nodeId, newRank);maxDelta = Math.max(maxDelta, Math.abs(newRank - (this.pageRanks.get(nodeId) || 0)));@@ -322,10 +238,7 @@ export class MemoryGraph extends EventEmitter {this.pageRanks = newRanks;iterations = iter + 1;-- if (maxDelta < this.config.pageRankConvergence) {- break;- }+ if (maxDelta < this.config.pageRankConvergence) break;}this.dirty = false;@@ -333,46 +246,27 @@ export class MemoryGraph extends EventEmitter {return new Map(this.pageRanks);}- // ===== Community Detection =====-- /**- * Detect communities using the label propagation algorithm.- * Returns a map of node ID to community label.- */+ /** Detect communities using label propagation. Returns map of nodeId to communityId. */detectCommunities(): Map<string, string> {const labels = new Map<string, string>();+ for (const nodeId of this.nodes.keys()) labels.set(nodeId, nodeId);- // Initialize: each node is its own community- for (const nodeId of this.nodes.keys()) {- labels.set(nodeId, nodeId);- }-- const MAX_ITERATIONS = 20;-- for (let iter = 0; iter < MAX_ITERATIONS; iter++) {+ for (let iter = 0; iter < 20; iter++) {let changed = false;const nodeIds = this.shuffleArray([...this.nodes.keys()]);for (const nodeId of nodeIds) {const labelCounts = new Map<string, number>();- // Count labels from outgoing neighbors- const outEdges = this.edges.get(nodeId) || [];- for (const edge of outEdges) {- const neighborLabel = labels.get(edge.targetId);- if (neighborLabel !== undefined) {- labelCounts.set(neighborLabel, (labelCounts.get(neighborLabel) || 0) + edge.weight);- }+ for (const edge of this.edges.get(nodeId) || []) {+ const lbl = labels.get(edge.targetId);+ if (lbl !== undefined) labelCounts.set(lbl, (labelCounts.get(lbl) || 0) + edge.weight);}-- // Count labels from incoming neighborsconst incoming = this.reverseEdges.get(nodeId);if (incoming) {for (const sourceId of incoming) {- const neighborLabel = labels.get(sourceId);- if (neighborLabel !== undefined) {- labelCounts.set(neighborLabel, (labelCounts.get(neighborLabel) || 0) + 1);- }+ const lbl = labels.get(sourceId);+ if (lbl !== undefined) labelCounts.set(lbl, (labelCounts.get(lbl) || 0) + 1);}}@@ -380,74 +274,47 @@ export class MemoryGraph extends EventEmitter {let maxLabel = labels.get(nodeId)!;let maxCount = 0;for (const [label, count] of labelCounts) {- if (count > maxCount) {- maxCount = count;- maxLabel = label;- }+ if (count > maxCount) { maxCount = count; maxLabel = label; }}-if (maxLabel !== labels.get(nodeId)) {labels.set(nodeId, maxLabel);changed = true;}}}-- if (!changed) {- break;- }+ if (!changed) break;}this.communities = labels;- this.emit('communities:detected', {- communityCount: new Set(labels.values()).size,- });+ this.emit('communities:detected', { communityCount: new Set(labels.values()).size });return new Map(this.communities);}- // ===== Graph-Aware Ranking =====-/**- * Rank search results using a blend of vector similarity and PageRank.- *- * @param searchResults - Original vector search results+ * Rank search results blending vector similarity and PageRank.* @param alpha - Weight for vector score (default 0.7). PageRank weight is (1 - alpha).- * @returns Ranked results with combined scores*/rankWithGraph(searchResults: SearchResult[], alpha: number = 0.7): RankedResult[] {- if (this.dirty) {- this.computePageRank();- }-+ if (this.dirty) this.computePageRank();const N = this.nodes.size || 1;return searchResults.map((result) => {const pageRank = this.pageRanks.get(result.entry.id) || 0;- const combinedScore = alpha * result.score + (1 - alpha) * (pageRank * N);- const community = this.communities.get(result.entry.id);-return {entry: result.entry,score: result.score,pageRank,- combinedScore,- community,+ combinedScore: alpha * result.score + (1 - alpha) * (pageRank * N),+ community: this.communities.get(result.entry.id),};}).sort((a, b) => b.combinedScore - a.combinedScore);}- // ===== Query Methods =====-- /**- * Get the top N nodes by PageRank score.- */+ /** Get top N nodes by PageRank score. */getTopNodes(n: number): Array<{ id: string; pageRank: number; community: string }> {- if (this.dirty) {- this.computePageRank();- }-+ if (this.dirty) this.computePageRank();return [...this.pageRanks.entries()].sort((a, b) => b[1] - a[1]).slice(0, n)@@ -458,13 +325,7 @@ export class MemoryGraph extends EventEmitter {}));}- /**- * Get all neighbors reachable from a node up to the given depth via BFS.- *- * @param id - Starting node ID- * @param depth - Maximum traversal depth (default: 1)- * @returns Set of reachable node IDs (excluding the start node)- */+ /** BFS neighbors from a node up to given depth. Excludes the start node. */getNeighbors(id: string, depth: number = 1): Set<string> {const visited = new Set<string>();let frontier = new Set<string>([id]);@@ -472,8 +333,7 @@ export class MemoryGraph extends EventEmitter {for (let d = 0; d < depth; d++) {const nextFrontier = new Set<string>();for (const nodeId of frontier) {- const outEdges = this.edges.get(nodeId) || [];- for (const edge of outEdges) {+ for (const edge of this.edges.get(nodeId) || []) {if (!visited.has(edge.targetId) && edge.targetId !== id) {visited.add(edge.targetId);nextFrontier.add(edge.targetId);@@ -481,26 +341,17 @@ export class MemoryGraph extends EventEmitter {}}frontier = nextFrontier;- if (frontier.size === 0) {- break;- }+ if (frontier.size === 0) break;}-return visited;}- /**- * Get statistics about the current graph state.- */+ /** Get statistics about the current graph state. */getStats(): GraphStats {let totalEdges = 0;- for (const edgeList of this.edges.values()) {- totalEdges += edgeList.length;- }+ for (const edgeList of this.edges.values()) totalEdges += edgeList.length;const nodeCount = this.nodes.size;- const uniqueCommunities = new Set(this.communities.values());-let maxPageRank = 0;let minPageRank = Infinity;if (this.pageRanks.size > 0) {@@ -516,7 +367,7 @@ export class MemoryGraph extends EventEmitter {nodeCount,edgeCount: totalEdges,avgDegree: nodeCount > 0 ? totalEdges / nodeCount : 0,- communityCount: uniqueCommunities.size,+ communityCount: new Set(this.communities.values()).size,pageRankComputed: !this.dirty,maxPageRank,minPageRank,@@ -525,18 +376,11 @@ export class MemoryGraph extends EventEmitter {// ===== Internal Helpers =====- /**- * Check whether a directed edge exists between two nodes.- */private hasEdge(sourceId: string, targetId: string): boolean {const edgeList = this.edges.get(sourceId);- if (!edgeList) return false;- return edgeList.some((e) => e.targetId === targetId);+ return edgeList ? edgeList.some((e) => e.targetId === targetId) : false;}- /**- * Fisher-Yates shuffle for randomized iteration order.- */private shuffleArray<T>(arr: T[]): T[] {const shuffled = [...arr];for (let i = shuffled.length - 1; i > 0; i--) {