cortex-agents 1.1.0 → 2.1.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 (34) hide show
  1. package/.opencode/agents/build.md +34 -3
  2. package/.opencode/agents/debug.md +24 -2
  3. package/.opencode/agents/devops.md +1 -2
  4. package/.opencode/agents/fullstack.md +1 -2
  5. package/.opencode/agents/plan.md +5 -3
  6. package/.opencode/agents/security.md +1 -2
  7. package/.opencode/agents/testing.md +1 -2
  8. package/.opencode/skills/api-design/SKILL.md +348 -0
  9. package/.opencode/skills/architecture-patterns/SKILL.md +323 -0
  10. package/.opencode/skills/backend-development/SKILL.md +329 -0
  11. package/.opencode/skills/code-quality/SKILL.md +12 -0
  12. package/.opencode/skills/database-design/SKILL.md +347 -0
  13. package/.opencode/skills/deployment-automation/SKILL.md +7 -0
  14. package/.opencode/skills/design-patterns/SKILL.md +295 -0
  15. package/.opencode/skills/desktop-development/SKILL.md +295 -0
  16. package/.opencode/skills/frontend-development/SKILL.md +210 -0
  17. package/.opencode/skills/mobile-development/SKILL.md +407 -0
  18. package/.opencode/skills/performance-optimization/SKILL.md +330 -0
  19. package/.opencode/skills/testing-strategies/SKILL.md +33 -0
  20. package/README.md +390 -76
  21. package/dist/cli.js +249 -27
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +38 -0
  24. package/dist/plugin.js +3 -2
  25. package/dist/registry.d.ts +45 -0
  26. package/dist/registry.d.ts.map +1 -0
  27. package/dist/registry.js +140 -0
  28. package/dist/tools/cortex.d.ts.map +1 -1
  29. package/dist/tools/cortex.js +2 -3
  30. package/dist/tools/docs.d.ts +52 -0
  31. package/dist/tools/docs.d.ts.map +1 -0
  32. package/dist/tools/docs.js +328 -0
  33. package/package.json +11 -4
  34. package/.opencode/skills/web-development/SKILL.md +0 -122
