Reference docOpen

Hill-Climbing on an Eval

If you arrived via /claude-api hillclimb: this is the right file. Work through the steps in order - Steps 0 and 0.5 are hard prerequisites; Steps 1-2 feed the plan sign-off you need before the loop starts. Don't summarize this guide; execute it.

Hill-Climbing on an Eval

If you arrived via /claude-api hillclimb: this is the right file. Work through the steps in order - Steps 0 and 0.5 are hard prerequisites; Steps 1-2 feed the plan sign-off you need before the loop starts. Don't summarize this guide; execute it.

This guide is for iteratively improving a Claude-powered app against a fixed eval: run the eval, read the failures, change something in the codebase, run again, and repeat until the score stops moving or the budget runs out. It picks up where eval-building leaves off - the user has a way to measure; now they want to move a number: usually the quality score up, but just as often cost or latency down while quality holds.

The loop itself is simple. What makes it work or not is discipline: reading the actual transcripts rather than pattern-matching on summary stats, knowing which change produced which effect, keeping a clean record of what was tried, and not fooling yourself by tuning on the same cases you score on. The number that matters at the end is the test-set delta versus the starting point - improvement on the cases you read while iterating is not the result, it's the process. Those are the things this guide is opinionated about. Everything else - what to change, how many rounds to run, when to stop - is the user's call, and you should ask rather than assume.

Stay recommendation-forward - propose a concrete default with every question so the user can just say "yes" - and treat the plan sign-off at the end of Step 2 as the minimum approval you need before the loop starts. How often to check in during the loop is one of the Step 2 questions; don't ask it separately here.

Talking to the user. These steps are your execution plan, not a script to narrate. Keep user-facing messages short and outcome-focused: what you ran, the score, what you'll try next, a path or link to open. Don't walk the user through which step you're on, which files you're writing, or internal bookkeeping unless they ask. One concise update per round is enough; put detail in report.html and narrative.md, not the chat. When you need a decision - what's in scope to change, which change to try next, whether to spend another round - use the AskUserQuestion tool rather than free-text prose: batch up to four related questions into one call, give each two to four concrete options with your recommendation listed first and labelled "(Recommended)", and don't add your own "Other" option - the tool appends a free-text one automatically. If AskUserQuestion isn't available (headless runs), fall back to one short question at a time.
Run the eval command in the background; keep the conversation free. An eval run can take minutes to hours - don't make the user sit through it, but don't wrap it in a subagent either. Each round, do the quick parts yourself in the main session - apply the change, write vN/change.* - then launch the runner - the eval command itself, not an Agent - as one Bash call with run_in_background: true and a timeout that covers the run (normally at most 7200000 ms; with no timeout a background command may be stopped after 30 minutes; if the runner is stopped at its limit, re-launch the same command - resume is idempotent). You'll get a completion notification when it exits; meanwhile stay available for the user's questions and, when useful, spawn the analyzer subagent (Step 4) - the only subagent this loop uses. When the runner finishes, verify on disk before trusting the notification: vN/results.jsonl should have N×R rows and vN/summary.json should exist; if rows are short, re-launch the same command (resume is idempotent at (case, rep), so it picks up where it stopped). Then regenerate report.html via the report builder (full or lite, per build-eval.md), tell the user the score and the path, and pick the next change - via AskUserQuestion if the Step 2 cadence has you checking in now, otherwise just state it and proceed. Before the first unattended round, show the user the exact runner command and ask them to allow it for the session, so a permission prompt can't stall a round nobody is watching. Be clear with the user about what that allowlist entry is: it is the security boundary for the loop - whatever that command executes runs under their standing approval - so keep it to the one runner command, and keep the runner's dependencies pinned (a lockfile, npm ci). The scaffold's harness-integrity gate is a change detector layered on top, not a second boundary: the runner hashes itself, any lockfile beside it or in the directory it is run from, plus _state.json.harness_paths, and exits 2 when the hash differs from the one last recorded with --approve-harness, so a round that edits a listed harness file - by accident or by an analyzer proposal - stops the next run until the user has seen the diff and said OK. It does not cover node_modules/, interpreter or SDK versions, or any file not listed in harness_paths, and it cannot stop an agent that can already write anywhere the user can; the allowlist scope is what does that. Never pass --approve-harness from an unattended round; it is the user's to run. If you're running headless (-p / SDK) there's no conversation to keep free. In a one-shot -p run, run the eval in the foreground, because background work is stopped when the run ends; in an SDK session that stays open, launch it in the background exactly as above. When the user asks how a run is going, answer from the runner's own progress line (the scaffold prints k/N done ... ~Ns left every 30 s and mirrors it to vN/progress.txt) - one line, not a narration.

