ez-agent-ruby/test/workflow_test_support.rb
# frozen_string_literal: true
require "tmpdir"
require "fileutils"
require "ez_agent/workflow"
module PreparedWorkflowTest
Leaf = Struct.new(:id, :root_id, :name, :turn_id, :updated_at, :is_temp, :metadata, :status, keyword_init: true)
Created = Struct.new(:leaf_id, :root_id, :request_id, keyword_init: true)
Stats = Struct.new(:root_cwd, :state, :tip_turn_id, :runtime, keyword_init: true)
Acceptance = Struct.new(:root_id, :leaf_id, :turn_ids, :tip_turn_id, :request_id, keyword_init: true)
SteerAcceptance = Struct.new(:leaf_id, :turn_ids, :tip_turn_id, :request_id, keyword_init: true)
Turn = Struct.new(:id, :root_id, :leaf_id, :parent_id, :kind, :state, :seq, :content,
:content_type, :stop_reason, :usage, :other_meta, :timestamp,
:exit_message, :exit_classification, :thinking, :model, :provider,
:tool_call_id, :tool_name, :meta_files, keyword_init: true)
HelloAck = Struct.new(:state_dir, keyword_init: true)
MacroResult = Struct.new(:is_error, :result, keyword_init: true)
ConfigEntry = Struct.new(:key, :value, keyword_init: true)
Outcome = Struct.new(:reason, :message, keyword_init: true)
Runtime = Struct.new(:outcome, keyword_init: true)
ProviderMacroCall = Struct.new(:leaf_id, keyword_init: true) do
def success(result = "") = MacroResult.new(is_error: false, result: result)
end
class FakeEvents
Subscription = Struct.new(:id, :type, keyword_init: true)
def initialize
@mutex = Mutex.new
@handlers = Hash.new { |hash, key| hash[key] = {} }
@terminal_handlers = {}
@next_id = 0
end
def on(type, &block)
@mutex.synchronize do
@next_id += 1
@handlers[type.to_sym][@next_id] = block
Subscription.new(id: @next_id, type: type.to_sym)
end
end
def on_terminal(&block)
@mutex.synchronize do
@next_id += 1
@terminal_handlers[@next_id] = block
Subscription.new(id: @next_id, type: :terminal)
end
end
def off(subscription)
@mutex.synchronize do
handlers = subscription.type == :terminal ? @terminal_handlers : @handlers[subscription.type]
!handlers.delete(subscription.id).nil?
end
end
def publish(event)
@mutex.synchronize { @handlers[event.type].values.dup }.each { |handler| handler.call(event) }
end
def fail(error)
@mutex.synchronize { @terminal_handlers.values.dup }.each { |handler| handler.call(error) }
end
end
class FakeAPIClient
def initialize(backend) = @backend = backend
def sessions = @backend
def metadata = @backend
def config = @backend
def turns = @backend
def macros = @backend
def models = @backend.models
def events = @backend.events
def hello_ack = @backend.hello_ack
end
class FakeAPI
attr_reader :leaves, :prompts, :prompt_turns, :events, :buffer_dir, :create_options,
:fork_sources, :macro_params, :steers, :virtual_roots,
:provided_macros, :hello_ack, :model_sets, :thinking_sets
attr_accessor :prompt_behavior, :macro_behavior, :create_behavior, :steer_behavior
attr_accessor :tree_summaries
def initialize
@leaves, @prompts, @cwds = [], [], {}
@prompt_turns = []
@metadata_store = Hash.new { |hash, key| hash[key] = {} }
@config_store = Hash.new { |hash, key| hash[key] = {} }
@steers = []
@virtual_roots = []
@create_options, @fork_sources, @macro_params = [], [], []
@provided_macros = {}
@model_sets = []
@thinking_sets = []
@histories = Hash.new { |hash, key| hash[key] = [] }
@tree_turns = []
@acceptances = {}
@next = @buffer_next = 0
@events = FakeEvents.new
@buffer_dir = temporary_directory("prepared-workflow-test")
@state_dir = temporary_directory("prepared-workflow-state")
@hello_ack = HelloAck.new(state_dir: @state_dir)
@mutex = Mutex.new
end
def fresh_client = FakeAPIClient.new(self)
def state_dir = @state_dir
def temporary_directory(prefix)
path = Dir.mktmpdir(prefix)
RubyAPITest.defer_cleanup { FileUtils.remove_entry(path) if File.exist?(path) }
path
end
private :temporary_directory
def add_state_buffer(type, name, content)
directory = case type
when "tmp" then File.join(@state_dir, "buffers", "uuids")
when "cache" then File.join(@state_dir, "cache", File.dirname(name))
else File.join(@state_dir, "buffers", type)
end
FileUtils.mkdir_p(directory)
path = case type
when "tmp" then File.join(directory, "#{name}.txt")
when "cache" then File.join(@state_dir, "cache", name)
else File.join(directory, "#{name}.txt")
end
File.binwrite(path, content)
path
end
def sessions = self
def metadata = self
def config = self
def turns = self
def macros = self
def models
api = self
@models ||= Object.new.tap do |models|
models.define_singleton_method(:set) do |leaf_id, model|
api.model_sets << [leaf_id, model]
end
models.define_singleton_method(:set_thinking_level) do |leaf_id, level|
api.thinking_sets << [leaf_id, level]
end
end
end
def add(id:, cwd:, parent: nil, wf: nil, agent: nil, query: nil, turn_id: "",
at: "2026-01-01T00:00:00Z", status: "idle", temporary: false,
name: "leaf", passive: nil)
inferred_root_agent = false
if wf && agent.nil?
begin
workflow_id, nonce = EzAgent::Workflow.decode_wf_identifier(wf)
agent = EzAgent::Workflow.encode_agent_identifier(
id: workflow_id, nonce: nonce, agent_path: []
)
inferred_root_agent = true
rescue EzAgent::WorkflowIdentifiers::DecodeError
# Legacy and malformed roots remain visible so materialization can
# reject them without the fake silently upgrading their identity.
end
end
metadata = {"session_origin" => "ruby_workflow"}
metadata["parent_leaf"] = parent if parent
config = {}
config["workflow.wf_identifier"] = wf if wf
config["workflow.agent_identifier"] = agent if agent
config["workflow.query_identifier"] = query if query
@metadata_store[id] = metadata
@config_store[id] = config
@cwds[id] = cwd
leaf = Leaf.new(id: id, root_id: "root-#{id}", name: name, turn_id: turn_id,
updated_at: at, is_temp: temporary,
metadata: metadata.merge(config), status: status)
@leaves << leaf
seed_passive_workflow_agent(leaf, wf, agent) if
(passive == true && wf && agent) ||
(passive.nil? && inferred_root_agent && turn_id.empty?)
leaf
end
def list(id = nil, metadata_keys: nil)
if id
return @config_store.fetch(id).map do |key, value|
ConfigEntry.new(key: key, value: value)
end.freeze
end
raise "metadata keys required" unless metadata_keys
@leaves.each { |leaf| refresh_leaf_metadata(leaf.id) }
@leaves.dup.freeze
end
def stats(id)
leaf = @leaves.find { |candidate| candidate.id == id }
Stats.new(root_cwd: @cwds.fetch(id), state: leaf&.status || "idle",
tip_turn_id: leaf&.turn_id, runtime: nil)
end
def canonical_history(id) = @histories[id].dup.freeze
def remember_tree_turns(*turns)
@tree_turns.concat(turns.flatten)
end
def list_tree(root_id)
turns = (@histories.values.flatten + @tree_turns)
.select { |turn| turn.root_id == root_id }
.uniq(&:id)
.sort_by(&:seq)
.freeze
return turns unless tree_summaries
turns.map do |turn|
fields = %i[id parent_id kind state seq timestamp model provider stop_reason tool_name]
EzAgent::API::TurnTreeNode.new(fields.to_h do |field|
[field.to_s, turn.public_send(field)]
end.reject { |_key, value| value.nil? })
end.freeze
end
def get(turn_id)
turn = (@histories.values.flatten + @tree_turns).find { |entry| entry.id == turn_id }
raise ArgumentError, "unknown turn #{turn_id.inspect}" unless turn
frame = turn.to_h.reject do |key, value|
value.nil? || %i[exit_message exit_classification].include?(key)
end.transform_keys(&:to_s)
EzAgent::API::StoredTurn.new(frame.merge("type" => "turn_content", "request_id" => "get-#{turn_id}"))
end
def create(name:, cwd:, **options)
@create_behavior.call(name) if @create_behavior
@create_options << options.merge(name: name, cwd: cwd)
id = @mutex.synchronize { @next += 1; "created-#{@next}" }
leaf = add(id: id, cwd: cwd, name: name, at: "2026-01-02T00:00:00Z")
Created.new(leaf_id: id, root_id: leaf.root_id, request_id: "create-#{id}")
end
def create_virtual_root(id, reason:, pending_turns: [])
raise ArgumentError, "fake virtual root only supports no pending turns" unless pending_turns.empty?
leaf = @leaves.find { |candidate| candidate.id == id }
seq = @histories[id].map(&:seq).max.to_i + 1
turn = Turn.new(
id: "virtual-root-#{id}-#{seq}", root_id: leaf.root_id, leaf_id: id,
parent_id: leaf.turn_id.nil? || leaf.turn_id.empty? ? nil : leaf.turn_id,
kind: "virtual_root", state: "sent", seq: seq, content: reason,
content_type: "text", timestamp: "2026-01-02T00:00:00Z"
)
@histories[id] << turn
@virtual_roots << [id, reason]
leaf.turn_id = turn.id
Created.new(leaf_id: id, root_id: leaf.root_id, request_id: "virtual-root-#{id}")
end
def fork(source_turn_id, name:, **options)
@fork_sources << source_turn_id
source_leaf_id, source_turns = @histories.find do |_leaf_id, turns|
turns.any? { |turn| turn.id == source_turn_id }
end
unless source_turns
# Compaction hides old canonical prefixes, but they remain forkable.
stored = (@histories.values.flatten + @tree_turns).to_h { |turn| [turn.id, turn] }
source = stored.fetch(source_turn_id)
source_leaf_id = source.leaf_id
source_turns = [source]
while source_turns.first.parent_id
source_turns.unshift(stored.fetch(source_turns.first.parent_id))
end
end
source_leaf = @leaves.find { |leaf| leaf.id == source_leaf_id }
source_index = source_turns.index { |turn| turn.id == source_turn_id }
@create_options << options.merge(name: name, cwd: @cwds.fetch(source_leaf_id))
id = @mutex.synchronize { @next += 1; "created-#{@next}" }
leaf = add(id: id, cwd: @cwds.fetch(source_leaf_id), name: name,
at: "2026-01-02T00:00:00Z")
leaf.root_id = source_leaf.root_id
leaf.turn_id = source_turn_id
@histories[id] = source_turns.take(source_index + 1).map do |turn|
copy = turn.dup
copy.leaf_id = nil
copy
end
Created.new(leaf_id: id, root_id: leaf.root_id, request_id: "create-#{id}")
end
def history(id) = @histories[id]
def rename(id, name) = @leaves.find { |leaf| leaf.id == id }.name = name
def update(id, set:)
wrong = set.keys.select { |key| config_key?(key) }
raise "config keys must use api.config.set: #{wrong.inspect}" unless wrong.empty?
@metadata_store[id].merge!(set)
refresh_leaf_metadata(id)
end
def set(id, key, value)
if %w[parent_leaf session_origin].include?(key)
raise "metadata keys must use api.metadata.update: #{key.inspect}"
end
@config_store[id][key] = value
refresh_leaf_metadata(id)
end
def delete(id, key)
@config_store[id].delete(key)
refresh_leaf_metadata(id)
ConfigEntry.new(key: key, value: nil)
end
def abort(id) = (@leaves.find { |leaf| leaf.id == id }.status = "closed")
def prompt(id, text, parent_turn_id: nil)
prompt_turn(id, EzAgent::API::PendingTurn.text(text), parent_turn_id: parent_turn_id)
end
def prompt_turn(id, turn, parent_turn_id: nil)
text = turn.content
leaf = @leaves.find { |candidate| candidate.id == id }
tip = leaf.turn_id
if tip && !tip.empty? && parent_turn_id.nil?
raise "prompt parent is required for existing tip #{tip.inspect}"
end
if parent_turn_id && parent_turn_id != tip
raise "prompt parent #{parent_turn_id.inspect} does not match tip #{tip.inspect}"
end
@prompts << [id, text]
@prompt_turns << turn
seq = @histories[id].map(&:seq).max.to_i + 1
timestamp = "2026-01-03T00:00:#{format('%02d', @prompts.length)}Z"
user = Turn.new(id: "user-#{id}-#{seq}", root_id: leaf.root_id, leaf_id: id,
parent_id: leaf.turn_id.nil? || leaf.turn_id.empty? ? nil : leaf.turn_id,
kind: "user", state: "sent", seq: seq, content: text,
content_type: "text", timestamp: timestamp)
@histories[id] << user
leaf.turn_id = user.id
leaf.status = "running"
acceptance = Acceptance.new(root_id: leaf.root_id, leaf_id: id,
turn_ids: [user.id], tip_turn_id: user.id,
request_id: "prompt-#{id}-#{seq}")
@acceptances[id] = acceptance
if @prompt_behavior
result = @prompt_behavior.call(self, leaf, acceptance)
return result.is_a?(Acceptance) ? result : acceptance
end
assistant = Turn.new(id: "assistant-#{id}-#{seq + 1}", root_id: leaf.root_id,
leaf_id: id, parent_id: user.id, kind: "assistant",
state: "sent", seq: seq + 1,
content: "answer: #{text}", content_type: "text",
stop_reason: "stop", usage: "{}",
other_meta: '{"exit_message":"SUCCESS"}',
exit_message: "SUCCESS", exit_classification: :success,
timestamp: timestamp)
@histories[id] << assistant
leaf.turn_id = assistant.id
leaf.status = "idle"
emit_completion(leaf)
acceptance
end
def steer(id, text, parent_turn_id: :missing)
raise "steer parent must be explicitly nil" unless parent_turn_id.nil?
leaf = @leaves.find { |candidate| candidate.id == id }
raise EzAgent::API::ServiceError, "leaf is not active" unless leaf&.status == "running"
@steers << [id, text, parent_turn_id]
return @steer_behavior.call(self, leaf, text) if @steer_behavior
turn_id = "steer-#{id}-#{@steers.length}"
complete(leaf, "steered: #{text}")
SteerAcceptance.new(leaf_id: id, turn_ids: [turn_id], tip_turn_id: turn_id,
request_id: "steer-request-#{@steers.length}")
end
def complete(leaf, text)
seq = @histories[leaf.id].map(&:seq).max.to_i + 1
timestamp = "2026-01-04T00:00:00Z"
assistant = Turn.new(id: "assistant-custom-#{leaf.id}-#{seq}", root_id: leaf.root_id,
leaf_id: leaf.id, parent_id: @histories[leaf.id].last&.id,
kind: "assistant", state: "sent", seq: seq,
content: text, content_type: "text", stop_reason: "stop",
usage: "{}", other_meta: '{"exit_message":"SUCCESS"}',
exit_message: "SUCCESS", exit_classification: :success,
timestamp: timestamp)
@histories[leaf.id] << assistant
leaf.turn_id = assistant.id
leaf.status = "idle"
emit_completion(leaf)
assistant
end
def complete_error(leaf, text, message: "provider exhausted")
seq = @histories[leaf.id].map(&:seq).max.to_i + 1
timestamp = "2026-01-04T00:00:00Z"
assistant = Turn.new(
id: "assistant-error-#{leaf.id}-#{seq}", root_id: leaf.root_id,
leaf_id: leaf.id, parent_id: @histories[leaf.id].last&.id,
kind: "assistant", state: "sent", seq: seq, content: text,
content_type: "text", stop_reason: "error", usage: "{}",
other_meta: JSON.generate("exit_message" => message),
exit_message: message, exit_classification: :error,
timestamp: timestamp
)
@histories[leaf.id] << assistant
leaf.turn_id = assistant.id
leaf.status = "idle"
emit_completion(leaf, reason: "error", message: message)
assistant
end
def add_success(id:, text:, timestamp:, exit_message: "SUCCESS", stop_reason: "stop")
leaf = @leaves.find { |candidate| candidate.id == id }
existing = @histories[id]
boundary = existing.last
first_seq = existing.map(&:seq).max.to_i + 1
user = Turn.new(id: "user-#{id}", root_id: leaf.root_id, leaf_id: id,
parent_id: boundary&.id, kind: "user", state: "sent",
seq: first_seq, content: "old", content_type: "text",
timestamp: timestamp)
classification = exit_message.nil? ? :continue :
(exit_message == "SUCCESS" ? :success : :error)
other_meta = JSON.generate("exit_message" => exit_message)
assistant = Turn.new(id: "assistant-#{id}", root_id: leaf.root_id, leaf_id: id,
parent_id: user.id, kind: "assistant", state: "sent",
seq: first_seq + 1, content: text,
content_type: "text", stop_reason: stop_reason,
usage: "{}", other_meta: other_meta,
exit_message: exit_message,
exit_classification: classification, timestamp: timestamp)
@histories[id] = existing + [user, assistant]
if boundary&.kind == "virtual_root" &&
@config_store[id].key?("workflow.query_identifier")
@config_store[id]["workflow.query_boundary_turn_id"] = boundary.id
refresh_leaf_metadata(id)
end
leaf.turn_id = assistant.id
end
def add_legacy(id:, text:, timestamp:)
leaf = @leaves.find { |candidate| candidate.id == id }
user = Turn.new(id: "user-#{id}", root_id: leaf.root_id, leaf_id: id,
kind: "user", state: "sent", seq: 1, content: "old",
content_type: "text", timestamp: timestamp)
assistant = Turn.new(id: "assistant-#{id}", root_id: leaf.root_id, leaf_id: id,
parent_id: user.id, kind: "assistant", state: "sent", seq: 2,
content: text, content_type: "text", stop_reason: "stop",
usage: "{}", timestamp: timestamp,
exit_message: nil, exit_classification: :continue)
@histories[id] = [user, assistant]
leaf.turn_id = assistant.id
end
def provide(name, **options, &handler)
@provided_macros[name] = {options: options, handler: handler}
Struct.new(:name).new(name)
end
def signal_terminal(leaf_id)
name, definition = @provided_macros.find do |macro_name, _definition|
macro_name.end_with?(".terminal")
end
raise "terminal macro is not provided" unless name
definition.fetch(:handler).call(ProviderMacroCall.new(leaf_id: leaf_id))
end
def emit_completion(leaf, reason: "stop", message: nil, request_id: nil,
root_id: leaf.root_id, leaf_id: leaf.id)
signal_terminal(leaf.id)
acceptance = @acceptances[leaf.id]
frame = {
"type" => "prompt_completed", "request_id" => request_id || acceptance&.request_id,
"leaf_id" => leaf_id, "root_id" => root_id, "reason" => reason
}
frame["message"] = message if message
@events.publish(EzAgent::API.event_from_frame(frame))
end
def invoke(name, param_string:)
raise "unexpected macro" unless name == "default.unique_buffer"
@macro_params << param_string
return @macro_behavior.call(param_string) if @macro_behavior
number = @mutex.synchronize { @buffer_next += 1 }
type = param_string.empty? ? "tmp" : param_string.split(":", 2).first
path = File.join(@buffer_dir, "buffer-#{number}")
File.binwrite(path, "")
MacroResult.new(is_error: false,
result: JSON.generate("buffer_name" => "#{type}:prepared-#{number}", "path" => path))
end
private
def seed_passive_workflow_agent(leaf, workflow_identifier, agent_identifier)
workflow_id, = EzAgent::Workflow.decode_wf_identifier(workflow_identifier)
EzAgent::Workflow.decode_agent_identifier(agent_identifier)
turn = Turn.new(
id: "virtual-root-#{leaf.id}-1", root_id: leaf.root_id, leaf_id: leaf.id,
parent_id: nil, kind: "virtual_root", state: "sent", seq: 1,
content: "Ruby Workflow #{workflow_id.inspect} prepare: version-3 stable Agent " \
"#{agent_identifier.inspect}; no prompt or model call was made",
content_type: "text", timestamp: "2026-01-02T00:00:00Z"
)
@histories[leaf.id] << turn
leaf.turn_id = turn.id
end
def config_key?(key)
key.start_with?("workflow.", "active_") ||
%w[builtin.auto_title.state builtin.mode].include?(key)
end
def refresh_leaf_metadata(id)
leaf = @leaves.find { |candidate| candidate.id == id }
leaf.metadata = @metadata_store[id].merge(@config_store[id]) if leaf
leaf
end
end
module_function
def compact_active_prompt(api, leaf, acceptance, unrelated_user: false,
precompaction_user: false, success_marker: true,
connected_ancestry: true, emit_completion: true,
terminal_error: nil)
original = api.history(leaf.id).dup
accepted = original.find { |turn| turn.id == acceptance.tip_turn_id }
raise "accepted turn is unavailable" unless accepted
timestamp = "2026-01-03T00:01:00Z"
next_seq = original.map(&:seq).max
prior_assistant = Turn.new(
id: "precompact-assistant-#{leaf.id}", root_id: leaf.root_id, leaf_id: leaf.id,
parent_id: accepted.id, kind: "assistant", state: "sent", seq: next_seq += 1,
content: "working", content_type: "text", stop_reason: "tool_calls",
usage: "{}", other_meta: "{}", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
prior_tool = Turn.new(
id: "precompact-tool-#{leaf.id}", root_id: leaf.root_id, leaf_id: leaf.id,
parent_id: prior_assistant.id, kind: "tool_result", state: "sent",
seq: next_seq += 1, content: "tool evidence", content_type: "text",
timestamp: timestamp, exit_message: nil, exit_classification: :continue
)
precompaction_turns = []
boundary_parent = prior_tool.id
if precompaction_user
unrelated = Turn.new(
id: "precompact-unrelated-user-#{leaf.id}", root_id: leaf.root_id,
leaf_id: leaf.id, parent_id: boundary_parent, kind: "user", state: "sent",
seq: next_seq += 1, content: "unrelated accepted work before compaction",
content_type: "text", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
unrelated_assistant = Turn.new(
id: "precompact-unrelated-assistant-#{leaf.id}", root_id: leaf.root_id,
leaf_id: leaf.id, parent_id: unrelated.id, kind: "assistant", state: "sent",
seq: next_seq += 1, content: "result for unrelated work",
content_type: "text", stop_reason: "tool_calls", usage: "{}",
other_meta: "{}", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
precompaction_turns.concat([unrelated, unrelated_assistant])
boundary_parent = unrelated_assistant.id
end
detached = Turn.new(
id: "detached-#{leaf.id}", root_id: leaf.root_id, leaf_id: leaf.id,
parent_id: nil, kind: "tool_result", state: "sent", seq: next_seq,
content: "unrelated branch", content_type: "text", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
boundary = Turn.new(
id: "compact-root-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: connected_ancestry ? boundary_parent : detached.id,
kind: "virtual_root", state: "sent", seq: next_seq += 1,
content: "Compaction\nAutomatic: summarized earlier conversation and retained the current suffix.",
content_type: "text", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
system = Turn.new(
id: "compact-system-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: boundary.id, kind: "system", state: "sent", seq: next_seq += 1,
content: "current system", content_type: "text", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
continuation = Turn.new(
id: "compact-user-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: system.id, kind: "user", state: "sent", seq: next_seq += 1,
content: "<mode mode=\"build\" />\ngive the chat summary, and continue",
content_type: "text", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
summary = Turn.new(
id: "compact-summary-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: continuation.id, kind: "assistant", state: "sent", seq: next_seq += 1,
content: "summary of the accepted Workflow run", content_type: "text",
stop_reason: "stop", usage: "{}", other_meta: "{}", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
canonical = [boundary, system, continuation, summary]
parent_id = summary.id
if unrelated_user
unrelated = Turn.new(
id: "unrelated-user-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: parent_id, kind: "user", state: "sent", seq: next_seq += 1,
content: "a later unrelated request", content_type: "text", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
canonical << unrelated
parent_id = unrelated.id
end
working = Turn.new(
id: "continued-assistant-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: parent_id, kind: "assistant", state: "sent", seq: next_seq += 1,
content: "continuing after compaction", content_type: "text",
stop_reason: "tool_calls", usage: "{}", other_meta: "{}", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
tool = Turn.new(
id: "continued-tool-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: working.id, kind: "tool_result", state: "sent", seq: next_seq += 1,
content: "continued tool result", content_type: "text", timestamp: timestamp,
exit_message: nil, exit_classification: :continue
)
exit_message = terminal_error || (success_marker ? "SUCCESS" : nil)
exit_classification = if terminal_error
:error
elsif success_marker
:success
else
:continue
end
final = Turn.new(
id: "continued-final-#{leaf.id}", root_id: leaf.root_id, leaf_id: nil,
parent_id: tool.id, kind: "assistant", state: "sent", seq: next_seq + 1,
content: "compacted final result", content_type: "text",
stop_reason: terminal_error ? "error" : "stop",
usage: "{}", other_meta: JSON.generate("exit_message" => exit_message),
timestamp: timestamp, exit_message: exit_message,
exit_classification: exit_classification
)
canonical.concat([working, tool, final])
api.remember_tree_turns(original, prior_assistant, prior_tool, precompaction_turns)
api.remember_tree_turns(detached) unless connected_ancestry
api.history(leaf.id).replace(canonical)
leaf.turn_id = final.id
leaf.status = "idle"
if emit_completion
if terminal_error
api.emit_completion(leaf, reason: "error", message: terminal_error)
else
api.emit_completion(leaf)
end
end
{original: original, canonical: canonical, final: final, prompt: accepted}.freeze
end
# Unlike compact_active_prompt's legacy no-copy fixture, this models the
# current virtual-root payload and preserves hidden originals for turns.get.
# A callable retain selector receives history and the admitted prompt, and
# returns the first source turn to copy on each round.
# The optional block corrupts evidence before the completion event is emitted.
# work: false, finish: false models post-success compaction itself, without
# relocating the old terminal marker or adding a new model completion.
def compact_prompt_with_copies(api, leaf, acceptance, rounds: 1,
format: :automatic, retain: :prompt,
pivot: true, filtered_errors: false,
work: true, finish: true, final_text: "compacted final result",
emit_completion: true, terminal_error: nil)
api.tree_summaries = true
prompt = api.history(leaf.id).find { |turn| turn.id == acceptance.tip_turn_id }
raise "accepted turn is unavailable" unless prompt
compactions = []
rounds.times do |round|
held = retain == :held && round.zero?
if held
raise "held prompt must be the current tip" unless api.history(leaf.id).last == prompt
api.history(leaf.id).pop
leaf.turn_id = prompt.parent_id
elsif work
append_compaction_turn(api, leaf, kind: "error", content: "not replayable before work") if filtered_errors
append_compaction_work(api, leaf, "work before compaction #{round + 1}")
append_compaction_turn(api, leaf, kind: "error", content: "not replayable after work") if filtered_errors
end
original = api.history(leaf.id).dup
anchor_index = if held
nil
elsif retain == :none
original.length
elsif retain.respond_to?(:call)
original.index(retain.call(original, prompt))
elsif retain == :assistant
original.rindex { |turn| turn.kind == "assistant" }
else
original.index { |turn| turn.kind == "user" && turn.content == prompt.content }
end
retained = held ? [] : original.drop(anchor_index).reject { |turn| %w[virtual_root error].include?(turn.kind) }
anchor = held ? prompt.id : retained.first&.id
pivot_id = held ? original.last.id : original.fetch(anchor_index - 1).id
reason = "Compaction\n#{format == :manual ? 'Manual' : 'Automatic'}: " \
"summarized earlier conversation and retained the current suffix."
reason += "\nAnchor: #{anchor}" if format == :automatic
metadata = {}
if format == :marked
reason = "History shortened for this run"
metadata = {"continuation" => true, "fixture_extra" => {"unknown" => [1, true]}}
metadata["pivot_turn_id"] = pivot_id if pivot
end
api.remember_tree_turns(original)
api.history(leaf.id).clear
boundary = append_compaction_turn(api, leaf, kind: "virtual_root", content: reason,
other_meta: JSON.generate(metadata))
system = append_compaction_turn(api, leaf, kind: "system", content: "current system")
continuation = append_compaction_turn(
api, leaf, kind: "user",
content: format == :marked ? "Resume using the following notes" :
"<mode mode=\"build\" />\nSkills: /ruby /unslop\ngive the chat summary, and continue"
)
summary = append_compaction_turn(
api, leaf, kind: "assistant", content: "summary of earlier work #{round + 1}",
stop_reason: "stop", usage: "{}"
)
newest_assistant = retained.rindex { |turn| turn.kind == "assistant" }
copies = retained.each_with_index.map do |source, index|
fields = source.to_h.reject do |key, _value|
%i[id root_id leaf_id parent_id seq timestamp exit_message exit_classification].include?(key)
end
metadata = JSON.parse(source.other_meta || "{}")
# The compactor removes exit_message; virtual-root admission also
# scrubs background_progress instead of accepting producer claims.
fields[:other_meta] = JSON.generate(metadata.reject do |key, _value|
%w[exit_message background_progress].include?(key)
end)
if index == newest_assistant
output = JSON.parse(source.usage || "{}").fetch("output", 0)
fields[:usage] = JSON.generate(
"input" => 120, "output" => output, "cacheRead" => 0,
"cacheWrite" => 0, "totalTokens" => 120 + output
)
end
append_compaction_turn(api, leaf, **fields).tap { |copy| copy.leaf_id = nil }
end
if held
# A held draft keeps its admitted ID instead of becoming a copied turn.
prompt.parent_id = summary.id
prompt.seq = summary.seq + 1
api.history(leaf.id) << prompt
leaf.turn_id = prompt.id
end
compactions << {boundary: boundary, system: system, continuation: continuation,
summary: summary, retained: retained, copies: copies, anchor: anchor,
pivot: pivot_id, original: original}
end
append_compaction_work(api, leaf, "work after compaction") if work
exit_message = terminal_error || "SUCCESS"
final = if finish
append_compaction_turn(
api, leaf, kind: "assistant", content: final_text,
stop_reason: terminal_error ? "error" : "stop",
usage: "{}", other_meta: JSON.generate("exit_message" => exit_message),
exit_message: exit_message, exit_classification: terminal_error ? :error : :success
)
else
api.history(leaf.id).last
end
leaf.status = "idle"
shape = {prompt: prompt, final: final, compactions: compactions,
canonical: api.history(leaf.id).dup}.freeze
yield shape if block_given?
if emit_completion && finish
api.emit_completion(leaf, reason: terminal_error ? "error" : "stop", message: terminal_error)
end
shape
end
def append_compaction_turn(api, leaf, **fields)
seq = api.list_tree(leaf.root_id).map(&:seq).max.to_i + 1
turn = Turn.new(
id: "compaction-fixture-#{leaf.id}-#{seq}", root_id: leaf.root_id,
leaf_id: leaf.id, parent_id: leaf.turn_id, seq: seq, state: "sent",
content_type: "text", timestamp: "2026-01-04T00:00:00Z",
other_meta: "{}", exit_message: nil, exit_classification: :continue,
**fields
)
api.history(leaf.id) << turn
leaf.turn_id = turn.id
turn
end
def append_compaction_work(api, leaf, text)
append_compaction_turn(
api, leaf, kind: "assistant", content: text, thinking: "checking the evidence",
model: "fixture-model", provider: "fixture-provider", stop_reason: "tool_calls",
usage: '{"input":900,"output":17,"cacheRead":30,"cacheWrite":10,"totalTokens":917,"historical":true}',
other_meta: '{"fixture":"preserved"}'
)
append_compaction_turn(
api, leaf, kind: "tool_result", content: "tool evidence for #{text}",
tool_call_id: "call-#{leaf.turn_id}", tool_name: "fixture.inspect"
)
end
def workflow(api: nil, **options)
EzAgent::Workflow.new(id: "release", title: "Release", estimated_phases: 3,
api: api, **options)
end
def identifier(query, attempt: 0)
EzAgent::Workflow.encode_query_identifier(
id: query.workflow.id, nonce: query.workflow.nonce,
agent_path: query.owner.agent_path, operation_key: query.key,
generation: query.generation, try_occurrence: attempt
)
end
def with_leaf_id(value)
present, old = ENV.key?("EZ_AGENT_LEAF_ID"), ENV["EZ_AGENT_LEAF_ID"]
value.nil? ? ENV.delete("EZ_AGENT_LEAF_ID") : ENV["EZ_AGENT_LEAF_ID"] = value
yield
ensure
present ? ENV["EZ_AGENT_LEAF_ID"] = old : ENV.delete("EZ_AGENT_LEAF_ID")
end
# Answers a fake prompt RPC parked on +release+ once cancellation starts,
# as a live service answers a pending prompt RPC. Cancellation sends no
# abort before acceptance, so a fixture that waits for abort instead holds
# close for the full prompt admission settlement bound plus worker drain
# (~13s). Tests that need an unanswered RPC must not use this.
def release_prompt_on_cancellation(workflow, release, timeout: 10)
releaser = Thread.new do
RubyAPITest.wait_until(timeout: timeout) { workflow.__send__(:cancellation_requested?) }
release << true
end
releaser.report_on_exception = false
RubyAPITest.defer_cleanup { releaser.value }
releaser
end
end