ruby_llm-contract 1.0.0 → 1.1.1

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.
Files changed (36) hide show
  1. checksums.yaml +4 -4
  2. data/.ruby-version +1 -0
  3. data/CHANGELOG.md +287 -224
  4. data/README.md +1 -1
  5. data/docs/guide/getting_started.md +3 -1
  6. data/docs/guide/testing.md +1 -1
  7. data/lib/ruby_llm/contract/concerns/eval_host.rb +2 -2
  8. data/lib/ruby_llm/contract/cost_calculator.rb +5 -4
  9. data/lib/ruby_llm/contract/eval/aggregated_report.rb +4 -0
  10. data/lib/ruby_llm/contract/eval/baseline_diff.rb +19 -2
  11. data/lib/ruby_llm/contract/eval/case_executor.rb +1 -1
  12. data/lib/ruby_llm/contract/eval/case_result.rb +12 -3
  13. data/lib/ruby_llm/contract/eval/case_result_builder.rb +2 -1
  14. data/lib/ruby_llm/contract/eval/evaluator/proc_evaluator.rb +6 -2
  15. data/lib/ruby_llm/contract/eval/prompt_diff_serializer.rb +1 -1
  16. data/lib/ruby_llm/contract/eval/recommender.rb +2 -2
  17. data/lib/ruby_llm/contract/eval/report.rb +5 -2
  18. data/lib/ruby_llm/contract/eval/report_stats.rb +7 -2
  19. data/lib/ruby_llm/contract/eval/report_storage.rb +6 -6
  20. data/lib/ruby_llm/contract/eval/step_expectation_applier.rb +2 -1
  21. data/lib/ruby_llm/contract/eval/unknown_cost_gate.rb +32 -0
  22. data/lib/ruby_llm/contract/eval.rb +1 -0
  23. data/lib/ruby_llm/contract/minitest.rb +6 -1
  24. data/lib/ruby_llm/contract/pipeline/trace.rb +7 -0
  25. data/lib/ruby_llm/contract/railtie.rb +1 -1
  26. data/lib/ruby_llm/contract/rake_task/suite_gate.rb +19 -10
  27. data/lib/ruby_llm/contract/rake_task.rb +9 -3
  28. data/lib/ruby_llm/contract/rspec/pass_eval.rb +80 -52
  29. data/lib/ruby_llm/contract/step/base.rb +6 -4
  30. data/lib/ruby_llm/contract/step/dsl.rb +5 -14
  31. data/lib/ruby_llm/contract/step/runner_config.rb +2 -2
  32. data/lib/ruby_llm/contract/step/trace.rb +19 -0
  33. data/lib/ruby_llm/contract/unknown_policy.rb +21 -0
  34. data/lib/ruby_llm/contract/version.rb +1 -1
  35. data/lib/ruby_llm/contract.rb +17 -4
  36. metadata +4 -1
data/CHANGELOG.md CHANGED
@@ -1,16 +1,79 @@
1
1
  # Changelog
2
2
 