Step 0: Confirm there's a runnable eval

Ask the user:

Do you have an eval script for this flow - something I can run from the command line that exercises the app against a fixed set of prompts and prints a score?

If yes, ask for the command and where it writes its per-case results. Also ask whether the runner retries failed cases - and if so, which attempt's grade, transcript, and usage land in the results; score strict per attempt (a case that passed only on retry is a fail unless the user decides otherwise) and make sure retry attempts show up in cost accounting rather than being silently absorbed. Make sure the eval measures the outcome you're trying to improve, not just a behavior you assume correlates with it. If you're using a behavioral proxy because the real outcome is too expensive to measure every round, say so up front and run the winner on the real eval once at the end. Each eval run must capture, per case: the full transcript, model, usage (input/output/cache token counts), and the grade dict - not just an aggregate score. The transcript and the score for a case must come from the same model call; don't re-run the model separately to collect a transcript and then grade a different sample. Search the user's codebase for an existing runner or wrapper for this eval that already persists those fields before building anything new. Run it once to confirm it works and see the output shape (or work from a recent results file if one's handy). Then read shared/evals/eval-audit.md and run it against the eval - cases, runner, grader - reporting per its §6; an eval that wasn't built by build-eval hasn't had these checks, and Step 0.5 below is the must-pass subset, not the whole list.

If no, stop here. Hill-climbing without an eval is just editing and hoping. Route the user to /claude-api build-eval (read shared/evals/build-eval.md and run that flow), and come back when there's a script and a baseline number.

If the reason for hill-climbing is a model migration - the user wants to move to a newer Claude model and tune their prompts for it - read shared/model-migration.md alongside this guide so your proposed changes account for the new model's breaking changes and behavioral shifts.


Step 0.5: Prove the eval can be climbed

