Claude Cursor Skill

optimize

Use when asked to optimize code, speed up a path, reduce allocations, repair a regression, or profile a target. Not for remote, credential, publish, deploy, or irreversible changes.

LLM Mart · 0 points · 9 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download OutlineDriven-odin-claude-plugin-plugins_odin-code_skills_optimize-f73ec79.zip · 22 KB
Part of outlinedriven/odin-claude-plugin — 120 skills

Install

skills CLI npx skills add https://github.com/OutlineDriven/odin-claude-plugin/tree/main/plugins/odin-code/skills/optimize
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install outlinedriven-odin-claude-plugin@llmmart
Git git clone https://github.com/OutlineDriven/odin-claude-plugin.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole outlinedriven/odin-claude-plugin collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Optimize

Five mode names share one authority: reversible local writes to the resolved target, never push, tag, publish, deploy, or mutate a remote. Full and extremely-optimize intentionally select the same measured-floor campaign route, rather than separate procedures; the retired name remains an explicit compatibility mode value. That route runs an isolated five-lens search with an integrated 1.05x gate and an atomic commit. Quick mode runs a single measure-identify-fix-verify loop with a noise-aware keep/revert and a CI guard for the obvious-bottleneck case. fastopt mode reports suspected-hot-path hypotheses without mutating code. fastopt-extreme mode reports estimated hot paths and complexity-neutral cold-path simplifications while refusing complexity theater.

Contract

Field Bound contract
Trigger The user asks to optimize code, make a path faster, make this as fast as possible, reduce allocations, fix a performance regression, profile and optimize a path, symbol, or diff, or a performance requirement, slowness report, Core Web Vitals miss, or profiling evidence identifies a bottleneck; asks for a measured-floor campaign, hypothesis-only suspected-hot-path analysis, or estimated hot/cold analysis that refuses complexity theater; or says "extremely optimize" or "grill every inefficiency".
Authority Full and extremely-optimize modes write only the exact VCS-tracked source-target set shown before mutation plus .outline/optimize/<target>/ (destructive; rollback is version control); quick mode writes only the named target and an authorized CI performance-budget or field-monitor guard; fastopt and fastopt-extreme modes are read-only with no file, VCS, credential, paid, published, deployed, or remote mutation. Full mode may commit one winning optimization, but no mode tags, publishes, deploys, or mutates a remote.
Side effect Full and extremely-optimize modes append measurements and decisions to .outline/optimize/<target>/log.jsonl, benchmark isolated candidates, gate all boundary surfaces before touch, revert non-wins, apply the winner, and create one atomic commit. Quick mode applies one targeted fix and may add a CI performance budget or field monitor. fastopt mode emits labeled hypotheses and benchmark designs. fastopt-extreme mode emits hot-path hypotheses, benchmark designs, cold-path simplifications, and complexity-theater refusals.
Done Full and extremely-optimize modes rebuild hot units with a measured 1.05x-or-better win, grade cold units fixed/at-floor/left, remove residue, pass the verifier, and land the target atomically. Quick mode: the identified bottleneck is measurably improved past noise, tests remain green, no new regressions exist, and a CI budget or field monitor guards the metric. fastopt mode: every named path has a labeled hypothesis and benchmark design, with no mutation or speed claim. fastopt-extreme mode: every hot estimate has a falsifiable benchmark, every cold candidate is complexity-neutral or rejected, and every complexity-theater proposal is refused.
Inputs The required mode-specific inputs are listed below; the mode input selects exactly one route and must not combine a mutating route with a read-only route.

Inputs

  • Mode (optional, exact values when supplied): full, extremely-optimize, quick, fastopt, or fastopt-extreme. The mode selects exactly one route; do not combine a mutating route with a read-only route. When omitted, select from the trigger and evidence.
  • Full or extremely-optimize mode (measured-floor campaign): a named resolvable path, symbol, diff, or active local change, or no path only for an explicit repo-wide survey; repo-wide work is opt-in and never inferred. For a bare extremely-optimize invocation after that opt-in, profile the repository's own workload and work the ranked list. One representative runnable workload or benchmark command and repository-native verification commands are required. The workload must be supplied or constructed before measurement and must exercise the target for at least one second of wall time. The verifier must be supplied or discovered before any target lands. A supplied profile or named hotspot is optional. Optional controls are a performance budget, maximum gate attempts, maximum wall time, and minimum marginal speedup. An observable approximation is permitted only when the user's request authorizes it and the exact changed contract is confirmed before mutation. If the target or workload cannot be resolved without guessing, stop with exit 11.
  • Quick mode: a resolvable target, a performance symptom and the codebase under optimization, and repository-native verification commands. Existing measurements, profiling evidence, performance budgets, or Core Web Vitals targets are optional.
  • fastopt mode: one or more suspected hot paths named by the user (file, function, or call site) and the workload or input shape that makes each path hot. Prior measurements, profiling traces, and environment constraints are optional; absent measurements are unmeasured, not evidence of slowness.
  • fastopt-extreme mode: the target code region or module. Call frequencies, profiling data, or prior benchmark results are optional. If no code is supplied, request the target before proceeding.

Mode selection

User says or evidence Mode Gate
optimize this path, profile and optimize, reduce allocations, fix a regression, hot-path speedup, make this as fast as possible, grill every inefficiency, or run a measured-floor campaign full / extremely-optimize Integrated benchmark proves at least 1.05x; adversarial behavior gate; atomic commit
quick optimize, obvious bottleneck, Web Vitals miss, slowness report, or single targeted fix quick Improvement past measurement noise; tests green; CI guard added
analyze suspected hot paths without waiting for benchmarks, or name a suspected hot path and its workload fastopt Read-only hypotheses and seven-part benchmark designs; no mutation or speed claim
estimate hot paths, simplify complexity-neutral cold paths, or refuse complexity theater fastopt-extreme Labeled hot hypotheses with falsifiable benchmarks; cold simplifications or explicit refusals; no mutation

When the user names a hot path and a benchmark, use full mode. When the user names a single symptom and an evident bottleneck (N+1 query, missing index, bundle size, re-renders), use quick mode. When the evidence is a profiling trace with one dominant hotspot at least 5% of total time, use full mode; when one evident fix addresses the symptom, use quick mode. Use fastopt when the path is suspected but measurement is intentionally deferred. Use fastopt-extreme when only call frequency, loop depth, allocation density, or I/O and syscall evidence is available and the request rejects complexity theater. extremely-optimize is the explicit name for the measured-floor full route.

Procedure

Run exactly one named mode below. Every mode is part of this single procedure; do not combine a mutating mode with a read-only mode.