3
- ## 1.0.0 (2026-09-27)
3
+ ## 1.1.1 (2026-10-10)
4
+
5
+ ### Fixed
6
+
7
+ - **A failed rake eval gate printed "Eval suite FAILED: Eval suite FAILED".** The
8
+ message now reads "Eval suite FAILED: one or more evals did not pass".
9
+
10
+ ### Changed (internal, no API change)
11
+
12
+ - Values that two or more places must agree on now have one owner, so one side can no
13
+ longer drift alone: the `:refuse`/`:warn` modes and their default for every
14
+ `on_unknown_*` option (`UnknownPolicy`), the Rails contract and eval dirs that the
15
+ Railtie ignores and `load_evals!` loads, the reload flag, the `:skipped` step status
16
+ (`CaseResult::SKIPPED_STATUS`), baseline and history file extensions, the context keys
17
+ forwarded to the adapter, the generic "passed"/"not passed" details the report hides,
18
+ and the optimize task's `MIN_SCORE` default, which now reads `Eval::DEFAULT_MIN_SCORE`.
19
+ The unknown-context-key warning lists the known keys in a different order, and in a
20
+ Rails app `load_evals!` now loads `app/contracts/eval` before `app/steps/eval` (the order
21
+ the Railtie and eager loading already used); this matters only if both dirs define an
22
+ eval of the same name on the same class, where the later file wins.
23
+
24
+ ### Tests
25
+
26
+ - A real attachment through the RubyLLM 2.x adapter with HTTP intercepted (webmock):
27
+ pins the `input_image` part on the wire and the usage read back.
28
+ - A minimal Rails app booted in a child process: pins that Zeitwerk ignores the
29
+ `eval/` dirs, that evals register after boot, and that the rake tasks appear.
30
+ - `rubocop` is pinned to `~> 1.92.0`: CI resolves without a lockfile, so a floating
31
+ version let new cops land on CI before they ran locally.
32
+
33
+ ## 1.1.0 (2026-10-10)
34
+
35
+ ### Changed - may turn a green CI red
36
+
37
+ - **Eval cost gates now fail closed on unknown pricing.** `pass_eval(...).with_maximum_cost`,
38
+ `RakeTask#maximum_cost` and `assert_eval_passes(maximum_cost:)` compared the report's
39
+ `total_cost`, which counts a case it cannot price as $0. An eval running on a model
40
+ without pricing data (a local or fine-tuned model) therefore passed any budget. The
41
+ gates now fail and name the unpriced cases, matching what step-level `max_cost`
42
+ already did. Opt out with `.on_unknown_pricing(:warn)`, `t.on_unknown_pricing = :warn`
43
+ or `on_unknown_pricing: :warn`: the budget is then checked against the priced cases
44
+ and a warning lists the rest. Offline runs (`sample_response`, a `Test` adapter
45
+ without `usage:`) report zero tokens and are never flagged. Only gates with a
46
+ maximum cost set are affected.
47
+
48
+ ### Added
49
+
50
+ - `Report#unknown_cost_results` (also on `AggregatedReport`), `CaseResult#cost_unknown?`,
51
+ and `cost_unknown?` on step and pipeline traces. A retried step is judged per attempt,
52
+ so a priced subtotal no longer hides an unpriced attempt. `CaseResult#to_h` gains a
53
+ `cost_unknown: true` key only for flagged cases; baseline files are unchanged.
54
+
55
+ ### Fixed
56
+
57
+ - **A previously passing case that was skipped (no adapter) is reported as `SKIPPED`,
58
+ not `REGRESSED`.** The regression gate still fails on it - a skip is no evidence the
59
+ case still passes - but the report no longer showed an unchanged score next to a
60
+ "regression". Applies to `BaselineDiff#to_s` (rake task output) and the
61
+ `without_regressions` failure message; new `BaselineDiff#skipped_passing_cases`.
62
+ - A code comment in `CostCalculator` claimed an unreadable pricing shape refuses budgeted
63
+ calls "with no error"; the refusal does carry an error, it just names missing pricing
64
+ as the cause.
65
+
66
+ ## 1.0.0 (2026-10-10)
4
67
 
5
68
  **Requires `ruby_llm ~> 2.0`.** This is the only breaking change: it is a
6
69
  dependency requirement, not a change to this gem's API. Your call sites,
7
70
  `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.
71
+ untouched - if you are on ruby_llm 2.x, upgrading should need no code edits.
9
72
 
10
73
  1.0 also states what is now stable: the documented DSL, the `Result`/`trace`
11
74
  shapes including `trace[:usage]`'s `{ input_tokens:, output_tokens: }` keys, and
12
75
  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.
76
+ require a major version here - that is what this release is.
14
77
 
15
78
  ### Added
16
79
 
@@ -36,7 +99,7 @@ require a major version here — that is what this release is.
36
99
  - **`ruby_llm-schema` replaced by `schematist ~> 1.1`.** `ruby_llm-schema` 1.0.0 is
37
100
  31 lines that emit a deprecation warning and alias `RubyLLM::Schema =
38
101
  Schematist::Schema`; ruby_llm 2.x depends on schematist directly. The
39
- `output_schema do ... end` DSL is unchanged — same object behind a different
102
+ `output_schema do ... end` DSL is unchanged - same object behind a different
40
103
  constant.
41
104
  - **Adapter reads token counts from `Message#tokens`.** RubyLLM 2.0 replaced
42
105
  `Message#input_tokens`/`#output_tokens` with a `Tokens` value object. This is the
@@ -71,7 +134,7 @@ require a major version here — that is what this release is.
71
134
  `input_price_per_million` / `output_price_per_million` readers on `Model` for a
72
135
  nested `pricing -> text_tokens -> standard` walk. Because `CostCalculator`
73
136
  rescued `StandardError` into a nil cost, every priced model silently became
74
- "unknown pricing" — and since `max_cost` fails closed on unknown pricing, every
137
+ "unknown pricing" - and since `max_cost` fails closed on unknown pricing, every
75
138
  budgeted call would have been refused. Pricing extraction is now explicit for
76
139
  both shapes (upstream models and locally `register_model`-ed ones), and an
77
140
  unrecognised shape returns nil rather than a swallowed exception.
@@ -91,33 +154,33 @@ Result of a 20-pass systematic audit of the whole repository. No API changes and
91
154
 
92
155
  ### Changed