A runnable eval (Step 0) is not yet a trustworthy one. Before you spend a round, rule out the possibility that the harness is lying to you - a hill-climb on a broken measurement is worse than none, because you'll "improve" an artifact, declare victory, and ship nothing. eval-audit.md (loaded in Step 0, or by build-eval if that's how the eval was made) is the full checklist; the checks below are the ones that must pass before round 1, each of which has silently wrecked a run:

  • Prove the eval can detect the win you're after. From the baseline at its actual rep count, put three numbers in front of the user: the noise floor on the Step 1 target (paired-difference CI half-width at the current n × R - eval-audit.md §5 has the arithmetic), the headroom (ceiling minus baseline), and the smallest improvement they'd act on. If the noise floor is bigger than either, the loop cannot show a real in-scope win no matter how good the changes are - say so now, not after five rounds, and offer more reps, more cases, or a finer-grained metric before starting.
  • Prove the mechanism is actually wired. Whatever the score depends on - a memory store the agent writes to, a tool it should call, a file it should read - run a one-off probe that it takes effect end-to-end before you trust any score: write a value and read it back through the same path the eval uses, or confirm the tool actually shows up in the agent's tool list. If the eval comes back as though the mechanism does nothing, check the wiring before concluding "the model can't do this."
  • Recompute the headline number from raw per-case results. Don't trust an aggregate field in a manifest - recompute the number you'll report from the per-instance values in results.jsonl yourself. Mean-vs-sum and similar aggregation mixups produce spectacular phantom results that look exactly like a breakthrough until you hand-check them. A too-good-to-be-true number is a measurement bug until a manual cross-check says otherwise; make the cross-check a step, not a lucky catch.
  • Spot-check the grading on the baseline failures. For a handful of the lowest-scoring baseline cases, read the model's actual output, the judge's reasoning, and the expected value: did the judge grade fairly, and is the ground truth correct? A wrong rubric or wrong expected value will send every round chasing a harness fix for a measurement error. If you find one, fix the rubric/GT and re-grade the baseline in place (re-run the judge on the stored transcripts - no model re-run needed) before round 1. While you're there, triage every zero-scoring baseline case: classify each as harness error vs. grader verdict (read the per-case error field or errors sidecar, wherever the runner records failures), and exclude the harness-error cases from the scored denominator before round 1. Spot-check the graders your gates depend on: confirm each reads the artifact the agent actually writes, and that nothing outside the fixture can flip it (host repo state, pre-seeded files, wall clock) - a grader that escapes its fixture measures the environment, not the agent.
  • Verify what served the requests and how the runner retries. Run one smoke case and read model from the response, not your config - silent server-side substitution invalidates every comparison - and confirm request retries back off with jitter and are counted, not absorbed. runner-scaffold.mjs asserts both by default; a user-supplied runner needs the check (eval-audit.md §2-3).
  • If the artifact you score is generated from the artifact you tune, measure its build variance first. Some flows put a stochastic generation step between the lever and the score: the prompt you're iterating on builds something - a memory store, a retrieval index, a synthesized corpus - and the eval then scores reads against the built thing. When that build runs once per variant and every rep reads the same build, reps and their CIs measure only the noise of scoring a fixed build; the build's own run-to-run variance is sampled once per variant, invisible to every gate, and can be the larger term. Before round 1, rebuild the baseline artifact two or three times with the prompt unchanged and score each build the same way: the spread across those no-change rebuilds is the floor a one-edit effect has to clear. In one climb, three builds of the same prompt spanned ~7 points against rescore noise near ±1.4 on the train mean - every edit had been compared against a single baseline build, and the loop could not tell any of them from the default. If the build spread exceeds a plausible one-edit effect, build K times per variant and compare build-pooled means, or move the lever closer to the score; adding reps over one build can't see it.

If the flow spawns subagents, also confirm the parameters you're iterating on - model, effort, prompt - actually reach every subagent and that traces capture their turns; a knob that silently doesn't propagate makes every round on it a no-op.

If you have a choice of which eval or slice to climb on, pick the one with the most signal per token:

  • The mechanism must actually drive the score - disable it and re-run; if the score barely drops, the eval isn't measuring what you're tuning, and no amount of tuning will show up.
  • Low run-to-run variance at small rep counts - if the baseline's per-rep scores swing widely, a "win" is indistinguishable from variance. Raise reps or pick a calmer slice rather than chasing noise.
  • An inspectable mechanism - prefer an eval where you can see why a variant won (an artifact it wrote and reused, a tool-call trace) over a black-box delta you can't attribute and that may not generalize.

Step 1: Agree on the goal, what to change, and how it's wired in

First, the goal. "Make the number go up" is only one of the things a hillclimb is for, and the loop behaves differently for each - so always ask before anything else, via AskUserQuestion, listing the metrics and perf fields the eval actually records:

What should this hillclimb optimize? - Raise <headline metric> (Recommended when the eval is new and the score has obvious room) - Cut cost per request - hold <headline metric> within noise of baseline - Cut latency - hold <headline metric> within noise of baseline - Move to <other model> and recover <headline metric> on it

The answer sets three things for the rest of the loop: the primary target the analyzer is pointed at each round (Step 4), the metric the stopping condition is phrased against (Step 2), and the guardrails - every other recorded metric becomes a must-not-regress-outside-noise constraint rather than something to improve. If the goal is cost or latency, make sure cost_usd / latency_s is in _state.json's perf_fields whether or not it was picked as a display column in build-eval - the goal forces the column. Record the goal in _state.json (e.g. "approve_each_round": false, "goal": {"target": "cost_usd", "direction": "lower", "hold": ["accuracy"]}) so a resumed session doesn't silently revert to climbing the score.

Then ask which part of the app is on the table:

