ruby_llm-contract 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/CHANGELOG.md CHANGED
@@ -1,16 +1,49 @@
1
1
  # Changelog
2
2
 
3
- ## 1.0.0 (2026-09-27)
3
+ ## 1.1.0 (2026-10-10)
4
+
5
+ ### Changed - may turn a green CI red
6
+
7
+ - **Eval cost gates now fail closed on unknown pricing.** `pass_eval(...).with_maximum_cost`,
8
+ `RakeTask#maximum_cost` and `assert_eval_passes(maximum_cost:)` compared the report's
9
+ `total_cost`, which counts a case it cannot price as $0. An eval running on a model
10
+ without pricing data (a local or fine-tuned model) therefore passed any budget. The
11
+ gates now fail and name the unpriced cases, matching what step-level `max_cost`
12
+ already did. Opt out with `.on_unknown_pricing(:warn)`, `t.on_unknown_pricing = :warn`
13
+ or `on_unknown_pricing: :warn`: the budget is then checked against the priced cases
14
+ and a warning lists the rest. Offline runs (`sample_response`, a `Test` adapter
15
+ without `usage:`) report zero tokens and are never flagged. Only gates with a
16
+ maximum cost set are affected.
17
+
18
+ ### Added
19
+
20
+ - `Report#unknown_cost_results` (also on `AggregatedReport`), `CaseResult#cost_unknown?`,
21
+ and `cost_unknown?` on step and pipeline traces. A retried step is judged per attempt,
22
+ so a priced subtotal no longer hides an unpriced attempt. `CaseResult#to_h` gains a
23
+ `cost_unknown: true` key only for flagged cases; baseline files are unchanged.
24
+
25
+ ### Fixed
26
+
27
+ - **A previously passing case that was skipped (no adapter) is reported as `SKIPPED`,
28
+ not `REGRESSED`.** The regression gate still fails on it - a skip is no evidence the
29
+ case still passes - but the report no longer showed an unchanged score next to a
30
+ "regression". Applies to `BaselineDiff#to_s` (rake task output) and the
31
+ `without_regressions` failure message; new `BaselineDiff#skipped_passing_cases`.
32
+ - A code comment in `CostCalculator` claimed an unreadable pricing shape refuses budgeted
33
+ calls "with no error"; the refusal does carry an error, it just names missing pricing
34
+ as the cause.
35
+
36
+ ## 1.0.0 (2026-10-10)
4
37
 
5
38
  **Requires `ruby_llm ~> 2.0`.** This is the only breaking change: it is a
6
39
  dependency requirement, not a change to this gem's API. Your call sites,
7
40
  `output_schema` blocks, `trace[:usage]` keys and adapter interface are all
8
- untouched — if you are on ruby_llm 2.x, upgrading should need no code edits.
41
+ untouched - if you are on ruby_llm 2.x, upgrading should need no code edits.
9
42
 
10
43
  1.0 also states what is now stable: the documented DSL, the `Result`/`trace`
11
44
  shapes including `trace[:usage]`'s `{ input_tokens:, output_tokens: }` keys, and
12
45
  the adapter interface. A future major version of a runtime dependency may again
13
- require a major version here — that is what this release is.
46
+ require a major version here - that is what this release is.
14
47
 
15
48
  ### Added
16
49
 
@@ -36,7 +69,7 @@ require a major version here — that is what this release is.
36
69
  - **`ruby_llm-schema` replaced by `schematist ~> 1.1`.** `ruby_llm-schema` 1.0.0 is
37
70
  31 lines that emit a deprecation warning and alias `RubyLLM::Schema =
38
71
  Schematist::Schema`; ruby_llm 2.x depends on schematist directly. The
39
- `output_schema do ... end` DSL is unchanged — same object behind a different
72
+ `output_schema do ... end` DSL is unchanged - same object behind a different
40
73
  constant.
41
74
  - **Adapter reads token counts from `Message#tokens`.** RubyLLM 2.0 replaced
42
75
  `Message#input_tokens`/`#output_tokens` with a `Tokens` value object. This is the
@@ -71,7 +104,7 @@ require a major version here — that is what this release is.
71
104
  `input_price_per_million` / `output_price_per_million` readers on `Model` for a
72
105
  nested `pricing -> text_tokens -> standard` walk. Because `CostCalculator`
73
106
  rescued `StandardError` into a nil cost, every priced model silently became
74
- "unknown pricing" — and since `max_cost` fails closed on unknown pricing, every
107
+ "unknown pricing" - and since `max_cost` fails closed on unknown pricing, every
75
108
  budgeted call would have been refused. Pricing extraction is now explicit for
76
109
  both shapes (upstream models and locally `register_model`-ed ones), and an
77
110
  unrecognised shape returns nil rather than a swallowed exception.
@@ -91,33 +124,33 @@ Result of a 20-pass systematic audit of the whole repository. No API changes and
91
124
 
92
125
  ### Changed
93
126
 
94
- - **The published gem no longer ships development-only files.** Measured by building the gem and unpacking it: `.rubocop.yml`, `Gemfile`, `Gemfile.lock` and `Rakefile` were being packaged, contradicting the gemspec's own stated policy ("dev configs excluded so the published gem contains only what adopters actually need at runtime"). The shipped `Rakefile` was unusable anyway — it `require`s rspec, which is not a runtime dependency, and defines a task over `spec/`, which the same build excludes. Package contents: **137 → 133 files**; `lib/` (105) and `docs/` (16) unchanged.
127
+ - **The published gem no longer ships development-only files.** Measured by building the gem and unpacking it: `.rubocop.yml`, `Gemfile`, `Gemfile.lock` and `Rakefile` were being packaged, contradicting the gemspec's own stated policy ("dev configs excluded so the published gem contains only what adopters actually need at runtime"). The shipped `Rakefile` was unusable anyway - it `require`s rspec, which is not a runtime dependency, and defines a task over `spec/`, which the same build excludes. Package contents: **137 → 133 files**; `lib/` (105) and `docs/` (16) unchanged.
95
128
  - **`Gemfile.lock` is no longer tracked.** It was in the index despite being matched by `.gitignore:10`, and was repacked on every release. A library should not pin its adopters' dependency versions.
96
- - **The RubyGems page will now show a "Source Code" link.** `metadata["homepage_uri"]` duplicated `spec.homepage` and, being listed first, suppressed `source_code_uri` in the UI — `gem build` warned about this on every build. Dropped the duplicate; `source_code_uri` stays, because `bundle info` and the RubyGems API read it as a distinct field.
129
+ - **The RubyGems page will now show a "Source Code" link.** `metadata["homepage_uri"]` duplicated `spec.homepage` and, being listed first, suppressed `source_code_uri` in the UI - `gem build` warned about this on every build. Dropped the duplicate; `source_code_uri` stays, because `bundle info` and the RubyGems API read it as a distinct field.
97
130
 
98
131
  ### Fixed
99
132
 
100
- - **`.rubocop.yml` declared `AllCops` twice.** Psych applies last-key-wins, so `TargetRubyVersion: 3.2`, `NewCops: enable` and `SuggestExtensions: false` were silently discarded, and the second block's `Exclude` **replaced** RuboCop's defaults instead of adding to them. Effect: the linter scanned 353 files / 2423 offences, 147 of those files untracked under `tmp/` (they carried 2155 of the offences). Merging the blocks alone does not fix it — `inherit_mode: merge` is what restores the defaults. Now 206 files / 300 offences, all pre-existing formatting on real code. (Both counts measured with rubocop 1.88.0; `Gemfile.lock` is no longer tracked, so pin the tool when reproducing.)
101
- - **`docs/guide/multimodal_input.md` linked to a file that could never resolve** — `../decisions/ADR-0022-*.md` points at `docs/decisions/` (no such directory; the ADR lives in `doc/decisions/`, singular) and that path is gitignored. Since `docs/guide/*` is packaged, this reproduced exactly the "links 404'd locally" defect that 0.10.2 set out to fix. Same dangling reference removed from the 0.9.0 CHANGELOG entry.
102
- - **Two documented rake-task environment variables never existed.** `REASONING_EFFORT=` and `OLLAMA_API_BASE=` were listed in the 0.5.0 CHANGELOG entry, but `git log --all -S<name> -- lib/` is empty for both — they were never read at any point in the project's history, and ruby_llm's own configuration only seeds `RUBYLLM_DEBUG` / `RUBYLLM_STREAM_DEBUG` from the environment. Setting either was a silent no-op. Reasoning effort is selected with `CANDIDATES=model@effort`; Ollama's base URL goes through `RubyLLM.configure`.
103
- - **README stated the wrong current version** (0.10.4 while `version.rb` was 0.10.6) — the one sentence that has to change every release.
133
+ - **`.rubocop.yml` declared `AllCops` twice.** Psych applies last-key-wins, so `TargetRubyVersion: 3.2`, `NewCops: enable` and `SuggestExtensions: false` were silently discarded, and the second block's `Exclude` **replaced** RuboCop's defaults instead of adding to them. Effect: the linter scanned 353 files / 2423 offences, 147 of those files untracked under `tmp/` (they carried 2155 of the offences). Merging the blocks alone does not fix it - `inherit_mode: merge` is what restores the defaults. Now 206 files / 300 offences, all pre-existing formatting on real code. (Both counts measured with rubocop 1.88.0; `Gemfile.lock` is no longer tracked, so pin the tool when reproducing.)
134
+ - **`docs/guide/multimodal_input.md` linked to a file that could never resolve** - `../decisions/ADR-0022-*.md` points at `docs/decisions/` (no such directory; the ADR lives in `doc/decisions/`, singular) and that path is gitignored. Since `docs/guide/*` is packaged, this reproduced exactly the "links 404'd locally" defect that 0.10.2 set out to fix. Same dangling reference removed from the 0.9.0 CHANGELOG entry.
135
+ - **Two documented rake-task environment variables never existed.** `REASONING_EFFORT=` and `OLLAMA_API_BASE=` were listed in the 0.5.0 CHANGELOG entry, but `git log --all -S<name> -- lib/` is empty for both - they were never read at any point in the project's history, and ruby_llm's own configuration only seeds `RUBYLLM_DEBUG` / `RUBYLLM_STREAM_DEBUG` from the environment. Setting either was a silent no-op. Reasoning effort is selected with `CANDIDATES=model@effort`; Ollama's base URL goes through `RubyLLM.configure`.
136
+ - **README stated the wrong current version** (0.10.4 while `version.rb` was 0.10.6) - the one sentence that has to change every release.
104
137
  - **`examples/README.md` claimed every example carries an "Expected output" section**; four of seven do, for three different reasons, so the sentence was the error rather than the files.
105
- - **`docs/architecture.md` was reachable from nowhere** — the only one of 16 tracked docs with no inbound link. Added to the README index.
138
+ - **`docs/architecture.md` was reachable from nowhere** - the only one of 16 tracked docs with no inbound link. Added to the README index.
106
139
 
107
140
  ### Removed
108
141
 
109
142
  - Dead code with a full evidence battery behind each cut: `SchemaValidator::Node#numeric?` (zero readers; the one place needing the check inlines `value.is_a?(Numeric)`), an abandoned twin test helper whose sibling has 14 call sites, three unused `let`/helper definitions, four useless assignments, seven redundant `require`s in specs, and a `SimpleCov.start` that was a measured no-op because `require "simplecov"` already autoloads `.simplecov`.
110
- - 31 WHAT comment blocks (51 lines) in `lib/` plus 20 comment lines in `spec/`, all restating the line or class below them - including all six `Extracted from ...` comments, five of them the "to reduce class length" boilerplate (refactor history git already records) and ten one-line class docstrings paraphrasing their own class name. WHY comments — invariants, external-behaviour notes, anti-duplication markers — were deliberately kept; so were the three evaluator banners that name a comparison semantic the class name cannot convey.
143
+ - 31 WHAT comment blocks (51 lines) in `lib/` plus 20 comment lines in `spec/`, all restating the line or class below them - including all six `Extracted from ...` comments, five of them the "to reduce class length" boilerplate (refactor history git already records) and ten one-line class docstrings paraphrasing their own class name. WHY comments - invariants, external-behaviour notes, anti-duplication markers - were deliberately kept; so were the three evaluator banners that name a comparison semantic the class name cannot convey.
111
144
  - Private-project residue: a spec block still labelled "reddit promo planner shape" although that project was removed as private in #25, and four dangling `(Batch N / TODO)` references to a `TODO.md` deleted in 0.10.1.
112
145
 
113
146
  ## 0.10.6 (2026-06-11)
114
147
 
115
- Docs accuracy patch: correct the positioning of `llm_judge.md` against `ruby_llm-tribunal` after a deeper audit of Tribunal's documented scope. The previous wording ("you are reinventing what `ruby_llm-tribunal` ships as a built-in catalog") read as if Tribunal made `llm_judge.md` redundant — incorrect. Tribunal's README ships an off-the-shelf implementation catalog (`assert_faithful`, `assert_hallucination`, `assert_refusal`, `assert_no_pii`, etc.) but does **not** document calibration workflow, per-claim breakdown, judge-prompt iteration, or judge-as-`evaluator:` integration — exactly the methodology `llm_judge.md` covers. The two are complementary layers, not alternatives. No code behaviour change.
148
+ Docs accuracy patch: correct the positioning of `llm_judge.md` against `ruby_llm-tribunal` after a deeper audit of Tribunal's documented scope. The previous wording ("you are reinventing what `ruby_llm-tribunal` ships as a built-in catalog") read as if Tribunal made `llm_judge.md` redundant - incorrect. Tribunal's README ships an off-the-shelf implementation catalog (`assert_faithful`, `assert_hallucination`, `assert_refusal`, `assert_no_pii`, etc.) but does **not** document calibration workflow, per-claim breakdown, judge-prompt iteration, or judge-as-`evaluator:` integration - exactly the methodology `llm_judge.md` covers. The two are complementary layers, not alternatives. No code behaviour change.
116
149
 
