| name | cf-optimize |
| description | Structured optimization workflow — baseline, analyze, optimize, measure, compare. Auto-invoke this skill when the conversation involves performance optimization, speed improvements, or the user mentions something is slow — e.g. "this is slow", "make it faster", "optimize", "performance", "bottleneck", "too many queries", "high latency", "memory leak", "reduce load time", "speed up", "takes too long", "timeout", "O(n²)", "N+1". Do NOT auto-invoke for minor refactors or style changes that are not performance-related.
|
| user-invocable | true |
| argument-hint | [target to optimize] |
| created | "2026-02-20T00:00:00.000Z" |
| updated | "2026-07-04T00:00:00.000Z" |
| model | opus |
/cf-optimize
CLI Requirement: OPTIONAL — Uses the memory MCP from coding-friend-cli for fast indexed search and storage. Without the CLI: falls back to grep over docs/memory/ and direct file writes. Full functionality preserved, slower memory recall. See CLI requirements.
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
Custom guide — auto-loaded below (if the raw command shows instead of its output, run it yourself):
bash "${CLAUDE_PLUGIN_ROOT}/lib/load-custom-guide.sh" cf-optimize
If output is not empty, integrate returned sections: ## Before → before first step, ## Rules → apply throughout, ## After → after final step.
Step 1: Detect Available Tools
Run quick availability checks for profiling/benchmarking tools. Store the result for use in later steps.
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"
command -v hyperfine >/dev/null 2>&1 && echo "TOOL:hyperfine"
command -v perf >/dev/null 2>&1 && echo "TOOL:perf"
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): Launch the cf-explorer agent to map the system context. Use the Agent tool with subagent_type: "coding-friend:cf-explorer". 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 the cf-implementer agent to implement the optimization test-first. Use the Agent tool with subagent_type: "coding-friend:cf-implementer".
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
Automatically invoke /cf-review — use the Skill tool with skill name coding-friend:cf-review. Do NOT ask the user first, just run it.
If review.withCodex: true is set in the config, cf-review automatically runs a Codex second-opinion review alongside Claude's 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.