What do you want me to iterate on? For example: - The system prompt - A specific skill or instruction file the agent reads - Tool descriptions - Model choice or API parameters (effort, thinking, max_tokens) - The agent loop / harness code itself - All of the above - whatever moves the target And is there anything that's off-limits - parts of the prompt or code I should leave alone even if I think changing them would help?

Record the answer. This defines what you'll be editing each round; the off-limits list is a hard constraint. Also have the user name the harness paths - the runner script, grader, and any file the eval command executes - and record them in _state.json.harness_paths (repo-relative); the runner refuses to start when any of them changed since the user last ran it with --approve-harness, so an unreviewed edit to a listed file surfaces as a stopped round rather than a silently different eval (the gate detects changes to the files it digests - the session allowlist for the runner command is the boundary itself). If the user says "whatever moves it," that's fine - but still ask about off-limits, because there's almost always something (a compliance disclaimer, a tone requirement, a tool that's contractually required). For a cost or latency goal, model choice and API parameters (effort, max_tokens, caching) are usually the biggest levers - make sure they're explicitly in or out.

If the target is a skill or instruction file, confirm how it reaches the model during the eval: is it appended directly into the system prompt (which isolates "is the content good?"), or loaded through the app's real skill-discovery path (which also tests "does the model find and use it?")? Both are valid and they measure different things - ask which one the user wants, and make sure the eval runner matches.

Two things you can choose freely unless the user objects: the model that reads transcripts and proposes changes doesn't have to be the model under test - using a stronger model for diagnosis is often worth it - and the proposed changes don't have to be prose. If a concrete helper script, a code snippet, or a worked example would guide the model better than another paragraph of instructions, write that instead.


Step 2: Agree on a stopping condition (and a budget, if cost matters)

Ask via AskUserQuestion how many rounds to run before checking back in:

One pass over the full set is N cases × R reps on <model>, roughly ~Y minutes. How many rounds before I check back in? - Until plateau (Recommended): keep going until the Step 1 target improves by less than delta for K consecutive rounds (K >= 3 - two flat rounds is too few to call a plateau), or a guardrail metric regresses outside noise, then report. - One round at a time: propose, run, report, ask again. Pick this to steer each change. - N rounds: run N, report, ask whether to continue. (User types N.)

This is both the stopping condition and the check-in cadence - the loop runs autonomously between check-ins.

Set delta above the noise floor from Step 0.5 - a stopping threshold finer than the eval can resolve never fires honestly.

If reducing cost is itself the Step 1 goal - not just a ceiling on this loop - read shared/evals/cost-hillclimb.md before planning rounds: it narrows this guide's loop to the cost objective, with a lever search order (caching health -> prompt audit -> a model × effort staircase walk -> prompt climb on the frozen model -> a down-left re-probe -> a registered joint confirm), pre-registered adoption gates, and cost-specific stopping rules. (shared/cost-optimization.md is the no-eval checklist for the same goal; inside this loop, follow cost-hillclimb.md.)

If the user asks what the loop will cost or gives you a budget, also present the total loop cost - baseline plus every planned round - and get a ceiling. Estimate it from real numbers, don't guess:

  1. From a recent results file (or a small sample run if none exists), sum the usage fields across all cases, including judge calls if model-graded.
  2. Multiply by the per-token prices for the user's provider - the Current Models table in SKILL.md is first-party; ask or look up if they're on Bedrock/Vertex/etc. Cached reads are ~10× cheaper than base input. This gives the cost of one pass at one rep.
  3. Measure wall-clock for that pass - time a real run end-to-end and scale; don't estimate.
  4. Add a rough allowance for the per-round analysis turns - typically small relative to the eval itself.

Present (N + 1) × R × $X and ask what total spend they're comfortable with. If they hesitate, offer the levers: fewer rounds, fewer reps, a cheaper judge model, or trim to the discriminating cases (rank by cross-rep variance from the baseline run, keep the top K, then run the full set on baseline + winner at the end to confirm). Whatever they pick, the default inside the loop is still to run the same set every round; never silently subset it to fit. The N, R, and case count you present must be what you actually run - if reps/split later push the total above the approved ceiling, mention it before proceeding.