@@ -0,0 +1,330 @@
1
+ ---
2
+ name: performance-optimization
3
+ description: Profiling, caching strategies, algorithm optimization, memory management, web performance, and build optimization
4
+ license: Apache-2.0
5
+ compatibility: opencode
6
+ ---
7
+
8
+ # Performance Optimization Skill
9
+
10
+ This skill provides patterns and techniques for identifying and resolving performance bottlenecks across the stack.
11
+
12
+ ## When to Use
13
+
14
+ Use this skill when:
15
+ - Applications are slow or unresponsive
16
+ - Scaling to handle more users or data
17
+ - Optimizing resource consumption (CPU, memory, network)
18
+ - Improving web performance metrics (Core Web Vitals)
19
+ - Reducing build times or bundle sizes
20
+
21
+ ## Performance Methodology
22
+
23
+ ### The Optimization Process
24
+ 1. **Measure** — Profile before optimizing (never guess)
25
+ 2. **Identify** — Find the actual bottleneck (Pareto: 20% of code causes 80% of issues)
26
+ 3. **Optimize** — Apply targeted fix to the bottleneck
27
+ 4. **Verify** — Measure again to confirm improvement
28
+ 5. **Repeat** — Move to the next bottleneck
29
+
30
+ ### Key Principle
31
+ > "Premature optimization is the root of all evil" — Donald Knuth
32
+ >
33
+ > Optimize only what you've measured. Optimize the bottleneck, not the code that's "probably slow."
34
+
35
+ ## Profiling
36
+
37
+ ### CPU Profiling
38
+ - Identify functions consuming the most CPU time
39
+ - Look for hot loops, excessive computation, blocking operations
40
+ - Tools: Chrome DevTools Performance tab, Node.js `--prof`, Go `pprof`, Rust `perf`
41
+
42
+ ### Memory Profiling
43
+ - Identify memory leaks, excessive allocations, large objects
44
+ - Monitor heap size over time — growing heap = likely leak
45
+ - Tools: Chrome DevTools Memory tab, Node.js `--inspect` + heap snapshot
46
+
47
+ ### Flame Graphs
48
+ - Visual representation of call stacks over time
49
+ - Wide bars = functions consuming more time
50
+ - Read bottom-up: root at bottom, hot functions at top
51
+ - Tools: `0x` (Node.js), `pprof` (Go), `cargo flamegraph` (Rust)
52
+
53
+ ### Benchmarking
54
+ ```typescript
55
+ // Node.js — basic benchmarking
56
+ console.time("operation");
57
+ await performOperation();
58
+ console.timeEnd("operation"); // operation: 42.53ms
59
+
60
+ // Go — built-in benchmarking
61
+ func BenchmarkSort(b *testing.B) {
62
+ for i := 0; i < b.N; i++ {
63
+ sort(data)
64
+ }
65
+ }
66
+ ```
67
+
68
+ ## Web Performance
69
+
70
+ ### Core Web Vitals
71
+ | Metric | Target | Measures | Optimization |
72
+ |--------|--------|----------|-------------|
73
+ | LCP | < 2.5s | Largest content render time | Optimize images, fonts, critical CSS |
74
+ | INP | < 200ms | Interaction responsiveness | Reduce JS execution, use web workers |
75
+ | CLS | < 0.1 | Visual stability | Set dimensions on media, avoid dynamic injection |
76
+
77
+ ### Critical Rendering Path
78
+ 1. HTML parsing → DOM tree
79
+ 2. CSS parsing → CSSOM tree
80
+ 3. Combine → Render tree
81
+ 4. Layout → Compute geometry
82
+ 5. Paint → Render pixels
83
+
84
+ ### Optimization Techniques
85
+ - **Critical CSS** — Inline above-the-fold CSS, defer the rest
86
+ - **Font optimization** — `font-display: swap`, preload critical fonts, subset fonts
87
+ - **Image optimization** — WebP/AVIF, responsive `srcset`, lazy loading, correct dimensions
88
+ - **JavaScript** — Defer non-critical scripts, code split, tree shake unused code
89
+ - **Preloading** — `<link rel="preload">` for critical resources
90
+ - **Prefetching** — `<link rel="prefetch">` for likely next navigation
91
+
92
+ ## Caching Strategies
93
+
94
+ ### HTTP Caching
95
+ ```
96
+ Cache-Control: public, max-age=31536000, immutable # Static assets (hashed filenames)
97
+ Cache-Control: private, no-cache # User-specific, validate every time
98
+ Cache-Control: no-store # Sensitive data, never cache
99
+ ETag: "abc123" # Conditional requests
100
+ ```
101
+
102
+ ### Caching Layers (from fastest to slowest)
103
+ | Layer | Speed | Scope | Example |
104
+ |-------|-------|-------|---------|
105
+ | CPU cache | ~1ns | Single core | Hardware-managed |
106
+ | In-memory (app) | ~100ns | Single process | LRU cache, memoization |
107
+ | Distributed cache | ~1ms | All processes | Redis, Memcached |
108
+ | CDN | ~10ms | Global edge | Cloudflare, CloudFront |
109
+ | Database | ~10ms | Persistent | Query cache, materialized views |
110
+ | Disk | ~100ms | Persistent | File cache, SQLite |
111
+
112
+ ### Memoization Pattern
113
+ ```typescript
114
+ // Simple memoization for expensive computations
115
+ function memoize<T extends (...args: any[]) => any>(fn: T): T {
116
+ const cache = new Map<string, ReturnType<T>>();
117
+ return ((...args: Parameters<T>) => {
118
+ const key = JSON.stringify(args);
119
+ if (cache.has(key)) return cache.get(key)!;
120
+ const result = fn(...args);
121
+ cache.set(key, result);
122
+ return result;
123
+ }) as T;
124
+ }
125
+
126
+ // React memoization
127
+ const ExpensiveList = React.memo(({ items }) => (
128
+ <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>
129
+ ));
130
+ ```
131
+
132
+ ## Algorithm Optimization
133
+
134
+ ### Big-O Complexity Guide
135
+ | Complexity | Name | Example |
136
+ |-----------|------|---------|
137
+ | O(1) | Constant | Hash map lookup, array index |
138
+ | O(log n) | Logarithmic | Binary search, balanced BST |
139
+ | O(n) | Linear | Array scan, single loop |
140
+ | O(n log n) | Linearithmic | Merge sort, heap sort |
141
+ | O(n²) | Quadratic | Nested loops, bubble sort |
142
+ | O(2ⁿ) | Exponential | Brute-force subsets |
143
+
144
+ ### Common Optimizations
145
+ | Problem | Slow Approach | Fast Approach |
146
+ |---------|---------------|---------------|
147
+ | Lookup in list | O(n) linear scan | O(1) hash map/set |
148
+ | Find duplicates | O(n²) nested loops | O(n) with Set |
149
+ | Sorted data search | O(n) scan | O(log n) binary search |
150
+ | String building | O(n²) concatenation | O(n) array join or StringBuilder |
151
+ | Frequent min/max | O(n) rescan | O(log n) heap/priority queue |
152
+
153
+ ### Data Structure Selection
154
+ | Need | Use | Why |
155
+ |------|-----|-----|
156
+ | Fast lookup by key | HashMap/Object/Dict | O(1) average |
157
+ | Ordered unique values | TreeSet/BTreeSet | O(log n) sorted operations |
158
+ | Fast membership test | Set/HashSet | O(1) contains |
159
+ | FIFO processing | Queue/Deque | O(1) enqueue/dequeue |
160
+ | Priority processing | Heap/Priority Queue | O(log n) insert/extract |
161
+ | Frequent insert/delete middle | Linked List | O(1) with pointer |
162
+
163
+ ## Memory Management
164
+
165
+ ### Memory Leak Detection
166
+ - **Symptoms**: Increasing memory usage over time, eventual OOM
167
+ - **Common causes**:
168
+ - Unclosed event listeners or subscriptions
169
+ - Growing caches without eviction
170
+ - Circular references preventing garbage collection
171
+ - Closures capturing large scopes
172
+ - Global variables accumulating data
173
+
174
+ ### Prevention Strategies
175
+ ```typescript
176
+ // Use WeakRef/WeakMap for caches that shouldn't prevent GC
177
+ const cache = new WeakMap<object, ComputedResult>();
178
+
179
+ // Always clean up subscriptions
180
+ useEffect(() => {
181
+ const subscription = eventBus.subscribe("update", handler);
182
+ return () => subscription.unsubscribe(); // Cleanup!
183
+ }, []);
184
+
185
+ // Set limits on in-memory caches
186
+ class LRUCache<K, V> {
187
+ private maxSize: number;
188
+ private cache = new Map<K, V>();
189
+
190
+ get(key: K): V | undefined {
191
+ const value = this.cache.get(key);
192
+ if (value) {
193
+ this.cache.delete(key);
194
+ this.cache.set(key, value); // Move to end (most recent)
195
+ }
196
+ return value;
197
+ }
198
+ }
199
+ ```
200
+
201
+ ### Object Pooling
202
+ - Reuse objects instead of allocating/deallocating
203
+ - Useful for: database connections, thread pools, game entities
204
+ - Reduces GC pressure in high-throughput scenarios
205
+
206
+ ## Concurrency & Parallelism
207
+
208
+ ### Async I/O
209
+ - Use async/await for all I/O operations — never block the event loop
210
+ - Run independent I/O in parallel with `Promise.all()`
211
+ - Use worker threads for CPU-intensive work (not the main thread)
212
+
213
+ ```typescript
214
+ // Bad — sequential I/O (slow)
215
+ const users = await getUsers();
216
+ const orders = await getOrders();
217
+ const stats = await getStats();
218
+
219
+ // Good — parallel I/O (fast)
220
+ const [users, orders, stats] = await Promise.all([
221
+ getUsers(),
222
+ getOrders(),
223
+ getStats(),
224
+ ]);
225
+ ```
226
+
227
+ ### Web Workers / Worker Threads
228
+ - Offload CPU-intensive work to separate threads
229
+ - Communicate via message passing (structured clone)
230
+ - Use for: image processing, data transformation, crypto, parsing
231
+
232
+ ### Concurrency Patterns
233
+ | Pattern | Use Case | Implementation |
234
+ |---------|----------|----------------|
235
+ | Promise.all() | Parallel independent tasks | JS/TS |
236
+ | Promise.allSettled() | Parallel tasks, handle individual failures | JS/TS |
237
+ | asyncio.gather() | Parallel async tasks | Python |
238
+ | goroutines + channels | Concurrent processing pipeline | Go |
239
+ | rayon par_iter | Data parallelism | Rust |
240
+ | Worker pool | Limit concurrent work | Any language |
241
+
242
+ ## Database Performance
243
+
244
+ ### Query Optimization
245
+ - Index columns in WHERE, JOIN, ORDER BY clauses
246
+ - Use EXPLAIN ANALYZE to understand query plans
247
+ - Avoid SELECT * — fetch only needed columns
248
+ - Use cursor pagination instead of OFFSET for large datasets
249
+
250
+ ### Connection Pooling
251
+ - Always use connection pools — never connect per query
252
+ - Size: `connections = (CPU cores * 2) + disk spindles`
253
+ - Monitor active, idle, and waiting connections
254
+ - Set timeouts: connection, idle, query
255
+
256
+ ### Read Optimization
257
+ - Read replicas for read-heavy workloads
258
+ - Materialized views for complex aggregations
259
+ - Query result caching with Redis/Memcached
260
+ - Denormalize for read-heavy access patterns
261
+
262
+ ## Network Optimization
263
+
264
+ ### Reduce Payload
265
+ - Compression — gzip/Brotli for text, WebP/AVIF for images
266
+ - Sparse fieldsets — return only requested fields
267
+ - Pagination — never return unbounded results
268
+
269
+ ### Reduce Round Trips
270
+ - Batch API calls where possible
271
+ - Use HTTP/2 for multiplexed connections
272
+ - Prefetch data for likely next actions
273
+ - Use CDN for static assets and cacheable API responses
274
+
275
+ ### Connection Optimization
276
+ - HTTP/2 — multiplexed streams, header compression, server push
277
+ - Keep-alive connections — reuse TCP connections
278
+ - DNS prefetch — `<link rel="dns-prefetch" href="//api.example.com">`
279
+
280
+ ## Build Optimization
281
+
282
+ ### Bundle Size Reduction
283
+ - Tree shaking — eliminate unused exports (use ES modules)
284
+ - Code splitting — load code on demand (route-based, component-based)
285
+ - Dynamic imports — `import()` for heavy libraries used conditionally
286
+ - Analyze bundle — rollup-plugin-visualizer, webpack-bundle-analyzer
287
+ - Replace heavy deps — date-fns instead of moment, preact instead of react
288
+
289
+ ### Build Speed
290
+ - Use fast bundlers — Vite (esbuild + Rollup), Turbopack, SWC
291
+ - Incremental builds — only rebuild what changed
292
+ - Cache build artifacts — Turborepo, nx, build caches
293
+ - Parallelize — run lint, type-check, test concurrently
294
+
295
+ ## Language-Specific Tools
296
+
297
+ ### PHP / Laravel
298
+ - **Laravel Telescope** — Debug assistant (queries, requests, jobs, mail, cache)
299
+ - **Laravel Debugbar** — In-browser debug toolbar (queries, memory, time)
300
+ - **Laravel Octane** — High-performance server (Swoole/RoadRunner, persistent workers)
301
+ - **OPcache** — Bytecode caching (essential for production PHP)
302
+ - **Xdebug / SPX** — CPU and memory profiling
303
+ - **Eager loading** — `with()` to prevent N+1 queries (most common Laravel perf issue)
304
+ - **Route caching** — `artisan route:cache` for production
305
+ - **Config/view caching** — `artisan config:cache`, `artisan view:cache`
306
+ - **Queue heavy work** — Dispatch jobs for emails, reports, imports
307
+
308
+ ### JavaScript/TypeScript
309
+ - Chrome DevTools (Performance, Memory, Network tabs)
310
+ - Lighthouse for web performance auditing
311
+ - `perf_hooks` module for server-side timing
312
+ - Bundle analyzers for client-side optimization
313
+
314
+ ### Python
315
+ - `cProfile` / `py-spy` for CPU profiling
316
+ - `tracemalloc` for memory tracking
317
+ - `asyncio` for concurrent I/O
318
+ - `uvloop` for faster event loop
319
+
320
+ ### Go
321
+ - `pprof` for CPU and memory profiling (built-in)
322
+ - `go test -bench` for benchmarking (built-in)
323
+ - `go tool trace` for execution tracing
324
+ - Race detector: `go run -race`
325
+
326
+ ### Rust
327
+ - `cargo bench` with `criterion` for benchmarking
328
+ - `cargo flamegraph` for flame graphs
329
+ - `perf` for low-level profiling
330
+ - Zero-cost abstractions — most patterns have no runtime overhead
@@ -135,6 +135,39 @@ describe('Calculator', () => {
135
135
 
136
136
  ## Testing Tools by Language
137
137
 
138
+ ### PHP / Laravel
139
+ - **Pest** (recommended) — Elegant, expressive syntax built on PHPUnit
140
+ - **PHPUnit** — Standard PHP testing framework
141
+ - **Laravel Testing** — Built-in HTTP, database, queue, and mail testing
142
+ - **Laravel Dusk** — Browser testing with ChromeDriver
143
+ - **Mockery** — Mock objects for PHP
144
+ - **Faker** — Realistic test data generation (built into Laravel factories)
145
+
146
+ ```php
147
+ // Pest test (Laravel)
148
+ it('creates a user via API', function () {
149
+ $response = $this->postJson('/api/users', [
150
+ 'name' => 'John Doe',
151
+ 'email' => 'john@example.com',
152
+ ]);
153
+
154
+ $response->assertStatus(201)
155
+ ->assertJsonStructure(['id', 'name', 'email']);
156
+
157
+ $this->assertDatabaseHas('users', ['email' => 'john@example.com']);
158
+ });
159
+
160
+ // Laravel model factory + test
161
+ it('lists active users', function () {
162
+ User::factory()->count(3)->active()->create();
163
+ User::factory()->count(2)->inactive()->create();
164
+
165
+ $this->getJson('/api/users?status=active')
166
+ ->assertOk()
167
+ ->assertJsonCount(3, 'data');
168
+ });
169
+ ```
170
+
138
171
  ### JavaScript/TypeScript
139
172
  - Jest or Vitest (unit)
140
173
  - React Testing Library (components)