owflow 0.5.0 → 0.7.0

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 (195) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +448 -261
  3. package/dist/agents/bottleneck-analyzer.md +332 -329
  4. package/dist/agents/code-quality-pragmatist.md +353 -354
  5. package/dist/agents/code-reviewer.md +238 -239
  6. package/dist/agents/codebase-analysis-reporter.md +245 -246
  7. package/dist/agents/docs-operator.md +22 -23
  8. package/dist/agents/e2e-test-verifier.md +447 -448
  9. package/dist/agents/gap-analyzer.md +501 -502
  10. package/dist/agents/implementation-completeness-checker.md +219 -220
  11. package/dist/agents/implementation-planner.md +308 -309
  12. package/dist/agents/information-gatherer.md +690 -691
  13. package/dist/agents/production-readiness-checker.md +278 -279
  14. package/dist/agents/project-analyzer.md +403 -403
  15. package/dist/agents/reality-assessor.md +365 -366
  16. package/dist/agents/research-planner.md +449 -450
  17. package/dist/agents/research-synthesizer.md +402 -403
  18. package/dist/agents/solution-brainstormer.md +256 -257
  19. package/dist/agents/solution-designer.md +371 -372
  20. package/dist/agents/spec-auditor.md +297 -298
  21. package/dist/agents/specification-creator.md +333 -334
  22. package/dist/agents/task-classifier.md +449 -450
  23. package/dist/agents/task-group-implementer.md +283 -284
  24. package/dist/agents/test-suite-runner.md +194 -195
  25. package/dist/agents/user-docs-generator.md +508 -509
  26. package/dist/commands/reviews-code.md +90 -90
  27. package/dist/commands/reviews-pragmatic.md +99 -99
  28. package/dist/commands/reviews-production-readiness.md +113 -113
  29. package/dist/commands/reviews-reality-check.md +110 -110
  30. package/dist/commands/reviews-spec-audit.md +114 -114
  31. package/dist/commands/work.md +280 -280
  32. package/dist/configuration/agents-config.d.ts +2 -0
  33. package/dist/configuration/agents-config.js +8 -44
  34. package/dist/configuration/commands-config.d.ts +23 -0
  35. package/dist/configuration/commands-config.js +17 -17
  36. package/dist/configuration/skills-config.d.ts +2 -0
  37. package/dist/configuration/skills-config.js +3 -3
  38. package/dist/hooks/hooks-diagnostics.d.ts +3 -0
  39. package/dist/hooks/hooks-diagnostics.js +21 -0
  40. package/dist/hooks/hooks-persistence.d.ts +17 -0
  41. package/dist/hooks/hooks-persistence.js +207 -0
  42. package/dist/hooks/hooks-registry.d.ts +6 -0
  43. package/dist/hooks/hooks-registry.js +104 -0
  44. package/dist/hooks/hooks-wrapper.d.ts +25 -0
  45. package/dist/hooks/hooks-wrapper.js +318 -0
  46. package/dist/hooks/internal/before-tool.d.ts +6 -0
  47. package/dist/hooks/internal/before-tool.js +13 -0
  48. package/dist/hooks/internal/session-compaction.d.ts +9 -0
  49. package/dist/hooks/{session-compaction.js → internal/session-compaction.js} +9 -7
  50. package/dist/hooks/runtime/circuit-breaker.d.ts +23 -0
  51. package/dist/hooks/runtime/circuit-breaker.js +39 -0
  52. package/dist/hooks/runtime/failure-policy.d.ts +15 -0
  53. package/dist/hooks/runtime/failure-policy.js +49 -0
  54. package/dist/hooks/runtime/process-executor.d.ts +33 -0
  55. package/dist/hooks/runtime/process-executor.js +147 -0
  56. package/dist/hooks/runtime/status-recorder.d.ts +27 -0
  57. package/dist/hooks/runtime/status-recorder.js +111 -0
  58. package/dist/index.d.ts +7 -0
  59. package/dist/index.js +111 -40
  60. package/dist/skills/agents-md-generator/SKILL.md +223 -223
  61. package/dist/skills/codebase-analyzer/SKILL.md +162 -162
  62. package/dist/skills/codebase-analyzer/references/code-analysis.md +63 -63
  63. package/dist/skills/codebase-analyzer/references/combined.md +31 -31
  64. package/dist/skills/codebase-analyzer/references/context-discovery.md +63 -63
  65. package/dist/skills/codebase-analyzer/references/file-discovery.md +51 -51
  66. package/dist/skills/codebase-analyzer/references/migration-target.md +23 -23
  67. package/dist/skills/codebase-analyzer/references/pattern-mining.md +22 -22
  68. package/dist/skills/dev-analyze/SKILL.md +115 -115
  69. package/dist/skills/dev-bugfix/SKILL.md +452 -452
  70. package/dist/skills/dev-finalize/SKILL.md +118 -118
  71. package/dist/skills/dev-implement/SKILL.md +167 -167
  72. package/dist/skills/dev-plan/SKILL.md +147 -147
  73. package/dist/skills/dev-spec/SKILL.md +182 -182
  74. package/dist/skills/dev-tdd-red/SKILL.md +94 -94
  75. package/dist/skills/dev-verify/SKILL.md +153 -153
  76. package/dist/skills/development/SKILL.md +260 -260
  77. package/dist/skills/diagrams-mermaid/SKILL.md +183 -159
  78. package/dist/skills/diagrams-mermaid/references/reference.md +220 -148
  79. package/dist/skills/docs-manager/SKILL.md +379 -379
  80. package/dist/skills/docs-manager/docs/INDEX.md +199 -199
  81. package/dist/skills/docs-manager/docs/standards/backend/api.md +25 -25
  82. package/dist/skills/docs-manager/docs/standards/backend/migrations.md +22 -22
  83. package/dist/skills/docs-manager/docs/standards/backend/models.md +25 -25
  84. package/dist/skills/docs-manager/docs/standards/backend/queries.md +22 -22
  85. package/dist/skills/docs-manager/docs/standards/frontend/accessibility.md +25 -25
  86. package/dist/skills/docs-manager/docs/standards/frontend/components.md +28 -28
  87. package/dist/skills/docs-manager/docs/standards/frontend/css.md +16 -16
  88. package/dist/skills/docs-manager/docs/standards/frontend/responsive.md +28 -28
  89. package/dist/skills/docs-manager/docs/standards/global/coding-style.md +25 -25
  90. package/dist/skills/docs-manager/docs/standards/global/commenting.md +10 -10
  91. package/dist/skills/docs-manager/docs/standards/global/conventions.md +31 -31
  92. package/dist/skills/docs-manager/docs/standards/global/error-handling.md +22 -22
  93. package/dist/skills/docs-manager/docs/standards/global/minimal-implementation.md +22 -22
  94. package/dist/skills/docs-manager/docs/standards/global/validation.md +28 -28
  95. package/dist/skills/docs-manager/docs/standards/testing/test-writing.md +25 -25
  96. package/dist/skills/docs-manager/references/agents-md-template.md +29 -29
  97. package/dist/skills/docs-manager/references/index-md-template.md +73 -73
  98. package/dist/skills/flow-init/SKILL.md +234 -234
  99. package/dist/skills/flow-init/references/architecture-template.md +45 -45
  100. package/dist/skills/flow-init/references/roadmap-templates.md +93 -93
  101. package/dist/skills/flow-init/references/tech-stack-template.md +70 -70
  102. package/dist/skills/flow-init/references/vision-templates.md +75 -75
  103. package/dist/skills/goal-development/SKILL.md +96 -96
  104. package/dist/skills/goal-migration/SKILL.md +114 -114
  105. package/dist/skills/goal-performance/SKILL.md +126 -0
  106. package/dist/skills/goal-research/SKILL.md +118 -118
  107. package/dist/skills/html-renderer/SKILL.md +173 -173
  108. package/dist/skills/html-renderer/references/index.html +318 -318
  109. package/dist/skills/html-renderer/references/styles.css +388 -388
  110. package/dist/skills/html-renderer/references/tokens.json +104 -104
  111. package/dist/skills/implementation-plan-executor/SKILL.md +378 -378
  112. package/dist/skills/implementation-verifier/SKILL.md +307 -307
  113. package/dist/skills/migration/SKILL.md +268 -268
  114. package/dist/skills/migration-analyze/SKILL.md +126 -126
  115. package/dist/skills/migration-finalize/SKILL.md +161 -161
  116. package/dist/skills/migration-fix/SKILL.md +155 -155
  117. package/dist/skills/migration-implement/SKILL.md +131 -131
  118. package/dist/skills/migration-plan/SKILL.md +131 -131
  119. package/dist/skills/migration-spec/SKILL.md +135 -135
  120. package/dist/skills/migration-spec/references/migration-strategies.md +430 -430
  121. package/dist/skills/migration-target/SKILL.md +134 -134
  122. package/dist/skills/migration-target/references/migration-types.md +489 -489
  123. package/dist/skills/migration-verify/SKILL.md +184 -184
  124. package/dist/skills/orchestrator-framework/SKILL.md +65 -65
  125. package/dist/skills/orchestrator-framework/references/command-namespacing.md +7 -7
  126. package/dist/skills/orchestrator-framework/references/confirm-or-revise-exception.md +20 -20
  127. package/dist/skills/orchestrator-framework/references/delegation-rules.md +54 -54
  128. package/dist/skills/orchestrator-framework/references/dispatcher-handoff.md +27 -27
  129. package/dist/skills/orchestrator-framework/references/fix-loop-contract.md +65 -65
  130. package/dist/skills/orchestrator-framework/references/gate-contract.md +122 -117
  131. package/dist/skills/orchestrator-framework/references/orchestrator-creation-checklist.md +51 -51
  132. package/dist/skills/orchestrator-framework/references/orchestrator-patterns.md +235 -235
  133. package/dist/skills/performance/SKILL.md +267 -437
  134. package/dist/skills/performance-analyze/SKILL.md +129 -0
  135. package/dist/skills/{performance → performance-analyze}/references/performance-optimization-guide.md +271 -365
  136. package/dist/skills/performance-finalize/SKILL.md +117 -0
  137. package/dist/skills/performance-implement/SKILL.md +114 -0
  138. package/dist/skills/performance-plan/SKILL.md +112 -0
  139. package/dist/skills/performance-spec/SKILL.md +145 -0
  140. package/dist/skills/performance-verify/SKILL.md +164 -0
  141. package/dist/skills/research/SKILL.md +249 -249
  142. package/dist/skills/research-brainstorm/SKILL.md +120 -120
  143. package/dist/skills/research-brainstorm/references/brainstorming-techniques.md +84 -84
  144. package/dist/skills/research-converge/SKILL.md +130 -130
  145. package/dist/skills/research-design/SKILL.md +146 -146
  146. package/dist/skills/research-design/references/design-techniques.md +40 -40
  147. package/dist/skills/research-finalize/SKILL.md +125 -125
  148. package/dist/skills/research-fork/SKILL.md +190 -190
  149. package/dist/skills/research-gather/SKILL.md +133 -133
  150. package/dist/skills/research-plan/SKILL.md +141 -141
  151. package/dist/skills/research-plan/references/research-methodologies.md +710 -710
  152. package/dist/skills/research-quick/SKILL.md +139 -139
  153. package/dist/skills/research-synthesize/SKILL.md +127 -127
  154. package/dist/skills/rule-reviewer/SKILL.md +334 -334
  155. package/dist/skills/standards-discover/SKILL.md +260 -260
  156. package/dist/skills/standards-discover/references/aggregation-strategy.md +76 -76
  157. package/dist/skills/standards-discover/references/code-pattern-prompt.md +68 -68
  158. package/dist/skills/standards-discover/references/config-analyzer-prompt.md +67 -67
  159. package/dist/skills/standards-discover/references/docs-extractor-prompt.md +65 -65
  160. package/dist/skills/standards-discover/references/external-analyzer-prompt.md +75 -75
  161. package/dist/skills/standards-update/SKILL.md +207 -207
  162. package/dist/templates/orchestrator-state-base.yml +17 -17
  163. package/dist/templates/orchestrator-state-development.yml +95 -95
  164. package/dist/templates/orchestrator-state-migration.yml +95 -95
  165. package/dist/templates/orchestrator-state-performance.yml +64 -53
  166. package/dist/templates/orchestrator-state-research.yml +67 -67
  167. package/dist/tools/fork_task.d.ts +17 -0
  168. package/dist/tools/fork_task.js +21 -11
  169. package/dist/tools/verify_template.d.ts +11 -0
  170. package/dist/tools/verify_template.js +32 -17
  171. package/dist/tui/hooks-dialogs.d.ts +20 -0
  172. package/dist/tui/hooks-dialogs.js +181 -0
  173. package/dist/tui/hooks-presenter.d.ts +15 -0
  174. package/dist/tui/hooks-presenter.js +70 -0
  175. package/dist/tui/hooks-sidebar.d.ts +10 -0
  176. package/dist/tui/hooks-sidebar.js +104 -0
  177. package/dist/tui/primitives.d.ts +21 -0
  178. package/dist/tui/primitives.js +47 -0
  179. package/dist/tui.d.ts +12 -0
  180. package/dist/tui.js +129 -0
  181. package/dist/types/hook-types.d.ts +125 -0
  182. package/dist/types/hook-types.js +76 -0
  183. package/dist/types/opencode-types.d.ts +13 -0
  184. package/dist/utils/file-util.d.ts +2 -0
  185. package/dist/utils/file-util.js +6 -6
  186. package/dist/utils/fork-task.d.ts +27 -0
  187. package/dist/utils/fork-task.js +18 -23
  188. package/dist/utils/plugin-info.d.ts +3 -0
  189. package/dist/utils/plugin-info.js +8 -10
  190. package/dist/utils/workflow-paths.d.ts +17 -0
  191. package/dist/utils/workflow-paths.js +18 -0
  192. package/dist/utils/yaml-structure.d.ts +7 -0
  193. package/dist/utils/yaml-structure.js +7 -11
  194. package/package.json +68 -48
  195. package/dist/hooks/before-tool.js +0 -19