When the goal is cost and the candidate change is prompt text, price the instruction itself first - its per-request input tokens × requests per case, against the predicted saving; some candidates disqualify on paper before you spend a round.

Get the plan approved

Before you touch any files, confirm the plan with the user and get a clear yes. Three pieces:

  • A scope table - two columns, "will change" and "won't touch," populated from Step 1. The user should be able to glance at it and know exactly which files and knobs are in play.
  • Who applies changes - by default you apply each round's change and the user reviews the result; offer the alternative of showing each round's diff for a yes/no before it runs (recommend it when the artifact is customer-facing copy, legal/medical/regulated content, or anything the user said a human must own). Record the choice as _state.json.approve_each_round.
  • A short approach paragraph - how you intend to run the loop. For example: "Each round I'll have a fresh analyzer read the train traces and propose one change; I'll apply it, rerun the full set, and post a status table. I'll spend rounds only on changes big enough to show above the eval's noise floor - a rewritten section or a new rule, not a reworded line. Early on I'll try different levers (tool descriptions, the system prompt, effort) to find where the headroom is. Running 8 rounds max."

Don't make the user ask for this; produce it by default. It's what lets them trust the loop enough to let it run without checking in every twenty minutes.


Step 3: Set up state, split the data, and take a baseline

The loop will run for multiple rounds, possibly across multiple sessions. Keep state on disk so it survives interruption and so the user can see the history. If the user already has a results directory and file layout from a prior eval, keep theirs - what matters is that each run produces the per-case data from Step 0 (full transcript, model, usage, grade dict, all from the same model call); the layout below is the default when starting fresh. Otherwise, create a working directory - .claude/hillclimb/<flow-name>/ is a reasonable default, but put it wherever fits their repo - with this layout. The report generator reads this tree directly, so the file names and field names below are an exact contract, not a suggestion:

.claude/hillclimb/<flow>/
  _state.json            # loop state + report config - shape below
  metrics.md             # free-text rubric (markdown) - what each metric means; the full viewer renders it
  narrative.md           # model-authored running exec summary - rewritten after every round; final version in Step 5
  trajectory/
    scores.tsv           # derived by the report builder (full or lite): per-case mean of the primary metric, one column per round
  baseline/
    results.jsonl        # one JSON object per (case, rep) - shape below
    summary.json         # per-variant header - shape below
    traces/
      <id>_rep<k>.json   # full transcript, one file per rep, every case (the analyzer is handed only the train ones - Step 4)
  v1/
    change.md            # what changed this round and why (from the analyzer)
    change.patch         # the actual diff applied to the codebase
    results.jsonl  summary.json  traces/<id>_rep<k>.json
  v2/
    ...

_state.json - everything here is optional except the split ids; metrics and perf_fields let you override what the report infers from the data. best.round is 0-indexed (0 = baseline). If the eval has multiple metrics, the first binary-kind metric (else metrics[0]) is the report's headline - order the list accordingly. goal records the Step 1 answer - the metric or perf field the loop is optimizing, its direction, and the metrics it must hold - so best is picked against the goal, not blindly against the headline:

{ "current_round": 2, "reps": 2,
  "goal": {"target": "pass", "direction": "higher", "hold": ["cost_usd"]},
  "approve_each_round": false,
  "best": {"round": 1, "test_score": 0.70},
  "train_ids": ["case_01", ...], "test_ids": [...],
  "harness_paths": ["eval/run-eval.mjs", "eval/grade.mjs"],
  "harness_sha": "...written by the runner on --approve-harness; never edit by hand...",
  "metrics": [
    {"id": "pass",      "kind": "binary", "label": "Pass"},
    {"id": "quality",   "kind": "judge"},
    {"id": "verbosity", "kind": "float",  "better": "lower"}
  ],
  "perf_fields": [
    {"id": "cost_usd",  "label": "Cost",    "unit": "$"},
    {"id": "latency_s", "label": "Latency", "unit": "s"}
  ],
  "prices": { "my-custom-model": {"in": 2.0, "out": 8.0} } }

