🌊 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 edit:
rUv7a7c7dcdc91d
diff --git a/v3/@claude-flow/memory/src/agentdb-backend.ts b/v3/@claude-flow/memory/src/agentdb-backend.tsnew file mode 100644index 0000000000..aa301ca236--- /dev/null+++ b/v3/@claude-flow/memory/src/agentdb-backend.ts@@ -0,0 +1,898 @@+/**+ * AgentDB Backend - Integration with [email protected]+ *+ * Provides IMemoryBackend implementation using AgentDB with:+ * - HNSW vector search (150x-12,500x faster than brute-force)+ * - Native or WASM backend support with graceful fallback+ * - Optional dependency handling (works without hnswlib-node)+ * - Seamless integration with HybridBackend+ *+ * @module v3/memory/agentdb-backend+ */++import { EventEmitter } from 'node:events';+import {+ IMemoryBackend,+ MemoryEntry,+ MemoryEntryInput,+ MemoryEntryUpdate,+ MemoryQuery,+ SearchOptions,+ SearchResult,+ BackendStats,+ HealthCheckResult,+ ComponentHealth,+ MemoryType,+ EmbeddingGenerator,+ generateMemoryId,+ createDefaultEntry,+ CacheStats,+ HNSWStats,+} from './types.js';++// ===== AgentDB Optional Import =====++let AgentDB: any;+let HNSWIndex: any;+let isHnswlibAvailable: (() => Promise<boolean>) | undefined;++try {+ const agentdbModule = await import('agentdb');+ AgentDB = agentdbModule.AgentDB || agentdbModule.default;+ HNSWIndex = agentdbModule.HNSWIndex;+ isHnswlibAvailable = agentdbModule.isHnswlibAvailable;+} catch (error) {+ console.warn('AgentDB not available, AgentDBBackend will not be functional:', error);+}++// ===== Configuration =====++/**+ * Configuration for AgentDB Backend+ */+export interface AgentDBBackendConfig {+ /** Database path for persistence */+ dbPath?: string;++ /** Namespace for memory organization */+ namespace?: string;++ /** Force WASM backend (skip native hnswlib) */+ forceWasm?: boolean;++ /** Vector backend: 'auto', 'ruvector', 'hnswlib' */+ vectorBackend?: 'auto' | 'ruvector' | 'hnswlib';++ /** Vector dimensions (default: 1536) */+ vectorDimension?: number;++ /** HNSW M parameter */+ hnswM?: number;++ /** HNSW efConstruction parameter */+ hnswEfConstruction?: number;++ /** HNSW efSearch parameter */+ hnswEfSearch?: number;++ /** Enable caching */+ cacheEnabled?: boolean;++ /** Embedding generator function */+ embeddingGenerator?: EmbeddingGenerator;++ /** Maximum entries */+ maxEntries?: number;+}++/**+ * Default configuration+ */+const DEFAULT_CONFIG: Required<+ Omit<AgentDBBackendConfig, 'dbPath' | 'embeddingGenerator'>+> = {+ namespace: 'default',+ forceWasm: false,+ vectorBackend: 'auto',+ vectorDimension: 1536,+ hnswM: 16,+ hnswEfConstruction: 200,+ hnswEfSearch: 100,+ cacheEnabled: true,+ maxEntries: 1000000,+};++// ===== AgentDB Backend Implementation =====++/**+ * AgentDB Backend+ *+ * Integrates AgentDB for vector search with the V3 memory system.+ * Provides 150x-12,500x faster search compared to brute-force approaches.+ *+ * Features:+ * - HNSW indexing for fast approximate nearest neighbor search+ * - Automatic fallback: native hnswlib → ruvector → WASM+ * - Graceful handling of optional native dependencies+ * - Semantic search with filtering+ * - Compatible with HybridBackend for combined SQLite+AgentDB queries+ */+export class AgentDBBackend extends EventEmitter implements IMemoryBackend {+ private config: Required<+ Omit<AgentDBBackendConfig, 'dbPath' | 'embeddingGenerator'>+ > & {+ dbPath?: string;+ embeddingGenerator?: EmbeddingGenerator;+ };+ private agentdb: any;+ private initialized: boolean = false;+ private available: boolean = false;++ // In-memory storage for compatibility+ private entries: Map<string, MemoryEntry> = new Map();+ private namespaceIndex: Map<string, Set<string>> = new Map();+ private keyIndex: Map<string, string> = new Map();++ // Performance tracking+ private stats = {+ queryCount: 0,+ totalQueryTime: 0,+ searchCount: 0,+ totalSearchTime: 0,+ };++ constructor(config: AgentDBBackendConfig = {}) {+ super();+ this.config = { ...DEFAULT_CONFIG, ...config };+ this.available = AgentDB !== undefined;++ if (!this.available) {+ console.warn(+ 'AgentDB not available. Install [email protected] for vector search support.'+ );+ }+ }++ /**+ * Initialize AgentDB+ */+ async initialize(): Promise<void> {+ if (this.initialized) return;++ if (!this.available) {+ console.warn('AgentDB not available, using fallback in-memory storage');+ this.initialized = true;+ return;+ }++ try {+ // Initialize AgentDB with config+ this.agentdb = new AgentDB({+ dbPath: this.config.dbPath || ':memory:',+ namespace: this.config.namespace,+ forceWasm: this.config.forceWasm,+ vectorBackend: this.config.vectorBackend,+ vectorDimension: this.config.vectorDimension,+ });++ await this.agentdb.initialize();++ // Create memory_entries table if it doesn't exist+ await this.createSchema();++ this.initialized = true;+ this.emit('initialized', {+ backend: this.agentdb.vectorBackendName,+ isWasm: this.agentdb.isWasm,+ });+ } catch (error) {+ console.error('Failed to initialize AgentDB:', error);+ this.available = false;+ this.initialized = true;+ this.emit('initialization:failed', { error });+ }+ }++ /**+ * Shutdown AgentDB+ */+ async shutdown(): Promise<void> {+ if (!this.initialized) return;++ if (this.agentdb) {+ await this.agentdb.close();+ }++ this.initialized = false;+ this.emit('shutdown');+ }++ /**+ * Store a memory entry+ */+ async store(entry: MemoryEntry): Promise<void> {+ // Generate embedding if needed+ if (entry.content && !entry.embedding && this.config.embeddingGenerator) {+ entry.embedding = await this.config.embeddingGenerator(entry.content);+ }++ // Store in-memory for quick access+ this.entries.set(entry.id, entry);++ // Update indexes+ this.updateIndexes(entry);++ // Store in AgentDB if available+ if (this.agentdb) {+ await this.storeInAgentDB(entry);+ }++ this.emit('entry:stored', { id: entry.id });+ }++ /**+ * Get entry by ID+ */+ async get(id: string): Promise<MemoryEntry | null> {+ // Check in-memory first+ const cached = this.entries.get(id);+ if (cached) return cached;++ // Query AgentDB if available+ if (this.agentdb) {+ return this.getFromAgentDB(id);+ }++ return null;+ }++ /**+ * Get entry by key+ */+ async getByKey(namespace: string, key: string): Promise<MemoryEntry | null> {+ const keyIndexKey = `${namespace}:${key}`;+ const id = this.keyIndex.get(keyIndexKey);+ if (!id) return null;+ return this.get(id);+ }++ /**+ * Update entry+ */+ async update(id: string, update: MemoryEntryUpdate): Promise<MemoryEntry | null> {+ const entry = this.entries.get(id);+ if (!entry) return null;++ // Apply updates+ if (update.content !== undefined) {+ entry.content = update.content;+ // Regenerate embedding if needed+ if (this.config.embeddingGenerator) {+ entry.embedding = await this.config.embeddingGenerator(entry.content);+ }+ }++ if (update.tags !== undefined) {+ entry.tags = update.tags;+ }++ if (update.metadata !== undefined) {+ entry.metadata = { ...entry.metadata, ...update.metadata };+ }++ if (update.accessLevel !== undefined) {+ entry.accessLevel = update.accessLevel;+ }++ if (update.expiresAt !== undefined) {+ entry.expiresAt = update.expiresAt;+ }++ if (update.references !== undefined) {+ entry.references = update.references;+ }++ entry.updatedAt = Date.now();+ entry.version++;++ // Update in AgentDB+ if (this.agentdb) {+ await this.updateInAgentDB(entry);+ }++ this.emit('entry:updated', { id });+ return entry;+ }++ /**+ * Delete entry+ */+ async delete(id: string): Promise<boolean> {+ const entry = this.entries.get(id);+ if (!entry) return false;++ // Remove from indexes+ this.entries.delete(id);+ this.namespaceIndex.get(entry.namespace)?.delete(id);+ const keyIndexKey = `${entry.namespace}:${entry.key}`;+ this.keyIndex.delete(keyIndexKey);++ // Delete from AgentDB+ if (this.agentdb) {+ await this.deleteFromAgentDB(id);+ }++ this.emit('entry:deleted', { id });+ return true;+ }++ /**+ * Query entries+ */+ async query(query: MemoryQuery): Promise<MemoryEntry[]> {+ const startTime = performance.now();+ let results: MemoryEntry[] = [];++ if (query.type === 'semantic' && (query.embedding || query.content)) {+ // Use semantic search+ const searchResults = await this.semanticSearch(query);+ results = searchResults.map((r) => r.entry);+ } else {+ // Fallback to in-memory filtering+ results = this.queryInMemory(query);+ }++ const duration = performance.now() - startTime;+ this.stats.queryCount++;+ this.stats.totalQueryTime += duration;++ return results;+ }++ /**+ * Semantic vector search+ */+ async search(+ embedding: Float32Array,+ options: SearchOptions+ ): Promise<SearchResult[]> {+ const startTime = performance.now();++ if (!this.agentdb) {+ // Fallback to brute-force search+ return this.bruteForceSearch(embedding, options);+ }++ try {+ // Use AgentDB HNSW search+ const results = await this.searchWithAgentDB(embedding, options);++ const duration = performance.now() - startTime;+ this.stats.searchCount++;+ this.stats.totalSearchTime += duration;++ return results;+ } catch (error) {+ console.error('AgentDB search failed, falling back to brute-force:', error);+ return this.bruteForceSearch(embedding, options);+ }+ }++ /**+ * Bulk insert+ */+ async bulkInsert(entries: MemoryEntry[]): Promise<void> {+ for (const entry of entries) {+ await this.store(entry);+ }+ }++ /**+ * Bulk delete+ */+ async bulkDelete(ids: string[]): Promise<number> {+ let deleted = 0;+ for (const id of ids) {+ if (await this.delete(id)) {+ deleted++;+ }+ }+ return deleted;+ }++ /**+ * Count entries+ */+ async count(namespace?: string): Promise<number> {+ if (namespace) {+ return this.namespaceIndex.get(namespace)?.size || 0;+ }+ return this.entries.size;+ }++ /**+ * List namespaces+ */+ async listNamespaces(): Promise<string[]> {+ return Array.from(this.namespaceIndex.keys());+ }++ /**+ * Clear namespace+ */+ async clearNamespace(namespace: string): Promise<number> {+ const ids = this.namespaceIndex.get(namespace);+ if (!ids) return 0;++ let deleted = 0;+ for (const id of ids) {+ if (await this.delete(id)) {+ deleted++;+ }+ }++ return deleted;+ }++ /**+ * Get statistics+ */+ async getStats(): Promise<BackendStats> {+ const entriesByNamespace: Record<string, number> = {};+ for (const [namespace, ids] of this.namespaceIndex) {+ entriesByNamespace[namespace] = ids.size;+ }++ const entriesByType: Record<MemoryType, number> = {+ episodic: 0,+ semantic: 0,+ procedural: 0,+ working: 0,+ cache: 0,+ };++ for (const entry of this.entries.values()) {+ entriesByType[entry.type]++;+ }++ // Get HNSW stats if available+ let hnswStats: HNSWStats | undefined;+ if (this.agentdb && HNSWIndex) {+ try {+ const hnsw = this.agentdb.getController('hnsw');+ if (hnsw) {+ const stats = hnsw.getStats();+ hnswStats = {+ vectorCount: stats.numElements || 0,+ memoryUsage: 0,+ avgSearchTime: stats.avgSearchTimeMs || 0,+ buildTime: stats.lastBuildTime || 0,+ compressionRatio: 1.0,+ };+ }+ } catch {+ // HNSW not available+ }+ }++ return {+ totalEntries: this.entries.size,+ entriesByNamespace,+ entriesByType,+ memoryUsage: this.estimateMemoryUsage(),+ hnswStats,+ avgQueryTime:+ this.stats.queryCount > 0+ ? this.stats.totalQueryTime / this.stats.queryCount+ : 0,+ avgSearchTime:+ this.stats.searchCount > 0+ ? this.stats.totalSearchTime / this.stats.searchCount+ : 0,+ };+ }++ /**+ * Health check+ */+ async healthCheck(): Promise<HealthCheckResult> {+ const issues: string[] = [];+ const recommendations: string[] = [];++ // Check AgentDB availability+ const storageHealth: ComponentHealth = this.agentdb+ ? { status: 'healthy', latency: 0 }+ : {+ status: 'degraded',+ latency: 0,+ message: 'AgentDB not available, using fallback',+ };++ // Check index health+ const indexHealth: ComponentHealth = { status: 'healthy', latency: 0 };+ if (!this.agentdb) {+ indexHealth.status = 'degraded';+ indexHealth.message = 'HNSW index not available';+ recommendations.push('Install agentdb for 150x-12,500x faster vector search');+ }++ // Check cache health+ const cacheHealth: ComponentHealth = { status: 'healthy', latency: 0 };++ const status =+ storageHealth.status === 'unhealthy' || indexHealth.status === 'unhealthy'+ ? 'unhealthy'+ : storageHealth.status === 'degraded' || indexHealth.status === 'degraded'+ ? 'degraded'+ : 'healthy';++ return {+ status,+ components: {+ storage: storageHealth,+ index: indexHealth,+ cache: cacheHealth,+ },+ timestamp: Date.now(),+ issues,+ recommendations,+ };+ }++ // ===== Private Methods =====++ /**+ * Create database schema+ */+ private async createSchema(): Promise<void> {+ if (!this.agentdb?.database) return;++ const db = this.agentdb.database;++ // Create memory_entries table+ await db.run(`+ CREATE TABLE IF NOT EXISTS memory_entries (+ id TEXT PRIMARY KEY,+ key TEXT NOT NULL,+ content TEXT NOT NULL,+ embedding BLOB,+ type TEXT NOT NULL,+ namespace TEXT NOT NULL,+ tags TEXT,+ metadata TEXT,+ owner_id TEXT,+ access_level TEXT NOT NULL,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ expires_at INTEGER,+ version INTEGER NOT NULL,+ references TEXT,+ access_count INTEGER DEFAULT 0,+ last_accessed_at INTEGER+ )+ `);++ // Create indexes+ await db.run(+ 'CREATE INDEX IF NOT EXISTS idx_namespace ON memory_entries(namespace)'+ );+ await db.run('CREATE INDEX IF NOT EXISTS idx_key ON memory_entries(key)');+ await db.run('CREATE INDEX IF NOT EXISTS idx_type ON memory_entries(type)');+ }++ /**+ * Store entry in AgentDB+ */+ private async storeInAgentDB(entry: MemoryEntry): Promise<void> {+ if (!this.agentdb?.database) return;++ const db = this.agentdb.database;++ await db.run(+ `+ INSERT OR REPLACE INTO memory_entries+ (id, key, content, embedding, type, namespace, tags, metadata, owner_id,+ access_level, created_at, updated_at, expires_at, version, references,+ access_count, last_accessed_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `,+ [+ entry.id,+ entry.key,+ entry.content,+ entry.embedding ? Buffer.from(entry.embedding.buffer) : null,+ entry.type,+ entry.namespace,+ JSON.stringify(entry.tags),+ JSON.stringify(entry.metadata),+ entry.ownerId || null,+ entry.accessLevel,+ entry.createdAt,+ entry.updatedAt,+ entry.expiresAt || null,+ entry.version,+ JSON.stringify(entry.references),+ entry.accessCount,+ entry.lastAccessedAt,+ ]+ );++ // Add to vector index if HNSW is available+ if (entry.embedding && HNSWIndex) {+ try {+ const hnsw = this.agentdb.getController('hnsw');+ if (hnsw) {+ // Convert string ID to number for HNSW (use hash)+ const numericId = this.stringIdToNumeric(entry.id);+ hnsw.addVector(numericId, entry.embedding);+ }+ } catch {+ // HNSW not available+ }+ }+ }++ /**+ * Get entry from AgentDB+ */+ private async getFromAgentDB(id: string): Promise<MemoryEntry | null> {+ if (!this.agentdb?.database) return null;++ const db = this.agentdb.database;+ const row = await db.get('SELECT * FROM memory_entries WHERE id = ?', [id]);++ if (!row) return null;++ return this.rowToEntry(row);+ }++ /**+ * Update entry in AgentDB+ */+ private async updateInAgentDB(entry: MemoryEntry): Promise<void> {+ await this.storeInAgentDB(entry);+ }++ /**+ * Delete entry from AgentDB+ */+ private async deleteFromAgentDB(id: string): Promise<void> {+ if (!this.agentdb?.database) return;++ const db = this.agentdb.database;+ await db.run('DELETE FROM memory_entries WHERE id = ?', [id]);+ }++ /**+ * Search with AgentDB HNSW+ */+ private async searchWithAgentDB(+ embedding: Float32Array,+ options: SearchOptions+ ): Promise<SearchResult[]> {+ if (!this.agentdb || !HNSWIndex) {+ return [];+ }++ try {+ const hnsw = this.agentdb.getController('hnsw');+ if (!hnsw) {+ return this.bruteForceSearch(embedding, options);+ }++ const results = await hnsw.search(embedding, options.k, {+ threshold: options.threshold,+ });++ const searchResults: SearchResult[] = [];++ for (const result of results) {+ const id = this.numericIdToString(result.id);+ const entry = await this.get(id);+ if (!entry) continue;++ searchResults.push({+ entry,+ score: result.similarity,+ distance: result.distance,+ });+ }++ return searchResults;+ } catch (error) {+ console.error('HNSW search failed:', error);+ return this.bruteForceSearch(embedding, options);+ }+ }++ /**+ * Brute-force vector search fallback+ */+ private bruteForceSearch(+ embedding: Float32Array,+ options: SearchOptions+ ): SearchResult[] {+ const results: SearchResult[] = [];++ for (const entry of this.entries.values()) {+ if (!entry.embedding) continue;++ const distance = this.cosineSimilarity(embedding, entry.embedding);+ const score = 1 - distance;++ if (options.threshold && score < options.threshold) continue;++ results.push({ entry, score, distance });+ }++ // Sort by score descending+ results.sort((a, b) => b.score - a.score);++ return results.slice(0, options.k);+ }++ /**+ * Semantic search helper+ */+ private async semanticSearch(query: MemoryQuery): Promise<SearchResult[]> {+ let embedding = query.embedding;++ if (!embedding && query.content && this.config.embeddingGenerator) {+ embedding = await this.config.embeddingGenerator(query.content);+ }++ if (!embedding) {+ return [];+ }++ return this.search(embedding, {+ k: query.limit,+ threshold: query.threshold,+ filters: query,+ });+ }++ /**+ * In-memory query fallback+ */+ private queryInMemory(query: MemoryQuery): MemoryEntry[] {+ let results = Array.from(this.entries.values());++ // Apply filters+ if (query.namespace) {+ results = results.filter((e) => e.namespace === query.namespace);+ }++ if (query.key) {+ results = results.filter((e) => e.key === query.key);+ }++ if (query.keyPrefix) {+ results = results.filter((e) => e.key.startsWith(query.keyPrefix!));+ }++ if (query.tags && query.tags.length > 0) {+ results = results.filter((e) =>+ query.tags!.every((tag) => e.tags.includes(tag))+ );+ }++ return results.slice(0, query.limit);+ }++ /**+ * Update in-memory indexes+ */+ private updateIndexes(entry: MemoryEntry): void {+ const namespace = entry.namespace;++ if (!this.namespaceIndex.has(namespace)) {+ this.namespaceIndex.set(namespace, new Set());+ }+ this.namespaceIndex.get(namespace)!.add(entry.id);++ const keyIndexKey = `${namespace}:${entry.key}`;+ this.keyIndex.set(keyIndexKey, entry.id);+ }++ /**+ * Convert DB row to MemoryEntry+ */+ private rowToEntry(row: any): MemoryEntry {+ return {+ id: row.id,+ key: row.key,+ content: row.content,+ embedding: row.embedding+ ? new Float32Array(new Uint8Array(row.embedding).buffer)+ : undefined,+ type: row.type,+ namespace: row.namespace,+ tags: JSON.parse(row.tags || '[]'),+ metadata: JSON.parse(row.metadata || '{}'),+ ownerId: row.owner_id,+ accessLevel: row.access_level,+ createdAt: row.created_at,+ updatedAt: row.updated_at,+ expiresAt: row.expires_at,+ version: row.version,+ references: JSON.parse(row.references || '[]'),+ accessCount: row.access_count || 0,+ lastAccessedAt: row.last_accessed_at || row.created_at,+ };+ }++ /**+ * Convert string ID to numeric for HNSW+ */+ private stringIdToNumeric(id: string): number {+ let hash = 0;+ for (let i = 0; i < id.length; i++) {+ hash = (hash << 5) - hash + id.charCodeAt(i);+ hash |= 0;+ }+ return Math.abs(hash);+ }++ /**+ * Convert numeric ID back to string (placeholder)+ */+ private numericIdToString(numericId: number): string {+ // In practice, maintain a bidirectional map+ for (const [id, entry] of this.entries) {+ if (this.stringIdToNumeric(id) === numericId) {+ return id;+ }+ }+ return String(numericId);+ }++ /**+ * Cosine similarity+ */+ private cosineSimilarity(a: Float32Array, b: Float32Array): number {+ let dotProduct = 0;+ let normA = 0;+ let normB = 0;++ for (let i = 0; i < a.length; i++) {+ dotProduct += a[i] * b[i];+ normA += a[i] * a[i];+ normB += b[i] * b[i];+ }++ return 1 - dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));+ }++ /**+ * Estimate memory usage+ */+ private estimateMemoryUsage(): number {+ let total = 0;++ for (const entry of this.entries.values()) {+ total += entry.content.length * 2;+ if (entry.embedding) {+ total += entry.embedding.length * 4;+ }+ }++ return total;+ }++ /**+ * Check if AgentDB is available+ */+ isAvailable(): boolean {+ return this.available;+ }++ /**+ * Get underlying AgentDB instance+ */+ getAgentDB(): any {+ return this.agentdb;+ }+}++export default AgentDBBackend;diff --git a/v3/@claude-flow/memory/src/hybrid-backend.ts b/v3/@claude-flow/memory/src/hybrid-backend.tsindex 5304965a9f..7b2d309182 100644--- a/v3/@claude-flow/memory/src/hybrid-backend.ts+++ b/v3/@claude-flow/memory/src/hybrid-backend.ts@@ -25,7 +25,7 @@ import {QueryType,} from './types.js';import { SQLiteBackend, SQLiteBackendConfig } from './sqlite-backend.js';-import { AgentDBAdapter, AgentDBAdapterConfig } from './agentdb-adapter.js';+import { AgentDBBackend, AgentDBBackendConfig } from './agentdb-backend.js';/*** Configuration for HybridBackenddiff --git a/v3/@claude-flow/performance/src/examples/flash-attention-demo.ts b/v3/@claude-flow/performance/src/examples/flash-attention-demo.tsnew file mode 100644index 0000000000..2517383f4b--- /dev/null+++ b/v3/@claude-flow/performance/src/examples/flash-attention-demo.ts@@ -0,0 +1,160 @@+/**+ * Flash Attention Integration Demo+ *+ * Demonstrates how to use the Flash Attention integration in V3 performance module.+ */++import {+ FlashAttentionOptimizer,+ createFlashAttentionOptimizer,+ quickBenchmark,+ AttentionBenchmarkRunner,+ quickValidation,+ runAndDisplaySuite,+ type AttentionInput,+} from '../index.js';++// ============================================================================+// Example 1: Basic Flash Attention Usage+// ============================================================================++async function basicUsageExample() {+ console.log('\n=== Example 1: Basic Flash Attention Usage ===\n');++ // Create optimizer with 512-dimensional vectors+ const optimizer = createFlashAttentionOptimizer(512, 64);++ // Prepare input data+ const dim = 512;+ const numKeys = 100;++ const input: AttentionInput = {+ query: new Float32Array(dim).fill(1.0),+ keys: Array.from({ length: numKeys }, () => new Float32Array(dim).fill(1.0)),+ values: Array.from({ length: numKeys }, () => new Float32Array(dim).fill(1.0)),+ };++ // Run optimized attention+ const output = await optimizer.optimize(input);++ console.log(`Runtime: ${output.runtime}`);+ console.log(`Execution time: ${output.executionTimeMs.toFixed(3)}ms`);+ console.log(`Result shape: Float32Array[${output.result.length}]`);+ console.log(`Memory usage: ${output.memoryUsageBytes ? `${(output.memoryUsageBytes / 1024).toFixed(2)} KB` : 'N/A'}`);+}++// ============================================================================+// Example 2: Performance Benchmarking+// ============================================================================++async function benchmarkExample() {+ console.log('\n=== Example 2: Performance Benchmarking ===\n');++ // Quick benchmark with default settings+ const result = await quickBenchmark(512);++ console.log(`Flash Attention: ${result.flashAttention.averageTimeMs.toFixed(3)}ms`);+ console.log(`Baseline: ${result.baseline.averageTimeMs.toFixed(3)}ms`);+ console.log(`Speedup: ${result.speedup.toFixed(2)}x`);+ console.log(`Meets target (≥2.49x): ${result.meetsTarget ? 'YES ✓' : 'NO ✗'}`);+}++// ============================================================================+// Example 3: Comprehensive Suite+// ============================================================================++async function comprehensiveSuiteExample() {+ console.log('\n=== Example 3: Comprehensive Benchmark Suite ===\n');++ const runner = new AttentionBenchmarkRunner();+ const suite = await runner.runComprehensiveSuite();++ console.log(`Suite: ${suite.suiteName}`);+ console.log(`Benchmarks run: ${suite.summary.totalBenchmarks}`);+ console.log(`Average speedup: ${suite.summary.averageSpeedup.toFixed(2)}x`);+ console.log(`Min speedup: ${suite.summary.minSpeedup.toFixed(2)}x`);+ console.log(`Max speedup: ${suite.summary.maxSpeedup.toFixed(2)}x`);+ console.log(`Success rate: ${suite.summary.successRate.toFixed(1)}%`);+}++// ============================================================================+// Example 4: V3 Target Validation+// ============================================================================++async function targetValidationExample() {+ console.log('\n=== Example 4: V3 Target Validation ===\n');++ const isValid = await quickValidation();++ console.log(`\nValidation result: ${isValid ? 'PASSED ✓' : 'FAILED ✗'}`);+}++// ============================================================================+// Example 5: Continuous Metrics Tracking+// ============================================================================++async function metricsTrackingExample() {+ console.log('\n=== Example 5: Continuous Metrics Tracking ===\n');++ const optimizer = createFlashAttentionOptimizer(512);++ // Run multiple operations+ const dim = 512;+ const input: AttentionInput = {+ query: new Float32Array(dim).fill(1.0),+ keys: Array.from({ length: 100 }, () => new Float32Array(dim).fill(1.0)),+ values: Array.from({ length: 100 }, () => new Float32Array(dim).fill(1.0)),+ };++ console.log('Running 10 operations...\n');++ for (let i = 0; i < 10; i++) {+ await optimizer.optimize(input);+ }++ // Run benchmarks to update speedup metrics+ await optimizer.benchmark();++ // Get accumulated metrics+ const metrics = optimizer.getMetrics();++ console.log(`Total operations: ${metrics.totalOperations}`);+ console.log(`Average speedup: ${metrics.averageSpeedup.toFixed(2)}x`);+ console.log(`Peak speedup: ${metrics.peakSpeedup.toFixed(2)}x`);+ console.log(`Average execution time: ${metrics.averageExecutionTimeMs.toFixed(3)}ms`);+ console.log(`Success rate: ${metrics.successRate.toFixed(1)}%`);+}++// ============================================================================+// Main Demo Runner+// ============================================================================++async function runAllExamples() {+ try {+ await basicUsageExample();+ await benchmarkExample();+ await comprehensiveSuiteExample();+ await targetValidationExample();+ await metricsTrackingExample();++ console.log('\n=== All Examples Completed ===\n');+ } catch (error) {+ console.error('Error running examples:', error);+ process.exit(1);+ }+}++// Run if executed directly+if (import.meta.url === `file://${process.argv[1]}`) {+ runAllExamples();+}++// Export for programmatic use+export {+ basicUsageExample,+ benchmarkExample,+ comprehensiveSuiteExample,+ targetValidationExample,+ metricsTrackingExample,+ runAllExamples,+};