Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(eval): takes-quality re-asks a malformed judge slot once (#5325)

time-attack8a2d8a82aad5
diff --git a/docs/architecture/key-files/evaluation.md b/docs/architecture/key-files/evaluation.md
index fcbc01eff8..8b31ea02d9 100644
--- a/docs/architecture/key-files/evaluation.md
+++ b/docs/architecture/key-files/evaluation.md
@@ -30,6 +30,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/eval/ranked-docs.ts` — dependency-free page-level ranking primitive shared by the retrieval eval harness, NamedThingBench, and the qrels correctness gate. `dedupeRankedKeys()` preserves the first/best occurrence of each `${source_id}::${slug}` or slug key before any cutoff, so repeated chunks neither inflate relevance gain nor consume document ranks. Precision retains its fixed-`k` denominator; Recall and nDCG are structurally bounded to `[0,1]`. Pinned across `test/eval.test.ts`, `test/retrieval-quality-harness.test.ts`, `test/bench/qrels-file.test.ts`, and `test/bench/correctness-gate.test.ts`.
- `src/core/takes-quality-eval/pricing.ts` — budget pricing for `eval takes-quality run`. `getPricing(model, overrides?)` returns the operator rate registered with `gbrain pricing set` (`pricing.overrides`), else the canonical rate (`canonicalLookup`), else null; schema `{input_per_1m, output_per_1m}`. Every canonically priced model is gateable. Miss policy (new models must run): with no `--budget-usd` an unpriced model runs with a warning naming the registration command and its spend is not counted; under a user cap the runner refuses before any call with `no_pricing` (`unpricedUnderCapError`), whose fix is `gbrain pricing set <model> --input … --output … --source …` (no-pricing.ts). Rates are never copied here; `test/model-pricing.test.ts` pins equality with canonical for every canonical key.
+- `src/core/takes-quality-eval/runner.ts` — `eval takes-quality run` orchestrator: samples takes, sends the rendered rubric prompt to every panel model per cycle (`allowFallback: false`, `thinking: 'off'`), and re-asks each malformed slot once with the same model and sample plus the validator's error (`slotFormatFailure` in `aggregate.ts`: `parse_failed` including an empty reply, or `incomplete_scores`; provider errors and valid low scores never re-run). A correction is priced against `--budget-usd` before it is sent and recorded `corrected: null` with `skipped_reason` when it does not fit or the run was aborted; it replaces the first attempt only when it validates. The receipt carries `protocol_version: TAKES_QUALITY_PROTOCOL_VERSION` (2), `correction_selection_rule` and `corrections` (additive at `schema_version: 1`); `regress.ts` lists a protocol change among the dissimilar inputs. Pinned by `test/eval-takes-quality-runner.serial.test.ts` and `test/eval-takes-quality-regress.test.ts`.
- `src/eval/brainbench/` + `src/commands/eval-brainbench.ts` — BrainBench, the cross-harness memory conformance suite (`gbrain eval brainbench`; methodology in `docs/eval/BRAINBENCH.md`). `types.ts` carries the PUBLISHED interchange shapes (fixture/gold/result/baseline — mirrored as JSON Schemas in `evals/brainbench/schema/`; breaking changes bump the schema versions). `fixtures.ts`: strict loader/validator + corpus `fixtures_hash` (covers fixture AND gold files); a `gold` key inside a fixture turn is a validation error — gold is SEALED in the gold dir and adapters only ever see sanitized `PublicTurn`s. `seed.ts`: fail-fast hermetic seeding (`importFromContent` noEmbed + NULL-embedding `insertFact`; any non-`imported` status ⇒ `SeedError` ⇒ fixture `seed_failed` ⇒ run exit 2). `adapters/shared.ts`: ONE `runReflexPipeline` all three adapters drive with declarative config (pointer budget, suppression mode) — cross-harness comparability is structural; `openclaw.ts` (seam `production`, the shipped pipeline), `claude-code.ts` (seam `production`; drives the shipped `gbrain hook user-prompt` path end-to-end — fixture turns become `UserPromptSubmit` stdin JSON, synthesized Claude Code JSONL transcripts feed the real window parse + cross-turn dedupe, and resolution rides a run-scoped resolve-IPC server with the real shared secret; bench-pinned deviations disclosed in `docs/eval/BRAINBENCH.md`: generous `userPromptDeadlineMs`, push-failure banner suppressed), `codex.ts` (seam `contract`; static entity-index preamble whose slugs deliberately don't count as injections + ≤1 per-turn fragment; fixture conversations round-trip through the real rollout format + the shipped parser `src/core/transcripts/codex.ts` for turn selection — fragment DELIVERY remains harness-shaped until a shipped codex injection path lands). `metrics/`: know-to-ask (+false-fire anti-gaming companion), push (micro-averaged P/R), write-back (drives the PRODUCTION conversation→facts pipeline via the injectable-extractor seam; gold extractor in CI, real extractor under `--llm`), continuity (writer→reader pairs on a shared brain through DIFFERENT adapters; pointer-injection OR stored-fact keyword probe). `harness.ts`: ONE in-memory PGLite per run + `resetTables` between fixtures (longmemeval engine-sharing pattern); read-only suites share one seeding across all adapters; emits per-(harness×suite) cells + re-scoreable turn rows; `source_isolation_violations` counted per turn and gated at zero. `scoreboard.ts`: markdown render, canonical diff-stable committed baseline (4-decimal rounding, sorted keys, receipts excluded), `compareBaselines` with main-baseline governance — same-hash count-aware gate vs corpus-bless mode (the committed baseline must byte-match the run; regressions vs main require a `justification`). The CLI brings its own PGLite (cli.ts routes before connectEngine), writes `--out` as the canonical CI artifact, and terminates via an explicit grace-tick `process.exit(verdict)` (0 pass / 1 regression / 2 error) because PGLite stomps `process.exitCode` and Bun discards queued stdout on exit. `runBrainBenchCore()` is the in-process entry `eval run-all` uses (one record per sweep, `EvalRunRecord` schema_version 3, `mode: 'n/a'`). Pinned by `test/brainbench-*.test.ts` + `test/eval-brainbench-e2e.slow.test.ts`. System One arm: `--decide*` flags (`src/eval/decide-eval-flags.ts`) configure the benchmark brain; the claude-code adapter captures the turn-context `decide.recall_needed` meta onto `turn_rows[].decide`, the result gains a `decide` block, and `--update-baseline` is refused for an arm (`test/eval-brainbench-decide.serial.test.ts`).
diff --git a/docs/eval-takes-quality.md b/docs/eval-takes-quality.md
index 1725c1ee18..240741ce25 100644
--- a/docs/eval-takes-quality.md
+++ b/docs/eval-takes-quality.md
@@ -65,7 +65,12 @@ receipt file from disk and re-renders it. The other modes need the brain.
"cost_usd": 1.85,
"improvements": ["..."],
"errors": [],
- "verdictMessage": "PASS: every dim mean >=7 and min >=5 ..."
+ "verdictMessage": "PASS: every dim mean >=7 and min >=5 ...",
+ "protocol_version": 2,
+ "correction_selection_rule": "corrected_if_valid",
+ "corrections": [
+ { "cycle": 0, "modelId": "google:gemini-2.5-flash", "first_error": "incomplete_scores: missing dim(s) [accuracy]", "corrected": "valid" }
+ ]
}
```
@@ -87,6 +92,20 @@ receipt file from disk and re-renders it. The other modes need the brain.
- `verdict` — `pass` if every dim mean >= 7 AND every dim min across
contributing models >= 5; `fail` otherwise; `inconclusive` if fewer than
2/3 models contributed complete scores.
+- `protocol_version` — the eval protocol (absent on older receipts, read as
+ 1). Protocol 2 runs every judge with thinking off (so a judge-sized output
+ cap is not spent on reasoning) and re-asks a malformed slot once. `regress`
+ lists a protocol change among the dissimilar inputs.
+- `corrections` — one entry per slot whose reply was malformed: unparseable
+ (`parse_failed`, including an empty reply) or missing a dimension
+ (`incomplete_scores`). The same model gets the same sample once more with
+ the validator's error appended. `first_error` is the first attempt's
+ failure; `corrected` is `valid`, `invalid` (with `corrected_error`), or
+ `null` when the correction was not sent (`skipped_reason`: `budget` when the
+ cap could not cover it, `aborted`). Under `correction_selection_rule:
+ corrected_if_valid` a corrected reply replaces the first attempt only when
+ it validates. Provider errors and valid low scores are never re-asked.
+ Correction calls count toward `cost_usd` and the budget cap.
- `cost_usd` — sum of per-call cost via `pricing.ts` (a rate registered with
`gbrain pricing set`, else the canonical table). An unpriced model with
`--budget-usd` set refuses with `no_pricing` before any call fires; its fix
@@ -144,7 +163,7 @@ gbrain eval takes-quality regress --against .ci/takes-quality-baseline.json \
The threshold is the per-dim-mean drop counting as regression. Default 0.5.
Regress reuses the **same** model panel + slug prefix + source as the prior
receipt for an apples-to-apples compare. Diffs in `corpus_sha8` /
-`prompt_sha8` / `rubric_sha8` are surfaced as informational warnings (the
+`prompt_sha8` / `rubric_sha8` / `protocol_version` are surfaced as informational warnings (the
runner doesn't refuse — that's the caller's call).
## Contract stability
diff --git a/src/core/takes-quality-eval/aggregate.ts b/src/core/takes-quality-eval/aggregate.ts
index d86baa7cb6..677f947b3e 100644
--- a/src/core/takes-quality-eval/aggregate.ts
+++ b/src/core/takes-quality-eval/aggregate.ts
@@ -62,16 +62,26 @@ const TOP_IMPROVEMENTS_CAP = 10;
const DEDUP_PREFIX_LEN = 40;
/**
- * Returns true iff `parsed.scores` contains a finite number for every
- * declared rubric dimension. Codex review #5: missing-dim disqualifies
- * the contribution.
+ * Declared rubric dimensions without a finite score. Codex review #5: a
+ * missing dim disqualifies the contribution.
*/
-function hasAllRequiredDims(parsed: ParsedModelResult): boolean {
- for (const dim of RUBRIC_DIMENSIONS) {
- const entry = parsed.scores[dim];
- if (!entry || !Number.isFinite(entry.score)) return false;
- }
- return true;
+function missingDims(parsed: ParsedModelResult): RubricDimension[] {
+ return RUBRIC_DIMENSIONS.filter(d => {
+ const e = parsed.scores[d];
+ return !e || !Number.isFinite(e.score);
+ });
+}
+
+/**
+ * The slot's format failure (`parse_failed:` unparseable reply, or
+ * `incomplete_scores:` missing dims), or null for a valid slot or a
+ * provider error. Only format failures get a correction pass (#5325); a
+ * valid low score is never re-asked.
+ */
+export function slotFormatFailure(slot: SlotResult): string | null {
+ if (!slot.ok) return slot.error.startsWith('parse_failed:') ? slot.error : null;
+ const missing = missingDims(slot.parsed);
+ return missing.length > 0 ? `incomplete_scores: missing dim(s) [${missing.join(', ')}]` : null;
}
export function aggregate(input: AggregateInput): AggregateResult {
@@ -84,15 +94,9 @@ export function aggregate(input: AggregateInput): AggregateResult {
failed.push({ modelId: s.modelId, error: s.error });
continue;
}
- if (!hasAllRequiredDims(s.parsed)) {
- const missing = RUBRIC_DIMENSIONS.filter(d => {
- const e = s.parsed.scores[d];
- return !e || !Number.isFinite(e.score);
- });
- failed.push({
- modelId: s.modelId,
- error: `incomplete_scores: missing dim(s) [${missing.join(', ')}]`,
- });
+ const formatFailure = slotFormatFailure(s);
+ if (formatFailure) {
+ failed.push({ modelId: s.modelId, error: formatFailure });
continue;
}
contributing.push(s);
diff --git a/src/core/takes-quality-eval/receipt.ts b/src/core/takes-quality-eval/receipt.ts
index 39d1ab9a5c..6887834192 100644
--- a/src/core/takes-quality-eval/receipt.ts
+++ b/src/core/takes-quality-eval/receipt.ts
@@ -41,4 +41,30 @@ export interface TakesQualityReceipt {
errors?: Array<{ modelId: string; error: string }>;
/** One-line human verdict prose. */
verdictMessage?: string;
+ /**
+ * Eval protocol; absent means 1. Protocol 2 (#5331, #5325): judges run with
+ * thinking off, and a slot whose reply is malformed (`parse_failed` /
+ * `incomplete_scores`) is re-asked once with the same model and sample.
+ * `regress` reports a protocol change as a dissimilar input.
+ */
+ protocol_version?: number;
+ /** Protocol 2: a corrected reply replaces the first attempt only when it validates. */
+ correction_selection_rule?: 'corrected_if_valid';
+ /**
+ * Protocol 2: one entry per malformed slot. `cycle` is 0-based like
+ * `successes_per_cycle`. `first_error` is the first attempt's format
+ * failure; `corrected` is the correction's outcome, or null when it was not
+ * sent (`skipped_reason`: the budget cap could not cover it, or the run was
+ * aborted). Provider errors and valid low scores are never corrected.
+ */
+ corrections?: TakesQualityCorrection[];
+}
+
+export interface TakesQualityCorrection {
+ cycle: number;
+ modelId: string;
+ first_error: string;
+ corrected: 'valid' | 'invalid' | null;
+ corrected_error?: string;
+ skipped_reason?: 'budget' | 'aborted';
}
diff --git a/src/core/takes-quality-eval/regress.ts b/src/core/takes-quality-eval/regress.ts
index 4ec9c3c2a8..b2efd3e42d 100644
--- a/src/core/takes-quality-eval/regress.ts
+++ b/src/core/takes-quality-eval/regress.ts
@@ -25,7 +25,7 @@ export interface RegressionDelta {
threshold: number;
/** Human-readable summary line. */
summary: string;
- /** True if any 4-sha component differs between current and prior. */
+ /** True if any 4-sha component or the eval protocol differs between current and prior. */
inputs_differ: boolean;
/** Specific 4-sha diffs when inputs_differ. */
input_diffs?: string[];
@@ -56,6 +56,9 @@ export function compareReceipts(
if (current.rubric_sha8 !== prior.rubric_sha8) {
inputDiffs.push(`rubric_sha8 differs (${prior.rubric_sha8} → ${current.rubric_sha8})`);
}
+ if ((current.protocol_version ?? 1) !== (prior.protocol_version ?? 1)) {
+ inputDiffs.push(`protocol_version differs (${prior.protocol_version ?? 1} → ${current.protocol_version ?? 1})`);
+ }
const inputs_differ = inputDiffs.length > 0;
const dim_deltas: Partial<Record<RubricDimension, number>> = {};
diff --git a/src/core/takes-quality-eval/runner.ts b/src/core/takes-quality-eval/runner.ts
index cb12403b2a..b1bc7fba4b 100644
--- a/src/core/takes-quality-eval/runner.ts
+++ b/src/core/takes-quality-eval/runner.ts
@@ -2,8 +2,10 @@
* takes-quality-eval/runner — orchestrator for one `eval takes-quality run`.
*
* Three-model panel scored over a sample of takes. Each cycle dispatches
- * gateway.chat() to all 3 models in parallel via Promise.allSettled, parses
- * the JSON via the shared eval-shared/json-repair, drops models with
+ * gateway.chat() to all 3 models in parallel via Promise.allSettled (thinking
+ * off, #5331), parses the JSON via the shared eval-shared/json-repair, re-asks
+ * each malformed slot once with the same model and sample (#5325; a correction
+ * replaces the first attempt only when it validates), drops models with
* incomplete dim scores (codex review #5), aggregates, and stops early on
* PASS or INCONCLUSIVE.
*
@@ -20,7 +22,7 @@
import type { BrainEngine } from '../engine.ts';
import { chat } from '../ai/gateway.ts';
import { parseModelJSON } from '../eval-shared/json-repair.ts';
-import { aggregate, type SlotResult, type AggregateResult } from './aggregate.ts';
+import { aggregate, slotFormatFailure, type SlotResult, type AggregateResult } from './aggregate.ts';
import {
RUBRIC_VERSION,
rubricSha8,
@@ -30,7 +32,7 @@ import {
corpusSha8,
modelSetSha8,
} from './receipt-name.ts';
-import type { TakesQualityReceipt } from './receipt.ts';
+import type { TakesQualityCorrection, TakesQualityReceipt } from './receipt.ts';
import { estimateCost, getPricing, unpricedUnderCapError, unpricedWarning } from './pricing.ts';
import { loadPricingOverrides } from '../budget/budget-tracker.ts';
import { DEFAULT_CYCLES_NONTTY } from '../eval/cycle-default.ts';
@@ -43,6 +45,15 @@ import { DEFAULT_CYCLES_NONTTY } from '../eval/cycle-default.ts';
* the OpenAI recipe's chat list) sat here dead until #3510; gemini-2.0-flash
* replaced the former and was itself retired before it was ever swept.
*/
+/** Receipt `protocol_version`: thinking-off judges plus one correction per malformed slot. */
+export const TAKES_QUALITY_PROTOCOL_VERSION = 2;
+
+function correctionPrompt(prompt: string, formatFailure: string): string {
+ return `${prompt}\n\nYour previous response failed validation: ${formatFailure}\n` +
+ 'Return a complete replacement in the requested JSON shape, with a score for every dimension. ' +
+ 'Do not invent scores when evidence is insufficient.';
+}
+
export const DEFAULT_MODEL_PANEL = [
'openai:gpt-5.2',
'anthropic:claude-opus-4-7',
@@ -194,6 +205,7 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<
let cumulativeCost = 0;
let budgetAborted = false;
let lastAggregate: AggregateResult | null = null;
+ const corrections: TakesQualityCorrection[] = [];
for (let cycle = 0; cycle < cycles; cycle++) {
if (opts.abortSignal?.aborted) {
@@ -237,6 +249,29 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<
slots.push({ ok: false, modelId: m, error: `allSettled_rejected: ${String(s.reason)}` });
}
}
+ // #5325: one same-model correction per malformed slot, priced against the
+ // cap before it is sent. Provider errors and valid low scores never re-run.
+ for (let i = 0; i < slots.length; i++) {
+ const firstError = slotFormatFailure(slots[i]!);
+ if (!firstError) continue;
+ const m = models[i]!;
+ const skipped = opts.abortSignal?.aborted ? 'aborted'
+ : budgetUsd !== null && cumulativeCost + (estimateCost(m, 5000, 2000, overrides) ?? 0) > budgetUsd ? 'budget'
+ : null;
+ if (skipped) {
+ corrections.push({ cycle, modelId: m, first_error: firstError, corrected: null, skipped_reason: skipped });
+ continue;
+ }
+ const retry = await callOneModel(m, correctionPrompt(prompt, firstError), opts.abortSignal);
+ if (retry._usage) cumulativeCost += estimateCost(m, retry._usage.input_tokens, retry._usage.output_tokens, overrides) ?? 0;
+ const retryError = retry.ok ? slotFormatFailure(retry) : retry.error;
+ corrections.push({
+ cycle, modelId: m, first_error: firstError,
+ corrected: retryError === null ? 'valid' : 'invalid',
+ ...(retryError !== null ? { corrected_error: retryError } : {}),
+ });
+ if (retryError === null) slots[i] = retry;
+ }
const agg = aggregate({ slots });
lastAggregate = agg;
successes_per_cycle.push(agg.successes);
@@ -275,6 +310,9 @@ export async function runEval(engine: BrainEngine, opts: RunOpts = {}): Promise<
improvements: lastAggregate.topImprovements,
errors: lastAggregate.errors,
verdictMessage: lastAggregate.verdictMessage,
+ protocol_version: TAKES_QUALITY_PROTOCOL_VERSION,
+ correction_selection_rule: 'corrected_if_valid',
+ ...(corrections.length > 0 ? { corrections } : {}),
};
return { receipt, budgetAborted };
diff --git a/test/eval-takes-quality-regress.test.ts b/test/eval-takes-quality-regress.test.ts
index 04cc6dbce8..cd52d554db 100644
--- a/test/eval-takes-quality-regress.test.ts
+++ b/test/eval-takes-quality-regress.test.ts
@@ -114,3 +114,19 @@ describe('compareReceipts — input drift detection', () => {
expect(d.inputs_differ).toBe(true);
});
});
+
+describe('compareReceipts — eval protocol (#5325)', () => {
+ test('a protocol 2 run against a pre-protocol receipt is a dissimilar input', () => {
+ const prior = receipt({});
+ const current = { ...receipt({}), protocol_version: 2 };
+ const d = compareReceipts(current, prior);
+ expect(d.inputs_differ).toBe(true);
+ expect(d.input_diffs).toEqual(['protocol_version differs (1 → 2)']);
+ expect(d.regressed).toBe(false);
+ });
+
+ test('two protocol 2 receipts compare as similar inputs', () => {
+ const r = { ...receipt({}), protocol_version: 2 };
+ expect(compareReceipts(r, r).inputs_differ).toBe(false);
+ });
+});
diff --git a/test/eval-takes-quality-runner.serial.test.ts b/test/eval-takes-quality-runner.serial.test.ts
index f356ca8337..c7f1e70029 100644
--- a/test/eval-takes-quality-runner.serial.test.ts
+++ b/test/eval-takes-quality-runner.serial.test.ts
@@ -274,3 +274,97 @@ describe('runner — pricing gate (new models must run)', () => {
}
});
});
+
+describe('runner — malformed-slot correction pass (#5325, protocol 2)', () => {
+ const PANEL = ['openai:gpt-5.2', 'anthropic:claude-opus-4-7'];
+ const reply = (text: string, outputTokens = 50) => ({
+ text, blocks: [], stopReason: 'end',
+ usage: { input_tokens: 100, output_tokens: outputTokens, cache_read_tokens: 0, cache_creation_tokens: 0 },
+ model: 'stub', providerId: 'stub',
+ });
+ function missingAccuracy(): string {
+ const parsed = JSON.parse(fullScoreJson(8));
+ delete parsed.scores[RUBRIC_DIMENSIONS[0]];
+ return JSON.stringify(parsed);
+ }
+
+ test('a slot missing a dimension is re-asked once with the validator error and the run reaches a verdict', async () => {
+ const calls: Array<{ model: string; prompt: string; thinking?: string }> = [];
+ chatHandler = async (opts) => {
+ calls.push({ model: opts.model, prompt: opts.messages[0].content, thinking: opts.thinking });
+ const second = opts.model === PANEL[1];
+ const isCorrection = String(opts.messages[0].content).includes('failed validation');
+ return reply(second && !isCorrection ? missingAccuracy() : fullScoreJson(8));
+ };
+
+ const r = await runEval(engine, { limit: 5, cycles: 1, models: PANEL, budgetUsd: null });
+
+ expect(calls).toHaveLength(3);
+ expect(calls[2]!.model).toBe(PANEL[1]);
+ expect(calls[2]!.prompt).toContain(`incomplete_scores: missing dim(s) [${RUBRIC_DIMENSIONS[0]}]`);
+ expect(calls.every(c => c.thinking === 'off')).toBe(true);
+ expect(r.receipt.verdict).toBe('pass');
+ expect(r.receipt.successes_per_cycle).toEqual([2]);
+ expect(r.receipt.protocol_version).toBe(2);
+ expect(r.receipt.correction_selection_rule).toBe('corrected_if_valid');
+ expect(r.receipt.corrections).toEqual([{
+ cycle: 0, modelId: PANEL[1], first_error: `incomplete_scores: missing dim(s) [${RUBRIC_DIMENSIONS[0]}]`, corrected: 'valid',
+ }]);
+ });
+
+ test('an empty reply (the output cap spent on reasoning) is a format failure and gets the correction', async () => {
+ let n = 0;
+ chatHandler = async (opts) => {
+ n++;
+ if (opts.model === PANEL[0] && n === 1) return { ...reply('', 2000), stopReason: 'length' };
+ return reply(fullScoreJson(8));
+ };
+
+ const r = await runEval(engine, { limit: 5, cycles: 1, models: PANEL, budgetUsd: null });
+
+ expect(r.receipt.corrections?.[0]).toMatchObject({ modelId: PANEL[0], corrected: 'valid' });
+ expect(r.receipt.corrections?.[0]!.first_error).toStartWith('parse_failed:');
+ expect(r.receipt.verdict).toBe('pass');
+ });
+
+ test('a correction that is still malformed keeps the first failure and records both', async () => {
+ chatHandler = async (opts) => reply(opts.model === PANEL[1] ? 'no json here' : fullScoreJson(8));
+
+ const r = await runEval(engine, { limit: 5, cycles: 1, models: PANEL, budgetUsd: null });
+
+ expect(r.receipt.verdict).toBe('inconclusive');
+ expect(r.receipt.corrections).toHaveLength(1);
+ expect(r.receipt.corrections![0]).toMatchObject({ corrected: 'invalid' });
+ expect(r.receipt.corrections![0]!.corrected_error).toStartWith('parse_failed:');
+ expect(r.receipt.errors?.[0]?.error).toBe(r.receipt.corrections![0]!.first_error);
+ });
+
+ test('valid low scores and provider errors are never re-asked', async () => {
+ const calls: string[] = [];
+ chatHandler = async (opts) => {
+ calls.push(opts.model);
+ if (opts.model === PANEL[1]) throw new Error('synthetic provider error');
+ return reply(fullScoreJson(3));
+ };
+
+ const r = await runEval(engine, { limit: 5, cycles: 1, models: PANEL, budgetUsd: null });
+
+ expect(calls).toEqual(PANEL);
+ expect(r.receipt.corrections).toBeUndefined();
+ });
+
+ test('a correction the budget cap cannot cover is not sent and is recorded with corrected: null', async () => {
+ const calls: string[] = [];
+ chatHandler = async (opts) => {
+ calls.push(opts.model);
+ return reply(opts.model === PANEL[1] ? missingAccuracy() : fullScoreJson(8), 60_000);
+ };
+
+ const r = await runEval(engine, { limit: 5, cycles: 1, models: PANEL, budgetUsd: 0.5 });
+
+ expect(calls).toEqual(PANEL);
+ expect(r.receipt.corrections).toEqual([{
+ cycle: 0, modelId: PANEL[1], first_error: `incomplete_scores: missing dim(s) [${RUBRIC_DIMENSIONS[0]}]`, corrected: null, skipped_reason: 'budget',
+ }]);
+ });
+});