117
150
  ### Fixed
118
151
 
119
- - **`docs/guide/relation_to_tribunal.md`** — added the **"Tribunal's catalog vs Contract's `llm_judge.md` — concrete decision tree"** sub-section under "When to use which", giving adopters a sharp three-way fork: reach for Tribunal's catalog when the check is domain-general (faithfulness vs context, hallucination, refusal, PII, jailbreak, toxicity, bias); build a custom judge per `llm_judge.md` when the criterion is domain-specific, when the judge needs to live inside a `define_eval` regression gate as the `evaluator:` lambda, when per-claim sentence-level debug output is required, or when the judge prompt itself needs to be iterated against your data; use both for the same project at different lifecycle stages (Tribunal at spec-time, calibrated custom judge at CI merge gate). Added the **"What Tribunal documents — and what it doesn't"** sub-section with a five-row comparison table making explicit which methodology gaps `llm_judge.md` covers that Tribunal's README leaves to the adopter (calibration against humans, prompt iteration on over-flag, per-claim breakdown, evaluator-lambda integration, the six anti-patterns).
120
- - **`docs/guide/llm_judge.md`** — rewrote the closing "When to escalate to Tribunal's catalog" section as **"When to reach for Tribunal instead"**: shorter, accurate (Tribunal is a complementary catalog, not a replacement), points to `relation_to_tribunal.md` for the full decision tree and integration patterns. The previous wording implied that building any of the four standard judges (faithful / hallucination / refusal / PII) was "reinvention" — true for the **implementation** (Tribunal ships them), false for the **methodology** (Tribunal's README doesn't document calibration, anti-patterns, or per-claim breakdown). The methodology applies equally to Tribunal's built-ins, Tribunal's custom registered judges, and Contract `Step::Base` judges.
152
+ - **`docs/guide/relation_to_tribunal.md`** - added the **"Tribunal's catalog vs Contract's `llm_judge.md` - concrete decision tree"** sub-section under "When to use which", giving adopters a sharp three-way fork: reach for Tribunal's catalog when the check is domain-general (faithfulness vs context, hallucination, refusal, PII, jailbreak, toxicity, bias); build a custom judge per `llm_judge.md` when the criterion is domain-specific, when the judge needs to live inside a `define_eval` regression gate as the `evaluator:` lambda, when per-claim sentence-level debug output is required, or when the judge prompt itself needs to be iterated against your data; use both for the same project at different lifecycle stages (Tribunal at spec-time, calibrated custom judge at CI merge gate). Added the **"What Tribunal documents - and what it doesn't"** sub-section with a five-row comparison table making explicit which methodology gaps `llm_judge.md` covers that Tribunal's README leaves to the adopter (calibration against humans, prompt iteration on over-flag, per-claim breakdown, evaluator-lambda integration, the six anti-patterns).
153
+ - **`docs/guide/llm_judge.md`** - rewrote the closing "When to escalate to Tribunal's catalog" section as **"When to reach for Tribunal instead"**: shorter, accurate (Tribunal is a complementary catalog, not a replacement), points to `relation_to_tribunal.md` for the full decision tree and integration patterns. The previous wording implied that building any of the four standard judges (faithful / hallucination / refusal / PII) was "reinvention" - true for the **implementation** (Tribunal ships them), false for the **methodology** (Tribunal's README doesn't document calibration, anti-patterns, or per-claim breakdown). The methodology applies equally to Tribunal's built-ins, Tribunal's custom registered judges, and Contract `Step::Base` judges.
121
154
 
122
155
  ## 0.10.5 (2026-06-11)
123
156
 
@@ -125,21 +158,21 @@ Docs release: new `llm_judge.md` guide + comprehensive clarity audit across all
125
158
 
126
159
  ### Added
127
160
 
128
- - **`docs/guide/llm_judge.md`** — new guide for the LLM-as-judge pattern. Three-step workflow (build judge as a Contract Step → calibrate against humans on real production data → use as eval gate). Hook is the Cursor "Sam" April 2025 incident (support chatbot hallucinated company policy, schema valid, brand damage). Covers claims-breakdown alternative output schema, the "calibration is itself iterative" failure mode (over-flagging stylistic courtesy), six anti-patterns (stubbing the judge, calibrating on synthetic data, per-language regex, judge on request path, proxy label assertion, calibrating once and shipping), and an escalation pointer to `ruby_llm-tribunal`'s catalog. 206 lines. Linked from `eval_first.md` (oracle-validation rule) and `relation_to_tribunal.md` (composition recipe). Cited research: Eugene Yan on evals, Hamel Husain field guide, May 2025 LLM-hallucination court-case database, Klarna AI customer-service reversal.
161
+ - **`docs/guide/llm_judge.md`** - new guide for the LLM-as-judge pattern. Three-step workflow (build judge as a Contract Step → calibrate against humans on real production data → use as eval gate). Hook is the Cursor "Sam" April 2025 incident (support chatbot hallucinated company policy, schema valid, brand damage). Covers claims-breakdown alternative output schema, the "calibration is itself iterative" failure mode (over-flagging stylistic courtesy), six anti-patterns (stubbing the judge, calibrating on synthetic data, per-language regex, judge on request path, proxy label assertion, calibrating once and shipping), and an escalation pointer to `ruby_llm-tribunal`'s catalog. 206 lines. Linked from `eval_first.md` (oracle-validation rule) and `relation_to_tribunal.md` (composition recipe). Cited research: Eugene Yan on evals, Hamel Husain field guide, May 2025 LLM-hallucination court-case database, Klarna AI customer-service reversal.
129
162
 
130
163
  ### Fixed
131
164
 
132
- - **`docs/guide/migration.md` — `save_baseline = false` in CI Rakefile.** Pre-0.10.5 the migration template set `save_baseline = true`, which dirties the working checkout on every CI run and races the regression check — directly violating the project invariant ("`save_baseline: true` in CI dirties checkout and races the regression check — keep it false; refresh in a separate job"). Adopters copy-pasting the template hit non-deterministic CI failures + git status noise. The corrected template now sets `false` with an inline comment explaining the baseline-refresh-in-separate-workflow rationale.
133
- - **`docs/guide/relation_to_tribunal.md` — evaluator lambda arity corrected from 3 to 1.** The example previously used `->(output, _expected, _input)`, but `ProcEvaluator` only accepts arity 1 or 2 — adopters copy-pasting hit `ArgumentError: wrong number of arguments`. Now reads `->(output)`.
134
- - **`docs/guide/eval_first.md`** — added explicit definition of "partial match" (`expected:` is treated as a subset of `parsed_output`; extra output keys ignored, listed keys must equal), added definition of `adapter` (the layer that actually executes the LLM call), clarified `system`/`rule`/`example`/`validate` as prompt-shaping building blocks with a `prompt_ast.md` link.
135
- - **`docs/guide/getting_started.md`** — explained the `{X}` prompt template syntax (gem-specific, not ERB, not `String#%`), described `validate(...) { |o, _| ... }` arity convention, named the retry triggers `:validation_failed` / `:parse_error`, differentiated `default_input` from `add_case input:`, explained partial-match semantics.
136
- - **`README.md`** — three clarity edits to the SummarizeArticle example: `{input}` placeholder syntax explained, `validate` lambda args (`|o, _|`) explained, `retry_policy do escalate(...) end` block form aliased to `retry_policy models: %w[...]` shorthand (both forms share the same DSL — `models` is an alias for `escalate`). Plus the multimodal upgrade FAQ entry was compressed from 7 sentences to a 2-sentence SEO pointer to `multimodal_input.md` (where the full `attachment_token_estimate` setup, fail-closed behaviour, and `on_unknown_attachment_size :warn` opt-out already lived canonically) — reduces README cognitive load for the 90% of adopters not upgrading from pre-0.10.0.
137
- - **`docs/guide/testing.md`** — clarified pipeline test responses (`responses: { :summarize, :tag, :card }` keys must match `add_step :name, ...` identifiers), distinguished `validate` block (Step-level) from `verify` block (eval-case evaluator declared via `verify(name) { |output| ... }` inside `define_eval`), explained `stub_all_steps(response: { ... })` shape semantics.
138
- - **`docs/guide/best_practices.md`** — explained `rule` as a prompt DSL element distinct from `system` / `user` with a link to `prompt_ast.md`.
139
- - **`docs/guide/optimizing_retry_policy.md`** — explained `gpt-4.1-mini@low` CLI shorthand for `{model:, reasoning_effort:}`, defined `production_mode: { fallback: ... }` as an optional `compare_models` kwarg that reports effective cost (first-try + weighted fallback) instead of first-attempt only, compressed the "two orthogonal dimensions" callout from 7 concepts to 3 (DSL alias details moved to the dedicated `thinking` DSL note at the end).
140
- - **`docs/guide/output_schema.md`** — compressed the `RubyLLM::Agent.schema` boundary callout from 6 concepts to 3 + pointer (full Agent-vs-Step comparison lives canonically in `relation_to_agent.md`).
141
- - **`docs/guide/pipeline.md`** — documented that `Pipeline.run_eval` matches **only** the final step's output against `expected:` (assertions on intermediate-step outputs silently never match — gem-level invariant).
142
- - **`docs/guide/prompt_ast.md`** — explained `Types::Hash.schema(...)` typed-input declaration as distinct from plain `input_type Hash` (typed form raises `TypeError` on missing/wrong-type keys; plain form accepts any hash).
165
+ - **`docs/guide/migration.md` - `save_baseline = false` in CI Rakefile.** Pre-0.10.5 the migration template set `save_baseline = true`, which dirties the working checkout on every CI run and races the regression check - directly violating the project invariant ("`save_baseline: true` in CI dirties checkout and races the regression check - keep it false; refresh in a separate job"). Adopters copy-pasting the template hit non-deterministic CI failures + git status noise. The corrected template now sets `false` with an inline comment explaining the baseline-refresh-in-separate-workflow rationale.
166
+ - **`docs/guide/relation_to_tribunal.md` - evaluator lambda arity corrected from 3 to 1.** The example previously used `->(output, _expected, _input)`, but `ProcEvaluator` only accepts arity 1 or 2 - adopters copy-pasting hit `ArgumentError: wrong number of arguments`. Now reads `->(output)`.
167
+ - **`docs/guide/eval_first.md`** - added explicit definition of "partial match" (`expected:` is treated as a subset of `parsed_output`; extra output keys ignored, listed keys must equal), added definition of `adapter` (the layer that actually executes the LLM call), clarified `system`/`rule`/`example`/`validate` as prompt-shaping building blocks with a `prompt_ast.md` link.
168
+ - **`docs/guide/getting_started.md`** - explained the `{X}` prompt template syntax (gem-specific, not ERB, not `String#%`), described `validate(...) { |o, _| ... }` arity convention, named the retry triggers `:validation_failed` / `:parse_error`, differentiated `default_input` from `add_case input:`, explained partial-match semantics.
169
+ - **`README.md`** - three clarity edits to the SummarizeArticle example: `{input}` placeholder syntax explained, `validate` lambda args (`|o, _|`) explained, `retry_policy do escalate(...) end` block form aliased to `retry_policy models: %w[...]` shorthand (both forms share the same DSL - `models` is an alias for `escalate`). Plus the multimodal upgrade FAQ entry was compressed from 7 sentences to a 2-sentence SEO pointer to `multimodal_input.md` (where the full `attachment_token_estimate` setup, fail-closed behaviour, and `on_unknown_attachment_size :warn` opt-out already lived canonically) - reduces README cognitive load for the 90% of adopters not upgrading from pre-0.10.0.
170
+ - **`docs/guide/testing.md`** - clarified pipeline test responses (`responses: { :summarize, :tag, :card }` keys must match `add_step :name, ...` identifiers), distinguished `validate` block (Step-level) from `verify` block (eval-case evaluator declared via `verify(name) { |output| ... }` inside `define_eval`), explained `stub_all_steps(response: { ... })` shape semantics.
171
+ - **`docs/guide/best_practices.md`** - explained `rule` as a prompt DSL element distinct from `system` / `user` with a link to `prompt_ast.md`.
172
+ - **`docs/guide/optimizing_retry_policy.md`** - explained `gpt-4.1-mini@low` CLI shorthand for `{model:, reasoning_effort:}`, defined `production_mode: { fallback: ... }` as an optional `compare_models` kwarg that reports effective cost (first-try + weighted fallback) instead of first-attempt only, compressed the "two orthogonal dimensions" callout from 7 concepts to 3 (DSL alias details moved to the dedicated `thinking` DSL note at the end).
173
+ - **`docs/guide/output_schema.md`** - compressed the `RubyLLM::Agent.schema` boundary callout from 6 concepts to 3 + pointer (full Agent-vs-Step comparison lives canonically in `relation_to_agent.md`).
174
+ - **`docs/guide/pipeline.md`** - documented that `Pipeline.run_eval` matches **only** the final step's output against `expected:` (assertions on intermediate-step outputs silently never match - gem-level invariant).
175
+ - **`docs/guide/prompt_ast.md`** - explained `Types::Hash.schema(...)` typed-input declaration as distinct from plain `input_type Hash` (typed form raises `TypeError` on missing/wrong-type keys; plain form accepts any hash).
143
176
 
144
177
  ### Audit method
145
178
 
@@ -151,23 +184,23 @@ Patch release: the `ruby_llm_contract:optimize` rake task now auto-loads in Rail
151
184
 
152
185
  ### Fixed
153
186
 
