Documentation
¶
Overview ¶
Package eval is CommitBrief's review-quality eval harness (ADR-0018).
It scores a provider's actual review output against a curated known-answer corpus and reports precision / recall / false-positive rate. The corpus lives under testdata/corpus/<name>/, one directory per fixture: input.diff (the change under review), expected.json (the answer key), and, for the deterministic tier, mock_response.json (scripted findings fed to the mock provider).
Two execution tiers (ADR-0018 §3):
Deterministic tier — TestEvalMockCorpus runs the corpus through the mock provider with each fixture's scripted response. It validates the harness, matcher, and scoring math, runs in plain `go test ./...`, and is therefore part of the CI gate. It does NOT measure model quality.
Live tier — TestEvalLive (behind the `live` build tag, like the rest of the live provider tests) runs the corpus through a real provider and prints the quality scorecard. Non-deterministic and gated; it is the source of the README quality numbers, never a CI gate.
The harness consumes provider output through the locked --json schema v1 findings[] (ADR-0014); it introduces no new output contract.
Index ¶
- Constants
- func CorpusFingerprint(root string) (string, error)
- func LanguageDistribution(fixtures []Fixture) map[string]int
- func PromptSHA256() string
- func WriteResult(path string, corpus CorpusInfo, runs int, thresholds Thresholds, ...) error
- type BenchmarkFile
- type BenchmarkRow
- type CategoryRecall
- type CorpusInfo
- type ExpectedFinding
- type Fixture
- type FixtureScore
- type RowPricing
- type Scorecard
- func (sc Scorecard) CategoryRecall() []CategoryRecall
- func (sc Scorecard) CleanAlarms() int
- func (sc Scorecard) Dev() Scorecard
- func (sc Scorecard) Errors() int
- func (sc Scorecard) HeldOut() Scorecard
- func (sc Scorecard) NBuggy() int
- func (sc Scorecard) NClean() int
- func (sc Scorecard) NExpected() int
- func (sc Scorecard) Precision() float64
- func (sc Scorecard) PrecisionN() int
- func (sc Scorecard) Recall() float64
- func (sc Scorecard) RecallN() int
- func (sc Scorecard) SilenceViolationRate() float64
- func (sc Scorecard) SilenceViolationRateN() int
- func (sc Scorecard) TotalUsage() provider.Usage
- type SilenceAnchor
- type Thresholds
Constants ¶
const ( RecallMinValue = 0.90 FPRMaxValue = 0.10 )
RecallMinValue and FPRMaxValue are ADR-0043 §2's recall/fpr gate "in force today" (0.90/0.10). §1.5 forbids relaxing a threshold for a single run — env/flag overrides would make exactly that silent and undetectable from the results file, so these are package constants, not a knob. Changing them requires a dated §Update to ADR-0043 (review 2026-09-24, BLOCKER).
Variables ¶
This section is empty.
Functions ¶
func CorpusFingerprint ¶ added in v1.18.0
CorpusFingerprint returns a stable SHA-256 fingerprint of the corpus rooted at root (ADR-0043 §4): for every fixture directory in directory-name order (the same order LoadCorpus returns), the fixture's name plus the raw bytes of its input.diff and expected.json. README.md and mock_response.json are deliberately excluded — one documents a fixture, the other only drives the mock tier, and neither is part of what a live measurement is graded against, so editing either must not change the fingerprint a results row is keyed to. Reads files directly rather than going through LoadFixture so the fingerprint covers the exact on-disk expected.json bytes, not the struct JSON round-tripped back through it.
func LanguageDistribution ¶ added in v1.18.0
LanguageDistribution counts fixtures per answer-key language. Every reported ratio (recall/precision/fpr) must carry its language mix alongside n, so a results row and a `make eval` summary both build this from the same fixture slice they scored. A fixture whose expected.json omits "language" is counted under "unknown" rather than silently dropped — a gap in the corpus metadata should be visible, not hidden.
func PromptSHA256 ¶ added in v1.18.0
func PromptSHA256() string
PromptSHA256 fingerprints the eval prompt independent of any fixture's diff (ADR-0043 §4): the system prompt and the user prompt *template* (diff not yet substituted in), the same (system, userTpl) pair buildRequest's prompt.Build call is built from. It changes whenever either text changes — including a user-template-only edit such as the line-number instructions — so a results row can be told apart from a measurement taken under an older prompt.
func WriteResult ¶ added in v1.18.0
func WriteResult(path string, corpus CorpusInfo, runs int, thresholds Thresholds, row BenchmarkRow) error
WriteResult merges one provider+model measurement into the results file at path (ADR-0043 §4), creating it if absent. Rows are keyed by (provider, model): re-measuring a pair replaces its row outright, even one written under an older prompt — prompt history survives only on whichever *other* rows still hold their own provider/model slot, not by stacking multiple measurements under one slot. Every row's `eligible` — including every pre-existing row, not only the one just written — is recomputed against corpus, runs, thresholds and row's own prompt hash, so an older row silently drops out of eligibility the moment a newer prompt is measured, without needing its own rewrite to notice.
The write is refused if the file already holds evidence for a different corpus fingerprint or run count: a results file holds exactly one corpus's worth of evidence, and mixing two would make every row's n meaningless. Output is deterministic: rows sorted by (provider, model), fixed field order via the struct, indented JSON with a trailing newline.
Types ¶
type BenchmarkFile ¶ added in v1.18.0
type BenchmarkFile struct {
Schema int `json:"schema"`
GeneratedAt string `json:"generated_at"`
Corpus CorpusInfo `json:"corpus"`
Runs int `json:"runs"`
Thresholds Thresholds `json:"thresholds"`
Results []BenchmarkRow `json:"results"`
}
BenchmarkFile is the whole ADR-0043 §4 results document — one corpus's worth of evidence across every measured provider+model.
func LoadResults ¶ added in v1.18.0
func LoadResults(path string) (bf BenchmarkFile, existed bool, err error)
LoadResults reads the results file at path. A missing file is not an error — it returns a zero BenchmarkFile and existed=false so WriteResult can create it on the first write.
A file whose schema isn't 1 is refused rather than silently accepted: a future schema bump read back by this (older) code would otherwise get merged and rewritten as schema:1, quietly downgrading it (review 2026-09-24, MINOR).
type BenchmarkRow ¶ added in v1.18.0
type BenchmarkRow struct {
Provider string `json:"provider"`
Model string `json:"model"`
MeasuredAt string `json:"measured_at"`
PromptSHA256 string `json:"prompt_sha256"`
CommitbriefCommit string `json:"commitbrief_commit"`
Runs int `json:"runs"`
NBuggy int `json:"n_buggy"`
NClean int `json:"n_clean"`
NExpected int `json:"n_expected"`
Recall float64 `json:"recall"`
RecallMin float64 `json:"recall_min"`
RecallMax float64 `json:"recall_max"`
Precision float64 `json:"precision"`
FPR float64 `json:"fpr"`
FPRMin float64 `json:"fpr_min"`
FPRMax float64 `json:"fpr_max"`
SilenceViolationRate float64 `json:"silence_violation_rate"`
Errors int `json:"errors"`
InputTokens float64 `json:"input_tokens"`
OutputTokens float64 `json:"output_tokens"`
CachedInputTokens float64 `json:"cached_input_tokens"`
Pricing RowPricing `json:"pricing"`
USDPerReview float64 `json:"usd_per_review"`
Eligible bool `json:"eligible"`
}
BenchmarkRow is one provider+model measurement (ADR-0043 §4).
func BuildRow ¶ added in v1.18.0
func BuildRow(scs []Scorecard, pricing provider.Pricing, promptSHA256, commit string, measuredAt time.Time) (BenchmarkRow, error)
BuildRow pools k Scorecards — one per COMMITBRIEF_EVAL_RUNS repeat, all against the same corpus and provider+model — into a single ADR-0043 §4 results row. The headline ratios (recall, precision, fpr, silence_violation_rate) are pooled by summing raw counts across every run and dividing once, not by averaging each run's own ratio, so a run that happened to score more evidence isn't outweighed by one that scored less. recall_min/max and fpr_min/max instead report the spread across the individual per-run ratios — that spread is exactly what a flaky provider shows up as, and pooling it away would hide it.
type CategoryRecall ¶
CategoryRecall is per-category recall for one expected-finding category.
type CorpusInfo ¶ added in v1.18.0
type CorpusInfo struct {
Fingerprint string `json:"fingerprint"`
NFixtures int `json:"n_fixtures"`
NBuggy int `json:"n_buggy"`
NClean int `json:"n_clean"`
NExpected int `json:"n_expected"`
Languages map[string]int `json:"languages"`
}
CorpusInfo identifies which corpus a results file's rows were measured against (ADR-0043 §4). Fingerprint is the authority WriteResult uses to refuse mixing two different corpora into one file.
func NewCorpusInfo ¶ added in v1.18.0
func NewCorpusInfo(fixtures []Fixture, fingerprint string) CorpusInfo
NewCorpusInfo summarizes a fixture slice into a results file's corpus block. fingerprint is computed separately (CorpusFingerprint) so every row written in the same eval-live invocation shares one value even though ADR-0043 §3 model-selection metrics score the whole corpus, not the dev/held-out split ADR-0018 uses for tuning-safety diagnostics.
type ExpectedFinding ¶
type ExpectedFinding struct {
ID string `json:"id"`
File string `json:"file"`
Line int `json:"line"`
LineTol int `json:"line_tol,omitempty"`
Category string `json:"category"`
MinSeverity render.Severity `json:"min_severity,omitempty"`
Summary string `json:"summary"`
}
ExpectedFinding is one entry in a fixture answer key — a defect the review SHOULD surface (ADR-0018 §1). Category is reporting metadata, not a match criterion: the locked findings schema carries no category field.
type Fixture ¶
type Fixture struct {
Name string
Dir string
Language string
Diff string
Expected []ExpectedFinding
MustStaySilentOn []SilenceAnchor
MockResponse string
// HeldOut marks the fixture as part of the generalization-only slice;
// see answerKey.HeldOut.
HeldOut bool
}
Fixture is one known-answer corpus entry: a diff plus its answer key. MockResponse is the scripted findings JSON used by the deterministic tier; it is empty when the fixture ships no mock_response.json.
func LoadCorpus ¶
LoadCorpus loads every fixture under root — each child directory that contains an input.diff. Fixtures are returned sorted by name so every run iterates deterministically.
func LoadFixture ¶
LoadFixture reads a single corpus directory: input.diff + expected.json (required) and mock_response.json (optional, for the deterministic tier).
func (Fixture) Categories ¶
Categories returns the distinct categories a fixture exercises: the category of each expected finding, or "clean" for a clean control (no expected findings). Used to check that the held-out slice is representative rather than concentrated in one category.
type FixtureScore ¶
type FixtureScore struct {
Fixture string
HeldOut bool // mirrors Fixture.HeldOut so a Scorecard can be split
TruePositives int // expected findings that were matched
FalseNegatives int // expected findings that were missed
FalsePositives int // produced findings that matched no expected finding
SilenceViolations int // produced findings landing on a silence anchor
SilenceAnchors int // total silence anchors in the fixture
// CaughtByCategory / MissedByCategory attribute each expected finding to
// its category, giving a per-category recall breakdown (ADR-0018 §2).
CaughtByCategory map[string]int
MissedByCategory map[string]int
// Usage is the token usage the provider reported for this fixture's
// Review call. Zero on the mock tier (the mock provider's usage is a
// fixed stub, never billed) and on a fixture whose Review call itself
// failed (no response was ever returned to report usage from). Still
// populated on a fixture that errored only because its response body
// couldn't be parsed as findings — the provider did report usage for
// that call, and RunFixture/RunCorpus carry it through rather than
// discarding it (review 2026-09-24, MINOR).
Usage provider.Usage
// CleanAlarm reports whether this run raised at least one produced
// finding of severity low-or-higher on a clean-control fixture —
// ADR-0043 §3's fpr numerator for a single fixture run. info findings
// don't count (the severity rubric defines info as "no action
// required"); they still show up in Precision. Always false for a
// fixture that planted a defect.
CleanAlarm bool
// Errored marks a fixture whose review call failed after the harness's
// own retries, or whose output could not be parsed (ADR-0043 §3). Such
// a run is scored as a miss for every expected finding and, for a
// clean fixture, as a CleanAlarm — see ErrorScore.
Errored bool
// ErrorMsg is the last attempt's error text when Errored is true (empty
// otherwise). RunCorpus previously swallowed this after exhausting
// retries — a run's log looked identical whether a model genuinely
// missed every finding or every call to it failed. Carrying the message
// through lets the caller log it instead (review 2026-09-24, MAJOR).
ErrorMsg string
}
FixtureScore is the per-fixture outcome of scoring produced findings against the answer key.
func ErrorScore ¶ added in v1.18.0
func ErrorScore(fx Fixture) FixtureScore
ErrorScore produces the FixtureScore for a fixture whose review call failed after the harness's own retries, or whose output could not be parsed (ADR-0043 §3). It counts as a miss for every expected finding of a buggy fixture, and as a CleanAlarm for a clean fixture — an errored model is not silently dropped from the corpus it failed on.
func RunFixture ¶
func RunFixture(ctx context.Context, p provider.Provider, fx Fixture, model string) (FixtureScore, error)
RunFixture runs one fixture through a provider and scores the result. An empty model uses the provider's default model. On error the returned FixtureScore is not a scored result — callers must check err first — but it still carries Usage when reviewFindings obtained one (a parse failure still means the provider billed for and returned a response), so a caller building an ErrorScore for this attempt doesn't have to throw that usage away (review 2026-09-24, MINOR).
func Score ¶
func Score(produced []render.Finding, fx Fixture) FixtureScore
Score matches produced findings against a fixture's answer key using one-to-one greedy assignment (ADR-0018 §2) and returns the tally. The corpus is assumed fully annotated, so any produced finding that matches no expected finding counts as a false positive.
func (FixtureScore) IsBuggy ¶ added in v1.18.0
func (s FixtureScore) IsBuggy() bool
IsBuggy reports whether this fixture had at least one planted defect — the same "expected == 0 means clean" rule Recall/Precision already use.
func (FixtureScore) Precision ¶
func (s FixtureScore) Precision() float64
Precision = TP / (TP + FP). A run that produced no findings is vacuously precise (returns 1) so it does not divide by zero or drag an aggregate.
func (FixtureScore) Recall ¶
func (s FixtureScore) Recall() float64
Recall = TP / (TP + FN). A fixture that expects nothing (a clean diff) is fully recalled by definition (returns 1).
func (FixtureScore) SilenceViolationRate ¶ added in v1.18.0
func (s FixtureScore) SilenceViolationRate() float64
SilenceViolationRate = silence violations ÷ silence anchors. Returns 0 when the fixture defines no anchors.
type RowPricing ¶ added in v1.18.0
type RowPricing struct {
InputPer1M float64 `json:"input_per_1m"`
OutputPer1M float64 `json:"output_per_1m"`
}
RowPricing is the pricing snapshot a results row was costed against — copied from provider.Pricing rather than reusing it directly so a pricing-struct field this package doesn't emit (there are none today, but the type is provider-owned) never leaks into the results schema by accident.
type Scorecard ¶
type Scorecard struct {
Provider string
Model string
Fixtures []FixtureScore
}
Scorecard aggregates fixture scores for one provider+model run.
func RunCorpus ¶
func RunCorpus(ctx context.Context, p provider.Provider, model string, fixtures []Fixture) (Scorecard, error)
RunCorpus runs every fixture through the provider and returns a Scorecard. A fixture hitting a transient provider error (isRetriable) is retried up to corpusAttempts times with linear backoff. A fixture that still fails once retries are exhausted — or a non-transient failure on the first attempt — does not abort the run (ADR-0043 §3): it is recorded via ErrorScore (a miss for every expected finding, an alarm if the fixture is clean) and the corpus continues, so one flaky model call doesn't erase every other fixture's evidence. Only ctx cancellation (an operator-level abort, not a model error) still stops the run early.
func RunCorpusN ¶ added in v1.18.0
func RunCorpusN(ctx context.Context, p provider.Provider, model string, fixtures []Fixture, n int) ([]Scorecard, error)
RunCorpusN runs the corpus n times (COMMITBRIEF_EVAL_RUNS, ADR-0043 §3's k), returning one Scorecard per run in order. Stops and returns the error immediately if any run itself fails to complete (ctx cancellation) — per-fixture errors within a run are already absorbed by RunCorpus and never reach this level.
func (Scorecard) CategoryRecall ¶
func (sc Scorecard) CategoryRecall() []CategoryRecall
CategoryRecall returns recall per expected-finding category, sorted by category name for deterministic output.
func (Scorecard) CleanAlarms ¶ added in v1.18.0
CleanAlarms is the count of clean-control fixtures on which this run raised at least one low-or-higher finding — ADR-0043 §3's fpr numerator for a single Scorecard. Pool across k runs by summing CleanAlarms() and dividing by (runs × NClean()), not by averaging each run's own rate.
func (Scorecard) Dev ¶
Dev returns the tunable slice (fixtures the prompt/corpus may be tuned against). HeldOut returns the generalization-only slice (ADR-0018 §Goodhart). A change is overfitting when Dev recall rises but HeldOut recall does not.
func (Scorecard) Errors ¶ added in v1.18.0
Errors is the count of fixtures in the scorecard whose run errored after retries (ADR-0043 §3) — a provider failure or an unparseable response, recorded rather than aborting the corpus.
func (Scorecard) NBuggy ¶ added in v1.18.0
NBuggy is the number of fixtures in the scorecard that planted at least one defect (mirrors Recall's own "expected == 0 means clean" rule).
func (Scorecard) NClean ¶ added in v1.18.0
NClean is the number of clean-control fixtures (no planted defect) in the scorecard.
func (Scorecard) NExpected ¶ added in v1.18.0
NExpected is the total number of planted defects (expected findings) across every fixture in the scorecard.
func (Scorecard) PrecisionN ¶ added in v1.18.0
PrecisionN is Precision's denominator (TP + FP, every produced finding the run was scored against).
func (Scorecard) RecallN ¶ added in v1.18.0
RecallN is Recall's denominator (TP + FN, i.e. every planted defect the run was scored against) — the n a reported recall figure should always be printed alongside, since "87% recall" is meaningless without it.
func (Scorecard) SilenceViolationRate ¶ added in v1.18.0
SilenceViolationRate is the corpus-wide silence violations ÷ silence anchors.
func (Scorecard) SilenceViolationRateN ¶ added in v1.18.0
SilenceViolationRateN is SilenceViolationRate's denominator (total silence anchors in the scored fixtures).
func (Scorecard) TotalUsage ¶ added in v1.18.0
TotalUsage sums the provider usage reported across every fixture in the scorecard — the basis for a cost-per-review figure.
type SilenceAnchor ¶
type SilenceAnchor struct {
File string `json:"file"`
Line int `json:"line"`
Reason string `json:"reason"`
}
SilenceAnchor marks a line a good review should NOT flag. A produced finding landing on (File, ~Line) is a measured false positive (ADR-0018 §2).
type Thresholds ¶ added in v1.18.0
Thresholds mirrors D-W2-4's recall/fpr gate for ADR-0043 §1 as stored in a results file. Always populated from DefaultThresholds (ADR-0043 §2) — see its doc comment.
func DefaultThresholds ¶ added in v1.18.0
func DefaultThresholds() Thresholds
DefaultThresholds returns the ADR-0043 §2 gate every WriteResult call asserts against.