results.jsonl - one line per case per rep, appended as each case completes so a crash doesn't lose finished work. grade can be a bool, a number, or a {metric_id: number} dict; explanation is an optional {metric_id: "judge reasoning"} sibling for judge-kind metrics. Put the full prompt text in prompt (the report shows it). tags is ordered - tags[0] is the primary grouping key. Record model from the response, not from config - cost_usd is derived from each row's model × usage (plus judge_model × judge_usage when present), so a model swap can't carry a stale rate and the runner doesn't compute cost at all. The full viewer does that derivation when it is on disk; otherwise compute cost_usd per row yourself when you report, with the recipe in build-eval.md § Before the first paid call (the "If the user asks what this will cost" bullets: Current Models prices in SKILL.md; cache writes at 1.25× input, cache reads at 0.1× input) - that is where the status table's $/run and spend come from. The adapter is forgiving on input: prompt_id may also be spelled id or case_id, and if _state.json omits metrics they're inferred from the union of grade keys. Perf keys are read by exact name:

{ "prompt_id": "case_17", "rep": 0, "prompt": "...full prompt text...",
  "tags": ["topic-a", "hard"],
  "grade": {"pass": 1, "quality": 7.2, "verbosity": 3.0},
  "explanation": {"quality": "Cites two sources; balanced."},
  "model": "claude-opus-5-5",
  "latency_s": 12.4,
  "tool_calls": 2, "web_searches": 1,
  "usage": {"input_tokens": 1200, "output_tokens": 480} }

Two more optional per-row keys the report understands: attachments (a list of {kind: "image"|"file"|"url", ref, alt?} shown alongside the prompt) and meta (an arbitrary dict surfaced in the transcript header).

summary.json - per-variant header for the report, not aggregate stats (the report recomputes those from results.jsonl). All optional; target is one of "system_prompt" | "skill" | "tools" | "code":

{ "description": "Enable web_search tool",
  "target": "system_prompt",
  "suspicious": "val lift not replicated on a second seed" }

traces/<id>_rep<k>.json - the verbatim conversation as a JSON list of {role, content, thinking?, name?} turns where role is system | user | assistant | tool_call | tool_result.

The traces/ directories are what the analyzer reads between rounds. Keeping them per-round with one file per rep means that by round 3 the analyzer can diff baseline/traces/case_17_rep0.json against v2/traces/case_17_rep0.json and see exactly what behavior changed. trajectory/scores.tsv is the at-a-glance cross-round view: one row per case, one column per round, cell = that case's mean primary-metric score - derived by the report builder (full or lite, identically) from the results.jsonl files, so the runner doesn't write it and it can't drift.

Make artifacts visible. If the flow consumes or produces visual or structured artifacts - input images or PDFs, computer-use screenshots, generated HTML/SVG/plots, files the model wrote - make sure a human reviewing a case can actually see them, not just a filename - rendered in the Transcripts tab with the full viewer, opened from the referenced path otherwise. The full viewer has prebuilt slots for this; the runner just fills them:

  • Input artifacts - on the results.jsonl row: "attachments": [{"kind":"pdf","ref":"baseline/inputs/case_3.pdf","alt":"source doc"}]. Renders above the first user turn.
  • Output artifacts - on the trace turn that produced them: {"role":"assistant","content":"...","attachments":[{"kind":"html","ref":"v2/out/case_3.html"}]}. Renders below that turn. Write the artifact to disk under the variant dir and ref it relative to the flow root.
  • Rich content in the response text - fenced `html , `svg , `json blocks in an assistant turn's content get a "> Render" toggle automatically; nothing extra to write.

The text continues at the source. Read the rest.

Source: https://github.com/anthropics/skills/blob/main/skills/claude-api/shared/evals/eval-hillclimb.md

Author: anthropics, Anthropic skills. License: Apache-2.0.

Shown here with formatting for the web. Keep the author and license notice when you reuse it.

Related entries

There are more like this in the members library

The Claude Code library holds 13,843 entries. Members can search all of them by meaning and read every one in full.