154
- - **`ruby_llm_contract:optimize` no longer requires manual `require "ruby_llm/contract/rake_task"` in Rails apps.** Pre-0.10.4 the docs claimed the task was "included" with `RubyLLM::Contract::RakeTask`, but the railtie did not load the file — adopters running `bin/rails ruby_llm_contract:optimize` got `Unrecognized command` until they added the require to `Rakefile` or `lib/tasks/*.rake`. The railtie now uses the standard `rake_tasks { require "..." }` idiom, lazy-loading the file only when `rake` is invoked (no boot cost).
155
- - **Docs corrected** in `docs/guide/optimizing_retry_policy.md` — the "rake task is included" line now explicitly states it auto-loads on 0.10.4+ in Rails, and that non-Rails / older-Rails setups still need the explicit `require`.
187
+ - **`ruby_llm_contract:optimize` no longer requires manual `require "ruby_llm/contract/rake_task"` in Rails apps.** Pre-0.10.4 the docs claimed the task was "included" with `RubyLLM::Contract::RakeTask`, but the railtie did not load the file - adopters running `bin/rails ruby_llm_contract:optimize` got `Unrecognized command` until they added the require to `Rakefile` or `lib/tasks/*.rake`. The railtie now uses the standard `rake_tasks { require "..." }` idiom, lazy-loading the file only when `rake` is invoked (no boot cost).
188
+ - **Docs corrected** in `docs/guide/optimizing_retry_policy.md` - the "rake task is included" line now explicitly states it auto-loads on 0.10.4+ in Rails, and that non-Rails / older-Rails setups still need the explicit `require`.
156
189
 
157
190
  ## 0.10.3 (2026-06-10)
158
191
 
159
- Hot-fix release: the schema validator now correctly accepts `nil` on **required-but-nullable** fields. This unblocks OpenAI structured-output strict mode, where every property has to be in `required` and "nullable" is expressed as a `null` branch in `anyOf`/`oneOf` or as an array `type` — exactly the combination the prior validator wrongly rejected.
192
+ Hot-fix release: the schema validator now correctly accepts `nil` on **required-but-nullable** fields. This unblocks OpenAI structured-output strict mode, where every property has to be in `required` and "nullable" is expressed as a `null` branch in `anyOf`/`oneOf` or as an array `type` - exactly the combination the prior validator wrongly rejected.
160
193
 
161
194
  ### Fixed
162
195
 
163
- - **`SchemaValidator` no longer rejects legal `nil` on required-nullable fields.** Pre-0.10.3 (every published version 0.2.x–0.10.2) conflated "required" (must be present) with "non-nullable" (cannot be null) — JSON Schema treats those as orthogonal. The validator now honours all three idioms for nullability:
196
+ - **`SchemaValidator` no longer rejects legal `nil` on required-nullable fields.** Pre-0.10.3 (every published version 0.2.x–0.10.2) conflated "required" (must be present) with "non-nullable" (cannot be null) - JSON Schema treats those as orthogonal. The validator now honours all three idioms for nullability:
164
197
  - `type: ["string", "null"]` (array form)
165
198
  - `type: "null"` (degenerate scalar form)
166
199
  - `anyOf: [{type: "string"}, {type: "null"}]` and `oneOf` equivalents
167
200
 