93
156
 
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.
157
+ - **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
158
  - **`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.
159
+ - **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
160
 
98
161
  ### Fixed
99
162
 
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.
163
+ - **`.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.)
164
+ - **`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.
165
+ - **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`.
166
+ - **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
167
  - **`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.
168
+ - **`docs/architecture.md` was reachable from nowhere** - the only one of 16 tracked docs with no inbound link. Added to the README index.
106
169
 
107
170
  ### Removed
108
171
 
109
172
  - 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.
173
+ - 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
174
  - 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
175
 
113
176
  ## 0.10.6 (2026-06-11)
114
177
 
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.
178
+ 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
179
 
117
180
  ### Fixed
118
181
 
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.
182
+ - **`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).
183
+ - **`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
184
 
122
185
  ## 0.10.5 (2026-06-11)
123
186
 
@@ -125,21 +188,21 @@ Docs release: new `llm_judge.md` guide + comprehensive clarity audit across all
125
188
 
126
189
  ### Added
127
190
 
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.
191
+ - **`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
192
 
130
193
  ### Fixed
131
194
 
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).
195
+ - **`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.
196
+ - **`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)`.
197
+ - **`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.
198
+ - **`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.
199
+ - **`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.
200
+ - **`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.
201
+ - **`docs/guide/best_practices.md`** - explained `rule` as a prompt DSL element distinct from `system` / `user` with a link to `prompt_ast.md`.
202
+ - **`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).
203
+ - **`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`).
204
+ - **`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).
205
+ - **`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
206
 
144
207
  ### Audit method
145
208
 
@@ -151,23 +214,23 @@ Patch release: the `ruby_llm_contract:optimize` rake task now auto-loads in Rail
151
214
 
152
215
  ### Fixed
153
216
 
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`.
217
+ - **`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).
218
+ - **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
219
 
157
220
  ## 0.10.3 (2026-06-10)
158
221
 
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.
222
+ 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
223
 
161
224
  ### Fixed
162
225
 
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:
226
+ - **`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
227
  - `type: ["string", "null"]` (array form)
165
228
  - `type: "null"` (degenerate scalar form)
166
229
  - `anyOf: [{type: "string"}, {type: "null"}]` and `oneOf` equivalents
167
230
 
168
231
  **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
232
 
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.
233
+ 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
234
 
172
235
  ## 0.10.2 (2026-06-10)
173
236
 
@@ -197,7 +260,7 @@ First published release since 0.8.0. Consolidates work originally tagged as 0.9.
197
260
 
198
261
  ### Breaking changes
199
262
 
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.
263
+ - **`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
264
 
202
265
  ### Migration
203
266
 
@@ -213,9 +276,9 @@ validate("score in range 0-100") { |o| o[:score].between?(0, 100) }
213
276
 
214
277
  ### Added
215
278
 
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.
279
+ - **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).
280
+ - **`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.
281
+ - **`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
282
 
220
283
  ### Behavioural change (READ BEFORE UPGRADING)
221
284
 
@@ -223,13 +286,13 @@ validate("score in range 0-100") { |o| o[:score].between?(0, 100) }
223
286
 
224
287
  ### Changed
225
288
 
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.
289
+ - **`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.
290
+ - **`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
291
 
229
292
  ### Fixed
230
293
 
231
294
  - **`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:)`.
295
+ - **`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
296
  - **`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
297
 
235
298
  ### Internal
@@ -239,9 +302,9 @@ validate("score in range 0-100") { |o| o[:score].between?(0, 100) }
239
302
 
240
303
  ### Deferred (not in 0.10.x)
241
304
 
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.
305
+ - `add_history` multi-turn replay of prior attachments - single-turn multimodal supported; follow-up questions on the same document deferred to a later release.
306
+ - Streaming + attachment - contract steps remain synchronous.
307
+ - Provider-specific attachment size caps - surface only via `attachment_token_estimate` calibration; consult provider docs.
245
308
 
246
309
  ### Tests
247
310
 
@@ -253,20 +316,20 @@ Narrative repositioning + small API additions. Internal architecture unchanged:
253
316
 
254
317
  ### Added
255
318
 
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.
319
+ - **`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.
320
+ - **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
321
 
259
322
  ### Dependencies
260
323
 
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.
324
+ - **`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
325
 
263
326
  ### Changed
264
327
 
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.
328
+ - **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.
329
+ - **`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.
330
+ - **`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`.
331
+ - **`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.
332
+ - **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
333
 
271
334
  ### Documentation
272
335
 
@@ -275,30 +338,30 @@ Narrative repositioning + small API additions. Internal architecture unchanged:
275
338
 
276
339
  ### Issues closed
277
340
 
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.
341
+ - **#11** (Optimizer is blind to same-model attempts) - closed after empirical experiments. `attempts: N` retry stays in API; not marketed as a default.
342
+ - **#6** (Production cost reporting) - already implemented in 0.7.x; close confirmed.
280
343
 
281
344
  ### Not in this release (deferred)
282
345
 
