/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 "${CLAUDE_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 "${CLAUDE_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.
1---2name: cf-optimize3description: Structured performance work — baseline, analyze, optimize, measure, compare. TRIGGER — "this is slow", "make it faster", "optimize", "performance", "bottleneck", "too many queries", "high latency", "memory leak", "speed up", "timeout", "N+1", or any request to reduce time, memory, or query count with numbers to prove it. SKIP — minor refactors, readability or style changes, and correctness bugs that are not performance-related (use cf-fix).4---56# /cf-optimize78Optimize: **$ARGUMENTS**910## Purpose1112Structured workflow for optimizing existing features, algorithms, or performance-critical code. Ensures every optimization is measured before and after so you know it actually helped.1314## Workflow1516### Step 0: Custom Guide1718```!19bash "${CLAUDE_PLUGIN_ROOT}/lib/load-custom-guide.sh" cf-optimize20```2122If 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.2324### Step 1: Detect Available Tools2526Run quick availability checks for profiling/benchmarking tools. Store the result for use in later steps.2728```bash29# Node.js / JavaScript30command -v clinic >/dev/null 2>&1 && echo "TOOL:clinic"31command -v 0x >/dev/null 2>&1 && echo "TOOL:0x"32npx lighthouse --version >/dev/null 2>&1 && echo "TOOL:lighthouse"3334# General35command -v hyperfine >/dev/null 2>&1 && echo "TOOL:hyperfine"36command -v perf >/dev/null 2>&1 && echo "TOOL:perf"3738# Web / Bundle39command -v webpack-bundle-analyzer >/dev/null 2>&1 && echo "TOOL:webpack-bundle-analyzer"40```4142If 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.4344### Step 2: Understand the Target45461. Read `$ARGUMENTS` to identify what to optimize472. If the target is vague, ask the user to clarify what "better" means:48 - Faster execution time?49 - Lower memory usage?50 - Fewer API calls / network requests?51 - Smaller bundle size?52 - Better algorithmic complexity?5354### Step 3: Gather Context (conditional — based on target complexity)5556Assess whether the optimization target is **simple** (single file/function, clear scope) or **complex** (cross-module, unclear bottleneck location, system-level):5758- **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.5960- **Complex target** (e.g., "API is slow", "reduce page load time", cross-module performance): Dispatch `cf-explorer` to map the system context. Pass:6162 > Explore the codebase to understand the performance context for: [optimization target]63 >64 > Questions to answer:65 >66 > 1. What is the call chain / data flow for this operation?67 > 2. What modules, services, or layers are involved?68 > 3. Are there existing benchmarks, caching layers, or performance-related code?69 > 4. What dependencies (DB queries, API calls, I/O) are in the critical path?7071 **Note:** cf-explorer already checks memory internally — do NOT call `memory_search` separately when using cf-explorer.7273Memory and explorer results are **hints** — always verify against actual code and measurements.7475### Step 4: Baseline Measurement76771. Identify or create a benchmark/measurement. **Prefer detected tools** from Step 1:78 - **hyperfine** → `hyperfine --warmup 3 '<command>'` (automatic 3-run avg + stats)79 - **clinic** → `clinic doctor -- node <script>` (Node.js flamegraph + I/O analysis)80 - **0x** → `0x <script>` (flamegraph for hot path detection)81 - **lighthouse** → `lighthouse <url> --output json --quiet` (web performance audit)82 - **perf** → `perf stat <command>` (CPU counters on Linux)83 - **No tools** → create a simple benchmark (manual timing, `console.time()`, memory snapshots)842. Run the baseline measurement **3 times** to get stable numbers (hyperfine does this automatically)853. Record the results clearly:86 - Metric name, value, unit87 - Environment details (if relevant)88 - Which tool was used (or "AI-only" if no tools)894. Save baseline numbers — you will need them for comparison in Step 89091### Step 5: Analyze Bottlenecks92931. Profile the code path (add timing, use profiler if available)942. Identify the actual bottleneck — do NOT guess:95 - Where is time spent?96 - What allocations are excessive?97 - What operations are redundant?983. Rank bottlenecks by impact (fix the biggest one first)99100### Step 6: Plan the Optimization1011021. For the top bottleneck, propose 1-2 optimization approaches1032. For each approach, state:104 - **What changes:** specific files and functions105 - **Expected improvement:** rough estimate106 - **Risk:** what could break1073. Present the plan to the user and **wait for confirmation** before proceeding1084. Do NOT optimize multiple things at once — one change at a time109110### Step 7: Implement (via cf-implementer agent)111112Dispatch `cf-implementer` to implement the optimization test-first.113114**Prompt template:**115116> Implement the following optimization:117>118> **Optimization:** [approach confirmed in Step 6]119> **Target:** [specific files and functions]120> **Bottleneck:** [from Step 5 analysis]121> **Baseline:** [measurements from Step 4]122> **Existing tests:** [test file paths]123> **Test framework:** [framework and conventions]124>125> Requirements:126>127> 1. If tests exist for the target code, verify they pass before changing anything128> 2. If no tests exist, write tests first that verify current behavior129> 3. Implement the optimization — one change at a time130> 4. Run all tests — no regressions allowed131> 5. Report: what was changed, test results, any concerns132133Review 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.134135#### Capturing out-of-scope side-effects136137While 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:138139```bash140bash "${CLAUDE_PLUGIN_ROOT}/lib/capture-later.sh" \141 --name "<short title>" --description "<what & where — enough to act on cold>" \142 --source cf-optimize [--slug <task slug, if one exists>] [--problem "<the optimization target>"]143```144145This 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.146147### Step 8: Measure After1481491. Run the **exact same benchmark** from Step 4 (same tool, same parameters)1502. Run it **3 times** for stable numbers1513. Record the results152153### Step 9: Compare and Report1541551. Present a before/after comparison:156157| Metric | Before | After | Change |158| -------- | ------- | ------- | ---------------------- |159| _metric_ | _value_ | _value_ | _% or absolute change_ |1601612. If improvement is **< 5%**, note that it may be within noise — consider if the added complexity is worth it1623. If performance **regressed**, revert and try a different approach (go back to Step 6)1634. Summarize what was changed and why it helped1645. If running in **AI-only mode** (no profiling tools), add a disclaimer: "Measurements are code-instrumented estimates — install `hyperfine` or `clinic` for precise benchmarks."165166### Step 10: Auto-Review167168Load `/cf-review` now. Do not ask first.169170> 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).171172## Completion Protocol173174- **DONE** — Optimization verified with measurements. Show: before/after comparison table, % improvement, files changed.175- **DONE_WITH_CONCERNS** — Optimization applied but improvement is marginal (< 5%) or has trade-offs. Show: numbers + trade-off analysis.176- **BLOCKED** — Cannot optimize. Show: why (can't measure, no clear bottleneck, would require architectural change). Suggest next action.177178## Rules179180- ALWAYS measure before AND after — no "it should be faster" claims181- One optimization at a time — never batch multiple changes182- Tests must pass throughout — run existing tests after every change183- Get user confirmation before implementing (Step 6)184- If you cannot measure it, ask the user how to measure it before proceeding185- Revert if the optimization makes things worse or breaks tests186- Prefer real profiling tools over AI estimation when available187188## Tool Integration189190| Tool | Domain | Install | Used For |191| ------------------------- | ---------- | ---------------------------------------------------- | ------------------------------------------------------------- |192| `hyperfine` | General | `brew install hyperfine` / `cargo install hyperfine` | Precise CLI benchmarking with warmup and statistical analysis |193| `clinic` | Node.js | `npm i -g clinic` | Flamegraphs, I/O profiling, bubbleprof |194| `0x` | Node.js | `npm i -g 0x` | Lightweight flamegraph generation |195| `lighthouse` | Web | `npm i -g lighthouse` | Web performance audit (LCP, FID, CLS) |196| `perf` | Linux | System package | CPU counters, cache misses, syscall profiling |197| `webpack-bundle-analyzer` | JS bundles | `npm i -D webpack-bundle-analyzer` | Bundle size visualization |198199When 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.