Skip to content
safran

Type to search. Enter opens the first result.

    @safran/eval

    @safran/eval measures Safran on a company's own history. It answers two questions with two tools: "can code search find where a ticket's work lives?" (buildGoldenSet + runRetrievalEval, free, minutes) and "does Safran make an agent better at this company's work?" (runReplayEval, real agent runs that cost money and hours). This page documents every exported function with its options, result types, defaults and errors. The safran eval commands (CLI: measure) are thin shells over it, and the evaluation guide explains how to read the numbers.

    Three rules hold throughout: no number without its sample size, no "improvement" without a significance check, and everything skipped or failed is counted and shown.

    Example: a retrieval evaluation over fakes

    The first file builds a Safran instance over the in-memory connectors of @safran/kit/testing (Testing) and fills the link store. Against a real profile, replace it with createSafran() and a safran.links.refresh().

    acme.ts
    import { mkdtempSync } from "node:fs";
    import { tmpdir } from "node:os";
    import { join } from "node:path";
    import { createSafran, type Safran } from "@safran/core";
    import type { PullRequest } from "@safran/kit";
    import { FakeCodeHost, FakeCodeIndex, FakeTracker, fakePlugins } from "@safran/kit/testing";
    
    const files = {
      "src/refund/service.ts": "export function issuePartialRefund(orderId: string, amount: number) { /* refund */ }",
      "src/refund/policy.ts": "export function canRefund(amount: number, orderTotal: number) { return amount <= orderTotal; }",
      "src/webhook/retry.ts": "export function handleRefundWebhook(deliveryId: string) { /* idempotent retries */ }",
    };
    
    const pullRequests: PullRequest[] = [
      { id: "101", repo: "payments-api", title: "PAY-1423 fix partial refund rounding", description: "", mergedAt: "2026-08-03T09:00:00Z", mergeCommit: "a".repeat(40), linkedTicketKeys: ["PAY-1423"], changedFiles: ["src/refund/service.ts", "src/refund/policy.ts"] },
      { id: "102", repo: "payments-api", title: "PAY-1500 make webhook retries idempotent", description: "", mergedAt: "2026-08-17T09:00:00Z", mergeCommit: "b".repeat(40), linkedTicketKeys: ["PAY-1500"], changedFiles: ["src/webhook/retry.ts"] },
      { id: "103", repo: "payments-api", title: "Merge branch release into main", description: "", mergedAt: "2026-08-18T09:00:00Z", linkedTicketKeys: [], changedFiles: ["package.json"] },
    ];
    
    /** A Safran instance over in-memory connectors, with the link store already filled. */
    export async function createAcme(): Promise<Safran> {
      const safran = await createSafran({
        profile: {
          version: 1,
          company: "acme",
          languages: { tickets: "tr", code: "en" },
          trackers: [{ id: "jira", type: "fake", projects: ["PAY"] }],
          code: { hosts: [{ id: "azure", type: "fake" }], groups: { backend: ["payments-api"] } },
          glossary: [{ term: "İade", code: ["refund", "chargeback"] }],
          embeddings: { type: "fake" },
        },
        builtinPlugins: false,
        plugins: fakePlugins({
          trackers: [
            new FakeTracker({
              id: "jira",
              tickets: [
                { key: "PAY-1423", title: "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor" },
                { key: "PAY-1500", title: "Refund webhook retries are not idempotent" },
              ],
            }),
          ],
          hosts: [new FakeCodeHost({ id: "azure", repos: [{ name: "payments-api" }], pullRequests })],
        }),
        index: new FakeCodeIndex({ files: { "payments-api": files }, groups: { backend: ["payments-api"] } }),
        dataDir: mkdtempSync(join(tmpdir(), "acme-eval-")),
      });
      await safran.links.refresh({ since: "2026-01-01" });
      return safran;
    }

    The second file is the evaluation itself: build the golden set, run it under two configurations, compare them, and look at the misses.

    retrieval.ts
    import { buildGoldenSet, classifyMisses, compareConfigs, formatRetrievalSummary, loadGoldenSet, runRetrievalEval, saveGoldenSet } from "@safran/eval";
    import { createAcme } from "./acme";
    
    await using safran = await createAcme();
    
    // 1. Question → files, from the local link store. `checkExists: false` because the fake repos are not on disk.
    const golden = await buildGoldenSet(safran, { since: "2026-01-01", checkExists: false });
    console.log(`${golden.stats.prs} PRs → ${golden.stats.kept} items (${golden.stats.unlinked} unlinked, ${golden.stats.noise} noise)`);
    for (const item of golden.items) console.log(item.id, JSON.stringify(item.query), item.files);
    
    // A golden set is a JSON file: keep it next to the numbers it produced.
    await saveGoldenSet(`${safran.dataDir}/golden.json`, golden);
    const reloaded = await loadGoldenSet(`${safran.dataDir}/golden.json`);
    
    // 2. Run every question through code search, under two configurations.
    const report = await runRetrievalEval(safran, reloaded, {
      configs: [
        { name: "main", limit: 50 },
        { name: "no-glossary", expandGlossary: false, limit: 50 },
      ],
    });
    console.log(formatRetrievalSummary(report));
    
    // 3. Is the difference real, and why did the misses miss?
    const comparison = compareConfigs(report, "main", "no-glossary");
    console.log(comparison.verdict, comparison.summary);
    for (const result of classifyMisses(report, reloaded)) {
      console.log(result.config, `${result.misses} of ${result.scored} missed`, result.classes.filter((entry) => entry.count > 0));
    }

    It prints:

    3 PRs → 2 items (0 unlinked, 1 noise)
    payments-api#PAY-1423 "Kısmi iade işlemi İstanbul şubesinde başarısız oluyor" [
      "src/refund/policy.ts", "src/refund/service.ts"
    ]
    payments-api#PAY-1500 "Refund webhook retries are not idempotent" [ "src/webhook/retry.ts" ]
    Retrieval evaluation: 2 golden items, 2 configurations, k = 10
    
    config       slice           n  err  hit@1  hit@5  hit@10  recall@10    MRR  nDCG@10  p50 ms  p95 ms
    -----------  --------------  -  ---  -----  -----  ------  ---------  -----  -------  ------  ------
    main         overall         2    0  1.000  1.000   1.000      1.000  1.000    1.000     0.0     0.0
    main         group: backend  2    0  1.000  1.000   1.000      1.000  1.000    1.000     0.0     0.0
    no-glossary  overall         2    0  0.500  0.500   0.500      0.500  0.500    0.500     0.0     0.0
    no-glossary  group: backend  2    0  0.500  0.500   0.500      0.500  0.500    0.500     0.0     0.0
    
    Too few paired queries to compare "main" and "no-glossary" (n = 2, at least 10 needed). No difference is claimed.
    
    n = queries scored; err = failed searches, excluded from the means.
    
    insufficient_data Too few paired queries to compare "main" and "no-glossary" (n = 2, at least 10 needed). No difference is claimed.
    main 0 of 2 missed []
    no-glossary 1 of 2 missed [
      {
        class: "other_config_finds",
        kind: "ranking",
        count: 1,
        items: [ "payments-api#PAY-1423" ],
      }
    ]

    Read it as the package intends. The Turkish title finds its files only when the glossary maps İade to refund; without it the answer is missed, and the miss is classified as "another configuration finds it". And with two questions no difference is claimed, whatever the means say: the comparison needs at least DEFAULT_MIN_PAIRS (10) paired queries. These numbers come from a word-matching fake index and say nothing about real retrieval.

    The golden set

    Question = the title of the ticket a merged pull request was done for. Answer = the files that pull request changed.

    buildGoldenSet

    function buildGoldenSet(safran: Safran, options?: BuildGoldenSetOptions): Promise<GoldenSet>;

    Builds a golden set from the local work-record store. It reads only: run safran.links.refresh() first (Links). It calls safran.links.query, safran.tickets.get once per distinct ticket (for the title), and safran.repos.list when checkExists is on. Nothing is written; saving is saveGoldenSet.

    Unit: one item per (ticket, repo). Every pull request done for the same ticket in the same repo shares the question, so their files are unioned into one answer. A ticket that changed two repos gives two items that name each other in siblingRepos. When a ticket cannot be read 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".

    Throws INVALID_INPUT when since or until is not a date or a numeric option is not a positive integer, and ABORTED on cancellation. An unreadable ticket or an unavailable repo listing does not fail the build; both are counted in stats.

    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;
    }

    defined in packages/eval/src/golden.ts

    OptionDefaultMeaning
    sincenoneISO date, inclusive lower bound on the merge time.
    untilnoneISO date, exclusive upper bound. With since this is the time split: tune on one part of the history, report on another.
    reposallOnly these repo names.
    maxFilesDEFAULT_MAX_FILES (20)More answer files than this and the change is too wide to be "the place" for a title (too_wide).
    minQueryWordsDEFAULT_MIN_QUERY_WORDS (2)A query needs at least this many words (short_title).
    maxTicketsPerPrDEFAULT_MAX_TICKETS_PER_PR (3)A pull request linked to more tickets is a release or branch merge (multi_ticket).
    codeOnlytrueKeep only source files as answers; prose and configuration are dropped.
    includeUnlinkedfalseAlso build items from pull requests without a ticket, using the cleaned title.
    prTitleFallbacktrueFall back to the cleaned pull request title when a ticket cannot be read.
    checkExiststrueDrop answer files that are not in the local working tree: a file that is gone cannot be in the index.
    noisePatterns[]Extra patterns on top of DEFAULT_NOISE_PATTERNS, tested against pull request titles and queries.
    genericWordsDEFAULT_GENERIC_WORDSWords that say nothing about where a change lives. The default list is English and Turkish.
    excludePathsnoneExtra path patterns to drop from the answers; counted under stats.files.generated.
    languageprofile.languages.ticketsLanguage tag of the ticket titles.
    translationsnoneHand-written translations of queries, by language tag, looked up by ticket key first and then by query text.
    ticketConcurrencyDEFAULT_TICKET_CONCURRENCY (4)Tickets fetched in parallel.
    maxRecordsDEFAULT_MAX_RECORDS (100 000)Upper bound on work records read from the store; stats.truncated says when it was reached.
    now() => new Date()Clock for builtAt.
    signalnoneCancels the build.
    onProgressnoneCalled per ticket title read: { phase: "tickets", done, total }.
    /**
     * Titles that describe plumbing rather than work: branch merges, reverts, conflict
     * resolutions, "no issue" placeholders, `a -> b` branch syncs. Environment and branch names
     * differ per company; add yours through `noisePatterns`.
     */
    export const DEFAULT_NOISE_PATTERNS: readonly RegExp[]; // defined in packages/eval/src/golden.ts

    GoldenSet, GoldenItem, GoldenStats

    The golden-set types are derived from the schema parseGoldenSet validates with, so what a file may contain and what the code is typed against cannot drift apart.

    export type GoldenSet = z.output<typeof goldenSetSchema>;
    
    export type GoldenItem = z.output<typeof itemSchema>;
    
    export type GoldenPullRequest = z.output<typeof pullRequestSchema>;
    
    export type GoldenStats = z.output<typeof statsSchema>;
    
    export type GoldenThresholds = z.output<typeof thresholdsSchema>;
    
    export type QuerySource = z.output<typeof querySourceSchema>;
    
    export const GOLDEN_SET_VERSION = 1;

    defined in packages/eval/src/golden.ts

    GoldenSet fieldMeaning
    versionGOLDEN_SET_VERSION (1).
    builtAtISO time of the build.
    window{ since?, until? } on the merge date: since inclusive, until exclusive.
    thresholdsThe values the build used: maxFiles, minQueryWords, maxTicketsPerPr, codeOnly, includeUnlinked, checkExists.
    statsCounters of the build, below.
    itemsThe questions, sorted by repo and id.
    GoldenItem fieldMeaning
    idStable across rebuilds: <repo>#<ticket key>, or <repo>#pr-<id> for an unlinked pull request.
    repo, hostWhere the answer lives.
    groupsRepo groups from the profile, for per-group slices.
    ticketKeysTickets this item stands for; more than one when tickets with the same title were merged.
    queryThe question.
    querySourceticket_title, or pr_title for the fallback.
    languageLanguage tag of query.
    translationsThe same question in other languages, by tag. Optional.
    filesRepo-relative answer files, sorted. At least one.
    prsThe pull requests the answer was taken from, oldest first: id, title, optional mergedAt and mergeCommit.
    mergedAtNewest merge time among prs. Optional.
    siblingReposOther repos the same ticket changed. Optional.

    Every filter counts what it removed, so a set can be read critically:

    GoldenStats counterCountsRule
    prspull requestsMerged pull requests read from the store inside the window.
    unlinkedpull requestsNo ticket key (kept with includeUnlinked).
    multi_ticketpull requestsLinked to more tickets than maxTicketsPerPr.
    noisepull requestsThe title is plumbing: merge, revert, conflict, "no issue", cherry-pick or a -> b.
    candidatescandidatesOne per ticket and repo, before the candidate-level filters.
    noise_querycandidatesThe query itself matches a noise pattern.
    short_titlecandidatesFewer than minQueryWords words, or fewer than three words that are all generic and not identifier-shaped.
    no_filescandidatesNo answer file left after file filtering.
    too_widecandidatesMore than maxFiles answer files.
    dedupbothFolded into an existing item: same ticket and repo, or same repo and query.
    keptitemsItems in the set.
    ticketsticketsrequested, read, unreadable.
    querySourceitemsticket_title and pr_title.
    filesfileskept, existenceUnchecked, and one counter per reason a file was dropped: non_code, lockfile, generated, vendored, asset, invalid, missing.
    languagesitemsItems carrying a query in each language (original or translation).
    truncatedbooleanThe store held more records than maxRecords; the set covers only the newest.

    saveGoldenSet, loadGoldenSet, parseGoldenSet

    export async function saveGoldenSet(file: string, golden: GoldenSet): Promise<void>;
    
    export async function loadGoldenSet(file: string): Promise<GoldenSet>;
    
    /** Validates a parsed golden set. A version mismatch and a malformed file are different errors with different hints. */
    export function parseGoldenSet(data: unknown, source = "golden set"): GoldenSet;

    defined in packages/eval/src/golden.ts

    saveGoldenSet validates and writes pretty-printed JSON. loadGoldenSet reads and validates a file. parseGoldenSet validates data you already parsed. A version mismatch and a malformed file are different errors:

    CodeWhen
    NOT_FOUNDloadGoldenSet: the file could not be read.
    INVALID_INPUTNot valid JSON, not an object, fails the schema (up to five problems are listed), or an item id occurs twice.
    INCOMPATIBLE_DATAversion is not GOLDEN_SET_VERSION. Rebuild; results from different versions are not comparable.

    Query and path helpers

    /**
     * Makes a pull request title usable as a query: ticket keys and conventional prefixes
     * ("fix:", "feature/") describe the process, not the change.
     *
     * `ticketKeys` are the keys known to belong to this pull request; they are matched with a
     * loose separator ("PAY 1423", "pay_1423"). `projectKeys` catch other keys of the company.
     */
    export function cleanPullRequestTitle(title: string, ticketKeys: readonly string[] = [], projectKeys: readonly string[] = []): string;
    
    /** Tokens of a query that count as words: letters, digits and underscores, longer than one character. */
    export function queryWords(query: string): string[];
    
    /** The `short_title` rule: fewer than `minWords` words, or fewer than three words that are all generic and not identifier-shaped. */
    export function isShortTitle(query: string, minWords: number = DEFAULT_MIN_QUERY_WORDS, genericWords: readonly string[] = DEFAULT_GENERIC_WORDS): boolean;
    
    export function isNoiseTitle(title: string, extra: readonly RegExp[] = []): boolean;
    
    export function classifyPath(path: string): PathClass;
    
    /**
     * What kind of file a changed path is, judged from the path alone. Used to decide which
     * changed files of a pull request are a fair answer to "where does this ticket live".
     */
    export type PathClass = "code" | "non_code" | "lockfile" | "generated" | "vendored" | "asset" | "invalid";

    defined in packages/eval/src/golden.ts, packages/eval/src/paths.ts

    classifyPath judges a changed path from the path alone: code, non_code (prose, data and configuration), lockfile, generated, vendored, asset or invalid. Unknown extensions count as code, so a language nobody listed is never silently dropped.

    import { classifyPath, cleanPullRequestTitle, isNoiseTitle, isShortTitle } from "@safran/eval";
    
    console.log(cleanPullRequestTitle("fix: PAY-1423 partial refund rounding", ["PAY-1423"])); // "partial refund rounding"
    console.log(isNoiseTitle("Merge branch release into main")); // true
    console.log(isShortTitle("minor fix")); // true
    console.log(classifyPath("src/refund/service.ts"), classifyPath("docs/refunds.md"), classifyPath("bun.lock"));
    // code non_code lockfile

    Retrieval evaluation

    runRetrievalEval

    /**
     * Runs the golden set through code search. Every configuration sees the same items in the
     * same order, interleaved per item, so slow drift of the machine hits all of them alike.
     *
     * A failing search is recorded on its row and counted; it never fails the run and is never
     * scored as a miss (a dead embedder is not bad retrieval). Cancellation rejects with ABORTED.
     */
    export async function runRetrievalEval(safran: Safran, golden: GoldenSet, options: RetrievalEvalOptions = {}): Promise<RetrievalReport>;

    defined in packages/eval/src/retrieval.ts

    Calls safran.code.search once per question and configuration (plus one untimed warm-up per configuration) and safran.code.status once. It writes nothing. Per configuration and per slice (overall, repo group, query language) it reports hit@1/5/10, recall@k, MRR cut at k, nDCG@10, mean/p50/p95 latency and the number of failed searches.

    • Matching is file-level on (repo, path). A hit that lists the answer among its identical copies (alsoIn) counts. Several chunks of one file count once.
    • A failed search is recorded on its row and counted as an error; it is left out of every mean and is never a miss.
    • The answer is "files a pull request changed", a subset of the relevant files. Precision-style conclusions ("these other hits are wrong") are not supported.

    Throws INVALID_INPUT when two configurations share a name, a name is empty, or k, depth, limit or concurrency is not a positive integer; rejects with ABORTED on cancellation.

    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/retrieval.ts

    OptionDefaultMeaning
    configsone configuration named DEFAULT_CONFIG_NAME ("default")The configurations to measure.
    kDEFAULT_K (10)Cut-off for recall@k and MRR. Ten is what an agent reads from one search call.
    depthmax(k, 10)Results requested per query for configurations that do not set limit.
    queryLanguageeach item's own languageLanguage of the query used for the overall and per-group numbers. Items without a query in it are skipped and counted.
    languageSlicestrueAlso run every translation, for the per-language slices.
    concurrencyDEFAULT_RETRIEVAL_CONCURRENCY (1)Queries in flight. One, because the embedder is usually a local model and parallel queries only measure its queue.
    warmuptrueOne untimed search per configuration first, so a cold embedder does not land in p95.
    signalnoneCancels the run.
    onProgressnoneRetrievalProgress: done, total, config, itemId.
    now() => new Date()Clock for startedAt and finishedAt.
    export interface RetrievalConfig {
      /** Shown in every table; must be unique within a run. */
      name: string;
      mode?: SearchMode;
      /** Default: Safran's own default (on). */
      expandGlossary?: boolean;
      /** Results requested per query. Raised to at least `max(k, 10)`. Set 50 to let `classifyMisses` see answers just below the cut. */
      limit?: number;
      /** `repo` restricts each search to the item's own repo, as an agent that already knows the repo would. Default: `all`. */
      scope?: "all" | "repo";
    }

    defined in packages/eval/src/retrieval.ts

    FieldDefaultMeaning
    namerequiredShown in every table; unique within a run.
    modeSafran's defaultSearchMode: auto, hybrid, dense or lexical (types).
    expandGlossarySafran's default (on)false searches with the query as written.
    limitdepthResults requested per query, raised to at least max(k, 10) (MIN_SEARCH_DEPTH). Set 50 to let classifyMisses see answers just below the cut.
    scopeallrepo restricts each search to the item's own repo, as an agent that already knows the repo would.

    RetrievalReport

    export interface RetrievalReport {
      version: typeof RETRIEVAL_REPORT_VERSION;
      startedAt: string;
      finishedAt: string;
      durationMs: number;
      k: number;
      concurrency: number;
      warmup: boolean;
      queryLanguage?: string;
      golden: { builtAt: string; items: number; window: { since?: string; until?: string } };
      /** What was searched, when the index would say. */
      index?: { embedder: string; chunks: number; repos: number };
      configs: RetrievalConfigReport[];
    }
    
    export interface RetrievalConfigReport {
      config: RetrievalConfig & { limit: number };
      overall: SliceMetrics;
      /** Overall first, then groups, then languages; each sorted by name. */
      slices: RetrievalSlice[];
      /** Items skipped because they have no query in `queryLanguage`. */
      skipped: number;
      items: RetrievalItemResult[];
    }
    
    export interface RetrievalSlice {
      kind: "overall" | "group" | "language";
      name: string;
      metrics: SliceMetrics;
    }
    
    /** Means over `n` scored queries. Every value is null when `n` is 0. */
    export interface SliceMetrics {
      /** Queries that were scored. The sample size of every number in this object. */
      n: number;
      /** Queries whose search failed. Not part of `n`. */
      errors: number;
      hitAt1: number | null;
      hitAt5: number | null;
      hitAt10: number | null;
      recallAtK: number | null;
      mrr: number | null;
      ndcgAt10: number | null;
      latency: LatencySummary;
    }
    
    export interface LatencySummary {
      n: number;
      meanMs: number | null;
      p50Ms: number | null;
      p95Ms: number | null;
    }

    defined in packages/eval/src/retrieval.ts

    FieldMeaning
    nQueries that were scored: the sample size of every number in the object.
    errorsQueries whose search failed. Not part of n.
    hitAt1Share of queries with an answer file at rank 1. null when n is 0, like every mean below.
    hitAt5Share with an answer file in the top 5.
    hitAt10Share with an answer file in the top 10.
    recallAtKMean share of a query's answer files found in the top k.
    mrrMean reciprocal rank of the first answer file, cut at k.
    ndcgAt10Mean nDCG@10 with binary relevance.
    latencyn, meanMs, p50Ms, p95Ms over the scored queries.

    Slices come in a fixed order: overall, then groups, then languages, each sorted by name. Items whose repo is in no profile group form the slice NO_GROUP ("(no group)").

    Each configuration also keeps one row per query, so misses can be inspected without re-running:

    export interface RetrievalItemResult {
      itemId: string;
      language: string;
      /** True for the query that feeds the overall and per-group numbers; false for an extra translation. */
      primary: boolean;
      query: string;
      /** Present when the glossary changed the query. */
      effectiveQuery?: string;
      /** Present when the search failed; such a row has no metrics and is excluded from every mean. */
      error?: string;
      latencyMs?: number;
      /** Number of hits returned. */
      results: number;
      /** Rank of the first hit on an answer file anywhere in the returned list (may be beyond k). */
      firstHitRank?: number;
      found: { path: string; rank: number }[];
      missed: string[];
      /** The returned locations, best first, kept so misses can be inspected without re-running. */
      top: { repo: string; path: string; alsoIn?: { repo: string; path: string }[] }[];
      metrics?: ItemMetrics;
    }
    
    export interface ItemMetrics {
      hitAt1: number;
      hitAt5: number;
      hitAt10: number;
      recallAtK: number;
      reciprocalRank: number;
      ndcgAt10: number;
    }

    defined in packages/eval/src/retrieval.ts

    RETRIEVAL_REPORT_VERSION is 1. The report is plain JSON: JSON.stringify(report) is what safran eval retrieval --out writes.

    compareConfigs

    /**
     * Compares configuration `b` against `a` on the queries both scored.
     *
     * The deltas are plain differences of means and prove nothing by themselves: on a few
     * hundred title queries a swing of a couple of points is ordinary noise. The verdict comes
     * from a paired bootstrap on per-query reciprocal rank (see `pairedBootstrap`): a difference
     * is called only when the 95 % interval of the mean difference excludes zero. The seed is
     * fixed, so the same report always yields the same interval.
     *
     * Only primary rows are compared (one per item); translations are left to the language slices.
     */
    export function compareConfigs(report: RetrievalReport, a: string, b: string, options: PairedBootstrapOptions = {}): ConfigComparison;
    
    export interface ConfigComparison {
      a: string;
      b: string;
      /** Queries both configurations scored. Every value below rests on exactly these. */
      n: number;
      /** Queries left out because one side failed. */
      unpaired: number;
      deltas: MetricDelta[];
      latency: { p50Ms: { a: number | null; b: number | null; delta: number | null }; p95Ms: { a: number | null; b: number | null; delta: number | null } };
      /** Paired bootstrap on the per-query reciprocal rank (b − a). */
      significance: PairedBootstrapResult;
      verdict: SignificanceVerdict;
      /** The verdict in words, with the numbers it rests on. */
      summary: string;
    }
    
    export interface MetricDelta {
      metric: ComparedMetric;
      a: number | null;
      b: number | null;
      /** b − a. */
      delta: number | null;
    }
    
    export const COMPARED_METRICS = ["hitAt1", "hitAt5", "hitAt10", "recallAtK", "mrr", "ndcgAt10"] as const;

    defined in packages/eval/src/retrieval.ts

    Compares configuration b against a on the queries both scored. The deltas are plain differences of means and prove nothing by themselves. The verdict comes from a paired bootstrap on per-query reciprocal rank: a difference is called only when the 95 % interval of the mean difference excludes zero; otherwise summary reads "No significant difference", whatever the sign of the delta. Below minPairs paired queries no verdict is given. Only primary rows are compared (one per item); translations are left to the language slices. Only MRR is tested.

    Throws INVALID_INPUT when the report has no configuration of that name.

    pairedBootstrap

    /**
     * Paired bootstrap of a mean difference.
     *
     * Why paired: both configurations answered the same queries, and queries differ far more in
     * difficulty than configurations differ in quality. Comparing two independent means would
     * drown a real effect in that between-query noise; working on per-query differences removes
     * it.
     *
     * Method: given the n per-item differences d_i = score_b − score_a, draw n of them with
     * replacement and take their mean; repeat `resamples` times. The 2.5th and 97.5th
     * percentiles of those means (for 95 % confidence) are the interval. Whole items are
     * resampled, never single scores, so the pairing survives.
     *
     * Verdict: a difference is only called when the interval excludes zero. Otherwise the
     * answer is "no significant difference", whatever the sign of the observed delta. With fewer
     * than `minPairs` pairs no verdict is given at all.
     *
     * Limits worth knowing: the percentile interval is slightly too narrow for small n (tens of
     * items), reciprocal rank is bounded and lumpy so the interval is approximate, and running
     * many comparisons and reporting the one that "won" defeats the 95 %.
     */
    export function pairedBootstrap(differences: readonly number[], options: PairedBootstrapOptions = {}): PairedBootstrapResult;
    
    export interface PairedBootstrapOptions {
      resamples?: number;
      /** Two-sided confidence level in (0, 1). */
      confidence?: number;
      seed?: number;
      minPairs?: number;
    }
    
    export interface PairedBootstrapResult {
      /** Number of pairs the result rests on. */
      n: number;
      /** Mean of the differences (b − a). Null when there are no pairs. */
      meanDifference: number | null;
      /** Percentile interval of the mean difference. Null when no verdict can be given. */
      ci: { low: number; high: number } | null;
      confidence: number;
      resamples: number;
      seed: number;
      /** "better" means b is better than a (differences are b − a and higher is better). */
      verdict: SignificanceVerdict;
    }
    
    export type SignificanceVerdict = "better" | "worse" | "no_significant_difference" | "insufficient_data";

    defined in packages/eval/src/significance.ts

    OptionDefaultMeaning
    resamplesDEFAULT_BOOTSTRAP_RESAMPLES (10 000)Resamples drawn.
    confidenceDEFAULT_CONFIDENCE (0.95)Two-sided confidence level in (0, 1). A value outside throws RangeError.
    seedDEFAULT_BOOTSTRAP_SEED (20 260 101)Fixed, so two people running the same comparison read the same interval.
    minPairsDEFAULT_MIN_PAIRS (10)Below this many pairs the verdict is insufficient_data and ci is null.

    verdict is better when the interval lies above zero (b is better than a), worse when it lies below, no_significant_difference when it includes zero. The seeded generator is exported as createPrng.

    classifyMisses

    function classifyMisses(report: RetrievalReport, golden: GoldenSet, options?: ClassifyMissesOptions): MissClassification[];

    Sorts every miss (a scored primary query with no answer file in the top k) into one class, using only what the report and the golden set already hold: no new searches, no file reads. The classes are heuristics checked in priority order; the first that applies wins. It is a triage aid, not a measurement: look at the classes before tuning anything, because some misses are a property of the golden set and not of retrieval.

    KindClassMeaning
    golden_setnon_code_answerEvery answer file is prose or configuration.
    golden_setgeneric_titleThe title has too few informative words to point anywhere.
    rankingbelow_cutoffAn answer file was returned, but below rank k. Needs a limit above k, for example 50.
    rankingother_config_findsAnother configuration of the run has an answer file in its top k. Add mode: "lexical" and mode: "dense" configurations to see it.
    retrievalright_directoryA top-k hit is in the same directory of the same repo as an answer file.
    retrievalright_repoA top-k hit is in the answer's repo, but not near an answer file.
    retrievalsibling_repoA top-k hit is in another repo the same ticket changed.
    retrievalnothing_closeNone of the above.
    export interface ClassifyMissesOptions {
      /** Classify only this configuration. Default: all. */
      config?: string;
      genericWords?: readonly string[];
      minInformativeWords?: number;
    }
    
    export interface MissClassification {
      config: string;
      k: number;
      /** Scored primary queries. */
      scored: number;
      /** Queries with no answer file in the top k. */
      misses: number;
      classes: { class: MissClass; kind: MissKind; count: number; items: string[] }[];
      kinds: Record<MissKind, number>;
      items: ClassifiedMiss[];
      /** Whether the run asked for more than k results; without that `below_cutoff` cannot be seen. */
      sawBelowCutoff: boolean;
    }
    
    export interface ClassifiedMiss {
      itemId: string;
      class: MissClass;
      query: string;
      /** Rank at which an answer file did turn up, for `below_cutoff`. */
      rank?: number;
      /** Configuration that finds it, for `other_config_finds`. */
      foundBy?: string;
    }
    
    /**
     * Why a query missed, most specific reason first. The first two are properties of the golden
     * set (nothing to tune), the next two are ranking problems, the rest are retrieval problems.
     */
    export const MISS_CLASSES = ["non_code_answer", "generic_title", "below_cutoff", "other_config_finds", "right_directory", "right_repo", "sibling_repo", "nothing_close"] as const;
    
    export type MissKind = "golden_set" | "ranking" | "retrieval";

    defined in packages/eval/src/retrieval.ts

    OptionDefaultMeaning
    configall configurationsClassify only this one. An unknown name throws INVALID_INPUT.
    genericWordsDEFAULT_GENERIC_WORDSWords that do not count as informative.
    minInformativeWordsDEFAULT_MIN_INFORMATIVE_WORDS (2)Fewer informative words than this and the miss is generic_title.

    MISS_CLASS_INFO maps every class to its kind, a label and a one-sentence meaning. sawBelowCutoff on the result says whether the run asked for more than k results; without that below_cutoff cannot be seen.

    Metric functions

    All metric functions are pure and exported, so every number in a report can be checked by hand. They share conventions: ranked is the result list, best first, as opaque keys; relevant is the set of keys that count as an answer; a key that appears twice is credited once, at its first position; with no relevant keys every metric is 0.

    /** 1 / rank of the first relevant result; 0 when none is relevant. Averaged over queries this is MRR. */
    export function reciprocalRank(ranked: readonly string[], relevant: ReadonlySet<string>): number;
    
    /** 1-based rank of the first relevant result, or undefined when there is none. */
    export function firstRelevantRank(ranked: readonly string[], relevant: ReadonlySet<string>): number | undefined;
    
    /** 1 when at least one relevant key is in the top k, else 0. */
    export function hitAtK(ranked: readonly string[], relevant: ReadonlySet<string>, k: number): number;
    
    /** Distinct relevant keys in the top k, divided by the number of relevant keys. */
    export function recallAtK(ranked: readonly string[], relevant: ReadonlySet<string>, k: number): number;
    
    /**
     * Normalised discounted cumulative gain with binary relevance.
     *
     *   DCG@k  = Σ over ranks i ≤ k where a relevant key first appears of 1 / log2(i + 1)
     *   IDCG@k = Σ for i = 1 … min(|relevant|, k) of 1 / log2(i + 1)
     *
     * The ideal list puts every relevant key first, so the value is in [0, 1]. A repeated key
     * earns nothing the second time, which keeps the value ≤ 1 and mildly penalises a list that
     * spends its top ranks on the same file.
     */
    export function ndcgAtK(ranked: readonly string[], relevant: ReadonlySet<string>, k: number): number;
    
    /** Arithmetic mean, or null for an empty list: an average of nothing is not zero. */
    export function mean(values: readonly number[]): number | null;
    
    /** Sample standard deviation (n − 1). Null below two values. */
    export function sampleStdDev(values: readonly number[]): number | null;

    defined in packages/eval/src/metrics.ts

    percentile(values, p) uses linear interpolation between the two nearest order statistics (position = (n − 1) · p / 100) and returns null for an empty list. fileKey(repo, path) builds the key of a file inside a repo. rankedKeys(hits, relevant) turns a result list into one key per rank, crediting a hit with the first answer file (its own path or an alsoIn twin) that no earlier rank has found.

    /** Scores one result list against one item. Pure: the same function the runner uses. */
    export function scoreHits(hits: readonly Pick<CodeHit, "repo" | "path" | "alsoIn">[], item: Pick<GoldenItem, "repo" | "files">, k: number = DEFAULT_K);
    
    /** Judges a result list against the gold files of one repo. Pure; the single place matching is defined. */
    export function judgeRanking(hits: readonly RankedLocation[], repo: string, goldPaths: readonly string[]): RankingJudgement;
    
    export interface RankingJudgement {
      /** One key per rank, as produced by `rankedKeys`. */
      keys: string[];
      /** 1-based rank of the first hit that is (or mirrors) a gold file. */
      firstHitRank?: number;
      /** Gold paths found anywhere in the list, in rank order. */
      found: { path: string; rank: number }[];
      /** Gold paths not in the list, sorted. */
      missed: string[];
    }
    
    /** The part of a search hit the matcher looks at. `CodeHit` from `@safran/kit` satisfies it. */
    export interface RankedLocation {
      repo: string;
      path: string;
      alsoIn?: readonly { repo: string; path: string }[];
    }
    
    /** Aggregates rows into one slice. Rows with an error count as errors and nothing else. */
    export function summariseRows(rows: readonly RetrievalItemResult[]): SliceMetrics;
    
    export function summariseLatency(values: readonly number[]): LatencySummary;

    defined in packages/eval/src/retrieval.ts, packages/eval/src/metrics.ts

    import { fileKey, hitAtK, ndcgAtK, pairedBootstrap, percentile, recallAtK, reciprocalRank, scoreHits } from "@safran/eval";
    
    const relevant = new Set([fileKey("payments-api", "src/refund/service.ts"), fileKey("payments-api", "src/refund/policy.ts")]);
    const ranked = [
      fileKey("payments-api", "src/webhook/retry.ts"),
      fileKey("payments-api", "src/refund/service.ts"),
      fileKey("payments-api", "src/refund/service.ts"), // a second chunk of the same file earns nothing
      fileKey("payments-api", "src/refund/policy.ts"),
    ];
    console.log(reciprocalRank(ranked, relevant)); // 0.5
    console.log(hitAtK(ranked, relevant, 1), hitAtK(ranked, relevant, 5)); // 0 1
    console.log(recallAtK(ranked, relevant, 2)); // 0.5
    console.log(ndcgAtK(ranked, relevant, 10).toFixed(3)); // 0.651
    console.log(percentile([12, 15, 11, 240], 95)?.toFixed(2)); // 206.25
    
    // The same scoring the runner applies to one result list.
    const { metrics, judgement } = scoreHits(
      [
        { repo: "payments-api", path: "src/webhook/retry.ts" },
        { repo: "payments-api", path: "src/refund/service.ts" },
      ],
      { repo: "payments-api", files: ["src/refund/service.ts", "src/refund/policy.ts"] },
    );
    console.log(metrics.reciprocalRank, judgement.firstHitRank, judgement.missed); // 0.5 2 [ "src/refund/policy.ts" ]
    
    // Per-query differences (b − a) of any score where higher is better.
    const result = pairedBootstrap([0.5, 0, 0.25, 0, 0.5, 0, 0, 1, 0.5, 0, 0.25, 0]);
    console.log(result.verdict, result.n, result.meanDifference?.toFixed(3)); // better 12 0.250

    Replay evaluation

    For a merged pull request with a known commit, the repo is checked out as it was before the change, an agent command (an arm) is run in that checkout with the ticket as its task, and the files it touched are compared with the files the real change touched. Arms are whatever you supply: typically a bare agent and the same agent with the Safran MCP server. The real diff is the implicit third arm, the oracle: its file scores are 1.0 by definition, not by measurement, and it anchors the scale.

    replay.ts
    import { compareArms, formatReplaySummary, loadGoldenSet, renderReplayReport, replayTasksFromGoldenSet, runReplayEval, type ReplayArm } from "@safran/eval";
    import { createSafran } from "@safran/core";
    
    // Placeholder commands: replace `acme-agent` with the agent CLI you use, and check its flags.
    const bare: ReplayArm = {
      name: "bare",
      command: ["acme-agent", "--prompt-file", "{prompt_file}"],
      timeoutMs: 20 * 60_000,
    };
    const withSafran: ReplayArm = {
      name: "with-safran",
      command: ["acme-agent", "--prompt-file", "{prompt_file}", "--mcp-config", "/work/acme/safran.mcp.json"],
      env: { ACME_AGENT_RESULT: "{result_file}" },
      timeoutMs: 20 * 60_000,
    };
    
    await using safran = await createSafran();
    const golden = await loadGoldenSet(`${safran.dataDir}/eval/golden.json`);
    const { tasks, excluded } = replayTasksFromGoldenSet(golden);
    console.log(`${tasks.length} tasks, ${excluded.length} items cannot be replayed`);
    
    const report = await runReplayEval(safran, tasks, {
      arms: [bare, withSafran],
      runs: 3,
      maxTasks: 20,
      maxCostUsd: 40,
      testCommand: { "payments-api": ["bun", "test"] },
      onProgress: ({ phase, taskId, arm, done, total }) => console.error(`${taskId} ${phase} ${arm ?? ""} ${done}/${total}`),
    });
    
    console.log(formatReplaySummary(report));
    console.log(compareArms(report, "bare", "with-safran").summary);
    await Bun.write("replay.html", renderReplayReport(report, { profile: safran.profile.company }));

    replayTasksFromGoldenSet

    /** Tasks for the replay from a golden set: items backed by exactly one pull request with a recorded merge commit. */
    export function replayTasksFromGoldenSet(golden: GoldenSet): { tasks: ReplayTask[]; excluded: { id: string; reason: string }[] };
    
    export interface ReplayTask {
      id: string;
      repo: string;
      ticketKey?: string;
      title: string;
      /** Commit the change was merged as. The checkout is its first parent. */
      mergeCommit?: string;
      /** Explicit commit to check out; wins over `mergeCommit`'s parent. */
      baseCommit?: string;
      /** Files the real change touched. Used when git cannot provide the real diff. */
      files: string[];
    }

    defined in packages/eval/src/replay.ts

    Keeps the golden items backed by exactly one pull request with a recorded merge commit; the others are returned in excluded with a reason (several pull requests have several "before" states). You can also write tasks by hand.

    FieldMeaning
    idUnique within a run.
    repoSafran repo name. The repo must be cloned locally.
    ticketKeyTicket whose title and description become the prompt. Optional.
    titleUsed as the prompt when there is no ticket or it cannot be read.
    mergeCommitCommit the change was merged as. The checkout is its first parent.
    baseCommitExplicit commit to check out; wins over the parent of mergeCommit.
    filesFiles the real change touched. Used when git cannot provide the real diff.

    ReplayArm

    export interface ReplayArm {
      name: string;
      /** argv, no shell. Run with the checkout as its working directory. */
      command: string[];
      /** Added to the caller's environment. Values take placeholders too. */
      env?: Record<string, string>;
      timeoutMs?: number;
    }
    
    /** Placeholders replaced in an arm's command and env values. Anything else in braces is left alone (JSON arguments stay intact). */
    export const REPLAY_PLACEHOLDERS = ["workdir", "prompt_file", "prompt", "result_file", "ticket_key", "task_id", "repo", "title", "arm", "run"] as const;

    defined in packages/eval/src/replay.ts

    FieldDefaultMeaning
    namerequiredUnique; oracle is reserved for the real diff.
    commandrequiredargv, run without a shell, with the checkout as its working directory.
    envnoneAdded to the caller's environment. Values take placeholders too.
    timeoutMsDEFAULT_ARM_TIMEOUT_MS (30 minutes)The process group gets SIGTERM, then SIGKILL after killGraceMs.

    Placeholders are replaced in command and in env values; anything else in braces is left alone, so JSON arguments stay intact (fillPlaceholders is the exported function that does it).

    PlaceholderValue
    {workdir}The checkout.
    {prompt_file}A file holding the prompt.
    {prompt}The prompt text itself.
    {result_file}Where the arm may write its cost: { "cost_usd": 0.42, "tokens": 51000 }.
    {ticket_key}The task's ticket key, or empty.
    {task_id}The task id.
    {repo}The repo name.
    {title}The ticket title, or the task title.
    {arm}The arm name.
    {run}1-based repeat number.

    Cost is read from {result_file} only. If the arm writes nothing the cost is "unknown"; it is never estimated. To record cost, wrap the agent in a small script of your own that writes the file from the agent's usage output. Keep everything else identical between the arms (model, prompt, permissions, timeout), or the comparison measures those differences.

    runReplayEval

    /**
     * Runs every arm on every task, `runs` times each, one process at a time.
     *
     * Unlike the rest of Safran, cancellation does not reject: a replay costs real money, so an
     * aborted or budget-stopped run returns everything finished so far with `aborted` /
     * `budget.stoppedBy` set and the remaining tasks marked `not_run`. Temporary worktrees are
     * removed on every path.
     */
    export async function runReplayEval(safran: Safran, tasks: readonly ReplayTask[], options: ReplayEvalOptions): Promise<ReplayReport>;

    defined in packages/eval/src/replay.ts

    For each task the runner:

    1. finds the commit before the change (the first parent of the merge commit). Managed clones are shallow, so with fetchMissing it tries a depth-limited git fetch of that commit from the clone's remote; no ref and no FETCH_HEAD is moved. If the commit still cannot be had, the task is skipped. Nothing is ever substituted;
    2. creates a detached git worktree at that commit inside a temporary directory;
    3. runs each arm's command there, with the ticket written to a prompt file;
    4. compares the working tree with the base commit (committed, staged, unstaged and new files alike) and scores the touched files against the files the real change touched;
    5. removes the worktree, always, including on timeout and cancellation.

    When a test command applies it is also run on the real change (oracleTests), because tests that fail there cannot judge anyone.

    maxTasks, maxWallMs and maxCostUsd stop the run cleanly; tasks not reached are reported as not_run. A cancelled run returns what it finished instead of throwing (aborted: true), because those runs cost money. It throws INVALID_INPUT before any work starts: no arm, an empty or reserved arm name, an empty command, a non-positive timeout, two arms or two tasks with the same name or id, foundThreshold outside (0, 1], or a non-positive runs, maxTasks or maxDiffFiles.

    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

    OptionDefaultMeaning
    armsrequiredThe commands to compare.
    runsDEFAULT_REPLAY_RUNS (1)Repeats per task and arm. Agents are not deterministic; one run is an anecdote.
    foundThresholdDEFAULT_FOUND_THRESHOLD (0.5)"Found the right files" = at least this share of the really changed files was touched.
    testCommandnoneTest command per repo name, or a function of the task. argv, run in the checkout after the arm; exit 0 = pass.
    testTimeoutMsDEFAULT_TEST_TIMEOUT_MS (15 minutes)Timeout of one test run.
    oracleTeststrueAlso run the test command on the real change.
    maxTasksnoneStop after this many tasks.
    maxWallMsnoneChecked before each run starts; a run in flight is not cut short.
    maxCostUsdnoneCounts only costs the arms report. An arm that reports none is never stopped by this.
    fetchMissingtrueTry to fetch a missing commit from the clone's remote.
    includeDescriptiontruePut the ticket description in the prompt, not only the title.
    buildPromptbuilt-in promptYour own prompt from the task and the ticket (undefined when it could not be read).
    tempDirthe OS temp directoryParent of the temporary workspace.
    logDirdiscardedKeep each run's stdout and stderr here.
    maxDiffFilesDEFAULT_MAX_DIFF_FILES (50)A diff touching more files is flagged oversized: usually a formatter run or a dependency install.
    killGraceMsDEFAULT_KILL_GRACE_MS (2000)Time between SIGTERM and SIGKILL.
    signalnoneCancels the run; the report comes back with aborted: true.
    onProgressnoneReplayProgress: phase (prepare, run, test, done), taskId, arm, run, done, total.
    now() => new Date()Clock for startedAt and finishedAt.

    The built-in prompt names the repository, tells the agent to edit files in the current directory and not to commit, push or open a pull request, then gives the ticket key, title and (with includeDescription) description.

    ReplayReport

    export interface ReplayReport {
      version: typeof REPLAY_REPORT_VERSION;
      startedAt: string;
      finishedAt: string;
      durationMs: number;
      runsPerTask: number;
      foundThreshold: number;
      arms: { name: string; command: string[]; timeoutMs: number }[];
      tasks: ReplayTaskResult[];
      summary: ReplayArmSummary[];
      /** The real diff. Its file scores are 1.0 because it is the reference, not because anything was measured; only `tests` is measured. */
      oracle: { tasks: number; precision: 1; recall: 1; f1: 1; byConstruction: true; tests: { passed: number; of: number } };
      budget: {
        maxTasks?: number;
        maxWallMs?: number;
        maxCostUsd?: number;
        stoppedBy?: "maxTasks" | "maxWallMs" | "maxCostUsd" | "aborted";
        runsPlanned: number;
        runsExecuted: number;
        tasksNotRun: number;
        tasksSkipped: number;
        reportedCostUsd: number;
      };
      aborted: boolean;
      /** Problems removing temporary worktrees. Empty in a clean run. */
      cleanupErrors: string[];
    }
    
    export interface ReplayTaskResult {
      task: { id: string; repo: string; ticketKey?: string; title: string };
      /** `skipped`: could not be prepared (reason says why). `not_run`: a budget or cancellation stopped the run first. */
      status: "ran" | "skipped" | "not_run";
      reason?: string;
      baseCommit?: string;
      /** Files of the real change that the runs are scored against. */
      realFiles: string[];
      /** `git`: read from the diff between the base and the merge commit. `task`: taken from the task as given. */
      realFilesSource: "git" | "task";
      promptSource: "ticket" | "title";
      /** The test command on the real change. Absent when no test command applies or the merge commit is unavailable. */
      oracleTests?: TestOutcome;
      runs: ReplayRun[];
    }
    
    export interface ReplayRun {
      taskId: string;
      arm: string;
      /** 1-based repeat number. */
      run: number;
      status: ReplayRunStatus;
      exitCode?: number;
      wallMs: number;
      /** Files changed relative to the base commit, after dropping lockfiles, generated files, vendored trees and assets. */
      touched: string[];
      /** Changed files dropped by that filter. */
      ignored: number;
      /** Absent when the diff could not be read (`scoring_failed`) or the run was aborted. */
      score?: FileScore;
      foundRightFiles?: boolean;
      changedNothing?: boolean;
      diff?: { files: number; added: number; deleted: number; oversized: boolean };
      tests?: TestOutcome;
      /** As reported by the arm in `{result_file}`. Never estimated. */
      cost?: { usd?: number; tokens?: number };
      containment: {
        /** Entries the arm created in the temporary workspace outside its checkout. */
        strayFiles: string[];
        /** Refs or HEAD of the source clone differ from before the run. */
        sourceRepoChanged: boolean;
      };
      error?: string;
    }
    
    export interface FileScore {
      precision: number;
      recall: number;
      f1: number;
      truePositives: string[];
    }
    
    export type ReplayRunStatus = "ok" | "nonzero_exit" | "timeout" | "spawn_error" | "aborted" | "scoring_failed";
    
    export type TestOutcome = "pass" | "fail" | "timeout" | "error";

    defined in packages/eval/src/replay.ts

    FieldMeaning
    taskIdThe task.
    armThe arm.
    run1-based repeat number.
    statusok, nonzero_exit, timeout, spawn_error, aborted or scoring_failed.
    exitCodeExit code, when the process exited.
    wallMsWall time of the arm.
    touchedFiles changed relative to the base commit, after dropping lockfiles, generated files, vendored trees and assets.
    ignoredChanged files dropped by that filter.
    scoreprecision, recall, f1, truePositives. Absent when the diff could not be read or the run was aborted.
    foundRightFilesRecall is at least foundThreshold.
    changedNothingThe arm touched no scorable file.
    difffiles, added, deleted, oversized.
    testspass, fail, timeout or error, when a test command applies.
    costusd and tokens as reported by the arm. Never estimated.
    containmentstrayFiles (entries the arm created in the temporary workspace outside its checkout) and sourceRepoChanged (refs or HEAD of the source clone differ from before).
    errorWhat went wrong, for a failed run.

    A task result has status: "ran", "skipped" (could not be prepared; reason says why) or "not_run" (a budget or cancellation stopped the run first). REPLAY_REPORT_VERSION is 1.

    export interface ReplayArmSummary {
      arm: string;
      /** Tasks with at least one scored run. The n of the means below. */
      tasks: number;
      runs: number;
      scoredRuns: number;
      statuses: Record<ReplayRunStatus, number>;
      /** Mean over tasks of the per-task mean over runs, so a task with more runs does not weigh more. */
      precision: number | null;
      recall: number | null;
      f1: number | null;
      /** Mean run-to-run standard deviation of F1 within a task; null unless some task has two scored runs. */
      f1RunSd: number | null;
      /** Tasks that contributed to `f1RunSd`. */
      f1RunSdTasks: number;
      f1Min: number | null;
      f1Max: number | null;
      foundRightFiles: { count: number; of: number };
      changedNothing: { count: number; of: number };
      oversizedDiffs: number;
      tests: { passed: number; of: number };
      cost: { reportedRuns: number; totalUsd: number | null; medianUsd: number | null; totalTokens: number | null };
      wall: { n: number; medianMs: number | null; meanMs: number | null };
      containmentFlags: number;
    }
    
    export function summariseArm(arm: string, tasks: readonly ReplayTaskResult[]): ReplayArmSummary;

    defined in packages/eval/src/replay.ts

    Arm means are means over tasks of the per-task mean over runs, so a task with more runs does not weigh more. f1RunSd is the mean run-to-run standard deviation of F1 within a task; it is null unless some task has two scored runs.

    compareArms

    /**
     * Compares arm `b` with arm `a` on the tasks both ran, with the same paired bootstrap as
     * the retrieval comparison (tasks are resampled, runs of a task stay together). Replays are
     * small; expect "too few tasks" or "no significant difference" far more often than a win,
     * and read that as the honest answer it is.
     */
    export function compareArms(report: ReplayReport, a: string, b: string, options: PairedBootstrapOptions = {}): ArmComparison;
    
    export interface ArmComparison {
      a: string;
      b: string;
      /** Tasks both arms have a scored run for. */
      n: number;
      f1: { a: number | null; b: number | null; delta: number | null };
      /** Paired bootstrap over tasks on the per-task mean F1 (b − a). */
      significance: PairedBootstrapResult;
      verdict: SignificanceVerdict;
      summary: string;
    }

    defined in packages/eval/src/replay.ts

    The same paired bootstrap as compareConfigs, over tasks, on the per-task mean F1 (b − a); tasks are resampled and runs of a task stay together. Replays are small: expect "Too few tasks" or "No significant difference" far more often than a win, and read that as the honest answer it is. Throws INVALID_INPUT for an unknown arm name.

    Scoring helpers

    /** File-level precision / recall / F1 of touched files against the really changed ones. Touching nothing scores 0. */
    export function scoreFiles(touched: readonly string[], real: readonly string[]): FileScore;
    
    /** Replaces the documented placeholders; unknown `{…}` text is left untouched. */
    export function fillPlaceholders(template: string, values: Readonly<Record<string, string>>): string;
    
    /**
     * Environment for our own git calls. `@safran/core` keeps its builder (`buildGitEnv` in
     * `core/src/git.ts`) private, so this is a copy of its rules and has to stay one: a clone that
     * core refuses to let run a hook, write a symlink or call a helper must not get to do so because
     * the replay touched it instead. `test/replay.test.ts` pins the list.
     *
     * `extraConfig` is where a credential goes: through the environment, never argv or `.git/config`.
     */
    export function buildReplayGitEnv(extraConfig: readonly [string, string][] = [], base: Record<string, string | undefined> = process.env): Record<string, string>;

    defined in packages/eval/src/replay.ts

    import { fillPlaceholders, scoreFiles } from "@safran/eval";
    
    console.log(scoreFiles(["src/refund/service.ts", "README.md"], ["src/refund/service.ts", "src/refund/policy.ts"]));
    // { precision: 0.5, recall: 0.5, f1: 0.5, truePositives: [ "src/refund/service.ts" ] }
    console.log(fillPlaceholders("{ticket_key} in {repo}: {unknown}", { ticket_key: "PAY-1423", repo: "payments-api" }));
    // PAY-1423 in payments-api: {unknown}

    buildReplayGitEnv is the environment the runner uses for its own git calls (no hooks, no credential helpers; a credential goes through the environment, never argv). It is exported for tests of the runner; you do not need it to run a replay.

    What a replay score means

    File overlap with one accepted solution. A different correct solution scores low; the right files with wrong code score high. The ticket is read as it is today and may describe the solution. Agents are not deterministic: use runs and read the run-to-run deviation. A per-repo testCommand is the stronger judge where it exists.

    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.

    Reports

    /**
     * Renders a retrieval report as one self-contained HTML page. Pass the golden set the run
     * used to get the miss classification and the filter counts in the methodology section.
     */
    export function renderRetrievalReport(report: RetrievalReport, golden?: GoldenSet, options: RetrievalRenderOptions = {}): string;
    
    /** Renders a replay report as one self-contained HTML page. */
    export function renderReplayReport(report: ReplayReport, options: ReportRenderOptions = {}): string;
    
    /** Plain-text table for the terminal: one row per configuration and slice, each with its n. */
    export function formatRetrievalSummary(report: RetrievalReport, options: { bootstrap?: PairedBootstrapOptions } = {}): string;
    
    /**
     * Plain-text table for the terminal: one row per arm plus the real diff, each count with what
     * it is out of. The companion of `formatRetrievalSummary`; no colour, ends with a newline.
     */
    export function formatReplaySummary(report: ReplayReport, options: { bootstrap?: PairedBootstrapOptions } = {}): string;

    defined in packages/eval/src/report.ts

    renderRetrievalReport(report, golden?, options?) and renderReplayReport(report, options?) return one self-contained HTML page: the stylesheet is inlined, there is no script, image, font or external request, and a Content-Security-Policy meta element allows nothing but that one stylesheet. Every string from tickets, paths, repos and arm names is escaped, and escape sequences and invisible characters are removed. Pass the golden set to the retrieval report to get the miss classification and the filter counts in its methodology section.

    formatRetrievalSummary(report) and formatReplaySummary(report) are the same data as plain-text tables for a terminal: one row per configuration and slice, or one row per arm plus the real diff. With two or more configurations or arms they append the comparison sentences. Both accept { bootstrap } to pass PairedBootstrapOptions to those comparisons.

    export interface ReportRenderOptions {
      /** Heading of the report. */
      title?: string;
      /** Shows the "example data" notice. Set it for anything that is not a real measurement. */
      example?: boolean;
      /** Profile (company slug) named in the header line. */
      profile?: string;
      /** `<html lang>`. Default: en. */
      lang?: string;
      /** Options for the significance check behind every comparison. */
      bootstrap?: PairedBootstrapOptions;
    }
    
    export interface RetrievalRenderOptions extends ReportRenderOptions {
      missSamples?: number;
    }

    defined in packages/eval/src/report.ts

    OptionDefaultMeaning
    titlea built-in headingHeading of the report.
    examplefalseShows the "example data" notice. Set it for anything that is not a real measurement.
    profilenoneProfile (company slug) named in the header line.
    langenValue of the lang attribute of the page.
    bootstrapthe defaultsOptions for the significance check behind every comparison.
    OptionDefaultMeaning
    missSamplesDEFAULT_MISS_SAMPLES (10)Misses listed per configuration in the HTML report. The full list is in the report object.

    escapeHtml and loadReportCss are the building blocks the renderers use, exported for anyone writing a report of their own in the same design.

    import { renderRetrievalReport, type GoldenSet, type RetrievalReport } from "@safran/eval";
    
    export async function writeReport(report: RetrievalReport, golden: GoldenSet): Promise<void> {
      const html = renderRetrievalReport(report, golden, { title: "acme: code search", profile: "acme", missSamples: 20 });
      await Bun.write("retrieval.html", html);
    }

    Common mistakes

    • Building a golden set from an empty store. buildGoldenSet only reads; with stats.prs === 0 run safran.links.refresh() (or safran links refresh) first.
    • Reading a delta as a result. Use compareConfigs or compareArms and report the verdict. With fewer than ten pairs there is none.
    • Calling a failed search a miss. Rows with error are in errors, not in the means. If errors is large, fix the embedder before reading anything else.
    • Tuning on the misses without classifying them. non_code_answer and generic_title are properties of the golden set; no retrieval change will fix them.
    • Expecting below_cutoff with the default depth. Set limit: 50 on the configurations, otherwise nothing below rank k is ever returned.
    • Running a replay with arms that differ in more than Safran. A different model, prompt or timeout is what the comparison will then measure.
    • Mixing golden sets or reports from different versions. INCOMPATIBLE_DATA means rebuild; the numbers are not comparable.