283
346
  - `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.
347
+ - 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
348
 
286
349
  ## 0.7.3 (2026-04-24)
287
350
 
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.
351
+ 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
352
 
290
353
  ### Documentation
291
354
 
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.
355
+ - **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.
356
+ - **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.
357
+ - **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.).
358
+ - **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`).
359
+ - **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`.
360
+ - **Industry-standard terminology** - `temperature-locked` → `fixed-temperature`, `variance-induced` → `sampling variance`, `severity signals` → `severity keywords`, `takeaway drift` → `tone/takeaways mismatch`.
361
+ - **`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`.
362
+ - **Business framing added to guides** - every guide opens with a concrete production scenario or "why it matters" hook before the API reference.
300
363
 
301
- ### Examples — consolidated on `SummarizeArticle`, renumbered 00-06
364
+ ### Examples - consolidated on `SummarizeArticle`, renumbered 00-06
302
365
 
303
366
  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
367
 
@@ -314,19 +377,19 @@ The previous 12-file set mixed a private Reddit promo planner, customer support,
314
377
 
315
378
  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
379
 
317
- ### Examples — bug fixes carried along
380
+ ### Examples - bug fixes carried along
318
381
 
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.
382
+ - **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`.
383
+ - **`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
384
 
322
385
  ### Testing
323
386
 
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.
387
+ - **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
388
 
326
389
  ### Deleted (private-project cleanup)
327
390
 
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.
391
+ - `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.
392
+ - `examples/02_output_schema.rb` - fully covered by `docs/guide/output_schema.md`; deleting avoids duplication.
330
393
 
331
394
  ## 0.7.2 (2026-04-22)
332
395
 
@@ -336,24 +399,24 @@ Every file carries an "Expected output" block in its header so readers see the r
336
399
 
337
400
  ### Documentation
338
401
 
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.
402
+ - **`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.
403
+ - **`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.
404
+ - **`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.
405
+ - **`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`.
406
+ - **`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.
407
+ - **`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
408
 
346
409
  ## 0.7.1 (2026-04-22)
347
410
 
348
411
  ### Changed (behavioral, follow-up to v0.7.0)
349
412
 
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.
413
+ - **`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
414
 
352
415
  ## 0.7.0 (2026-04-21)
353
416
 
354
417
  ### Breaking changes
355
418
 
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.
419
+ - **`: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
420
  - **`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
421
 
359
422
  ### Migration
@@ -380,43 +443,43 @@ end
380
443
 
381
444
  ### Features
382
445
 
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.
446
+ - **`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.
447
+ - **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:`.
448
+ - **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.
449
+ - **`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
450
 
388
451
  ### Scope
389
452
 
390
453
  - 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.
454
+ - 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.
455
+ - **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
456
 
394
457
  ### Documentation
395
458
 
396
- - **Guide: [Production-mode cost measurement](docs/guide/optimizing_retry_policy.md#measure-effective-cost-before-shipping)** — API, metric interpretation, 2-tier scope note.
459
+ - **Guide: [Production-mode cost measurement](docs/guide/optimizing_retry_policy.md#measure-effective-cost-before-shipping)** - API, metric interpretation, 2-tier scope note.
397
460
 
398
461
  ## 0.6.3 (2026-04-20)
399
462
 
400
463
  ### Features
401
464
 
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.
465
+ - **`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.
466
+ - **`RUNS=N` on `rake ruby_llm_contract:optimize`** - CLI flag for variance-aware optimization.
467
+ - **`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`.
468
+ - **Guide: [Reducing variance with `runs:`](docs/guide/optimizing_retry_policy.md)** - when to use it and why.
406
469
 
407
470
  ## 0.6.2 (2026-04-18)
408
471
 
409
472
  ### Features
410
473
 
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.
474
+ - **`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).
475
+ - **`rake ruby_llm_contract:optimize`** - one-command retry chain optimization. Prints score table, constraining eval, suggested chain, and copy-paste DSL.
476
+ - **Offline by default** - `optimize` uses `sample_response` (zero API calls) unless `LIVE=1` or `PROVIDER=` is set.
477
+ - **`EVAL_DIRS=` support** - non-Rails setups can specify eval file directories.
478
+ - **Guide: [Optimizing retry_policy](docs/guide/optimizing_retry_policy.md)** - full procedure with prerequisites, troubleshooting, and real-world example.
416
479
 
417
480
  ### Fixes
418
481
 
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.
482
+ - 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
483
  - Removed ActiveSupport dependency from rake task (`.presence` → `.empty?`).
421
484
  - Added `require "set"` for non-Rails environments.
422
485
 
@@ -424,22 +487,22 @@ end
424
487
 
425
488
  ### Features
426
489
 
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 = ... }`).
490
+ - **Multi-provider operator tooling** - rake tasks support `PROVIDER=openai|anthropic|ollama` and `CANDIDATES=model@effort,...`.
491
+ - **`rake ruby_llm_contract:recommend`** - wraps `Step.recommend` with CLI interface, prints best config, retry chain, DSL, rationale, and savings.
492
+ - **Ollama support** - `PROVIDER=ollama` (base URL via `RubyLLM.configure { |c| c.ollama_api_base = ... }`).
430
493
 
