From 3d066d5782e74ef3051f5900e432f2fc826e5644 Mon Sep 17 00:00:00 2001 From: Amp Date: Tue, 3 Nov 2026 09:46:53 +0000 Subject: [PATCH] Add Testing::Cassette to record sessions and replay them without the CLI ClaudeAgentSDK::Testing::Cassette (require 'claude_agent_sdk/testing/cassette') records a session's stream-JSON frames to a JSONL file through the real transport and replays them in tests by playing the CLI's side: hooks, can_use_tool and SDK MCP tools run for real, and every frame the SDK writes is compared with the recording. Mismatches raise MismatchError from the read loop, so they reach query / ask / Client; verify! reports what a replay never reached. Options-fingerprint and pinned-CLI drift only warn. Built only on the public Transport contract; no existing code changes. Amp-Thread-ID: https://ampcode.com/threads/T-01a19fec-39e9-76e0-9914-6c8ab560a0c9 Co-authored-by: ya-luotao --- CHANGELOG.md | 3 + README.md | 1 + docs/testing.md | 67 ++ lib/claude_agent_sdk/testing/cassette.rb | 841 ++++++++++++++++++++++ sig/claude_agent_sdk/testing/cassette.rbs | 72 ++ spec/unit/require_surface_spec.rb | 10 + spec/unit/testing/cassette_spec.rb | 604 ++++++++++++++++ 7 files changed, 1598 insertions(+) create mode 100644 docs/testing.md create mode 100644 lib/claude_agent_sdk/testing/cassette.rb create mode 100644 sig/claude_agent_sdk/testing/cassette.rbs create mode 100644 spec/unit/testing/cassette_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 1829679d..fbc6da02 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **`ClaudeAgentSDK::Testing::Cassette`** (`require 'claude_agent_sdk/testing/cassette'`) records a session's stream-JSON frames to a JSONL file and replays them in tests without the CLI. The replay plays the CLI's side, so hooks, `can_use_tool` and SDK MCP tools run for real and what they return is compared with the recording; a mismatch raises `Cassette::MismatchError` from `query` / `ask` / `Client`. Works with `query(transport:)` and `Client` (`**cassette.client_args`); warns when the options or the pinned CLI changed since recording. See [docs/testing.md](docs/testing.md). + ### Changed - `CLIInstaller::PINNED_CLI_VERSION` moves from 2.1.311 to **2.1.314**, following the CLI the Python SDK bundles. `CLIInstaller.install_pinned` installs it. See the [Claude Code changelog](https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md). diff --git a/README.md b/README.md index 41f0616e..17d744ed 100644 --- a/README.md +++ b/README.md @@ -231,6 +231,7 @@ The block runs on a plain thread, so ActiveRecord calls inside it are safe. It i | Vendoring a pinned CLI binary and CLI discovery order | [docs/cli-installer.md](https://github.com/rubycatco/claude-agent-sdk-ruby/blob/main/docs/cli-installer.md) | | Hash-key rule, attribute access, and the message, content block, and configuration type reference | [docs/types.md](https://github.com/rubycatco/claude-agent-sdk-ruby/blob/main/docs/types.md) | | Error handling, exception hierarchy, timeouts | [docs/errors.md](https://github.com/rubycatco/claude-agent-sdk-ruby/blob/main/docs/errors.md) | +| Recording sessions and replaying them in tests without the CLI | [docs/testing.md](https://github.com/rubycatco/claude-agent-sdk-ruby/blob/main/docs/testing.md) | API reference: [rubydoc.info/gems/claude-agent-sdk](https://rubydoc.info/gems/claude-agent-sdk). Available built-in tools: [Claude Code tools reference](https://code.claude.com/docs/en/tools-reference). diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 00000000..b812a666 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,67 @@ +# Testing with Cassettes + +`ClaudeAgentSDK::Testing::Cassette` records the stream-JSON frames of a real session to a JSONL file, then replays them in later test runs without the CLI: no subprocess, no API call, and the same frames every time. It is not loaded by `require 'claude_agent_sdk'`; require it in your test helper: + +```ruby +require 'claude_agent_sdk/testing/cassette' +``` + +## Recording and Replaying + +```ruby +cassette = ClaudeAgentSDK::Testing::Cassette.new('spec/cassettes/weather.jsonl') + +# query() and ask take a transport instance +result = ClaudeAgentSDK.ask('Weather in Beijing?', options: options, transport: cassette.transport(options)) + +# Client takes a transport class and its arguments; each connect plays the next recorded connection +ClaudeAgentSDK::Client.open(options: options, **cassette.client_args) do |client| + client.query('Weather in Beijing?') + client.receive_response { |message| ... } +end + +cassette.verify! +``` + +The default mode, `:once`, records when the file does not exist and replays it when it does. `mode: :record` and `mode: :replay` force one or the other, and `CLAUDE_CASSETTE_RECORD=1` in the environment forces recording. A recording wraps `SubprocessCLITransport` by default, so it needs a CLI and credentials; pass `transport_class:` and `transport_args:` to record through another transport. + +Pass the same `options` to the query as to `cassette.transport(options)`. When they set `can_use_tool`, the transport starts the CLI with `--permission-prompt-tool stdio`, which `query` cannot add to a transport it did not build ([docs/client.md](client.md#one-shot-queries-over-a-custom-transport)). + +If `connect`, `write`, `end_input` or `close` of the recorded transport does not complete (it raises, or its task is cancelled), or the transport is closed while one of them is still running, the recording is not saved (an existing file is left as it was), a warning says why, and `verify!` raises `Cassette::Error`. With several connections on one cassette (a `Client` that reconnects, or concurrent transports), the file is written each time the last open connection closes. + +A replay plays the CLI's side of the conversation. Your hooks, `can_use_tool` callback and SDK MCP tools run during a replay exactly as they did while recording, and what they send back is compared with what was recorded. + +## What a Replay Checks + +Every frame the SDK writes (the `initialize` request, each prompt, each reply to a hook, permission or tool request) must match the recorded one. With `match: :strict`, the default, frames must be equal apart from `request_id`, `requestId` and `uuid` at the top level and any keys you list in `ignore:` (dropped at any depth). With `match: :type`, only the kind of frame is compared. Any object with `#call(recorded, written)`, such as a Proc or a Method, decides for itself. Frames the SDK writes back to back (replies to concurrent control requests) may arrive in any order; each is paired with the first recorded frame of the same kind that matches it. + +The SDK's own control requests get a new id every run; the replay maps the recorded ids to the new ones, so responses reach the right waiter. + +A mismatch raises `Cassette::MismatchError` from `query`, `ask`, `Client#connect` or `Client#receive_response`, naming the first difference: + +```text +connection 0: control_response 00000000-...-16 differs: $.response.response.mcp_response.result.content[0].text: recorded "5", written "six" +``` + +If the SDK does not write a frame the cassette expects within `wait:` seconds (default 5), the replay raises `MismatchError` instead of hanging. A recorded CLI failure replays as the same `ProcessError`, with its exit code (nil included) and stderr. + +The SDK does not have to read the CLI's output to its end: when it stops reading (a `break`, a disconnect) or the output ends before the SDK closes stdin, what it still writes, ends or closes is paired with the rest of the cassette when you call `verify!`, and CLI frames it never read are not reported. That includes a recorded result or CLI failure your test never read: a replay cannot tell whether your code used what the SDK delivered, so assert on the result in the test itself. + +Call `verify!` once the session has ended. It raises `MismatchError` listing every mismatch, every recorded event the SDK did not answer (a frame it should have written, or a turn your test no longer sends), every frame or `end_input` the SDK wrote that the cassette does not have, and every connection that was never opened. Calling it again reports the same. A cassette file with an event the format does not define raises `Cassette::Error` when it is loaded, naming the line. + +Read messages with a block (`query(...) { |message| ... }`, `receive_response { |message| ... }`) rather than iterating an Enumerator twice: a replay plays each recorded connection once. + +## Warnings + +A replay warns once, on stderr, and replays anyway, when: + +- the options produce different CLI arguments than when the cassette was recorded (the cassette stores a digest of them). Settings that reach the CLI over stdin, such as hooks, agents and the prompt, are checked frame by frame instead. +- `CLIInstaller::PINNED_CLI_VERSION` has changed since the cassette was recorded. + +Re-record with `CLAUDE_CASSETTE_RECORD=1` to clear either. + +## The File + +One JSON object per line: a header (`cassette`, `sdk_version`, `cli_version`, `pinned_cli_version`, `recorded_at`), then one event per line, each with the connection it belongs to (`conn`) and its direction (`dir`): `in` for a frame the CLI sent, `out` for a frame the SDK wrote, `connect`, `end_input` and `close` for the SDK's calls on the transport, and `exit` for the end of the CLI's output. + +A cassette holds everything that crossed the wire: prompts, tool inputs and outputs, file contents the model read, and paths of the machine it was recorded on. Review it like any other fixture before you commit it. diff --git a/lib/claude_agent_sdk/testing/cassette.rb b/lib/claude_agent_sdk/testing/cassette.rb new file mode 100644 index 00000000..3495ffd8 --- /dev/null +++ b/lib/claude_agent_sdk/testing/cassette.rb @@ -0,0 +1,841 @@ +# frozen_string_literal: true + +require 'English' +require 'digest' +require 'fileutils' +require 'json' +require 'securerandom' +require 'time' +require_relative '../../claude_agent_sdk' + +module ClaudeAgentSDK + module Testing + # Records the stream-JSON frames of real sessions to a JSONL file and + # replays them later without the CLI: no subprocess, no API call, the + # same frames every time. Hooks, can_use_tool, SDK MCP tools and + # SessionStore mirroring run for real during a replay, because the + # replay plays the CLI's side of the conversation and checks what the + # SDK writes back. + # + # require 'claude_agent_sdk/testing/cassette' + # + # cassette = ClaudeAgentSDK::Testing::Cassette.new('spec/cassettes/weather.jsonl') + # result = ClaudeAgentSDK.ask('Weather in Beijing?', options: options, transport: cassette.transport(options)) + # ClaudeAgentSDK::Client.open(options: options, **cassette.client_args) { |client| ... } + # cassette.verify! + # + # Mode :once (the default) records when the file does not exist and + # replays it when it does; :record and :replay force one or the other, + # and CLAUDE_CASSETTE_RECORD=1 in the environment forces recording. + # + # A cassette is a header line followed by one event per line, each + # tagged with the connection (+conn+) it belongs to. +dir+ is the + # direction: +in+ a frame the CLI sent, +out+ a frame the SDK wrote, + # +connect+, +end_input+ and +close+ the SDK's calls on the transport, + # +exit+ the end of the CLI's output. A replay walks the events of a + # connection in order: it yields each +in+ frame, waits for the SDK to + # write each +out+ frame and compares it, and waits for +end_input+ and + # +close+. Consecutive +out+ events are matched in any order, since + # replies to concurrent control requests can be written in either. + # + # A mismatch raises MismatchError from the transport's read loop, so it + # reaches the caller of query / ask / Client like a CLI failure would. + # (Raising it from #write would not: the SDK answers a failed write of a + # control response as a callback failure.) #verify! reports mismatches + # again, and events the replay never reached. + class Cassette + class Error < ClaudeSDKError; end + + # The SDK did something the cassette did not record. + class MismatchError < Error; end + + FORMAT_VERSION = 1 + MODES = %i[once record replay].freeze + MATCH_MODES = %i[strict type].freeze + + # Top-level keys that differ on every run: the ids the SDK gives its + # own control requests (remapped instead) and message uuids. + VOLATILE_KEYS = %i[request_id requestId uuid].freeze + + attr_reader :path, :mode, :match, :ignore, :wait + + # @param path [String, Pathname] the JSONL file + # @param mode [Symbol] :once, :record or :replay + # @param match [Symbol, Proc] how an SDK frame is compared with the + # recorded one: :strict (equal apart from VOLATILE_KEYS and +ignore+), + # :type (same type, subtype and control request id), or a Proc + # called with (recorded, written) that returns truthy on a match + # @param ignore [Array] keys :strict drops at any depth + # @param wait [Numeric] seconds a replay waits for each SDK write + # @param transport_class the transport a recording wraps + # @param transport_args [Hash] keyword arguments for transport_class.new + def initialize(path, mode: :once, match: :strict, ignore: [], wait: 5, + transport_class: SubprocessCLITransport, transport_args: {}) + raise ArgumentError, "mode must be one of #{MODES.inspect} (got #{mode.inspect})" unless MODES.include?(mode) + unless MATCH_MODES.include?(match) || match.respond_to?(:call) + raise ArgumentError, "match must be one of #{MATCH_MODES.inspect} or a Proc (got #{match.inspect})" + end + + @path = path.to_s + @mode = resolve_mode(mode) + @match = match + @ignore = ignore.map(&:to_sym) + @wait = wait + @transport_class = transport_class + @transport_args = transport_args + @mutex = Mutex.new + @connections = 0 + @inflight = Hash.new(0) + @open = [] + @saved = false + @publish = Mutex.new + @transports = [] + @problems = [] + @warned = {} + @events = [] + if recording? + @header = {} + else + load! + end + end + + def recording? + @mode == :record + end + + def replaying? + @mode == :replay + end + + # A transport for one connection, for query(transport:) / ask(transport:). + # Pass the same options to the query. With can_use_tool set, the + # transport gets them with permission_prompt_tool_name: 'stdio', which + # query cannot add to a transport it did not build (docs/client.md). + # @param options [ClaudeAgentOptions] the options of the call, used to + # spawn the CLI when recording and for the fingerprint check + def transport(options = nil) + options ||= ClaudeAgentOptions.new + if options.can_use_tool && !options.permission_prompt_tool_name + options = options.dup_with(permission_prompt_tool_name: 'stdio') + end + transport_class.new(options, cassette: self) + end + + # Keyword arguments for Client.new / Client.open. Each connect takes + # the next connection of the cassette. + def client_args + { transport_class: transport_class, transport_args: { cassette: self } } + end + + # Raises MismatchError listing every mismatch and every event a replay + # did not reach, or, for a recording, Error saying why it was not saved. Call it + # after the session has ended. Calling it again reports the same. + # @return [nil] + def verify! + transports = @mutex.synchronize { @transports.dup } + # Settled before the problems are read: settling reports mismatches. + leftovers = replaying? ? transports.flat_map(&:leftovers) : [] + problems = @mutex.synchronize do + @problems + @open.map { |conn| "connection #{conn} was never closed; the cassette was not saved" } + end + problems += leftovers + (transports.size...connection_count).each do |conn| + problems << "connection #{conn} was recorded but never opened" if replaying? + end + return nil if problems.empty? + + raise Error, "cassette #{@path} was not recorded cleanly:\n- #{problems.uniq.join("\n- ")}" if recording? + + raise MismatchError, "cassette #{@path} did not replay cleanly:\n- #{problems.uniq.join("\n- ")}" + end + + # A short digest of the CLI arguments +options+ produce (everything + # but the executable path), or nil when they cannot be built. Settings + # that reach the CLI through stdin instead (hooks, agents, the prompt) + # are checked frame by frame. + def self.fingerprint(options) + argv = CommandBuilder.new('claude', options).build.drop(1) + "sha256:#{Digest::SHA256.hexdigest(JSON.generate(argv))[0, 16]}" + rescue StandardError + nil + end + + # The rest is for the two transports. + + # @api private + attr_reader :transport_args + + # @api private + def recording_transport_class + @transport_class + end + + # @api private + def open_connection(transport) + @mutex.synchronize do + @transports << transport + @connections += 1 + @open << (@connections - 1) if recording? + @connections - 1 + end + end + + # @api private + def record(conn, dir, **fields) + frame = fields[:frame] + @mutex.synchronize do + if dir == 'in' && frame[:type] == 'system' && frame[:subtype] == 'init' && !@header[:cli_version] + @header[:cli_version] = frame[:claude_code_version] + end + @events << { conn: conn, dir: dir, **fields } + end + end + + # @api private + def events_for(conn) + @events.select { |event| event[:conn] == conn } + end + + # @api private + def report(problem) + @mutex.synchronize { @problems << problem } + end + + # Brackets a transport call while recording: save does not publish + # while a call on the connection it closes is in flight, its outcome + # not known yet. A call that did not return (it raised, or was + # cancelled) invalidates the recording in the same step as it ends, so + # a save never sees it finished but not yet failed. + # @api private + def call_started(conn) + @mutex.synchronize { @inflight[conn] += 1 } + end + + # @api private + def call_finished(conn, call, failed, error) + @mutex.synchronize do + @inflight[conn] -= 1 + invalidate_unlocked(conn, call, error) if failed + end + end + + # A transport call the format cannot replay did not complete: the + # cassette is not saved, so a bad recording never replaces a file. When + # it was saved already, verify! says it must be re-recorded. + # @api private + def invalidate(conn, call, error) + @mutex.synchronize { invalidate_unlocked(conn, call, error) } + end + + # @api private + def warn_once(message) + first = @mutex.synchronize { @warned[message] ? false : (@warned[message] = true) } + warn "Claude SDK: cassette #{@path}: #{message}" if first + end + + # Called when connection +conn+ closes. Publishes once every + # connection opened so far is closed: to a sibling temp file first, + # renamed into place, so a failure never leaves half a cassette. + # Publications are serialized from the snapshot to the rename, so an + # older snapshot never replaces a newer one. + # @api private + def save(conn) + @publish.synchronize do + lines, invalid = snapshot(conn) + return warn_once("not saved: #{invalid}") if invalid + return unless lines + + publish(lines) + end + end + + # Whether +written+ matches the +recorded+ frame (both already of the + # same kind), or a description of the first difference. + # @api private + def compare(recorded, written) + case @match + when :type then nil + when :strict + Cassette.difference(normalize(recorded), normalize(written)) + else + @match.call(recorded, written) ? nil : 'the match Proc returned false' + end + end + + # The first place +expected+ and +actual+ differ, as text, or nil. + # @api private + def self.difference(expected, actual, path = '$') # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity -- one recursive walk over Hash, Array and leaf + return nil if expected == actual + + if expected.is_a?(Hash) && actual.is_a?(Hash) + (expected.keys | actual.keys).each do |key| + at = "#{path}.#{key}" + return "#{at}: missing (recorded #{brief(expected[key])})" unless actual.key?(key) + return "#{at}: not recorded (written #{brief(actual[key])})" unless expected.key?(key) + + found = difference(expected[key], actual[key], at) + return found if found + end + elsif expected.is_a?(Array) && actual.is_a?(Array) && expected.size == actual.size + expected.each_index do |i| + found = difference(expected[i], actual[i], "#{path}[#{i}]") + return found if found + end + end + "#{path}: recorded #{brief(expected)}, written #{brief(actual)}" + end + + # @api private + def self.brief(value) + text = JSON.generate(value) + text.size > 120 ? "#{text[0, 117]}..." : text + end + + private + + def invalidate_unlocked(conn, call, error) + outcome = error ? "raised #{error.class}: #{error.message}" : 'did not complete' + problem = "connection #{conn}: #{call} #{outcome}" + @invalid ||= problem + @problems << (@saved ? "#{problem} after the cassette was saved; re-record it" : "#{problem}; not saved") + end + + # The lines to publish, nil while another connection is open, or the + # reason the recording is invalid. + # Only a completed rename counts as saved. A failure (or cancellation) + # invalidates the recording, so verify! reports it, and goes on. + def publish(lines) + done = false + temp = "#{@path}.#{Process.pid}.#{SecureRandom.hex(4)}.tmp" + FileUtils.mkdir_p(File.dirname(@path)) + File.write(temp, lines.join("\n") << "\n") + File.rename(temp, @path) + done = true + ensure + FileUtils.rm_f(temp) unless done + @mutex.synchronize do + if done + @saved = true + else + error = $ERROR_INFO + @invalid ||= "writing #{@path} #{error ? "raised #{error.class}: #{error.message}" : 'did not complete'}" + @problems << "#{@invalid}; not saved" + end + end + end + + def snapshot(conn) + @mutex.synchronize do + @open.delete(conn) + if @inflight[conn].positive? + @invalid ||= "connection #{conn} was closed while #{@inflight[conn]} call(s) on it were in flight" + @problems << "#{@invalid}; not saved" + end + next [nil, @invalid] if @invalid + next [nil, nil] unless @open.empty? + + header = { cassette: FORMAT_VERSION, sdk_version: VERSION, cli_version: @header[:cli_version], + pinned_cli_version: CLIInstaller::PINNED_CLI_VERSION, recorded_at: Time.now.utc.iso8601 } + [[header, *@events].map { |line| JSON.generate(line) }, nil] + end + end + + def transport_class + recording? ? RecordingTransport : ReplayTransport + end + + def connection_count + @events.map { |event| event[:conn] }.uniq.size + end + + def resolve_mode(mode) + return :record if ENV['CLAUDE_CASSETTE_RECORD'] == '1' + return mode unless mode == :once + + File.exist?(@path) ? :replay : :record + end + + def load! + raise Error, "cassette #{@path} does not exist (record it with mode: :record)" unless File.exist?(@path) + + header, *events = File.readlines(@path, chomp: true).reject(&:empty?) + .map { |line| JSON.parse(line, symbolize_names: true) } + unless header.is_a?(Hash) && header[:cassette] == FORMAT_VERSION + raise Error, "#{@path} is not a version #{FORMAT_VERSION} cassette" + end + + events.each_with_index { |event, index| validate_event(event, index + 2) } + @header = header + @events = events + pinned = header[:pinned_cli_version] + return if pinned.nil? || pinned == CLIInstaller::PINNED_CLI_VERSION + + warn_once("recorded with CLI #{header[:cli_version] || 'unknown'} when the pinned CLI was #{pinned}; " \ + "the pin is now #{CLIInstaller::PINNED_CLI_VERSION}. Re-record it with CLAUDE_CASSETTE_RECORD=1.") + rescue JSON::ParserError => e + raise Error, "#{@path} is not a valid cassette: #{e.message}" + end + + DIRECTIONS = %w[connect in out end_input close exit].freeze + private_constant :DIRECTIONS + + def validate_event(event, line) + valid = event.is_a?(Hash) && event[:conn].is_a?(Integer) && DIRECTIONS.include?(event[:dir]) && + (!%w[in out].include?(event[:dir]) || event[:frame].is_a?(Hash)) + raise Error, "#{@path}:#{line} is not a cassette event: #{Cassette.brief(event)}" unless valid + end + + def normalize(frame) + strip_keys(frame.except(*VOLATILE_KEYS)) + end + + def strip_keys(value) + case value + when Hash then value.except(*@ignore).transform_values { |item| strip_keys(item) } + when Array then value.map { |item| strip_keys(item) } + else value + end + end + + # Wraps a real transport (cassette transport_class, by default + # SubprocessCLITransport) and records every call and frame. + class RecordingTransport < Transport + def initialize(options, cassette:) + super() + @cassette = cassette + @options = options + @inner = cassette.recording_transport_class.new(options, **cassette.transport_args) + @conn = cassette.open_connection(self) + @close_state = nil + @close_lock = Mutex.new + end + + def connect + guard('connect') do + @inner.connect + @cassette.record(@conn, 'connect', fingerprint: Cassette.fingerprint(@options)) + end + end + + def ready? + @inner.ready? + end + + # Recorded before the write: the CLI's reply can be read before the + # write returns, and the replay must see the write first. + def write(data) + guard('write') do + data.each_line do |line| + next if line.strip.empty? + + @cassette.record(@conn, 'out', frame: JSON.parse(line, symbolize_names: true)) + end + @inner.write(data) + end + end + + def end_input + guard('end_input') do + @cassette.record(@conn, 'end_input') + @inner.end_input + end + end + + def read_messages + return enum_for(:read_messages) unless block_given? + + from_sdk = nil + @inner.read_messages do |message| + @cassette.record(@conn, 'in', frame: JSON.parse(JSON.generate(message), symbolize_names: true)) + begin + yield message + rescue StandardError => e + from_sdk = e + raise + end + end + @cassette.record(@conn, 'exit', status: 0) + rescue StandardError => e + record_failure(e) unless e.equal?(from_sdk) + raise + end + + # Idempotent; one caller at a time owns the close. Only a close + # that returns completes it: one that raised or was cancelled + # invalidates the recording and can be retried, to release what the + # inner transport holds. The close event is recorded once. + def close + first = @close_lock.synchronize do + next nil if %i[closing closed].include?(@close_state) + + first_attempt = @close_state.nil? + @close_state = :closing + first_attempt + end + return if first.nil? + + @cassette.record(@conn, 'close') if first + done = false + begin + @inner.close + done = true + ensure + @close_state = done ? :closed : :failed + @cassette.invalidate(@conn, 'close', $ERROR_INFO) unless done + @cassette.save(@conn) + end + end + + private + + # A call counts as done only when it returns: an exception or a + # cancellation (Async::Stop) invalidates the recording, then goes on. + def guard(call) + @cassette.call_started(@conn) + done = false + result = yield + done = true + result + ensure + @cassette.call_finished(@conn, call, !done, $ERROR_INFO) + end + + # The end of the CLI's output as an error: a ProcessError replays as + # one (exit_code nil included), anything else as CLIConnectionError. + # ProcessError decorates its message with the exit code and stderr; + # the base message is recorded so a replay raises the same text. + def record_failure(error) + message = error.message + unless error.is_a?(ProcessError) + return @cassette.record(@conn, 'exit', error: error.class.name, message: message) + end + + message = message.split("\nError output: ").first if error.stderr + message = message.delete_suffix(" (exit code: #{error.exit_code})") if error.exit_code + @cassette.record(@conn, 'exit', error: 'ProcessError', status: error.exit_code, stderr: error.stderr, + message: message) + end + end + + # Plays the CLI's side of one recorded connection. + class ReplayTransport < Transport + def initialize(options, cassette:) + super() + @cassette = cassette + @options = options + @conn = cassette.open_connection(self) + @events = cassette.events_for(@conn) + @position = 0 + @unmatched = [] + @written = Thread::Queue.new + @ids = {} + @state = Mutex.new + @reading = false + @backlog = [] + @settle_failed = false + @connected = false + end + + def connect + if @events.empty? + raise Error, "cassette #{@cassette.path} has no connection #{@conn} (it was recorded with fewer connects)" + end + + @connected = true + event = current + return unless event&.dig(:dir) == 'connect' + + advance + fingerprint = Cassette.fingerprint(@options) + return if event[:fingerprint].nil? || fingerprint.nil? || event[:fingerprint] == fingerprint + + @cassette.warn_once("connection #{@conn}: the options produce different CLI arguments than when it was " \ + 'recorded. Re-record it with CLAUDE_CASSETTE_RECORD=1.') + end + + def ready? + @connected + end + + # Only queues: a mismatch is raised from #read_messages (see Cassette). + def write(data) + data.each_line do |line| + next if line.strip.empty? + + frame = begin + JSON.parse(line, symbolize_names: true) + rescue JSON::ParserError + { unparsable: line.chomp } + end + @written << [:frame, frame] + end + end + + def end_input + @written << [:end_input] + end + + # Idempotent: only the first close pairs with the recorded one. + def close + @written << [:close] + @connected = false + end + + def read_messages(&block) + return enum_for(:read_messages) unless block + + read(&block) + end + + # What #verify! reports for this connection. + # @api private + def leftovers + @state.synchronize do + settle_unlocked unless @reading + remaining = @unmatched + @events.drop(@position) + where = remaining.empty? ? 'after the cassette ended' : 'where the cassette does not have it' + remaining.map { |event| "connection #{@conn}: never reached #{describe(event)}" } + + @backlog.filter_map do |(what, frame)| + case what + when :frame then "connection #{@conn}: the SDK wrote #{Cassette.brief(frame)} #{where}" + when :end_input then "connection #{@conn}: the SDK called end_input #{where}" + end + end + end + end + + private + + # Only the call that took the read loop releases it. + def read(&) + @state.synchronize do + raise Error, "connection #{@conn} is already being read" if @reading + + @reading = true + end + begin + play(&) + rescue MismatchError => e + @cassette.report(e.message) + raise + ensure + @state.synchronize { @reading = false } + end + end + + # Once the read loop is over (the CLI's output ended, or the SDK + # stopped reading), what the SDK wrote, ended or closed that the loop + # never took is paired with the events left, in order, without + # waiting. CLI frames left are skipped: the SDK need not read the + # CLI's output to its end. Stops at the first event without its + # call, and for good at the first mismatch, so repeated calls report + # the same; #leftovers reports the rest. + def settle_unlocked + @backlog << @written.pop(timeout: 0) until @written.empty? + @backlog.compact! + return if @settle_failed + + loop do + pending = @unmatched + @unmatched = [] + pending << advance_unlocked while current&.dig(:dir) == 'out' + unless pending.empty? + settled = settle_writes(pending) + @unmatched = pending + return unless settled + + next + end + return unless (event = current) && settled?(event) + end + end + + def settle_writes(pending) + until pending.empty? + return false unless @backlog.first&.first == :frame + + check_write(pending, @backlog.shift[1]) + end + true + rescue MismatchError => e + @cassette.report(e.message) + @settle_failed = true + false + end + + # CLI events are skipped; an SDK call is taken from the backlog. + def settled?(event) + unless %w[in exit connect].include?(event[:dir]) + return false unless @backlog.first&.first == event[:dir].to_sym + + @backlog.shift + end + advance_unlocked + true + end + + def play + while (event = current) + case event[:dir] + when 'connect' then advance + when 'in' + advance + yield rewrite(event[:frame]) + when 'out' then return unless expect_writes + when 'end_input' then return unless called?(:end_input) + when 'close' then return unless called?(:close) + when 'exit' + advance + finish(event) + return + else raise Error, "connection #{@conn}: unknown cassette event #{Cassette.brief(event)}" + end + end + end + + # Takes the run of consecutive +out+ events at the current position + # and waits until the SDK has written a matching frame for each, in + # any order. False when the SDK closed the transport instead. What + # is still pending when this ends early (close, a mismatch, or the + # SDK stopping the read task) is kept for #leftovers. + def expect_writes + pending = [] + pending << advance while current&.dig(:dir) == 'out' + until pending.empty? + item = next_written("the SDK to write #{describe(pending.first)}") + case item[0] + when :close then return false + when :end_input + raise MismatchError, "connection #{@conn}: the SDK closed stdin before writing #{describe(pending.first)}" + end + check_write(pending, item[1]) + end + true + ensure + @state.synchronize { @unmatched.concat(pending) } + end + + # Of the pending frames of the same kind, the first that matches is + # the one written; with none, the first is reported as differing. + def check_write(pending, frame) + candidates = pending.select { |event| kind(event[:frame]) == kind(frame) } + if candidates.empty? + raise MismatchError, "connection #{@conn}: the SDK wrote #{Cassette.brief(frame)}; " \ + "the cassette expects #{pending.map { |event| describe(event) }.join(' or ')}" + end + + matched = matching(candidates, frame) + recorded = pending.delete_at(pending.index { |event| event.equal?(matched) })[:frame] + @ids[recorded[:request_id]] = frame[:request_id] if frame[:type] == 'control_request' + end + + def matching(candidates, frame) + differences = candidates.map { |event| @cassette.compare(event[:frame], frame) } + index = differences.index(nil) + return candidates[index] if index + + raise MismatchError, "connection #{@conn}: #{describe_frame(candidates.first[:frame])} differs: " \ + "#{differences.first}" + end + + # Waits for the SDK to call end_input / close. A write, or an + # end_input where close is expected, is something the cassette does + # not have. False when the SDK closed where end_input was expected. + def called?(marker) + what, frame = marker == :close ? @written.pop : next_written("the SDK to call #{marker}") + if what == :frame + raise MismatchError, "connection #{@conn}: the SDK wrote #{Cassette.brief(frame)}; " \ + "the cassette expects #{marker}" + end + if what == :end_input && marker == :close + raise MismatchError, "connection #{@conn}: the SDK called end_input; the cassette expects close" + end + + unless what == marker + put_back([what]) + return false + end + + advance + true + end + + # A call the read loop took but does not answer stays for #leftovers. + def put_back(item) + @state.synchronize { @backlog << item } + end + + def next_written(what) + item = @written.pop(timeout: @cassette.wait) + raise MismatchError, "connection #{@conn}: timed out after #{@cassette.wait}s waiting for #{what}" unless item + + item + end + + def finish(event) + case event[:error] + when nil then nil + when 'ProcessError' + raise ProcessError.new(event[:message] || 'Command failed', exit_code: event[:status], + stderr: event[:stderr]) + else + raise CLIConnectionError, "#{event[:message]} (recorded #{event[:error]})" + end + end + + # A fresh copy, as the subprocess transport parses each line anew, + # with the SDK's own request ids put back into responses to them. + def rewrite(frame) + frame = JSON.parse(JSON.generate(frame), symbolize_names: true) + return frame unless frame[:type] == 'control_response' + + # Both places Query reads a response's id from. + [frame, frame[:response]].each do |holder| + next unless holder.is_a?(Hash) + + %i[request_id requestId].each do |key| + holder[key] = @ids[holder[key]] if holder.key?(key) && @ids.key?(holder[key]) + end + end + frame + end + + # What identifies a written frame among concurrent ones. + def kind(frame) + case frame[:type] + when 'control_request' then ['control_request', frame.dig(:request, :subtype)] + when 'control_response' then ['control_response', frame.dig(:response, :request_id)] + else [frame[:type]] + end + end + + def describe(event) + case event[:dir] + when 'out' then describe_frame(event[:frame]) + when 'in' then "CLI frame #{describe_frame(event[:frame])}" + else event[:dir] + end + end + + def describe_frame(frame) + kind(frame).compact.join(' ') + end + + def current + @events[@position] + end + + def advance + @state.synchronize { advance_unlocked } + end + + def advance_unlocked + event = @events[@position] + @position += 1 + event + end + end + end + end +end diff --git a/sig/claude_agent_sdk/testing/cassette.rbs b/sig/claude_agent_sdk/testing/cassette.rbs new file mode 100644 index 00000000..7e39e2f0 --- /dev/null +++ b/sig/claude_agent_sdk/testing/cassette.rbs @@ -0,0 +1,72 @@ +module ClaudeAgentSDK + module Testing + # Records sessions' stream-JSON frames to a JSONL file and replays them + # without the CLI (`require 'claude_agent_sdk/testing/cassette'`). + class Cassette + class Error < ClaudeSDKError + end + + # The SDK did something the cassette did not record. + class MismatchError < Error + end + + FORMAT_VERSION: Integer + + MODES: Array[Symbol] + + MATCH_MODES: Array[Symbol] + + VOLATILE_KEYS: Array[Symbol] + + type mode = :once | :record | :replay + + # A Proc, Method or any object with #call. + interface _Matcher + def call: (wire_hash recorded, wire_hash written) -> boolish + end + + type match = :strict | :type | _Matcher + + attr_reader path: String + + # :record or :replay once resolved. + attr_reader mode: (:record | :replay) + + attr_reader match: match + + attr_reader ignore: Array[Symbol] + + attr_reader wait: Numeric + + def initialize: (String | Pathname path, ?mode: mode, ?match: match, ?ignore: Array[String | Symbol], + ?wait: Numeric, ?transport_class: _TransportClass, ?transport_args: Hash[Symbol, untyped]) -> void + + def recording?: () -> bool + + def replaying?: () -> bool + + # A transport for query(transport:) / ask(transport:). + def transport: (?ClaudeAgentOptions? options) -> Transport + + # Keyword arguments for Client.new / Client.open. + def client_args: () -> { transport_class: _TransportClass, transport_args: { cassette: Cassette } } + + # Raises MismatchError on any mismatch or unreplayed event; Error for a + # recording that was not saved. + def verify!: () -> nil + + # Digest of the CLI arguments options produce, or nil. + def self.fingerprint: (ClaudeAgentOptions options) -> String? + + # Wraps a real transport and records every frame. + class RecordingTransport < Transport + def initialize: (ClaudeAgentOptions options, cassette: Cassette) -> void + end + + # Plays the CLI's side of one recorded connection. + class ReplayTransport < Transport + def initialize: (ClaudeAgentOptions options, cassette: Cassette) -> void + end + end + end +end diff --git a/spec/unit/require_surface_spec.rb b/spec/unit/require_surface_spec.rb index 2687421c..3dc1a97e 100644 --- a/spec/unit/require_surface_spec.rb +++ b/spec/unit/require_surface_spec.rb @@ -40,6 +40,16 @@ def run_ruby(code) expect(status.exitstatus).to eq(0), "a non-Rails require must load neither Rails nor the Railtie: #{err}" end + it 'loads the cassette only on request, and the cassette entry point loads the SDK core' do + plain = "require 'claude_agent_sdk'; exit(defined?(ClaudeAgentSDK::Testing::Cassette) ? 1 : 0)" + _out, err, status = run_ruby(plain) + expect(status.exitstatus).to eq(0), "a plain require must not define Testing::Cassette: #{err}" + + code = "require 'claude_agent_sdk/testing/cassette'; exit(ClaudeAgentSDK.respond_to?(:query) ? 0 : 1)" + _out, err, status = run_ruby(code) + expect(status.exitstatus).to eq(0), "the cassette entry point must load the SDK core: #{err}" + end + it 'lets the configuration file be required on its own' do # default_options= deep-copies through Type.deep_dup_for_options; a # standalone require of configuration.rb must bring that in itself. diff --git a/spec/unit/testing/cassette_spec.rb b/spec/unit/testing/cassette_spec.rb new file mode 100644 index 00000000..8e646220 --- /dev/null +++ b/spec/unit/testing/cassette_spec.rb @@ -0,0 +1,604 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'tmpdir' +require 'claude_agent_sdk/testing/cassette' + +# Records through the real SubprocessCLITransport against FakeClaude (a child +# process speaking the CLI's protocol), then replays with the executable +# deleted, so a replay that tried to reach a CLI would fail. +# The CLI side of a transport, in process: answers each control request +# (in the shape +reply+ builds) and each prompt with a result. +fail_on+ +# :write raises on the prompt, :exit ends the output with a ProcessError at +# end_input, :block holds the prompt's write until +release+ is popped +# (pushing to +entered+ first), :eof ends the output right after the result, +# :close holds every close the same way. +closes+ counts the closes. +class CassetteStubCLI < ClaudeAgentSDK::Transport + def initialize(_options, reply: :nested, fail_on: nil, entered: nil, release: nil) + super() + @queue = Thread::Queue.new + @reply = reply + @fail_on = fail_on + @entered = entered + @release = release + @closes = 0 + end + + attr_reader :closes + + def connect; end + + def write(data) + frame = JSON.parse(data, symbolize_names: true) + return prompt if frame[:type] == 'user' + + id = frame[:request_id] + @queue << if @reply == :top_level + { type: 'control_response', request_id: id, response: { subtype: 'success', response: {} } } + else + { type: 'control_response', response: { subtype: 'success', request_id: id, response: {} } } + end + end + + def prompt + raise ClaudeAgentSDK::CLIConnectionError, 'send failed' if @fail_on == :write + + if @fail_on == :block + @entered << true + @release.pop + end + return if @queue.closed? + + @queue << { type: 'system', subtype: 'session_state_changed', state: 'running', sdk_host_only: true } if @fail_on == :eof + @queue << { type: 'result', subtype: 'success', is_error: false, session_id: 's', result: 'OK' } + @queue << :eof if @fail_on == :eof + end + + def read_messages + while (message = @queue.pop) + break if message == :eof + raise ClaudeAgentSDK::ProcessError.new('cannot reap', stderr: 'gone') if message == :fail + + yield message + end + end + + def end_input + @queue << :fail if @fail_on == :exit + end + + def close + @closes += 1 + if @fail_on == :close + @entered << true + @release.pop + end + @queue.close + end +end + +RSpec.describe ClaudeAgentSDK::Testing::Cassette do + around do |example| + Dir.mktmpdir('cassette') do |dir| + @dir = File.realpath(dir) + @cli = FakeClaude.install(@dir) + @path = File.join(@dir, 'cassettes', 'session.jsonl') + Timeout.timeout(30) { example.run } + end + end + + let(:hook_inputs) { [] } + let(:tool_calls) { [] } + + def options(**overrides) + hook = lambda do |input, _tool_use_id, _context| + hook_inputs << input.tool_name + {} + end + add = ClaudeAgentSDK.create_tool('add', 'Add two numbers', { a: :number, b: :number }) do |args| + tool_calls << args + @tool_result ? @tool_result.call(args) : (args[:a] + args[:b]).to_s + end + ClaudeAgentSDK::ClaudeAgentOptions.new( + cli_path: @cli, cwd: @dir, + env: FakeClaude.env(tool_call: JSON.generate(server: 'calc', name: 'add', arguments: { a: 2, b: 3 }), + reply: 'The sum is 5'), + hooks: { 'PreToolUse' => [ClaudeAgentSDK::HookMatcher.new(matcher: 'Bash', hooks: [hook])] }, + mcp_servers: { 'calc' => ClaudeAgentSDK.create_sdk_mcp_server(name: 'calc', tools: [add]) }, + **overrides + ) + end + + def run_query(cassette, prompt = 'add 2 and 3', opts = options) + messages = [] + ClaudeAgentSDK.query(prompt: prompt, options: opts, transport: cassette.transport(opts)) { |m| messages << m } + messages + end + + def run_client(cassette, prompts) + ClaudeAgentSDK::Client.open(options: options, **cassette.client_args) do |client| + prompts.map do |prompt| + client.query(prompt) + last = nil + client.receive_response { |message| last = message } + last.result + end + end + end + + def record_query + cassette = described_class.new(@path) + expect(cassette).to be_recording + run_query(cassette) + hook_inputs.clear + tool_calls.clear + File.delete(@cli) + end + + it 'replays a recorded query() with hooks and an SDK MCP tool, without a CLI' do + recorded = run_query(described_class.new(@path)) + hook_inputs.clear + tool_calls.clear + File.delete(@cli) + + cassette = described_class.new(@path) + expect(cassette).to be_replaying + replayed = run_query(cassette) + + expect(replayed.map(&:class)).to eq(recorded.map(&:class)) + expect(replayed.last.result).to eq('The sum is 5') + # The callbacks ran again during the replay, with the recorded inputs. + expect(hook_inputs).to eq(['Bash']) + expect(tool_calls).to eq([{ a: 2, b: 3 }]) + expect(cassette.verify!).to be_nil + + header = JSON.parse(File.readlines(@path).first) + expect(header).to include('cassette' => 1, 'cli_version' => FakeClaude::CLI_VERSION, + 'pinned_cli_version' => ClaudeAgentSDK::CLIInstaller::PINNED_CLI_VERSION) + end + + it 'replays a multi-turn Client session, remapping the request ids the SDK generates' do + expect(run_client(described_class.new(@path), %w[one two])).to eq(['The sum is 5'] * 2) + File.delete(@cli) + sdk_requests = File.readlines(@path).map { |line| JSON.parse(line) }.select do |event| + event['dir'] == 'out' && event.dig('frame', 'type') == 'control_request' + end + # initialize, whose response must reach its waiter under a new id. + expect(sdk_requests.map { |event| event.dig('frame', 'request', 'subtype') }).to eq(['initialize']) + + cassette = described_class.new(@path) + expect(run_client(cassette, %w[one two])).to eq(['The sum is 5'] * 2) + expect(cassette.verify!).to be_nil + end + + it 'raises MismatchError naming the difference when a tool now returns something else' do + record_query + @tool_result = ->(_args) { 'six' } + + cassette = described_class.new(@path) + expect { run_query(cassette) }.to raise_error(described_class::MismatchError, /recorded "5", written "six"/) + expect { cassette.verify! }.to raise_error(described_class::MismatchError, /written "six"/) + end + + it 'accepts the changed tool output under match: :type' do + record_query + @tool_result = ->(_args) { 'six' } + + cassette = described_class.new(@path, match: :type) + expect(run_query(cassette).last.result).to eq('The sum is 5') + expect(cassette.verify!).to be_nil + end + + it 'raises MismatchError from ask when the prompt differs' do + record_query + + cassette = described_class.new(@path) + expect { ClaudeAgentSDK.ask('subtract', options: options, transport: cassette.transport(options)) } + .to raise_error(described_class::MismatchError, /\$\.message\.content: recorded "add 2 and 3", written "subtract"/) + end + + it 'replays a failed CLI as the same ProcessError' do + opts = ClaudeAgentSDK::ClaudeAgentOptions.new(cli_path: @cli, cwd: @dir, + env: FakeClaude.env(scenario: 'stderr_then_fail', stderr_lines: 2)) + recorded = begin + run_query(described_class.new(@path), 'hi', opts) + rescue ClaudeAgentSDK::ProcessError => e + e + end + expect(recorded).to be_a(ClaudeAgentSDK::ProcessError) + File.delete(@cli) + + expect { run_query(described_class.new(@path), 'hi', opts) }.to raise_error(ClaudeAgentSDK::ProcessError) do |error| + expect([error.class, error.message, error.exit_code, error.stderr]) + .to eq([recorded.class, recorded.message, recorded.exit_code, recorded.stderr]) + end + end + + it 'reports the turns a replay never reached' do + run_client(described_class.new(@path), %w[one two]) + File.delete(@cli) + + cassette = described_class.new(@path) + expect(run_client(cassette, %w[one])).to eq(['The sum is 5']) + expect { cassette.verify! }.to raise_error(described_class::MismatchError, /\A[^\n]+\n- connection 0: never reached user\n/) + end + + it 'warns once when the options or the pinned CLI changed since recording, and replays anyway' do + record_query + expect { run_query(described_class.new(@path)) }.not_to output.to_stderr + + changed = options(model: 'claude-sonnet-5-5') + expect { run_query(described_class.new(@path), 'add 2 and 3', changed) } + .to output(/different CLI arguments than when it was recorded/).to_stderr + + lines = File.readlines(@path) + lines[0] = "#{JSON.generate(JSON.parse(lines[0]).merge('pinned_cli_version' => '2.0.0'))}\n" + File.write(@path, lines.join) + expect { run_query(described_class.new(@path)) } + .to output(/recorded with CLI #{Regexp.escape(FakeClaude::CLI_VERSION)} when the pinned CLI was 2\.0\.0/) + .to_stderr + end + + # A cassette written by hand, for cases a FakeClaude session cannot produce. + def write_cassette(events) + FileUtils.mkdir_p(File.dirname(@path)) + File.write(@path, [{ cassette: 1 }, *events.map { |event| { conn: 0, **event } }] + .map { |line| "#{JSON.generate(line)}\n" }.join) + end + + def replay_transport(**cassette_options) + cassette = described_class.new(@path, **cassette_options) + transport = cassette.transport + transport.connect + [cassette, transport] + end + + def write_frame(transport, frame) + transport.write("#{JSON.generate(frame)}\n") + end + + it 'does not save a recording when a transport call failed, and verify! says why' do + cassette = described_class.new(@path, transport_class: CassetteStubCLI, transport_args: { fail_on: :write }) + expect { ClaudeAgentSDK.ask('hi', transport: cassette.transport) } + .to raise_error(ClaudeAgentSDK::CLIConnectionError, 'send failed') + .and output(/not saved: connection 0: write raised/).to_stderr + + expect(File).not_to exist(@path) + expect { cassette.verify! }.to raise_error(described_class::Error, /write raised .*send failed/) + end + + it 'starts a recorded CLI with the permission prompt tool when can_use_tool is set' do + log = File.join(@dir, 'cli.log') + allow_all = ->(*) { ClaudeAgentSDK::PermissionResultAllow.new } + opts = ClaudeAgentSDK::ClaudeAgentOptions.new(cli_path: @cli, cwd: @dir, env: FakeClaude.env(log: log), + can_use_tool: allow_all) + ClaudeAgentSDK.ask('hi', options: opts, transport: described_class.new(@path).transport(opts)) + + argv = FakeClaude.events(log).find { |event| event['event'] == 'start' }.fetch('argv') + expect(argv.each_cons(2)).to include(['--permission-prompt-tool', 'stdio']) + end + + it 'replays a ProcessError without an exit code as a ProcessError' do + cassette = described_class.new(@path, transport_class: CassetteStubCLI, transport_args: { fail_on: :exit }) + expect { ClaudeAgentSDK.ask('hi', transport: cassette.transport) }.to raise_error(ClaudeAgentSDK::ProcessError) + + expect { ClaudeAgentSDK.ask('hi', transport: described_class.new(@path).transport) } + .to raise_error(ClaudeAgentSDK::ProcessError) { |error| expect([error.exit_code, error.stderr]).to eq([nil, 'gone']) } + end + + it 'remaps request ids in control responses that carry them at the top level' do + cassette = described_class.new(@path, transport_class: CassetteStubCLI, transport_args: { reply: :top_level }) + ClaudeAgentSDK::Client.open(**cassette.client_args) { nil } + + cassette = described_class.new(@path, wait: 1) + expect(ClaudeAgentSDK::Client.open(**cassette.client_args) { :connected }).to eq(:connected) + expect(cassette.verify!).to be_nil + end + + it 'pairs concurrent writes of the same kind by content, in either order' do + a = { type: 'control_request', request_id: 'rec_a', request: { subtype: 'set_model', model: 'A' } } + b = { type: 'control_request', request_id: 'rec_b', request: { subtype: 'set_model', model: 'B' } } + reply = ->(id) { { type: 'control_response', response: { subtype: 'success', request_id: id, response: {} } } } + write_cassette([{ dir: 'out', frame: a }, { dir: 'out', frame: b }, { dir: 'in', frame: reply.call('rec_b') }, + { dir: 'in', frame: reply.call('rec_a') }, { dir: 'exit', status: 0 }]) + cassette, transport = replay_transport + write_frame(transport, b.merge(request_id: 'new_b')) + write_frame(transport, a.merge(request_id: 'new_a')) + + replies = [] + transport.read_messages { |frame| replies << frame.dig(:response, :request_id) } + expect(replies).to eq(%w[new_b new_a]) + expect(cassette.verify!).to be_nil + end + + it 'keeps reporting a write or end_input the cassette does not have' do + write_cassette([{ dir: 'exit', status: 0 }, { dir: 'close' }]) + cassette, transport = replay_transport + transport.read_messages { nil } + transport.close + transport.end_input + write_frame(transport, type: 'user', message: { content: 'late' }) + transport.close + + 2.times do + expect { cassette.verify! }.to raise_error(described_class::MismatchError) { |error| + expect(error.message.lines.drop(1).map(&:strip)).to eq( + ['- connection 0: the SDK called end_input after the cassette ended', + '- connection 0: the SDK wrote {"type":"user","message":{"content":"late"}} after the cassette ended'] + ) + } + end + end + + it 'does not save a recording whose write was cancelled' do + entered = Thread::Queue.new + cassette = described_class.new(@path, transport_class: CassetteStubCLI, + transport_args: { fail_on: :block, entered: entered, + release: Thread::Queue.new }) + expect do + Sync do |task| + query = task.async { ClaudeAgentSDK.query(prompt: 'hi', transport: cassette.transport) { nil } } + entered.pop + query.stop + end + end.to output(/not saved: connection 0: write raised/).to_stderr + + expect(File).not_to exist(@path) + expect { cassette.verify! }.to raise_error(described_class::Error, /write raised/) + end + + it 'keeps the existing file when the transport is closed while a write is in flight' do + write_cassette([{ dir: 'connect' }, { dir: 'close' }]) + original = File.read(@path) + entered = Thread::Queue.new + release = Thread::Queue.new + cassette = described_class.new(@path, mode: :record, transport_class: CassetteStubCLI, + transport_args: { fail_on: :block, entered: entered, release: release }) + transport = cassette.transport + transport.connect + writer = Thread.new { write_frame(transport, type: 'user', message: { content: 'hi' }) } + entered.pop + expect { transport.close }.to output(/not saved: connection 0 was closed while 1 call/).to_stderr + release << true + writer.join + + expect(File.read(@path)).to eq(original) + expect { cassette.verify! }.to raise_error(described_class::Error, /connection 0 was closed while 1 call/) + end + + it 'publishes once every connection is closed, not when another one closes mid-write' do + entered = Thread::Queue.new + release = Thread::Queue.new + cassette = described_class.new(@path, transport_class: CassetteStubCLI, + transport_args: { fail_on: :block, entered: entered, release: release }) + idle, busy = Array.new(2) { cassette.transport.tap(&:connect) } + writer = Thread.new { write_frame(busy, type: 'user', message: { content: 'hi' }) } + entered.pop + idle.close + expect(File).not_to exist(@path) + release << true + writer.join + busy.close + + events = File.readlines(@path).drop(1).map { |line| JSON.parse(line).values_at('conn', 'dir') } + expect(events).to eq([[0, 'connect'], [1, 'connect'], [1, 'out'], [0, 'close'], [1, 'close']]) + expect(cassette.verify!).to be_nil + end + + it 'reports a wrong frame the SDK wrote after it stopped reading, the same way every time' do + write_cassette([{ dir: 'in', frame: { type: 'system', subtype: 'a' } }, + { dir: 'out', frame: { type: 'user', n: 1 } }, { dir: 'in', frame: { type: 'system', subtype: 'b' } }, + { dir: 'out', frame: { type: 'user', n: 2 } }, { dir: 'close' }]) + cassette, transport = replay_transport + transport.read_messages { break } + write_frame(transport, type: 'user', n: 2) + write_frame(transport, type: 'user', n: 1) + transport.close + + messages = Array.new(2) do + cassette.verify! + rescue described_class::MismatchError => e + e.message + end + expect(messages.first).to include('user differs: $.n: recorded 1, written 2') + expect(messages.uniq.size).to eq(1) + end + + it 'refuses a second read loop and keeps the first one running' do + write_cassette([{ dir: 'in', frame: { type: 'system', subtype: 'a' } }, + { dir: 'in', frame: { type: 'system', subtype: 'b' } }, { dir: 'exit', status: 0 }]) + _cassette, transport = replay_transport + read = [] + transport.read_messages do |frame| + transport.read_messages # an Enumerator; must not release the running loop + expect { transport.read_messages { nil } }.to raise_error(described_class::Error, /already being read/) + read << frame[:subtype] + end + expect(read).to eq(%w[a b]) + end + + it 'does not save a recording whose close was cancelled, and lets the SDK close again' do + write_cassette([{ dir: 'connect' }, { dir: 'close' }]) + original = File.read(@path) + entered = Thread::Queue.new + release = Thread::Queue.new + cassette = described_class.new(@path, mode: :record, transport_class: CassetteStubCLI, + transport_args: { fail_on: :close, entered: entered, release: release }) + transport = cassette.transport + transport.connect + expect do + Sync do |task| + closer = task.async { transport.close } + entered.pop + closer.stop + end + end.to output(/not saved: connection 0: close raised/).to_stderr + + expect(File.read(@path)).to eq(original) + expect { cassette.verify! }.to raise_error(described_class::Error, /close raised/) + release << true + transport.close + expect(entered.size).to eq(1) # the retry reached the inner transport + end + + it 'records one close when a second close comes while the first is in progress' do + entered = Thread::Queue.new + release = Thread::Queue.new + cassette = described_class.new(@path, transport_class: CassetteStubCLI, + transport_args: { fail_on: :close, entered: entered, release: release }) + transport = cassette.transport + transport.connect + closer = Thread.new { transport.close } + entered.pop + transport.close # returns at once: the first close owns it + release << true + closer.join + + expect(File.readlines(@path).drop(1).map { |line| JSON.parse(line)['dir'] }).to eq(%w[connect close]) + expect(cassette.verify!).to be_nil + end + + it 'reports a cassette file it could not write' do + File.write(File.join(@dir, 'cassettes'), 'a file where the directory should be') + cassette = described_class.new(@path, transport_class: CassetteStubCLI) + transport = cassette.transport + transport.connect + expect { transport.close }.to raise_error(SystemCallError) + + 2.times { expect { cassette.verify! }.to raise_error(described_class::Error, /writing .* raised Errno::/) } + end + + it 'counts a write as in flight from before its frame is recorded' do + write_cassette([{ dir: 'connect' }, { dir: 'close' }]) + original = File.read(@path) + cassette = described_class.new(@path, mode: :record, transport_class: CassetteStubCLI) + transport = cassette.transport + transport.connect + entered = Thread::Queue.new + release = Thread::Queue.new + writer = Thread.new do + trace = TracePoint.new(:call) do |point| + next unless point.method_id == :record && point.self.equal?(cassette) + + trace.disable + entered << true + release.pop + end + trace.enable(target_thread: Thread.current) { write_frame(transport, type: 'user', message: { content: 'hi' }) } + end + entered.pop + expect { transport.close }.to output(/not saved: connection 0 was closed while 1 call/).to_stderr + release << true + writer.join + + expect(File.read(@path)).to eq(original) + end + + it 'never lets an older publication replace a newer one' do + cassette = described_class.new(@path, transport_class: CassetteStubCLI) + first = cassette.transport.tap(&:connect) + entered = Thread::Queue.new + release = Thread::Queue.new + closer = Thread.new do + trace = TracePoint.new(:c_call) do |point| + next unless point.method_id == :rename && point.self == File + + trace.disable + entered << true + release.pop + end + trace.enable(target_thread: Thread.current) { first.close } + end + entered.pop + second = cassette.transport.tap(&:connect) + second_closer = Thread.new { second.close } + sleep 0.1 + release << true + [closer, second_closer].each(&:join) + + expect(File.readlines(@path).drop(1).map { |line| JSON.parse(line).values_at('conn', 'dir') }) + .to eq([[0, 'connect'], [0, 'close'], [1, 'connect'], [1, 'close']]) + end + + it 'does not take a close for the end_input the cassette expects' do + write_cassette([{ dir: 'end_input' }, { dir: 'close' }]) + cassette, transport = replay_transport + Sync do |task| + reader = task.async { transport.read_messages { nil } } + transport.close + reader.wait + end + + expect { cassette.verify! }.to raise_error(described_class::MismatchError, /never reached end_input/) + end + + it 'pairs a close the SDK makes while the read loop is still running' do + write_cassette([{ dir: 'in', frame: { type: 'system', subtype: 'x' } }, { dir: 'exit', status: 0 }, + { dir: 'close' }]) + cassette, transport = replay_transport + transport.read_messages { transport.close } + + expect(cassette.verify!).to be_nil + end + + it 'does not require the SDK to read the CLI output to its end' do + write_cassette([{ dir: 'in', frame: { type: 'system', subtype: 'a' } }, + { dir: 'in', frame: { type: 'system', subtype: 'b' } }, { dir: 'close' }]) + cassette, transport = replay_transport + read = [] + transport.read_messages do |frame| + read << frame[:subtype] + break + end + transport.close + + expect(read).to eq(['a']) + expect(cassette.verify!).to be_nil + end + + it 'replays a CLI whose output ends before the SDK closes stdin' do + # can_use_tool keeps the control channel needed, so stdin stays open + # until the SDK sees the output end. + opts = ClaudeAgentSDK::ClaudeAgentOptions.new(can_use_tool: ->(*) { ClaudeAgentSDK::PermissionResultAllow.new }) + cassette = described_class.new(@path, transport_class: CassetteStubCLI, transport_args: { fail_on: :eof }) + expect(ClaudeAgentSDK.ask('hi', options: opts, transport: cassette.transport(opts)).result).to eq('OK') + directions = File.readlines(@path).drop(1).map { |line| JSON.parse(line)['dir'] } + expect(directions.last(3)).to eq(%w[exit end_input close]) + + cassette = described_class.new(@path) + expect(ClaudeAgentSDK.ask('hi', options: opts, transport: cassette.transport(opts)).result).to eq('OK') + expect(cassette.verify!).to be_nil + end + + it 'pairs what the SDK wrote before it disconnected and stopped reading' do + send_only = ->(cassette) { ClaudeAgentSDK::Client.open(options: options, **cassette.client_args) { |c| c.query('hi') } } + send_only.call(described_class.new(@path)) + File.delete(@cli) + + cassette = described_class.new(@path) + send_only.call(cassette) + expect(cassette.verify!).to be_nil + end + + it 'rejects an event it does not know when loading' do + write_cassette([{ dir: 'inn', frame: { type: 'user' } }]) + expect { described_class.new(@path) }.to raise_error(described_class::Error, /session\.jsonl:2 is not a cassette event/) + end + + it 'accepts any object with #call as the matcher' do + write_cassette([{ dir: 'out', frame: { type: 'user', n: 1 } }, { dir: 'exit', status: 0 }]) + cassette, transport = replay_transport(match: ->(recorded, written) { written[:n] == recorded[:n] + 1 }.method(:call)) + write_frame(transport, type: 'user', n: 2) + transport.read_messages { nil } + transport.close + expect(cassette.verify!).to be_nil + end + + it 'times out instead of hanging when the SDK never writes the recorded frame' do + write_cassette([{ dir: 'out', frame: { type: 'user' } }]) + _cassette, transport = replay_transport(wait: 0.2) + + expect { transport.read_messages { nil } } + .to raise_error(described_class::MismatchError, /timed out after 0.2s waiting for the SDK to write user/) + end +end