168
201
  **Adopter impact:** if you bypassed the bug by setting `required: false` + disabling OpenAI `strict: true` on every nullable field, you can now restore `strict: true` and keep the field required (= OpenAI's standard nullable idiom). Non-nullable required fields still reject `nil` exactly as before; this is a strictly additive fix.
169
202
 
170
- Discovered via dogfooding in a production adopter using OpenAI strict structured output with 17 nullable fields (`"set the rest to null"` prompt). Smoking-gun mutation: remove `nullable_schema?` short-circuit from `validate_nil_field` — the three new spec cases in `spec/ruby_llm/contract/contract/schema_validator_spec.rb` fail.
203
+ Discovered via dogfooding in a production adopter using OpenAI strict structured output with 17 nullable fields (`"set the rest to null"` prompt). Smoking-gun mutation: remove `nullable_schema?` short-circuit from `validate_nil_field` - the three new spec cases in `spec/ruby_llm/contract/contract/schema_validator_spec.rb` fail.
171
204
 
172
205
  ## 0.10.2 (2026-06-10)
173
206
 
@@ -197,7 +230,7 @@ First published release since 0.8.0. Consolidates work originally tagged as 0.9.
197
230
 
198
231
  ### Breaking changes
199
232
 
200
- - **`validate(description, &block)` and `Definition#invariant(description, &block)` now raise `ArgumentError` when `description` is `nil` or empty.** Pre-0.10.0 the empty descriptor was silently accepted and produced `""` entries in `result.validation_errors`, making debugging impossible. Codex audit found zero production use sites across `lib/`, `examples/`, `README` — only the regression-marker test certifying the bug.
233
+ - **`validate(description, &block)` and `Definition#invariant(description, &block)` now raise `ArgumentError` when `description` is `nil` or empty.** Pre-0.10.0 the empty descriptor was silently accepted and produced `""` entries in `result.validation_errors`, making debugging impossible. Codex audit found zero production use sites across `lib/`, `examples/`, `README` - only the regression-marker test certifying the bug.
201
234
 
202
235
  ### Migration
203
236
 
@@ -213,9 +246,9 @@ validate("score in range 0-100") { |o| o[:score].between?(0, 100) }
213
246
 
214
247
  ### Added
215
248
 
216
- - **Multimodal input via `context: { attachment: ... }`** — pass a file/IO/URL through `Step.run(input, context: { attachment: path })`; the adapter forwards it to `RubyLLM::Chat#ask(content, with: attachment)`. RubyLLM normalises wire format per provider (Anthropic url/base64, OpenAI `image_url`/`file`, Gemini `inline_data`). Multi-attachment supported natively (`with: [pdf1, pdf2]` or `with: { images: [...], pdfs: [...] }`). See [multimodal input guide](docs/guide/multimodal_input.md) (rationale in the internal ADR-0022, not shipped).
217
- - **`attachment_token_estimate(n)` class macro** — adopter-declared conservative estimate of attachment input tokens. Applied to BOTH runtime (`limit_checker`) and pre-flight (`estimate_cost`) — same source of truth, no estimate/runtime drift.
218
- - **`on_unknown_attachment_size(:refuse | :warn)` class macro** — mirrors `on_unknown_pricing` opt-out semantics. Defaults to `:refuse`. Never settable as global default — same invariant as `max_cost` fail-closed.
249
+ - **Multimodal input via `context: { attachment: ... }`** - pass a file/IO/URL through `Step.run(input, context: { attachment: path })`; the adapter forwards it to `RubyLLM::Chat#ask(content, with: attachment)`. RubyLLM normalises wire format per provider (Anthropic url/base64, OpenAI `image_url`/`file`, Gemini `inline_data`). Multi-attachment supported natively (`with: [pdf1, pdf2]` or `with: { images: [...], pdfs: [...] }`). See [multimodal input guide](docs/guide/multimodal_input.md) (rationale in the internal ADR-0022, not shipped).
250
+ - **`attachment_token_estimate(n)` class macro** - adopter-declared conservative estimate of attachment input tokens. Applied to BOTH runtime (`limit_checker`) and pre-flight (`estimate_cost`) - same source of truth, no estimate/runtime drift.
251
+ - **`on_unknown_attachment_size(:refuse | :warn)` class macro** - mirrors `on_unknown_pricing` opt-out semantics. Defaults to `:refuse`. Never settable as global default - same invariant as `max_cost` fail-closed.
219
252
 
220
253
  ### Behavioural change (READ BEFORE UPGRADING)
221
254
 
@@ -223,13 +256,13 @@ validate("score in range 0-100") { |o| o[:score].between?(0, 100) }
223
256
 
224
257
  ### Changed
225
258
 
226
- - **`run_eval` (no args) return shape pinned to `Hash<String, Report>` keyed by eval name.** Documents the existing contract used by `RubyLLM::Contract::RakeTask#collect_host_reports` and adopters. No runtime change vs 0.8.0 — only the spec assertion now locks the shape.
227
- - **`Parser.parse(text, strategy: :json)` first-bracket-wins boundary documented.** Extraction commits to the first balanced `{` or `[` structure and does NOT retry on later candidates. Empty `{}` followed by real JSON parses as the empty Hash; non-JSON `{braces}` before real JSON raises `ParseError`. No runtime change — this codifies long-standing behavior with explicit boundary tests.
259
+ - **`run_eval` (no args) return shape pinned to `Hash<String, Report>` keyed by eval name.** Documents the existing contract used by `RubyLLM::Contract::RakeTask#collect_host_reports` and adopters. No runtime change vs 0.8.0 - only the spec assertion now locks the shape.
260
+ - **`Parser.parse(text, strategy: :json)` first-bracket-wins boundary documented.** Extraction commits to the first balanced `{` or `[` structure and does NOT retry on later candidates. Empty `{}` followed by real JSON parses as the empty Hash; non-JSON `{braces}` before real JSON raises `ParseError`. No runtime change - this codifies long-standing behavior with explicit boundary tests.
228
261
 
229
262
  ### Fixed
230
263
 
231
264
  - **`with_retry_disabled` no longer mutates the step class's singleton method.** The optimizer now passes `retry_policy_override: nil` through `context:` to `compare_models`, which `Step::Base#runtime_settings` already honours. Removes a concurrency hazard where two parallel `optimize_retry_policy` calls on the same step would race on the singleton restore in `ensure`.
232
- - **`CostCalculator.find_model` exposed as a public class method.** Removes two `CostCalculator.send(:find_model, ...)` workarounds in `Step::Base#estimate_cost`. The `estimated_cost_for` helper is gone — `estimate_cost` now routes through the existing public `CostCalculator.calculate(model_name:, usage:)`.
265
+ - **`CostCalculator.find_model` exposed as a public class method.** Removes two `CostCalculator.send(:find_model, ...)` workarounds in `Step::Base#estimate_cost`. The `estimated_cost_for` helper is gone - `estimate_cost` now routes through the existing public `CostCalculator.calculate(model_name:, usage:)`.
233
266
  - **`stub_step` unified on a single storage path.** Both block and non-block forms now write to `RubyLLM::Contract.step_adapter_overrides` (thread-local). The `around(:each)` hook in `rspec.rb` handles cleanup between examples. Removes the prior `allow(step).to receive(:run)` branch.
234
267
 
235
268
  ### Internal
@@ -239,9 +272,9 @@ validate("score in range 0-100") { |o| o[:score].between?(0, 100) }
239
272
 
240
273
  ### Deferred (not in 0.10.x)
241
274
 
242
- - `add_history` multi-turn replay of prior attachments — single-turn multimodal supported; follow-up questions on the same document deferred to a later release.
243
- - Streaming + attachment — contract steps remain synchronous.
244
- - Provider-specific attachment size caps — surface only via `attachment_token_estimate` calibration; consult provider docs.
275
+ - `add_history` multi-turn replay of prior attachments - single-turn multimodal supported; follow-up questions on the same document deferred to a later release.
276
+ - Streaming + attachment - contract steps remain synchronous.
277
+ - Provider-specific attachment size caps - surface only via `attachment_token_estimate` calibration; consult provider docs.
245
278
 
246
279
  ### Tests
247
280
 
@@ -253,20 +286,20 @@ Narrative repositioning + small API additions. Internal architecture unchanged:
253
286
 
254
287
  ### Added
255
288
 
256
- - **`thinking(effort:, budget:)` class macro on `Step::Base`** — mirrors `RubyLLM::Agent.thinking` signature exactly. Stored as `{ effort:, budget: }` hash; reader returns the hash; supports `:default` reset semantics; superclass inheritance like `model`/`temperature`. The convenience alias `reasoning_effort(:low)` is implemented as `thinking(effort: :low)` — single normalized state, not separate ivar.
257
- - **Adapter wiring for `with_thinking`** — when `thinking` is set on the Step class, OR when `reasoning_effort:` is passed through context, OR when an attempt config in `retry_policy escalate(...)` carries `reasoning_effort:`, the RubyLLM adapter resolves the effective `{ effort:, budget: }` hash and forwards it via `chat.with_thinking(**)` — provider-agnostic (supports OpenAI `reasoning_effort` AND Anthropic extended-thinking budget). Precedence: per-attempt / context `reasoning_effort` overrides class-level `thinking[:effort]`; budget is taken from class-level `thinking[:budget]`. **Behavioural change vs 0.7.x**: `reasoning_effort` is now forwarded via `with_thinking` instead of `with_params`. Same wire-level OpenAI parameter; provider-agnostic Anthropic support is now automatic.
289
+ - **`thinking(effort:, budget:)` class macro on `Step::Base`** - mirrors `RubyLLM::Agent.thinking` signature exactly. Stored as `{ effort:, budget: }` hash; reader returns the hash; supports `:default` reset semantics; superclass inheritance like `model`/`temperature`. The convenience alias `reasoning_effort(:low)` is implemented as `thinking(effort: :low)` - single normalized state, not separate ivar.
290
+ - **Adapter wiring for `with_thinking`** - when `thinking` is set on the Step class, OR when `reasoning_effort:` is passed through context, OR when an attempt config in `retry_policy escalate(...)` carries `reasoning_effort:`, the RubyLLM adapter resolves the effective `{ effort:, budget: }` hash and forwards it via `chat.with_thinking(**)` - provider-agnostic (supports OpenAI `reasoning_effort` AND Anthropic extended-thinking budget). Precedence: per-attempt / context `reasoning_effort` overrides class-level `thinking[:effort]`; budget is taken from class-level `thinking[:budget]`. **Behavioural change vs 0.7.x**: `reasoning_effort` is now forwarded via `with_thinking` instead of `with_params`. Same wire-level OpenAI parameter; provider-agnostic Anthropic support is now automatic.
258
291
 
259
292
  ### Dependencies
260
293
 
261
- - **`ruby_llm` constraint bumped from `~> 1.0` to `~> 1.12`** — `Chat#with_thinking` is the canonical path for reasoning effort + extended thinking; it shipped in RubyLLM 1.12. Adopters on `ruby_llm < 1.12` need to bump RubyLLM before upgrading this gem to 0.8.0.
294
+ - **`ruby_llm` constraint bumped from `~> 1.0` to `~> 1.12`** - `Chat#with_thinking` is the canonical path for reasoning effort + extended thinking; it shipped in RubyLLM 1.12. Adopters on `ruby_llm < 1.12` need to bump RubyLLM before upgrading this gem to 0.8.0.
262
295
 
263
296
  ### Changed
264
297
 
265
- - **Tagline + README opening** — repositioned around "Contracts + Evals for RubyLLM". New "Relation to RubyLLM::Agent" section explicitly frames Step as a sibling abstraction (same niche as Agent, wider contract), not an alternative or foundation. README does not claim "Step uses Agent under the hood" — current call path is `Step → Runner → Adapters::RubyLLM → RubyLLM.chat` directly.
266
- - **`TokenEstimator` documented as heuristic** — module docstring expanded with explicit "±30% accuracy" framing. Refusal messages from `LimitChecker` now include `(heuristic ±30%)` suffix so adopters know the pre-flight number is estimated, not measured. RubyLLM 1.14 also has no pre-flight tokenizer; `RubyLLM::Tokens` is post-hoc only.
267
- - **`CostCalculator` repositioned in docs** — module narrative reframed from "cost calculator" to "fine-tune pricing registry + lookup with fallback chain". Math methods (`compute_cost`, `token_cost`, etc.) were already private; this release makes the docs match. Public API surface unchanged: `register_model`, `unregister_model`, `reset_custom_models!`, `calculate`.
268
- - **`output_schema` reframed in docs** — described as "wrapper around `RubyLLM::Schema` + client-side validation step", not a standalone feature. The schema language is identical to what `RubyLLM::Agent.schema` accepts; the difference is what wraps it.
269
- - **README retry framing** — `retry_policy escalate(...)` (model escalation on validation failure) is the marketed default. `retry_policy attempts: N` (same-model retry) stays in the API for backward compat and niche cases (subjective criteria, multi-step pipelines, weaker models) but is no longer marketed as a recommended default. Empirical basis: four small experiments across PDF quiz generation, GSM8K math (n=30 + n=120), and multi-constraint schedule generation found no useful lift for nano-class models on tasks with clear correctness criteria.
298
+ - **Tagline + README opening** - repositioned around "Contracts + Evals for RubyLLM". New "Relation to RubyLLM::Agent" section explicitly frames Step as a sibling abstraction (same niche as Agent, wider contract), not an alternative or foundation. README does not claim "Step uses Agent under the hood" - current call path is `Step → Runner → Adapters::RubyLLM → RubyLLM.chat` directly.
299
+ - **`TokenEstimator` documented as heuristic** - module docstring expanded with explicit "±30% accuracy" framing. Refusal messages from `LimitChecker` now include `(heuristic ±30%)` suffix so adopters know the pre-flight number is estimated, not measured. RubyLLM 1.14 also has no pre-flight tokenizer; `RubyLLM::Tokens` is post-hoc only.
300
+ - **`CostCalculator` repositioned in docs** - module narrative reframed from "cost calculator" to "fine-tune pricing registry + lookup with fallback chain". Math methods (`compute_cost`, `token_cost`, etc.) were already private; this release makes the docs match. Public API surface unchanged: `register_model`, `unregister_model`, `reset_custom_models!`, `calculate`.
301
+ - **`output_schema` reframed in docs** - described as "wrapper around `RubyLLM::Schema` + client-side validation step", not a standalone feature. The schema language is identical to what `RubyLLM::Agent.schema` accepts; the difference is what wraps it.
302
+ - **README retry framing** - `retry_policy escalate(...)` (model escalation on validation failure) is the marketed default. `retry_policy attempts: N` (same-model retry) stays in the API for backward compat and niche cases (subjective criteria, multi-step pipelines, weaker models) but is no longer marketed as a recommended default. Empirical basis: four small experiments across PDF quiz generation, GSM8K math (n=30 + n=120), and multi-constraint schedule generation found no useful lift for nano-class models on tasks with clear correctness criteria.
270
303
 
271
304
  ### Documentation
272
305
 
@@ -275,30 +308,30 @@ Narrative repositioning + small API additions. Internal architecture unchanged:
275
308
 
276
309
  ### Issues closed
277
310
 
278
- - **#11** (Optimizer is blind to same-model attempts) — closed after empirical experiments. `attempts: N` retry stays in API; not marketed as a default.
279
- - **#6** (Production cost reporting) — already implemented in 0.7.x; close confirmed.
311
+ - **#11** (Optimizer is blind to same-model attempts) - closed after empirical experiments. `attempts: N` retry stays in API; not marketed as a default.
312
+ - **#6** (Production cost reporting) - already implemented in 0.7.x; close confirmed.
280
313
 
281
314
  ### Not in this release (deferred)
282
315
 
283
316
  - `output_schema` Proc form for runtime-input-aware schemas (parity with `Agent.schema` Proc form). Additive, low-risk; deferred to 0.9 to keep 0.8 scope tight.
284
- - H4 (Step composing `RubyLLM::Agent` internally as config holder) — verified feasible but ROI insufficient for current adopter base; trigger-based revisit, no calendar commitment.
317
+ - H4 (Step composing `RubyLLM::Agent` internally as config holder) - verified feasible but ROI insufficient for current adopter base; trigger-based revisit, no calendar commitment.
285
318
 
286
319
  ## 0.7.3 (2026-04-24)
287
320
 
288
- Adoption-friction release. No runtime behavior changes — every delta is in `docs/`, `examples/`, or `spec/integration/` (plus the `version.rb` / Gemfile.lock bumps). Upgrading from 0.7.2 picks up the expanded guide set, the new runnable showcases, and one extra integration spec.
321
+ Adoption-friction release. No runtime behavior changes - every delta is in `docs/`, `examples/`, or `spec/integration/` (plus the `version.rb` / Gemfile.lock bumps). Upgrading from 0.7.2 picks up the expanded guide set, the new runnable showcases, and one extra integration spec.
289
322
 
290
323
  ### Documentation
291
324
 
292
- - **New guide: `docs/guide/why.md`** — four production failure modes the gem exists for (schema-valid logically wrong, silent prompt regression, sampling variance on fixed-temperature models, runaway cost). Opens from a concrete incident each time; designed for readers who have not yet felt the pain the gem relieves.
293
- - **New guide: `docs/guide/rails_integration.md`** — seven Rails-specific FAQs with runnable snippets: where step classes live (`app/contracts/`), initializer setup, background jobs, `around_call` observability, RSpec/Minitest stubs, error handling in controllers, CI gate wiring.
294
- - **README adoption-friction pass** — added a short "Do I need this?" block after Install, a reading-order hint (`README → why.md → getting_started.md`), and outcome-based labels in the docs index ("Prevent silent prompt regressions" instead of "Eval-First", etc.).
295
- - **TL;DR box at the top of every guide** — single-sentence orientation for readers who land via search; "Skip if" clause added where real confusion exists (`eval_first.md`, `testing.md`, `migration.md`).
296
- - **API coverage gaps closed** — `estimate_cost` / `estimate_eval_cost`, `max_cost on_unknown_pricing: :warn`, `run_eval(..., concurrency:)`, `around_call` testing patterns now documented in `getting_started.md`, `eval_first.md`, `testing.md`.
297
- - **Industry-standard terminology** — `temperature-locked` → `fixed-temperature`, `variance-induced` → `sampling variance`, `severity signals` → `severity keywords`, `takeaway drift` → `tone/takeaways mismatch`.
298
- - **`docs/architecture.md` refresh** — diagram now reflects the current class layout: added `Step::RetryPolicy`, `Pipeline::Result`, `Eval::AggregatedReport`, `Eval::BaselineDiff`, `Eval::PromptDiffComparator`, `Eval::EvalHistory`, `Eval::RetryOptimizer`, `OptimizeRakeTask`. Replaced the outdated `Eval::TraitEvaluator` entry with `Eval::ExpectationEvaluator`.
299
- - **Business framing added to guides** — every guide opens with a concrete production scenario or "why it matters" hook before the API reference.
325
+ - **New guide: `docs/guide/why.md`** - four production failure modes the gem exists for (schema-valid logically wrong, silent prompt regression, sampling variance on fixed-temperature models, runaway cost). Opens from a concrete incident each time; designed for readers who have not yet felt the pain the gem relieves.
326
+ - **New guide: `docs/guide/rails_integration.md`** - seven Rails-specific FAQs with runnable snippets: where step classes live (`app/contracts/`), initializer setup, background jobs, `around_call` observability, RSpec/Minitest stubs, error handling in controllers, CI gate wiring.
327
+ - **README adoption-friction pass** - added a short "Do I need this?" block after Install, a reading-order hint (`README → why.md → getting_started.md`), and outcome-based labels in the docs index ("Prevent silent prompt regressions" instead of "Eval-First", etc.).
328
+ - **TL;DR box at the top of every guide** - single-sentence orientation for readers who land via search; "Skip if" clause added where real confusion exists (`eval_first.md`, `testing.md`, `migration.md`).
329
+ - **API coverage gaps closed** - `estimate_cost` / `estimate_eval_cost`, `max_cost on_unknown_pricing: :warn`, `run_eval(..., concurrency:)`, `around_call` testing patterns now documented in `getting_started.md`, `eval_first.md`, `testing.md`.
330
+ - **Industry-standard terminology** - `temperature-locked` → `fixed-temperature`, `variance-induced` → `sampling variance`, `severity signals` → `severity keywords`, `takeaway drift` → `tone/takeaways mismatch`.
331
+ - **`docs/architecture.md` refresh** - diagram now reflects the current class layout: added `Step::RetryPolicy`, `Pipeline::Result`, `Eval::AggregatedReport`, `Eval::BaselineDiff`, `Eval::PromptDiffComparator`, `Eval::EvalHistory`, `Eval::RetryOptimizer`, `OptimizeRakeTask`. Replaced the outdated `Eval::TraitEvaluator` entry with `Eval::ExpectationEvaluator`.
332
+ - **Business framing added to guides** - every guide opens with a concrete production scenario or "why it matters" hook before the API reference.
300
333
 
301
- ### Examples — consolidated on `SummarizeArticle`, renumbered 00-06
334
+ ### Examples - consolidated on `SummarizeArticle`, renumbered 00-06
302
335
 
303
336
  The previous 12-file set mixed a private Reddit promo planner, customer support, meetings, keyword extraction, and translation. The new set is seven runnable files, each answering one adopter question on the README's `SummarizeArticle` case.
304
337
 
@@ -314,19 +347,19 @@ The previous 12-file set mixed a private Reddit promo planner, customer support,
314
347
 
315
348
  Every file carries an "Expected output" block in its header so readers see the result without running the script. The `docs/ideas/` directory is now fully untracked (already in `.gitignore`; one stray file removed from version control).
316
349
 
317
- ### Examples — bug fixes carried along
350
+ ### Examples - bug fixes carried along
318
351
 
319
- - **Schema pitfall fixed in 5 files** — `array :x do; string :y; ...; end` silently produces `items: string` and drops every declaration after the first, matching the documented pitfall in `spec/ruby_llm/contract/nested_schema_spec.rb:71`. Every affected array block is now wrapped in `object do...end`.
320
- - **`examples/05_eval_dataset.rb` (pre-renumber: `09_eval_dataset.rb`) `result[:passed]` → `result.passed?`** — the previous code called `[]` on an `Eval::CaseResult` and raised `NoMethodError` at runtime.
352
+ - **Schema pitfall fixed in 5 files** - `array :x do; string :y; ...; end` silently produces `items: string` and drops every declaration after the first, matching the documented pitfall in `spec/ruby_llm/contract/nested_schema_spec.rb:71`. Every affected array block is now wrapped in `object do...end`.
353
+ - **`examples/05_eval_dataset.rb` (pre-renumber: `09_eval_dataset.rb`) `result[:passed]` → `result.passed?`** - the previous code called `[]` on an `Eval::CaseResult` and raised `NoMethodError` at runtime.
321
354
 
322
355
  ### Testing
323
356
 
324
- - **New `spec/integration/pipeline_eval_spec.rb`** — three cases guaranteeing pipeline-level `run_eval` stays functional: happy path, final-step mismatch, and fail-fast propagation when an intermediate `validate` rejects. Closes the "09 STEP 5 pipeline evaluation" known issue flagged in the 0.7.2 release. The fail-fast case asserts `step_status == :validation_failed` and the validate's label in `details`, so a regression that short-circuits on schema instead of validate would fail loudly.
357
+ - **New `spec/integration/pipeline_eval_spec.rb`** - three cases guaranteeing pipeline-level `run_eval` stays functional: happy path, final-step mismatch, and fail-fast propagation when an intermediate `validate` rejects. Closes the "09 STEP 5 pipeline evaluation" known issue flagged in the 0.7.2 release. The fail-fast case asserts `step_status == :validation_failed` and the validate's label in `details`, so a regression that short-circuits on schema instead of validate would fail loudly.
325
358
 
326
359
  ### Deleted (private-project cleanup)
327
360
 
328
- - `examples/01_classify_threads.rb`, `02_generate_comment.rb`, `03_target_audience.rb`, `10_reddit_full_showcase.rb`, `spec/integration/reddit_pipeline_spec.rb` — Reddit Promo Planner was a separate private project; its examples do not belong in the gem's public repo.
329
- - `examples/02_output_schema.rb` — fully covered by `docs/guide/output_schema.md`; deleting avoids duplication.
361
+ - `examples/01_classify_threads.rb`, `02_generate_comment.rb`, `03_target_audience.rb`, `10_reddit_full_showcase.rb`, `spec/integration/reddit_pipeline_spec.rb` - Reddit Promo Planner was a separate private project; its examples do not belong in the gem's public repo.
362
+ - `examples/02_output_schema.rb` - fully covered by `docs/guide/output_schema.md`; deleting avoids duplication.
330
363
 
331
364
  ## 0.7.2 (2026-04-22)
332
365
 
@@ -336,24 +369,24 @@ Every file carries an "Expected output" block in its header so readers see the r
336
369
 
337
370
  ### Documentation
338
371
 
339
- - **`docs/guide/optimizing_retry_policy.md` rewritten** — 17.7k → 6.4k characters. Continues the `SummarizeArticle` narrative from README. Offline mode clearly positioned as wiring-check; real optimization runs via `LIVE=1 RUNS=3`. Output samples match actual `print_summary` format.
340
- - **`docs/guide/getting_started.md` rewritten** — 8.7k → 6.1k. Every example uses `SummarizeArticle`. Evals + CI gates section moved before Budget caps. Structured Prompts / Dynamic Prompts / "Already using ruby_llm?" / Reasoning effort sections removed; content delegated to `prompt_ast.md` and README.
341
- - **`docs/guide/eval_first.md` refined** — 6.3k → 5.0k. Switched to `SummarizeArticle` case. Team workflow section compressed with links back to `getting_started.md` for the matcher chain.
342
- - **`docs/guide/testing.md` refined** — 10.7k → 7.4k. Switched to `SummarizeArticle` case. Threshold gating / Rake task / baseline walkthrough / prompt A/B sections delegated back to `getting_started.md` and `eval_first.md`.
343
- - **`docs/guide/output_schema.md` DSL bug fix** — the Supported constraints table documented JSON Schema camelCase keys (`minLength`, `minItems`, `additionalProperties`) that are not valid DSL arguments. Every copy-paste from the previous table would have raised `ArgumentError`. Switched to snake_case (`min_length`, `min_items`, `additional_properties`) as the DSL actually expects; added a short note on the internal camelCase conversion.
344
- - **`docs/guide/best_practices.md`, `pipeline.md`, `migration.md` sanity pass** — terminology alignment (model escalation → model fallback where narrative; `escalate` DSL method unchanged) and `SummarizeArticle` case where the guide is not inherently multi-step.
372
+ - **`docs/guide/optimizing_retry_policy.md` rewritten** - 17.7k → 6.4k characters. Continues the `SummarizeArticle` narrative from README. Offline mode clearly positioned as wiring-check; real optimization runs via `LIVE=1 RUNS=3`. Output samples match actual `print_summary` format.
373
+ - **`docs/guide/getting_started.md` rewritten** - 8.7k → 6.1k. Every example uses `SummarizeArticle`. Evals + CI gates section moved before Budget caps. Structured Prompts / Dynamic Prompts / "Already using ruby_llm?" / Reasoning effort sections removed; content delegated to `prompt_ast.md` and README.
374
+ - **`docs/guide/eval_first.md` refined** - 6.3k → 5.0k. Switched to `SummarizeArticle` case. Team workflow section compressed with links back to `getting_started.md` for the matcher chain.
375
+ - **`docs/guide/testing.md` refined** - 10.7k → 7.4k. Switched to `SummarizeArticle` case. Threshold gating / Rake task / baseline walkthrough / prompt A/B sections delegated back to `getting_started.md` and `eval_first.md`.
376
+ - **`docs/guide/output_schema.md` DSL bug fix** - the Supported constraints table documented JSON Schema camelCase keys (`minLength`, `minItems`, `additionalProperties`) that are not valid DSL arguments. Every copy-paste from the previous table would have raised `ArgumentError`. Switched to snake_case (`min_length`, `min_items`, `additional_properties`) as the DSL actually expects; added a short note on the internal camelCase conversion.
377
+ - **`docs/guide/best_practices.md`, `pipeline.md`, `migration.md` sanity pass** - terminology alignment (model escalation → model fallback where narrative; `escalate` DSL method unchanged) and `SummarizeArticle` case where the guide is not inherently multi-step.
345
378
 
346
379
  ## 0.7.1 (2026-04-22)
347
380
 
348
381
  ### Changed (behavioral, follow-up to v0.7.0)
349
382
 
350
- - **`Step::Base#run_once` no longer swallows adapter-phase `ArgumentError` as `:input_error`.** The previous blanket `rescue ArgumentError` was there to convert DSL misconfiguration (e.g. missing `prompt`) into an `:input_error` Result. Side effect: programmer bugs in adapter code that raised `ArgumentError` (wrong arity, bad config argument) were silently coerced into `:input_error` and retried as if the user had given bad input. Now the rescue is narrowed to the Runner-construction phase only — DSL configuration errors still produce `:input_error` (the `prompt has not been set` case is regression-tested), but `ArgumentError` raised from adapter code during `Runner#call` propagates to the caller. Input-type validation failures continue to produce `:input_error` through `InputValidator`'s own scoped rescue, unchanged.
383
+ - **`Step::Base#run_once` no longer swallows adapter-phase `ArgumentError` as `:input_error`.** The previous blanket `rescue ArgumentError` was there to convert DSL misconfiguration (e.g. missing `prompt`) into an `:input_error` Result. Side effect: programmer bugs in adapter code that raised `ArgumentError` (wrong arity, bad config argument) were silently coerced into `:input_error` and retried as if the user had given bad input. Now the rescue is narrowed to the Runner-construction phase only - DSL configuration errors still produce `:input_error` (the `prompt has not been set` case is regression-tested), but `ArgumentError` raised from adapter code during `Runner#call` propagates to the caller. Input-type validation failures continue to produce `:input_error` through `InputValidator`'s own scoped rescue, unchanged.
351
384
 
352
385
  ## 0.7.0 (2026-04-21)
353
386
 
354
387
  ### Breaking changes
355
388
 
356
- - **`:adapter_error` removed from `DEFAULT_RETRY_ON`.** New default: `[:validation_failed, :parse_error]`. `ruby_llm` already retries transport errors (`RateLimitError`, `ServerError`, `ServiceUnavailableError`, `OverloadedError`, timeouts) at the Faraday layer, so the previous default re-ran the same model on errors the HTTP middleware already retried with backoff. To restore pre-0.7 behavior: `retry_on :validation_failed, :parse_error, :adapter_error`. Recommended pattern: pair `:adapter_error` with `escalate "model_a", "model_b"` — a different model/provider can bypass what transport retry could not.
389
+ - **`:adapter_error` removed from `DEFAULT_RETRY_ON`.** New default: `[:validation_failed, :parse_error]`. `ruby_llm` already retries transport errors (`RateLimitError`, `ServerError`, `ServiceUnavailableError`, `OverloadedError`, timeouts) at the Faraday layer, so the previous default re-ran the same model on errors the HTTP middleware already retried with backoff. To restore pre-0.7 behavior: `retry_on :validation_failed, :parse_error, :adapter_error`. Recommended pattern: pair `:adapter_error` with `escalate "model_a", "model_b"` - a different model/provider can bypass what transport retry could not.
357
390
  - **`AdapterCaller` narrows `rescue` from `StandardError` to `RubyLLM::Error` + `Faraday::Error`.** Provider errors and transport errors that escape ruby_llm's Faraday retry middleware (`Faraday::TimeoutError`, `Faraday::ConnectionFailed`) still produce `:adapter_error` as before. Programmer errors that are neither (`NoMethodError`, adapter code bugs) now propagate instead of being silently converted to `:adapter_error` and retried. **Known limitation:** adapter code raising `ArgumentError` is still coerced into `:input_error` by `Step::Base#run_once` (which rescues `ArgumentError` for input-type validation). Disambiguating adapter-ArgumentError vs input-validation-ArgumentError requires a `run_once` refactor and is tracked as a follow-up.
358
391
 
359
392
  ### Migration
@@ -380,43 +413,43 @@ end
380
413
 
381
414
  ### Features
382
415
 
383
- - **`production_mode:` on `compare_models` and `optimize_retry_policy`** — measures retry-aware, end-to-end cost per successful output. Pass `production_mode: { fallback: "gpt-5-mini" }` and each candidate runs with a runtime-injected `[candidate, fallback]` retry chain. The report exposes `escalation_rate`, `single_shot_cost`, and `effective_cost` so "the cheaper candidate" decision matches production cost rather than first-attempt cost.
384
- - **New Report metrics** — `escalation_rate`, `single_shot_cost`, `effective_cost`, `single_shot_latency_ms`, `effective_latency_ms`, `latency_percentiles` (p50/p95/max). `AggregatedReport` averages all of them across `runs:`.
385
- - **Extended `ModelComparison#table`** — when `production_mode:` is set, renders a `Chain` column (`candidate → fallback`) with `single-shot`, `escalation`, `effective cost`, `latency`, `score`. Edge case `candidate == fallback` renders as a single model and `—` in the escalation column, with retry injection skipped entirely so `effective == single-shot` by construction, not by coincidence.
386
- - **`context[:retry_policy_override]`** — new context key that nullifies or replaces class-level `retry_policy` for a single call. Used internally by production-mode injection; safe to use directly when you need a transient override that doesn't mutate the step class.
416
+ - **`production_mode:` on `compare_models` and `optimize_retry_policy`** - measures retry-aware, end-to-end cost per successful output. Pass `production_mode: { fallback: "gpt-5-mini" }` and each candidate runs with a runtime-injected `[candidate, fallback]` retry chain. The report exposes `escalation_rate`, `single_shot_cost`, and `effective_cost` so "the cheaper candidate" decision matches production cost rather than first-attempt cost.
417
+ - **New Report metrics** - `escalation_rate`, `single_shot_cost`, `effective_cost`, `single_shot_latency_ms`, `effective_latency_ms`, `latency_percentiles` (p50/p95/max). `AggregatedReport` averages all of them across `runs:`.
418
+ - **Extended `ModelComparison#table`** - when `production_mode:` is set, renders a `Chain` column (`candidate → fallback`) with `single-shot`, `escalation`, `effective cost`, `latency`, `score`. Edge case `candidate == fallback` renders as a single model and `—` in the escalation column, with retry injection skipped entirely so `effective == single-shot` by construction, not by coincidence.
419
+ - **`context[:retry_policy_override]`** - new context key that nullifies or replaces class-level `retry_policy` for a single call. Used internally by production-mode injection; safe to use directly when you need a transient override that doesn't mutate the step class.
387
420
 
388
421
  ### Scope
389
422
 
390
423
  - Single-fallback (2-tier) chains only. Multi-tier chains can be inspected post-hoc via `trace.attempts` but aren't summarized in the optimize table.
391
- - Costs with `runs: 3 + production_mode: { fallback: "gpt-5-mini" }` are ≈3× a single-shot eval plus the actual retry attempts — not 6×. Production-mode metrics come from a single pass.
392
- - **Step-only.** Calling `compare_models` with `production_mode:` on a `Pipeline::Base` subclass raises `ArgumentError` — retry injection is Step-level and pipeline-wide fallback semantics aren't defined yet. Benchmark individual steps.
424
+ - Costs with `runs: 3 + production_mode: { fallback: "gpt-5-mini" }` are ≈3× a single-shot eval plus the actual retry attempts - not 6×. Production-mode metrics come from a single pass.
425
+ - **Step-only.** Calling `compare_models` with `production_mode:` on a `Pipeline::Base` subclass raises `ArgumentError` - retry injection is Step-level and pipeline-wide fallback semantics aren't defined yet. Benchmark individual steps.
393
426
 
394
427
  ### Documentation
395
428
 
396
- - **Guide: [Production-mode cost measurement](docs/guide/optimizing_retry_policy.md#measure-effective-cost-before-shipping)** — API, metric interpretation, 2-tier scope note.
429
+ - **Guide: [Production-mode cost measurement](docs/guide/optimizing_retry_policy.md#measure-effective-cost-before-shipping)** - API, metric interpretation, 2-tier scope note.
397
430
 
398
431
  ## 0.6.3 (2026-04-20)
399
432
 
400
433
  ### Features
401
434
 
402
- - **`runs:` parameter on `compare_models` and `optimize_retry_policy`** — runs each candidate N times per eval and aggregates the mean score, mean cost per run, and mean latency. Reduces sampling variance in live mode where LLM outputs are non-deterministic (gpt-5 family enforces `temperature=1.0` server-side, so a single unlucky sample can misclassify a viable candidate as "failing"). Default `runs: 1` — backward compatible.
403
- - **`RUNS=N` on `rake ruby_llm_contract:optimize`** — CLI flag for variance-aware optimization.
404
- - **`Eval::AggregatedReport`** — duck-type `Report` exposing `score` (mean), `score_min`/`score_max` (spread), `total_cost` (mean per run), `pass_rate` (clean-pass count x/N), and `clean_passes`.
405
- - **Guide: [Reducing variance with `runs:`](docs/guide/optimizing_retry_policy.md)** — when to use it and why.
435
+ - **`runs:` parameter on `compare_models` and `optimize_retry_policy`** - runs each candidate N times per eval and aggregates the mean score, mean cost per run, and mean latency. Reduces sampling variance in live mode where LLM outputs are non-deterministic (gpt-5 family enforces `temperature=1.0` server-side, so a single unlucky sample can misclassify a viable candidate as "failing"). Default `runs: 1` - backward compatible.
436
+ - **`RUNS=N` on `rake ruby_llm_contract:optimize`** - CLI flag for variance-aware optimization.
437
+ - **`Eval::AggregatedReport`** - duck-type `Report` exposing `score` (mean), `score_min`/`score_max` (spread), `total_cost` (mean per run), `pass_rate` (clean-pass count x/N), and `clean_passes`.
438
+ - **Guide: [Reducing variance with `runs:`](docs/guide/optimizing_retry_policy.md)** - when to use it and why.
406
439
 
407
440
  ## 0.6.2 (2026-04-18)
408
441
 
409
442
  ### Features
410
443
 
411
- - **`Step.optimize_retry_policy`** — runs `compare_models` on ALL evals for the step, builds a score matrix, identifies the constraining eval, and suggests a retry chain. Chain's last model always passes all evals (safe fallback).
412
- - **`rake ruby_llm_contract:optimize`** — one-command retry chain optimization. Prints score table, constraining eval, suggested chain, and copy-paste DSL.
413
- - **Offline by default** — `optimize` uses `sample_response` (zero API calls) unless `LIVE=1` or `PROVIDER=` is set.
414
- - **`EVAL_DIRS=` support** — non-Rails setups can specify eval file directories.
415
- - **Guide: [Optimizing retry_policy](docs/guide/optimizing_retry_policy.md)** — full procedure with prerequisites, troubleshooting, and real-world example.
444
+ - **`Step.optimize_retry_policy`** - runs `compare_models` on ALL evals for the step, builds a score matrix, identifies the constraining eval, and suggests a retry chain. Chain's last model always passes all evals (safe fallback).
445
+ - **`rake ruby_llm_contract:optimize`** - one-command retry chain optimization. Prints score table, constraining eval, suggested chain, and copy-paste DSL.
446
+ - **Offline by default** - `optimize` uses `sample_response` (zero API calls) unless `LIVE=1` or `PROVIDER=` is set.
447
+ - **`EVAL_DIRS=` support** - non-Rails setups can specify eval file directories.
448
+ - **Guide: [Optimizing retry_policy](docs/guide/optimizing_retry_policy.md)** - full procedure with prerequisites, troubleshooting, and real-world example.
416
449
 
417
450
  ### Fixes
418
451
 
419
- - Chain semantics aligned with `retry_executor` — retry fires on `validation_failed`/`parse_error`, not on low eval score. Disjoint eval coverage (A passes e1, B passes e2, neither passes both) correctly returns empty chain.
452
+ - Chain semantics aligned with `retry_executor` - retry fires on `validation_failed`/`parse_error`, not on low eval score. Disjoint eval coverage (A passes e1, B passes e2, neither passes both) correctly returns empty chain.
420
453
  - Removed ActiveSupport dependency from rake task (`.presence` → `.empty?`).
421
454
  - Added `require "set"` for non-Rails environments.
422
455
 
@@ -424,22 +457,22 @@ end
424
457
 
425
458
  ### Features
426
459
 
427
- - **Multi-provider operator tooling** — rake tasks support `PROVIDER=openai|anthropic|ollama` and `CANDIDATES=model@effort,...`.
428
- - **`rake ruby_llm_contract:recommend`** — wraps `Step.recommend` with CLI interface, prints best config, retry chain, DSL, rationale, and savings.
429
- - **Ollama support** — `PROVIDER=ollama` (base URL via `RubyLLM.configure { |c| c.ollama_api_base = ... }`).
460
+ - **Multi-provider operator tooling** - rake tasks support `PROVIDER=openai|anthropic|ollama` and `CANDIDATES=model@effort,...`.
461
+ - **`rake ruby_llm_contract:recommend`** - wraps `Step.recommend` with CLI interface, prints best config, retry chain, DSL, rationale, and savings.
462
+ - **Ollama support** - `PROVIDER=ollama` (base URL via `RubyLLM.configure { |c| c.ollama_api_base = ... }`).
430
463
 
431
464
  ## 0.6.0 (2026-04-12)
432
465
 
433
- "What should I do?" — model + configuration recommendation.
466
+ "What should I do?" - model + configuration recommendation.
434
467
 
435
468
  ### Features
436
469
 
437
- - **`Step.recommend`** — `ClassifyTicket.recommend("eval", candidates: [...], min_score: 0.95)` runs eval on all candidates and returns a `Recommendation` with optimal model, retry chain, rationale, savings vs current config, and `to_dsl` code output.
438
- - **Candidates as configurations** — `candidates:` accepts `{ model:, reasoning_effort: }` hashes, not just model name strings. `gpt-5-mini` with `reasoning_effort: "low"` is a different candidate than with `"high"`.
439
- - **`compare_models` extended** — new `candidates:` parameter alongside existing `models:` (backward compatible). Candidate labels include reasoning effort in output table.
440
- - **Per-attempt `reasoning_effort` in retry policies** — `escalate` accepts config hashes: `escalate({ model: "gpt-5-nano" }, { model: "gpt-5-mini", reasoning_effort: "high" })`. Each attempt gets its own reasoning_effort forwarded to the provider.
441
- - **`pass_rate_ratio`** — numeric float (0.0–1.0) on `Report` and `ReportStats`, complementing the string `pass_rate` (`"3/5"`).
442
- - **History entries enriched** — `save_history!` accepts `reasoning_effort:` and stores `model`, `reasoning_effort`, `pass_rate_ratio` in JSONL entries.
470
+ - **`Step.recommend`** - `ClassifyTicket.recommend("eval", candidates: [...], min_score: 0.95)` runs eval on all candidates and returns a `Recommendation` with optimal model, retry chain, rationale, savings vs current config, and `to_dsl` code output.
471
+ - **Candidates as configurations** - `candidates:` accepts `{ model:, reasoning_effort: }` hashes, not just model name strings. `gpt-5-mini` with `reasoning_effort: "low"` is a different candidate than with `"high"`.
472
+ - **`compare_models` extended** - new `candidates:` parameter alongside existing `models:` (backward compatible). Candidate labels include reasoning effort in output table.
473
+ - **Per-attempt `reasoning_effort` in retry policies** - `escalate` accepts config hashes: `escalate({ model: "gpt-5-nano" }, { model: "gpt-5-mini", reasoning_effort: "high" })`. Each attempt gets its own reasoning_effort forwarded to the provider.
474
+ - **`pass_rate_ratio`** - numeric float (0.0–1.0) on `Report` and `ReportStats`, complementing the string `pass_rate` (`"3/5"`).
475
+ - **History entries enriched** - `save_history!` accepts `reasoning_effort:` and stores `model`, `reasoning_effort`, `pass_rate_ratio` in JSONL entries.
443
476
 
444
477
  ### Game changer continuity
445
478
 
@@ -455,7 +488,7 @@ v0.6: "What should I do?" → recommend (actionable advice)
455
488
 
456
489
  ### Features
457
490
 
458
- - **`reasoning_effort` forwarded to provider** — `context: { reasoning_effort: "low" }` now passed through `with_params` to the LLM. Previously accepted as a known context key but silently ignored by the RubyLLM adapter.
491
+ - **`reasoning_effort` forwarded to provider** - `context: { reasoning_effort: "low" }` now passed through `with_params` to the LLM. Previously accepted as a known context key but silently ignored by the RubyLLM adapter.
459
492
 
460
493
  ## 0.5.0 (2026-03-25)
461
494
 
@@ -463,9 +496,9 @@ Data-Driven Prompt Engineering.
463
496
 
464
497
  ### Features
465
498
 
466
- - **`observe` DSL** — soft observations that log but never fail. `observe("scores differ") { |o| o[:a] != o[:b] }`. Results in `result.observations`. Logged via `Contract.logger` when they fail. Runs only when validation passes.
467
- - **`compare_with`** — prompt A/B testing. `StepV2.compare_with(StepV1, eval: "regression", model: "nano")` returns `PromptDiff` with `improvements`, `regressions`, `score_delta`, `safe_to_switch?`. Reuses `BaselineDiff` internally.
468
- - **RSpec `compared_with` chain** — `expect(StepV2).to pass_eval("x").compared_with(StepV1).without_regressions` blocks merge if new prompt regresses any case.
499
+ - **`observe` DSL** - soft observations that log but never fail. `observe("scores differ") { |o| o[:a] != o[:b] }`. Results in `result.observations`. Logged via `Contract.logger` when they fail. Runs only when validation passes.
500
+ - **`compare_with`** - prompt A/B testing. `StepV2.compare_with(StepV1, eval: "regression", model: "nano")` returns `PromptDiff` with `improvements`, `regressions`, `score_delta`, `safe_to_switch?`. Reuses `BaselineDiff` internally.
501
+ - **RSpec `compared_with` chain** - `expect(StepV2).to pass_eval("x").compared_with(StepV1).without_regressions` blocks merge if new prompt regresses any case.
469
502
 
470
503
  ### Game changer continuity
471
504
 
@@ -478,25 +511,25 @@ v0.5: "Which prompt is better?" → compare_with (A/B testing)
478
511
 
479
512
  ## 0.4.5 (2026-03-24)
480
513
 
481
- Audit hardening — 18 bugs fixed across 4 audit rounds.
514
+ Audit hardening - 18 bugs fixed across 4 audit rounds.
482
515
 
483
516
  ### Fixes
484
517
 
485
- - **RakeTask history before abort** — `track_history` now saves all reports (pass and fail) before gating, so failed runs appear in eval history.
486
- - **RSpec/Minitest stub scoping** — block form `stub_step` uses thread-local overrides with real cleanup. Non-block `stub_all_steps` auto-restored by RSpec `around(:each)` hook and Minitest `setup`/`teardown`.
487
- - **StepAdapterOverride** — handles `context: nil` and respects string key `"adapter"`. Moved to `contract.rb` so both test frameworks share one mechanism.
488
- - **max_cost fail closed output estimate** — preflight uses 1x input tokens as output estimate when `max_output` not set, preventing cost bypass for output-expensive models.
489
- - **reset_configuration! clears overrides** — `step_adapter_overrides` now cleared on reset.
490
- - **CostCalculator.register_model** — validates `Numeric`, `finite?`, non-negative. Rejects NaN, Infinity, strings, nil.
491
- - **Pipeline token_budget** — rejects negative and zero values (parity with `timeout_ms`).
492
- - **track_history model fallback** — uses step DSL `model`, then `default_model` when context has no model. Handles string key `"model"`.
493
- - **estimate_cost / estimate_eval_cost** — falls back to step DSL model when no explicit model arg given.
494
- - **stub_steps string keys** — both RSpec and Minitest normalize string-keyed options with `transform_keys(:to_sym)`.
495
- - **DSL `:default` reset** — `model(:default)`, `temperature(:default)`, `max_cost(:default)` reset inherited parent values.
518
+ - **RakeTask history before abort** - `track_history` now saves all reports (pass and fail) before gating, so failed runs appear in eval history.
519
+ - **RSpec/Minitest stub scoping** - block form `stub_step` uses thread-local overrides with real cleanup. Non-block `stub_all_steps` auto-restored by RSpec `around(:each)` hook and Minitest `setup`/`teardown`.
520
+ - **StepAdapterOverride** - handles `context: nil` and respects string key `"adapter"`. Moved to `contract.rb` so both test frameworks share one mechanism.
521
+ - **max_cost fail closed output estimate** - preflight uses 1x input tokens as output estimate when `max_output` not set, preventing cost bypass for output-expensive models.
522
+ - **reset_configuration! clears overrides** - `step_adapter_overrides` now cleared on reset.
523
+ - **CostCalculator.register_model** - validates `Numeric`, `finite?`, non-negative. Rejects NaN, Infinity, strings, nil.
524
+ - **Pipeline token_budget** - rejects negative and zero values (parity with `timeout_ms`).
525
+ - **track_history model fallback** - uses step DSL `model`, then `default_model` when context has no model. Handles string key `"model"`.
526
+ - **estimate_cost / estimate_eval_cost** - falls back to step DSL model when no explicit model arg given.
527
+ - **stub_steps string keys** - both RSpec and Minitest normalize string-keyed options with `transform_keys(:to_sym)`.
528
+ - **DSL `:default` reset** - `model(:default)`, `temperature(:default)`, `max_cost(:default)` reset inherited parent values.
496
529
 
497
530
  ## 0.4.4 (2026-03-24)
498
531
 
499
- - **`stub_steps` (plural)** — stub multiple steps with different responses in one block. No nesting needed. Works in RSpec and Minitest:
532
+ - **`stub_steps` (plural)** - stub multiple steps with different responses in one block. No nesting needed. Works in RSpec and Minitest:
500
533
  ```ruby
501
534
  stub_steps(
502
535
  ClassifyTicket => { response: { priority: "high" } },
@@ -510,33 +543,33 @@ Production feedback release.
510
543
 
511
544
  ### Features
512
545
 
513
- - **`stub_step` block form** — `stub_step(Step, response: x) { test }` auto-resets adapter after block. Works in RSpec and Minitest. Eliminates leaked test state.
514
- - **Minitest per-step routing** — `stub_step(StepA, ...)` now actually routes to StepA only (was setting global adapter, ignoring step class).
515
- - **`track_history` in RakeTask** — `t.track_history = true` auto-appends every eval run (pass and fail) to `.eval_history/`. Drift detection without manual `save_history!` calls.
516
- - **`max_cost` fail closed** — unknown model pricing now refuses the call instead of silently skipping. Set `on_unknown_pricing: :warn` for old behavior.
517
- - **`CostCalculator.register_model`** — register pricing for custom/fine-tuned models: `register_model("ft:gpt-4o", input_per_1m: 3.0, output_per_1m: 6.0)`.
546
+ - **`stub_step` block form** - `stub_step(Step, response: x) { test }` auto-resets adapter after block. Works in RSpec and Minitest. Eliminates leaked test state.
547
+ - **Minitest per-step routing** - `stub_step(StepA, ...)` now actually routes to StepA only (was setting global adapter, ignoring step class).
548
+ - **`track_history` in RakeTask** - `t.track_history = true` auto-appends every eval run (pass and fail) to `.eval_history/`. Drift detection without manual `save_history!` calls.
549
+ - **`max_cost` fail closed** - unknown model pricing now refuses the call instead of silently skipping. Set `on_unknown_pricing: :warn` for old behavior.
550
+ - **`CostCalculator.register_model`** - register pricing for custom/fine-tuned models: `register_model("ft:gpt-4o", input_per_1m: 3.0, output_per_1m: 6.0)`.
518
551
 
519
552
  ## 0.4.2 (2026-03-24)
520
553
 
521
- - **RakeTask lazy context** — `t.context` now accepts a Proc, resolved at task runtime (after `:environment`). Fixes adapter not being available at Rake load time in Rails apps.
554
+ - **RakeTask lazy context** - `t.context` now accepts a Proc, resolved at task runtime (after `:environment`). Fixes adapter not being available at Rake load time in Rails apps.
522
555
 
523
556
  ## 0.4.1 (2026-03-24)
524
557
 
525
- - **RakeTask `:environment` fix** — uses `defined?(::Rails)` instead of `Rake::Task.task_defined?(:environment)`. Works in Rails 8 without manual `Rake::Task.enhance`.
526
- - **Concurrent eval deterministic** — `clone_for_concurrency` protocol, `ContextHelpers` extracted.
527
- - **README** — added eval history, concurrency, quality tracking examples.
558
+ - **RakeTask `:environment` fix** - uses `defined?(::Rails)` instead of `Rake::Task.task_defined?(:environment)`. Works in Rails 8 without manual `Rake::Task.enhance`.
559
+ - **Concurrent eval deterministic** - `clone_for_concurrency` protocol, `ContextHelpers` extracted.
560
+ - **README** - added eval history, concurrency, quality tracking examples.
528
561
 
529
562
  ## 0.4.0 (2026-03-24)
530
563
 
531
- Observability & Scale — see what changed, run it fast, debug it easily.
564
+ Observability & Scale - see what changed, run it fast, debug it easily.
532
565
 
533
566
  ### Features
534
567
 
535
- - **Structured logging** — `Contract.configure { |c| c.logger = Rails.logger }`. Auto-logs model, status, latency, tokens, cost on every `step.run`.
536
- - **Batch eval concurrency** — `run_eval("regression", concurrency: 4)`. Parallel case execution via Concurrent::Future. 4x faster CI for large eval suites.
537
- - **Eval history & trending** — `report.save_history!` appends to JSONL. `report.eval_history` returns `EvalHistory` with `score_trend`, `drift?`, run-by-run scores.
538
- - **Pipeline per-step eval** — `add_case(..., step_expectations: { classify: { priority: "high" } })`. See which step in a pipeline regressed.
539
- - **Minitest support** — `assert_satisfies_contract`, `assert_eval_passes`, `stub_step` for Minitest users. `require "ruby_llm/contract/minitest"`.
568
+ - **Structured logging** - `Contract.configure { |c| c.logger = Rails.logger }`. Auto-logs model, status, latency, tokens, cost on every `step.run`.
569
+ - **Batch eval concurrency** - `run_eval("regression", concurrency: 4)`. Parallel case execution via Concurrent::Future. 4x faster CI for large eval suites.
570
+ - **Eval history & trending** - `report.save_history!` appends to JSONL. `report.eval_history` returns `EvalHistory` with `score_trend`, `drift?`, run-by-run scores.
571
+ - **Pipeline per-step eval** - `add_case(..., step_expectations: { classify: { priority: "high" } })`. See which step in a pipeline regressed.
572
+ - **Minitest support** - `assert_satisfies_contract`, `assert_eval_passes`, `stub_step` for Minitest users. `require "ruby_llm/contract/minitest"`.
540
573
 
541
574
  ### Game changer continuity
542
575
 
@@ -550,71 +583,71 @@ v0.4: "Show me the trend" → eval history (time series)
550
583
 
551
584
  ## 0.3.7 (2026-03-24)
552
585
 
553
- - **Trait missing key = error** — `expected_traits: { title: 0..5 }` on output `{}` now fails instead of silently passing.
554
- - **nil input in dynamic prompts** — `run(nil)` with `prompt { |input| ... }` correctly passes nil to block.
555
- - **Defensive sample pre-validation** — `sample_response` uses the same parser as runtime (handles code fences, BOM, prose around JSON).
556
- - **Baseline diff excludes skipped** — self-compare with skipped cases no longer shows artificial score delta.
557
- - **Zeitwerk eval/ ignore** — `eager_load_contract_dirs!` ignores `eval/` subdirs before eager load.
586
+ - **Trait missing key = error** - `expected_traits: { title: 0..5 }` on output `{}` now fails instead of silently passing.
587
+ - **nil input in dynamic prompts** - `run(nil)` with `prompt { |input| ... }` correctly passes nil to block.
588
+ - **Defensive sample pre-validation** - `sample_response` uses the same parser as runtime (handles code fences, BOM, prose around JSON).
589
+ - **Baseline diff excludes skipped** - self-compare with skipped cases no longer shows artificial score delta.
590
+ - **Zeitwerk eval/ ignore** - `eager_load_contract_dirs!` ignores `eval/` subdirs before eager load.
558
591
 
559
592
  ## 0.3.6 (2026-03-24)
560
593
 
561
- - **Recursive array/object validation** — nested arrays (`array of array of string`) validated recursively. Object items validated even without `:properties` (e.g. `additionalProperties: false`).
562
- - **Deep symbolize in sample pre-validation** — array samples with string keys (`[{"name" => "Alice"}]`) correctly symbolized before schema validation.
594
+ - **Recursive array/object validation** - nested arrays (`array of array of string`) validated recursively. Object items validated even without `:properties` (e.g. `additionalProperties: false`).
595
+ - **Deep symbolize in sample pre-validation** - array samples with string keys (`[{"name" => "Alice"}]`) correctly symbolized before schema validation.
563
596
 
564
597
  ## 0.3.5 (2026-03-24)
565
598
 
566
- - **String constraints in SchemaValidator** — `minLength`/`maxLength` enforced for root and nested strings.
567
- - **Array item validation** — scalar items (string, integer) validated against items schema type and constraints.
568
- - **Non-JSON sample_response fails fast** — `sample_response("hello")` with object schema raises ArgumentError at definition time instead of silently passing.
569
- - **`max_tokens` in KNOWN_CONTEXT_KEYS** — no more spurious "Unknown context keys" warning.
570
- - **Duplicate models deduplicated** — `compare_models(models: ["m", "m"])` runs model once.
599
+ - **String constraints in SchemaValidator** - `minLength`/`maxLength` enforced for root and nested strings.
600
+ - **Array item validation** - scalar items (string, integer) validated against items schema type and constraints.
601
+ - **Non-JSON sample_response fails fast** - `sample_response("hello")` with object schema raises ArgumentError at definition time instead of silently passing.
602
+ - **`max_tokens` in KNOWN_CONTEXT_KEYS** - no more spurious "Unknown context keys" warning.
603
+ - **Duplicate models deduplicated** - `compare_models(models: ["m", "m"])` runs model once.
571
604
 
572
605
  ## 0.3.4 (2026-03-24)
573
606
 
574
- - **SchemaValidator validates non-object roots** — boolean, integer, number, array root schemas now enforce type, min/max, enum, minItems/maxItems. Previously only object schemas were validated.
575
- - **Removed passing cases = regression** — `regressed?` returns true when baseline had passing cases that are now missing. Prevents gate bypass by deleting eval cases.
576
- - **JSON string sample_response fixed** — `sample_response('{"name":"Alice"}')` correctly parsed for pre-validation instead of double-encoding.
577
- - **`context[:max_tokens]` forwarded** — overrides step's `max_output` for adapter call AND budget precheck.
607
+ - **SchemaValidator validates non-object roots** - boolean, integer, number, array root schemas now enforce type, min/max, enum, minItems/maxItems. Previously only object schemas were validated.
608
+ - **Removed passing cases = regression** - `regressed?` returns true when baseline had passing cases that are now missing. Prevents gate bypass by deleting eval cases.
609
+ - **JSON string sample_response fixed** - `sample_response('{"name":"Alice"}')` correctly parsed for pre-validation instead of double-encoding.
610
+ - **`context[:max_tokens]` forwarded** - overrides step's `max_output` for adapter call AND budget precheck.
578
611
 
579
612
  ## 0.3.3 (2026-03-23)
580
613
 
581
- - **Skipped cases visible in regression diff** — baseline PASS → current SKIP now detected as regression by `without_regressions` and `fail_on_regression`.
582
- - **Skip only on missing adapter** — eval runner no longer masks evaluator errors as SKIP. Only "No adapter configured" triggers skip.
583
- - **Array/Hash sample pre-validation** — `sample_response([{...}])` correctly validated against schema instead of silently skipping.
584
- - **`assume_model_exists: false` forwarded** — boolean `false` no longer dropped by truthiness check in adapter options.
585
- - **Duplicate case names caught at definition** — `add_case`/`verify` with same name raises immediately, not at run time.
614
+ - **Skipped cases visible in regression diff** - baseline PASS → current SKIP now detected as regression by `without_regressions` and `fail_on_regression`.
615
+ - **Skip only on missing adapter** - eval runner no longer masks evaluator errors as SKIP. Only "No adapter configured" triggers skip.
616
+ - **Array/Hash sample pre-validation** - `sample_response([{...}])` correctly validated against schema instead of silently skipping.
617
+ - **`assume_model_exists: false` forwarded** - boolean `false` no longer dropped by truthiness check in adapter options.
618
+ - **Duplicate case names caught at definition** - `add_case`/`verify` with same name raises immediately, not at run time.
586
619
 
587
620
  ## 0.3.2 (2026-03-23)
588
621
 
589
- - **Array response preserved** — `Adapters::RubyLLM` no longer stringifies Array content. Steps with `output_type Array` work correctly.
590
- - **Falsy prompt input** — `run(false)` and `build_messages(false)` pass `false` to dynamic prompt blocks instead of falling back to `instance_eval`.
591
- - **`retry_on` flatten** — `retry_on([:a, :b])` no longer wraps in nested array.
592
- - **Builder reset** — `Prompt::Builder` resets nodes on each build (no accumulation on reuse).
593
- - **Pipeline false output** — `output: false` no longer shows "(no output)" in pretty_print.
622
+ - **Array response preserved** - `Adapters::RubyLLM` no longer stringifies Array content. Steps with `output_type Array` work correctly.
623
+ - **Falsy prompt input** - `run(false)` and `build_messages(false)` pass `false` to dynamic prompt blocks instead of falling back to `instance_eval`.
624
+ - **`retry_on` flatten** - `retry_on([:a, :b])` no longer wraps in nested array.
625
+ - **Builder reset** - `Prompt::Builder` resets nodes on each build (no accumulation on reuse).
626
+ - **Pipeline false output** - `output: false` no longer shows "(no output)" in pretty_print.
594
627
 
595
628
  ## 0.3.1 (2026-03-23)
596
629
 
597
630
  Fixes from persona_tool production deployment (4 services migrated).
598
631
 
599
- - **Proc/Lambda in `expected_traits`** — `expected_traits: { score: ->(v) { v > 3 } }` now works.
600
- - **Zeitwerk eager-load** — `load_evals!` eager-loads `app/contracts/` and `app/steps/` before loading eval files. Fixes uninitialized constant errors in Rake tasks.
601
- - **Falsy values** — `expected: false`, `input: false`, `sample_response(nil)` all handled correctly.
602
- - **Context key forwarding** — `provider:` and `assume_model_exists:` forwarded to adapter. `schema:` and `max_tokens:` are step-level only (no split-brain).
603
- - **Deep-freeze immutability** — constructors never mutate caller's data.
632
+ - **Proc/Lambda in `expected_traits`** - `expected_traits: { score: ->(v) { v > 3 } }` now works.
633
+ - **Zeitwerk eager-load** - `load_evals!` eager-loads `app/contracts/` and `app/steps/` before loading eval files. Fixes uninitialized constant errors in Rake tasks.
634
+ - **Falsy values** - `expected: false`, `input: false`, `sample_response(nil)` all handled correctly.
635
+ - **Context key forwarding** - `provider:` and `assume_model_exists:` forwarded to adapter. `schema:` and `max_tokens:` are step-level only (no split-brain).
636
+ - **Deep-freeze immutability** - constructors never mutate caller's data.
604
637
 
605
638
  ## 0.3.0 (2026-03-23)
606
639
 
607
- Baseline regression detection — know when quality drops before users do.
640
+ Baseline regression detection - know when quality drops before users do.
608
641
 
609
642
  ### Features
610
643
 
611
- - **`report.save_baseline!`** — serialize eval results to `.eval_baselines/` (JSON, git-tracked)
612
- - **`report.compare_with_baseline`** — returns `BaselineDiff` with regressions, improvements, score_delta, new/removed cases
613
- - **`diff.regressed?`** — true when any previously-passing case now fails
614
- - **`without_regressions` RSpec chain** — `expect(Step).to pass_eval("x").without_regressions`
615
- - **RakeTask `fail_on_regression`** — blocks CI when regressions detected
616
- - **RakeTask `save_baseline`** — auto-save after successful run
617
- - **Migration guide** — `docs/guide/migration.md` with 7 patterns for adopting the gem in existing Rails apps
644
+ - **`report.save_baseline!`** - serialize eval results to `.eval_baselines/` (JSON, git-tracked)
645
+ - **`report.compare_with_baseline`** - returns `BaselineDiff` with regressions, improvements, score_delta, new/removed cases
646
+ - **`diff.regressed?`** - true when any previously-passing case now fails
647
+ - **`without_regressions` RSpec chain** - `expect(Step).to pass_eval("x").without_regressions`
648
+ - **RakeTask `fail_on_regression`** - blocks CI when regressions detected
649
+ - **RakeTask `save_baseline`** - auto-save after successful run
650
+ - **Migration guide** - `docs/guide/migration.md` with 7 patterns for adopting the gem in existing Rails apps
618
651
 
619
652
  ### Stats
620
653
 
@@ -624,21 +657,21 @@ Baseline regression detection — know when quality drops before users do.
624
657
 
625
658
  Production hardening from senior Rails review panel.
626
659
 
627
- - **`around_call` propagates exceptions** — no longer silently swallows DB errors, timeouts, etc. User who wants swallowing can rescue in their block.
628
- - **Nil section content skipped** — `section "X", nil` no longer renders `"null"` to the LLM. Section is omitted entirely.
629
- - **Range support in `expected:`** — `expected: { score: 1..5 }` works in `add_case`. Previously only Regexp was supported.
630
- - **`Trace#dig`** — `trace.dig(:usage, :input_tokens)` works on both Step and Pipeline traces.
660
+ - **`around_call` propagates exceptions** - no longer silently swallows DB errors, timeouts, etc. User who wants swallowing can rescue in their block.
661
+ - **Nil section content skipped** - `section "X", nil` no longer renders `"null"` to the LLM. Section is omitted entirely.
662
+ - **Range support in `expected:`** - `expected: { score: 1..5 }` works in `add_case`. Previously only Regexp was supported.
663
+ - **`Trace#dig`** - `trace.dig(:usage, :input_tokens)` works on both Step and Pipeline traces.
631
664
 
632
665
  ## 0.2.2 (2026-03-23)
633
666
 
634
667
  Fixes from first real-world integration (persona_tool).
635
668
 
636
- - **`around_call` fires per-run** — not per-attempt. With retry_policy, callback fires once with final result. Signature: `around_call { |step, input, result| ... }`
637
- - **`Result#trace` always `Trace` object** — never bare Hash. `result.trace.model` works on success AND failure.
638
- - **`around_call` exception safe** — warns and returns result instead of crashing.
639
- - **`model` DSL** — `model "gpt-4o-mini"` per-step. Priority: context > step DSL > global config.
640
- - **Test adapter `raw_output` always String** — Hash/Array normalized to `.to_json`.
641
- - **`Trace#dig`** — `trace.dig(:usage, :input_tokens)` works.
669
+ - **`around_call` fires per-run** - not per-attempt. With retry_policy, callback fires once with final result. Signature: `around_call { |step, input, result| ... }`
670
+ - **`Result#trace` always `Trace` object** - never bare Hash. `result.trace.model` works on success AND failure.
671
+ - **`around_call` exception safe** - warns and returns result instead of crashing.
672
+ - **`model` DSL** - `model "gpt-4o-mini"` per-step. Priority: context > step DSL > global config.
673
+ - **Test adapter `raw_output` always String** - Hash/Array normalized to `.to_json`.
674
+ - **`Trace#dig`** - `trace.dig(:usage, :input_tokens)` works.
642
675
 
643
676
  ## 0.2.1 (2026-03-23)
644
677
 
@@ -646,18 +679,18 @@ Production DX improvements from first real-world integration (persona_tool).
646
679
 
647
680
  ### Features
648
681
 
649
- - **`temperature` DSL** — `temperature 0.3` in step definition, overridable via `context: { temperature: 0.7 }`. RubyLLM handles per-model normalization natively.
650
- - **`around_call` hook** — callback for logging, metrics, observability. Replaces need for custom middleware.
651
- - **`build_messages` public** — inspect rendered prompt without running the step.
652
- - **`stub_step` RSpec helper** — `stub_step(MyStep, response: { ... })` reduces test boilerplate. Auto-included via `require "ruby_llm/contract/rspec"`.
653
- - **`estimate_cost` / `estimate_eval_cost`** — predict spend before API calls.
682
+ - **`temperature` DSL** - `temperature 0.3` in step definition, overridable via `context: { temperature: 0.7 }`. RubyLLM handles per-model normalization natively.
683
+ - **`around_call` hook** - callback for logging, metrics, observability. Replaces need for custom middleware.
684
+ - **`build_messages` public** - inspect rendered prompt without running the step.
685
+ - **`stub_step` RSpec helper** - `stub_step(MyStep, response: { ... })` reduces test boilerplate. Auto-included via `require "ruby_llm/contract/rspec"`.
686
+ - **`estimate_cost` / `estimate_eval_cost`** - predict spend before API calls.
654
687
 
655
688
  ### Fixes
656
689
 
657
- - **Reload lifecycle** — `load_evals!` clears definitions before re-loading. Railtie hooks `config.to_prepare` for development reload. `define_eval` warns on duplicate name (suppressed during reload).
658
- - **Pipeline eval cost** — uses `Pipeline::Trace#total_cost` (all steps), not just last step.
659
- - **Adapter isolation** — `compare_models` and `run_all_own_evals` deep-dup context per run.
660
- - **Offline mode** — cases without adapter return `:skipped` instead of crashing. Skipped cases excluded from score.
690
+ - **Reload lifecycle** - `load_evals!` clears definitions before re-loading. Railtie hooks `config.to_prepare` for development reload. `define_eval` warns on duplicate name (suppressed during reload).
691
+ - **Pipeline eval cost** - uses `Pipeline::Trace#total_cost` (all steps), not just last step.
692
+ - **Adapter isolation** - `compare_models` and `run_all_own_evals` deep-dup context per run.
693
+ - **Offline mode** - cases without adapter return `:skipped` instead of crashing. Skipped cases excluded from score.
661
694
  - **`expected_traits`** reachable from `define_eval` DSL via `add_case`.
662
695
  - **`verify`** raises when both positional and `expect:` keyword provided.
663
696
  - **`best_for`** excludes zero-score models from recommendation.
@@ -687,28 +720,28 @@ Contracts for LLM quality. Know which model to use, what it costs, and when accu
687
720
 
688
721
  ### Features
689
722
 
690
- - **`add_case` in `define_eval`** — `add_case "billing", input: "...", expected: { priority: "high" }` with partial matching. Supports `expected_traits:` for regex/range matching.
691
- - **`CaseResult` value objects** — `result.name`, `result.passed?`, `result.output`, `result.expected`, `result.mismatches` (structured diff), `result.cost`, `result.duration_ms`.
692
- - **`report.failures`** — returns only failed cases. `report.skipped` counts skipped (offline) cases.
693
- - **Model comparison** — `Step.compare_models("eval", models: %w[nano mini full])` runs same eval across models. Returns table with score/cost/latency per model. `comparison.best_for(min_score: 0.95)` returns cheapest model meeting threshold.
694
- - **Cost tracking** — `report.total_cost`, `report.avg_latency_ms`, per-case `result.cost`. Pipeline eval uses total pipeline cost, not just last step.
695
- - **Cost prediction** — `Step.estimate_cost(input:, model:)` and `Step.estimate_eval_cost("eval", models: [...])` predict spend before API calls.
696
- - **CI gating** — `pass_eval("regression").with_minimum_score(0.8).with_maximum_cost(0.01)`. RakeTask with suite-level `minimum_score` and `maximum_cost`.
697
- - **`RubyLLM::Contract.run_all_evals`** — discovers all Steps/Pipelines with evals, runs them all. Includes inherited evals.
698
- - **`RubyLLM::Contract::RakeTask`** — `rake ruby_llm_contract:eval` with `minimum_score`, `maximum_cost`, `fail_on_empty`, `eval_dirs`.
699
- - **Rails Railtie** — auto-loads eval files via `config.after_initialize` + `config.to_prepare` (supports development reload).
700
- - **Offline mode** — cases without adapter return `:skipped` instead of crashing. Skipped cases excluded from score/passed.
701
- - **Safe `define_eval`** — warns on duplicate name; suppressed during reload.
723
+ - **`add_case` in `define_eval`** - `add_case "billing", input: "...", expected: { priority: "high" }` with partial matching. Supports `expected_traits:` for regex/range matching.
724
+ - **`CaseResult` value objects** - `result.name`, `result.passed?`, `result.output`, `result.expected`, `result.mismatches` (structured diff), `result.cost`, `result.duration_ms`.
725
+ - **`report.failures`** - returns only failed cases. `report.skipped` counts skipped (offline) cases.
726
+ - **Model comparison** - `Step.compare_models("eval", models: %w[nano mini full])` runs same eval across models. Returns table with score/cost/latency per model. `comparison.best_for(min_score: 0.95)` returns cheapest model meeting threshold.
727
+ - **Cost tracking** - `report.total_cost`, `report.avg_latency_ms`, per-case `result.cost`. Pipeline eval uses total pipeline cost, not just last step.
728
+ - **Cost prediction** - `Step.estimate_cost(input:, model:)` and `Step.estimate_eval_cost("eval", models: [...])` predict spend before API calls.
729
+ - **CI gating** - `pass_eval("regression").with_minimum_score(0.8).with_maximum_cost(0.01)`. RakeTask with suite-level `minimum_score` and `maximum_cost`.
730
+ - **`RubyLLM::Contract.run_all_evals`** - discovers all Steps/Pipelines with evals, runs them all. Includes inherited evals.
731
+ - **`RubyLLM::Contract::RakeTask`** - `rake ruby_llm_contract:eval` with `minimum_score`, `maximum_cost`, `fail_on_empty`, `eval_dirs`.
732
+ - **Rails Railtie** - auto-loads eval files via `config.after_initialize` + `config.to_prepare` (supports development reload).
733
+ - **Offline mode** - cases without adapter return `:skipped` instead of crashing. Skipped cases excluded from score/passed.
734
+ - **Safe `define_eval`** - warns on duplicate name; suppressed during reload.
702
735
 
703
736
  ### Fixes
704
737
 
705
- - **P1: Eval files not autoloaded by Rails** — Railtie uses `load` (not Zeitwerk). Hooks into reloader for dev.
706
- - **P2: report.results returns raw Hashes** — now returns `CaseResult` objects.
707
- - **P3: No way to run all evals at once** — `Contract.run_all_evals` + Rake task.
708
- - **P4: String vs symbol key mismatch** — warns when `validate` or `verify` proc returns nil.
709
- - **Pipeline eval cost** — uses `Pipeline::Trace#total_cost` (all steps), not just last step.
710
- - **Reload lifecycle** — `load_evals!` clears definitions before re-loading. Registry filters stale hosts.
711
- - **Adapter isolation** — `compare_models` and `run_all_own_evals` deep-dup context per run.
738
+ - **P1: Eval files not autoloaded by Rails** - Railtie uses `load` (not Zeitwerk). Hooks into reloader for dev.
739
+ - **P2: report.results returns raw Hashes** - now returns `CaseResult` objects.
740
+ - **P3: No way to run all evals at once** - `Contract.run_all_evals` + Rake task.
741
+ - **P4: String vs symbol key mismatch** - warns when `validate` or `verify` proc returns nil.
742
+ - **Pipeline eval cost** - uses `Pipeline::Trace#total_cost` (all steps), not just last step.
743
+ - **Reload lifecycle** - `load_evals!` clears definitions before re-loading. Registry filters stale hosts.
744
+ - **Adapter isolation** - `compare_models` and `run_all_own_evals` deep-dup context per run.
712
745
 
713
746
  ### Verified with real API
714
747
 
@@ -731,16 +764,16 @@ Initial release.
731
764
 
732
765
  ### Features
733
766
 
734
- - **Step abstraction** — `RubyLLM::Contract::Step::Base` with prompt DSL, typed input/output
735
- - **Output schema** — declarative structure via ruby_llm-schema, sent to provider for enforcement
736
- - **Validate** — business logic checks (1-arity and 2-arity with input cross-validation)
737
- - **Retry with model escalation** — start cheap, auto-escalate on contract failure or network error
738
- - **Preflight limits** — `max_input`, `max_cost`, `max_output` refuse before calling the LLM
739
- - **Pipeline** — multi-step composition with fail-fast, timeout, token budget
740
- - **Eval** — offline contract verification with `define_eval`, `run_eval`, zero-verify auto-case
741
- - **Adapters** — RubyLLM (production), Test (deterministic specs)
742
- - **RSpec matchers** — `satisfy_contract`, `pass_eval`
743
- - **Structured trace** — model, latency, tokens, cost, attempt log per step
767
+ - **Step abstraction** - `RubyLLM::Contract::Step::Base` with prompt DSL, typed input/output
768
+ - **Output schema** - declarative structure via ruby_llm-schema, sent to provider for enforcement
769
+ - **Validate** - business logic checks (1-arity and 2-arity with input cross-validation)
770
+ - **Retry with model escalation** - start cheap, auto-escalate on contract failure or network error
771
+ - **Preflight limits** - `max_input`, `max_cost`, `max_output` refuse before calling the LLM
772
+ - **Pipeline** - multi-step composition with fail-fast, timeout, token budget
773
+ - **Eval** - offline contract verification with `define_eval`, `run_eval`, zero-verify auto-case
774
+ - **Adapters** - RubyLLM (production), Test (deterministic specs)
775
+ - **RSpec matchers** - `satisfy_contract`, `pass_eval`
776
+ - **Structured trace** - model, latency, tokens, cost, attempt log per step
744
777
 
745
778
  ### Robustness
746
779