431
494
  ## 0.6.0 (2026-04-12)
432
495
 
433
- "What should I do?" — model + configuration recommendation.
496
+ "What should I do?" - model + configuration recommendation.
434
497
 
435
498
  ### Features
436
499
 
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.
500
+ - **`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.
501
+ - **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"`.
502
+ - **`compare_models` extended** - new `candidates:` parameter alongside existing `models:` (backward compatible). Candidate labels include reasoning effort in output table.
503
+ - **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.
504
+ - **`pass_rate_ratio`** - numeric float (0.0–1.0) on `Report` and `ReportStats`, complementing the string `pass_rate` (`"3/5"`).
505
+ - **History entries enriched** - `save_history!` accepts `reasoning_effort:` and stores `model`, `reasoning_effort`, `pass_rate_ratio` in JSONL entries.
443
506
 
444
507
  ### Game changer continuity
445
508
 
@@ -455,7 +518,7 @@ v0.6: "What should I do?" → recommend (actionable advice)
455
518
 
456
519
  ### Features
457
520
 
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.
521
+ - **`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
522
 
460
523
  ## 0.5.0 (2026-03-25)
461
524
 
@@ -463,9 +526,9 @@ Data-Driven Prompt Engineering.
463
526
 
464
527
  ### Features
465
528
 
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.
529
+ - **`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.
530
+ - **`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.
531
+ - **RSpec `compared_with` chain** - `expect(StepV2).to pass_eval("x").compared_with(StepV1).without_regressions` blocks merge if new prompt regresses any case.
469
532
 
470
533
  ### Game changer continuity
471
534
 
@@ -478,25 +541,25 @@ v0.5: "Which prompt is better?" → compare_with (A/B testing)
478
541
 
479
542
  ## 0.4.5 (2026-03-24)
480
543
 
481
- Audit hardening — 18 bugs fixed across 4 audit rounds.
544
+ Audit hardening - 18 bugs fixed across 4 audit rounds.
482
545
 
483
546
  ### Fixes
484
547
 
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.
548
+ - **RakeTask history before abort** - `track_history` now saves all reports (pass and fail) before gating, so failed runs appear in eval history.
549
+ - **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`.
550
+ - **StepAdapterOverride** - handles `context: nil` and respects string key `"adapter"`. Moved to `contract.rb` so both test frameworks share one mechanism.
551
+ - **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.
552
+ - **reset_configuration! clears overrides** - `step_adapter_overrides` now cleared on reset.
553
+ - **CostCalculator.register_model** - validates `Numeric`, `finite?`, non-negative. Rejects NaN, Infinity, strings, nil.
554
+ - **Pipeline token_budget** - rejects negative and zero values (parity with `timeout_ms`).
555
+ - **track_history model fallback** - uses step DSL `model`, then `default_model` when context has no model. Handles string key `"model"`.
556
+ - **estimate_cost / estimate_eval_cost** - falls back to step DSL model when no explicit model arg given.
557
+ - **stub_steps string keys** - both RSpec and Minitest normalize string-keyed options with `transform_keys(:to_sym)`.
558
+ - **DSL `:default` reset** - `model(:default)`, `temperature(:default)`, `max_cost(:default)` reset inherited parent values.
496
559
 
497
560
  ## 0.4.4 (2026-03-24)
498
561
 
499
- - **`stub_steps` (plural)** — stub multiple steps with different responses in one block. No nesting needed. Works in RSpec and Minitest:
562
+ - **`stub_steps` (plural)** - stub multiple steps with different responses in one block. No nesting needed. Works in RSpec and Minitest:
500
563
  ```ruby
501
564
  stub_steps(
502
565
  ClassifyTicket => { response: { priority: "high" } },
@@ -510,33 +573,33 @@ Production feedback release.
510
573
 
511
574
  ### Features
512
575
 
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)`.
576
+ - **`stub_step` block form** - `stub_step(Step, response: x) { test }` auto-resets adapter after block. Works in RSpec and Minitest. Eliminates leaked test state.
577
+ - **Minitest per-step routing** - `stub_step(StepA, ...)` now actually routes to StepA only (was setting global adapter, ignoring step class).
578
+ - **`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.
579
+ - **`max_cost` fail closed** - unknown model pricing now refuses the call instead of silently skipping. Set `on_unknown_pricing: :warn` for old behavior.
580
+ - **`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
581
 
519
582
  ## 0.4.2 (2026-03-24)
520
583
 
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.
584
+ - **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
585
 
