@sparkleideas/plugins 3.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +401 -0
  2. package/__tests__/collection-manager.test.ts +332 -0
  3. package/__tests__/dependency-graph.test.ts +434 -0
  4. package/__tests__/enhanced-plugin-registry.test.ts +488 -0
  5. package/__tests__/plugin-registry.test.ts +368 -0
  6. package/__tests__/ruvector-bridge.test.ts +2429 -0
  7. package/__tests__/ruvector-integration.test.ts +1602 -0
  8. package/__tests__/ruvector-migrations.test.ts +1099 -0
  9. package/__tests__/ruvector-quantization.test.ts +846 -0
  10. package/__tests__/ruvector-streaming.test.ts +1088 -0
  11. package/__tests__/sdk.test.ts +325 -0
  12. package/__tests__/security.test.ts +348 -0
  13. package/__tests__/utils/ruvector-test-utils.ts +860 -0
  14. package/examples/plugin-creator/index.ts +636 -0
  15. package/examples/plugin-creator/plugin-creator.test.ts +312 -0
  16. package/examples/ruvector/README.md +288 -0
  17. package/examples/ruvector/attention-patterns.ts +394 -0
  18. package/examples/ruvector/basic-usage.ts +288 -0
  19. package/examples/ruvector/docker-compose.yml +75 -0
  20. package/examples/ruvector/gnn-analysis.ts +501 -0
  21. package/examples/ruvector/hyperbolic-hierarchies.ts +557 -0
  22. package/examples/ruvector/init-db.sql +119 -0
  23. package/examples/ruvector/quantization.ts +680 -0
  24. package/examples/ruvector/self-learning.ts +447 -0
  25. package/examples/ruvector/semantic-search.ts +576 -0
  26. package/examples/ruvector/streaming-large-data.ts +507 -0
  27. package/examples/ruvector/transactions.ts +594 -0
  28. package/examples/ruvector-plugins/hook-pattern-library.ts +486 -0
  29. package/examples/ruvector-plugins/index.ts +79 -0
  30. package/examples/ruvector-plugins/intent-router.ts +354 -0
  31. package/examples/ruvector-plugins/mcp-tool-optimizer.ts +424 -0
  32. package/examples/ruvector-plugins/reasoning-bank.ts +657 -0
  33. package/examples/ruvector-plugins/ruvector-plugins.test.ts +518 -0
  34. package/examples/ruvector-plugins/semantic-code-search.ts +498 -0
  35. package/examples/ruvector-plugins/shared/index.ts +20 -0
  36. package/examples/ruvector-plugins/shared/vector-utils.ts +257 -0
  37. package/examples/ruvector-plugins/sona-learning.ts +445 -0
  38. package/package.json +97 -0
  39. package/src/collections/collection-manager.ts +661 -0
  40. package/src/collections/index.ts +56 -0
  41. package/src/collections/official/index.ts +1040 -0
  42. package/src/core/base-plugin.ts +416 -0
  43. package/src/core/plugin-interface.ts +215 -0
  44. package/src/hooks/index.ts +685 -0
  45. package/src/index.ts +378 -0
  46. package/src/integrations/agentic-flow.ts +743 -0
  47. package/src/integrations/index.ts +88 -0
  48. package/src/integrations/ruvector/ARCHITECTURE.md +1245 -0
  49. package/src/integrations/ruvector/attention-advanced.ts +1040 -0
  50. package/src/integrations/ruvector/attention-executor.ts +782 -0
  51. package/src/integrations/ruvector/attention-mechanisms.ts +757 -0
  52. package/src/integrations/ruvector/attention.ts +1063 -0
  53. package/src/integrations/ruvector/gnn.ts +3050 -0
  54. package/src/integrations/ruvector/hyperbolic.ts +1948 -0
  55. package/src/integrations/ruvector/index.ts +394 -0
  56. package/src/integrations/ruvector/migrations/001_create_extension.sql +135 -0
  57. package/src/integrations/ruvector/migrations/002_create_vector_tables.sql +259 -0
  58. package/src/integrations/ruvector/migrations/003_create_indices.sql +328 -0
  59. package/src/integrations/ruvector/migrations/004_create_functions.sql +598 -0
  60. package/src/integrations/ruvector/migrations/005_create_attention_functions.sql +654 -0
  61. package/src/integrations/ruvector/migrations/006_create_gnn_functions.sql +728 -0
  62. package/src/integrations/ruvector/migrations/007_create_hyperbolic_functions.sql +762 -0
  63. package/src/integrations/ruvector/migrations/index.ts +35 -0
  64. package/src/integrations/ruvector/migrations/migrations.ts +647 -0
  65. package/src/integrations/ruvector/quantization.ts +2036 -0
  66. package/src/integrations/ruvector/ruvector-bridge.ts +2000 -0
  67. package/src/integrations/ruvector/self-learning.ts +2376 -0
  68. package/src/integrations/ruvector/streaming.ts +1737 -0
  69. package/src/integrations/ruvector/types.ts +1945 -0
  70. package/src/providers/index.ts +643 -0
  71. package/src/registry/dependency-graph.ts +568 -0
  72. package/src/registry/enhanced-plugin-registry.ts +994 -0
  73. package/src/registry/plugin-registry.ts +604 -0
  74. package/src/sdk/index.ts +563 -0
  75. package/src/security/index.ts +594 -0
  76. package/src/types/index.ts +446 -0
  77. package/src/workers/index.ts +700 -0
  78. package/tmp.json +0 -0
  79. package/tsconfig.json +25 -0
  80. package/vitest.config.ts +23 -0