Full mode, extremely-optimize: measured-floor campaign

  1. Resolve the target set and bound the write surface. Resolve one target and bound writes to that target plus .outline/optimize/<target>/. Record the exact VCS-tracked source-target set before mutation; generated files and untracked targets are not silently included. For an explicit repo-wide survey with no path, profile the repository workload, rank the targets, and select one target before candidate work; never infer repo-wide scope. Reject architecture-wide redesign and mixed optimization concerns. For a single function under 50 lines with one evident concern, report auto-skip and use one candidate; otherwise use all five lenses below. Require the runnable workload and repository-native verifier before measurement. If no workload can exercise the target, classify the run as no workload and stop. Done when: one target, its exact source set, workload, and verifier are resolved and bounded, or an explicit repo-wide survey has produced a ranked list and selected target, or auto-skip is reported.
  2. Pin the workload and baseline. Run hyperfine --warmup 3 --min-runs 10 '<cmd>' and one suitable profiler pass. Record median, standard deviation, minimum, and maximum. Reject the measurement while standard deviation exceeds 20% of the median: pin CPU frequency, isolate the process, widen --min-runs, or enlarge the input until the noise clears. Record the top self-time function or widest plateau as HOT_PATH. If no path accounts for at least 5% of total time, continue only when call-count evidence identifies a unit whose calls scale with input and instrumentation confirms it; otherwise stop because the workload is not measurable. Done when: the workload runs for at least one second, a stable baseline with standard deviation under 20% of median is recorded, and either HOT_PATH is at or above 5% or a scaled-call hot unit is confirmed, or the run is stopped with its blocker.
  3. Split hot from cold. Use the profiler pass from step 2 and write both lists. A unit is hot when it holds at least 5% of total measured time or its call count scales with input size; everything else is cold. Where the sampling profiler disagrees with a call-count argument, believe the call count and confirm by instrumentation. Done when: every relevant unit is on exactly one written hot or cold list.
  4. State each contract and compute its floor. Work the hot list in descending order of time share. For each unit, write what it owes its callers based on call sites, tests, and the signature, never its own internals. Compute the floor from that contract alone: bytes that must move at achievable bandwidth, the algorithmic lower bound at a measured per-operation cost, and syscalls or round-trips the protocol cannot avoid. Show the arithmetic with eval, never in prose. Divide measured cost by floor; that multiple is the unit's headroom. A unit already within 2x of its floor is finished and moves on. Done when: every hot unit has its contract, floor arithmetic, headroom multiple, and within-2x verdict recorded.
  5. Classify consumers and derive blind. Inventory each unit's consumers and mark it interior (every caller in-tree, nothing persisted or shipped) or boundary (public API, wire or on-disk format, config running in someone else's deployment, or plugin point). Treat reflection, string dispatch, generated code, external integration, and other channels static analysis cannot resolve as boundaries until evidence changes the classification. Build the replacement from the contract and floor alone, without reading the old implementation for structure; reading it reproduces the costly shape. Choose the data layout that puts the floor in reach: contiguity, batching, hot and cold fields split, or one pass where there were three. Done when: every consumer is classified and the replacement is written from the contract and floor alone.
  6. Audit the divergence. Walk the old implementation branch by branch and classify every behavior as folded into the replacement (essential) or cut (residue), with a one-line reason. Read for guards, early returns, side effects, ordering guarantees, error semantics, and state transitions. A branch never read is a feature deleted by accident. Done when: every old-implementation branch is classified as essential or residue.
  7. Gate boundaries before mutation. Present every surface marked boundary in step 5 and get an explicit answer before touching it. Interior surfaces need no ask and may be demolished. Do not cut a boundary on silence or after a no. Done when: every boundary surface has an explicit answer before any touch and all interior surfaces are demolished.
  8. Locate the benchmark evidence. Locate or create a minimal benchmark under .outline/optimize/<target>/. Use the already captured step 2 workload and baseline; do not run a second baseline. Append the baseline statistics and benchmark command to log.jsonl. Do not continue while standard deviation exceeds 20% of the median. Done when: the existing baseline evidence and command are appended to log.jsonl.
  9. Start an append-only run record. Before candidate work, append an in-progress record containing a run ID, target, start time, stop limits, and a fingerprint of the target revision, hot-path source, and benchmark command. Never rewrite or truncate the log. On interruption, resume only when the fingerprint matches and a fresh baseline agrees with the recorded baseline; otherwise mark measurements stale and start a new run. Reuse matching recorded candidates and rerun only missing candidates. Done when: the in-progress record and fingerprint are appended.
  10. Launch disjoint candidates. Unless auto-skip applies, launch five independent, worktree-isolated candidates together. Give each the same hot-path source, benchmark, and baseline, but one distinct lens: algo changes complexity or removes work; data changes representation or layout; cache reuses valid results with explicit invalidation and bounds; concur changes safe parallelism or contention; arch removes a local boundary or transfer cost without redesigning the module. State that the lenses are disjoint, worktrees are isolated, and candidates become read-only after reporting. Done when: five isolated candidates are launched, or auto-skip uses one candidate.
  11. Measure and record each candidate. Require each candidate to apply one transformation and run the same benchmark protocol. Return its lens, change summary, before and after medians, speedup ratio, behavior assessment, readability cost, and patch. Append each candidate record before scoring it. Do not record a failed candidate, so a resumed run retries it. Done when: every viable candidate result is appended before scoring.
  12. Score and rank. Drop failed results and score each remaining candidate as speedup_ratio * behavior_safety * (1 - readability_cost * 0.3), where exact behavior is 1.0, a confirmed approximation is 0.7, and unsafe or undisclosed behavior is 0.0. Treat an approximation as viable only when the user's inputs authorize it and the changed contract is confirmed; otherwise stop with exit 14. Rank the winner and runner-up and append the ranking. Stop if no candidate reaches 1.05x. Done when: candidates are scored, ranked, and appended, or a terminal no-candidate or unconfirmed-approximation result is recorded.
  13. Run the adversarial behavior gate. For the leading candidate, compare original and optimized behavior over output identity, error semantics, public contracts, empty and boundary inputs, negative values, NaN where applicable, and concurrent call sequences. Append every gate verdict and failure scenario. On failure, discard that candidate and consider the next ranked candidate. Done when: the leading candidate passes every adversarial gate with verdicts appended, or all candidates are discarded.
  14. Enforce promotion limits. Before each promotion, enforce the configured maximum attempts, maximum wall time, and minimum marginal-speedup floor; default maximum attempts to the viable-candidate count and the marginal floor to 1.02. If a limit trips before any candidate passes, append the best-so-far and commit nothing. If candidates are exhausted, stop with the precise terminal class. Done when: a candidate is promoted within all limits, or promotion stops with the limit or exhaustion recorded.
  15. Measure, prove, and promote only a win. Apply only the gate-cleared patch to the main worktree. Run the same step 2 workload with three warmups and at least ten measured runs, append the integrated median, variance, and speedup, and discard the target patch if baseline_median / integrated_median < 1.05. Run the repository's verifier and cover every essential behavior from step 6 that no test reached. Done when: the integrated benchmark proves at least 1.05x speedup and all required behavior is covered, or the target is restored with the blocker recorded.
  16. Land one concern. Delete the old unit and every symbol reachable only from it. Commit exactly the named target as one optimization concern. Include the hot path, lens, rationale, baseline and integrated medians with variance, ratio, and any confirmed approximation contract in the commit message. Remove only .outline/optimize/<target>/agent-* worktrees, preserve the log and benchmark evidence, and append the authoritative terminal run record with status done and exit 0. Done when: one atomic optimization commit is made, residue symbols return nothing, candidate worktrees are removed, and the terminal run record is appended.
  17. Grill cold paths. Cold code is off the clock; buying speed with complexity is a loss. Hunt waste that costs something other than time on this workload: complexity that bites at a larger N, allocations and retained memory, redundant I/O and repeated round-trips, startup and build cost, artifact size, and dependency weight. Every unit on the cold list takes one verdict: fixed (name the cost that fell), at floor, or left (with the reason). A cold fix that adds a branch, cache, or configuration knob to buy microseconds is rejected. Done when: every cold unit has a fixed, at-floor, or left verdict.

Work one target at a time. Half-rebuilt is the forbidden state: finish a target or revert it. Scope equals the ask; never escalate a named target into a repo-wide campaign.

Quick mode

  1. Establish baseline. Measure the bottleneck with profiling tools or timing data before touching any code. Record the specific metric, the tool or method used, and the measured value. If a baseline cannot be established, stop and report blocked. Done when: the metric, tool, and measured value are recorded.
  2. Identify the specific bottleneck. Use the symptom to determine the profiling target: frontend performance (Lighthouse, DevTools Performance tab, web-vitals RUM), backend latency (APM, query logging, EXPLAIN ANALYZE), bundle analysis, or heap profiling. Do not assume the cause. The query plan is the measurement for database queries; the trace is the measurement for frontend jank. Done when: the profiling target is determined from the symptom.
  3. Fix the identified bottleneck only. Apply one targeted change. Code it completely before measuring again. Common fixes: N+1 queries -> single query with join or include; unbounded pagination -> limit and offset; missing index -> CREATE INDEX with a composite key shaped to the query; connection pool exhaustion -> size the pool to the database ceiling; large bundle -> code splitting or lazy loading; unoptimized images -> responsive srcset, lazy loading, or a modern format; unnecessary re-renders -> React.memo, useMemo, or stable references; missing caching -> cache expensive reads with a stated TTL and key design. Done when: one targeted change is coded completely.
  4. Re-measure under identical conditions. Use the same tool, same conditions, and same measurement method as the baseline. Make one change at a time. Done when: the after-measurement is recorded under identical conditions.
  5. Keep or revert strictly. Past noise and tests green: keep. Within noise or tests red: revert immediately. Neutral is a revert. An optimization that wins by dropping needed work is a revert. Done when: the change is kept (past noise, tests green) or reverted (noise, tests red, or neutral).
  6. Guard the metric. Add a synthetic CI performance budget or a field monitor (RUM p75) for the primary metric. This prevents the fix from regressing unseen. Done when: a CI performance budget or field monitor guards the primary metric.

fastopt mode: hypothesis-only analysis

  1. Read each named path. For each suspected hot path, read the source and surrounding call graph read-only. Record the inputs, allocations, loops, and branches that plausibly dominate cost. Done when: every named path is read and its cost-plausible elements are recorded.
  2. Label observations as hypotheses. For every cost observation, state the assumed workload, assumed dominant operation, and assumed magnitude rank. Label it a hypothesis, never a finding, and make no speed claim. Done when: every observation has its hypothesis label, workload, dominant operation, and magnitude rank.
  3. Design a falsifiable benchmark. For each hypothesis, name the metric, baseline, variant, workload generator, warm-up, repetition count, and noise controls that would confirm or refute it. Done when: every hypothesis has all seven benchmark elements.
  4. Bound the implied change. Restrict any implied change to the named path; do not propose edits outside it or assume a fix is correct. Done when: every hypothesis has a bounded change scope.
  5. Report measurement blockers. If a hypothesis cannot be tested without mutating code, state the minimal mutation needed to measure it and stop before performing it. Done when: the blocking reason and minimal mutation are stated, or the hypothesis is testable read-only.
  6. Emit without mutation. Emit the hypotheses and benchmark designs as chat output. Do not mutate any file and do not claim a speedup. Done when: the chat report is emitted with no mutation or speed claim.

fastopt-extreme mode: estimate and complexity-neutral simplification

  1. Bound scope. Restrict analysis to the named code region or module and do not widen to unrelated code. Done when: scope is bounded to the named region or module.
  2. Estimate hot paths. Estimate hot paths from call frequency, loop depth, allocation density, and I/O or syscall blocking. Label every estimate as a hypothesis, not a measured fact, and state its basis. Done when: every hot-path estimate is labeled with its basis.
  3. Classify cold candidates by complexity. Identify complexity-neutral cold paths whose optimization adds no new abstraction, wrapper, configuration flag, caching layer, or indirection. The change must be simpler than or equal in complexity to the original. Done when: every cold candidate is classified as complexity-neutral or rejected.
  4. Design hot-path benchmarks. For each hot-path hypothesis, state the metric, baseline measurement, and falsification condition under which the hypothesis is rejected. Done when: every hot-path hypothesis has a benchmark design with its metric, baseline, and falsification condition.
  5. Propose cold simplifications. For each complexity-neutral cold candidate, state the specific simplification and why it adds no complexity. Done when: every cold candidate has its simplification and complexity justification stated.
  6. Refuse complexity theater. Reject any proposal that introduces a new abstraction, wrapper, flag, caching layer, or indirection whose complexity exceeds the gain it claims. State the complexity cost and claimed gain. Done when: every complexity-theater proposal is refused with its cost and claimed gain.
  7. Emit without mutation. Emit all hypotheses, benchmark designs, simplification proposals, and refusals as chat output. Do not mutate any file. Done when: the chat report is emitted with no file mutation.

Failure and recovery

Full mode and extremely-optimize

Full and extremely-optimize intentionally share this measured-floor route. The exit map below is canonical for both names, rather than maintaining two procedures or two conflicting code maps.