523
586
  ## 0.4.1 (2026-03-24)
524
587
 
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.
588
+ - **RakeTask `:environment` fix** - uses `defined?(::Rails)` instead of `Rake::Task.task_defined?(:environment)`. Works in Rails 8 without manual `Rake::Task.enhance`.
589
+ - **Concurrent eval deterministic** - `clone_for_concurrency` protocol, `ContextHelpers` extracted.
590
+ - **README** - added eval history, concurrency, quality tracking examples.
528
591
 
529
592
  ## 0.4.0 (2026-03-24)
530
593
 
531
- Observability & Scale — see what changed, run it fast, debug it easily.
594
+ Observability & Scale - see what changed, run it fast, debug it easily.
532
595
 
533
596
  ### Features
534
597
 
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"`.
598
+ - **Structured logging** - `Contract.configure { |c| c.logger = Rails.logger }`. Auto-logs model, status, latency, tokens, cost on every `step.run`.
599
+ - **Batch eval concurrency** - `run_eval("regression", concurrency: 4)`. Parallel case execution via Concurrent::Future. 4x faster CI for large eval suites.
600
+ - **Eval history & trending** - `report.save_history!` appends to JSONL. `report.eval_history` returns `EvalHistory` with `score_trend`, `drift?`, run-by-run scores.
601
+ - **Pipeline per-step eval** - `add_case(..., step_expectations: { classify: { priority: "high" } })`. See which step in a pipeline regressed.
602
+ - **Minitest support** - `assert_satisfies_contract`, `assert_eval_passes`, `stub_step` for Minitest users. `require "ruby_llm/contract/minitest"`.
540
603
 
541
604
  ### Game changer continuity
542
605
 
@@ -550,71 +613,71 @@ v0.4: "Show me the trend" → eval history (time series)
550
613
 
551
614
  ## 0.3.7 (2026-03-24)
552
615
 
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.
616
+ - **Trait missing key = error** - `expected_traits: { title: 0..5 }` on output `{}` now fails instead of silently passing.
617
+ - **nil input in dynamic prompts** - `run(nil)` with `prompt { |input| ... }` correctly passes nil to block.
618
+ - **Defensive sample pre-validation** - `sample_response` uses the same parser as runtime (handles code fences, BOM, prose around JSON).
619
+ - **Baseline diff excludes skipped** - self-compare with skipped cases no longer shows artificial score delta.
620
+ - **Zeitwerk eval/ ignore** - `eager_load_contract_dirs!` ignores `eval/` subdirs before eager load.
558
621
 
559
622
  ## 0.3.6 (2026-03-24)
560
623
 
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.
624
+ - **Recursive array/object validation** - nested arrays (`array of array of string`) validated recursively. Object items validated even without `:properties` (e.g. `additionalProperties: false`).
625
+ - **Deep symbolize in sample pre-validation** - array samples with string keys (`[{"name" => "Alice"}]`) correctly symbolized before schema validation.
563
626
 
564
627
  ## 0.3.5 (2026-03-24)
565
628
 
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.
629
+ - **String constraints in SchemaValidator** - `minLength`/`maxLength` enforced for root and nested strings.
630
+ - **Array item validation** - scalar items (string, integer) validated against items schema type and constraints.
631
+ - **Non-JSON sample_response fails fast** - `sample_response("hello")` with object schema raises ArgumentError at definition time instead of silently passing.
632
+ - **`max_tokens` in KNOWN_CONTEXT_KEYS** - no more spurious "Unknown context keys" warning.
633
+ - **Duplicate models deduplicated** - `compare_models(models: ["m", "m"])` runs model once.
571
634
 
572
635
  ## 0.3.4 (2026-03-24)
573
636
 
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.
637
+ - **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.
638
+ - **Removed passing cases = regression** - `regressed?` returns true when baseline had passing cases that are now missing. Prevents gate bypass by deleting eval cases.
639
+ - **JSON string sample_response fixed** - `sample_response('{"name":"Alice"}')` correctly parsed for pre-validation instead of double-encoding.
640
+ - **`context[:max_tokens]` forwarded** - overrides step's `max_output` for adapter call AND budget precheck.
578
641
 
579
642
  ## 0.3.3 (2026-03-23)
580
643
 
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.
644
+ - **Skipped cases visible in regression diff** - baseline PASS → current SKIP now detected as regression by `without_regressions` and `fail_on_regression`.
645
+ - **Skip only on missing adapter** - eval runner no longer masks evaluator errors as SKIP. Only "No adapter configured" triggers skip.
646
+ - **Array/Hash sample pre-validation** - `sample_response([{...}])` correctly validated against schema instead of silently skipping.
647
+ - **`assume_model_exists: false` forwarded** - boolean `false` no longer dropped by truthiness check in adapter options.
648
+ - **Duplicate case names caught at definition** - `add_case`/`verify` with same name raises immediately, not at run time.
586
649
 
