@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,1245 @@
1
+ # RuVector PostgreSQL Bridge Plugin Architecture
2
+
3
+ ## Document Information
4
+
5
+ | Property | Value |
6
+ |----------|-------|
7
+ | Version | 1.0.0 |
8
+ | Status | Draft |
9
+ | Author | Claude Flow Architecture Team |
10
+ | Last Updated | 2026-01-16 |
11
+ | ADR References | ADR-006 (Unified Memory), ADR-009 (Hybrid Memory Backend) |
12
+
13
+ ---
14
+
15
+ ## 1. Executive Summary
16
+
17
+ The RuVector PostgreSQL Bridge plugin provides a high-performance integration layer between Claude-Flow v3 and PostgreSQL databases enhanced with RuVector extensions. This plugin exposes 53+ SQL functions for vector operations, 39 attention mechanisms, Graph Neural Network (GNN) layers, hyperbolic embeddings, and self-learning capabilities through MCP tools.
18
+
19
+ ### Key Capabilities
20
+
21
+ - **Vector Operations**: Similarity search, clustering, quantization (150x-12,500x faster)
22
+ - **Attention Mechanisms**: Multi-head, self-attention, cross-attention, sparse variants
23
+ - **Graph Processing**: GNN layers, message passing, node/edge embeddings
24
+ - **Hyperbolic Geometry**: Poincare ball, Lorentz model for hierarchical data
25
+ - **Self-Learning**: Query optimization, index tuning, pattern recognition
26
+
27
+ ---
28
+
29
+ ## 2. System Context (C4 Level 1)
30
+
31
+ ```
32
+ +------------------------------------------------------------------+
33
+ | Claude Code / MCP Client |
34
+ +------------------------------------------------------------------+
35
+ |
36
+ | MCP Protocol (stdio/HTTP/WebSocket)
37
+ v
38
+ +------------------------------------------------------------------+
39
+ | Claude-Flow v3 MCP Server |
40
+ | +------------------------------------------------------------+ |
41
+ | | RuVector PostgreSQL Bridge | |
42
+ | | +----------------+ +----------------+ +---------------+ | |
43
+ | | | Connection | | Tool | | Query | | |
44
+ | | | Pool Manager | | Registry | | Executor | | |
45
+ | | +----------------+ +----------------+ +---------------+ | |
46
+ | +------------------------------------------------------------+ |
47
+ +------------------------------------------------------------------+
48
+ |
49
+ | pg Protocol (libpq/node-postgres)
50
+ v
51
+ +------------------------------------------------------------------+
52
+ | PostgreSQL + RuVector Extensions |
53
+ | +------------------+ +------------------+ +----------------+ |
54
+ | | pg_ruvector | | pg_ruvector_gnn | | pg_ruvector | |
55
+ | | (vectors) | | (graph ops) | | _attention | |
56
+ | +------------------+ +------------------+ +----------------+ |
57
+ +------------------------------------------------------------------+
58
+ ```
59
+
60
+ ---
61
+
62
+ ## 3. Container Architecture (C4 Level 2)
63
+
64
+ ### 3.1 Plugin Container Structure
65
+
66
+ ```
67
+ @claude-flow/plugins/src/integrations/ruvector/
68
+ |
69
+ +-- index.ts # Plugin entry point & exports
70
+ +-- plugin.ts # Main plugin class (extends BasePlugin)
71
+ +-- ARCHITECTURE.md # This document
72
+ |
73
+ +-- core/
74
+ | +-- connection-manager.ts # PostgreSQL connection pooling
75
+ | +-- query-executor.ts # Query execution with metrics
76
+ | +-- schema-manager.ts # Extension & schema management
77
+ | +-- types.ts # Core type definitions
78
+ |
79
+ +-- sql/
80
+ | +-- index.ts # SQL function registry
81
+ | +-- vector-functions.ts # 15+ vector similarity functions
82
+ | +-- graph-functions.ts # 12+ graph-aware query functions
83
+ | +-- pattern-functions.ts # 10+ pattern matching functions
84
+ | +-- index-functions.ts # 8+ index management functions
85
+ | +-- aggregate-functions.ts # 8+ vector aggregation functions
86
+ |
87
+ +-- attention/
88
+ | +-- index.ts # Attention mechanism registry
89
+ | +-- multi-head.ts # Multi-head attention (8 variants)
90
+ | +-- self-attention.ts # Self-attention (6 variants)
91
+ | +-- cross-attention.ts # Cross-attention (5 variants)
92
+ | +-- sparse-attention.ts # Sparse attention (10 variants)
93
+ | +-- linear-attention.ts # Linear attention (5 variants)
94
+ | +-- flash-attention.ts # Flash Attention v2 integration
95
+ | +-- types.ts # Attention type definitions
96
+ |
97
+ +-- gnn/
98
+ | +-- index.ts # GNN layer registry
99
+ | +-- graph-conv.ts # Graph convolution layers
100
+ | +-- message-passing.ts # Message passing networks
101
+ | +-- node-embeddings.ts # Node embedding generation
102
+ | +-- edge-embeddings.ts # Edge embedding generation
103
+ | +-- pooling.ts # Graph pooling operations
104
+ | +-- types.ts # GNN type definitions
105
+ |
106
+ +-- hyperbolic/
107
+ | +-- index.ts # Hyperbolic embedding registry
108
+ | +-- poincare.ts # Poincare ball model
109
+ | +-- lorentz.ts # Lorentz (hyperboloid) model
110
+ | +-- distance.ts # Distance calculations
111
+ | +-- operations.ts # Mobius operations
112
+ | +-- types.ts # Hyperbolic type definitions
113
+ |
114
+ +-- learning/
115
+ | +-- index.ts # Self-learning registry
116
+ | +-- query-optimizer.ts # Query plan optimization
117
+ | +-- index-tuner.ts # Index parameter tuning
118
+ | +-- pattern-recognizer.ts # Pattern recognition engine
119
+ | +-- statistics-collector.ts # Usage statistics collection
120
+ | +-- types.ts # Learning type definitions
121
+ |
122
+ +-- mcp/
123
+ | +-- index.ts # MCP tool registration
124
+ | +-- vector-tools.ts # Vector operation tools
125
+ | +-- attention-tools.ts # Attention mechanism tools
126
+ | +-- gnn-tools.ts # GNN operation tools
127
+ | +-- hyperbolic-tools.ts # Hyperbolic embedding tools
128
+ | +-- admin-tools.ts # Administration tools
129
+ ```
130
+
131
+ ---
132
+
133
+ ## 4. Component Architecture (C4 Level 3)
134
+
135
+ ### 4.1 Core Components
136
+
137
+ #### 4.1.1 Connection Manager
138
+
139
+ ```typescript
140
+ /**
141
+ * PostgreSQL Connection Pool Manager
142
+ *
143
+ * Manages connection lifecycle, health checks, and load balancing
144
+ * for PostgreSQL instances with RuVector extensions.
145
+ */
146
+ interface IConnectionManager {
147
+ // Connection lifecycle
148
+ initialize(config: ConnectionConfig): Promise<void>;
149
+ shutdown(): Promise<void>;
150
+
151
+ // Connection acquisition
152
+ acquire(): Promise<PooledConnection>;
153
+ release(connection: PooledConnection): void;
154
+
155
+ // Health monitoring
156
+ healthCheck(): Promise<HealthCheckResult>;
157
+ getStats(): ConnectionPoolStats;
158
+
159
+ // Extension management
160
+ ensureExtensions(): Promise<ExtensionStatus[]>;
161
+ }
162
+
163
+ interface ConnectionConfig {
164
+ host: string;
165
+ port: number;
166
+ database: string;
167
+ user: string;
168
+ password: string;
169
+ ssl?: SSLConfig;
170
+ pool: {
171
+ min: number; // Default: 2
172
+ max: number; // Default: 10
173
+ idleTimeout: number; // Default: 30000ms
174
+ acquireTimeout: number; // Default: 5000ms
175
+ };
176
+ extensions: {
177
+ ruvector: boolean;
178
+ ruvector_gnn?: boolean;
179
+ ruvector_attention?: boolean;
180
+ };
181
+ }
182
+ ```
183
+
184
+ **Design Decisions**:
185
+ - Uses `pg` (node-postgres) for PostgreSQL connectivity
186
+ - Connection pooling with configurable min/max connections
187
+ - Automatic reconnection with exponential backoff
188
+ - Health checks verify extension availability
189
+
190
+ #### 4.1.2 Query Executor
191
+
192
+ ```typescript
193
+ /**
194
+ * Query Executor with Metrics Collection
195
+ *
196
+ * Executes SQL queries with timing, caching, and error handling.
197
+ */
198
+ interface IQueryExecutor {
199
+ // Query execution
200
+ execute<T>(query: string, params?: unknown[]): Promise<QueryResult<T>>;
201
+ executeMany<T>(queries: BatchQuery[]): Promise<QueryResult<T>[]>;
202
+
203
+ // Prepared statements
204
+ prepare(name: string, query: string): Promise<PreparedStatement>;
205
+ executePrepared<T>(name: string, params?: unknown[]): Promise<QueryResult<T>>;
206
+
207
+ // Transaction support
208
+ beginTransaction(): Promise<Transaction>;
209
+
210
+ // Metrics
211
+ getQueryStats(): QueryStatistics;
212
+ resetStats(): void;
213
+ }
214
+
215
+ interface QueryResult<T> {
216
+ rows: T[];
217
+ rowCount: number;
218
+ fields: FieldInfo[];
219
+ duration: number;
220
+ fromCache: boolean;
221
+ }
222
+ ```
223
+
224
+ **Design Decisions**:
225
+ - Query result caching with configurable TTL
226
+ - Automatic query plan analysis for optimization hints
227
+ - Prepared statement reuse for repeated queries
228
+ - Comprehensive metrics collection
229
+
230
+ ### 4.2 SQL Functions Module
231
+
232
+ #### 4.2.1 Vector Functions (15+)
233
+
234
+ | Function | Description | SQL Signature |
235
+ |----------|-------------|---------------|
236
+ | `rv_similarity` | Cosine similarity | `rv_similarity(vector, vector) -> float` |
237
+ | `rv_distance` | Euclidean distance | `rv_distance(vector, vector) -> float` |
238
+ | `rv_inner_product` | Inner product | `rv_inner_product(vector, vector) -> float` |
239
+ | `rv_l1_distance` | Manhattan distance | `rv_l1_distance(vector, vector) -> float` |
240
+ | `rv_l2_distance` | L2 distance | `rv_l2_distance(vector, vector) -> float` |
241
+ | `rv_cosine_distance` | Cosine distance | `rv_cosine_distance(vector, vector) -> float` |
242
+ | `rv_normalize` | L2 normalization | `rv_normalize(vector) -> vector` |
243
+ | `rv_add` | Vector addition | `rv_add(vector, vector) -> vector` |
244
+ | `rv_subtract` | Vector subtraction | `rv_subtract(vector, vector) -> vector` |
245
+ | `rv_multiply` | Scalar multiplication | `rv_multiply(vector, float) -> vector` |
246
+ | `rv_dimensions` | Get dimensions | `rv_dimensions(vector) -> int` |
247
+ | `rv_slice` | Vector slicing | `rv_slice(vector, int, int) -> vector` |
248
+ | `rv_concat` | Vector concatenation | `rv_concat(vector, vector) -> vector` |
249
+ | `rv_quantize` | Quantization | `rv_quantize(vector, int) -> bytea` |
250
+ | `rv_dequantize` | Dequantization | `rv_dequantize(bytea, int) -> vector` |
251
+
252
+ ```typescript
253
+ interface VectorFunctions {
254
+ // Similarity/Distance
255
+ similarity(a: Float32Array, b: Float32Array): Promise<number>;
256
+ distance(a: Float32Array, b: Float32Array, metric: DistanceMetric): Promise<number>;
257
+
258
+ // Operations
259
+ normalize(v: Float32Array): Promise<Float32Array>;
260
+ add(a: Float32Array, b: Float32Array): Promise<Float32Array>;
261
+ subtract(a: Float32Array, b: Float32Array): Promise<Float32Array>;
262
+ multiply(v: Float32Array, scalar: number): Promise<Float32Array>;
263
+
264
+ // Transformations
265
+ quantize(v: Float32Array, bits: 4 | 8 | 16): Promise<Uint8Array>;
266
+ dequantize(data: Uint8Array, bits: 4 | 8 | 16): Promise<Float32Array>;
267
+ }
268
+
269
+ type DistanceMetric = 'euclidean' | 'cosine' | 'manhattan' | 'inner_product';
270
+ ```
271
+
272
+ #### 4.2.2 Graph-Aware Functions (12+)
273
+
274
+ | Function | Description | SQL Signature |
275
+ |----------|-------------|---------------|
276
+ | `rv_graph_neighbors` | K-nearest neighbors | `rv_graph_neighbors(id, k) -> setof record` |
277
+ | `rv_graph_similarity` | Graph-based similarity | `rv_graph_similarity(id1, id2) -> float` |
278
+ | `rv_graph_cluster` | Graph clustering | `rv_graph_cluster(table, k) -> setof record` |
279
+ | `rv_graph_pagerank` | PageRank scores | `rv_graph_pagerank(table) -> setof record` |
280
+ | `rv_graph_connected` | Connected components | `rv_graph_connected(table) -> setof record` |
281
+ | `rv_graph_shortest_path` | Shortest path | `rv_graph_shortest_path(table, id1, id2) -> path` |
282
+ | `rv_graph_community` | Community detection | `rv_graph_community(table) -> setof record` |
283
+ | `rv_graph_centrality` | Node centrality | `rv_graph_centrality(table, metric) -> setof record` |
284
+ | `rv_graph_embedding` | Graph embedding | `rv_graph_embedding(table) -> setof vector` |
285
+ | `rv_graph_walk` | Random walk | `rv_graph_walk(table, start, steps) -> path` |
286
+ | `rv_graph_subgraph` | Subgraph extraction | `rv_graph_subgraph(table, nodes) -> table` |
287
+ | `rv_graph_metrics` | Graph statistics | `rv_graph_metrics(table) -> record` |
288
+
289
+ #### 4.2.3 Pattern Matching Functions (10+)
290
+
291
+ | Function | Description | SQL Signature |
292
+ |----------|-------------|---------------|
293
+ | `rv_pattern_search` | Pattern similarity search | `rv_pattern_search(vector, table, k) -> setof record` |
294
+ | `rv_pattern_match` | Exact pattern match | `rv_pattern_match(pattern, table) -> setof record` |
295
+ | `rv_pattern_cluster` | Pattern clustering | `rv_pattern_cluster(table, k) -> setof record` |
296
+ | `rv_pattern_detect` | Anomaly detection | `rv_pattern_detect(table, threshold) -> setof record` |
297
+ | `rv_pattern_frequent` | Frequent patterns | `rv_pattern_frequent(table, min_support) -> setof record` |
298
+ | `rv_pattern_sequence` | Sequence pattern mining | `rv_pattern_sequence(table, max_gap) -> setof record` |
299
+ | `rv_pattern_associate` | Association rules | `rv_pattern_associate(table, confidence) -> setof record` |
300
+ | `rv_pattern_timeseries` | Time series patterns | `rv_pattern_timeseries(table, window) -> setof record` |
301
+ | `rv_pattern_similarity_join` | Similarity join | `rv_pattern_similarity_join(t1, t2, threshold) -> setof record` |
302
+ | `rv_pattern_deduplicate` | Near-duplicate detection | `rv_pattern_deduplicate(table, threshold) -> setof record` |
303
+
304
+ #### 4.2.4 Index Management Functions (8+)
305
+
306
+ | Function | Description | SQL Signature |
307
+ |----------|-------------|---------------|
308
+ | `rv_index_create` | Create HNSW index | `rv_index_create(table, column, config) -> void` |
309
+ | `rv_index_drop` | Drop index | `rv_index_drop(index_name) -> void` |
310
+ | `rv_index_rebuild` | Rebuild index | `rv_index_rebuild(index_name) -> void` |
311
+ | `rv_index_stats` | Index statistics | `rv_index_stats(index_name) -> record` |
312
+ | `rv_index_tune` | Auto-tune parameters | `rv_index_tune(index_name) -> record` |
313
+ | `rv_index_validate` | Validate index integrity | `rv_index_validate(index_name) -> boolean` |
314
+ | `rv_index_compact` | Compact index | `rv_index_compact(index_name) -> void` |
315
+ | `rv_index_analyze` | Analyze query performance | `rv_index_analyze(query) -> record` |
316
+
317
+ ### 4.3 Attention Mechanisms Module (39 Total)
318
+
319
+ #### 4.3.1 Multi-Head Attention (8 variants)
320
+
321
+ ```typescript
322
+ interface MultiHeadAttention {
323
+ // Standard implementations
324
+ standard(query: Tensor, key: Tensor, value: Tensor, config: MHAConfig): Promise<Tensor>;
325
+ scaled(query: Tensor, key: Tensor, value: Tensor, config: MHAConfig): Promise<Tensor>;
326
+
327
+ // Optimized variants
328
+ flashAttention(query: Tensor, key: Tensor, value: Tensor, config: FlashConfig): Promise<Tensor>;
329
+ memoryEfficient(query: Tensor, key: Tensor, value: Tensor, config: MEConfig): Promise<Tensor>;
330
+
331
+ // Specialized variants
332
+ rotary(query: Tensor, key: Tensor, value: Tensor, config: RoPEConfig): Promise<Tensor>;
333
+ alibi(query: Tensor, key: Tensor, value: Tensor, config: ALiBiConfig): Promise<Tensor>;
334
+ grouped(query: Tensor, key: Tensor, value: Tensor, config: GQAConfig): Promise<Tensor>;
335
+ multiQuery(query: Tensor, key: Tensor, value: Tensor, config: MQAConfig): Promise<Tensor>;
336
+ }
337
+
338
+ interface MHAConfig {
339
+ numHeads: number;
340
+ headDim: number;
341
+ dropout?: number;
342
+ causal?: boolean;
343
+ maxSeqLen?: number;
344
+ }
345
+ ```
346
+
347
+ | Variant | Description | Use Case |
348
+ |---------|-------------|----------|
349
+ | `mha_standard` | Standard multi-head attention | General purpose |
350
+ | `mha_scaled` | Scaled dot-product attention | Transformer default |
351
+ | `mha_flash` | Flash Attention v2 | Long sequences (2.49x-7.47x speedup) |
352
+ | `mha_memory_efficient` | Memory-efficient attention | Large batch sizes |
353
+ | `mha_rotary` | Rotary position embeddings (RoPE) | Position-aware attention |
354
+ | `mha_alibi` | Attention with Linear Biases | Extrapolation to longer sequences |
355
+ | `mha_grouped` | Grouped-Query Attention (GQA) | Reduced KV cache |
356
+ | `mha_multi_query` | Multi-Query Attention (MQA) | Single KV head |
357
+
358
+ #### 4.3.2 Self-Attention (6 variants)
359
+
360
+ | Variant | Description | Complexity |
361
+ |---------|-------------|------------|
362
+ | `self_standard` | Standard self-attention | O(n^2) |
363
+ | `self_causal` | Causal (autoregressive) | O(n^2) |
364
+ | `self_bidirectional` | Bidirectional | O(n^2) |
365
+ | `self_local` | Local window attention | O(n * w) |
366
+ | `self_sliding` | Sliding window | O(n * w) |
367
+ | `self_dilated` | Dilated attention | O(n * w) |
368
+
369
+ #### 4.3.3 Cross-Attention (5 variants)
370
+
371
+ | Variant | Description | Use Case |
372
+ |---------|-------------|----------|
373
+ | `cross_standard` | Standard cross-attention | Encoder-decoder |
374
+ | `cross_memory` | Memory-augmented | External memory |
375
+ | `cross_perceiver` | Perceiver-style | Variable-length inputs |
376
+ | `cross_latent` | Latent cross-attention | Latent space mapping |
377
+ | `cross_adaptive` | Adaptive cross-attention | Dynamic routing |
378
+
379
+ #### 4.3.4 Sparse Attention (10 variants)
380
+
381
+ | Variant | Description | Pattern |
382
+ |---------|-------------|---------|
383
+ | `sparse_strided` | Strided attention | Fixed stride |
384
+ | `sparse_fixed` | Fixed pattern | Predefined mask |
385
+ | `sparse_random` | Random attention | Sampled positions |
386
+ | `sparse_local_global` | Local + global tokens | Longformer-style |
387
+ | `sparse_bigbird` | BigBird pattern | Random + local + global |
388
+ | `sparse_longformer` | Longformer pattern | Sliding + global |
389
+ | `sparse_axial` | Axial attention | Row/column decomposition |
390
+ | `sparse_star` | Star transformer | Global token hub |
391
+ | `sparse_cluster` | Cluster attention | Learned clusters |
392
+ | `sparse_routing` | Routing attention | Top-k selection |
393
+
394
+ #### 4.3.5 Linear Attention (5 variants)
395
+
396
+ | Variant | Description | Complexity |
397
+ |---------|-------------|------------|
398
+ | `linear_standard` | Linear attention | O(n) |
399
+ | `linear_performer` | Performer (FAVOR+) | O(n) |
400
+ | `linear_rfa` | Random Feature Attention | O(n) |
401
+ | `linear_cosformer` | Cosine-reweighted | O(n) |
402
+ | `linear_nystrom` | Nystrom approximation | O(n * m) |
403
+
404
+ ### 4.4 GNN Layers Module
405
+
406
+ #### 4.4.1 Graph Convolution Layers
407
+
408
+ ```typescript
409
+ interface GraphConvolutionLayers {
410
+ // Standard layers
411
+ gcn(features: Tensor, adjacency: SparseTensor, weights: Tensor): Promise<Tensor>;
412
+ graphSAGE(features: Tensor, adjacency: SparseTensor, config: SAGEConfig): Promise<Tensor>;
413
+ gat(features: Tensor, adjacency: SparseTensor, config: GATConfig): Promise<Tensor>;
414
+ gin(features: Tensor, adjacency: SparseTensor, config: GINConfig): Promise<Tensor>;
415
+
416
+ // Advanced layers
417
+ edgeConv(features: Tensor, edges: Tensor, config: EdgeConvConfig): Promise<Tensor>;
418
+ gatv2(features: Tensor, adjacency: SparseTensor, config: GATv2Config): Promise<Tensor>;
419
+ pna(features: Tensor, adjacency: SparseTensor, config: PNAConfig): Promise<Tensor>;
420
+ }
421
+ ```
422
+
423
+ | Layer | Description | Reference |
424
+ |-------|-------------|-----------|
425
+ | `GCN` | Graph Convolutional Network | Kipf & Welling (2016) |
426
+ | `GraphSAGE` | Sample and Aggregate | Hamilton et al. (2017) |
427
+ | `GAT` | Graph Attention Network | Velickovic et al. (2018) |
428
+ | `GATv2` | Improved GAT | Brody et al. (2021) |
429
+ | `GIN` | Graph Isomorphism Network | Xu et al. (2019) |
430
+ | `EdgeConv` | Edge Convolution | Wang et al. (2019) |
431
+ | `PNA` | Principal Neighbourhood Aggregation | Corso et al. (2020) |
432
+
433
+ #### 4.4.2 Message Passing Networks
434
+
435
+ ```typescript
436
+ interface MessagePassingNetwork {
437
+ // Core operations
438
+ propagate(
439
+ nodeFeatures: Tensor,
440
+ edgeIndex: Tensor,
441
+ edgeFeatures?: Tensor
442
+ ): Promise<Tensor>;
443
+
444
+ // Message functions
445
+ message(source: Tensor, target: Tensor, edge?: Tensor): Promise<Tensor>;
446
+ aggregate(messages: Tensor, index: Tensor, method: AggregateMethod): Promise<Tensor>;
447
+ update(nodeFeatures: Tensor, aggregated: Tensor): Promise<Tensor>;
448
+ }
449
+
450
+ type AggregateMethod = 'sum' | 'mean' | 'max' | 'min' | 'attention' | 'lstm';
451
+ ```
452
+
453
+ #### 4.4.3 Node/Edge Embeddings
454
+
455
+ ```typescript
456
+ interface EmbeddingGenerator {
457
+ // Node embeddings
458
+ node2vec(adjacency: SparseTensor, config: Node2VecConfig): Promise<Tensor>;
459
+ deepwalk(adjacency: SparseTensor, config: DeepWalkConfig): Promise<Tensor>;
460
+ struc2vec(adjacency: SparseTensor, config: Struc2VecConfig): Promise<Tensor>;
461
+
462
+ // Edge embeddings
463
+ edgeEmbedding(nodeEmbeddings: Tensor, edgeIndex: Tensor, method: EdgeMethod): Promise<Tensor>;
464
+
465
+ // Subgraph embeddings
466
+ subgraphEmbedding(nodeEmbeddings: Tensor, subgraphNodes: number[]): Promise<Float32Array>;
467
+ }
468
+
469
+ type EdgeMethod = 'hadamard' | 'average' | 'l1' | 'l2' | 'concat';
470
+ ```
471
+
472
+ ### 4.5 Hyperbolic Embeddings Module
473
+
474
+ #### 4.5.1 Poincare Ball Model
475
+
476
+ ```typescript
477
+ interface PoincareBallOperations {
478
+ // Core operations (curvature c = -1 default)
479
+ expMap(v: Float32Array, base?: Float32Array): Promise<Float32Array>;
480
+ logMap(point: Float32Array, base?: Float32Array): Promise<Float32Array>;
481
+
482
+ // Distance
483
+ distance(a: Float32Array, b: Float32Array): Promise<number>;
484
+
485
+ // Mobius operations
486
+ mobiusAdd(a: Float32Array, b: Float32Array): Promise<Float32Array>;
487
+ mobiusScalarMul(r: number, v: Float32Array): Promise<Float32Array>;
488
+ mobiusMatVecMul(M: Float32Array[], v: Float32Array): Promise<Float32Array>;
489
+
490
+ // Transformations
491
+ euclideanToPoincare(v: Float32Array): Promise<Float32Array>;
492
+ poincareToEuclidean(v: Float32Array): Promise<Float32Array>;
493
+
494
+ // Aggregation
495
+ centroid(points: Float32Array[], weights?: number[]): Promise<Float32Array>;
496
+ midpoint(a: Float32Array, b: Float32Array): Promise<Float32Array>;
497
+
498
+ // Utilities
499
+ norm(v: Float32Array): Promise<number>;
500
+ project(v: Float32Array): Promise<Float32Array>;
501
+ isInBall(v: Float32Array): Promise<boolean>;
502
+ }
503
+ ```
504
+
505
+ #### 4.5.2 Lorentz (Hyperboloid) Model
506
+
507
+ ```typescript
508
+ interface LorentzModelOperations {
509
+ // Core operations
510
+ expMap(v: Float32Array, base?: Float32Array): Promise<Float32Array>;
511
+ logMap(point: Float32Array, base?: Float32Array): Promise<Float32Array>;
512
+
513
+ // Distance (Minkowski inner product based)
514
+ distance(a: Float32Array, b: Float32Array): Promise<number>;
515
+ minkowskiInnerProduct(a: Float32Array, b: Float32Array): Promise<number>;
516
+
517
+ // Transformations
518
+ lorentzToPoincare(v: Float32Array): Promise<Float32Array>;
519
+ poincareToLorentz(v: Float32Array): Promise<Float32Array>;
520
+
521
+ // Lorentz operations
522
+ lorentzBoost(v: Float32Array, velocity: Float32Array): Promise<Float32Array>;
523
+ parallelTransport(v: Float32Array, from: Float32Array, to: Float32Array): Promise<Float32Array>;
524
+
525
+ // Utilities
526
+ lorentzNorm(v: Float32Array): Promise<number>;
527
+ projectToHyperboloid(v: Float32Array): Promise<Float32Array>;
528
+ }
529
+ ```
530
+
531
+ #### 4.5.3 Distance Calculations
532
+
533
+ | Function | Model | Formula |
534
+ |----------|-------|---------|
535
+ | `poincare_distance` | Poincare | d(x,y) = arcosh(1 + 2||x-y||^2 / ((1-||x||^2)(1-||y||^2))) |
536
+ | `lorentz_distance` | Lorentz | d(x,y) = arcosh(-<x,y>_L) |
537
+ | `klein_distance` | Klein | d(x,y) = arcosh(1 - 2<x,y> / ((1-||x||^2)(1-||y||^2)))^(1/2) |
538
+ | `halfplane_distance` | Upper half-plane | d(x,y) = 2 * arcsinh(||x-y|| / (2*sqrt(x_n * y_n))) |
539
+
540
+ ### 4.6 Self-Learning Module
541
+
542
+ #### 4.6.1 Query Optimizer
543
+
544
+ ```typescript
545
+ interface QueryOptimizer {
546
+ // Query analysis
547
+ analyzeQuery(sql: string): Promise<QueryAnalysis>;
548
+ suggestOptimizations(sql: string): Promise<Optimization[]>;
549
+
550
+ // Learning
551
+ recordExecution(query: string, plan: QueryPlan, duration: number): Promise<void>;
552
+ learnFromHistory(): Promise<LearningReport>;
553
+
554
+ // Optimization application
555
+ rewrite(sql: string): Promise<string>;
556
+ selectIndex(query: string, available: Index[]): Promise<Index | null>;
557
+ }
558
+
559
+ interface QueryAnalysis {
560
+ complexity: 'low' | 'medium' | 'high';
561
+ estimatedCost: number;
562
+ bottlenecks: Bottleneck[];
563
+ recommendations: string[];
564
+ vectorOperations: VectorOperation[];
565
+ }
566
+
567
+ interface Optimization {
568
+ type: 'index' | 'rewrite' | 'parallel' | 'cache';
569
+ description: string;
570
+ expectedSpeedup: number;
571
+ sql?: string;
572
+ }
573
+ ```
574
+
575
+ #### 4.6.2 Index Tuner
576
+
577
+ ```typescript
578
+ interface IndexTuner {
579
+ // Analysis
580
+ analyzeWorkload(queries: QueryLog[]): Promise<WorkloadAnalysis>;
581
+ recommendIndexes(analysis: WorkloadAnalysis): Promise<IndexRecommendation[]>;
582
+
583
+ // HNSW tuning
584
+ tuneHNSW(indexName: string): Promise<HNSWParams>;
585
+ estimateHNSWParams(dataSize: number, dimensions: number, queryPattern: QueryPattern): HNSWParams;
586
+
587
+ // IVF tuning
588
+ tuneIVF(indexName: string): Promise<IVFParams>;
589
+ estimateIVFParams(dataSize: number, dimensions: number): IVFParams;
590
+
591
+ // Monitoring
592
+ monitorPerformance(indexName: string): Promise<PerformanceMetrics>;
593
+ }
594
+
595
+ interface HNSWParams {
596
+ m: number; // Max connections per layer (default: 16)
597
+ efConstruction: number; // Construction search depth (default: 200)
598
+ efSearch: number; // Query search depth (default: 100)
599
+ ml: number; // Level multiplier (default: 1/ln(M))
600
+ }
601
+ ```
602
+
603
+ #### 4.6.3 Pattern Recognizer
604
+
605
+ ```typescript
606
+ interface PatternRecognizer {
607
+ // Query pattern detection
608
+ detectQueryPatterns(queries: Query[]): Promise<QueryPattern[]>;
609
+ classifyQuery(sql: string): Promise<QueryClassification>;
610
+
611
+ // Data pattern detection
612
+ detectDataPatterns(vectors: Float32Array[]): Promise<DataPattern[]>;
613
+ detectAnomalies(vectors: Float32Array[], threshold: number): Promise<Anomaly[]>;
614
+
615
+ // Learning
616
+ trainOnPatterns(patterns: Pattern[]): Promise<void>;
617
+ predictPattern(query: string): Promise<PatternPrediction>;
618
+ }
619
+
620
+ interface QueryPattern {
621
+ id: string;
622
+ template: string;
623
+ frequency: number;
624
+ avgDuration: number;
625
+ vectorOperations: string[];
626
+ }
627
+ ```
628
+
629
+ ---
630
+
631
+ ## 5. Data Flow Diagrams
632
+
633
+ ### 5.1 Vector Similarity Search Flow
634
+
635
+ ```
636
+ +-------------+ +-----------------+ +------------------+
637
+ | Client | | RuVector | | PostgreSQL |
638
+ | Request | --> | Bridge Plugin | --> | + RuVector |
639
+ +-------------+ +-----------------+ +------------------+
640
+ | | |
641
+ | 1. MCP Tool Call | |
642
+ | (vector_search) | |
643
+ | | |
644
+ | 2. Validate input |
645
+ | 3. Get connection |
646
+ | | |
647
+ | | 4. Execute query |
648
+ | | SELECT * FROM items |
649
+ | | ORDER BY embedding |
650
+ | | <=> $1 LIMIT $2 |
651
+ | |----------------------->|
652
+ | | |
653
+ | | 5. HNSW index scan |
654
+ | |<-----------------------|
655
+ | | |
656
+ | 6. Transform results |
657
+ | 7. Update metrics |
658
+ |<-------------------| |
659
+ | 8. MCP Response | |
660
+ ```
661
+
662
+ ### 5.2 Attention Mechanism Flow
663
+
664
+ ```
665
+ +-------------+ +-----------------+ +------------------+
666
+ | Input | | Attention | | PostgreSQL |
667
+ | Tensors | --> | Module | --> | UDF Execution |
668
+ +-------------+ +-----------------+ +------------------+
669
+ | | |
670
+ | Q, K, V tensors | |
671
+ | | |
672
+ | 1. Select variant |
673
+ | 2. Prepare parameters |
674
+ | | |
675
+ | | 3. Execute UDF |
676
+ | | rv_attention_mha( |
677
+ | | $Q, $K, $V, $config |
678
+ | | ) |
679
+ | |----------------------->|
680
+ | | |
681
+ | | 4. SIMD computation |
682
+ | | (in-database) |
683
+ | |<-----------------------|
684
+ | | |
685
+ | 5. Return attention output |
686
+ |<-------------------| |
687
+ ```
688
+
689
+ ### 5.3 Self-Learning Flow
690
+
691
+ ```
692
+ +-------------+ +-----------------+ +------------------+
693
+ | Query | | Learning | | Statistics |
694
+ | Execution | --> | Module | --> | Storage |
695
+ +-------------+ +-----------------+ +------------------+
696
+ | | |
697
+ | Query + Results | |
698
+ | | |
699
+ | 1. Record execution |
700
+ | 2. Extract features |
701
+ | | |
702
+ | | 3. Store statistics |
703
+ | |----------------------->|
704
+ | | |
705
+ | 4. Analyze patterns |
706
+ | 5. Update models |
707
+ | | |
708
+ | 6. Generate recommendations |
709
+ |<-------------------| |
710
+ ```
711
+
712
+ ---
713
+
714
+ ## 6. Interface Definitions
715
+
716
+ ### 6.1 Plugin Interface
717
+
718
+ ```typescript
719
+ import { BasePlugin } from '@claude-flow/plugins';
720
+
721
+ export class RuVectorPostgreSQLBridgePlugin extends BasePlugin {
722
+ // Metadata
723
+ static readonly PLUGIN_NAME = 'ruvector-postgresql-bridge';
724
+ static readonly VERSION = '1.0.0';
725
+
726
+ // Components
727
+ private connectionManager: ConnectionManager;
728
+ private queryExecutor: QueryExecutor;
729
+ private sqlFunctions: SQLFunctionRegistry;
730
+ private attentionMechanisms: AttentionRegistry;
731
+ private gnnLayers: GNNRegistry;
732
+ private hyperbolicOps: HyperbolicRegistry;
733
+ private learningEngine: LearningEngine;
734
+
735
+ // Plugin lifecycle
736
+ protected async onInitialize(): Promise<void>;
737
+ protected async onShutdown(): Promise<void>;
738
+ protected async onHealthCheck(): Promise<Record<string, HealthStatus>>;
739
+
740
+ // Extension registration
741
+ registerMCPTools(): MCPToolDefinition[];
742
+ registerHooks(): HookDefinition[];
743
+ registerAgentTypes(): AgentTypeDefinition[];
744
+ }
745
+ ```
746
+
747
+ ### 6.2 MCP Tool Definitions
748
+
749
+ ```typescript
750
+ // Vector Operations Tools
751
+ interface VectorTools {
752
+ 'ruvector:search': {
753
+ input: {
754
+ query: number[]; // Query vector
755
+ table: string; // Table name
756
+ column: string; // Vector column
757
+ k: number; // Number of results
758
+ metric?: string; // Distance metric
759
+ filter?: string; // SQL WHERE clause
760
+ };
761
+ output: {
762
+ results: Array<{
763
+ id: string;
764
+ score: number;
765
+ metadata: Record<string, unknown>;
766
+ }>;
767
+ duration: number;
768
+ };
769
+ };
770
+
771
+ 'ruvector:index:create': {
772
+ input: {
773
+ table: string;
774
+ column: string;
775
+ type: 'hnsw' | 'ivf' | 'flat';
776
+ params?: {
777
+ m?: number;
778
+ efConstruction?: number;
779
+ lists?: number;
780
+ };
781
+ };
782
+ output: {
783
+ indexName: string;
784
+ created: boolean;
785
+ };
786
+ };
787
+
788
+ // ... 50+ more tools
789
+ }
790
+
791
+ // Attention Tools
792
+ interface AttentionTools {
793
+ 'ruvector:attention:mha': {
794
+ input: {
795
+ query: number[][];
796
+ key: number[][];
797
+ value: number[][];
798
+ config: {
799
+ numHeads: number;
800
+ dropout?: number;
801
+ causal?: boolean;
802
+ };
803
+ };
804
+ output: {
805
+ attention: number[][];
806
+ weights?: number[][][];
807
+ };
808
+ };
809
+
810
+ // ... more attention tools
811
+ }
812
+
813
+ // GNN Tools
814
+ interface GNNTools {
815
+ 'ruvector:gnn:propagate': {
816
+ input: {
817
+ features: number[][];
818
+ edgeIndex: number[][];
819
+ layer: 'gcn' | 'gat' | 'sage' | 'gin';
820
+ config: Record<string, unknown>;
821
+ };
822
+ output: {
823
+ features: number[][];
824
+ };
825
+ };
826
+
827
+ // ... more GNN tools
828
+ }
829
+ ```
830
+
831
+ ### 6.3 Configuration Schema
832
+
833
+ ```typescript
834
+ interface RuVectorBridgeConfig {
835
+ // Connection settings
836
+ connection: {
837
+ host: string;
838
+ port: number;
839
+ database: string;
840
+ user: string;
841
+ password: string;
842
+ ssl?: {
843
+ enabled: boolean;
844
+ ca?: string;
845
+ key?: string;
846
+ cert?: string;
847
+ };
848
+ };
849
+
850
+ // Pool settings
851
+ pool: {
852
+ min: number;
853
+ max: number;
854
+ idleTimeout: number;
855
+ acquireTimeout: number;
856
+ maxWaitingClients: number;
857
+ };
858
+
859
+ // Feature flags
860
+ features: {
861
+ vectorOperations: boolean;
862
+ attentionMechanisms: boolean;
863
+ gnnLayers: boolean;
864
+ hyperbolicEmbeddings: boolean;
865
+ selfLearning: boolean;
866
+ };
867
+
868
+ // Learning settings
869
+ learning: {
870
+ enabled: boolean;
871
+ queryHistorySize: number;
872
+ patternUpdateInterval: number;
873
+ indexTuningEnabled: boolean;
874
+ };
875
+
876
+ // Performance settings
877
+ performance: {
878
+ queryTimeout: number;
879
+ cacheEnabled: boolean;
880
+ cacheTTL: number;
881
+ maxBatchSize: number;
882
+ };
883
+ }
884
+ ```
885
+
886
+ ---
887
+
888
+ ## 7. Extension Points
889
+
890
+ ### 7.1 Custom SQL Functions
891
+
892
+ ```typescript
893
+ interface SQLFunctionExtension {
894
+ // Register custom function
895
+ registerFunction(definition: CustomFunctionDefinition): void;
896
+
897
+ // Function definition
898
+ interface CustomFunctionDefinition {
899
+ name: string;
900
+ args: ArgDefinition[];
901
+ returns: ReturnType;
902
+ implementation: string; // SQL or PL/pgSQL
903
+ volatile?: boolean;
904
+ parallel?: 'safe' | 'restricted' | 'unsafe';
905
+ }
906
+ }
907
+ ```
908
+
909
+ ### 7.2 Custom Attention Mechanisms
910
+
911
+ ```typescript
912
+ interface AttentionExtension {
913
+ // Register custom attention
914
+ registerAttention(definition: CustomAttentionDefinition): void;
915
+
916
+ interface CustomAttentionDefinition {
917
+ name: string;
918
+ compute: (query: Tensor, key: Tensor, value: Tensor, config: unknown) => Promise<Tensor>;
919
+ validateConfig: (config: unknown) => boolean;
920
+ estimateComplexity: (seqLen: number, dim: number) => ComplexityEstimate;
921
+ }
922
+ }
923
+ ```
924
+
925
+ ### 7.3 Custom GNN Layers
926
+
927
+ ```typescript
928
+ interface GNNExtension {
929
+ // Register custom layer
930
+ registerLayer(definition: CustomLayerDefinition): void;
931
+
932
+ interface CustomLayerDefinition {
933
+ name: string;
934
+ message: (source: Tensor, target: Tensor, edge?: Tensor) => Tensor;
935
+ aggregate: (messages: Tensor, index: Tensor) => Tensor;
936
+ update: (node: Tensor, aggregated: Tensor) => Tensor;
937
+ }
938
+ }
939
+ ```
940
+
941
+ ### 7.4 Custom Learning Strategies
942
+
943
+ ```typescript
944
+ interface LearningExtension {
945
+ // Register custom optimizer
946
+ registerOptimizer(definition: CustomOptimizerDefinition): void;
947
+
948
+ // Register custom tuner
949
+ registerTuner(definition: CustomTunerDefinition): void;
950
+
951
+ // Register custom pattern detector
952
+ registerPatternDetector(definition: CustomPatternDetectorDefinition): void;
953
+ }
954
+ ```
955
+
956
+ ---
957
+
958
+ ## 8. Performance Considerations
959
+
960
+ ### 8.1 Connection Pooling
961
+
962
+ | Configuration | Small Workload | Medium Workload | High Workload |
963
+ |---------------|----------------|-----------------|---------------|
964
+ | min connections | 2 | 5 | 10 |
965
+ | max connections | 10 | 25 | 50 |
966
+ | idle timeout | 60s | 30s | 15s |
967
+ | acquire timeout | 10s | 5s | 3s |
968
+
969
+ ### 8.2 Index Selection Guide
970
+
971
+ | Data Size | Dimensions | Query Pattern | Recommended Index |
972
+ |-----------|------------|---------------|-------------------|
973
+ | < 10K | Any | Any | Flat (exact) |
974
+ | 10K - 1M | < 256 | High recall | HNSW (m=16, ef=100) |
975
+ | 10K - 1M | >= 256 | Balanced | HNSW (m=32, ef=200) |
976
+ | > 1M | < 256 | High throughput | IVF (lists=sqrt(n)) |
977
+ | > 1M | >= 256 | Balanced | IVF-HNSW hybrid |
978
+
979
+ ### 8.3 Attention Mechanism Selection
980
+
981
+ | Sequence Length | Memory Constraint | Recommended |
982
+ |-----------------|-------------------|-------------|
983
+ | < 512 | None | Standard MHA |
984
+ | 512 - 2K | Moderate | Flash Attention |
985
+ | 2K - 8K | Strict | Sparse (Longformer) |
986
+ | > 8K | Strict | Linear (Performer) |
987
+
988
+ ### 8.4 Memory Optimization
989
+
990
+ ```typescript
991
+ // Quantization levels and memory savings
992
+ const QUANTIZATION_SAVINGS = {
993
+ 'float32': { bits: 32, ratio: 1.0 },
994
+ 'float16': { bits: 16, ratio: 0.5 },
995
+ 'int8': { bits: 8, ratio: 0.25 },
996
+ 'int4': { bits: 4, ratio: 0.125 },
997
+ };
998
+
999
+ // Recommended quantization by use case
1000
+ const QUANTIZATION_RECOMMENDATIONS = {
1001
+ 'similarity_search': 'int8', // 4x memory reduction, <2% recall loss
1002
+ 'clustering': 'float16', // 2x memory reduction, minimal loss
1003
+ 'exact_match': 'float32', // No quantization
1004
+ 'approximate_nn': 'int4', // 8x memory reduction, ~5% recall loss
1005
+ };
1006
+ ```
1007
+
1008
+ ---
1009
+
1010
+ ## 9. Security Considerations
1011
+
1012
+ ### 9.1 Connection Security
1013
+
1014
+ - TLS/SSL required for production connections
1015
+ - Certificate validation enabled by default
1016
+ - Connection string credentials never logged
1017
+ - Secrets retrieved from environment or secret manager
1018
+
1019
+ ### 9.2 Query Security
1020
+
1021
+ - Parameterized queries only (no string interpolation)
1022
+ - Input validation via Zod schemas
1023
+ - SQL injection prevention via prepared statements
1024
+ - Query timeout enforcement
1025
+
1026
+ ### 9.3 Data Security
1027
+
1028
+ - Vector data encrypted at rest (PostgreSQL TDE)
1029
+ - Network encryption via TLS 1.3
1030
+ - Access control via PostgreSQL roles
1031
+ - Audit logging for sensitive operations
1032
+
1033
+ ---
1034
+
1035
+ ## 10. Deployment Architecture
1036
+
1037
+ ### 10.1 Single Node Deployment
1038
+
1039
+ ```
1040
+ +------------------------------------------+
1041
+ | Application Server |
1042
+ | +------------------------------------+ |
1043
+ | | Claude-Flow MCP Server | |
1044
+ | | +------------------------------+ | |
1045
+ | | | RuVector Bridge Plugin | | |
1046
+ | | +------------------------------+ | |
1047
+ | +------------------------------------+ |
1048
+ +------------------------------------------+
1049
+ |
1050
+ | pg protocol
1051
+ v
1052
+ +------------------------------------------+
1053
+ | PostgreSQL + RuVector |
1054
+ | (Single Instance) |
1055
+ +------------------------------------------+
1056
+ ```
1057
+
1058
+ ### 10.2 High Availability Deployment
1059
+
1060
+ ```
1061
+ +------------------------------------------+
1062
+ | Load Balancer |
1063
+ +------------------------------------------+
1064
+ | | |
1065
+ v v v
1066
+ +------------+ +------------+ +------------+
1067
+ | MCP | | MCP | | MCP |
1068
+ | Server 1 | | Server 2 | | Server 3 |
1069
+ +------------+ +------------+ +------------+
1070
+ | | |
1071
+ +-------+------+-------+------+
1072
+ | |
1073
+ v v
1074
+ +------------+ +------------+
1075
+ | Primary | | Replica |
1076
+ | PostgreSQL| | PostgreSQL|
1077
+ | + RuVector| | + RuVector|
1078
+ +------------+ +------------+
1079
+ ```
1080
+
1081
+ ### 10.3 Distributed Deployment
1082
+
1083
+ ```
1084
+ +------------------------------------------+
1085
+ | Global Load Balancer |
1086
+ +------------------------------------------+
1087
+ | |
1088
+ v v
1089
+ +------------------+ +------------------+
1090
+ | Region A | | Region B |
1091
+ | +-------------+ | | +-------------+ |
1092
+ | | MCP Pool | | | | MCP Pool | |
1093
+ | +-------------+ | | +-------------+ |
1094
+ | | | | | |
1095
+ | v | | v |
1096
+ | +-------------+ | | +-------------+ |
1097
+ | | PG Cluster | | | | PG Cluster | |
1098
+ | | (Citus) | | | | (Citus) | |
1099
+ | +-------------+ | | +-------------+ |
1100
+ +------------------+ +------------------+
1101
+ ```
1102
+
1103
+ ---
1104
+
1105
+ ## 11. Testing Strategy
1106
+
1107
+ ### 11.1 Unit Tests
1108
+
1109
+ - SQL function validation
1110
+ - Attention mechanism correctness
1111
+ - GNN layer outputs
1112
+ - Hyperbolic operations accuracy
1113
+ - Configuration validation
1114
+
1115
+ ### 11.2 Integration Tests
1116
+
1117
+ - Connection pooling behavior
1118
+ - Query execution correctness
1119
+ - MCP tool functionality
1120
+ - Learning engine feedback loop
1121
+ - Extension installation/upgrade
1122
+
1123
+ ### 11.3 Performance Tests
1124
+
1125
+ - Vector search latency (p50, p95, p99)
1126
+ - Attention throughput (tokens/second)
1127
+ - GNN propagation time
1128
+ - Index build/query tradeoffs
1129
+ - Connection pool saturation
1130
+
1131
+ ### 11.4 Chaos Tests
1132
+
1133
+ - Connection failure recovery
1134
+ - PostgreSQL restart handling
1135
+ - Extension upgrade during operation
1136
+ - Memory pressure scenarios
1137
+ - Network partition behavior
1138
+
1139
+ ---
1140
+
1141
+ ## 12. Monitoring and Observability
1142
+
1143
+ ### 12.1 Metrics
1144
+
1145
+ | Metric | Type | Description |
1146
+ |--------|------|-------------|
1147
+ | `ruvector_query_duration_seconds` | Histogram | Query execution time |
1148
+ | `ruvector_pool_connections_active` | Gauge | Active connections |
1149
+ | `ruvector_pool_connections_idle` | Gauge | Idle connections |
1150
+ | `ruvector_index_size_bytes` | Gauge | Index storage size |
1151
+ | `ruvector_attention_tokens_processed` | Counter | Tokens processed |
1152
+ | `ruvector_learning_patterns_detected` | Counter | Patterns detected |
1153
+
1154
+ ### 12.2 Logging
1155
+
1156
+ ```typescript
1157
+ // Structured log format
1158
+ interface LogEntry {
1159
+ timestamp: string;
1160
+ level: 'debug' | 'info' | 'warn' | 'error';
1161
+ module: string;
1162
+ message: string;
1163
+ context: {
1164
+ queryId?: string;
1165
+ duration?: number;
1166
+ rowCount?: number;
1167
+ error?: string;
1168
+ };
1169
+ }
1170
+ ```
1171
+
1172
+ ### 12.3 Tracing
1173
+
1174
+ - OpenTelemetry integration
1175
+ - Distributed trace context propagation
1176
+ - Span attributes for vector operations
1177
+ - Query plan visualization
1178
+
1179
+ ---
1180
+
1181
+ ## 13. Migration Guide
1182
+
1183
+ ### 13.1 From pgvector
1184
+
1185
+ ```sql
1186
+ -- Convert pgvector to ruvector
1187
+ ALTER TABLE items
1188
+ ALTER COLUMN embedding TYPE ruvector
1189
+ USING embedding::ruvector;
1190
+
1191
+ -- Rebuild indexes
1192
+ DROP INDEX IF EXISTS items_embedding_idx;
1193
+ CREATE INDEX items_embedding_idx ON items
1194
+ USING ruvector_hnsw (embedding ruvector_cosine_ops)
1195
+ WITH (m = 16, ef_construction = 200);
1196
+ ```
1197
+
1198
+ ### 13.2 From In-Memory VectorDB
1199
+
1200
+ ```typescript
1201
+ // Migrate from AgentDB to PostgreSQL
1202
+ async function migrate(agentDB: AgentDBBridge, pgBridge: RuVectorBridge) {
1203
+ const entries = await agentDB.listAll();
1204
+
1205
+ for (const entry of entries) {
1206
+ await pgBridge.insert({
1207
+ id: entry.id,
1208
+ vector: entry.vector,
1209
+ metadata: entry.metadata,
1210
+ });
1211
+ }
1212
+ }
1213
+ ```
1214
+
1215
+ ---
1216
+
1217
+ ## 14. Appendix
1218
+
1219
+ ### A. Complete SQL Function Reference
1220
+
1221
+ See `/docs/sql-functions-reference.md` for the complete 53+ function reference.
1222
+
1223
+ ### B. Attention Mechanism Benchmarks
1224
+
1225
+ See `/docs/attention-benchmarks.md` for performance comparisons.
1226
+
1227
+ ### C. GNN Layer Specifications
1228
+
1229
+ See `/docs/gnn-specifications.md` for detailed layer documentation.
1230
+
1231
+ ### D. Hyperbolic Geometry Mathematics
1232
+
1233
+ See `/docs/hyperbolic-math.md` for mathematical foundations.
1234
+
1235
+ ### E. Self-Learning Algorithm Details
1236
+
1237
+ See `/docs/learning-algorithms.md` for algorithm descriptions.
1238
+
1239
+ ---
1240
+
1241
+ ## 15. Revision History
1242
+
1243
+ | Version | Date | Author | Changes |
1244
+ |---------|------|--------|---------|
1245
+ | 1.0.0 | 2026-01-16 | Architecture Team | Initial architecture document |