Terminal class Recovery
No workload (exit 10) The target's cost cannot be reproduced on demand. Construct a runnable workload or stop; do not claim success.
Baseline too noisy (exit 11) Standard deviation exceeds 20% of median and cannot be cleared. Clear the noise or stop.
No measurable hotspot (exit 11) No path accounts for at least 5% of time or the workload is not measurable. Report the blocker and commit nothing.
No headroom (exit 12) Every hot unit is already within 2x of its floor. Report the terminal result and commit nothing.
No candidate or integrated no-win (exit 13) No candidate or integrated result clears the 1.05x gate. Revert the replacement or target patch and keep the original.
No win or failed behavior/check gate (exit 13) A candidate fails the campaign gate, or the repository checks fail. Revert the replacement or target patch and keep the original.
Approximation unconfirmed (exit 14) The request did not authorize the approximation or the changed contract was not confirmed. Discard that candidate and do not promote it.
Divergence unclassified (exit 14) Old behavior is neither folded in as essential nor cut as residue. Complete the step 6 walk before proceeding.
Mixed optimization concerns (exit 15) The proposed commit mixes concerns and must be split before retrying.
Boundary cut without an answer (exit 15) A published surface was destroyed on silence or after a no. Restore it and settle the question.
Campaign stalled mid-target (exit 16) A target is half old and half new. Finish it or revert it; never ship it.
Scope exceeded (exit 17) A repo-wide sweep ran off a named target. Revert the untargeted work.
Stopping limit (exit 16) or failed verifier (exit 13) Before commit, restore only the named target and remove only run-created candidate worktrees; retain append-only evidence, append the exact terminal class, commit nothing, and never revert an unrelated commit. Resume only through the fingerprint match and fresh-baseline agreement.

Partial-result rule for full and extremely-optimize: a target that has not reached the done predicate is reverted to its pre-campaign state; no half-rebuilt target remains. Non-wins and untargeted work are reverted. Never swallow an error or pretend the done predicate holds.

Quick mode

Failure Response
Baseline unavailable Measurement tools are unavailable or the codebase cannot be profiled. Result: blocked. Do not proceed without baseline evidence.
No bottleneck found Profiling reveals no measurable code-level bottleneck. Report uncertainty and whether environmental or statistical noise is suspected.
Fix produces no measurable gain Improvement is within noise range of the baseline. Revert. Never keep a neutral change.
Correctness regression Tests fail or behavior changes after the fix. Revert immediately. Correctness gates the metric.
Fix exceeds available authority The bottleneck requires unavailable credentials, remote mutation, or infrastructure changes outside local write scope. Document the requirement and do not widen authority.

Partial-result rule for quick mode: reverted code leaves no trace. Keep a ledger entry (baseline, fix applied, before/after measurement, and verdict) so discarded ideas are not re-profiled.

fastopt

Failure Response
Unmeasured path Mark the hypothesis unmeasured; do not infer slowness from absent data.
Ambiguous hot path Ask the user to name the path and workload; stop rather than guess.
Benchmark infeasible read-only State the blocking reason and the minimal mutation that would unblock measurement; do not perform it.
No recovery widens authority fastopt never mutates files, VCS, credentials, or remote state; a blocked result is emitted as blocked, not as success.

fastopt-extreme

Failure Response
No code supplied Request the target code region or module; do not guess or analyze from memory.
Path unclassifiable Label a path unclassified and exclude it from optimization proposals.
Complexity theater detected Refuse the proposal and record its complexity cost and claimed gain. Do not emit it as a valid optimization.
Partial result Emit obtained hypotheses and designs, and mark every unclassified or refused item so the done predicate is not falsely satisfied.
Non-mutation No file, VCS, or remote change is made. Rollback is not applicable.

Output

Full mode and extremely-optimize. On success, return exit 0 with the commit identifier, target, selected lens, benchmark command, baseline and integrated statistics, measured speedup, behavior-gate result, repository checks, cold-path verdicts, and durable log path. On failure, return the applicable terminal class, unchanged or rolled-back target state, measurements obtained, and the precise blocker; never report a worktree-only result as a landed win.

Quick mode. Return optimized code with before/after measurements, plus a ledger entry per attempt (kept and reverted) documenting the hypothesis, baseline, result, and verdict. Each entry states the metric name, baseline value, result value, and tool used.

fastopt mode. Return one labeled hypothesis per suspected path and one benchmark design per hypothesis containing the metric, baseline, variant, workload generator, warm-up, repetitions, and noise controls. Report blocked paths with their reason and minimal measurement mutation. Never mutate or claim a speedup.

fastopt-extreme mode. Return hot-path hypotheses with falsifiable benchmark designs, complexity-neutral cold-path simplification proposals, and explicit complexity-theater refusals with their complexity costs and claimed gains. Never mutate a file.