587
650
  ## 0.3.2 (2026-03-23)
588
651
 
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.
652
+ - **Array response preserved** - `Adapters::RubyLLM` no longer stringifies Array content. Steps with `output_type Array` work correctly.
653
+ - **Falsy prompt input** - `run(false)` and `build_messages(false)` pass `false` to dynamic prompt blocks instead of falling back to `instance_eval`.
654
+ - **`retry_on` flatten** - `retry_on([:a, :b])` no longer wraps in nested array.
655
+ - **Builder reset** - `Prompt::Builder` resets nodes on each build (no accumulation on reuse).
656
+ - **Pipeline false output** - `output: false` no longer shows "(no output)" in pretty_print.
594
657
 
595
658
  ## 0.3.1 (2026-03-23)
596
659
 
597
660
  Fixes from persona_tool production deployment (4 services migrated).
598
661
 
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.
662
+ - **Proc/Lambda in `expected_traits`** - `expected_traits: { score: ->(v) { v > 3 } }` now works.
663
+ - **Zeitwerk eager-load** - `load_evals!` eager-loads `app/contracts/` and `app/steps/` before loading eval files. Fixes uninitialized constant errors in Rake tasks.
664
+ - **Falsy values** - `expected: false`, `input: false`, `sample_response(nil)` all handled correctly.
665
+ - **Context key forwarding** - `provider:` and `assume_model_exists:` forwarded to adapter. `schema:` and `max_tokens:` are step-level only (no split-brain).
666
+ - **Deep-freeze immutability** - constructors never mutate caller's data.
604
667
 
605
668
  ## 0.3.0 (2026-03-23)
606
669
 
607
- Baseline regression detection — know when quality drops before users do.
670
+ Baseline regression detection - know when quality drops before users do.
608
671
 
609
672
  ### Features
610
673
 
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
674
+ - **`report.save_baseline!`** - serialize eval results to `.eval_baselines/` (JSON, git-tracked)
675
+ - **`report.compare_with_baseline`** - returns `BaselineDiff` with regressions, improvements, score_delta, new/removed cases
676
+ - **`diff.regressed?`** - true when any previously-passing case now fails
677
+ - **`without_regressions` RSpec chain** - `expect(Step).to pass_eval("x").without_regressions`
678
+ - **RakeTask `fail_on_regression`** - blocks CI when regressions detected
679
+ - **RakeTask `save_baseline`** - auto-save after successful run
680
+ - **Migration guide** - `docs/guide/migration.md` with 7 patterns for adopting the gem in existing Rails apps
618
681
 
619
682
  ### Stats
620
683
 
@@ -624,21 +687,21 @@ Baseline regression detection — know when quality drops before users do.
624
687
 
625
688
  Production hardening from senior Rails review panel.
626
689
 
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.
690
+ - **`around_call` propagates exceptions** - no longer silently swallows DB errors, timeouts, etc. User who wants swallowing can rescue in their block.
691
+ - **Nil section content skipped** - `section "X", nil` no longer renders `"null"` to the LLM. Section is omitted entirely.
692
+ - **Range support in `expected:`** - `expected: { score: 1..5 }` works in `add_case`. Previously only Regexp was supported.
693
+ - **`Trace#dig`** - `trace.dig(:usage, :input_tokens)` works on both Step and Pipeline traces.
631
694
 
632
695
  ## 0.2.2 (2026-03-23)
633
696
 
634
697
  Fixes from first real-world integration (persona_tool).
635
698
 
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.
699
+ - **`around_call` fires per-run** - not per-attempt. With retry_policy, callback fires once with final result. Signature: `around_call { |step, input, result| ... }`
700
+ - **`Result#trace` always `Trace` object** - never bare Hash. `result.trace.model` works on success AND failure.
701
+ - **`around_call` exception safe** - warns and returns result instead of crashing.
702
+ - **`model` DSL** - `model "gpt-4o-mini"` per-step. Priority: context > step DSL > global config.
703
+ - **Test adapter `raw_output` always String** - Hash/Array normalized to `.to_json`.
704
+ - **`Trace#dig`** - `trace.dig(:usage, :input_tokens)` works.
642
705
 
643
706
  ## 0.2.1 (2026-03-23)
644
707
 
@@ -646,18 +709,18 @@ Production DX improvements from first real-world integration (persona_tool).
646
709
 
647
710
  ### Features
648
711
 
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.
712
+ - **`temperature` DSL** - `temperature 0.3` in step definition, overridable via `context: { temperature: 0.7 }`. RubyLLM handles per-model normalization natively.
713
+ - **`around_call` hook** - callback for logging, metrics, observability. Replaces need for custom middleware.
714
+ - **`build_messages` public** - inspect rendered prompt without running the step.
715
+ - **`stub_step` RSpec helper** - `stub_step(MyStep, response: { ... })` reduces test boilerplate. Auto-included via `require "ruby_llm/contract/rspec"`.
716
+ - **`estimate_cost` / `estimate_eval_cost`** - predict spend before API calls.
654
717
 
