@claude-flow/plugin-perf-optimizer 3.0.0-alpha.1

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.
package/README.md ADDED
@@ -0,0 +1,276 @@
1
+ # @claude-flow/plugin-performance-optimizer
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@claude-flow/plugin-performance-optimizer.svg)](https://www.npmjs.com/package/@claude-flow/plugin-performance-optimizer)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@claude-flow/plugin-performance-optimizer.svg)](https://www.npmjs.com/package/@claude-flow/plugin-performance-optimizer)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
+
7
+ A comprehensive performance optimization plugin combining sparse inference for efficient trace analysis with graph neural networks for dependency chain optimization. The plugin enables intelligent bottleneck detection, memory leak identification, N+1 query detection, and bundle size optimization while providing explainable recommendations based on historical performance patterns.
8
+
9
+ ## Features
10
+
11
+ - **Bottleneck Detection**: Identify performance bottlenecks using GNN-based dependency analysis
12
+ - **Memory Analysis**: Detect memory leaks, retention chains, and GC pressure points
13
+ - **Query Optimization**: Detect N+1 queries, missing indexes, and slow joins
14
+ - **Bundle Optimization**: Analyze and optimize JavaScript bundle size with tree shaking and code splitting
15
+ - **Configuration Optimization**: Learn optimal configurations from workload patterns using SONA
16
+
17
+ ## Installation
18
+
19
+ ### npm
20
+
21
+ ```bash
22
+ npm install @claude-flow/plugin-performance-optimizer
23
+ ```
24
+
25
+ ### CLI
26
+
27
+ ```bash
28
+ npx claude-flow plugins install --name @claude-flow/plugin-performance-optimizer
29
+ ```
30
+
31
+ ## Quick Start
32
+
33
+ ```typescript
34
+ import { PerfOptimizerPlugin } from '@claude-flow/plugin-performance-optimizer';
35
+
36
+ // Initialize the plugin
37
+ const plugin = new PerfOptimizerPlugin();
38
+ await plugin.initialize();
39
+
40
+ // Detect performance bottlenecks
41
+ const bottlenecks = await plugin.detectBottlenecks({
42
+ traceData: {
43
+ format: 'otlp',
44
+ spans: traceSpans,
45
+ metrics: performanceMetrics
46
+ },
47
+ analysisScope: ['cpu', 'memory', 'database'],
48
+ threshold: {
49
+ latencyP95: 500, // 500ms
50
+ throughput: 1000,
51
+ errorRate: 0.01
52
+ }
53
+ });
54
+
55
+ console.log('Detected bottlenecks:', bottlenecks);
56
+ ```
57
+
58
+ ## MCP Tools
59
+
60
+ ### 1. `perf/bottleneck-detect`
61
+
62
+ Detect performance bottlenecks using GNN-based dependency analysis.
63
+
64
+ ```typescript
65
+ // Example usage via MCP
66
+ const result = await mcp.call('perf/bottleneck-detect', {
67
+ traceData: {
68
+ format: 'chrome_devtools',
69
+ spans: chromeTraceSpans,
70
+ metrics: { renderTime: 150, scriptTime: 200 }
71
+ },
72
+ analysisScope: ['cpu', 'render', 'network'],
73
+ threshold: {
74
+ latencyP95: 100,
75
+ throughput: 60
76
+ }
77
+ });
78
+ ```
79
+
80
+ **Returns:** List of identified bottlenecks with severity, location, and recommended fixes.
81
+
82
+ ### 2. `perf/memory-analyze`
83
+
84
+ Analyze memory usage patterns and detect potential leaks.
85
+
86
+ ```typescript
87
+ const result = await mcp.call('perf/memory-analyze', {
88
+ heapSnapshot: '/path/to/heap-snapshot.heapsnapshot',
89
+ timeline: memoryTimelineData,
90
+ analysis: ['leak_detection', 'retention_analysis', 'gc_pressure'],
91
+ compareBaseline: '/path/to/baseline-snapshot.heapsnapshot'
92
+ });
93
+ ```
94
+
95
+ **Returns:** Memory analysis report with leak candidates, retention chains, and optimization suggestions.
96
+
97
+ ### 3. `perf/query-optimize`
98
+
99
+ Detect N+1 queries and suggest database optimizations.
100
+
101
+ ```typescript
102
+ const result = await mcp.call('perf/query-optimize', {
103
+ queries: [
104
+ { sql: 'SELECT * FROM users WHERE id = ?', duration: 5, resultSize: 1 },
105
+ { sql: 'SELECT * FROM orders WHERE user_id = ?', duration: 3, resultSize: 10 }
106
+ ],
107
+ patterns: ['n_plus_1', 'missing_index', 'slow_join'],
108
+ suggestIndexes: true
109
+ });
110
+ ```
111
+
112
+ **Returns:** Detected query anti-patterns with suggested batch alternatives and index recommendations.
113
+
114
+ ### 4. `perf/bundle-optimize`
115
+
116
+ Analyze and optimize JavaScript bundle size.
117
+
118
+ ```typescript
119
+ const result = await mcp.call('perf/bundle-optimize', {
120
+ bundleStats: '/path/to/webpack-stats.json',
121
+ analysis: ['tree_shaking', 'code_splitting', 'duplicate_deps', 'large_modules'],
122
+ targets: {
123
+ maxSize: 250, // 250KB
124
+ maxChunks: 10
125
+ }
126
+ });
127
+ ```
128
+
129
+ **Returns:** Bundle analysis with optimization recommendations for tree shaking, code splitting, and dependency deduplication.
130
+
131
+ ### 5. `perf/config-optimize`
132
+
133
+ Suggest optimal configurations based on workload patterns using SONA learning.
134
+
135
+ ```typescript
136
+ const result = await mcp.call('perf/config-optimize', {
137
+ workloadProfile: {
138
+ type: 'api',
139
+ metrics: { requestsPerSecond: 1000, avgLatency: 50 },
140
+ constraints: { maxMemory: '4GB', maxCpu: 4 }
141
+ },
142
+ configSpace: {
143
+ poolSize: { type: 'number', range: [10, 100], current: 25 },
144
+ cacheSize: { type: 'number', range: [100, 1000], current: 200 }
145
+ },
146
+ objective: 'latency'
147
+ });
148
+ ```
149
+
150
+ **Returns:** Optimized configuration values with expected performance improvements.
151
+
152
+ ## Configuration Options
153
+
154
+ ```typescript
155
+ interface PerfOptimizerConfig {
156
+ // WASM memory limit (default: 2GB)
157
+ memoryLimit: number;
158
+
159
+ // Analysis timeout in seconds (default: 300)
160
+ analysisTimeout: number;
161
+
162
+ // Enable SONA learning for configuration optimization
163
+ enableSONALearning: boolean;
164
+
165
+ // Supported trace formats
166
+ supportedFormats: ('otlp' | 'chrome_devtools' | 'jaeger' | 'zipkin')[];
167
+
168
+ // Performance thresholds for alerting
169
+ thresholds: {
170
+ latencyP95: number;
171
+ throughput: number;
172
+ errorRate: number;
173
+ };
174
+ }
175
+ ```
176
+
177
+ ## Performance Targets
178
+
179
+ | Metric | Target | Improvement vs Baseline |
180
+ |--------|--------|------------------------|
181
+ | Trace analysis (1M spans) | <5s | 24x faster |
182
+ | Memory analysis (1GB heap) | <30s | 10x faster |
183
+ | Query pattern detection (10K queries) | <1s | 600x faster |
184
+ | Bundle analysis (10MB) | <10s | 6x faster |
185
+ | Config optimization | <1min convergence | 1440x+ faster |
186
+
187
+ ## Security Considerations
188
+
189
+ - **Trace Data Sanitization**: Automatically sanitizes sensitive data (passwords, tokens, cookies) from trace data before processing
190
+ - **Query Parse-Only**: SQL queries are parsed and analyzed but never executed
191
+ - **WASM Sandboxing**: All analysis runs in isolated WASM sandbox with 2GB memory limit and no network access
192
+ - **Path Validation**: Bundle stats paths are validated to prevent path traversal attacks
193
+ - **Input Validation**: All inputs validated with Zod schemas to prevent injection attacks
194
+ - **No Code Execution**: Performance suggestions are recommendations only - no automatic code modification
195
+
196
+ ### WASM Security Constraints
197
+
198
+ | Constraint | Value | Rationale |
199
+ |------------|-------|-----------|
200
+ | Memory Limit | 2GB max | Handle large trace datasets |
201
+ | CPU Time Limit | 300 seconds | Allow deep performance analysis |
202
+ | No Network Access | Enforced | Prevent data exfiltration |
203
+ | No File System Write | Enforced | Read-only analysis mode |
204
+ | Sandboxed Paths | Validated prefixes only | Prevent path traversal |
205
+
206
+ ### Input Limits
207
+
208
+ | Input | Limit |
209
+ |-------|-------|
210
+ | Max spans per trace | 1,000,000 |
211
+ | Max query size | 10KB |
212
+ | Max queries per batch | 10,000 |
213
+ | Max heap snapshot size | 1GB |
214
+ | Max bundle stats size | 50MB |
215
+ | CPU time limit | 300 seconds |
216
+
217
+ ### Rate Limiting
218
+
219
+ ```typescript
220
+ const rateLimits = {
221
+ 'perf/bottleneck-detect': { requestsPerMinute: 10, maxConcurrent: 2 },
222
+ 'perf/memory-analyze': { requestsPerMinute: 5, maxConcurrent: 1 },
223
+ 'perf/query-optimize': { requestsPerMinute: 30, maxConcurrent: 3 },
224
+ 'perf/bundle-optimize': { requestsPerMinute: 10, maxConcurrent: 2 },
225
+ 'perf/config-optimize': { requestsPerMinute: 5, maxConcurrent: 1 }
226
+ };
227
+ ```
228
+
229
+ ## Dependencies
230
+
231
+ - `ruvector-sparse-inference-wasm` - Efficient sparse performance trace processing
232
+ - `ruvector-gnn-wasm` - Dependency chain analysis and critical path detection
233
+ - `micro-hnsw-wasm` - Similar performance pattern matching
234
+ - `ruvector-fpga-transformer-wasm` - Fast transformer inference for trace analysis
235
+ - `sona` - Learning optimal configurations from historical data
236
+
237
+ ## Supported Formats
238
+
239
+ | Category | Formats |
240
+ |----------|---------|
241
+ | Tracing | OpenTelemetry, Jaeger, Zipkin, Chrome DevTools |
242
+ | Profiling | Chrome CPU Profile, Node.js Profile, pprof |
243
+ | Memory | Chrome Heap Snapshot, Node.js Heap |
244
+ | Bundles | Webpack Stats, Vite Stats, Rollup |
245
+
246
+ ## Related Plugins
247
+
248
+ | Plugin | Description | Use Case |
249
+ |--------|-------------|----------|
250
+ | [@claude-flow/plugin-code-intelligence](../code-intelligence) | Code analysis | Identify code causing performance issues |
251
+ | [@claude-flow/plugin-test-intelligence](../test-intelligence) | Test optimization | Performance regression test selection |
252
+ | [@claude-flow/plugin-financial-risk](../financial-risk) | Risk analysis | Trading system latency optimization |
253
+
254
+ ## License
255
+
256
+ MIT License
257
+
258
+ Copyright (c) 2026 Claude Flow
259
+
260
+ Permission is hereby granted, free of charge, to any person obtaining a copy
261
+ of this software and associated documentation files (the "Software"), to deal
262
+ in the Software without restriction, including without limitation the rights
263
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
264
+ copies of the Software, and to permit persons to whom the Software is
265
+ furnished to do so, subject to the following conditions:
266
+
267
+ The above copyright notice and this permission notice shall be included in all
268
+ copies or substantial portions of the Software.
269
+
270
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
271
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
272
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
273
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
274
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
275
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
276
+ SOFTWARE.
@@ -0,0 +1,81 @@
1
+ /**
2
+ * FPGA Transformer Bridge for Performance Optimizer
3
+ *
4
+ * Provides fast configuration optimization using FPGA-accelerated
5
+ * transformer inference from ruvector-fpga-transformer-wasm.
6
+ */
7
+ import type { FpgaBridgeInterface, WorkloadProfile, ConfigOptimization } from '../types.js';
8
+ /**
9
+ * FPGA transformer configuration
10
+ */
11
+ interface FpgaConfig {
12
+ modelSize: 'small' | 'medium' | 'large';
13
+ searchIterations: number;
14
+ explorationRate: number;
15
+ bayesianOptimization: boolean;
16
+ }
17
+ /**
18
+ * FPGA Transformer Bridge Implementation
19
+ *
20
+ * Uses FPGA-accelerated transformers for:
21
+ * - Configuration space exploration
22
+ * - Performance prediction
23
+ * - Optimal configuration search
24
+ */
25
+ export declare class PerfFpgaBridge implements FpgaBridgeInterface {
26
+ readonly name = "perf-optimizer-fpga";
27
+ readonly version = "0.1.0";
28
+ private status;
29
+ private config;
30
+ private performanceModel;
31
+ private configHistory;
32
+ private baselinePerformance;
33
+ constructor(config?: Partial<FpgaConfig>);
34
+ init(): Promise<void>;
35
+ destroy(): Promise<void>;
36
+ isReady(): boolean;
37
+ /**
38
+ * Optimize configuration for workload
39
+ *
40
+ * Uses SONA-based learning to find optimal configuration parameters.
41
+ */
42
+ optimizeConfig(workload: WorkloadProfile, configSpace: Record<string, unknown>): Promise<ConfigOptimization>;
43
+ /**
44
+ * Predict performance for configuration
45
+ *
46
+ * Uses the learned performance model to estimate performance metrics.
47
+ */
48
+ predictPerformance(config: Record<string, unknown>, workload: WorkloadProfile): Promise<number>;
49
+ /**
50
+ * Search for optimal configuration
51
+ *
52
+ * Uses Bayesian optimization or grid search to find the best configuration.
53
+ */
54
+ searchOptimalConfig(objective: string, constraints: Record<string, number>): Promise<Record<string, unknown>>;
55
+ /**
56
+ * Learn from performance feedback
57
+ */
58
+ learnFromFeedback(config: Record<string, unknown>, actualPerformance: number): void;
59
+ private initializePerformanceModel;
60
+ private optimizeParameter;
61
+ private getOptimalRatio;
62
+ private suggestBooleanConfig;
63
+ private suggestEnumConfig;
64
+ private predictImprovement;
65
+ private getWorkloadBaseline;
66
+ private getParameterImpact;
67
+ private embedConfig;
68
+ private embeddingToKey;
69
+ private defineSearchSpace;
70
+ private bayesianSearch;
71
+ private gridSearch;
72
+ private getBestHistoricalValue;
73
+ private evaluateConfig;
74
+ private hashString;
75
+ }
76
+ /**
77
+ * Create a new FPGA bridge instance
78
+ */
79
+ export declare function createPerfFpgaBridge(config?: Partial<FpgaConfig>): PerfFpgaBridge;
80
+ export {};
81
+ //# sourceMappingURL=fpga-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fpga-bridge.d.ts","sourceRoot":"","sources":["../../src/bridges/fpga-bridge.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EACV,mBAAmB,EACnB,eAAe,EACf,kBAAkB,EAEnB,MAAM,aAAa,CAAC;AAOrB;;GAEG;AACH,UAAU,UAAU;IAClB,SAAS,EAAE,OAAO,GAAG,QAAQ,GAAG,OAAO,CAAC;IACxC,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IACxB,oBAAoB,EAAE,OAAO,CAAC;CAC/B;AAYD;;;;;;;GAOG;AACH,qBAAa,cAAe,YAAW,mBAAmB;IACxD,QAAQ,CAAC,IAAI,yBAAyB;IACtC,QAAQ,CAAC,OAAO,WAAW;IAE3B,OAAO,CAAC,MAAM,CAAgC;IAC9C,OAAO,CAAC,MAAM,CAAa;IAC3B,OAAO,CAAC,gBAAgB,C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