Evaluation explained
This guide shows how to measure Safran on your own company's history: how the golden set is built and what it drops, what every retrieval metric means in plain words, how two configurations are compared without fooling yourself, and how the replay evaluation runs agent commands against finished tickets. Every rule, threshold and wording below is taken from @safran/eval.
Two questions, two tools:
| Question | Tool | What it costs |
|---|---|---|
| Can code search find where a ticket's work lives? | safran eval golden + safran eval retrieval | Ticket reads from the tracker and local searches. No agent is run. |
| Does Safran make an agent better at this company's work? | safran eval replay | Real agent runs: money and time. |
Both follow the same three rules: no number without its sample size, no "improvement" without a significance check, and everything skipped or failed is counted and shown.
The short version
The golden set is built from the local link store, so the store and the index must exist first (Keeping the index fresh covers both commands).
$ safran sync --profile /work/acme/safran.yaml
$ safran links refresh --profile /work/acme/safran.yaml
$ safran eval golden --profile /work/acme/safran.yaml
pull requests 5
items kept 3
dropped no ticket 1, plumbing title 1
ticket titles 3 read
languages tr 3
✔ Wrote 3 items to /work/acme/data/eval/golden.json
→ Measure with `safran eval retrieval --profile /work/acme/safran.yaml`.
$ safran eval retrieval --profile /work/acme/safran.yaml
3 items from /work/acme/data/eval/golden.json · index ollama:bge-m3, 7 chunks · 70 ms
Retrieval evaluation: 3 golden items, 1 configuration, k = 10
config slice n err hit@1 hit@5 hit@10 recall@10 MRR nDCG@10 p50 ms p95 ms
------- --------------- - --- ----- ----- ------ --------- ----- ------- ------ ------
default overall 3 0 1.000 1.000 1.000 1.000 1.000 1.000 14 14
default group: backend 2 0 1.000 1.000 1.000 1.000 1.000 1.000 7.2 13
default group: frontend 1 0 1.000 1.000 1.000 1.000 1.000 1.000 14 14
n = queries scored; err = failed searches, excluded from the means.The output is real, from a temporary setup with two tiny repositories and the three tickets of the acme story; progress lines (written to stderr) are left out. A perfect score on seven chunks says nothing about retrieval. What matters is the shape: every row carries its n, and the dropped pull requests are counted by reason.
The golden set
A golden set is a list of questions with known answers, taken from work the company already finished:
- Question: the title of the ticket a merged pull request was done for.
- Answer: the files that pull request changed.
The unit is one item per (ticket, repo). All pull requests for the same ticket in the same repo share the question, so their files are joined into one answer. A ticket that changed two repos gives two items, and each names the other repo in siblingRepos. Item ids are stable across rebuilds: <repo>#<ticket key>, or <repo>#pr-<id> for a pull request without a ticket.
safran eval golden reads pull requests only from the local link store (run safran links refresh first). It then reads each ticket's title from the tracker, four tickets at a time (DEFAULT_TICKET_CONCURRENCY), and asks the code hosts for the repo list so it can check which answer files still exist in the local working trees. Nothing is written to any service. The file goes to <data dir>/eval/golden.json unless --out says otherwise.
What is dropped, and where it is counted
A golden set built from history is free and it is noisy. Every filter counts what it removed in stats, so the set can be read critically. The filters run in this order:
| Stat | Counts | Rule | Default |
|---|---|---|---|
prs | pull requests | Merged pull requests in the store inside the time window. | |
noise | pull requests | The title is plumbing: a merge, a revert, a conflict resolution, "no issue", a cherry-pick, a back-merge, a branch sync written a -> b, or nothing but punctuation. | DEFAULT_NOISE_PATTERNS, plus noisePatterns |
unlinked | pull requests | No ticket key. | Dropped; --include-unlinked keeps them, with the cleaned pull request title as the question |
multi_ticket | pull requests | Linked to more tickets than the limit: a release or a branch merge, not one piece of work. | DEFAULT_MAX_TICKETS_PER_PR = 3 |
candidates | candidates | One per (ticket, repo), formed from what is left. Not a drop. | |
noise_query | candidates | The question itself matches a noise pattern. | |
short_title | candidates | Fewer than two words, or exactly two words that are both generic ("fix bug", "ufak düzeltme") and not identifier-shaped. A word is a run of letters, digits or underscores longer than one character. | DEFAULT_MIN_QUERY_WORDS = 2, DEFAULT_GENERIC_WORDS |
no_files | candidates | No answer file is left after the file filter below. | |
too_wide | candidates | More answer files than the limit: too wide to be "the place" for a title. Applied again after identical questions are merged. | DEFAULT_MAX_FILES = 20 |
dedup | both | Folded into an existing item: another pull request for a ticket and repo already seen, or a candidate with the same repo and the same question (compared case-insensitively). | |
kept | items | Items in the set. |
The CLI prints the drop counts that are not zero, under plain names: no ticket (unlinked), too many tickets (multi_ticket), plumbing title (noise), noise query, title too short, no answer file left, too many files, duplicate. In the run above, one pull request had no ticket ("bump dependencies") and one was a branch merge.
DEFAULT_GENERIC_WORDS holds English and Turkish words ("fix", "update", "refactor", "düzeltme", "güncelleme", …). For another language, or for your own branch and environment names, pass genericWords and noisePatterns through the SDK; the CLI has no flag for them.
Which files count as an answer
Each changed file gets one verdict per (repo, path), counted in stats.files:
| Counter | The file is dropped because |
|---|---|
lockfile | It is a dependency lock (package-lock.json, go.sum, anything ending in .lock or .lockb, …). |
vendored | It sits in a third-party or tool-written directory (node_modules/, vendor/, dist/, obj/, __snapshots__/, …). |
generated | It is tool-written (.min.js, .d.ts, .generated., .pb.go, .snap, .map, anything under migrations/), or it matches one of your excludePaths. |
asset | It is a binary or an asset (images, archives, fonts, office documents, …). |
non_code | It is prose, data or configuration (.md, .json, .yaml, .xml, files without an extension such as Dockerfile, …). Dropped with codeOnly, which is the default. |
invalid | The path is empty, absolute, or contains ... |
missing | It is not in the local working tree any more. A file that is gone cannot be in the index, so it cannot be measured. |
kept counts the files that passed. existenceUnchecked counts files that were kept without the existence check, because the repo is not cloned locally or the code hosts could not be listed. Any extension that is not on one of the lists counts as code, so a language nobody thought of is never dropped silently.
When a ticket cannot be read
A deleted ticket, a missing permission or a tracker that is down does not fail the build. The item falls back to the pull request title with ticket keys and prefixes such as fix: or feature/ removed, and is flagged querySource: "pr_title". The CLI reports how many (N unreadable (PR title used)), and stats.querySource holds both counts.
The time window
--since is an inclusive and --until an exclusive bound on the merge date. Together they split the history: tune on one period, report on another. A pull request without a merge time cannot be placed on either side, so it is left out whenever a window is given.
The builder reads at most 100,000 records from the store (DEFAULT_MAX_RECORDS). If the store held more, stats.truncated is true and the CLI says that the set covers the newest records only.
Leakage: what this set can and cannot answer
Two more limits belong next to every number from this set:
- The question is a ticket title. Some titles cannot locate code however good retrieval is. Read the miss classes before the headline number.
- The answer is the files one pull request changed, which is a subset of the files that are relevant. A hit that is not an answer file is not thereby wrong, so this set supports no precision-style conclusion.
Flags of eval golden
| Flag | Meaning |
|---|---|
--out <file> | Where to write the set. Default: <data dir>/eval/golden.json. |
--since <date> | Only pull requests merged on or after this date. |
--until <date> | Only pull requests merged before this date. |
--include-unlinked | Also use pull requests without a ticket; the question is the cleaned pull request title. |
Retrieval metrics in plain words
safran eval retrieval sends every question through the same code search the agents use (safran.code.search) and looks at where the answer files land in the result list.
| Column | Plain meaning |
|---|---|
n | Queries that were scored. The sample size of every number in the row. |
err | Queries whose search failed. They are not part of n. |
hit@1, hit@5, hit@10 | Share of queries with at least one answer file in the first 1, 5 or 10 results. "Did the search get the agent to the right place at all?" |
recall@k | Of all the answer files of a query, the share found in the first k results, averaged over queries. "How much of the change's footprint did it see?" |
MRR | Mean reciprocal rank: 1 divided by the rank of the first answer file (1 for rank 1, 0.5 for rank 2, 0 when none is in the first k), averaged. "How far down does the agent have to read?" |
nDCG@10 | Rewards answer files near the top of the first 10 results and compares the list with the ideal one that puts every answer file first. 1.0 is that ideal; relevance is binary. |
p50 ms, p95 ms | Median and 95th percentile of the search time over scored queries (linear interpolation between the two nearest values). |
k is 10 by default (DEFAULT_K, "what an agent reads from one search call") and is set with --k. It cuts recall@k and MRR only; hit@1/5/10 and nDCG@10 keep their fixed depths, and every search asks for at least max(k, 10) results.
The rules behind the numbers:
- Matching is file-level on (repo, path), exact and case-sensitive. The right file at the wrong lines counts as found. Several chunks of one file count once, at their first rank.
- Identical copies count. A hit that lists the answer file among its identical copies (
alsoIn) credits it. - Errors are not misses. A failed search is recorded on its row, counted under
errand left out of every mean. A dead embedder is not bad retrieval. The command exits with code 1 only when searches failed and no configuration scored a single query. - One untimed warm-up query runs per configuration first, so a cold embedding model does not land in p95.
- One query at a time (
DEFAULT_RETRIEVAL_CONCURRENCY = 1): the embedder is usually a local model, and parallel queries would only measure its queue.
Besides overall, the table has one row per repo group of the profile (group: backend; repos in no group are collected under (no group)) and, when the set carries translations of its questions, one per query language. A slice that would only repeat the overall row is not printed.
The metric functions are pure and exported, so any number can be checked by hand:
import { scoreHits } from "@safran/eval";
// Three results; the answer is two files of payments-api.
const { metrics } = scoreHits(
[
{ repo: "payments-api", path: "src/webhook/retry.ts" },
{ repo: "payments-api", path: "src/refund/policy.ts" },
{ repo: "payments-api", path: "src/refund/policy.ts" },
],
{ repo: "payments-api", files: ["src/refund/policy.ts", "src/refund/service.ts"] },
);
console.log(metrics);
// { hitAt1: 0, hitAt5: 1, hitAt10: 1, recallAtK: 0.5, reciprocalRank: 0.5, ndcgAt10: 0.38685280723454163 }Comparing configurations
A configuration is a named way of searching. Give two or more with --config name=mode[,option…] and every question runs through each of them, interleaved per question so that slow drift of the machine hits all alike:
modeisauto,hybrid,denseorlexical(the modes of code search).noglossaryturns glossary expansion off for that configuration.reporestricts each search to the item's own repo, as an agent that already knows the repo would. The focused help lists onlynoglossary;repois accepted by the parser inpackages/cli/src/commands/eval.ts.
The classic use at a company whose tickets are not written in the language of the code is to measure what the glossary is worth (Non-English tickets):
$ safran eval retrieval --config with=auto --config without=auto,noglossary --config lexical=lexical --report retrieval.html --out retrieval.json --profile /work/acme/safran.yaml
3 items from /work/acme/data/eval/golden.json · index ollama:bge-m3, 7 chunks · 77 ms
Retrieval evaluation: 3 golden items, 3 configurations, k = 10
config slice n err hit@1 hit@5 hit@10 recall@10 MRR nDCG@10 p50 ms p95 ms
------- --------------- - --- ----- ----- ------ --------- ----- ------- ------ ------
with overall 3 0 1.000 1.000 1.000 1.000 1.000 1.000 14 14
with group: backend 2 0 1.000 1.000 1.000 1.000 1.000 1.000 7.3 14
with group: frontend 1 0 1.000 1.000 1.000 1.000 1.000 1.000 14 14
without overall 3 0 0.667 1.000 1.000 1.000 0.833 0.898 0.3 0.3
without group: backend 2 0 0.500 1.000 1.000 1.000 0.750 0.847 0.3 0.3
without group: frontend 1 0 1.000 1.000 1.000 1.000 1.000 1.000 0.3 0.3
lexical overall 3 0 1.000 1.000 1.000 1.000 1.000 1.000 0.2 0.2
lexical group: backend 2 0 1.000 1.000 1.000 1.000 1.000 1.000 0.2 0.2
lexical group: frontend 1 0 1.000 1.000 1.000 1.000 1.000 1.000 0.2 0.2
Too few paired queries to compare "with" and "without" (n = 3, at least 10 needed). No difference is claimed.
Too few paired queries to compare "with" and "lexical" (n = 3, at least 10 needed). No difference is claimed.
n = queries scored; err = failed searches, excluded from the means.
✔ Report: /work/acme/retrieval.html
✔ Result: /work/acme/retrieval.jsonRead this output the way the tool does. Without the glossary the Turkish title of PAY-1423 finds its file at rank 2 instead of rank 1, and MRR drops from 1.000 to 0.833. With three questions that is an anecdote, and the summary refuses to call it: "No difference is claimed."
The first configuration is the baseline. Each of the others is compared against it.
Is the difference real?
The deltas between two rows are plain differences of means and prove nothing by themselves. The verdict comes from a paired bootstrap on the per-query reciprocal rank:
- Only queries that both configurations scored are used (a pair). Queries where one side failed are counted as
unpaired. - For each pair the difference
b − aof the reciprocal rank is taken. Pairing matters because queries differ far more in difficulty than configurations differ in quality. - The differences are resampled with replacement 10,000 times; each resample gives a mean.
- The 2.5th and 97.5th percentiles of those means form the 95% interval.
- A difference is called only when the interval excludes zero.
The summary line is one of four, word for word from the source (… stands for MRR a vs b (Δ, 95% CI low to high, n = N paired queries)):
| Verdict | Summary line |
|---|---|
better | "b" is better than "a": …. The interval excludes zero. |
worse | "b" is worse than "a": …. The interval excludes zero. |
no_significant_difference | No significant difference between "a" and "b": …. The interval includes zero, so the delta may be noise. |
insufficient_data | Too few paired queries to compare "a" and "b" (n = N, at least 10 needed). No difference is claimed. |
"No significant difference" is said whatever the sign of the observed delta. A positive mean with an interval that touches zero is not a win:
import { pairedBootstrap } from "@safran/eval";
// Per-query differences in reciprocal rank (b − a) for twelve paired queries.
const differences = [0.5, 0, 0, 0.25, -0.1, 0, 0.5, 0, 0.2, 0, 0.5, -0.25];
const result = pairedBootstrap(differences);
console.log(result.meanDifference, result.ci, result.verdict);
// 0.13333333333333333 { low: 0, high: 0.27499999999999997 } no_significant_difference| Parameter | Default | Why |
|---|---|---|
| Resamples | DEFAULT_BOOTSTRAP_RESAMPLES = 10_000 | Keeps the cut points stable to about the third decimal. |
| Confidence | DEFAULT_CONFIDENCE = 0.95 | Two-sided. |
| Minimum pairs | DEFAULT_MIN_PAIRS = 10 | Below it no verdict is given: with one pair every resample is that pair, the interval collapses to a point and would read as "significant". |
| Seed | DEFAULT_BOOTSTRAP_SEED = 20_260_101 | The random generator is seeded, so the same report always gives the same interval, for everyone. |
The limits of the check, as the source states them: the percentile interval is slightly too narrow for small samples (tens of items); reciprocal rank is bounded and lumpy, so the interval is approximate; only MRR is tested; and running many comparisons and reporting the one that "won" defeats the 95%.
Flags of eval retrieval
| Flag | Meaning |
|---|---|
--golden <file> | Golden set to use. Default: <data dir>/eval/golden.json. |
--config <name=mode[,noglossary]> | A search configuration to measure; repeat it to compare. Names must be unique. Without it, one configuration named default runs with Safran's defaults. |
--k <n> | Cut-off for recall@k and MRR. Default: 10. |
--report <file.html> | Also write the HTML report. |
--out <file.json> | Also write the full result, with one row per query and configuration, as JSON. |
The fields of a configuration in the SDK:
| Field | CLI form | Meaning |
|---|---|---|
name | name= | Shown in every table; unique within a run. |
mode | =auto, =hybrid, =dense, =lexical | Search mode. Without it, Safran's default. |
expandGlossary | ,noglossary sets it to false | Glossary expansion. On by default. |
limit | none | Results requested per query, raised to at least max(k, 10). |
scope | ,repo sets it to repo | repo searches only the item's own repo. Default: all. |
Why a query missed
A miss is a scored query with no answer file in the first k results. classifyMisses sorts each miss into exactly one class, using only what the report and the golden set already hold (no new searches, no file reads). The classes are checked in this order and the first that applies wins:
| Kind | Class | Meaning |
|---|---|---|
| golden set | non_code_answer | Every answer file is prose or configuration, which the code index may not hold. |
| golden set | generic_title | The title has fewer than two informative words (three letters or more, not on the generic list). |
| ranking | below_cutoff | An answer file was returned, but below rank k. |
| ranking | other_config_finds | Another configuration of the same run has an answer file in its first k. |
| retrieval | right_directory | A top-k hit is in the same directory of the same repo as an answer file. |
| retrieval | right_repo | A top-k hit is in the answer's repo, but not near an answer file. |
| retrieval | sibling_repo | A top-k hit is in another repo the same ticket changed. |
| retrieval | nothing_close | None of the above. |
The first two kinds are properties of the golden set: there is nothing to tune. Look at the classes before changing anything in retrieval.
Two classes need the run to be set up for them:
below_cutoffcan only be seen when a configuration asked for more thankresults. From the CLI the depth ismax(k, 10), so it appears only with--kbelow 10; from the SDK setlimit: 50on the configuration.other_config_findsneeds other configurations in the run, for examplelexical=lexicalanddense=densenext to the main one.
The classes are heuristics for triage, not a measurement.
The HTML report
--report <file.html> writes one self-contained page: the summary table, the comparison of each configuration with the baseline, the miss classes with sample queries (up to 10 per class, DEFAULT_MISS_SAMPLES), and a methodology section with the golden-set filter counts and the known limits. The page contains no script and makes no external request; its Content-Security-Policy allows nothing but its own inlined stylesheet, and every string that comes from tickets, paths, repos or names is escaped.
The report holds ticket titles and file paths of your company. Treat the file like the data it was built from.
--out <file.json> writes the full RetrievalReport: per query the returned locations, the rank of each answer file found, the files missed, the latency and, when the glossary changed the query, the effectiveQuery. Keep it next to the golden set when you want to compare two versions of Safran later.
Retrieval from the SDK
The CLI commands are thin shells over three calls. The SDK gives access to every threshold the CLI does not expose.
import { writeFile } from "node:fs/promises";
import { createSafran } from "@safran/core";
import { buildGoldenSet, classifyMisses, compareConfigs, formatRetrievalSummary, renderRetrievalReport, runRetrievalEval, saveGoldenSet } from "@safran/eval";
await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
await safran.links.refresh(); // the builder only reads the local store
// Tune on the first eight months, keep the rest for the final report.
const golden = await buildGoldenSet(safran, {
since: "2026-01-01",
until: "2026-09-01",
noisePatterns: [/^sync (dev|staging|prod)\b/i],
});
await saveGoldenSet("golden.json", golden);
console.log(golden.stats);
const report = await runRetrievalEval(safran, golden, {
configs: [
{ name: "with", limit: 50 },
{ name: "without", expandGlossary: false, limit: 50 },
{ name: "lexical", mode: "lexical", limit: 50 },
],
});
console.log(formatRetrievalSummary(report));
const comparison = compareConfigs(report, "with", "without");
console.log(comparison.verdict, comparison.n, comparison.summary);
for (const result of classifyMisses(report, golden, { config: "with" })) {
console.log(result.misses, "misses of", result.scored, result.kinds);
}
await writeFile("retrieval.html", renderRetrievalReport(report, golden, { profile: safran.profile.company }));runRetrievalEval rejects with ABORTED when its signal fires; a failing search never fails the run. The option objects are documented in the @safran/eval reference:
export interface BuildGoldenSetOptions {
/** ISO date, inclusive lower bound on the merge time. */
since?: string;
/** ISO date, exclusive upper bound on the merge time. Together with `since` this is the time split. */
until?: string;
repos?: string[];
maxFiles?: number;
minQueryWords?: number;
maxTicketsPerPr?: number;
/** Keep only source files as answers; prose and configuration are dropped. Default: true. */
codeOnly?: boolean;
/** Also build items from pull requests without a ticket, using the cleaned PR title. Default: false. */
includeUnlinked?: boolean;
/** When a ticket cannot be read, fall back to the cleaned PR title (flagged on the item). Default: true. */
prTitleFallback?: boolean;
/**
* Drop answer files that are not in the local working tree: a file that is gone cannot be
* in the index, so it is not measurable. Needs the repo listing (asks the code hosts).
* Default: true.
*/
checkExists?: boolean;
/** Extra noise patterns, tested against PR titles and queries (branch and environment names of your company). */
noisePatterns?: readonly RegExp[];
genericWords?: readonly string[];
/** Extra path patterns to drop from the answers. Counted under `stats.files.generated`. */
excludePaths?: readonly RegExp[];
/** Language tag of the ticket titles. Default: `profile.languages.tickets`. */
language?: string;
/**
* Hand-written translations of queries: `{ en: { "PAY-1423": "…", "kısmi iade": "…" } }`.
* Looked up by ticket key first, then by the query text (case-insensitive).
*/
translations?: Record<string, Record<string, string>>;
ticketConcurrency?: number;
maxRecords?: number;
/** Clock for `builtAt`, so tests are deterministic. */
now?: () => Date;
signal?: AbortSignal;
onProgress?: (progress: { phase: "tickets"; done: number; total: number }) => void;
}
export interface RetrievalEvalOptions {
/** Default: one configuration named "default" with Safran's defaults. */
configs?: RetrievalConfig[];
k?: number;
/** Default results requested per query for configurations that do not set `limit`. */
depth?: number;
/**
* Language of the query used for the overall and per-group numbers. Default: each item's
* own language. Items without a query in this language are skipped and counted.
*/
queryLanguage?: string;
/** Also run every translation, for the per-language slices. Default: true. */
languageSlices?: boolean;
concurrency?: number;
/** One untimed search per configuration first, so a cold embedder (seconds) does not land in p95. Default: true. */
warmup?: boolean;
signal?: AbortSignal;
onProgress?: (progress: RetrievalProgress) => void;
now?: () => Date;
}defined in packages/eval/src/golden.ts, packages/eval/src/retrieval.ts
Replay: does Safran help an agent?
The replay evaluation answers the question the golden set cannot. For a finished ticket it checks the repo out as it was before the change, runs an agent command there with the ticket as its task, and compares the files the agent touched with the files the real change touched. There are three arms:
- A bare agent: your agent command with no company context.
- The agent with Safran: the same command with the Safran MCP server attached (MCP server).
- The oracle: the real diff. It is implicit and added automatically. Its file scores are 1.0 by definition, not by measurement; it anchors the scale.
The runner knows nothing about the agent behind an arm. An arm is a command template; you supply both.
What the runner does for each task
Tasks come from the golden set: an item qualifies when it is backed by exactly one pull request with a recorded merge commit. The others are excluded and counted (several pull requests have several "before" states, and none of them precedes the whole answer).
- Find the commit before the change: the first parent of the merge commit. Managed clones are shallow, so when the commit is missing the runner fetches it from the clone's remote with depth 2, without moving any ref. If the commit still cannot be had, the task is
skippedwith the reasonbase commit unavailable. Another commit is never substituted: a replay from the wrong state measures nothing. - Read the real change from git (the diff between that commit and the merge commit). Lockfiles, generated files, vendored trees and assets are left out of both sides of the comparison.
- Write the prompt: the ticket key, title and description as the tracker returns them today. If the ticket cannot be read, only the title is used and the result says so (
promptSource: "title"). - Create a detached
git worktreeat the base commit inside a temporary directory, once per run. - Run the arm's command there, without a shell, in its own process group, with a timeout (30 minutes unless the arm sets
timeout_ms). On timeout or cancellation the whole group getsSIGTERM, thenSIGKILLtwo seconds later. - Score: compare the working tree with the base commit (committed, staged, unstaged and new files alike) and compute file-level precision, recall and F1 against the real change. If a test command is configured for the repo and the arm exited, run it in the checkout.
- Remove the worktree, always, including on timeout and cancellation.
Arms run one process at a time: for each task, each repeat, each arm in turn.
The arms file
safran eval replay --arms <file.json> reads a JSON array of arms, or an object with the arms and a few settings:
{
"runs": 3,
"max_cost_usd": 40,
"test_command": { "payments-api": ["bun", "test"] },
"arms": [
{
"name": "bare",
"command": ["claude", "-p", "{prompt}", "--permission-mode", "acceptEdits", "--output-format", "json"],
"timeout_ms": 1200000
},
{
"name": "with-safran",
"command": ["claude", "-p", "{prompt}", "--permission-mode", "acceptEdits", "--output-format", "json", "--mcp-config", "/work/acme/safran.mcp.json"],
"timeout_ms": 1200000
}
]
}| Field | In the arms file | Meaning |
|---|---|---|
name | name | Shown in every table; unique. oracle is reserved for the real diff. |
command | command | argv as a list of strings. No shell. Runs with the checkout as its working directory. |
env | env | Variables added to your environment for this arm. Values take placeholders too. |
timeoutMs | timeout_ms | Per-run timeout in milliseconds. Default: 30 minutes (DEFAULT_ARM_TIMEOUT_MS). |
Settings next to arms: runs (repeats per task and arm), test_command (repo name → argv; exit code 0 is a pass), max_wall_ms and max_cost_usd (budgets, below). The flags --runs and --max-tasks win over the file.
Placeholders are replaced in command and in env values; anything else in braces is left alone, so JSON arguments stay intact:
| Placeholder | Value |
|---|---|
{workdir} | The checkout (also the working directory). |
{prompt} | The prompt text. |
{prompt_file} | A file holding the prompt, outside the checkout. |
{result_file} | Where the arm may write its cost (see below). |
{ticket_key} | The ticket key, or empty. |
{task_id} | The golden item id, for example payments-api#PAY-1423. |
{repo} | The repo name. |
{title} | The ticket title. |
{arm}, {run} | The arm's name and the 1-based repeat number. |
Try the plumbing before you spend money
Before any agent runs, check that tasks can be prepared (commits found, worktrees created) with stand-in commands that cost nothing. Here one arm does nothing and the other appends a line to one file:
{
"runs": 1,
"arms": [
{ "name": "does-nothing", "command": ["true"] },
{ "name": "edits-one-file", "command": ["sh", "-c", "echo '// {ticket_key}' >> src/refund/service.ts"], "timeout_ms": 60000 }
]
}$ safran eval replay --arms smoke-arms.json --report replay.html --log-dir logs --profile /work/acme/safran.yaml
Ticket replay: 3 of 3 tasks ran, 2 arms, 1 run per task and arm, 560 ms
arm tasks scored/runs precision recall F1 right files no change tests cost median time
------------------ ----- ------------- --------- ------ ---- ----------- --------- ------- ------- -----------
does-nothing 3 3/3 0.00 0.00 0.00 0/3 3/3 not run unknown 2 ms
edits-one-file 3 3/3 0.33 0.17 0.22 1/3 1/3 not run unknown 3 ms
real diff (oracle) 3 by definition 1.00 1.00 1.00 3/3 0/3 not run n/a n/a
Too few tasks to compare "does-nothing" and "edits-one-file" (n = 3, at least 10 needed). No difference is claimed.
tasks = tasks with a scored run (the n of precision, recall and F1); right files = runs with recall of at least 50%, out of scored runs; cost is what the arm reported, never estimated.
Note: 3 tasks is too few to tell two arms apart; treat the numbers as anecdotes.
✔ Report: /work/acme/replay.htmlThis is real output from the same toy setup (progress lines left out). The stand-in arm touches src/refund/service.ts in every task: for PAY-1423 that is one of the two files the real change touched (recall 0.5, so "right files"), for PAY-1500 it is the wrong file, and in web-app the file does not exist, so the command fails and changes nothing. The numbers mean nothing about any agent; the run shows that all three tasks could be checked out and scored.
Reading the table
| Column | Meaning |
|---|---|
tasks | Tasks with at least one scored run: the n of precision, recall and F1. |
scored/runs | Runs whose diff could be read, out of runs started. |
precision | Of the files the arm touched, the share the real change also touched. |
recall | Of the files the real change touched, the share the arm touched. |
F1 | The harmonic mean of the two. Per task the runs are averaged first, then tasks are averaged, so a task with more runs does not weigh more. Touching nothing scores 0. |
right files | Runs with recall of at least 50% (DEFAULT_FOUND_THRESHOLD = 0.5). |
no change | Runs that left the checkout untouched. |
tests | Runs where the test command passed, out of runs where it ran; not run without a test command. |
cost | The sum the arm reported, or unknown. |
median time | Median wall time of runs that ran to their end or their timeout. |
The first arm in the file is the baseline; each other arm is compared with it by the same paired bootstrap, here on the per-task mean F1, with tasks as the pairs. Below 10 shared tasks the answer is "Too few tasks", and that is the honest answer. Replays are small; expect that line, or "No significant difference", far more often than a win.
Under the table the summary adds a note when the run stopped early, when tasks could not be prepared ("in no average"), when a run wrote outside its checkout or changed the source clone, and for every cleanup problem. A diff touching more than 50 files (DEFAULT_MAX_DIFF_FILES) is flagged as oversized in the report: that is usually a formatter run or a dependency install, not a solution.
When a test command is given it is also run on the real change, in a worktree at the merge commit: tests that fail there cannot judge anyone.
Cost and budgets
Running agents costs money and time. Start with --max-tasks 3.
- Cost is read, never estimated. An arm may write a JSON file to
{result_file}:{ "cost_usd": 0.42, "tokens": 51000 }. If it writes nothing, the cost isunknown. To record cost, wrap the agent in a small script of your own that writes that file from the agent's usage output. --max-tasks(maxTasks) stops after that many tasks.max_wall_msis checked before each run starts. A run in flight is not cut short, so the overshoot is at most one arm timeout.max_cost_usdcounts only the costs the arms report. An arm that reports none is never stopped by it.- Tasks not reached are reported as
not_run, with the budget that stopped the run. - Ctrl-C does not throw the work away: the run returns everything finished so far with
abortedset, and the command exits with code 130. --runs <n>repeats every task and arm. Agents are not deterministic; one run is an anecdote. With repeats the report carries the run-to-run deviation of F1.
What a replay score means, and does not mean
A replay score is file overlap with one accepted solution.
- An agent that solves the ticket differently but correctly scores low.
- An agent that touches the right files with wrong code scores high. A per-repo test command is the stronger judge where it exists.
- The ticket is read as it is today. It may have been edited after the work was done and may describe the solution.
- A few tasks cannot separate two arms. Read the verdict line, not the F1 column.
This is not a sandbox
What the runner does:
- hands the arm only paths inside one temporary directory (
{workdir},{prompt_file},{result_file}); - runs the command in its own process group and kills the group on timeout or cancel;
- flags entries the arm left in the temporary workspace outside its checkout (
containment.strayFiles); - flags a change of refs or
HEADin the source clone (containment.sourceRepoChanged); - runs its own git commands with hooks, credential helpers and symlink checkout turned off, so reading the diff of a checkout does not run what the arm left behind.
What it cannot do:
- see or stop a write to any other path on the machine;
- see or stop a network call;
- stop a process that moved itself to another process group;
- keep the arm out of the source clone: a worktree shares the object store and refs of the clone it came from, so an arm can create branches or objects there;
- filter the ticket. The ticket text goes to the agent as it is, and a ticket can contain instructions. The untrusted-data wrapper of the MCP server does not apply to the replay prompt.
Run agents you do not trust, or tickets you do not trust, inside a container or a virtual machine. If the process running the replay is killed outright, a worktree may stay registered in the source clone; git worktree prune in that clone removes it. The wider picture is in the security guide.
Flags of eval replay
| Flag | Meaning |
|---|---|
--arms <file.json> | The commands to compare. Required. |
--golden <file> | Golden set the tasks come from. Default: <data dir>/eval/golden.json. |
--max-tasks <n> | Stop after this many tasks. |
--runs <n> | Repeats per task and arm. |
--report <file.html> | Also write the HTML report. |
--log-dir <dir> | Keep each run's stdout and stderr here, as <task>.<arm>.<run>.out.log and .err.log. Without it they are discarded with the workspace. |
Replay from the SDK
import { writeFile } from "node:fs/promises";
import { createSafran } from "@safran/core";
import { compareArms, formatReplaySummary, loadGoldenSet, renderReplayReport, replayTasksFromGoldenSet, runReplayEval, type ReplayArm } from "@safran/eval";
// Examples to edit: check the flags against your agent CLI before a batch.
const bare: ReplayArm = {
name: "bare",
command: ["claude", "-p", "{prompt}", "--permission-mode", "acceptEdits", "--output-format", "json"],
timeoutMs: 20 * 60_000,
};
const withSafran: ReplayArm = {
name: "with-safran",
command: [...bare.command, "--mcp-config", "/work/acme/safran.mcp.json"],
timeoutMs: 20 * 60_000,
};
await using safran = await createSafran({ profile: "/work/acme/safran.yaml" });
const golden = await loadGoldenSet("golden.json");
const { tasks, excluded } = replayTasksFromGoldenSet(golden);
console.log(`${tasks.length} tasks, ${excluded.length} items cannot be replayed`);
const controller = new AbortController();
process.once("SIGINT", () => controller.abort());
const report = await runReplayEval(safran, tasks, {
arms: [bare, withSafran],
runs: 3,
maxTasks: 20,
maxCostUsd: 40,
testCommand: { "payments-api": ["bun", "test"] },
signal: controller.signal,
});
console.log(formatReplaySummary(report));
console.log(compareArms(report, "bare", "with-safran").summary);
for (const task of report.tasks) {
if (task.status !== "ran") console.log(task.task.id, task.status, task.reason);
}
await writeFile("replay.html", renderReplayReport(report, { profile: safran.profile.company }));Unlike the rest of Safran, a cancelled replay does not reject: runReplayEval resolves with what it finished, aborted: true and the remaining tasks marked not_run, because those runs cost money.
export interface ReplayEvalOptions {
arms: ReplayArm[];
/** Repeats per task and arm. Agents are not deterministic; one run is an anecdote. */
runs?: number;
foundThreshold?: number;
/** Test command per repo name (argv, run in the checkout after the arm). Exit 0 = pass. */
testCommand?: Record<string, string[]> | ((task: ReplayTask) => string[] | undefined);
testTimeoutMs?: number;
/** Also run the test command on the real change, to check that the tests can judge the task at all. Default: true. */
oracleTests?: boolean;
/** Budget guards. The run stops cleanly before the next unit of work and reports what was not run. */
maxTasks?: number;
/** Checked before each run starts; a run in flight is not cut short, so the overshoot is at most one arm timeout. */
maxWallMs?: number;
/** Counts only costs the arms report. An arm that reports none is never stopped by this. */
maxCostUsd?: number;
/** Try to fetch a missing commit from the clone's remote (shallow clones). Default: true. */
fetchMissing?: boolean;
/** Put the ticket description in the prompt, not only the title. Default: true. */
includeDescription?: boolean;
buildPrompt?: (task: ReplayTask, ticket: { title: string; description: string } | undefined) => string;
/** Parent of the temporary workspace. Default: the OS temp directory. */
tempDir?: string;
/** Keep each run's stdout/stderr here (`<task>.<arm>.<run>.out.log`). Default: discarded with the workspace. */
logDir?: string;
maxDiffFiles?: number;
killGraceMs?: number;
signal?: AbortSignal;
onProgress?: (progress: ReplayProgress) => void;
now?: () => Date;
}defined in packages/eval/src/replay.ts
The principle: before and after
Retrieval quality is not checked by unit tests in Safran; it is checked by evaluation. The working rule:
- Build a golden set once and keep the file. A rebuilt set is a different exam.
- Before a change to anything that affects retrieval (the embedding model, the glossary, the search mode, a new version of Safran), run
safran eval retrievalwith--outand keep the result. - Make the change. Re-index if the change needs it.
- Run the same command on the same golden set.
- A regression blocks the change. A delta whose interval includes zero is not an improvement and is not a regression either: it is noise until more questions say otherwise.
Where both variants can be expressed as configurations (glossary on or off, one search mode against another), put them in one run with --config, so the pairing and the significance check are done for you. Where they cannot (two embedding models need two indexes), keep the two --out files and compare the per-query rows on the same item ids; pairedBootstrap takes the differences directly.
Common mistakes
The golden set is empty. When pull requests is 0, the link store has nothing in the window: run safran links refresh (a local code host lists no pull requests, so it has no history to build from). When pull requests were read but every one was filtered, the dropped counts say why; --include-unlinked keeps the ones without a ticket.
No golden set at …. eval retrieval and eval replay read <data dir>/eval/golden.json unless --golden points elsewhere. Build it with safran eval golden.
Every row has n 0 and a count under err. The searches failed: the index is not built, or the embedder is not reachable. Run safran doctor; see Troubleshooting.
Reading a delta as a result. Two rows that differ by a couple of points, with "No significant difference" underneath, do not differ as far as this set can tell.
Tuning on the set you report on. Use --since and --until to keep a period out of sight while you tune.
Rebuilding the golden set between "before" and "after". New pull requests, a ticket that was renamed or a file that was deleted change the items. Compare runs on the same file.
Comparing many configurations and reporting the winner. Each comparison has its own 5% chance of calling noise a difference. Decide what you compare before you run it.
Every replay task is skipped with base commit unavailable. The clone does not hold the commit before the change and it could not be fetched from the remote (expired token, or the commit is gone from the host after a history rewrite).
Trusting a replay score from three tasks. The CLI says it itself: treat the numbers as anecdotes.
See also
measurecommands: every flag and exit code of the three commands.@safran/evalreference: every exported function and type.- Non-English tickets: measuring the glossary with
--config with=auto --config without=auto,noglossary. - Project status: what has and has not been measured.