6 added, 6 removed. Audit B to B.
---
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.
created: 2026-02-20
updated: 2026-07-04
---
# /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](../../../docs/cli-requirements.md).
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 "${AGY_PLUGIN_ROOT}/lib/load-custom-guide.sh" cf-optimize
+ bash "<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.
```bash
# 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
1. Read `$ARGUMENTS` to identify what to optimize
2. 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:
+ - **Complex target** (e.g., "API is slow", "reduce page load time", cross-module performance): Launch the **cf-explorer agent** to map the system context. Call `invoke_subagent` with agent `cf-explorer`. Pass:
> Explore the codebase to understand the performance context for: [optimization target]
>
> Questions to answer:
>
> 1. What is the call chain / data flow for this operation?
> 2. What modules, services, or layers are involved?
> 3. Are there existing benchmarks, caching layers, or performance-related code?
> 4. 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
1. 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)
2. Run the baseline measurement **3 times** to get stable numbers (hyperfine does this automatically)
3. Record the results clearly:
- Metric name, value, unit
- Environment details (if relevant)
- Which tool was used (or "AI-only" if no tools)
4. Save baseline numbers — you will need them for comparison in Step 8
### Step 5: Analyze Bottlenecks
1. Profile the code path (add timing, use profiler if available)
2. Identify the actual bottleneck — do NOT guess:
- Where is time spent?
- What allocations are excessive?
- What operations are redundant?
3. Rank bottlenecks by impact (fix the biggest one first)
### Step 6: Plan the Optimization
1. For the top bottleneck, propose 1-2 optimization approaches
2. For each approach, state:
- **What changes:** specific files and functions
- **Expected improvement:** rough estimate
- **Risk:** what could break
3. Present the plan to the user and **wait for confirmation** before proceeding
4. 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"`.
+ Dispatch the **cf-implementer agent** to implement the optimization test-first. Call `invoke_subagent` with agent `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:
>
> 1. If tests exist for the target code, verify they pass before changing anything
> 2. If no tests exist, write tests first that verify current behavior
> 3. Implement the optimization — one change at a time
> 4. Run all tests — no regressions allowed
> 5. 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
- bash "${AGY_PLUGIN_ROOT}/lib/capture-later.sh" \
+ 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
1. Run the **exact same benchmark** from Step 4 (same tool, same parameters)
2. Run it **3 times** for stable numbers
3. Record the results
### Step 9: Compare and Report
1. Present a before/after comparison:
| Metric | Before | After | Change |
| -------- | ------- | ------- | ---------------------- |
| _metric_ | _value_ | _value_ | _% or absolute change_ |
2. If improvement is **< 5%**, note that it may be within noise — consider if the added complexity is worth it
3. If performance **regressed**, revert and try a different approach (go back to Step 6)
4. Summarize what was changed and why it helped
5. 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.
+ Automatically invoke `/cf-review` — activate the `cf-review` skill (type `/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).
+ > On Google Antigravity, cf-review uses the native Coding Friend multi-agent review and ignores the Claude-only `review.withCodex` second-opinion setting.
## 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.