655
718
  ### Fixes
656
719
 
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.
720
+ - **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).
721
+ - **Pipeline eval cost** - uses `Pipeline::Trace#total_cost` (all steps), not just last step.
722
+ - **Adapter isolation** - `compare_models` and `run_all_own_evals` deep-dup context per run.
723
+ - **Offline mode** - cases without adapter return `:skipped` instead of crashing. Skipped cases excluded from score.
661
724
  - **`expected_traits`** reachable from `define_eval` DSL via `add_case`.
662
725
  - **`verify`** raises when both positional and `expect:` keyword provided.
663
726
  - **`best_for`** excludes zero-score models from recommendation.
@@ -687,28 +750,28 @@ Contracts for LLM quality. Know which model to use, what it costs, and when accu
687
750
 
688
751
  ### Features
689
752
 
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.
753
+ - **`add_case` in `define_eval`** - `add_case "billing", input: "...", expected: { priority: "high" }` with partial matching. Supports `expected_traits:` for regex/range matching.
754
+ - **`CaseResult` value objects** - `result.name`, `result.passed?`, `result.output`, `result.expected`, `result.mismatches` (structured diff), `result.cost`, `result.duration_ms`.
755
+ - **`report.failures`** - returns only failed cases. `report.skipped` counts skipped (offline) cases.
756
+ - **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.
757
+ - **Cost tracking** - `report.total_cost`, `report.avg_latency_ms`, per-case `result.cost`. Pipeline eval uses total pipeline cost, not just last step.
758
+ - **Cost prediction** - `Step.estimate_cost(input:, model:)` and `Step.estimate_eval_cost("eval", models: [...])` predict spend before API calls.
759
+ - **CI gating** - `pass_eval("regression").with_minimum_score(0.8).with_maximum_cost(0.01)`. RakeTask with suite-level `minimum_score` and `maximum_cost`.
760
+ - **`RubyLLM::Contract.run_all_evals`** - discovers all Steps/Pipelines with evals, runs them all. Includes inherited evals.
761
+ - **`RubyLLM::Contract::RakeTask`** - `rake ruby_llm_contract:eval` with `minimum_score`, `maximum_cost`, `fail_on_empty`, `eval_dirs`.
762
+ - **Rails Railtie** - auto-loads eval files via `config.after_initialize` + `config.to_prepare` (supports development reload).
763
+ - **Offline mode** - cases without adapter return `:skipped` instead of crashing. Skipped cases excluded from score/passed.
764
+ - **Safe `define_eval`** - warns on duplicate name; suppressed during reload.
702
765
 
703
766
  ### Fixes
704
767
 
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.
768
+ - **P1: Eval files not autoloaded by Rails** - Railtie uses `load` (not Zeitwerk). Hooks into reloader for dev.
769
+ - **P2: report.results returns raw Hashes** - now returns `CaseResult` objects.
770
+ - **P3: No way to run all evals at once** - `Contract.run_all_evals` + Rake task.
771
+ - **P4: String vs symbol key mismatch** - warns when `validate` or `verify` proc returns nil.
772
+ - **Pipeline eval cost** - uses `Pipeline::Trace#total_cost` (all steps), not just last step.
773
+ - **Reload lifecycle** - `load_evals!` clears definitions before re-loading. Registry filters stale hosts.
774
+ - **Adapter isolation** - `compare_models` and `run_all_own_evals` deep-dup context per run.
712
775
 
713
776
  ### Verified with real API
714
777
 
@@ -731,16 +794,16 @@ Initial release.
731
794
 
732
795
  ### Features
733
796
 
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
797
+ - **Step abstraction** - `RubyLLM::Contract::Step::Base` with prompt DSL, typed input/output
798
+ - **Output schema** - declarative structure via ruby_llm-schema, sent to provider for enforcement
799
+ - **Validate** - business logic checks (1-arity and 2-arity with input cross-validation)
800
+ - **Retry with model escalation** - start cheap, auto-escalate on contract failure or network error
801
+ - **Preflight limits** - `max_input`, `max_cost`, `max_output` refuse before calling the LLM
802
+ - **Pipeline** - multi-step composition with fail-fast, timeout, token budget
803
+ - **Eval** - offline contract verification with `define_eval`, `run_eval`, zero-verify auto-case
804
+ - **Adapters** - RubyLLM (production), Test (deterministic specs)
805
+ - **RSpec matchers** - `satisfy_contract`, `pass_eval`
806
+ - **Structured trace** - model, latency, tokens, cost, attempt log per step
744
807
 
745
808
  ### Robustness
746
809