| name | code-optimizer |
| description | Deep code optimization audit AND automatic fix execution using parallel specialist agents. Each agent hunts for performance anti-patterns, inefficiencies, duplication, and suboptimal code using pattern-based detection (Grep/Glob) WITHOUT reading the full source code first. Covers ALL domains: database queries, memory leaks, algorithmic complexity, concurrency, bundle size, dead code, I/O & network, rendering/UI, data structures, error handling, caching, build config, security-performance, logging, infrastructure, AND code simplification (duplication elimination, logic reduction, data compression, boilerplate extraction). With --fix flag, automatically implements fixes as parallel PRs in isolated git worktrees. Use when asked to: "optimize my code", "find performance issues", "audit code quality", "speed up my app", "find bottlenecks", "code review for performance", "find anti-patterns", "improve code efficiency", "reduce latency", "optimize performance", "code smell detection", "find slow code", "optimize this project", "performance audit", "code optimization", "simplify code", "reduce complexity", "reduce lines", "deduplicate", "remove duplication", "find redundancy", "consolidate code", "shrink codebase". Also triggers on: "optimizar codigo", "encontrar cuellos de botella", "mejorar rendimiento", "simplificar codigo", "reducir complejidad", "reducir lineas", "eliminar duplicacion".
|
Code Optimizer
Parallel multi-agent code optimization audit. Spawn 14 specialist agents simultaneously, each
hunting for a different class of problem using pattern-based detection. Optionally execute fixes
as parallel PRs in isolated git worktrees (with --fix).
Critical Principle: No Code Reading Before Analysis
Agents MUST NOT read source files before searching for patterns. Reading the code first causes
anchoring bias — the agent accepts the existing implementation as "reasonable" and misses
better alternatives. Instead, each agent:
- Read its assigned reference file from
references/ to load detection patterns
- Use Grep/Glob to scan the codebase for anti-patterns
- For each finding, ONLY THEN read the surrounding context (5-10 lines) to confirm the issue
- Propose the optimal solution based on best practices, NOT based on the existing code
Workflow
Step 1: Detect Stack
Use Glob to identify the project's tech stack:
**/package.json → Node.js/JS/TS (check for React, Next.js, Express, etc.)
**/requirements.txt, **/pyproject.toml, **/setup.py → Python
**/go.mod → Go
**/Cargo.toml → Rust
**/pom.xml, **/build.gradle → Java
**/Gemfile → Ruby
**/Dockerfile → Docker
**/*.sql → SQL
**/webpack.config.*, **/vite.config.*, **/tsconfig.json → Build tools
Step 2: Spawn 14 Parallel Agents
Launch ALL agents simultaneously using the Agent tool. Each agent receives:
- Its domain name and reference file path
- The detected tech stack (so it can focus on relevant patterns)
- The project root path
- Instructions to NOT read code files, only Grep/Glob for patterns
Agent definitions (spawn all 13 in a single message):
| # | Agent Name | Reference File | Focus |
|---|
| 1 | Database & Queries | references/database-queries.md | N+1 queries, SELECT *, missing indexes, ORM misuse, connection pooling |
| 2 | Memory & Resources | references/memory-resources.md | Memory leaks, unclosed resources, large allocations, string concat in loops |
| 3 | Algorithmic Complexity | references/algorithmic-complexity.md | O(n^2) patterns, unnecessary iterations, wrong data structures for lookups |
| 4 | Concurrency & Async | references/concurrency-async.md | Sequential awaits, blocking in async, race conditions, unbounded concurrency |
| 5 | Bundle & Dependencies | references/bundle-dependencies.md | Heavy imports, unused deps, duplicate libs, missing lazy loading |
| 6 | Dead Code & Redundancy | references/dead-code-redundancy.md | Unused exports, commented code, dead branches, duplicate logic |
| 7 | I/O & Network | references/io-network.md | Sequential requests, missing batching, no dedup, missing compression |
| 8 | Rendering & UI | references/rendering-ui.md | Re-renders, missing virtualization, layout thrashing, animation perf |
| 9 | Data Structures | references/data-structures.md | Wrong structures, unnecessary copies, inefficient serialization |
| 10 | Error & Resilience | references/error-resilience.md | Missing timeouts, swallowed errors, no retries, no circuit breakers |
| 11 | Caching & Memoization | references/caching-memoization.md | Missing memoization, cache without invalidation, redundant API calls |
| 12 | Build & Compilation | references/build-compilation.md | Dev code in prod, missing optimization flags, slow tests, Docker issues |
| 13 | Security-Performance | references/security-performance.md | Crypto misuse, missing rate limiting, ReDoS, SQL injection vectors |
| 14 | Simplification & Dedup | references/simplification-dedup.md | Duplicated functions, inline boilerplate, generated file compression, symmetric getters/setters, cross-file duplicate utilities |
Optional agents (spawn if relevant to detected stack):
- Logging & Observability (
references/logging-observability.md) — if logging framework detected
- Config & Infrastructure (
references/config-infra.md) — if Docker/deployment config detected
Agent Prompt Template
Each agent MUST receive this prompt structure:
You are a {DOMAIN_NAME} optimization specialist. Your job is to find performance
anti-patterns in the codebase at {PROJECT_ROOT}.
CRITICAL RULES:
1. DO NOT read source code files before searching. This avoids anchoring bias.
2. First, read your reference file: {SKILL_DIR}/references/{REFERENCE_FILE}
3. Use Grep and Glob to search for the patterns described in the reference file.
4. Only read 5-10 lines of context around each finding to confirm it's a real issue.
5. Skip patterns that don't match the project's stack: {DETECTED_STACK}
Tech stack detected: {DETECTED_STACK}
Project root: {PROJECT_ROOT}
For each finding, report:
- **File**: path:line_number
- **Pattern**: what anti-pattern was detected
- **Severity**: CRITICAL / HIGH / MEDIUM / LOW
- **Current code**: the problematic snippet (keep short)
- **Why it's slow**: brief explanation of the performance impact
- **Optimal fix**: the recommended solution (code snippet or approach)
- **Estimated impact**: qualitative improvement expected (e.g., "10x faster for large lists")
If you find 0 issues in your domain, report "No issues found" — this is a valid outcome.
Sort findings by severity (CRITICAL first).
Step 3: Consolidate Report
After all agents complete, consolidate their findings into a single prioritized report:
- Collect all findings from all agents
- Deduplicate (different agents may flag the same code for different reasons)
- Sort by severity: CRITICAL > HIGH > MEDIUM > LOW
- Group by file (so the user can fix file-by-file)
- Present the final report with:
- Executive summary: total findings by severity, top 3 most impactful
- Detailed findings table grouped by file
- Improvement plan: ordered list of fixes from highest to lowest impact
Report Format
# Code Optimization Audit Report
## Executive Summary
- **X** critical issues, **Y** high, **Z** medium, **W** low
- Top 3 highest-impact fixes:
1. [brief description] — [estimated impact]
2. [brief description] — [estimated impact]
3. [brief description] — [estimated impact]
## Findings by File
### `path/to/file.ts`
| # | Severity | Domain | Pattern | Fix | Impact |
|---|----------|--------|---------|-----|--------|
| 1 | CRITICAL | Database | N+1 query in loop | Use prefetch_related | 50x fewer queries |
| 2 | HIGH | Async | Sequential awaits | Use Promise.all | 3x faster |
[... for each file with findings ...]
## Improvement Plan
Priority-ordered steps to implement the fixes:
1. **[CRITICAL] Fix N+1 queries in `api/users.py`**
- Current: loop queries user.posts for each user
- Fix: add prefetch_related('posts') to queryset
- Impact: reduces N+1 to 2 queries
2. **[HIGH] Parallelize API calls in `services/sync.ts`**
- Current: 5 sequential await fetch() calls
- Fix: Promise.all([fetch1, fetch2, ...])
- Impact: ~5x faster sync operation
[... continue for all findings ...]
Step 4: Execute Fixes (only with --fix flag)
Skip this step unless the user passed --fix or explicitly asked to implement the fixes.
After presenting the report, group findings into independent units of work. Two findings are
independent if they touch different files (or non-overlapping regions of the same file).
Grouping rules:
- Findings in the same file that touch overlapping code go in the same unit
- Findings that create a shared utility used by multiple files go in one unit
- Everything else is independent
Execution:
- Present the grouped units to the user for confirmation
- Launch all independent units as parallel agents, each in its own worktree:
isolation: "worktree", run_in_background: true, mode: "bypassPermissions"
- Each agent must:
- Create a descriptive branch (e.g.,
refactor/extract-retry-utils)
- Implement the fix
- Run tests/linting if applicable to verify the change
- Commit with a clear conventional commit message
- Push the branch
- Open a PR to
main using gh pr create with a thorough PR description (see PR requirements below)
- Return the PR URL
- Report PR URLs as agents complete
- Final summary table with all PRs
PR requirements for fix execution:
Every PR must fill in all sections — no placeholders, no TODOs, no "N/A" hand-waves.
- What: One paragraph stating exactly what the PR does. Name the functions, components, or behaviors that change.
- Why: The motivation from the audit findings. Reference the severity and domain. For bugs: describe the broken behavior. For perf fixes: describe the measured/estimated impact.
- How: Walk through the implementation. Explain the approach, key decisions, and any trade-offs.
- Key changes: Bulleted list of files changed with a description of each change.
- Testing: Concrete verification steps. What commands were run and what was their output? Include actual terminal output in fenced code blocks — test results, linting output, build logs.
- Risk & rollback: Honest assessment of what could break and how to revert.
PR title: conventional commit style, under 70 characters (e.g., perf: batch N+1 queries in user endpoint).
Formatting the gh pr create call:
gh pr create --title "perf: short description" --body "$(cat <<'EOF'
## What
Concrete description of what this PR does...
## Why
Motivation from audit findings...
## How
Implementation walkthrough...
### Key changes
- `src/foo.ts` — description
- `src/bar.ts` — description
## Testing
- [x] Tests pass:
$ npm test
PASS src/queue.test.ts (3 tests, 0 failures)
- [x] Manual verification: describe what was checked
## Risk & rollback
Low risk — isolated change to X with no shared state.
EOF
)"
Agent prompt for fix execution:
Each agent prompt MUST include all of the following. The agent has zero context beyond what you provide.
You are working in an isolated git worktree. Your job is to implement a single optimization fix, verify it, and open a PR.
## Task
**What**: {DESCRIPTION}
**Why**: {ROOT_CAUSE_FROM_AUDIT} (Severity: {SEVERITY}, Domain: {DOMAIN})
**Audit finding**: {PATTERN_AND_IMPACT}
## Location
**Files to modify**: {FILE_PATHS_AND_LINES}
**Files to read for context**: {RELATED_FILES}
## Approach
{PROPOSED_FIX_FROM_AUDIT — step-by-step with code snippets}
## Branch
Create branch: `{BRANCH_NAME}` (e.g., `perf/batch-user-queries`)
## Verification
{What tests to run, what to check manually, what edge cases to consider}
## PR
- Push the branch
- Open a PR to `main` using `gh pr create`
- Use the PR template structure (What/Why/How/Key changes/Testing/Risk)
- Fill in EVERY section with real content — no placeholders
- Include actual terminal output from test/build runs in the Testing section
- PR title: conventional commit format, under 70 characters
- Return the PR URL as your final output
Arguments
- No arguments: audit only (report findings, no fixes)
--fix: audit + implement all fixes as parallel PRs
--fix-critical: audit + implement only CRITICAL and HIGH severity fixes
--simplify: only run the Simplification & Dedup agent (agent #14), skip performance agents
--simplify --fix: run simplification audit, then implement fixes as PRs
path/to/dir: limit audit scope to a specific directory