@@ -1,365 +1,271 @@
1
- # Performance Optimization Guide
2
-
3
- Reference covering performance metrics knowledge, optimization patterns, and static analysis detection strategies.
4
-
5
- ## Table of Contents
6
-
7
- 1. [Performance Metrics](#performance-metrics)
8
- 2. [Optimization Patterns](#optimization-patterns)
9
- 3. [Static Analysis Detection Patterns](#static-analysis-detection-patterns)
10
-
11
- ---
12
-
13
- # Performance Metrics
14
-
15
- ## Response Time Metrics
16
-
17
- **p50 (Median)**: 50% of requests faster than this value
18
- **p95**: 95% of requests faster (typical SLA target)
19
- **p99**: 99% of requests faster (worst-case for most users)
20
- **Max**: Slowest request (often outlier, less important)
21
-
22
- **Interpretation Thresholds**:
23
- - p95 < 100ms: Excellent
24
- - p95 100-500ms: Good
25
- - p95 500-1000ms: Acceptable
26
- - p95 > 1000ms: Slow (optimization needed)
27
-
28
- ## Throughput Metrics
29
-
30
- **Requests/sec**: Total requests handled per second
31
- **Transactions/sec**: Completed transactions per second
32
- **Saturation Point**: Concurrency level where throughput plateaus
33
-
34
- ## CPU Metrics
35
-
36
- **Usage %**: Overall CPU utilization
37
- **Hot Functions**: Top functions by CPU time
38
- **Complexity**: O(n), O(n log n), O(n^2), etc.
39
-
40
- **Thresholds**:
41
- - < 70%: Good headroom
42
- - 70-90%: Acceptable
43
- - \> 90%: Saturated
44
-
45
- ## Memory Metrics
46
-
47
- **Heap Size**: Current memory usage
48
- **Heap Growth**: Memory increase over time (leak indicator)
49
- **GC Frequency**: Garbage collection frequency
50
-
51
- **Leak Detection**: Heap grows continuously without plateau
52
-
53
- ## Database Metrics
54
-
55
- **Queries/Request**: Total database queries per request
56
- **Query Time**: Time spent in database
57
- **N+1 Pattern**: 1 query + N related queries in loop
58
- **Missing Indexes**: Full table scans
59
-
60
- ---
61
-
62
- # Optimization Patterns
63
-
64
- ## Database Optimizations
65
-
66
- ### Fix N+1 Queries
67
-
68
- **Problem**: 1 query to fetch list + N queries for related data
69
-
70
- **Bad** (N+1 pattern):
71
- ```javascript
72
- const users = await User.findAll(); // 1 query
73
- for (let user of users) {
74
- user.profile = await Profile.findByPk(user.id); // N queries
75
- }
76
- ```
77
-
78
- **Good** (eager loading):
79
- ```javascript
80
- const users = await User.findAll({
81
- include: [{ model: Profile }] // Single JOIN query
82
- });
83
- ```
84
-
85
- ### Add Missing Indexes
86
-
87
- **Detection**: Query filters/sorts on unindexed columns
88
-
89
- ```sql
90
- -- Before (slow - sequential scan)
91
- SELECT * FROM orders WHERE user_id = 123;
92
-
93
- -- Add index
94
- CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);
95
-
96
- -- After (fast - index scan)
97
- ```
98
-
99
- ### Connection Pooling
100
-
101
- ```javascript
102
- // Bad: New connection per query
103
- const connection = await mysql.createConnection(config);
104
-
105
- // Good: Connection pool
106
- const pool = mysql.createPool({
107
- connectionLimit: 10,
108
- ...config
109
- });
110
- ```
111
-
112
- ## Algorithm Optimizations
113
-
114
- ### Replace O(n^2) with O(n)
115
-
116
- **Bad** (nested loops):
117
- ```javascript
118
- // O(n^2)
119
- for (let user of users) {
120
- for (let order of orders) {
121
- if (order.userId === user.id) {
122
- user.orders.push(order);
123
- }
124
- }
125
- }
126
- ```
127
-
128
- **Good** (hash map):
129
- ```javascript
130
- // O(n)
131
- const ordersByUser = {};
132
- for (let order of orders) {
133
- if (!ordersByUser[order.userId]) ordersByUser[order.userId] = [];
134
- ordersByUser[order.userId].push(order);
135
- }
136
- for (let user of users) {
137
- user.orders = ordersByUser[user.id] || [];
138
- }
139
- ```
140
-
141
- ### Memoization
142
-
143
- **Bad** (repeated calculations):
144
- ```javascript
145
- function fibonacci(n) {
146
- if (n <= 1) return n;
147
- return fibonacci(n - 1) + fibonacci(n - 2); // Exponential time
148
- }
149
- ```
150
-
151
- **Good** (memoized):
152
- ```javascript
153
- const memo = {};
154
- function fibonacci(n) {
155
- if (n <= 1) return n;
156
- if (memo[n]) return memo[n];
157
- memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
158
- return memo[n];
159
- }
160
- ```
161
-
162
- ## Caching Strategies
163
-
164
- ### Cache Expensive Operations
165
-
166
- ```javascript
167
- // Bad: Calculate every time
168
- app.get('/stats', async (req, res) => {
169
- const stats = await calculateExpensiveStats(); // 5 seconds
170
- res.json(stats);
171
- });
172
-
173
- // Good: Cache results
174
- const cache = new Map();
175
- app.get('/stats', async (req, res) => {
176
- let stats = cache.get('stats');
177
- if (!stats) {
178
- stats = await calculateExpensiveStats();
179
- cache.set('stats', stats);
180
- setTimeout(() => cache.delete('stats'), 60000); // TTL: 1 min
181
- }
182
- res.json(stats);
183
- });
184
- ```
185
-
186
- ### Redis Caching
187
-
188
- ```javascript
189
- const redis = require('redis');
190
- const client = redis.createClient();
191
-
192
- // Cache expensive query
193
- async function getUser(id) {
194
- const cached = await client.get(`user:${id}`);
195
- if (cached) return JSON.parse(cached);
196
-
197
- const user = await db.query('SELECT * FROM users WHERE id = ?', [id]);
198
- await client.setex(`user:${id}`, 3600, JSON.stringify(user)); // TTL: 1 hour
199
- return user;
200
- }
201
- ```
202
-
203
- ## I/O Optimizations
204
-
205
- ### Async vs Sync
206
-
207
- **Bad** (blocking):
208
- ```javascript
209
- const data = fs.readFileSync('large-file.json'); // Blocks event loop
210
- ```
211
-
212
- **Good** (non-blocking):
213
- ```javascript
214
- const data = await fs.promises.readFile('large-file.json'); // Async
215
- ```
216
-
217
- ### Parallel API Calls
218
-
219
- **Bad** (sequential):
220
- ```javascript
221
- const user = await fetchUser(id); // 200ms
222
- const orders = await fetchOrders(id); // 200ms
223
- const profile = await fetchProfile(id); // 200ms
224
- // Total: 600ms
225
- ```
226
-
227
- **Good** (parallel):
228
- ```javascript
229
- const [user, orders, profile] = await Promise.all([
230
- fetchUser(id),
231
- fetchOrders(id),
232
- fetchProfile(id)
233
- ]);
234
- // Total: 200ms (slowest of the three)
235
- ```
236
-
237
- ## Memory Optimizations
238
-
239
- ### Streaming Large Data
240
-
241
- **Bad** (load all):
242
- ```javascript
243
- const data = await fs.promises.readFile('large-file.csv'); // 1GB in memory
244
- processCSV(data);
245
- ```
246
-
247
- **Good** (stream):
248
- ```javascript
249
- const stream = fs.createReadStream('large-file.csv');
250
- stream.pipe(csvParser()).on('data', processRow); // Constant memory
251
- ```
252
-
253
- ### Object Pooling
254
-
255
- ```javascript
256
- // Bad: Create new objects constantly
257
- for (let i = 0; i < 1000000; i++) {
258
- const obj = { x: i, y: i * 2 }; // 1M allocations
259
- process(obj);
260
- }
261
-
262
- // Good: Reuse objects
263
- const pool = { x: 0, y: 0 };
264
- for (let i = 0; i < 1000000; i++) {
265
- pool.x = i;
266
- pool.y = i * 2; // 1 allocation, reused
267
- process(pool);
268
- }
269
- ```
270
-
271
- ---
272
-
273
- # Static Analysis Detection Patterns
274
-
275
- Strategies for detecting performance bottlenecks by reading code rather than running profiling tools.
276
-
277
- ## Database Pattern Detection
278
-
279
- ### N+1 Query Detection by Framework
280
-
281
- **Generic ORM-in-loop patterns** (Grep heuristics):
282
- - Query call inside `for`/`forEach`/`map`/`while` body
283
- - `await` + model method inside iteration callback
284
- - Lazy-loaded relationship access inside loop
285
-
286
- **Framework-specific indicators**:
287
-
288
- | Framework | N+1 Pattern | Fix Pattern |
289
- |-----------|-------------|-------------|
290
- | Sequelize | `.findByPk()`/`.findOne()` in loop | `include: [{ model: X }]` |
291
- | Prisma | `prisma.x.findUnique()` in loop | `include: { x: true }` |
292
- | TypeORM | `repository.findOne()` in loop | `relations: ['x']` or QueryBuilder `.leftJoinAndSelect()` |
293
- | Django | Attribute access in template `{% for %}` | `.select_related()`/`.prefetch_related()` |
294
- | Rails | Association call without `.includes()` | `.includes(:association)` |
295
- | SQLAlchemy | Relationship access in loop | `joinedload()`/`subqueryload()` |
296
- | Hibernate | `@ManyToOne` lazy access in loop | `@Fetch(FetchMode.JOIN)` or JPQL `JOIN FETCH` |
297
-
298
- ### Missing Index Detection
299
-
300
- **Cross-reference strategy**:
301
- 1. Find all index definitions in schema/migration files
302
- 2. Find all query patterns (WHERE, ORDER BY, JOIN columns)
303
- 3. Flag columns queried but not indexed
304
-
305
- **Where to find indexes by framework**:
306
- - **Rails**: `add_index` in `db/migrate/` files
307
- - **Django**: `db_index=True` in model fields, `indexes` in Meta
308
- - **Sequelize**: `indexes` array in model definition
309
- - **Prisma**: `@@index` and `@@unique` in schema.prisma
310
- - **TypeORM**: `@Index()` decorator
311
- - **SQL migrations**: `CREATE INDEX` statements
312
-
313
- ### Slow Query Pattern Indicators
314
-
315
- Patterns detectable from code without running queries:
316
- - `SELECT *` on tables with many columns
317
- - Missing `LIMIT`/`TOP` on queries against known-large tables
318
- - `LIKE '%...'` (leading wildcard prevents index use)
319
- - `OR` conditions on different columns (prevents single index use)
320
- - Subqueries in WHERE that could be JOINs
321
- - `DISTINCT` masking a JOIN issue
322
-
323
- ## Algorithm Pattern Detection
324
-
325
- ### Nested Loop / O(n^2) Heuristics
326
-
327
- **Search patterns**:
328
- - Nested `for`/`forEach`/`while` loops over same or related collections
329
- - `.find()`/`.filter()`/`.some()`/`.includes()` inside `.map()`/`.forEach()`/`for`
330
- - `.indexOf()` inside loop (linear search repeated)
331
- - `.sort()` inside loop (O(n log n) per iteration)
332
-
333
- **Fix indicators**: Can be resolved by pre-building a Map/Set/index before the loop
334
-
335
- ### Blocking I/O Patterns
336
-
337
- **Node.js sync operations**:
338
- - `readFileSync`, `writeFileSync`, `readdirSync`, `statSync`, `existsSync`
339
- - `execSync`, `spawnSync`
340
- - `crypto.pbkdf2Sync`, `crypto.randomBytesSync`
341
-
342
- **Sequential awaits** (should be `Promise.all`):
343
- - Multiple `await` statements on independent operations in same function
344
- - Sequential HTTP/fetch calls to different endpoints
345
- - Sequential database queries with no data dependency between them
346
-
347
- ## Memory Pattern Detection
348
-
349
- **Unbounded growth indicators**:
350
- - `Map`/`Set`/`Object`/`Array` in module or class scope with `.set()`/`push()` but no `.delete()`/eviction
351
- - No size limit check before adding to collection
352
- - No TTL or expiration mechanism
353
-
354
- **Leak-prone patterns**:
355
- - `addEventListener`/`.on()` without paired `removeEventListener`/`.off()`
356
- - `setInterval` without `clearInterval` in cleanup/destroy/unmount
357
- - Closures in long-lived callbacks capturing large objects
358
-
359
- ## Caching Opportunity Detection
360
-
361
- **Indicators**:
362
- - Same query/function called multiple times with same parameters in a request lifecycle
363
- - Database query in a loop that could be batched and cached
364
- - External API call returning reference/config data (infrequent changes)
365
- - Expensive computation (sort, aggregate, transform) on data that doesn't change per-request
1
+ # Performance Optimization Guide
2
+
3
+ Reference covering performance metrics knowledge and optimization patterns.
4
+
5
+ ## Table of Contents
6
+
7
+ 1. [Performance Metrics](#performance-metrics)
8
+ 2. [Optimization Patterns](#optimization-patterns)
9
+
10
+ ---
11
+
12
+ # Performance Metrics
13
+
14
+ ## Response Time Metrics
15
+
16
+ **p50 (Median)**: 50% of requests faster than this value
17
+ **p95**: 95% of requests faster (typical SLA target)
18
+ **p99**: 99% of requests faster (worst-case for most users)
19
+ **Max**: Slowest request (often outlier, less important)
20
+
21
+ **Interpretation Thresholds**:
22
+ - p95 < 100ms: Excellent
23
+ - p95 100-500ms: Good
24
+ - p95 500-1000ms: Acceptable
25
+ - p95 > 1000ms: Slow (optimization needed)
26
+
27
+ ## Throughput Metrics
28
+
29
+ **Requests/sec**: Total requests handled per second
30
+ **Transactions/sec**: Completed transactions per second
31
+ **Saturation Point**: Concurrency level where throughput plateaus
32
+
33
+ ## CPU Metrics
34
+
35
+ **Usage %**: Overall CPU utilization
36
+ **Hot Functions**: Top functions by CPU time
37
+ **Complexity**: O(n), O(n log n), O(n^2), etc.
38
+
39
+ **Thresholds**:
40
+ - < 70%: Good headroom
41
+ - 70-90%: Acceptable
42
+ - \> 90%: Saturated
43
+
44
+ ## Memory Metrics
45
+
46
+ **Heap Size**: Current memory usage
47
+ **Heap Growth**: Memory increase over time (leak indicator)
48
+ **GC Frequency**: Garbage collection frequency
49
+
50
+ **Leak Detection**: Heap grows continuously without plateau
51
+
52
+ ## Database Metrics
53
+
54
+ **Queries/Request**: Total database queries per request
55
+ **Query Time**: Time spent in database
56
+ **N+1 Pattern**: 1 query + N related queries in loop
57
+ **Missing Indexes**: Full table scans
58
+
59
+ ---
60
+
61
+ # Optimization Patterns
62
+
63
+ ## Database Optimizations
64
+
65
+ ### Fix N+1 Queries
66
+
67
+ **Problem**: 1 query to fetch list + N queries for related data
68
+
69
+ **Bad** (N+1 pattern):
70
+ ```javascript
71
+ const users = await User.findAll(); // 1 query
72
+ for (let user of users) {
73
+ user.profile = await Profile.findByPk(user.id); // N queries
74
+ }
75
+ ```
76
+
77
+ **Good** (eager loading):
78
+ ```javascript
79
+ const users = await User.findAll({
80
+ include: [{ model: Profile }] // Single JOIN query
81
+ });
82
+ ```
83
+
84
+ ### Add Missing Indexes
85
+
86
+ **Detection**: Query filters/sorts on unindexed columns
87
+
88
+ ```sql
89
+ -- Before (slow - sequential scan)
90
+ SELECT * FROM orders WHERE user_id = 123;
91
+
92
+ -- Add index
93
+ CREATE INDEX CONCURRENTLY idx_orders_user_id ON orders(user_id);
94
+
95
+ -- After (fast - index scan)
96
+ ```
97
+
98
+ ### Connection Pooling
99
+
100
+ ```javascript
101
+ // Bad: New connection per query
102
+ const connection = await mysql.createConnection(config);
103
+
104
+ // Good: Connection pool
105
+ const pool = mysql.createPool({
106
+ connectionLimit: 10,
107
+ ...config
108
+ });
109
+ ```
110
+
111
+ ## Algorithm Optimizations
112
+
113
+ ### Replace O(n^2) with O(n)
114
+
115
+ **Bad** (nested loops):
116
+ ```javascript
117
+ // O(n^2)
118
+ for (let user of users) {
119
+ for (let order of orders) {
120
+ if (order.userId === user.id) {
121
+ user.orders.push(order);
122
+ }
123
+ }
124
+ }
125
+ ```
126
+
127
+ **Good** (hash map):
128
+ ```javascript
129
+ // O(n)
130
+ const ordersByUser = {};
131
+ for (let order of orders) {
132
+ if (!ordersByUser[order.userId]) ordersByUser[order.userId] = [];
133
+ ordersByUser[order.userId].push(order);
134
+ }
135
+ for (let user of users) {
136
+ user.orders = ordersByUser[user.id] || [];
137
+ }
138
+ ```
139
+
140
+ ### Memoization
141
+
142
+ **Bad** (repeated calculations):
143
+ ```javascript
144
+ function fibonacci(n) {
145
+ if (n <= 1) return n;
146
+ return fibonacci(n - 1) + fibonacci(n - 2); // Exponential time
147
+ }
148
+ ```
149
+
150
+ **Good** (memoized):
151
+ ```javascript
152
+ const memo = {};
153
+ function fibonacci(n) {
154
+ if (n <= 1) return n;
155
+ if (memo[n]) return memo[n];
156
+ memo[n] = fibonacci(n - 1) + fibonacci(n - 2);
157
+ return memo[n];
158
+ }
159
+ ```
160
+
161
+ ## Caching Strategies
162
+
163
+ ### Cache Expensive Operations
164
+
165
+ ```javascript
166
+ // Bad: Calculate every time
167
+ app.get('/stats', async (req, res) => {
168
+ const stats = await calculateExpensiveStats(); // 5 seconds
169
+ res.json(stats);
170
+ });
171
+
172
+ // Good: Cache results
173
+ const cache = new Map();
174
+ app.get('/stats', async (req, res) => {
175
+ let stats = cache.get('stats');
176
+ if (!stats) {
177
+ stats = await calculateExpensiveStats();
178
+ cache.set('stats', stats);
179
+ setTimeout(() => cache.delete('stats'), 60000); // TTL: 1 min
180
+ }
181
+ res.json(stats);
182
+ });
183
+ ```
184
+
185
+ ### Redis Caching
186
+
187
+ ```javascript
188
+ const redis = require('redis');
189
+ const client = redis.createClient();
190
+
191
+ // Cache expensive query
192
+ async function getUser(id) {
193
+ const cached = await client.get(`user:${id}`);
194
+ if (cached) return JSON.parse(cached);
195
+
196
+ const user = await db.query('SELECT * FROM users WHERE id = ?', [id]);
197
+ await client.setex(`user:${id}`, 3600, JSON.stringify(user)); // TTL: 1 hour
198
+ return user;
199
+ }
200
+ ```
201
+
202
+ ## I/O Optimizations
203
+
204
+ ### Async vs Sync
205
+
206
+ **Bad** (blocking):
207
+ ```javascript
208
+ const data = fs.readFileSync('large-file.json'); // Blocks event loop
209
+ ```
210
+
211
+ **Good** (non-blocking):
212
+ ```javascript
213
+ const data = await fs.promises.readFile('large-file.json'); // Async
214
+ ```
215
+
216
+ ### Parallel API Calls
217
+
218
+ **Bad** (sequential):
219
+ ```javascript
220
+ const user = await fetchUser(id); // 200ms
221
+ const orders = await fetchOrders(id); // 200ms
222
+ const profile = await fetchProfile(id); // 200ms
223
+ // Total: 600ms
224
+ ```
225
+
226
+ **Good** (parallel):
227
+ ```javascript
228
+ const [user, orders, profile] = await Promise.all([
229
+ fetchUser(id),
230
+ fetchOrders(id),
231
+ fetchProfile(id)
232
+ ]);
233
+ // Total: 200ms (slowest of the three)
234
+ ```
235
+
236
+ ## Memory Optimizations
237
+
238
+ ### Streaming Large Data
239
+
240
+ **Bad** (load all):
241
+ ```javascript
242
+ const data = await fs.promises.readFile('large-file.csv'); // 1GB in memory
243
+ processCSV(data);
244
+ ```
245
+
246
+ **Good** (stream):
247
+ ```javascript
248
+ const stream = fs.createReadStream('large-file.csv');
249
+ stream.pipe(csvParser()).on('data', processRow); // Constant memory
250
+ ```
251
+
252
+ ### Object Pooling
253
+
254
+ ```javascript
255
+ // Bad: Create new objects constantly
256
+ for (let i = 0; i < 1000000; i++) {
257
+ const obj = { x: i, y: i * 2 }; // 1M allocations
258
+ process(obj);
259
+ }
260
+
261
+ // Good: Reuse objects
262
+ const pool = { x: 0, y: 0 };
263
+ for (let i = 0; i < 1000000; i++) {
264
+ pool.x = i;
265
+ pool.y = i * 2; // 1 allocation, reused
266
+ process(pool);
267
+ }
268
+ ```
269
+
270
+ ---
271
+