---
name: sf-metric-optimization
description: Run an SF-native metric optimization loop inside automatic workflows when a task has a measurable target such as runtime, bundle size, test duration, model quality, or benchmark score.
user-invocable: false
model-invocable: true
side-effects: code-edits
permission-profile: normal
triggers:
  - build
  - verify
  - "*"
---

# SF Metric Optimization

Use this skill when SF should improve a measurable metric by trying one focused
change at a time, measuring it, keeping wins, and discarding regressions.

This is a workflow skill. Do not turn it into a user-facing guide. Produce small
state files that another SF unit can resume.

## Required Inputs

- Goal: what metric should improve.
- Command: how to measure it.
- Direction: `lower` or `higher`.
- Scope: files or packages allowed to change.
- Constraints: tests, deps, compatibility, time budget, and off-limits paths.

Infer these from repo context when possible. Ask only when the metric or command
is unknowable.

## State Files

Create or maintain these under `.sf/metric-optimization/` unless the project
already has a better generated experiment directory:

- `STATE.md`: objective, metric, command, scope, constraints, current
  best, and what has been tried.
- `measure.sh`: fast reproducible measurement script. It must print
  `METRIC name=value`.
- `runs.jsonl`: one JSON object per experiment.
- `checks.sh`: optional correctness backpressure.

Keep `STATE.md` terse. It is a resume surface, not a report.

## Loop

1. Read existing state and establish the current best metric.
2. Choose one hypothesis.
3. Edit only in scope.
4. Run `timeout 600 bash .sf/metric-optimization/measure.sh`.
5. Run `timeout 300 bash .sf/metric-optimization/checks.sh` if it exists.
6. Log result as `keep`, `discard`, `crash`, or `checks_failed`.
7. Keep improvements. Revert focused regressions.
8. Update `STATE.md` with one line per meaningful lesson.

Stop only when the stated budget or target is reached, the user interrupts, or
the repo is no longer in a safe state to continue.

## SF Integration

- Treat each experiment as one autonomous unit with a single hypothesis.
- Prefer cheap checks before expensive benchmarks.
- Use SF/UOK gates when available for commit and parity safety.
- Do not write long research narratives. Preserve enough evidence to resume and
  audit the decision.
