/cf-optimize
Optimize: $ARGUMENTS
Purpose
Structured workflow for optimizing existing features, algorithms, or performance-critical code. Ensures every optimization is measured before and after so you know it actually helped.
Workflow
Step 0: Custom Guide
bash "<plugin-root>/lib/load-custom-guide.sh" cf-optimize
If the block above printed anything, apply only the ## Before, ## Rules, and ## After sections; if it shows the raw command instead of output, re-run that exact load-custom-guide.sh fence now.
Step 1: Detect Available Tools
Run quick availability checks for profiling/benchmarking tools. Store the result for use in later steps.
# Node.js / JavaScript
command -v clinic >/dev/null 2>&1 && echo "TOOL:clinic"
command -v 0x >/dev/null 2>&1 && echo "TOOL:0x"
npx lighthouse --version >/dev/null 2>&1 && echo "TOOL:lighthouse"
# General
command -v hyperfine >/dev/null 2>&1 && echo "TOOL:hyperfine"
command -v perf >/dev/null 2>&1 && echo "TOOL:perf"
# Web / Bundle
command -v webpack-bundle-analyzer >/dev/null 2>&1 && echo "TOOL:webpack-bundle-analyzer"
If no tools are found, note this and proceed in AI-only mode — all profiling will be done via code instrumentation and manual timing. Results in AI-only mode are estimates; flag this clearly in the final report.
Step 2: Understand the Target
- Read
$ARGUMENTS to identify what to optimize
- If the target is vague, ask the user to clarify what "better" means:
- Faster execution time?
- Lower memory usage?
- Fewer API calls / network requests?
- Smaller bundle size?
- Better algorithmic complexity?
Step 3: Gather Context (conditional — based on target complexity)
Assess whether the optimization target is simple (single file/function, clear scope) or complex (cross-module, unclear bottleneck location, system-level):
Simple target (e.g., "optimize this function"): Search memory only (if memory_search tool is available). Call memory_search with: { "query": "<optimization target keywords — e.g. performance, latency, bottleneck, caching>", "limit": 5 }. Then read the relevant source files directly.
Complex target (e.g., "API is slow", "reduce page load time", cross-module performance): Dispatch cf-explorer to map the system context. Pass:
Explore the codebase to understand the performance context for: [optimization target]
Questions to answer:
- What is the call chain / data flow for this operation?
- What modules, services, or layers are involved?
- Are there existing benchmarks, caching layers, or performance-related code?
- What dependencies (DB queries, API calls, I/O) are in the critical path?
Note: cf-explorer already checks memory internally — do NOT call memory_search separately when using cf-explorer.
Memory and explorer results are hints — always verify against actual code and measurements.
Step 4: Baseline Measurement
- Identify or create a benchmark/measurement. Prefer detected tools from Step 1:
- hyperfine →
hyperfine --warmup 3 '<command>' (automatic 3-run avg + stats)
- clinic →
clinic doctor -- node <script> (Node.js flamegraph + I/O analysis)
- 0x →
0x <script> (flamegraph for hot path detection)
- lighthouse →
lighthouse <url> --output json --quiet (web performance audit)
- perf →
perf stat <command> (CPU counters on Linux)
- No tools → create a simple benchmark (manual timing,
console.time(), memory snapshots)
- Run the baseline measurement 3 times to get stable numbers (hyperfine does this automatically)
- Record the results clearly:
- Metric name, value, unit
- Environment details (if relevant)
- Which tool was used (or "AI-only" if no tools)
- Save baseline numbers — you will need them for comparison in Step 8
Step 5: Analyze Bottlenecks
- Profile the code path (add timing, use profiler if available)
- Identify the actual bottleneck — do NOT guess:
- Where is time spent?
- What allocations are excessive?
- What operations are redundant?
- Rank bottlenecks by impact (fix the biggest one first)
Step 6: Plan the Optimization
- For the top bottleneck, propose 1-2 optimization approaches
- For each approach, state:
- What changes: specific files and functions
- Expected improvement: rough estimate
- Risk: what could break
- Present the plan to the user and wait for confirmation before proceeding
- Do NOT optimize multiple things at once — one change at a time
Step 7: Implement (via cf-implementer agent)
Dispatch cf-implementer to implement the optimization test-first.
Prompt template:
Implement the following optimization:
Optimization: [approach confirmed in Step 6]
Target: [specific files and functions]
Bottleneck: [from Step 5 analysis]
Baseline: [measurements from Step 4]
Existing tests: [test file paths]
Test framework: [framework and conventions]
Requirements:
- If tests exist for the target code, verify they pass before changing anything
- If no tests exist, write tests first that verify current behavior
- Implement the optimization — one change at a time
- Run all tests — no regressions allowed
- Report: what was changed, test results, any concerns
Review the cf-implementer's report. If tests failed or the agent reported concerns, address them before proceeding. Then load the cf-verification skill and run the full checklist before measuring.
Capturing out-of-scope side-effects
While optimizing, if you notice a problem unrelated to the performance target that is non-trivial (fixing it inline would muddy the before/after measurement or expand scope), do NOT fix it now. Record it for later, then continue:
bash "<plugin-root>/lib/capture-later.sh" \
--name "<short title>" --description "<what & where — enough to act on cold>" \
--source cf-optimize [--slug <task slug, if one exists>] [--problem "<the optimization target>"]
This writes <docsDir>/later/YYYY-MM-DD-<name>.md with frontmatter (slug, problem, conversation_id). This is an in-repo audit trail, independent of the spawn_task tool.
Step 8: Measure After
- Run the exact same benchmark from Step 4 (same tool, same parameters)
- Run it 3 times for stable numbers
- Record the results
Step 9: Compare and Report
- Present a before/after comparison:
| Metric |
Before |
After |
Change |
| metric |
value |
value |
% or absolute change |
- If improvement is < 5%, note that it may be within noise — consider if the added complexity is worth it
- If performance regressed, revert and try a different approach (go back to Step 6)
- Summarize what was changed and why it helped
- If running in AI-only mode (no profiling tools), add a disclaimer: "Measurements are code-instrumented estimates — install
hyperfine or clinic for precise benchmarks."
Step 10: Auto-Review
Load /cf-review now. Do not ask first.
If review.withCodex: true is set in the config, cf-review automatically runs a Codex second-opinion review alongside the in-session review and merges both — no flag needed here (cf-review reads the config itself).
Completion Protocol
- DONE — Optimization verified with measurements. Show: before/after comparison table, % improvement, files changed.
- DONE_WITH_CONCERNS — Optimization applied but improvement is marginal (< 5%) or has trade-offs. Show: numbers + trade-off analysis.
- BLOCKED — Cannot optimize. Show: why (can't measure, no clear bottleneck, would require architectural change). Suggest next action.
Rules
- ALWAYS measure before AND after — no "it should be faster" claims
- One optimization at a time — never batch multiple changes
- Tests must pass throughout — run existing tests after every change
- Get user confirmation before implementing (Step 6)
- If you cannot measure it, ask the user how to measure it before proceeding
- Revert if the optimization makes things worse or breaks tests
- Prefer real profiling tools over AI estimation when available
Tool Integration
| Tool |
Domain |
Install |
Used For |
hyperfine |
General |
brew install hyperfine / cargo install hyperfine |
Precise CLI benchmarking with warmup and statistical analysis |
clinic |
Node.js |
npm i -g clinic |
Flamegraphs, I/O profiling, bubbleprof |
0x |
Node.js |
npm i -g 0x |
Lightweight flamegraph generation |
lighthouse |
Web |
npm i -g lighthouse |
Web performance audit (LCP, FID, CLS) |
perf |
Linux |
System package |
CPU counters, cache misses, syscall profiling |
webpack-bundle-analyzer |
JS bundles |
npm i -D webpack-bundle-analyzer |
Bundle size visualization |
When no tools are detected, cf-optimize falls back to AI-only mode: manual console.time(), process.memoryUsage(), and code-level instrumentation. Results are clearly marked as estimates.
Plugin root: the PLUGIN_ROOT: path in the session bootstrap context (HOST: devin), or the parent of the skills/ folder that contains this SKILL.md. Replace <plugin-root> with it when running bundled scripts.
1---2name: cf-optimize-43description: >4 Structured performance work — baseline, analyze, optimize, measure, compare.5 TRIGGER — "this is slow", "make it faster", "optimize", "performance",6 "bottleneck", "too many queries", "high latency", "memory leak", "speed up",7 "timeout", "N+1", or any request to reduce time, memory, or query count with8 numbers to prove it. SKIP — minor refactors, readability or style changes, and9 correctness bugs that are not performance-related (use cf-fix).10user-invocable: true11argument-hint: "[target to optimize]"12created: 2026-02-2013updated: 2026-09-0914model: opus15metadata:16 source: https://skillmd.com/skills/dinhanhthi/cf-optimize-417---1819# /cf-optimize2021Optimize: **$ARGUMENTS**2223## Purpose2425Structured workflow for optimizing existing features, algorithms, or performance-critical code. Ensures every optimization is measured before and after so you know it actually helped.2627## Workflow2829### Step 0: Custom Guide3031```!32bash "<plugin-root>/lib/load-custom-guide.sh" cf-optimize33```3435If the block above printed anything, apply only the `## Before`, `## Rules`, and `## After` sections; if it shows the raw command instead of output, re-run that exact `load-custom-guide.sh` fence now.3637### Step 1: Detect Available Tools3839Run quick availability checks for profiling/benchmarking tools. Store the result for use in later steps.4041```bash42# Node.js / JavaScript43command -v clinic >/dev/null 2>&1 && echo "TOOL:clinic"44command -v 0x >/dev/null 2>&1 && echo "TOOL:0x"45npx lighthouse --version >/dev/null 2>&1 && echo "TOOL:lighthouse"4647# General48command -v hyperfine >/dev/null 2>&1 && echo "TOOL:hyperfine"49command -v perf >/dev/null 2>&1 && echo "TOOL:perf"5051# Web / Bundle52command -v webpack-bundle-analyzer >/dev/null 2>&1 && echo "TOOL:webpack-bundle-analyzer"53```5455If no tools are found, note this and proceed in **AI-only mode** — all profiling will be done via code instrumentation and manual timing. Results in AI-only mode are estimates; flag this clearly in the final report.5657### Step 2: Understand the Target58591. Read `$ARGUMENTS` to identify what to optimize602. If the target is vague, ask the user to clarify what "better" means:61 - Faster execution time?62 - Lower memory usage?63 - Fewer API calls / network requests?64 - Smaller bundle size?65 - Better algorithmic complexity?6667### Step 3: Gather Context (conditional — based on target complexity)6869Assess whether the optimization target is **simple** (single file/function, clear scope) or **complex** (cross-module, unclear bottleneck location, system-level):7071- **Simple target** (e.g., "optimize this function"): Search memory only (if `memory_search` tool is available). Call `memory_search` with: `{ "query": "<optimization target keywords — e.g. performance, latency, bottleneck, caching>", "limit": 5 }`. Then read the relevant source files directly.7273- **Complex target** (e.g., "API is slow", "reduce page load time", cross-module performance): Dispatch `cf-explorer` to map the system context. Pass:7475 > Explore the codebase to understand the performance context for: [optimization target]76 >77 > Questions to answer:78 >79 > 1. What is the call chain / data flow for this operation?80 > 2. What modules, services, or layers are involved?81 > 3. Are there existing benchmarks, caching layers, or performance-related code?82 > 4. What dependencies (DB queries, API calls, I/O) are in the critical path?8384 **Note:** cf-explorer already checks memory internally — do NOT call `memory_search` separately when using cf-explorer.8586Memory and explorer results are **hints** — always verify against actual code and measurements.8788### Step 4: Baseline Measurement89901. Identify or create a benchmark/measurement. **Prefer detected tools** from Step 1:91 - **hyperfine** → `hyperfine --warmup 3 '<command>'` (automatic 3-run avg + stats)92 - **clinic** → `clinic doctor -- node <script>` (Node.js flamegraph + I/O analysis)93 - **0x** → `0x <script>` (flamegraph for hot path detection)94 - **lighthouse** → `lighthouse <url> --output json --quiet` (web performance audit)95 - **perf** → `perf stat <command>` (CPU counters on Linux)96 - **No tools** → create a simple benchmark (manual timing, `console.time()`, memory snapshots)972. Run the baseline measurement **3 times** to get stable numbers (hyperfine does this automatically)983. Record the results clearly:99 - Metric name, value, unit100 - Environment details (if relevant)101 - Which tool was used (or "AI-only" if no tools)1024. Save baseline numbers — you will need them for comparison in Step 8103104### Step 5: Analyze Bottlenecks1051061. Profile the code path (add timing, use profiler if available)1072. Identify the actual bottleneck — do NOT guess:108 - Where is time spent?109 - What allocations are excessive?110 - What operations are redundant?1113. Rank bottlenecks by impact (fix the biggest one first)112113### Step 6: Plan the Optimization1141151. For the top bottleneck, propose 1-2 optimization approaches1162. For each approach, state:117 - **What changes:** specific files and functions118 - **Expected improvement:** rough estimate119 - **Risk:** what could break1203. Present the plan to the user and **wait for confirmation** before proceeding1214. Do NOT optimize multiple things at once — one change at a time122123### Step 7: Implement (via cf-implementer agent)124125Dispatch `cf-implementer` to implement the optimization test-first.126127**Prompt template:**128129> Implement the following optimization:130>131> **Optimization:** [approach confirmed in Step 6]132> **Target:** [specific files and functions]133> **Bottleneck:** [from Step 5 analysis]134> **Baseline:** [measurements from Step 4]135> **Existing tests:** [test file paths]136> **Test framework:** [framework and conventions]137>138> Requirements:139>140> 1. If tests exist for the target code, verify they pass before changing anything141> 2. If no tests exist, write tests first that verify current behavior142> 3. Implement the optimization — one change at a time143> 4. Run all tests — no regressions allowed144> 5. Report: what was changed, test results, any concerns145146Review the cf-implementer's report. If tests failed or the agent reported concerns, address them before proceeding. Then load the `cf-verification` skill and run the full checklist before measuring.147148#### Capturing out-of-scope side-effects149150While optimizing, if you notice a problem **unrelated to the performance target** that is non-trivial (fixing it inline would muddy the before/after measurement or expand scope), do NOT fix it now. Record it for later, then continue:151152```bash153bash "<plugin-root>/lib/capture-later.sh" \154 --name "<short title>" --description "<what & where — enough to act on cold>" \155 --source cf-optimize [--slug <task slug, if one exists>] [--problem "<the optimization target>"]156```157158This writes `<docsDir>/later/YYYY-MM-DD-<name>.md` with frontmatter (slug, problem, conversation_id). This is an in-repo audit trail, independent of the `spawn_task` tool.159160### Step 8: Measure After1611621. Run the **exact same benchmark** from Step 4 (same tool, same parameters)1632. Run it **3 times** for stable numbers1643. Record the results165166### Step 9: Compare and Report1671681. Present a before/after comparison:169170| Metric | Before | After | Change |171| -------- | ------- | ------- | ---------------------- |172| _metric_ | _value_ | _value_ | _% or absolute change_ |1731742. If improvement is **< 5%**, note that it may be within noise — consider if the added complexity is worth it1753. If performance **regressed**, revert and try a different approach (go back to Step 6)1764. Summarize what was changed and why it helped1775. If running in **AI-only mode** (no profiling tools), add a disclaimer: "Measurements are code-instrumented estimates — install `hyperfine` or `clinic` for precise benchmarks."178179### Step 10: Auto-Review180181Load `/cf-review` now. Do not ask first.182183> If `review.withCodex: true` is set in the config, cf-review automatically runs a Codex second-opinion review alongside the in-session review and merges both — no flag needed here (cf-review reads the config itself).184185## Completion Protocol186187- **DONE** — Optimization verified with measurements. Show: before/after comparison table, % improvement, files changed.188- **DONE_WITH_CONCERNS** — Optimization applied but improvement is marginal (< 5%) or has trade-offs. Show: numbers + trade-off analysis.189- **BLOCKED** — Cannot optimize. Show: why (can't measure, no clear bottleneck, would require architectural change). Suggest next action.190191## Rules192193- ALWAYS measure before AND after — no "it should be faster" claims194- One optimization at a time — never batch multiple changes195- Tests must pass throughout — run existing tests after every change196- Get user confirmation before implementing (Step 6)197- If you cannot measure it, ask the user how to measure it before proceeding198- Revert if the optimization makes things worse or breaks tests199- Prefer real profiling tools over AI estimation when available200201## Tool Integration202203| Tool | Domain | Install | Used For |204| ------------------------- | ---------- | ---------------------------------------------------- | ------------------------------------------------------------- |205| `hyperfine` | General | `brew install hyperfine` / `cargo install hyperfine` | Precise CLI benchmarking with warmup and statistical analysis |206| `clinic` | Node.js | `npm i -g clinic` | Flamegraphs, I/O profiling, bubbleprof |207| `0x` | Node.js | `npm i -g 0x` | Lightweight flamegraph generation |208| `lighthouse` | Web | `npm i -g lighthouse` | Web performance audit (LCP, FID, CLS) |209| `perf` | Linux | System package | CPU counters, cache misses, syscall profiling |210| `webpack-bundle-analyzer` | JS bundles | `npm i -D webpack-bundle-analyzer` | Bundle size visualization |211212When no tools are detected, cf-optimize falls back to **AI-only mode**: manual `console.time()`, `process.memoryUsage()`, and code-level instrumentation. Results are clearly marked as estimates.213214> Plugin root: the `PLUGIN_ROOT:` path in the session bootstrap context (HOST: devin), or the parent of the `skills/` folder that contains this SKILL.md. Replace `<plugin-root>` with it when running bundled scripts.