Optimize
Autonomous optimization loop — hill-climb any target. Code with metrics, or skills/prompts/agents with LLM-as-judge eval. USE WHEN optimize, autoresearch, hill climb, improve metric, reduce latency, improve performance, benchmark optimization, bundle size, page speed, autonomous improvement loop, optimize skill, optimize prompt, improve quality, eval mode.
What this skill does
# /optimize — Autonomous Optimization v2
Run an autonomous optimization loop against **any target**. Two modes:
- **Metric mode** — code targets with a shell command that produces a number (the original)
- **Eval mode** — skills, prompts, agents, or any text target judged by LLM-as-judge binary evals
The agent modifies the target, measures the result, keeps improvements, discards failures, and repeats.
Inspired by Karpathy's [autoresearch](https://github.com/karpathy/autoresearch) and extended with LLM-as-judge evaluation.
## Invocation
### Metric Mode (code targets)
```
/optimize --metric "lighthouse_score" --higher-is-better \
--measure "npx lighthouse http://localhost:3000 --output=json" \
--extract "jq '.categories.performance.score * 100' lighthouse.json" \
--files "src/**/*.tsx,src/**/*.css" \
--budget 120
/optimize --resume # Resume a previous optimization loop
/optimize --status # Show results summary from last/current run
```
### Eval Mode (skill/prompt/agent targets)
```
/optimize --target "~/.claude/skills/ExtractWisdom"
/optimize --target "~/.claude/skills/Research/Workflows/QuickResearch.md"
/optimize --target "prompts/my-prompt.md"
/optimize --target "~/.claude/skills/ExtractWisdom" --max-experiments 20
```
In eval mode, the system automatically:
1. Detects the target type (skill, prompt, agent, code, function)
2. Reads the target to understand its purpose and constraints
3. Generates 3-6 binary eval criteria and 3-5 test inputs
4. Presents criteria + inputs for your approval before starting
5. Runs the optimization loop using LLM-as-judge scoring
6. Presents a recommendation (apply/reject/partial) when done
## What Happens
This skill triggers the PAI Algorithm in `mode: optimize`:
1. **OBSERVE** — Define or auto-detect the target, set eval_mode
2. **THINK** — Analyze codebase/skill, generate hypothesis queue
3. **PLAN** — Prioritize hypotheses by expected impact
4. **BUILD** — Phase 0: TARGET ANALYSIS (see `optimize-loop.md`)
- Detect target type, auto-generate eval criteria (eval mode), set up sandbox, baseline
5. **EXECUTE** — The autonomous loop (`optimize-loop.md`):
- Hypothesize → Modify target → Measure (metric or eval) → Keep/Revert → Repeat
- Metric mode: ~12 experiments/hour (at 5-min budget)
- Eval mode: ~6-8 experiments/hour (multi-run judging is slower)
6. **VERIFY** — Phase 9: RECOMMEND — diff, summary, apply/reject/partial options
7. **LEARN** — Phase 10: EXTRACT LEARNINGS — what worked, what didn't, structured insights
## Arguments — Metric Mode
| Argument | Required | Default | Description |
|----------|----------|---------|-------------|
| `--metric NAME` | yes | | Human-readable metric name |
| `--measure COMMAND` | yes | | Shell command that produces the metric |
| `--files GLOB` | yes | | Files the agent may modify (comma-separated) |
| `--higher-is-better` | | (default) | Higher metric values are better |
| `--lower-is-better` | | | Lower metric values are better |
| `--extract COMMAND` | | Last number in stdout | Extract metric from output |
| `--budget SECONDS` | | 300 | Time budget per experiment |
| `--target VALUE` | | none | Stop when metric reaches this value |
| `--max-experiments N` | | none | Stop after N experiments |
| `--locked GLOB` | | none | Files the agent must NOT modify |
| `--constraints TEXT` | | none | Additional rules (e.g., "tests must pass") |
## Arguments — Eval Mode
| Argument | Required | Default | Description |
|----------|----------|---------|-------------|
| `--target PATH` | yes | | Path to skill directory, prompt file, or agent definition |
| `--max-experiments N` | | none | Stop after N experiments |
| `--runs N` | | 3 | Runs per experiment (more = more reliable, slower) |
| `--criteria "Q1" "Q2"` | | auto-generated | Override auto-generated eval criteria |
| `--inputs "I1" "I2"` | | auto-generated | Override auto-generated test inputs |
| `--budget SECONDS` | | 300 | Time budget per experiment |
## Shared Arguments
| Argument | Description |
|----------|-------------|
| `--resume` | Resume a previous optimization run |
| `--status` | Show results summary |
## Algorithm Integration
When `/optimize` is invoked, the Algorithm enters with `mode: optimize` in the ISA frontmatter. The eval_mode is set based on arguments:
- `--measure` provided → `eval_mode: metric` (git branch sandbox)
- `--target` provided → `eval_mode: eval` (directory sandbox)
ISC criteria become **guard rails** — assertions that must hold true across ALL experiments. Guard rails must REMAIN satisfied perpetually. A violation triggers automatic revert regardless of score improvement.
**Reference files:**
- `~/.claude/PAI/ALGORITHM/optimize-loop.md` — the full loop protocol
- `~/.claude/PAI/ALGORITHM/eval-guide.md` — how to write good eval criteria
- `~/.claude/PAI/ALGORITHM/target-types.md` — target detection and ISC generation
## Examples
### Metric Mode
**Optimize page load time:**
```
/optimize --metric "lighthouse_perf" --higher-is-better \
--measure "npx lighthouse http://localhost:3000 --output=json --output-path=lh.json" \
--extract "jq '.categories.performance.score * 100' lh.json" \
--files "src/**/*.tsx,src/**/*.css" \
--target 95 --budget 120
```
**Optimize bundle size:**
```
/optimize --metric "bundle_bytes" --lower-is-better \
--measure "bun run build 2>&1 && du -sb dist/ | cut -f1" \
--files "src/**/*.ts" \
--constraints "all tests must pass"
```
**ML training (Karpathy-style):**
```
/optimize --metric "val_bpb" --lower-is-better \
--measure "uv run train.py > run.log 2>&1 && grep '^val_bpb:' run.log | cut -d' ' -f2" \
--files "train.py" \
--locked "prepare.py" \
--budget 300
```
### Eval Mode
**Optimize a skill's Extract workflow:**
```
/optimize --target "~/.claude/skills/ExtractWisdom" --max-experiments 15
```
**Optimize a standalone prompt:**
```
/optimize --target "prompts/summarize-article.md" --runs 5
```
**Optimize with custom criteria:**
```
/optimize --target "~/.claude/skills/Research/Workflows/QuickResearch.md" \
--criteria "Does the output contain specific facts with sources?" \
"Is the output structured with clear sections?" \
"Does the output avoid generic filler?" \
--inputs "research quantum computing breakthroughs 2025" \
"quick research on supply chain security" \
"find recent developments in AI agents"
```
## Gotchas
- **Hill-climbing can get stuck in local optima.** If score plateaus, consider resetting with different initial conditions.
- **Eval mode vs metric mode:** Use metric mode for quantifiable targets (latency, size). Use eval mode for qualitative targets (skill quality, prompt effectiveness).
- **Regression tolerance prevents catastrophic changes.** Don't set it to 0 — some regression in secondary metrics is acceptable if primary metric improves significantly.
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.