@@ -0,0 +1,1945 @@
1
+ /**
2
+ * RuVector PostgreSQL Bridge - Type Definitions
3
+ *
4
+ * Comprehensive TypeScript types for the RuVector PostgreSQL vector database
5
+ * integration, supporting advanced neural search, attention mechanisms,
6
+ * graph neural networks, and hyperbolic embeddings.
7
+ *
8
+ * @module @sparkleideas/plugins/integrations/ruvector
9
+ * @version 1.0.0
10
+ */
11
+
12
+ // ============================================================================
13
+ // Connection Configuration
14
+ // ============================================================================
15
+
16
+ /**
17
+ * SSL configuration options for secure PostgreSQL connections.
18
+ */
19
+ export interface SSLConfig {
20
+ /** Enable SSL connection */
21
+ readonly enabled: boolean;
22
+ /** Reject unauthorized certificates */
23
+ readonly rejectUnauthorized?: boolean;
24
+ /** Path to CA certificate file */
25
+ readonly ca?: string;
26
+ /** Path to client certificate file */
27
+ readonly cert?: string;
28
+ /** Path to client key file */
29
+ readonly key?: string;
30
+ /** Server name for SNI */
31
+ readonly servername?: string;
32
+ }
33
+
34
+ /**
35
+ * Connection pool configuration for managing database connections.
36
+ */
37
+ export interface PoolConfig {
38
+ /** Minimum number of connections to maintain */
39
+ readonly min: number;
40
+ /** Maximum number of connections allowed */
41
+ readonly max: number;
42
+ /** Time in milliseconds before idle connections are closed */
43
+ readonly idleTimeoutMs?: number;
44
+ /** Time in milliseconds to wait for a connection from the pool */
45
+ readonly acquireTimeoutMs?: number;
46
+ /** Time in milliseconds to wait for connection creation */
47
+ readonly createTimeoutMs?: number;
48
+ /** Number of times to retry failed connections */
49
+ readonly createRetryIntervalMs?: number;
50
+ /** Whether to destroy connections after use */
51
+ readonly destroyTimeoutMs?: number;
52
+ /** Maximum time a connection can be reused (in milliseconds) */
53
+ readonly maxLifetimeMs?: number;
54
+ /** Whether to validate connections on acquire */
55
+ readonly validateOnAcquire?: boolean;
56
+ }
57
+
58
+ /**
59
+ * Retry configuration for handling transient failures.
60
+ */
61
+ export interface RetryConfig {
62
+ /** Maximum number of retry attempts */
63
+ readonly maxAttempts: number;
64
+ /** Initial delay between retries in milliseconds */
65
+ readonly initialDelayMs: number;
66
+ /** Maximum delay between retries in milliseconds */
67
+ readonly maxDelayMs: number;
68
+ /** Backoff multiplier for exponential backoff */
69
+ readonly backoffMultiplier: number;
70
+ /** Whether to add jitter to retry delays */
71
+ readonly jitter?: boolean;
72
+ /** Specific error codes that should trigger a retry */
73
+ readonly retryableErrors?: string[];
74
+ }
75
+
76
+ /**
77
+ * Primary configuration for RuVector PostgreSQL connection.
78
+ */
79
+ export interface RuVectorConfig {
80
+ /** PostgreSQL host address */
81
+ readonly host: string;
82
+ /** PostgreSQL port (default: 5432) */
83
+ readonly port: number;
84
+ /** Database name */
85
+ readonly database: string;
86
+ /** Database user */
87
+ readonly user: string;
88
+ /** Database password */
89
+ readonly password: string;
90
+ /** SSL configuration */
91
+ readonly ssl?: boolean | SSLConfig;
92
+ /** Connection pool size (shorthand for pool.max) */
93
+ readonly poolSize?: number;
94
+ /** Detailed pool configuration */
95
+ readonly pool?: PoolConfig;
96
+ /** Connection timeout in milliseconds */
97
+ readonly connectionTimeoutMs?: number;
98
+ /** Query timeout in milliseconds */
99
+ readonly queryTimeoutMs?: number;
100
+ /** Statement timeout in milliseconds */
101
+ readonly statementTimeoutMs?: number;
102
+ /** Idle in transaction session timeout */
103
+ readonly idleInTransactionSessionTimeoutMs?: number;
104
+ /** Application name for pg_stat_activity */
105
+ readonly applicationName?: string;
106
+ /** Schema to use (default: 'public') */
107
+ readonly schema?: string;
108
+ /** Retry configuration for transient failures */
109
+ readonly retry?: RetryConfig;
110
+ /** Enable query logging */
111
+ readonly logging?: boolean | LogLevel;
112
+ /** Custom connection string (overrides other options) */
113
+ readonly connectionString?: string;
114
+ /** pgvector extension schema */
115
+ readonly vectorSchema?: string;
116
+ /** Default vector dimensions */
117
+ readonly defaultDimensions?: number;
118
+ /** Enable prepared statements caching */
119
+ readonly preparedStatements?: boolean;
120
+ /** Keep-alive configuration */
121
+ readonly keepAlive?: boolean | KeepAliveConfig;
122
+ }
123
+
124
+ /**
125
+ * Keep-alive configuration for long-lived connections.
126
+ */
127
+ export interface KeepAliveConfig {
128
+ /** Enable TCP keep-alive */
129
+ readonly enabled: boolean;
130
+ /** Initial delay before sending keep-alive probes (ms) */
131
+ readonly initialDelayMs?: number;
132
+ }
133
+
134
+ /**
135
+ * Log levels for query logging.
136
+ */
137
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'trace';
138
+
139
+ // ============================================================================
140
+ // Vector Operations
141
+ // ============================================================================
142
+
143
+ /**
144
+ * Distance/similarity metrics for vector operations.
145
+ */
146
+ export type DistanceMetric =
147
+ | 'cosine' // Cosine similarity (1 - cosine distance)
148
+ | 'euclidean' // L2 distance
149
+ | 'dot' // Inner product (dot product)
150
+ | 'hamming' // Hamming distance for binary vectors
151
+ | 'manhattan' // L1 distance
152
+ | 'chebyshev' // L-infinity distance
153
+ | 'jaccard' // Jaccard similarity
154
+ | 'minkowski' // Generalized Minkowski distance
155
+ | 'bray_curtis' // Bray-Curtis dissimilarity
156
+ | 'canberra' // Canberra distance
157
+ | 'mahalanobis' // Mahalanobis distance
158
+ | 'correlation'; // Correlation distance
159
+
160
+ /**
161
+ * Index types supported by RuVector/pgvector.
162
+ */
163
+ export type VectorIndexType =
164
+ | 'hnsw' // Hierarchical Navigable Small World
165
+ | 'ivfflat' // Inverted File with Flat vectors
166
+ | 'ivfpq' // Inverted File with Product Quantization
167
+ | 'flat' // Brute force (no index)
168
+ | 'diskann'; // Disk-based ANN
169
+
170
+ /**
171
+ * Options for vector similarity search operations.
172
+ */
173
+ export interface VectorSearchOptions {
174
+ /** Query vector (required) */
175
+ readonly query: number[] | Float32Array;
176
+ /** Number of results to return (k-nearest neighbors) */
177
+ readonly k: number;
178
+ /** Distance metric to use */
179
+ readonly metric: DistanceMetric;
180
+ /** Metadata filters (column name -> value) */
181
+ readonly filter?: Record<string, unknown>;
182
+ /** SQL WHERE clause for additional filtering */
183
+ readonly whereClause?: string;
184
+ /** Parameters for the WHERE clause */
185
+ readonly whereParams?: unknown[];
186
+ /** Minimum similarity threshold (0-1 for cosine, varies for others) */
187
+ readonly threshold?: number;
188
+ /** Maximum distance threshold */
189
+ readonly maxDistance?: number;
190
+ /** Include vector in results */
191
+ readonly includeVector?: boolean;
192
+ /** Include metadata in results */
193
+ readonly includeMetadata?: boolean;
194
+ /** Columns to select from the table */
195
+ readonly selectColumns?: string[];
196
+ /** Table name to search in */
197
+ readonly tableName?: string;
198
+ /** Vector column name (default: 'embedding') */
199
+ readonly vectorColumn?: string;
200
+ /** HNSW ef_search parameter for recall/speed tradeoff */
201
+ readonly efSearch?: number;
202
+ /** IVF probes parameter */
203
+ readonly probes?: number;
204
+ /** Enable query vector normalization */
205
+ readonly normalize?: boolean;
206
+ /** Timeout for this specific query in milliseconds */
207
+ readonly timeoutMs?: number;
208
+ /** Use approximate search (faster but less accurate) */
209
+ readonly approximate?: boolean;
210
+ /** Reranking options for multi-stage retrieval */
211
+ readonly rerank?: RerankOptions;
212
+ }
213
+
214
+ /**
215
+ * Reranking options for multi-stage retrieval.
216
+ */
217
+ export interface RerankOptions {
218
+ /** Enable reranking */
219
+ readonly enabled: boolean;
220
+ /** Model to use for reranking */
221
+ readonly model?: string;
222
+ /** Number of candidates to fetch before reranking */
223
+ readonly candidates?: number;
224
+ /** Cross-encoder scoring */
225
+ readonly crossEncoder?: boolean;
226
+ }
227
+
228
+ /**
229
+ * Options for batch vector operations.
230
+ */
231
+ export interface BatchVectorOptions {
232
+ /** Batch of query vectors */
233
+ readonly queries: Array<number[] | Float32Array>;
234
+ /** Number of results per query */
235
+ readonly k: number;
236
+ /** Distance metric */
237
+ readonly metric: DistanceMetric;
238
+ /** Shared filter for all queries */
239
+ readonly filter?: Record<string, unknown>;
240
+ /** Process queries in parallel */
241
+ readonly parallel?: boolean;
242
+ /** Maximum concurrent queries */
243
+ readonly concurrency?: number;
244
+ /** Table name */
245
+ readonly tableName?: string;
246
+ /** Vector column name */
247
+ readonly vectorColumn?: string;
248
+ }
249
+
250
+ /**
251
+ * Result from a vector search operation.
252
+ */
253
+ export interface VectorSearchResult {
254
+ /** Unique identifier of the result */
255
+ readonly id: string | number;
256
+ /** Similarity/distance score */
257
+ readonly score: number;
258
+ /** Distance value (inverse of similarity for some metrics) */
259
+ readonly distance?: number;
260
+ /** Result vector (if includeVector is true) */
261
+ readonly vector?: number[];
262
+ /** Associated metadata */
263
+ readonly metadata?: Record<string, unknown>;
264
+ /** Rank in the result set (1-indexed) */
265
+ readonly rank?: number;
266
+ /** Retrieval timestamp */
267
+ readonly retrievedAt?: Date;
268
+ }
269
+
270
+ /**
271
+ * Options for inserting vectors.
272
+ */
273
+ export interface VectorInsertOptions {
274
+ /** Table name */
275
+ readonly tableName: string;
276
+ /** Vector column name */
277
+ readonly vectorColumn?: string;
278
+ /** Vectors to insert */
279
+ readonly vectors: Array<{
280
+ id?: string | number;
281
+ vector: number[] | Float32Array;
282
+ metadata?: Record<string, unknown>;
283
+ }>;
284
+ /** Upsert mode (update on conflict) */
285
+ readonly upsert?: boolean;
286
+ /** Conflict column(s) for upsert */
287
+ readonly conflictColumns?: string[];
288
+ /** Skip invalid vectors instead of failing */
289
+ readonly skipInvalid?: boolean;
290
+ /** Batch size for bulk inserts */
291
+ readonly batchSize?: number;
292
+ /** Return inserted IDs */
293
+ readonly returning?: boolean;
294
+ }
295
+
296
+ /**
297
+ * Options for updating vectors.
298
+ */
299
+ export interface VectorUpdateOptions {
300
+ /** Table name */
301
+ readonly tableName: string;
302
+ /** Vector column name */
303
+ readonly vectorColumn?: string;
304
+ /** ID of the vector to update */
305
+ readonly id: string | number;
306
+ /** New vector value */
307
+ readonly vector?: number[] | Float32Array;
308
+ /** Updated metadata */
309
+ readonly metadata?: Record<string, unknown>;
310
+ /** Partial metadata update (merge with existing) */
311
+ readonly mergeMetadata?: boolean;
312
+ }
313
+
314
+ /**
315
+ * Options for creating a vector index.
316
+ */
317
+ export interface VectorIndexOptions {
318
+ /** Table name */
319
+ readonly tableName: string;
320
+ /** Column name */
321
+ readonly columnName: string;
322
+ /** Index type */
323
+ readonly indexType: VectorIndexType;
324
+ /** Index name (auto-generated if not provided) */
325
+ readonly indexName?: string;
326
+ /** Distance metric for the index */
327
+ readonly metric?: DistanceMetric;
328
+ /** HNSW M parameter (max connections per layer) */
329
+ readonly m?: number;
330
+ /** HNSW ef_construction parameter */
331
+ readonly efConstruction?: number;
332
+ /** IVF lists parameter */
333
+ readonly lists?: number;
334
+ /** Create index concurrently (non-blocking) */
335
+ readonly concurrent?: boolean;
336
+ /** Replace existing index if it exists */
337
+ readonly replace?: boolean;
338
+ }
339
+
340
+ // ============================================================================
341
+ // Attention Mechanisms (39 Types)
342
+ // ============================================================================
343
+
344
+ /**
345
+ * All 39 attention mechanism types supported by RuVector.
346
+ *
347
+ * These mechanisms enable sophisticated neural search and pattern matching
348
+ * directly within PostgreSQL using RuVector's attention functions.
349
+ */
350
+ export type AttentionMechanism =
351
+ // Core Attention Types
352
+ | 'multi_head' // Multi-Head Attention (Transformer)
353
+ | 'self_attention' // Self-Attention
354
+ | 'cross_attention' // Cross-Attention between two sequences
355
+ | 'sparse_attention' // Sparse Attention (BigBird, Longformer)
356
+ | 'linear_attention' // Linear Attention (O(n) complexity)
357
+ | 'local_attention' // Local/Sliding Window Attention
358
+ | 'global_attention' // Global Attention tokens
359
+
360
+ // Efficient Attention Variants
361
+ | 'flash_attention' // Flash Attention (memory-efficient)
362
+ | 'flash_attention_v2' // Flash Attention V2 (improved)
363
+ | 'memory_efficient' // Memory-Efficient Attention
364
+ | 'chunk_attention' // Chunked Attention processing
365
+ | 'sliding_window' // Sliding Window Attention
366
+ | 'dilated_attention' // Dilated/Strided Attention
367
+ | 'block_sparse' // Block-Sparse Attention
368
+
369
+ // Advanced Attention Patterns
370
+ | 'relative_position' // Relative Position Attention (T5, XLNet)
371
+ | 'rotary_position' // Rotary Position Embedding (RoPE)
372
+ | 'alibi' // Attention with Linear Biases
373
+ | 'causal' // Causal/Masked Attention (GPT-style)
374
+ | 'bidirectional' // Bidirectional Attention (BERT-style)
375
+ | 'axial' // Axial Attention (2D decomposition)
376
+
377
+ // Specialized Attention Types
378
+ | 'performer' // FAVOR+ (Performers)
379
+ | 'linformer' // Linformer (low-rank projection)
380
+ | 'reformer' // LSH Attention (Reformer)
381
+ | 'synthesizer' // Synthesizer (learned patterns)
382
+ | 'routing' // Routing Attention (mixture of experts)
383
+ | 'mixture_of_experts' // MoE Attention
384
+
385
+ // Graph and Structured Attention
386
+ | 'graph_attention' // Graph Attention (GAT)
387
+ | 'hyperbolic_attention' // Hyperbolic Attention (hierarchies)
388
+ | 'spherical_attention' // Spherical Attention
389
+ | 'toroidal_attention' // Toroidal Attention (periodic)
390
+
391
+ // Temporal and Sequential
392
+ | 'temporal_attention' // Time-aware Attention
393
+ | 'recurrent_attention' // Recurrent Attention (LSTM-style)
394
+ | 'state_space' // State Space Model Attention (S4, Mamba)
395
+
396
+ // Multi-Modal Attention
397
+ | 'cross_modal' // Cross-Modal Attention
398
+ | 'perceiver' // Perceiver IO Attention
399
+ | 'flamingo' // Flamingo-style Attention
400
+
401
+ // Retrieval-Augmented
402
+ | 'retrieval_attention' // Retrieval-Augmented Attention
403
+ | 'knn_attention' // k-NN Augmented Attention
404
+ | 'memory_augmented'; // External Memory Attention
405
+
406
+ /**
407
+ * Configuration for attention mechanism operations.
408
+ */
409
+ export interface AttentionConfig {
410
+ /** Attention mechanism type */
411
+ readonly mechanism: AttentionMechanism;
412
+ /** Number of attention heads */
413
+ readonly numHeads: number;
414
+ /** Dimension of each attention head */
415
+ readonly headDim: number;
416
+ /** Total embedding dimension (numHeads * headDim) */
417
+ readonly embedDim?: number;
418
+ /** Dropout rate for attention weights */
419
+ readonly dropout?: number;
420
+ /** Whether to use bias in projections */
421
+ readonly useBias?: boolean;
422
+ /** Scale factor for attention scores */
423
+ readonly scale?: number;
424
+ /** Causal masking for autoregressive attention */
425
+ readonly causal?: boolean;
426
+ /** Maximum sequence length */
427
+ readonly maxSeqLen?: number;
428
+ /** Mechanism-specific parameters */
429
+ readonly params?: AttentionParams;
430
+ }
431
+
432
+ /**
433
+ * Mechanism-specific attention parameters.
434
+ */
435
+ export interface AttentionParams {
436
+ // Sparse Attention
437
+ /** Block size for sparse attention */
438
+ readonly blockSize?: number;
439
+ /** Number of global tokens */
440
+ readonly numGlobalTokens?: number;
441
+ /** Number of random attention tokens */
442
+ readonly numRandomTokens?: number;
443
+
444
+ // Sliding Window
445
+ /** Window size for local attention */
446
+ readonly windowSize?: number;
447
+ /** Dilation rate for dilated attention */
448
+ readonly dilationRate?: number;
449
+
450
+ // Relative Position
451
+ /** Maximum relative distance */
452
+ readonly maxRelativePosition?: number;
453
+ /** Number of buckets for relative positions */
454
+ readonly numBuckets?: number;
455
+
456
+ // RoPE
457
+ /** Base frequency for rotary embeddings */
458
+ readonly ropeBase?: number;
459
+ /** Whether to apply RoPE to keys as well */
460
+ readonly ropeKeys?: boolean;
461
+
462
+ // Linear Attention
463
+ /** Feature map type for linear attention */
464
+ readonly featureMap?: 'elu' | 'relu' | 'softmax' | 'exp' | 'fourier';
465
+ /** Number of random features for approximation */
466
+ readonly numFeatures?: number;
467
+
468
+ // Flash Attention
469
+ /** Block size for flash attention tiles */
470
+ readonly flashBlockSize?: number;
471
+ /** Enable memory-efficient backward pass */
472
+ readonly checkpointing?: boolean;
473
+
474
+ // Graph Attention
475
+ /** Number of graph attention layers */
476
+ readonly numLayers?: number;
477
+ /** Edge feature dimension */
478
+ readonly edgeDim?: number;
479
+ /** Aggregation method */
480
+ readonly aggregation?: 'mean' | 'sum' | 'max' | 'attention';
481
+
482
+ // Hyperbolic
483
+ /** Curvature parameter for hyperbolic space */
484
+ readonly curvature?: number;
485
+
486
+ // MoE
487
+ /** Number of experts */
488
+ readonly numExperts?: number;
489
+ /** Top-k experts to route to */
490
+ readonly topK?: number;
491
+ /** Load balancing loss coefficient */
492
+ readonly loadBalanceLoss?: number;
493
+ }
494
+
495
+ /**
496
+ * Input for attention computation.
497
+ */
498
+ export interface AttentionInput {
499
+ /** Query vectors [batch, seq_len, dim] */
500
+ readonly query: number[][] | Float32Array[];
501
+ /** Key vectors [batch, seq_len, dim] */
502
+ readonly key: number[][] | Float32Array[];
503
+ /** Value vectors [batch, seq_len, dim] */
504
+ readonly value: number[][] | Float32Array[];
505
+ /** Attention mask [batch, seq_len] or [batch, 1, seq_len, seq_len] */
506
+ readonly mask?: boolean[][] | number[][];
507
+ /** Position IDs for positional encoding */
508
+ readonly positionIds?: number[];
509
+ /** Key-value cache for incremental decoding */
510
+ readonly kvCache?: KVCache;
511
+ }
512
+
513
+ /**
514
+ * Key-value cache for efficient incremental attention.
515
+ */
516
+ export interface KVCache {
517
+ /** Cached key vectors */
518
+ readonly keys: number[][];
519
+ /** Cached value vectors */
520
+ readonly values: number[][];
521
+ /** Current sequence position */
522
+ readonly seqPos: number;
523
+ /** Maximum cache size */
524
+ readonly maxSize?: number;
525
+ }
526
+
527
+ /**
528
+ * Output from attention computation.
529
+ */
530
+ export interface AttentionOutput {
531
+ /** Output vectors [batch, seq_len, dim] */
532
+ readonly output: number[][];
533
+ /** Attention weights [batch, num_heads, seq_len, seq_len] */
534
+ readonly attentionWeights?: number[][][][];
535
+ /** Updated KV cache */
536
+ readonly kvCache?: KVCache;
537
+ /** Computation statistics */
538
+ readonly stats?: AttentionStats;
539
+ }
540
+
541
+ /**
542
+ * Statistics from attention computation.
543
+ */
544
+ export interface AttentionStats {
545
+ /** Computation time in milliseconds */
546
+ readonly computeTimeMs: number;
547
+ /** Memory usage in bytes */
548
+ readonly memoryBytes: number;
549
+ /** FLOPs performed */
550
+ readonly flops?: number;
551
+ /** Sparsity ratio (for sparse attention) */
552
+ readonly sparsity?: number;
553
+ /** Number of tokens processed */
554
+ readonly tokensProcessed: number;
555
+ }
556
+
557
+ // ============================================================================
558
+ // Graph Neural Network (GNN) Layers
559
+ // ============================================================================
560
+
561
+ /**
562
+ * GNN layer types supported by RuVector.
563
+ */
564
+ export type GNNLayerType =
565
+ | 'gcn' // Graph Convolutional Network
566
+ | 'gat' // Graph Attention Network
567
+ | 'gat_v2' // GAT v2 (improved attention)
568
+ | 'sage' // GraphSAGE (sampling and aggregation)
569
+ | 'gin' // Graph Isomorphism Network
570
+ | 'mpnn' // Message Passing Neural Network
571
+ | 'edge_conv' // EdgeConv (dynamic graph)
572
+ | 'point_conv' // PointConv (point cloud)
573
+ | 'transformer' // Graph Transformer
574
+ | 'pna' // Principal Neighbourhood Aggregation
575
+ | 'film' // Feature-wise Linear Modulation
576
+ | 'rgcn' // Relational GCN
577
+ | 'hgt' // Heterogeneous Graph Transformer
578
+ | 'han' // Heterogeneous Attention Network
579
+ | 'metapath'; // MetaPath-based aggregation
580
+
581
+ /**
582
+ * Aggregation methods for GNN message passing.
583
+ */
584
+ export type GNNAggregation =
585
+ | 'mean'
586
+ | 'sum'
587
+ | 'max'
588
+ | 'min'
589
+ | 'attention'
590
+ | 'lstm'
591
+ | 'softmax'
592
+ | 'power_mean'
593
+ | 'std'
594
+ | 'var';
595
+
596
+ /**
597
+ * Configuration for a GNN layer.
598
+ */
599
+ export interface GNNLayer {
600
+ /** Layer type */
601
+ readonly type: GNNLayerType;
602
+ /** Input feature dimension */
603
+ readonly inputDim: number;
604
+ /** Output feature dimension */
605
+ readonly outputDim: number;
606
+ /** Hidden dimension (for multi-layer projections) */
607
+ readonly hiddenDim?: number;
608
+ /** Number of attention heads (for attention-based layers) */
609
+ readonly numHeads?: number;
610
+ /** Dropout rate */
611
+ readonly dropout?: number;
612
+ /** Aggregation method */
613
+ readonly aggregation?: GNNAggregation;
614
+ /** Whether to add self-loops */
615
+ readonly addSelfLoops?: boolean;
616
+ /** Whether to normalize by degree */
617
+ readonly normalize?: boolean;
618
+ /** Whether to use bias */
619
+ readonly useBias?: boolean;
620
+ /** Activation function */
621
+ readonly activation?: ActivationFunction;
622
+ /** Layer-specific parameters */
623
+ readonly params?: GNNLayerParams;
624
+ }
625
+
626
+ /**
627
+ * Activation functions for GNN layers.
628
+ */
629
+ export type ActivationFunction =
630
+ | 'relu'
631
+ | 'gelu'
632
+ | 'silu'
633
+ | 'swish'
634
+ | 'leaky_relu'
635
+ | 'elu'
636
+ | 'selu'
637
+ | 'tanh'
638
+ | 'sigmoid'
639
+ | 'softmax'
640
+ | 'none';
641
+
642
+ /**
643
+ * Layer-specific GNN parameters.
644
+ */
645
+ export interface GNNLayerParams {
646
+ // GAT parameters
647
+ /** Negative slope for LeakyReLU in GAT */
648
+ readonly negativeSlope?: number;
649
+ /** Concatenate or average heads */
650
+ readonly concat?: boolean;
651
+ /** Edge attention dimension */
652
+ readonly edgeAttnDim?: number;
653
+
654
+ // GraphSAGE parameters
655
+ /** Neighborhood sampling size */
656
+ readonly sampleSize?: number;
657
+ /** Sampling strategy */
658
+ readonly samplingStrategy?: 'uniform' | 'importance' | 'layer';
659
+
660
+ // GIN parameters
661
+ /** Epsilon for GIN update */
662
+ readonly eps?: number;
663
+ /** Whether epsilon is learnable */
664
+ readonly trainEps?: boolean;
665
+
666
+ // EdgeConv parameters
667
+ /** k for k-NN graph construction */
668
+ readonly k?: number;
669
+ /** Dynamic graph update */
670
+ readonly dynamic?: boolean;
671
+
672
+ // PNA parameters
673
+ /** Scalers for PNA */
674
+ readonly scalers?: ('identity' | 'amplification' | 'attenuation')[];
675
+ /** Aggregators for PNA */
676
+ readonly aggregators?: GNNAggregation[];
677
+
678
+ // RGCN parameters
679
+ /** Number of relation types */
680
+ readonly numRelations?: number;
681
+ /** Basis decomposition dimension */
682
+ readonly numBases?: number;
683
+
684
+ // HGT/HAN parameters
685
+ /** Node types */
686
+ readonly nodeTypes?: string[];
687
+ /** Edge types */
688
+ readonly edgeTypes?: string[];
689
+ /** Metapaths for aggregation */
690
+ readonly metapaths?: string[][];
691
+
692
+ // Multi-layer/Transformer parameters
693
+ /** Number of layers for multi-layer GNN */
694
+ readonly numLayers?: number;
695
+ }
696
+
697
+ /**
698
+ * Graph data structure for GNN operations.
699
+ */
700
+ export interface GraphData {
701
+ /** Node features [num_nodes, feature_dim] */
702
+ readonly nodeFeatures: number[][];
703
+ /** Edge index [2, num_edges] (source, target) */
704
+ readonly edgeIndex: [number[], number[]];
705
+ /** Edge features [num_edges, edge_feature_dim] (optional) */
706
+ readonly edgeFeatures?: number[][];
707
+ /** Edge weights [num_edges] (optional) */
708
+ readonly edgeWeights?: number[];
709
+ /** Node labels (for supervised learning) */
710
+ readonly nodeLabels?: number[];
711
+ /** Graph labels (for graph classification) */
712
+ readonly graphLabels?: number[];
713
+ /** Batch index for mini-batching */
714
+ readonly batch?: number[];
715
+ /** Node type indices (for heterogeneous graphs) */
716
+ readonly nodeTypes?: number[];
717
+ /** Edge type indices (for heterogeneous graphs) */
718
+ readonly edgeTypes?: number[];
719
+ }
720
+
721
+ /**
722
+ * Output from GNN forward pass.
723
+ */
724
+ export interface GNNOutput {
725
+ /** Node embeddings [num_nodes, output_dim] */
726
+ readonly nodeEmbeddings: number[][];
727
+ /** Graph embedding (pooled) [batch_size, output_dim] */
728
+ readonly graphEmbedding?: number[];
729
+ /** Attention weights (for attention-based layers) */
730
+ readonly attentionWeights?: number[][];
731
+ /** Edge predictions (for link prediction) */
732
+ readonly edgePredictions?: number[];
733
+ /** Computation statistics */
734
+ readonly stats?: GNNStats;
735
+ }
736
+
737
+ /**
738
+ * Statistics from GNN computation.
739
+ */
740
+ export interface GNNStats {
741
+ /** Forward pass time in milliseconds */
742
+ readonly forwardTimeMs: number;
743
+ /** Number of nodes processed */
744
+ readonly numNodes: number;
745
+ /** Number of edges processed */
746
+ readonly numEdges: number;
747
+ /** Memory usage in bytes */
748
+ readonly memoryBytes: number;
749
+ /** Number of message passing iterations */
750
+ readonly numIterations: number;
751
+ }
752
+
753
+ // ============================================================================
754
+ // Hyperbolic Embeddings
755
+ // ============================================================================
756
+
757
+ /**
758
+ * Hyperbolic space models supported by RuVector.
759
+ */
760
+ export type HyperbolicModel =
761
+ | 'poincare' // Poincare ball model
762
+ | 'lorentz' // Lorentz/Hyperboloid model
763
+ | 'klein' // Klein disk model
764
+ | 'half_space'; // Upper half-space model
765
+
766
+ /**
767
+ * Configuration for hyperbolic embeddings.
768
+ */
769
+ export interface HyperbolicEmbedding {
770
+ /** Hyperbolic space model */
771
+ readonly model: HyperbolicModel;
772
+ /** Curvature parameter (negative for hyperbolic space) */
773
+ readonly curvature: number;
774
+ /** Embedding dimension */
775
+ readonly dimension: number;
776
+ /** Whether curvature is learnable */
777
+ readonly learnCurvature?: boolean;
778
+ /** Manifold-specific parameters */
779
+ readonly params?: HyperbolicParams;
780
+ }
781
+
782
+ /**
783
+ * Hyperbolic space parameters.
784
+ */
785
+ export interface HyperbolicParams {
786
+ // Poincare Ball
787
+ /** Maximum norm for Poincare ball (< 1) */
788
+ readonly maxNorm?: number;
789
+ /** Epsilon for numerical stability */
790
+ readonly eps?: number;
791
+
792
+ // Lorentz
793
+ /** Time dimension index */
794
+ readonly timeDim?: number;
795
+
796
+ // Optimization
797
+ /** Riemannian optimizer type */
798
+ readonly optimizer?: 'rsgd' | 'radam' | 'ramsgrad';
799
+ /** Learning rate for hyperbolic parameters */
800
+ readonly learningRate?: number;
801
+ /** Burnin period for initialization */
802
+ readonly burninPeriod?: number;
803
+ }
804
+
805
+ /**
806
+ * Hyperbolic distance functions.
807
+ */
808
+ export type HyperbolicDistance =
809
+ | 'poincare_distance' // Geodesic distance in Poincare ball
810
+ | 'lorentz_distance' // Geodesic distance in Lorentz model
811
+ | 'poincare_2_lorentz' // Map Poincare to Lorentz
812
+ | 'lorentz_2_poincare' // Map Lorentz to Poincare
813
+ | 'hyperbolic_midpoint' // Geodesic midpoint
814
+ | 'hyperbolic_centroid'; // Frechet mean on manifold
815
+
816
+ /**
817
+ * Input for hyperbolic operations.
818
+ */
819
+ export interface HyperbolicInput {
820
+ /** Points in hyperbolic space */
821
+ readonly points: number[][];
822
+ /** Target points (for distance computation) */
823
+ readonly targets?: number[][];
824
+ /** Tangent vectors (for parallel transport) */
825
+ readonly tangentVectors?: number[][];
826
+ /** Base point for tangent space operations */
827
+ readonly basePoint?: number[];
828
+ }
829
+
830
+ /**
831
+ * Output from hyperbolic operations.
832
+ */
833
+ export interface HyperbolicOutput {
834
+ /** Computed embeddings/transformed points */
835
+ readonly embeddings: number[][];
836
+ /** Distances (if computed) */
837
+ readonly distances?: number[];
838
+ /** Geodesic paths (if requested) */
839
+ readonly geodesics?: number[][][];
840
+ /** Curvature values (if learned) */
841
+ readonly curvature?: number;
842
+ }
843
+
844
+ /**
845
+ * Operations available for hyperbolic embeddings.
846
+ */
847
+ export type HyperbolicOperation =
848
+ | 'embed' // Project Euclidean to hyperbolic
849
+ | 'project' // Project back to Euclidean
850
+ | 'distance' // Compute geodesic distance
851
+ | 'midpoint' // Compute geodesic midpoint
852
+ | 'centroid' // Compute Frechet mean
853
+ | 'parallel_transport' // Transport vectors along geodesic
854
+ | 'log_map' // Logarithmic map to tangent space
855
+ | 'exp_map' // Exponential map from tangent space
856
+ | 'mobius_add' // Mobius addition
857
+ | 'mobius_matvec' // Mobius matrix-vector multiplication
858
+ | 'gyration'; // Gyration operation
859
+
860
+ // ============================================================================
861
+ // SQL Function Types (53+ Functions)
862
+ // ============================================================================
863
+
864
+ /**
865
+ * RuVector SQL function categories.
866
+ */
867
+ export type RuVectorFunctionCategory =
868
+ | 'vector' // Vector operations
869
+ | 'index' // Index management
870
+ | 'attention' // Attention mechanisms
871
+ | 'gnn' // Graph neural networks
872
+ | 'hyperbolic' // Hyperbolic geometry
873
+ | 'embedding' // Embedding operations
874
+ | 'distance' // Distance/similarity functions
875
+ | 'aggregation' // Vector aggregation
876
+ | 'normalization' // Normalization functions
877
+ | 'quantization' // Vector quantization
878
+ | 'utility' // Utility functions
879
+ | 'admin'; // Administrative functions
880
+
881
+ /**
882
+ * Vector operation SQL functions.
883
+ */
884
+ export interface VectorFunctions {
885
+ // Core Vector Operations
886
+ 'ruvector.vector_add': VectorBinaryOp;
887
+ 'ruvector.vector_sub': VectorBinaryOp;
888
+ 'ruvector.vector_mul': VectorScalarOp;
889
+ 'ruvector.vector_div': VectorScalarOp;
890
+ 'ruvector.vector_neg': VectorUnaryOp;
891
+ 'ruvector.vector_dot': VectorBinaryScalarOp;
892
+ 'ruvector.vector_cross': VectorBinaryOp;
893
+ 'ruvector.vector_norm': VectorNormOp;
894
+ 'ruvector.vector_normalize': VectorUnaryOp;
895
+ 'ruvector.vector_scale': VectorScalarOp;
896
+ 'ruvector.vector_lerp': VectorLerpOp;
897
+ 'ruvector.vector_slerp': VectorSlerpOp;
898
+
899
+ // Distance Functions
900
+ 'ruvector.cosine_distance': DistanceFunction;
901
+ 'ruvector.cosine_similarity': DistanceFunction;
902
+ 'ruvector.euclidean_distance': DistanceFunction;
903
+ 'ruvector.l2_distance': DistanceFunction;
904
+ 'ruvector.manhattan_distance': DistanceFunction;
905
+ 'ruvector.l1_distance': DistanceFunction;
906
+ 'ruvector.hamming_distance': DistanceFunction;
907
+ 'ruvector.jaccard_distance': DistanceFunction;
908
+ 'ruvector.inner_product': DistanceFunction;
909
+ 'ruvector.dot_product': DistanceFunction;
910
+
911
+ // Aggregation Functions
912
+ 'ruvector.vector_avg': VectorAggregateOp;
913
+ 'ruvector.vector_sum': VectorAggregateOp;
914
+ 'ruvector.vector_min': VectorAggregateOp;
915
+ 'ruvector.vector_max': VectorAggregateOp;
916
+ 'ruvector.vector_centroid': VectorAggregateOp;
917
+ 'ruvector.vector_median': VectorAggregateOp;
918
+ }
919
+
920
+ /**
921
+ * Index management SQL functions.
922
+ */
923
+ export interface IndexFunctions {
924
+ 'ruvector.create_hnsw_index': CreateIndexOp;
925
+ 'ruvector.create_ivfflat_index': CreateIndexOp;
926
+ 'ruvector.drop_index': DropIndexOp;
927
+ 'ruvector.reindex': ReindexOp;
928
+ 'ruvector.index_stats': IndexStatsOp;
929
+ 'ruvector.set_ef_search': SetParamOp;
930
+ 'ruvector.set_probes': SetParamOp;
931
+ }
932
+
933
+ /**
934
+ * Attention SQL functions.
935
+ */
936
+ export interface AttentionFunctions {
937
+ 'ruvector.multi_head_attention': AttentionOp;
938
+ 'ruvector.self_attention': AttentionOp;
939
+ 'ruvector.cross_attention': CrossAttentionOp;
940
+ 'ruvector.flash_attention': FlashAttentionOp;
941
+ 'ruvector.linear_attention': LinearAttentionOp;
942
+ 'ruvector.sparse_attention': SparseAttentionOp;
943
+ 'ruvector.compute_attention_weights': AttentionWeightsOp;
944
+ }
945
+
946
+ /**
947
+ * GNN SQL functions.
948
+ */
949
+ export interface GNNFunctions {
950
+ 'ruvector.gcn_layer': GNNLayerOp;
951
+ 'ruvector.gat_layer': GNNLayerOp;
952
+ 'ruvector.sage_layer': GNNLayerOp;
953
+ 'ruvector.message_passing': MessagePassingOp;
954
+ 'ruvector.aggregate_neighbors': AggregateOp;
955
+ 'ruvector.graph_pooling': PoolingOp;
956
+ }
957
+
958
+ /**
959
+ * Hyperbolic SQL functions.
960
+ */
961
+ export interface HyperbolicFunctions {
962
+ 'ruvector.poincare_distance': HyperbolicDistanceOp;
963
+ 'ruvector.lorentz_distance': HyperbolicDistanceOp;
964
+ 'ruvector.exp_map': ExpMapOp;
965
+ 'ruvector.log_map': LogMapOp;
966
+ 'ruvector.mobius_add': MobiusOp;
967
+ 'ruvector.parallel_transport': TransportOp;
968
+ 'ruvector.hyperbolic_centroid': HyperbolicCentroidOp;
969
+ }
970
+
971
+ /**
972
+ * Embedding SQL functions.
973
+ */
974
+ export interface EmbeddingFunctions {
975
+ 'ruvector.embed_text': EmbedTextOp;
976
+ 'ruvector.embed_batch': EmbedBatchOp;
977
+ 'ruvector.embed_image': EmbedImageOp;
978
+ 'ruvector.embed_chunk': EmbedChunkOp;
979
+ }
980
+
981
+ /**
982
+ * Quantization SQL functions.
983
+ */
984
+ export interface QuantizationFunctions {
985
+ 'ruvector.quantize_scalar': QuantizeOp;
986
+ 'ruvector.quantize_product': ProductQuantizeOp;
987
+ 'ruvector.dequantize': DequantizeOp;
988
+ 'ruvector.binary_quantize': BinaryQuantizeOp;
989
+ }
990
+
991
+ /**
992
+ * Utility SQL functions.
993
+ */
994
+ export interface UtilityFunctions {
995
+ 'ruvector.version': VersionOp;
996
+ 'ruvector.config': ConfigOp;
997
+ 'ruvector.stats': StatsOp;
998
+ 'ruvector.health_check': HealthCheckOp;
999
+ 'ruvector.vacuum_vectors': VacuumOp;
1000
+ 'ruvector.analyze_vectors': AnalyzeOp;
1001
+ }
1002
+
1003
+ // SQL Function Operation Types
1004
+ type VectorBinaryOp = (a: number[], b: number[]) => number[];
1005
+ type VectorUnaryOp = (v: number[]) => number[];
1006
+ type VectorScalarOp = (v: number[], s: number) => number[];
1007
+ type VectorBinaryScalarOp = (a: number[], b: number[]) => number;
1008
+ type VectorNormOp = (v: number[], p?: number) => number;
1009
+ type VectorLerpOp = (a: number[], b: number[], t: number) => number[];
1010
+ type VectorSlerpOp = (a: number[], b: number[], t: number) => number[];
1011
+ type VectorAggregateOp = (vectors: number[][]) => number[];
1012
+ type DistanceFunction = (a: number[], b: number[]) => number;
1013
+ type CreateIndexOp = (table: string, column: string, options?: VectorIndexOptions) => void;
1014
+ type DropIndexOp = (indexName: string) => void;
1015
+ type ReindexOp = (indexName: string) => void;
1016
+ type IndexStatsOp = (indexName: string) => IndexStats;
1017
+ type SetParamOp = (value: number) => void;
1018
+ type AttentionOp = (input: AttentionInput, config: AttentionConfig) => AttentionOutput;
1019
+ type CrossAttentionOp = (query: number[][], kv: number[][], config: AttentionConfig) => AttentionOutput;
1020
+ type FlashAttentionOp = (input: AttentionInput, blockSize?: number) => AttentionOutput;
1021
+ type LinearAttentionOp = (input: AttentionInput, featureMap: string) => AttentionOutput;
1022
+ type SparseAttentionOp = (input: AttentionInput, pattern: string) => AttentionOutput;
1023
+ type AttentionWeightsOp = (query: number[][], key: number[][]) => number[][];
1024
+ type GNNLayerOp = (graph: GraphData, layer: GNNLayer) => GNNOutput;
1025
+ type MessagePassingOp = (graph: GraphData, aggregation: GNNAggregation) => number[][];
1026
+ type AggregateOp = (nodeFeatures: number[][], edgeIndex: [number[], number[]], agg: GNNAggregation) => number[][];
1027
+ type PoolingOp = (nodeFeatures: number[][], batch: number[], method: string) => number[][];
1028
+ type HyperbolicDistanceOp = (a: number[], b: number[], curvature: number) => number;
1029
+ type ExpMapOp = (point: number[], tangent: number[], curvature: number) => number[];
1030
+ type LogMapOp = (point: number[], target: number[], curvature: number) => number[];
1031
+ type MobiusOp = (a: number[], b: number[], curvature: number) => number[];
1032
+ type TransportOp = (vector: number[], start: number[], end: number[], curvature: number) => number[];
1033
+ type HyperbolicCentroidOp = (points: number[][], curvature: number) => number[];
1034
+ type EmbedTextOp = (text: string, model?: string) => number[];
1035
+ type EmbedBatchOp = (texts: string[], model?: string) => number[][];
1036
+ type EmbedImageOp = (imageData: Uint8Array, model?: string) => number[];
1037
+ type EmbedChunkOp = (text: string, chunkSize: number, overlap: number) => number[][];
1038
+ type QuantizeOp = (vector: number[], bits: number) => Uint8Array;
1039
+ type ProductQuantizeOp = (vector: number[], numSubvectors: number, bits: number) => Uint8Array;
1040
+ type DequantizeOp = (quantized: Uint8Array, originalDim: number) => number[];
1041
+ type BinaryQuantizeOp = (vector: number[]) => Uint8Array;
1042
+ type VersionOp = () => string;
1043
+ type ConfigOp = () => Record<string, unknown>;
1044
+ type StatsOp = () => RuVectorStats;
1045
+ type HealthCheckOp = () => HealthStatus;
1046
+ type VacuumOp = (tableName?: string) => void;
1047
+ type AnalyzeOp = (tableName?: string) => AnalysisResult;
1048
+
1049
+ /**
1050
+ * Index statistics.
1051
+ */
1052
+ export interface IndexStats {
1053
+ /** Index name */
1054
+ readonly indexName: string;
1055
+ /** Index type */
1056
+ readonly indexType: VectorIndexType;
1057
+ /** Number of vectors indexed */
1058
+ readonly numVectors: number;
1059
+ /** Index size in bytes */
1060
+ readonly sizeBytes: number;
1061
+ /** Build time in milliseconds */
1062
+ readonly buildTimeMs: number;
1063
+ /** Last rebuild timestamp */
1064
+ readonly lastRebuild: Date;
1065
+ /** Index-specific stats */
1066
+ readonly params: Record<string, unknown>;
1067
+ }
1068
+
1069
+ /**
1070
+ * RuVector statistics.
1071
+ */
1072
+ export interface RuVectorStats {
1073
+ /** Version string */
1074
+ readonly version: string;
1075
+ /** Total vectors stored */
1076
+ readonly totalVectors: number;
1077
+ /** Total storage size in bytes */
1078
+ readonly totalSizeBytes: number;
1079
+ /** Number of indices */
1080
+ readonly numIndices: number;
1081
+ /** Number of tables with vectors */
1082
+ readonly numTables: number;
1083
+ /** Query statistics */
1084
+ readonly queryStats: QueryStats;
1085
+ /** Memory statistics */
1086
+ readonly memoryStats: MemoryStats;
1087
+ }
1088
+
1089
+ /**
1090
+ * Query statistics.
1091
+ */
1092
+ export interface QueryStats {
1093
+ /** Total queries executed */
1094
+ readonly totalQueries: number;
1095
+ /** Average query time in milliseconds */
1096
+ readonly avgQueryTimeMs: number;
1097
+ /** 95th percentile query time */
1098
+ readonly p95QueryTimeMs: number;
1099
+ /** 99th percentile query time */
1100
+ readonly p99QueryTimeMs: number;
1101
+ /** Cache hit rate */
1102
+ readonly cacheHitRate: number;
1103
+ }
1104
+
1105
+ /**
1106
+ * Memory statistics.
1107
+ */
1108
+ export interface MemoryStats {
1109
+ /** Total memory used in bytes */
1110
+ readonly usedBytes: number;
1111
+ /** Peak memory usage in bytes */
1112
+ readonly peakBytes: number;
1113
+ /** Index memory in bytes */
1114
+ readonly indexBytes: number;
1115
+ /** Cache memory in bytes */
1116
+ readonly cacheBytes: number;
1117
+ }
1118
+
1119
+ /**
1120
+ * Health status.
1121
+ */
1122
+ export interface HealthStatus {
1123
+ /** Overall health status */
1124
+ readonly status: 'healthy' | 'degraded' | 'unhealthy';
1125
+ /** Component statuses */
1126
+ readonly components: Record<string, ComponentHealth>;
1127
+ /** Last check timestamp */
1128
+ readonly lastCheck: Date;
1129
+ /** Issues found */
1130
+ readonly issues: string[];
1131
+ }
1132
+
1133
+ /**
1134
+ * Component health.
1135
+ */
1136
+ export interface ComponentHealth {
1137
+ /** Component name */
1138
+ readonly name: string;
1139
+ /** Health status */
1140
+ readonly healthy: boolean;
1141
+ /** Latency in milliseconds */
1142
+ readonly latencyMs?: number;
1143
+ /** Error message if unhealthy */
1144
+ readonly error?: string;
1145
+ }
1146
+
1147
+ /**
1148
+ * Analysis result from ANALYZE operation.
1149
+ */
1150
+ export interface AnalysisResult {
1151
+ /** Table analyzed */
1152
+ readonly tableName: string;
1153
+ /** Number of rows */
1154
+ readonly numRows: number;
1155
+ /** Column statistics */
1156
+ readonly columnStats: ColumnStats[];
1157
+ /** Recommendations */
1158
+ readonly recommendations: string[];
1159
+ }
1160
+
1161
+ /**
1162
+ * Column statistics.
1163
+ */
1164
+ export interface ColumnStats {
1165
+ /** Column name */
1166
+ readonly columnName: string;
1167
+ /** Data type */
1168
+ readonly dataType: string;
1169
+ /** Null percentage */
1170
+ readonly nullPercent: number;
1171
+ /** Distinct values */
1172
+ readonly distinctCount: number;
1173
+ /** Average value size in bytes */
1174
+ readonly avgSizeBytes: number;
1175
+ }
1176
+
1177
+ // ============================================================================
1178
+ // Event Types
1179
+ // ============================================================================
1180
+
1181
+ /**
1182
+ * RuVector event types.
1183
+ */
1184
+ export type RuVectorEventType =
1185
+ // Connection Events
1186
+ | 'connection:open'
1187
+ | 'connection:close'
1188
+ | 'connection:error'
1189
+ | 'connection:reconnect'
1190
+ | 'connection:pool_acquired'
1191
+ | 'connection:pool_released'
1192
+
1193
+ // Query Events
1194
+ | 'query:start'
1195
+ | 'query:complete'
1196
+ | 'query:error'
1197
+ | 'query:slow'
1198
+
1199
+ // Index Events
1200
+ | 'index:created'
1201
+ | 'index:dropped'
1202
+ | 'index:rebuilt'
1203
+ | 'index:progress'
1204
+
1205
+ // Vector Events
1206
+ | 'vector:inserted'
1207
+ | 'vector:updated'
1208
+ | 'vector:deleted'
1209
+ | 'vector:batch_complete'
1210
+
1211
+ // Search Events
1212
+ | 'search:start'
1213
+ | 'search:complete'
1214
+ | 'search:cache_hit'
1215
+ | 'search:cache_miss'
1216
+
1217
+ // Attention Events
1218
+ | 'attention:computed'
1219
+ | 'attention:cached'
1220
+
1221
+ // GNN Events
1222
+ | 'gnn:forward'
1223
+ | 'gnn:message_passing'
1224
+
1225
+ // Hyperbolic Events
1226
+ | 'hyperbolic:embed'
1227
+ | 'hyperbolic:distance'
1228
+
1229
+ // Admin Events
1230
+ | 'admin:vacuum'
1231
+ | 'admin:analyze'
1232
+ | 'admin:checkpoint';
1233
+
1234
+ /**
1235
+ * Base event interface.
1236
+ */
1237
+ export interface RuVectorEvent<T extends RuVectorEventType = RuVectorEventType> {
1238
+ /** Event type */
1239
+ readonly type: T;
1240
+ /** Timestamp */
1241
+ readonly timestamp: Date;
1242
+ /** Event data */
1243
+ readonly data: EventDataMap[T];
1244
+ /** Source of the event */
1245
+ readonly source?: string;
1246
+ /** Correlation ID for tracing */
1247
+ readonly correlationId?: string;
1248
+ }
1249
+
1250
+ /**
1251
+ * Event data type mapping.
1252
+ */
1253
+ export interface EventDataMap {
1254
+ 'connection:open': ConnectionEventData;
1255
+ 'connection:close': ConnectionEventData;
1256
+ 'connection:error': ErrorEventData;
1257
+ 'connection:reconnect': ConnectionEventData;
1258
+ 'connection:pool_acquired': PoolEventData;
1259
+ 'connection:pool_released': PoolEventData;
1260
+
1261
+ 'query:start': QueryStartEventData;
1262
+ 'query:complete': QueryCompleteEventData;
1263
+ 'query:error': QueryErrorEventData;
1264
+ 'query:slow': QuerySlowEventData;
1265
+
1266
+ 'index:created': IndexEventData;
1267
+ 'index:dropped': IndexEventData;
1268
+ 'index:rebuilt': IndexEventData;
1269
+ 'index:progress': IndexProgressEventData;
1270
+
1271
+ 'vector:inserted': VectorEventData;
1272
+ 'vector:updated': VectorEventData;
1273
+ 'vector:deleted': VectorEventData;
1274
+ 'vector:batch_complete': BatchEventData;
1275
+
1276
+ 'search:start': SearchStartEventData;
1277
+ 'search:complete': SearchCompleteEventData;
1278
+ 'search:cache_hit': CacheEventData;
1279
+ 'search:cache_miss': CacheEventData;
1280
+
1281
+ 'attention:computed': AttentionEventData;
1282
+ 'attention:cached': CacheEventData;
1283
+
1284
+ 'gnn:forward': GNNEventData;
1285
+ 'gnn:message_passing': GNNEventData;
1286
+
1287
+ 'hyperbolic:embed': HyperbolicEventData;
1288
+ 'hyperbolic:distance': HyperbolicEventData;
1289
+
1290
+ 'admin:vacuum': AdminEventData;
1291
+ 'admin:analyze': AdminEventData;
1292
+ 'admin:checkpoint': AdminEventData;
1293
+ }
1294
+
1295
+ /**
1296
+ * Connection event data.
1297
+ */
1298
+ export interface ConnectionEventData {
1299
+ readonly connectionId: string;
1300
+ readonly host: string;
1301
+ readonly port: number;
1302
+ readonly database: string;
1303
+ readonly durationMs?: number;
1304
+ }
1305
+
1306
+ /**
1307
+ * Error event data.
1308
+ */
1309
+ export interface ErrorEventData {
1310
+ readonly error: Error;
1311
+ readonly code?: string;
1312
+ readonly detail?: string;
1313
+ readonly hint?: string;
1314
+ }
1315
+
1316
+ /**
1317
+ * Pool event data.
1318
+ */
1319
+ export interface PoolEventData {
1320
+ readonly connectionId: string;
1321
+ readonly poolSize: number;
1322
+ readonly availableConnections: number;
1323
+ readonly waitingClients: number;
1324
+ }
1325
+
1326
+ /**
1327
+ * Query start event data.
1328
+ */
1329
+ export interface QueryStartEventData {
1330
+ readonly queryId: string;
1331
+ readonly sql: string;
1332
+ readonly params?: unknown[];
1333
+ }
1334
+
1335
+ /**
1336
+ * Query complete event data.
1337
+ */
1338
+ export interface QueryCompleteEventData {
1339
+ readonly queryId: string;
1340
+ readonly durationMs: number;
1341
+ readonly rowCount: number;
1342
+ readonly affectedRows?: number;
1343
+ }
1344
+
1345
+ /**
1346
+ * Query error event data.
1347
+ */
1348
+ export interface QueryErrorEventData extends QueryStartEventData, ErrorEventData {
1349
+ readonly durationMs: number;
1350
+ }
1351
+
1352
+ /**
1353
+ * Query slow event data.
1354
+ */
1355
+ export interface QuerySlowEventData extends QueryCompleteEventData {
1356
+ readonly threshold: number;
1357
+ readonly explain?: string;
1358
+ }
1359
+
1360
+ /**
1361
+ * Index event data.
1362
+ */
1363
+ export interface IndexEventData {
1364
+ readonly indexName: string;
1365
+ readonly tableName: string;
1366
+ readonly columnName: string;
1367
+ readonly indexType: VectorIndexType;
1368
+ readonly durationMs?: number;
1369
+ }
1370
+
1371
+ /**
1372
+ * Index progress event data.
1373
+ */
1374
+ export interface IndexProgressEventData {
1375
+ readonly indexName: string;
1376
+ readonly progress: number;
1377
+ readonly phase: string;
1378
+ readonly vectorsProcessed: number;
1379
+ readonly totalVectors: number;
1380
+ readonly estimatedTimeRemainingMs: number;
1381
+ }
1382
+
1383
+ /**
1384
+ * Vector event data.
1385
+ */
1386
+ export interface VectorEventData {
1387
+ readonly tableName: string;
1388
+ readonly vectorId: string | number;
1389
+ readonly dimensions: number;
1390
+ }
1391
+
1392
+ /**
1393
+ * Batch event data.
1394
+ */
1395
+ export interface BatchEventData {
1396
+ readonly tableName: string;
1397
+ readonly count: number;
1398
+ readonly durationMs: number;
1399
+ readonly successCount: number;
1400
+ readonly failedCount: number;
1401
+ }
1402
+
1403
+ /**
1404
+ * Search start event data.
1405
+ */
1406
+ export interface SearchStartEventData {
1407
+ readonly searchId: string;
1408
+ readonly tableName: string;
1409
+ readonly k: number;
1410
+ readonly metric: DistanceMetric;
1411
+ readonly hasFilters: boolean;
1412
+ }
1413
+
1414
+ /**
1415
+ * Search complete event data.
1416
+ */
1417
+ export interface SearchCompleteEventData {
1418
+ readonly searchId: string;
1419
+ readonly durationMs: number;
1420
+ readonly resultCount: number;
1421
+ readonly scannedCount: number;
1422
+ readonly cacheHit: boolean;
1423
+ }
1424
+
1425
+ /**
1426
+ * Cache event data.
1427
+ */
1428
+ export interface CacheEventData {
1429
+ readonly cacheKey: string;
1430
+ readonly cacheSize: number;
1431
+ readonly ttl?: number;
1432
+ }
1433
+
1434
+ /**
1435
+ * Attention event data.
1436
+ */
1437
+ export interface AttentionEventData {
1438
+ readonly mechanism: AttentionMechanism;
1439
+ readonly seqLen: number;
1440
+ readonly numHeads: number;
1441
+ readonly durationMs: number;
1442
+ readonly memoryBytes: number;
1443
+ }
1444
+
1445
+ /**
1446
+ * GNN event data.
1447
+ */
1448
+ export interface GNNEventData {
1449
+ readonly layerType: GNNLayerType;
1450
+ readonly numNodes: number;
1451
+ readonly numEdges: number;
1452
+ readonly durationMs: number;
1453
+ }
1454
+
1455
+ /**
1456
+ * Hyperbolic event data.
1457
+ */
1458
+ export interface HyperbolicEventData {
1459
+ readonly model: HyperbolicModel;
1460
+ readonly operation: HyperbolicOperation;
1461
+ readonly numPoints: number;
1462
+ readonly durationMs: number;
1463
+ }
1464
+
1465
+ /**
1466
+ * Admin event data.
1467
+ */
1468
+ export interface AdminEventData {
1469
+ readonly operation: string;
1470
+ readonly tableName?: string;
1471
+ readonly durationMs: number;
1472
+ readonly details?: Record<string, unknown>;
1473
+ }
1474
+
1475
+ /**
1476
+ * Event handler type.
1477
+ */
1478
+ export type RuVectorEventHandler<T extends RuVectorEventType = RuVectorEventType> =
1479
+ (event: RuVectorEvent<T>) => void | Promise<void>;
1480
+
1481
+ /**
1482
+ * Event emitter interface.
1483
+ */
1484
+ export interface RuVectorEventEmitter {
1485
+ on<T extends RuVectorEventType>(event: T, handler: RuVectorEventHandler<T>): () => void;
1486
+ off<T extends RuVectorEventType>(event: T, handler: RuVectorEventHandler<T>): void;
1487
+ once<T extends RuVectorEventType>(event: T, handler: RuVectorEventHandler<T>): () => void;
1488
+ emit<T extends RuVectorEventType>(event: T, data: EventDataMap[T]): void;
1489
+ removeAllListeners(event?: RuVectorEventType): void;
1490
+ }
1491
+
1492
+ // ============================================================================
1493
+ // Result Types
1494
+ // ============================================================================
1495
+
1496
+ /**
1497
+ * Generic result wrapper with success/error discrimination.
1498
+ */
1499
+ export type Result<T, E = Error> =
1500
+ | { readonly success: true; readonly data: T }
1501
+ | { readonly success: false; readonly error: E };
1502
+
1503
+ /**
1504
+ * Async result type alias.
1505
+ */
1506
+ export type AsyncResult<T, E = Error> = Promise<Result<T, E>>;
1507
+
1508
+ /**
1509
+ * Connection result.
1510
+ */
1511
+ export interface ConnectionResult {
1512
+ /** Connection ID */
1513
+ readonly connectionId: string;
1514
+ /** Whether connection is ready */
1515
+ readonly ready: boolean;
1516
+ /** Server version */
1517
+ readonly serverVersion: string;
1518
+ /** RuVector extension version */
1519
+ readonly ruVectorVersion: string;
1520
+ /** Connection parameters */
1521
+ readonly parameters: Record<string, string>;
1522
+ }
1523
+
1524
+ /**
1525
+ * Query result wrapper.
1526
+ */
1527
+ export interface QueryResult<T = Record<string, unknown>> {
1528
+ /** Query rows */
1529
+ readonly rows: T[];
1530
+ /** Row count */
1531
+ readonly rowCount: number;
1532
+ /** Affected rows (for INSERT/UPDATE/DELETE) */
1533
+ readonly affectedRows?: number;
1534
+ /** Query execution time in milliseconds */
1535
+ readonly durationMs: number;
1536
+ /** Query plan (if EXPLAIN was used) */
1537
+ readonly plan?: QueryPlan;
1538
+ /** Command type (SELECT, INSERT, etc.) */
1539
+ readonly command: string;
1540
+ }
1541
+
1542
+ /**
1543
+ * Query execution plan.
1544
+ */
1545
+ export interface QueryPlan {
1546
+ /** Plan nodes */
1547
+ readonly nodes: PlanNode[];
1548
+ /** Total cost estimate */
1549
+ readonly totalCost: number;
1550
+ /** Actual execution time (if ANALYZE was used) */
1551
+ readonly actualTimeMs?: number;
1552
+ /** Actual rows returned */
1553
+ readonly actualRows?: number;
1554
+ /** Peak memory usage */
1555
+ readonly peakMemory?: number;
1556
+ }
1557
+
1558
+ /**
1559
+ * Query plan node.
1560
+ */
1561
+ export interface PlanNode {
1562
+ /** Node type (Seq Scan, Index Scan, etc.) */
1563
+ readonly type: string;
1564
+ /** Relation name (if applicable) */
1565
+ readonly relation?: string;
1566
+ /** Index name (if applicable) */
1567
+ readonly indexName?: string;
1568
+ /** Startup cost */
1569
+ readonly startupCost: number;
1570
+ /** Total cost */
1571
+ readonly totalCost: number;
1572
+ /** Estimated rows */
1573
+ readonly planRows: number;
1574
+ /** Actual rows (if ANALYZE) */
1575
+ readonly actualRows?: number;
1576
+ /** Actual time (if ANALYZE) */
1577
+ readonly actualTimeMs?: number;
1578
+ /** Child nodes */
1579
+ readonly children?: PlanNode[];
1580
+ /** Additional output info */
1581
+ readonly output?: string[];
1582
+ /** Filter condition */
1583
+ readonly filter?: string;
1584
+ /** Index condition */
1585
+ readonly indexCond?: string;
1586
+ }
1587
+
1588
+ /**
1589
+ * Batch operation result.
1590
+ */
1591
+ export interface BatchResult<T = void> {
1592
+ /** Total items processed */
1593
+ readonly total: number;
1594
+ /** Successfully processed items */
1595
+ readonly successful: number;
1596
+ /** Failed items */
1597
+ readonly failed: number;
1598
+ /** Results per item (if applicable) */
1599
+ readonly results?: T[];
1600
+ /** Errors encountered */
1601
+ readonly errors?: BatchError[];
1602
+ /** Total duration in milliseconds */
1603
+ readonly durationMs: number;
1604
+ /** Throughput (items per second) */
1605
+ readonly throughput: number;
1606
+ }
1607
+
1608
+ /**
1609
+ * Batch error.
1610
+ */
1611
+ export interface BatchError {
1612
+ /** Index of the failed item */
1613
+ readonly index: number;
1614
+ /** Error message */
1615
+ readonly message: string;
1616
+ /** Error code */
1617
+ readonly code?: string;
1618
+ /** Original input that caused the error */
1619
+ readonly input?: unknown;
1620
+ }
1621
+
1622
+ /**
1623
+ * Transaction result.
1624
+ */
1625
+ export interface TransactionResult<T = void> {
1626
+ /** Transaction ID */
1627
+ readonly transactionId: string;
1628
+ /** Whether transaction was committed */
1629
+ readonly committed: boolean;
1630
+ /** Result data (if any) */
1631
+ readonly data?: T;
1632
+ /** Transaction duration in milliseconds */
1633
+ readonly durationMs: number;
1634
+ /** Number of queries executed */
1635
+ readonly queryCount: number;
1636
+ }
1637
+
1638
+ /**
1639
+ * Migration result.
1640
+ */
1641
+ export interface MigrationResult {
1642
+ /** Migration name/version */
1643
+ readonly name: string;
1644
+ /** Whether migration succeeded */
1645
+ readonly success: boolean;
1646
+ /** Migration direction */
1647
+ readonly direction: 'up' | 'down';
1648
+ /** Duration in milliseconds */
1649
+ readonly durationMs: number;
1650
+ /** Affected tables */
1651
+ readonly affectedTables: string[];
1652
+ /** Error message (if failed) */
1653
+ readonly error?: string;
1654
+ }
1655
+
1656
+ /**
1657
+ * Bulk search result.
1658
+ */
1659
+ export interface BulkSearchResult {
1660
+ /** Results per query */
1661
+ readonly results: VectorSearchResult[][];
1662
+ /** Total search time in milliseconds */
1663
+ readonly totalDurationMs: number;
1664
+ /** Average search time per query */
1665
+ readonly avgDurationMs: number;
1666
+ /** Cache statistics */
1667
+ readonly cacheStats: {
1668
+ readonly hits: number;
1669
+ readonly misses: number;
1670
+ readonly hitRate: number;
1671
+ };
1672
+ }
1673
+
1674
+ /**
1675
+ * Embedding result.
1676
+ */
1677
+ export interface EmbeddingResult {
1678
+ /** Embedding vector */
1679
+ readonly embedding: number[];
1680
+ /** Model used */
1681
+ readonly model: string;
1682
+ /** Token count */
1683
+ readonly tokenCount: number;
1684
+ /** Embedding duration in milliseconds */
1685
+ readonly durationMs: number;
1686
+ /** Dimension */
1687
+ readonly dimension: number;
1688
+ }
1689
+
1690
+ /**
1691
+ * Batch embedding result.
1692
+ */
1693
+ export interface BatchEmbeddingResult {
1694
+ /** Embedding results */
1695
+ readonly embeddings: EmbeddingResult[];
1696
+ /** Total tokens processed */
1697
+ readonly totalTokens: number;
1698
+ /** Total duration in milliseconds */
1699
+ readonly totalDurationMs: number;
1700
+ /** Throughput (tokens per second) */
1701
+ readonly throughput: number;
1702
+ }
1703
+
1704
+ // ============================================================================
1705
+ // Client Interface
1706
+ // ============================================================================
1707
+
1708
+ /**
1709
+ * RuVector client configuration options.
1710
+ */
1711
+ export interface RuVectorClientOptions extends RuVectorConfig {
1712
+ /** Enable automatic reconnection */
1713
+ readonly autoReconnect?: boolean;
1714
+ /** Maximum reconnection attempts */
1715
+ readonly maxReconnectAttempts?: number;
1716
+ /** Event handlers */
1717
+ readonly eventHandlers?: Partial<{
1718
+ [K in RuVectorEventType]: RuVectorEventHandler<K>;
1719
+ }>;
1720
+ /** Custom logger */
1721
+ readonly logger?: RuVectorLogger;
1722
+ }
1723
+
1724
+ /**
1725
+ * Logger interface.
1726
+ */
1727
+ export interface RuVectorLogger {
1728
+ debug(message: string, meta?: Record<string, unknown>): void;
1729
+ info(message: string, meta?: Record<string, unknown>): void;
1730
+ warn(message: string, meta?: Record<string, unknown>): void;
1731
+ error(message: string, meta?: Record<string, unknown>): void;
1732
+ }
1733
+
1734
+ /**
1735
+ * RuVector client interface.
1736
+ */
1737
+ export interface IRuVectorClient extends RuVectorEventEmitter {
1738
+ // Connection Management
1739
+ connect(): Promise<ConnectionResult>;
1740
+ disconnect(): Promise<void>;
1741
+ isConnected(): boolean;
1742
+ getConnectionInfo(): ConnectionResult | null;
1743
+
1744
+ // Vector Operations
1745
+ search(options: VectorSearchOptions): Promise<VectorSearchResult[]>;
1746
+ batchSearch(options: BatchVectorOptions): Promise<BulkSearchResult>;
1747
+ insert(options: VectorInsertOptions): Promise<BatchResult<string>>;
1748
+ update(options: VectorUpdateOptions): Promise<boolean>;
1749
+ delete(tableName: string, id: string | number): Promise<boolean>;
1750
+ bulkDelete(tableName: string, ids: Array<string | number>): Promise<BatchResult>;
1751
+
1752
+ // Index Management
1753
+ createIndex(options: VectorIndexOptions): Promise<void>;
1754
+ dropIndex(indexName: string): Promise<void>;
1755
+ rebuildIndex(indexName: string): Promise<void>;
1756
+ getIndexStats(indexName: string): Promise<IndexStats>;
1757
+ listIndices(tableName?: string): Promise<IndexStats[]>;
1758
+
1759
+ // Attention Operations
1760
+ computeAttention(input: AttentionInput, config: AttentionConfig): Promise<AttentionOutput>;
1761
+
1762
+ // GNN Operations
1763
+ runGNNLayer(graph: GraphData, layer: GNNLayer): Promise<GNNOutput>;
1764
+ buildGraph(nodeFeatures: number[][], edges: [number, number][]): GraphData;
1765
+
1766
+ // Hyperbolic Operations
1767
+ hyperbolicEmbed(input: HyperbolicInput, config: HyperbolicEmbedding): Promise<HyperbolicOutput>;
1768
+ hyperbolicDistance(a: number[], b: number[], config: HyperbolicEmbedding): Promise<number>;
1769
+
1770
+ // Embedding Operations
1771
+ embed(text: string, model?: string): Promise<EmbeddingResult>;
1772
+ embedBatch(texts: string[], model?: string): Promise<BatchEmbeddingResult>;
1773
+
1774
+ // Transaction Support
1775
+ transaction<T>(fn: (tx: IRuVectorTransaction) => Promise<T>): Promise<TransactionResult<T>>;
1776
+
1777
+ // Admin Operations
1778
+ vacuum(tableName?: string): Promise<void>;
1779
+ analyze(tableName?: string): Promise<AnalysisResult>;
1780
+ healthCheck(): Promise<HealthStatus>;
1781
+ getStats(): Promise<RuVectorStats>;
1782
+ }
1783
+
1784
+ /**
1785
+ * Transaction interface.
1786
+ */
1787
+ export interface IRuVectorTransaction {
1788
+ query<T = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<QueryResult<T>>;
1789
+ insert(options: VectorInsertOptions): Promise<BatchResult<string>>;
1790
+ update(options: VectorUpdateOptions): Promise<boolean>;
1791
+ delete(tableName: string, id: string | number): Promise<boolean>;
1792
+ commit(): Promise<void>;
1793
+ rollback(): Promise<void>;
1794
+ }
1795
+
1796
+ // ============================================================================
1797
+ // Type Guards
1798
+ // ============================================================================
1799
+
1800
+ /**
1801
+ * Check if a value is a valid distance metric.
1802
+ */
1803
+ export function isDistanceMetric(value: unknown): value is DistanceMetric {
1804
+ const metrics = [
1805
+ 'cosine', 'euclidean', 'dot', 'hamming', 'manhattan',
1806
+ 'chebyshev', 'jaccard', 'minkowski', 'bray_curtis',
1807
+ 'canberra', 'mahalanobis', 'correlation'
1808
+ ];
1809
+ return typeof value === 'string' && metrics.indexOf(value) !== -1;
1810
+ }
1811
+
1812
+ /**
1813
+ * Check if a value is a valid attention mechanism.
1814
+ */
1815
+ export function isAttentionMechanism(value: unknown): value is AttentionMechanism {
1816
+ const mechanisms = [
1817
+ 'multi_head', 'self_attention', 'cross_attention', 'sparse_attention',
1818
+ 'linear_attention', 'local_attention', 'global_attention', 'flash_attention',
1819
+ 'flash_attention_v2', 'memory_efficient', 'chunk_attention', 'sliding_window',
1820
+ 'dilated_attention', 'block_sparse', 'relative_position', 'rotary_position',
1821
+ 'alibi', 'causal', 'bidirectional', 'axial', 'performer', 'linformer',
1822
+ 'reformer', 'synthesizer', 'routing', 'mixture_of_experts', 'graph_attention',
1823
+ 'hyperbolic_attention', 'spherical_attention', 'toroidal_attention',
1824
+ 'temporal_attention', 'recurrent_attention', 'state_space', 'cross_modal',
1825
+ 'perceiver', 'flamingo', 'retrieval_attention', 'knn_attention', 'memory_augmented'
1826
+ ];
1827
+ return typeof value === 'string' && mechanisms.indexOf(value) !== -1;
1828
+ }
1829
+
1830
+ /**
1831
+ * Check if a value is a valid GNN layer type.
1832
+ */
1833
+ export function isGNNLayerType(value: unknown): value is GNNLayerType {
1834
+ const types = [
1835
+ 'gcn', 'gat', 'gat_v2', 'sage', 'gin', 'mpnn', 'edge_conv',
1836
+ 'point_conv', 'transformer', 'pna', 'film', 'rgcn', 'hgt', 'han', 'metapath'
1837
+ ];
1838
+ return typeof value === 'string' && types.indexOf(value) !== -1;
1839
+ }
1840
+
1841
+ /**
1842
+ * Check if a value is a valid hyperbolic model.
1843
+ */
1844
+ export function isHyperbolicModel(value: unknown): value is HyperbolicModel {
1845
+ const models = ['poincare', 'lorentz', 'klein', 'half_space'];
1846
+ return typeof value === 'string' && models.indexOf(value) !== -1;
1847
+ }
1848
+
1849
+ /**
1850
+ * Check if a value is a valid vector index type.
1851
+ */
1852
+ export function isVectorIndexType(value: unknown): value is VectorIndexType {
1853
+ const types = ['hnsw', 'ivfflat', 'ivfpq', 'flat', 'diskann'];
1854
+ return typeof value === 'string' && types.indexOf(value) !== -1;
1855
+ }
1856
+
1857
+ /**
1858
+ * Check if a result is successful.
1859
+ */
1860
+ export function isSuccess<T, E>(result: Result<T, E>): result is { success: true; data: T } {
1861
+ return result.success === true;
1862
+ }
1863
+
1864
+ /**
1865
+ * Check if a result is an error.
1866
+ */
1867
+ export function isError<T, E>(result: Result<T, E>): result is { success: false; error: E } {
1868
+ return result.success === false;
1869
+ }
1870
+
1871
+ // ============================================================================
1872
+ // Factory Types
1873
+ // ============================================================================
1874
+
1875
+ /**
1876
+ * Factory function for creating RuVector clients.
1877
+ */
1878
+ export type RuVectorClientFactory = (options: RuVectorClientOptions) => IRuVectorClient;
1879
+
1880
+ /**
1881
+ * Plugin registration type for the RuVector integration.
1882
+ */
1883
+ export interface RuVectorPluginRegistration {
1884
+ /** Plugin name */
1885
+ readonly name: 'ruvector';
1886
+ /** Plugin version */
1887
+ readonly version: string;
1888
+ /** Client factory */
1889
+ readonly createClient: RuVectorClientFactory;
1890
+ /** Supported features */
1891
+ readonly features: RuVectorFeature[];
1892
+ }
1893
+
1894
+ /**
1895
+ * RuVector feature flags.
1896
+ */
1897
+ export type RuVectorFeature =
1898
+ | 'vector_search'
1899
+ | 'hnsw_index'
1900
+ | 'ivf_index'
1901
+ | 'attention'
1902
+ | 'gnn'
1903
+ | 'hyperbolic'
1904
+ | 'quantization'
1905
+ | 'batch_operations'
1906
+ | 'transactions'
1907
+ | 'streaming'
1908
+ | 'caching';
1909
+
1910
+ // ============================================================================
1911
+ // Export Aggregation
1912
+ // ============================================================================
1913
+
1914
+ /**
1915
+ * All SQL functions aggregated.
1916
+ */
1917
+ export interface RuVectorSQLFunctions
1918
+ extends VectorFunctions,
1919
+ IndexFunctions,
1920
+ AttentionFunctions,
1921
+ GNNFunctions,
1922
+ HyperbolicFunctions,
1923
+ EmbeddingFunctions,
1924
+ QuantizationFunctions,
1925
+ UtilityFunctions {}
1926
+
1927
+ /**
1928
+ * Namespace export for module organization.
1929
+ */
1930
+ export namespace RuVector {
1931
+ export type Config = RuVectorConfig;
1932
+ export type Client = IRuVectorClient;
1933
+ export type ClientOptions = RuVectorClientOptions;
1934
+ export type SearchOptions = VectorSearchOptions;
1935
+ export type SearchResult = VectorSearchResult;
1936
+ export type Attention = AttentionMechanism;
1937
+ export type AttentionCfg = AttentionConfig;
1938
+ export type GNN = GNNLayerType;
1939
+ export type GNNLayerCfg = GNNLayer;
1940
+ export type Hyperbolic = HyperbolicModel;
1941
+ export type HyperbolicCfg = HyperbolicEmbedding;
1942
+ export type Event = RuVectorEventType;
1943
+ export type EventData<T extends RuVectorEventType> = EventDataMap[T];
1944
+ export type Feature = RuVectorFeature;
1945
+ }