Files (odin-claude-plugin)
  • agents
    • openai.yaml 632 B
      interface:
        display_name: "Optimize"
        short_description: "Use when asked to optimize code, make a path faster, make this as fast as possible, reduce allocations, repair a regression, profile a target, grill every inefficiency, or run a subsystem or repo-wide performance campaign against a measured floor; when a performance requirement, slowness report, Core Web Vitals miss, or profiling evidence identifies a bottleneck; or for an \"extremely optimize\" performance campaign, optimizing suspected hot paths without waiting for benchmarks, or estimating hot and complexity-neutral cold paths while refusing complexity theater."
      
  • references
    • experiment-mode.md 6.3 KB
      # Experiment mode: metric-driven optimization for broad search spaces
      
      An optional extension to the primary hot-path optimization loop. Use when the target has
      a measurable metric but the search space is broad, parameter tuning, prompt optimization,
      threshold finding, configuration search, rather than a single hot-path transform.
      
      The primary optimize loop (five-lens fan-out, benchmark, gate, commit) remains the default.
      Experiment mode applies only when the conditions below are met.
      
      ## When to use experiment mode
      
      - The optimization target has a measurable metric (latency, accuracy, cost, throughput) but
        no single obvious hot-path transform addresses it.
      - The search space is combinatorial: configuration parameters, prompt variants, threshold
        values, feature toggles, preprocessing pipelines.
      - Hard metrics alone may be gameable: LLM-as-judge can catch degenerate solutions that
        optimize the metric without improving the real objective.
      - NOT for single hot-path transforms. That is the main optimize loop's job.
      
      **First-run advice:** start serial (no parallel experiments), cap iterations at 10-15, use
      the smallest sample sizes that still pass the variance check. Scale up only after the loop
      proves productive.
      
      ## Benchmark loop discipline
      
      1. **Define the measurement harness before generating hypotheses.** The harness is the
         contract: it specifies what is measured, how, and with what parameters. No harness, no
         experiments.
      2. **Run baseline measurement with variance check.** stddev must be < 20% of median. Fix
         noise before proceeding (pin CPU, isolate process, widen sample count).
      3. **Each experiment:** apply variant, measure, record result immediately to disk.
      4. **Verify writes.** Read back every critical write. Disk is the source of truth, not
         context or memory.
      5. **Crash-recovery markers.** In worktrees, mark each experiment's state so an interrupted
         run can resume without re-running completed work.
      6. **Strategy digest after each batch.** Compress learnings into a short summary after every
         batch of experiments: what worked, what failed, what to try next. This keeps context
         bounded across long runs.
      
      ## Experiment-log schema
      
      Run state lives at `.outline/optimize/<target>/experiment-log.yaml`.
      
      **Persistence model:** `experiments` is append-only: each experiment record is written
      the moment it completes and never rewritten. The `best` and `hypothesis_backlog` fields
      are mutable checkpoint state: rewritten after each batch evaluation, once the batch
      results are verified on disk. On crash recovery, replay `experiments` to reconstruct
      `best`. The `hypothesis_backlog` cannot be replayed from experiment records (unexecuted
      entries are not recorded); recover it from the latest checkpoint; if the checkpoint is
      missing, regenerate from scratch using the current code state and experiment history.
      
      ```yaml
      spec: <string>           # optimization spec name
      run_id: <string>         # unique run identifier
      started_at: <timestamp>  # ISO 8601
      baseline:
        timestamp: <timestamp>
        metrics:
          <name>: <value>      # gate and diagnostic metrics
      experiments:             # ordered list, append-only during iteration
        - iteration: <int>
          batch: <int>
          hypothesis: <string>
          category: <string>
          outcome: <enum>      # measured | kept | reverted | degenerate | error | timeout
          metrics: <object>
          learnings: <string>
          commit: <string>     # SHA if kept
      best:
        iteration: <int>
        metrics: <object>
      hypothesis_backlog:      # remaining hypotheses
        - description: <string>
          category: <string>
          priority: <enum>     # high | medium | low
      ```
      
      ### Outcome state transitions
      
      - `measured`: raw metrics persisted, awaiting batch evaluation
      - `kept`: improved primary metric, gates passed
      - `reverted`: did not improve
      - `degenerate`: gate failed (metric gamed, output degenerate)
      - `error` / `timeout`: measurement failure
      
      ## Stopping rules
      
      Evaluate before each new experiment. Stop on the first that trips:
      
      - Target reached. Primary metric meets the defined target.
      - Max iterations. Total experiments >= configured cap.
      - Max wall-hours. Wall-clock since `started_at` exceeds the cap.
      - Plateau. No improvement for N consecutive experiments (N configurable, default 5).
      - Judge budget exhausted. Cumulative judge spend >= cap (when using judge mode).
      - Empty backlog. No hypotheses remain and no new ones can be generated.
      
      ## Judge rubric (for qualitative metrics)
      
      Use when the metric can be gamed or human judgment matters: clustering quality, search
      relevance, summarization quality, prompt quality.
      
      ### Three-tier approach
      
      1. **Degenerate gates** (hard, cheap, fast). Catch obviously broken solutions. Run first.
         If gates fail, skip the expensive judge step. Examples: output length bounds, format
         compliance, non-empty checks, deduplication rate thresholds.
      2. **LLM-as-judge** (the actual optimization target). Sample outputs, score against a
         rubric, aggregate. This is what the loop optimizes. Use a 1-5 scale with concrete
         per-level descriptions. Include supplementary diagnostic fields. Make the rubric
         specific enough for inter-judge consistency.
      3. **Diagnostics** (logged, not gated). Distribution stats, counts, timing, useful for
         understanding why a judge score changed, not for accept/reject decisions.
      
      ### Rubric design
      
      - 1-5 scale with concrete per-level descriptions (not vague "good/bad").
      - Supplementary diagnostic fields: what specifically was scored, what drove the rating.
      - Specific enough that two independent judge runs on the same output converge.
      
      ### Sampling strategy
      
      - Stratified by output characteristics (length, complexity, domain).
      - Include edge cases and singletons when coverage matters.
      - Sample size: minimum 5 per stratum for stable estimates; scale up for high-variance
        domains.
      
      ## Hypothesis generation
      
      1. Analyze current code and configuration to identify improvement opportunities.
      2. Generate 10-30 initial hypotheses. Each has: description, category, priority.
      3. Categories (adapt to domain): signal-extraction, algorithm, preprocessing,
         parameter-tuning, architecture, data-handling.
      4. Dependency pre-approval: collect all new dependencies upfront and present for bulk
         approval before iterating. Do not pause mid-loop for dependency approval.
      5. After each batch, update the hypothesis backlog based on learnings. Prune dead ends,
         promote promising directions, add newly discovered opportunities.
      
    • lenses.md 10.3 KB
      # Optimize: lens catalogue
      
      Five independent lens prompts for the Phase 4 fan-out. Each is a verbatim agent prompt. The
      orchestrator appends the hot-path source and before-benchmark median before dispatch.
      
      Agent invocation shape (same for all five lenses):
      
      ```
      Agent(
        prompt  = <lens body below> + "\n\n---\n\nHOT_PATH: " + <symbol> +
                  "\n\nCODE:\n" + <source> +
                  "\n\nBEFORE (hyperfine median): " + <before_median_ms> + " ms" +
                  "\n\nBENCH_CMD: " + <bench_cmd>,
        isolation = "worktree"
      )
      ```
      
      Each agent must return a JSON object as its final output:
      
      ```json
      {
        "lens": "<algo|data|cache|concur|arch>",
        "change_summary": "<one sentence>",
        "before_median": <float ms>,
        "after_median": <float ms>,
        "speedup_ratio": <float>,
        "behavior_self_assessment": "<exact|approximation:<contract>>",
        "test_result": "<passed|failed:<reason>|skipped:<reason>>",
        "readability_cost": <0.0–1.0>,
        "diff_patch": "<unified diff string>"
      }
      ```
      
      If the lens yields no worthwhile change, return `speedup_ratio: 1.0` and explain in
      `change_summary`. Do not fabricate a speedup. If tests fail after applying the change, set
      `test_result` to `"failed:<first failing test name>"` and `speedup_ratio` to `1.0`: a broken
      optimization is not a candidate.
      
      ---
      
      ## Lens 1: Algorithmic complexity (`algo`)
      
      You are an algorithmic optimization agent. Your only job is to reduce the asymptotic or empirical
      complexity of the hot path by changing the algorithm, not the data structures or concurrency model.
      
      **Techniques to attempt (in order of expected impact):**
      1. Replace a nested scan (O(n²)) with a hash-set lookup (O(n)).
      2. Eliminate an N+1 query pattern by batching or pre-fetching.
      3. Precompute or index values computed inside a loop that depend only on loop-invariant data.
      4. Replace a linear search on a sorted structure with binary search.
      5. Apply memoization to a recursion that recomputes the same sub-problem.
      6. Eliminate redundant passes over the same data (fuse two O(n) loops into one).
      7. Apply an early-exit or short-circuit where the full traversal is never needed.
      
      **Rules:**
      - One algorithmic change per submission. Do not also change data structures or add concurrency.
      - Behavior must be identical unless the change is a documented approximation (state it clearly
        in `behavior_self_assessment`).
      - Apply the change, run the harness using the supplied `BENCH_CMD` (`hyperfine '<BENCH_CMD>'
        --warmup 3 --min-runs 10 --export-json after.json`), read after.json, populate the JSON result.
      - Run the repo-native test suite after applying; populate `test_result`. A failing test means
        the candidate is unsafe: set `speedup_ratio: 1.0` and do not report a win.
      - `readability_cost`: 0.0 = equally or more readable; 0.5 = somewhat harder to follow;
        1.0 = significantly more complex. Be honest: a complex algorithm that earns its speedup is fine,
        but lie about readability and the adversarial reviewer will catch you.
      
      ---
      
      ## Lens 2: Data structure and layout (`data`)
      
      You are a data-structure and memory-layout optimization agent. Your only job is to change how data
      is organized in memory to reduce cache misses, pointer-chasing, and allocation overhead.
      
      **Techniques to attempt (in order of expected impact):**
      1. Replace a pointer-chained structure (linked list, tree of heap-allocated nodes) with a
         contiguous Vec/slice where traversal order is predictable.
      2. Apply a Struct-of-Arrays (SoA) layout instead of Array-of-Structs (AoS) when the hot path
         accesses only one field across many items.
      3. Reduce struct padding: reorder fields large-to-small, or use `#[repr(packed)]` / `__attribute__
         ((packed))` when alignment permits.
      4. Replace a `HashMap<K, V>` with a `Vec<(K, V)>` + binary search when the map is small and
         lookup count is low; or swap to a purpose-built map (AHashMap, SwissTable) when hash
         performance dominates.
      5. Replace heap allocation (Box, Arc) with inline or stack storage where the size is known and
         bounded (SmallVec, arrayvec, inline arrays).
      6. Align hot structs to cache-line boundaries to prevent false sharing in multi-threaded paths.
      
      **Rules:**
      - One data-structure concern per submission. Do not also change the algorithm or add concurrency.
      - Preserve all public type signatures unless the change is a documented internal representation
        swap hidden behind the existing API.
      - Apply the change, run the harness using the supplied `BENCH_CMD` (`hyperfine '<BENCH_CMD>'
        --warmup 3 --min-runs 10 --export-json after.json`), read after.json, populate the JSON result.
      - Run the repo-native test suite after applying; populate `test_result`.
      - `readability_cost`: SoA layouts and bit-packing score 0.5+; document the layout invariant in
        a comment if cost > 0.3.
      
      ---
      
      ## Lens 3: Caching and memoization (`cache`)
      
      You are a caching and memoization optimization agent. Your only job is to eliminate redundant
      computation or I/O by introducing a transparent result cache, lazy initializer, or coalesced fetch.
      
      **Techniques to attempt (in order of expected impact):**
      1. Memoize a pure function called repeatedly with the same arguments (bounded LRU or full cache
         depending on argument cardinality).
      2. Hoist a repeated pure computation out of a loop into a `let once = compute()` before the loop.
      3. Coalesce multiple I/O fetches (DB reads, HTTP calls, file reads) into a single batched fetch.
      4. Replace eager computation with lazy initialization (`OnceLock`, `lazy_static`, `functools.cache`)
         when the result is not always needed.
      5. Add an in-process result cache with a TTL when the underlying source has bounded staleness
         tolerance (state this contract explicitly).
      6. Deduplicate identical work items in a queue before dispatching (idempotent-key dedup).
      
      **Rules:**
      - Caches that are not transparent (TTL, bounded eviction, staleness) are approximations. Set
        `behavior_self_assessment` to `"approximation:<contract>"` and describe the staleness/eviction
        contract precisely.
      - One caching concern per submission. Do not also change the algorithm or data structures.
      - Apply the change, run the harness using the supplied `BENCH_CMD` (`hyperfine '<BENCH_CMD>'
        --warmup 3 --min-runs 10 --export-json after.json`), read after.json, populate the JSON result.
      - Run the repo-native test suite after applying; populate `test_result`.
      - Unbounded caches in long-running processes are memory leaks; bound everything or justify infinite
        cardinality (small closed key space, etc.).
      
      ---
      
      ## Lens 4: Concurrency and parallelism (`concur`)
      
      You are a concurrency and parallelism optimization agent. Your only job is to speed up the hot path
      by exploiting available CPU cores, reducing lock contention, or eliminating false sharing.
      
      **Techniques to attempt (in order of expected impact):**
      1. Parallelize an embarrassingly-parallel loop (rayon par_iter, Go goroutine fan-out, Python
         ProcessPoolExecutor, Java parallel streams) where items are independent.
      2. Remove a global lock from a hot path: use per-shard locks, lock-free atomics, or a channel
         per producer.
      3. Eliminate false sharing: pad hot structs to cache-line size; separate fields accessed by
         different threads onto separate cache lines.
      4. Replace a synchronous I/O call inside a hot loop with async/non-blocking I/O + a runtime
         that schedules other work while waiting.
      5. Use SIMD intrinsics (or language-level vectorization hints) on a hot arithmetic loop with
         independent iterations.
      6. Pipeline producer-consumer stages (channel + worker pool) to overlap CPU and I/O.
      
      **Rules:**
      - Introduce concurrency only where the hot path is the bottleneck and parallelism does not
        introduce data races, locking cycles, or non-determinism in output.
      - All new concurrent paths must be race-free. If the language has a race detector (Go `-race`,
        Rust's ownership, ThreadSanitizer), run it; note the result in `test_result`.
      - One concurrency concern per submission.
      - Apply the change, run the harness using the supplied `BENCH_CMD` (single-threaded bench for
        baseline; parallel bench for after if the change adds parallelism) (`hyperfine '<BENCH_CMD>'
        --warmup 3 --min-runs 10 --export-json after.json`), populate the JSON result.
      - Run the repo-native test suite (including race detector where available) after applying;
        populate `test_result`.
      - `readability_cost`: concurrency always costs readability; score ≥0.3 unless the parallelism is
        a single `par_iter()` swap.
      
      ---
      
      ## Lens 5: Architectural and structural (`arch`)
      
      You are an architectural optimization agent. Your only job is to restructure the hot path at the
      module or system level, pipeline stages, call-graph depth, abstraction layers, dispatch
      mechanisms, to eliminate overhead that neither algorithmic, data-structure, caching, nor
      concurrency changes can address.
      
      **Techniques to attempt (in order of expected impact):**
      1. Collapse an unnecessarily deep call chain (>4 levels of thin wrappers, each adding only
         indirection) into a flat, inlined implementation.
      2. Replace a dynamic-dispatch hot path (virtual calls, trait objects, boxed closures) with a
         monomorphized or statically-dispatched version where the type is known at the call site.
      3. Eliminate a serialization/deserialization round-trip (JSON encode→decode, proto marshal→
         unmarshal) on a hot inter-layer boundary by passing the structured type directly.
      4. Replace a polling loop with an event/interrupt/notification mechanism to eliminate busy-wait CPU
         burn between events.
      5. Move a frequently-failing validation or guard check earlier in the pipeline so the expensive
         downstream work is skipped sooner (fail-fast restructuring).
      6. Fuse two sequential passes over a dataset into one by restructuring the pipeline to process
         each item to completion before moving to the next.
      
      **Rules:**
      - One architectural concern per submission. Do not also change the algorithm or data structures
        beyond what the restructuring requires.
      - Public API contracts must be preserved unless the change is explicitly a documented internal
        restructuring hidden behind the existing API surface.
      - Apply the change, run the harness using the supplied `BENCH_CMD` (`hyperfine '<BENCH_CMD>'
        --warmup 3 --min-runs 10 --export-json after.json`), read after.json, populate the JSON result.
      - Run the repo-native test suite after applying; populate `test_result`.
      - Architectural changes carry higher readability cost by default; score honestly, and add a
        comment explaining the architectural invariant being protected.
      
    • state-and-resume.md 2.6 KB
      # Optimize run state: append-only log and crash recovery
      
      Run state lives on disk, not in context. The single run-state file,
      `.outline/optimize/<target>/log.jsonl`, is one JSON object per line, **append-only**: a record is
      written the moment its fact is known and never rewritten. It sits beside the `agent-*` worktree
      dirs but is not matched by the Phase 7 cleanup glob (`…/agent-*`), so it survives the run.
      
      A five-agent fan-out can crash mid-benchmark. Every benchmarked candidate is already a durable
      line, so resume re-dispatches only the lenses with no `candidate` record. Benchmarked work is
      never repeated.
      
      Records (last `run` record wins for overall status):
      
      | record | written | key fields |
      |---|---|---|
      | `run` | Phase 4 start (`in-progress`), Phase 7 end (`done`) | `status`, `run_id`, `target`, `started_at`, `fingerprint`, `stop` config, `exit_code` |
      | `baseline` | Phase 3 | `median_ms`, `stddev_ms`, `bench_cmd` |
      | `candidate` | Phase 4, as each agent returns | `lens`, `after_median_ms`, `speedup_ratio`, `behavior_self_assessment`, `test_result`, `readability_cost` |
      | `rank` | Phase 5 | `winner`, `runner_up`, `composite` |
      | `gate` | Phase 6, each pass | `candidate`, `passed`, `failure_scenario`, `iteration` |
      | `integrated` | Phase 7 | `median_ms`, `integrated_speedup` |
      
      Once the Phase 4 `in-progress` marker is written, **every** terminal exit (0, 12, 13, 14, 16)
      appends a `done` marker carrying its `exit_code`. An `in-progress` marker as the last record
      therefore means a genuine crash. Only that offers resume; a clean non-zero exit does not.
      
      **`fingerprint`** = `{source_rev, bench_cmd, target}`, where `source_rev` is HEAD plus a hash of
      the uncommitted diff over the target files. It pins the base the recorded numbers were measured
      against. Candidate diffs are regenerated fresh each run and never cached, so a per-candidate hash
      buys nothing. The run-level fingerprint plus the resume baseline re-check are the only staleness
      guard needed.
      
      **Resume.** Phase 1 reads the target's log if present. A terminal `done` marker → start fresh
      (new `run_id`). An `in-progress` marker → recompute the fingerprint and re-measure the baseline.
      Honor the skip-re-benchmark path **only if** the fingerprint matches the logged `run` marker AND
      the re-measured baseline median falls inside the logged baseline's stddev band; then replay the
      `baseline` and `candidate` records, skip lenses already recorded, and continue at Phase 5 once the
      remaining lenses report. If either check fails (source edited, bench command changed, different
      machine, environment drift), the recorded numbers are stale. Discard the candidate records, write
      a fresh `run` marker, and start over.
      
    • tooling.md 7.4 KB
      # Optimize: tooling matrix and harness templates
      
      Used in Phase 2 (light locate) and Phase 3 (baseline benchmark) of the `/optimize` workflow.
      This matrix pairs profiling and location tools with benchmark harness templates for Phase 3.
      
      ---
      
      ## Per-language tooling matrix
      
      | Language | CPU profiler | Memory/alloc profiler | Benchmark / differential |
      |---|---|---|---|
      | **Rust** | `samply record`, `perf record` + `flamegraph`, `cargo flamegraph` | `heaptrack`, `dhat`, `valgrind --tool=massif` | `criterion`, `iai-callgrind`, `hyperfine` |
      | **C / C++** | `perf record` + `flamegraph`, `valgrind --tool=callgrind`, `samply` | `valgrind --tool=massif`, `heaptrack`, `dhat` | `hyperfine`, `google/benchmark`, `criterion.rs` (C via cbindgen) |
      | **Python** | `py-spy record --format flamegraph`, `scalene`, `cProfile` + `snakeviz` | `scalene` (memory mode), `tracemalloc`, `memray` | `pytest-benchmark`, `asv` (airspeed velocity), `hyperfine` |
      | **Go** | `go tool pprof` (CPU profile via `runtime/pprof`), `go test -cpuprofile` | `go tool pprof` (heap), `runtime.MemStats` | `go test -bench -benchmem`, `benchstat`, `hyperfine` |
      | **Java / Kotlin** | `async-profiler`, JFR (`jcmd <pid> JFR.start`) | JFR allocation events, Eclipse MAT on heap dump | JMH, `hyperfine` |
      | **JavaScript / TypeScript** | Chrome DevTools, `node --prof` + `node --prof-process`, `clinic flame` | Chrome heap snapshot, `clinic doctor` | `tinybench`, `mitata`, `hyperfine` |
      | **OCaml** | `landmarks`, `magic-trace`, `perf record` | `memtrace` + `memtrace-viewer`, `Statmemprof` | `bechamel`, `core_bench`, `hyperfine` |
      
      **Tool rules (inherit from the ODIN banned-tool list):**
      - `hyperfine` not `time`. `procs` not `ps`. `bat -P -p -n` not `cat`. `difft` not `diff`.
      - Always `--warmup 3 --min-runs 10` on hyperfine. Export JSON: `--export-json <path>`.
      - Profile in a release/optimized build, never debug. Benchmark the same binary that will ship.
      
      ---
      
      ## Minimal harness templates
      
      Use these when Phase 3 finds no existing benchmark harness for the hot path. It is a **throwaway
      instrument**: its only purpose is to measure `HOT_PATH` in isolation with realistic inputs.
      Delete it after the skill run unless the user asks to keep it as a regression guard.
      
      ### Harness placement
      
      - **Python, TypeScript, OCaml**: toolchain-agnostic runners discover files by path argument;
        write the harness directly to `.outline/optimize/<target>/` and invoke it from there.
      - **Rust (`cargo bench`)**: `cargo` discovers benches only under the project's `benches/`
        directory (registered in `Cargo.toml` or auto-discovered by convention). Write the harness to
        `<project-root>/benches/bench_<target>.rs`. Run from `<project-root>` as shown. Remove after
        the skill run.
      - **Go (`go test -bench`)**: `go test` runs only within the package directory. Write the
        `_test.go` harness alongside the source file being benchmarked (same package directory). Run
        from that directory. Remove after the skill run.
      - **JMH (Java/Kotlin)**: JMH requires the benchmark to live in the standard JMH source layout
        (`src/jmh/java/` for Gradle, `src/test/java/` annotated appropriately for Maven). Write to
        that location; run the build task (`./gradlew jmh` or `mvn jmh:benchmark`) from the project
        root. Remove after the skill run.
      
      The `BENCH_CMD` passed to lens agents must reflect the actual invocation path after placement.
      
      ### Rust: criterion
      
      ```rust
      // <project-root>/benches/bench_<target>.rs  (toolchain-native; registered in Cargo.toml)
      use criterion::{criterion_group, criterion_main, Criterion};
      use <crate>::<module>::<hot_function>;
      
      fn bench(c: &mut Criterion) {
          // Replace with realistic input that exercises the hot path.
          let input = setup_realistic_input();
          c.bench_function("<hot_function>", |b| b.iter(|| <hot_function>(criterion::black_box(&input))));
      }
      
      criterion_group!(benches, bench);
      criterion_main!(benches);
      ```
      
      Run: `cargo bench --bench bench_<target> -- --save-baseline before`
      
      ### Python: pytest-benchmark
      
      ```python
      # .outline/optimize/<target>/bench_<target>.py
      from <module> import <hot_function>
      
      def test_<hot_function>(benchmark):
          input_data = setup_realistic_input()
          benchmark(<hot_function>, input_data)
      ```
      
      Run: `pytest .outline/optimize/<target>/bench_<target>.py --benchmark-json before.json`
      
      ### Go
      
      ```go
      // <pkg-dir>/bench_<target>_test.go  (alongside the source file under test, same package)
      package <pkg>  // same-package: no import needed, call unexported functions directly
      
      import "testing"
      
      func Benchmark<HotFunction>(b *testing.B) {
          input := setupRealisticInput()
          b.ResetTimer()
          for i := 0; i < b.N; i++ {
              <HotFunction>(input)  // direct call — no package qualifier
          }
      }
      ```
      
      // For exported-API-only hot paths, swap `package <pkg>` → `package <pkg>_test` and add
      // `import "<module>"`, then call `<module>.<HotFunction>(input)`.
      
      Run: `go test -bench=Benchmark<HotFunction> -benchmem -count=10 .`
      Diff: `benchstat before.txt after.txt`
      
      ### Java / Kotlin: JMH
      
      ```java
      // src/jmh/java/BenchHotPath.java  (Gradle) or src/test/java/ with @Fork (Maven)
      @State(Scope.Thread)
      @BenchmarkMode(Mode.AverageTime)
      @OutputTimeUnit(TimeUnit.MICROSECONDS)
      @Warmup(iterations = 3)
      @Measurement(iterations = 10)
      public class BenchHotPath {
          private InputType input;
      
          @Setup
          public void setup() { input = setupRealisticInput(); }
      
          @Benchmark
          public ResultType bench() { return HotClass.hotFunction(input); }
      }
      ```
      
      Run: `./gradlew jmh` or `mvn jmh:benchmark`
      
      ### JavaScript / TypeScript: tinybench
      
      ```typescript
      // .outline/optimize/<target>/bench.<target>.ts
      import { Bench } from "tinybench";
      import { hotFunction } from "<module>";
      
      const bench = new Bench({ iterations: 100, warmupIterations: 10 });
      const input = setupRealisticInput();
      
      bench.add("<hotFunction>", () => { hotFunction(input); });
      
      await bench.run();
      console.table(bench.table());
      ```
      
      Run: `npx tsx .outline/optimize/<target>/bench.<target>.ts`
      Or via `hyperfine 'npx tsx bench.<target>.ts'` for wall-clock comparison.
      
      ### OCaml: bechamel
      
      ```ocaml
      (* .outline/optimize/<target>/bench_<target>.ml *)
      open Bechamel
      open Toolkit
      
      let test =
        Test.make ~name:"<hot_function>" (fun () ->
          let input = setup_realistic_input () in
          Staged.stage (fun () -> <Module>.<hot_function> input))
      
      let () =
        let cfg = Benchmark.cfg ~limit:100 ~quota:(Time.second 5.) () in
        let ols = Analyze.ols ~bootstrap:0 ~r_square:true ~predictors:[| Measure.run |] in
        let results = Benchmark.all cfg [ test ] in
        let analysis = Analyze.all ols results in
        Bechamel_notty.Unit.run Fmt.stderr analysis
      ```
      
      ---
      
      ## Measurement discipline
      
      - **stddev > 20 % of median**: stop and fix measurement noise before proceeding.
        Causes: CPU frequency scaling, background load, cold cache, OS jitter.
        Fixes: `cpupower frequency-set -g performance`, `nice -n -20`, warm-up runs, pin to a core
        (`taskset 0x1`), disable turbo boost (`echo 1 > /sys/devices/.../no_turbo`).
      - **Always measure what ships.** Optimize + benchmark the release build; debug builds have
        different inlining, bounds-check overhead, and optimization levels.
      - **Re-measure end-to-end (Phase 7, integrated benchmark gate).** A worktree win sometimes
        vanishes after integration due to changed inlining decisions, link order, or PGO profile
        invalidation. The integrated re-measure on the main tree before commit is the ground truth.
      - **Report variance, not just median.** Commit body format: `After: <median> ± <stddev>`.
        A 10 % speedup with 15 % stddev is noise; a 10 % speedup with 1 % stddev is a win.
      
  • SKILL.md 29.5 KB
    ---
    name: optimize
    description: 'Use when asked to optimize code, make a path faster, make this as fast as possible, reduce allocations, repair a regression, profile a target, grill every inefficiency, or run a subsystem or repo-wide performance campaign against a measured floor; when a performance requirement, slowness report, Core Web Vitals miss, or profiling evidence identifies a bottleneck; or for an "extremely optimize" performance campaign, optimizing suspected hot paths without waiting for benchmarks, or estimating hot and complexity-neutral cold paths while refusing complexity theater. Not for remote, credential, publish, deploy, or irreversible changes.'
    ---
    
    # Optimize
    
    Five mode names share one authority: reversible local writes to the resolved target, never push, tag, publish, deploy, or mutate a remote. Full and `extremely-optimize` intentionally select the same measured-floor campaign route, rather than separate procedures; the retired name remains an explicit compatibility mode value. That route runs an isolated five-lens search with an integrated 1.05x gate and an atomic commit. Quick mode runs a single measure-identify-fix-verify loop with a noise-aware keep/revert and a CI guard for the obvious-bottleneck case. `fastopt` mode reports suspected-hot-path hypotheses without mutating code. `fastopt-extreme` mode reports estimated hot paths and complexity-neutral cold-path simplifications while refusing complexity theater.
    
    ## Contract
    
    | Field | Bound contract |
    |---|---|
    | Trigger | The user asks to optimize code, make a path faster, make this as fast as possible, reduce allocations, fix a performance regression, profile and optimize a path, symbol, or diff, or a performance requirement, slowness report, Core Web Vitals miss, or profiling evidence identifies a bottleneck; asks for a measured-floor campaign, hypothesis-only suspected-hot-path analysis, or estimated hot/cold analysis that refuses complexity theater; or says "extremely optimize" or "grill every inefficiency". |
    | Authority | Full and `extremely-optimize` modes write only the exact VCS-tracked source-target set shown before mutation plus `.outline/optimize/<target>/` (destructive; rollback is version control); quick mode writes only the named target and an authorized CI performance-budget or field-monitor guard; `fastopt` and `fastopt-extreme` modes are read-only with no file, VCS, credential, paid, published, deployed, or remote mutation. Full mode may commit one winning optimization, but no mode tags, publishes, deploys, or mutates a remote. |
    | Side effect | Full and `extremely-optimize` modes append measurements and decisions to `.outline/optimize/<target>/log.jsonl`, benchmark isolated candidates, gate all boundary surfaces before touch, revert non-wins, apply the winner, and create one atomic commit. Quick mode applies one targeted fix and may add a CI performance budget or field monitor. `fastopt` mode emits labeled hypotheses and benchmark designs. `fastopt-extreme` mode emits hot-path hypotheses, benchmark designs, cold-path simplifications, and complexity-theater refusals. |
    | Done | Full and `extremely-optimize` modes rebuild hot units with a measured 1.05x-or-better win, grade cold units fixed/at-floor/left, remove residue, pass the verifier, and land the target atomically. Quick mode: the identified bottleneck is measurably improved past noise, tests remain green, no new regressions exist, and a CI budget or field monitor guards the metric. `fastopt` mode: every named path has a labeled hypothesis and benchmark design, with no mutation or speed claim. `fastopt-extreme` mode: every hot estimate has a falsifiable benchmark, every cold candidate is complexity-neutral or rejected, and every complexity-theater proposal is refused. |
    | Inputs | The required mode-specific inputs are listed below; the `mode` input selects exactly one route and must not combine a mutating route with a read-only route. |
    
    ## Inputs
    
    - Mode (optional, exact values when supplied): `full`, `extremely-optimize`, `quick`, `fastopt`, or `fastopt-extreme`. The mode selects exactly one route; do not combine a mutating route with a read-only route. When omitted, select from the trigger and evidence.
    - Full or `extremely-optimize` mode (measured-floor campaign): a named resolvable path, symbol, diff, or active local change, or no path only for an explicit repo-wide survey; repo-wide work is opt-in and never inferred. For a bare `extremely-optimize` invocation after that opt-in, profile the repository's own workload and work the ranked list. One representative runnable workload or benchmark command and repository-native verification commands are required. The workload must be supplied or constructed before measurement and must exercise the target for at least one second of wall time. The verifier must be supplied or discovered before any target lands. A supplied profile or named hotspot is optional. Optional controls are a performance budget, maximum gate attempts, maximum wall time, and minimum marginal speedup. An observable approximation is permitted only when the user's request authorizes it and the exact changed contract is confirmed before mutation. If the target or workload cannot be resolved without guessing, stop with exit 11.
    - Quick mode: a resolvable target, a performance symptom and the codebase under optimization, and repository-native verification commands. Existing measurements, profiling evidence, performance budgets, or Core Web Vitals targets are optional.
    - `fastopt` mode: one or more suspected hot paths named by the user (file, function, or call site) and the workload or input shape that makes each path hot. Prior measurements, profiling traces, and environment constraints are optional; absent measurements are unmeasured, not evidence of slowness.
    - `fastopt-extreme` mode: the target code region or module. Call frequencies, profiling data, or prior benchmark results are optional. If no code is supplied, request the target before proceeding.
    
    ## Mode selection
    
    | User says or evidence | Mode | Gate |
    |---|---|---|
    | optimize this path, profile and optimize, reduce allocations, fix a regression, hot-path speedup, make this as fast as possible, grill every inefficiency, or run a measured-floor campaign | full / `extremely-optimize` | Integrated benchmark proves at least 1.05x; adversarial behavior gate; atomic commit |
    | quick optimize, obvious bottleneck, Web Vitals miss, slowness report, or single targeted fix | quick | Improvement past measurement noise; tests green; CI guard added |
    | analyze suspected hot paths without waiting for benchmarks, or name a suspected hot path and its workload | `fastopt` | Read-only hypotheses and seven-part benchmark designs; no mutation or speed claim |
    | estimate hot paths, simplify complexity-neutral cold paths, or refuse complexity theater | `fastopt-extreme` | Labeled hot hypotheses with falsifiable benchmarks; cold simplifications or explicit refusals; no mutation |
    
    When the user names a hot path and a benchmark, use full mode. When the user names a single symptom and an evident bottleneck (N+1 query, missing index, bundle size, re-renders), use quick mode. When the evidence is a profiling trace with one dominant hotspot at least 5% of total time, use full mode; when one evident fix addresses the symptom, use quick mode. Use `fastopt` when the path is suspected but measurement is intentionally deferred. Use `fastopt-extreme` when only call frequency, loop depth, allocation density, or I/O and syscall evidence is available and the request rejects complexity theater. `extremely-optimize` is the explicit name for the measured-floor full route.
    
    ## Procedure
    
    Run exactly one named mode below. Every mode is part of this single procedure; do not combine a mutating mode with a read-only mode.
    
    ### Full mode, `extremely-optimize`: measured-floor campaign
    
    1. **Resolve the target set and bound the write surface.** Resolve one target and bound writes to that target plus `.outline/optimize/<target>/`. Record the exact VCS-tracked source-target set before mutation; generated files and untracked targets are not silently included. For an explicit repo-wide survey with no path, profile the repository workload, rank the targets, and select one target before candidate work; never infer repo-wide scope. Reject architecture-wide redesign and mixed optimization concerns. For a single function under 50 lines with one evident concern, report `auto-skip` and use one candidate; otherwise use all five lenses below. Require the runnable workload and repository-native verifier before measurement. If no workload can exercise the target, classify the run as no workload and stop. Done when: one target, its exact source set, workload, and verifier are resolved and bounded, or an explicit repo-wide survey has produced a ranked list and selected target, or `auto-skip` is reported.
    2. **Pin the workload and baseline.** Run `hyperfine --warmup 3 --min-runs 10 '<cmd>'` and one suitable profiler pass. Record median, standard deviation, minimum, and maximum. Reject the measurement while standard deviation exceeds 20% of the median: pin CPU frequency, isolate the process, widen `--min-runs`, or enlarge the input until the noise clears. Record the top self-time function or widest plateau as `HOT_PATH`. If no path accounts for at least 5% of total time, continue only when call-count evidence identifies a unit whose calls scale with input and instrumentation confirms it; otherwise stop because the workload is not measurable. Done when: the workload runs for at least one second, a stable baseline with standard deviation under 20% of median is recorded, and either `HOT_PATH` is at or above 5% or a scaled-call hot unit is confirmed, or the run is stopped with its blocker.
    3. **Split hot from cold.** Use the profiler pass from step 2 and write both lists. A unit is **hot** when it holds at least 5% of total measured time or its call count scales with input size; everything else is **cold**. Where the sampling profiler disagrees with a call-count argument, believe the call count and confirm by instrumentation. Done when: every relevant unit is on exactly one written hot or cold list.
    4. **State each contract and compute its floor.** Work the hot list in descending order of time share. For each unit, write what it owes its callers based on call sites, tests, and the signature, never its own internals. Compute the floor from that contract alone: bytes that must move at achievable bandwidth, the algorithmic lower bound at a measured per-operation cost, and syscalls or round-trips the protocol cannot avoid. Show the arithmetic with `eval`, never in prose. Divide measured cost by floor; that multiple is the unit's headroom. A unit already within 2x of its floor is finished and moves on. Done when: every hot unit has its contract, floor arithmetic, headroom multiple, and within-2x verdict recorded.
    5. **Classify consumers and derive blind.** Inventory each unit's consumers and mark it **interior** (every caller in-tree, nothing persisted or shipped) or **boundary** (public API, wire or on-disk format, config running in someone else's deployment, or plugin point). Treat reflection, string dispatch, generated code, external integration, and other channels static analysis cannot resolve as boundaries until evidence changes the classification. Build the replacement from the contract and floor alone, without reading the old implementation for structure; reading it reproduces the costly shape. Choose the data layout that puts the floor in reach: contiguity, batching, hot and cold fields split, or one pass where there were three. Done when: every consumer is classified and the replacement is written from the contract and floor alone.
    6. **Audit the divergence.** Walk the old implementation branch by branch and classify every behavior as folded into the replacement (**essential**) or cut (**residue**), with a one-line reason. Read for guards, early returns, side effects, ordering guarantees, error semantics, and state transitions. A branch never read is a feature deleted by accident. Done when: every old-implementation branch is classified as essential or residue.
    7. **Gate boundaries before mutation.** Present every surface marked boundary in step 5 and get an explicit answer before touching it. Interior surfaces need no ask and may be demolished. Do not cut a boundary on silence or after a no. Done when: every boundary surface has an explicit answer before any touch and all interior surfaces are demolished.
    8. **Locate the benchmark evidence.** Locate or create a minimal benchmark under `.outline/optimize/<target>/`. Use the already captured step 2 workload and baseline; do not run a second baseline. Append the baseline statistics and benchmark command to `log.jsonl`. Do not continue while standard deviation exceeds 20% of the median. Done when: the existing baseline evidence and command are appended to `log.jsonl`.
    9. **Start an append-only run record.** Before candidate work, append an `in-progress` record containing a run ID, target, start time, stop limits, and a fingerprint of the target revision, hot-path source, and benchmark command. Never rewrite or truncate the log. On interruption, resume only when the fingerprint matches and a fresh baseline agrees with the recorded baseline; otherwise mark measurements stale and start a new run. Reuse matching recorded candidates and rerun only missing candidates. Done when: the in-progress record and fingerprint are appended.
    10. **Launch disjoint candidates.** Unless `auto-skip` applies, launch five independent, worktree-isolated candidates together. Give each the same hot-path source, benchmark, and baseline, but one distinct lens: `algo` changes complexity or removes work; `data` changes representation or layout; `cache` reuses valid results with explicit invalidation and bounds; `concur` changes safe parallelism or contention; `arch` removes a local boundary or transfer cost without redesigning the module. State that the lenses are disjoint, worktrees are isolated, and candidates become read-only after reporting. Done when: five isolated candidates are launched, or `auto-skip` uses one candidate.
    11. **Measure and record each candidate.** Require each candidate to apply one transformation and run the same benchmark protocol. Return its lens, change summary, before and after medians, speedup ratio, behavior assessment, readability cost, and patch. Append each candidate record before scoring it. Do not record a failed candidate, so a resumed run retries it. Done when: every viable candidate result is appended before scoring.
    12. **Score and rank.** Drop failed results and score each remaining candidate as `speedup_ratio * behavior_safety * (1 - readability_cost * 0.3)`, where exact behavior is `1.0`, a confirmed approximation is `0.7`, and unsafe or undisclosed behavior is `0.0`. Treat an approximation as viable only when the user's inputs authorize it and the changed contract is confirmed; otherwise stop with exit 14. Rank the winner and runner-up and append the ranking. Stop if no candidate reaches 1.05x. Done when: candidates are scored, ranked, and appended, or a terminal no-candidate or unconfirmed-approximation result is recorded.
    13. **Run the adversarial behavior gate.** For the leading candidate, compare original and optimized behavior over output identity, error semantics, public contracts, empty and boundary inputs, negative values, NaN where applicable, and concurrent call sequences. Append every gate verdict and failure scenario. On failure, discard that candidate and consider the next ranked candidate. Done when: the leading candidate passes every adversarial gate with verdicts appended, or all candidates are discarded.
    14. **Enforce promotion limits.** Before each promotion, enforce the configured maximum attempts, maximum wall time, and minimum marginal-speedup floor; default maximum attempts to the viable-candidate count and the marginal floor to 1.02. If a limit trips before any candidate passes, append the best-so-far and commit nothing. If candidates are exhausted, stop with the precise terminal class. Done when: a candidate is promoted within all limits, or promotion stops with the limit or exhaustion recorded.
    15. **Measure, prove, and promote only a win.** Apply only the gate-cleared patch to the main worktree. Run the same step 2 workload with three warmups and at least ten measured runs, append the integrated median, variance, and speedup, and discard the target patch if `baseline_median / integrated_median < 1.05`. Run the repository's verifier and cover every essential behavior from step 6 that no test reached. Done when: the integrated benchmark proves at least 1.05x speedup and all required behavior is covered, or the target is restored with the blocker recorded.
    16. **Land one concern.** Delete the old unit and every symbol reachable only from it. Commit exactly the named target as one optimization concern. Include the hot path, lens, rationale, baseline and integrated medians with variance, ratio, and any confirmed approximation contract in the commit message. Remove only `.outline/optimize/<target>/agent-*` worktrees, preserve the log and benchmark evidence, and append the authoritative terminal `run` record with status `done` and exit 0. Done when: one atomic optimization commit is made, residue symbols return nothing, candidate worktrees are removed, and the terminal run record is appended.
    17. **Grill cold paths.** Cold code is off the clock; buying speed with complexity is a loss. Hunt waste that costs something other than time on this workload: complexity that bites at a larger N, allocations and retained memory, redundant I/O and repeated round-trips, startup and build cost, artifact size, and dependency weight. Every unit on the cold list takes one verdict: **fixed** (name the cost that fell), **at floor**, or **left** (with the reason). A cold fix that adds a branch, cache, or configuration knob to buy microseconds is rejected. Done when: every cold unit has a fixed, at-floor, or left verdict.
    
    Work one target at a time. Half-rebuilt is the forbidden state: finish a target or revert it. Scope equals the ask; never escalate a named target into a repo-wide campaign.
    
    ### Quick mode
    
    1. **Establish baseline.** Measure the bottleneck with profiling tools or timing data before touching any code. Record the specific metric, the tool or method used, and the measured value. If a baseline cannot be established, stop and report blocked. Done when: the metric, tool, and measured value are recorded.
    2. **Identify the specific bottleneck.** Use the symptom to determine the profiling target: frontend performance (Lighthouse, DevTools Performance tab, web-vitals RUM), backend latency (APM, query logging, EXPLAIN ANALYZE), bundle analysis, or heap profiling. Do not assume the cause. The query plan is the measurement for database queries; the trace is the measurement for frontend jank. Done when: the profiling target is determined from the symptom.
    3. **Fix the identified bottleneck only.** Apply one targeted change. Code it completely before measuring again. Common fixes: N+1 queries -> single query with join or include; unbounded pagination -> limit and offset; missing index -> `CREATE INDEX` with a composite key shaped to the query; connection pool exhaustion -> size the pool to the database ceiling; large bundle -> code splitting or lazy loading; unoptimized images -> responsive `srcset`, lazy loading, or a modern format; unnecessary re-renders -> `React.memo`, `useMemo`, or stable references; missing caching -> cache expensive reads with a stated TTL and key design. Done when: one targeted change is coded completely.
    4. **Re-measure under identical conditions.** Use the same tool, same conditions, and same measurement method as the baseline. Make one change at a time. Done when: the after-measurement is recorded under identical conditions.
    5. **Keep or revert strictly.** Past noise and tests green: keep. Within noise or tests red: revert immediately. Neutral is a revert. An optimization that wins by dropping needed work is a revert. Done when: the change is kept (past noise, tests green) or reverted (noise, tests red, or neutral).
    6. **Guard the metric.** Add a synthetic CI performance budget or a field monitor (RUM p75) for the primary metric. This prevents the fix from regressing unseen. Done when: a CI performance budget or field monitor guards the primary metric.
    
    ### `fastopt` mode: hypothesis-only analysis
    
    1. **Read each named path.** For each suspected hot path, read the source and surrounding call graph read-only. Record the inputs, allocations, loops, and branches that plausibly dominate cost. Done when: every named path is read and its cost-plausible elements are recorded.
    2. **Label observations as hypotheses.** For every cost observation, state the assumed workload, assumed dominant operation, and assumed magnitude rank. Label it a hypothesis, never a finding, and make no speed claim. Done when: every observation has its hypothesis label, workload, dominant operation, and magnitude rank.
    3. **Design a falsifiable benchmark.** For each hypothesis, name the metric, baseline, variant, workload generator, warm-up, repetition count, and noise controls that would confirm or refute it. Done when: every hypothesis has all seven benchmark elements.
    4. **Bound the implied change.** Restrict any implied change to the named path; do not propose edits outside it or assume a fix is correct. Done when: every hypothesis has a bounded change scope.
    5. **Report measurement blockers.** If a hypothesis cannot be tested without mutating code, state the minimal mutation needed to measure it and stop before performing it. Done when: the blocking reason and minimal mutation are stated, or the hypothesis is testable read-only.
    6. **Emit without mutation.** Emit the hypotheses and benchmark designs as chat output. Do not mutate any file and do not claim a speedup. Done when: the chat report is emitted with no mutation or speed claim.
    
    ### `fastopt-extreme` mode: estimate and complexity-neutral simplification
    
    1. **Bound scope.** Restrict analysis to the named code region or module and do not widen to unrelated code. Done when: scope is bounded to the named region or module.
    2. **Estimate hot paths.** Estimate hot paths from call frequency, loop depth, allocation density, and I/O or syscall blocking. Label every estimate as a hypothesis, not a measured fact, and state its basis. Done when: every hot-path estimate is labeled with its basis.
    3. **Classify cold candidates by complexity.** Identify complexity-neutral cold paths whose optimization adds no new abstraction, wrapper, configuration flag, caching layer, or indirection. The change must be simpler than or equal in complexity to the original. Done when: every cold candidate is classified as complexity-neutral or rejected.
    4. **Design hot-path benchmarks.** For each hot-path hypothesis, state the metric, baseline measurement, and falsification condition under which the hypothesis is rejected. Done when: every hot-path hypothesis has a benchmark design with its metric, baseline, and falsification condition.
    5. **Propose cold simplifications.** For each complexity-neutral cold candidate, state the specific simplification and why it adds no complexity. Done when: every cold candidate has its simplification and complexity justification stated.
    6. **Refuse complexity theater.** Reject any proposal that introduces a new abstraction, wrapper, flag, caching layer, or indirection whose complexity exceeds the gain it claims. State the complexity cost and claimed gain. Done when: every complexity-theater proposal is refused with its cost and claimed gain.
    7. **Emit without mutation.** Emit all hypotheses, benchmark designs, simplification proposals, and refusals as chat output. Do not mutate any file. Done when: the chat report is emitted with no file mutation.
    
    ## Failure and recovery
    
    ### Full mode and `extremely-optimize`
    
    Full and `extremely-optimize` intentionally share this measured-floor route. The exit map below is canonical for both names, rather than maintaining two procedures or two conflicting code maps.
    
    | Terminal class | Recovery |
    |---|---|
    | No workload (exit 10) | The target's cost cannot be reproduced on demand. Construct a runnable workload or stop; do not claim success. |
    | Baseline too noisy (exit 11) | Standard deviation exceeds 20% of median and cannot be cleared. Clear the noise or stop. |
    | No measurable hotspot (exit 11) | No path accounts for at least 5% of time or the workload is not measurable. Report the blocker and commit nothing. |
    | No headroom (exit 12) | Every hot unit is already within 2x of its floor. Report the terminal result and commit nothing. |
    | No candidate or integrated no-win (exit 13) | No candidate or integrated result clears the 1.05x gate. Revert the replacement or target patch and keep the original. |
    | No win or failed behavior/check gate (exit 13) | A candidate fails the campaign gate, or the repository checks fail. Revert the replacement or target patch and keep the original. |
    | Approximation unconfirmed (exit 14) | The request did not authorize the approximation or the changed contract was not confirmed. Discard that candidate and do not promote it. |
    | Divergence unclassified (exit 14) | Old behavior is neither folded in as essential nor cut as residue. Complete the step 6 walk before proceeding. |
    | Mixed optimization concerns (exit 15) | The proposed commit mixes concerns and must be split before retrying. |
    | Boundary cut without an answer (exit 15) | A published surface was destroyed on silence or after a no. Restore it and settle the question. |
    | Campaign stalled mid-target (exit 16) | A target is half old and half new. Finish it or revert it; never ship it. |
    | Scope exceeded (exit 17) | A repo-wide sweep ran off a named target. Revert the untargeted work. |
    | Stopping limit (exit 16) or failed verifier (exit 13) | Before commit, restore only the named target and remove only run-created candidate worktrees; retain append-only evidence, append the exact terminal class, commit nothing, and never revert an unrelated commit. Resume only through the fingerprint match and fresh-baseline agreement. |
    
    Partial-result rule for full and `extremely-optimize`: a target that has not reached the done predicate is reverted to its pre-campaign state; no half-rebuilt target remains. Non-wins and untargeted work are reverted. Never swallow an error or pretend the done predicate holds.
    
    ### Quick mode
    
    | Failure | Response |
    |---|---|
    | Baseline unavailable | Measurement tools are unavailable or the codebase cannot be profiled. Result: blocked. Do not proceed without baseline evidence. |
    | No bottleneck found | Profiling reveals no measurable code-level bottleneck. Report uncertainty and whether environmental or statistical noise is suspected. |
    | Fix produces no measurable gain | Improvement is within noise range of the baseline. Revert. Never keep a neutral change. |
    | Correctness regression | Tests fail or behavior changes after the fix. Revert immediately. Correctness gates the metric. |
    | Fix exceeds available authority | The bottleneck requires unavailable credentials, remote mutation, or infrastructure changes outside local write scope. Document the requirement and do not widen authority. |
    
    Partial-result rule for quick mode: reverted code leaves no trace. Keep a ledger entry (baseline, fix applied, before/after measurement, and verdict) so discarded ideas are not re-profiled.
    
    ### `fastopt`
    
    | Failure | Response |
    |---|---|
    | Unmeasured path | Mark the hypothesis unmeasured; do not infer slowness from absent data. |
    | Ambiguous hot path | Ask the user to name the path and workload; stop rather than guess. |
    | Benchmark infeasible read-only | State the blocking reason and the minimal mutation that would unblock measurement; do not perform it. |
    | No recovery widens authority | `fastopt` never mutates files, VCS, credentials, or remote state; a blocked result is emitted as blocked, not as success. |
    
    ### `fastopt-extreme`
    
    | Failure | Response |
    |---|---|
    | No code supplied | Request the target code region or module; do not guess or analyze from memory. |
    | Path unclassifiable | Label a path unclassified and exclude it from optimization proposals. |
    | Complexity theater detected | Refuse the proposal and record its complexity cost and claimed gain. Do not emit it as a valid optimization. |
    | Partial result | Emit obtained hypotheses and designs, and mark every unclassified or refused item so the done predicate is not falsely satisfied. |
    | Non-mutation | No file, VCS, or remote change is made. Rollback is not applicable. |
    
    ## Output
    
    **Full mode and `extremely-optimize`.** On success, return exit 0 with the commit identifier, target, selected lens, benchmark command, baseline and integrated statistics, measured speedup, behavior-gate result, repository checks, cold-path verdicts, and durable log path. On failure, return the applicable terminal class, unchanged or rolled-back target state, measurements obtained, and the precise blocker; never report a worktree-only result as a landed win.
    
    **Quick mode.** Return optimized code with before/after measurements, plus a ledger entry per attempt (kept and reverted) documenting the hypothesis, baseline, result, and verdict. Each entry states the metric name, baseline value, result value, and tool used.
    
    **`fastopt` mode.** Return one labeled hypothesis per suspected path and one benchmark design per hypothesis containing the metric, baseline, variant, workload generator, warm-up, repetitions, and noise controls. Report blocked paths with their reason and minimal measurement mutation. Never mutate or claim a speedup.
    
    **`fastopt-extreme` mode.** Return hot-path hypotheses with falsifiable benchmark designs, complexity-neutral cold-path simplification proposals, and explicit complexity-theater refusals with their complexity costs and claimed gains. Never mutate a file.
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related