Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Derive the injected actor keywords, and stop eager-loading on reload
Damian Legawiec916ea19d13dd
diff --git a/spree/api/lib/spree/api/agent_resource_map.rb b/spree/api/lib/spree/api/agent_resource_map.rbindex a46cb3bec1..f3a39ca881 100644--- a/spree/api/lib/spree/api/agent_resource_map.rb+++ b/spree/api/lib/spree/api/agent_resource_map.rb@@ -97,6 +97,16 @@ module Spree}.freezeclass << self+ # Registers this walk as how the core map fills itself, and marks the+ # map stale so the next reader gets a fresh one. Called on every code+ # reload; the walk itself runs when something actually reads the map.+ #+ # @return [void]+ def stale!+ Spree::AgentTools::ResourceMap.deriver = -> { install }+ Spree::AgentTools::ResourceMap.stale!+ end+# Walks every admin resource controller and registers what it serves.## @param map [Class] defaults to the core resource map@@ -104,13 +114,12 @@ module Spreedef install(map: Spree::AgentTools::ResourceMap)map.reset!- derived = controllers.filter_map { |controller| derive(controller) }-- resolve_collisions(derived).each { |entry| map.register(**entry) }+ registered = resolve_collisions(controllers.filter_map { |controller| derive(controller) })+ registered.each { |entry| map.register(**entry) }DYNAMIC_SCOPE_RESOURCES.each { |key, attributes| map.register(key: key, **attributes) }- map.all.size+ registered.size + DYNAMIC_SCOPE_RESOURCES.sizeend# Every admin resource controller in the application, the abstract@@ -237,11 +246,18 @@ module Spreereturn false unless model.respond_to?(:for_store)return true if model.method(:for_store).owner != Spree::Base.singleton_class- !model.for_store(Spree::Store.new).equal?(model)+ !model.for_store(probe_store).equal?(model)rescue StandardErrorfalseend+ # One unsaved store, reused: the probe asks what `for_store` does with+ # a store, not with any particular one, and the walk covers every+ # admin controller.+ def probe_store+ @probe_store ||= Spree::Store.new+ end+# The workflow a controller writes through, as its dotted key, so a# generic write can name the tool that does the job instead.def workflow_key(instance, method_name)diff --git a/spree/api/lib/spree/api/agent_write_schemas.rb b/spree/api/lib/spree/api/agent_write_schemas.rbindex ae0f97b820..6b5f3d056c 100644--- a/spree/api/lib/spree/api/agent_write_schemas.rb+++ b/spree/api/lib/spree/api/agent_write_schemas.rb@@ -33,11 +33,6 @@ module Spreeself.for(key).keysend- # @return [void]- def reset!- @schemas = nil- end-# Where the generated document lives, relative to this engine. Resolved# lazily: the engine class does not exist yet while this file loads.#diff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rbindex ebe14dd849..c3f11a8673 100644--- a/spree/api/lib/spree/api/engine.rb+++ b/spree/api/lib/spree/api/engine.rb@@ -22,11 +22,13 @@ module Spreeend# The resources agents may read and write are derived from the admin- # controllers themselves (see Spree::Api::AgentResourceMap). Rebuilt on- # every reload, because a controller edited in development changes what- # the map should say.+ # controllers themselves (see Spree::Api::AgentResourceMap). Marked+ # stale on every reload rather than rebuilt: deriving it eager-loads the+ # application, and doing that on each file save would turn Spree's+ # development reload from lazy into fully eager for everyone, whether or+ # not they run an agent client. The first caller pays instead.config.to_prepare do- Spree::Api::AgentResourceMap.install+ Spree::Api::AgentResourceMap.stale!end# Add API event subscribersdiff --git a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rbindex 4b9981e7e0..f2063b9bc0 100644--- a/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb+++ b/spree/api/spec/lib/spree/api/agent_tools_contract_spec.rb@@ -94,7 +94,7 @@ RSpec.describe 'agent tool contract' doit 'derives a schema for every exposed workflow' dofailures = catalog::WORKFLOWS.filter_map do |key, options|options = { permission: options } unless options.is_a?(Hash)- Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except])).to_json_schema+ Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except])).parametersnilrescue StandardError => e"#{key}: #{e.message}"@@ -139,17 +139,39 @@ RSpec.describe 'agent tool contract' doMESSAGEend- it 'never offers a principal parameter to the caller' do+ # Asserted against the naming convention rather than against the injected+ # list, which would be circular: a parameter is only offered because it is+ # not on that list, so comparing the two can never fail. A keyword that+ # reads as "who did this" and is still offered is the bug worth catching.+ it 'never offers a parameter that names who acted' do+ # `<verb>ed_by` is the shape that names a person. A `cancel_by` is a+ # date the merchant sets, not an actor, so the participle matters.+ actor_shaped = /\A(\w+ed_by|created_by|canceler|approver|reviewer|refunder|requester)\z/+offered = catalog::WORKFLOWS.flat_map do |key, options|options = { permission: options } unless options.is_a?(Hash)schema = Spree::AgentTools::WorkflowSchema.new(Spree.public_send(key), except: Array(options[:except]))schema.parameters.filter_map do |parameter|- "#{key}.#{parameter[:name]}" if Spree::AgentTools::WorkflowSchema::PRINCIPAL_PARAMETERS.include?(parameter[:name])+ "#{key}.#{parameter[:name]}" if parameter[:name].to_s.match?(actor_shaped)endend- expect(offered).to be_empty+ expect(offered).to be_empty, <<~MESSAGE+ These parameters name who performed the action, and the answer is the+ authenticated principal — never something a caller may claim:++ #{offered.join("\n ")}++ Declare the association with `acted_by` so it is injected, or add the+ keyword to WorkflowSchema::UNCONVERTED_PRINCIPAL_PARAMETERS until it is.+ MESSAGE+ end++ it 'injects every actor association the acted_by registry knows' do+ declared = Spree::ActedBy.models.flat_map(&:acted_by_associations).map(&:to_sym)++ expect(Spree::AgentTools::WorkflowSchema.principal_parameter_names).to include(*declared)endit 'gives every exposed workflow a unique tool name' dodiff --git a/spree/core/app/tools/spree/agent_tools/get_resource.rb b/spree/core/app/tools/spree/agent_tools/get_resource.rbindex cd9d25ecb5..a8c897bbf9 100644--- a/spree/core/app/tools/spree/agent_tools/get_resource.rb+++ b/spree/core/app/tools/spree/agent_tools/get_resource.rb@@ -18,6 +18,8 @@ module Spreerecord = find_record(entry, id)return { error: "No #{entry.key.singularize} found for #{id.inspect}" } if record.nil?+ attributes = Spree::AgentTools::RecordSummary.sanitize(entry.serializer_class.new(record).to_h)+{resource: entry.key,# The full record for the model to answer from, plus the same@@ -28,8 +30,8 @@ module Spree# that emits a whole serializer hash, so without the filter a# serializer that gains a token field would send it straight to the# AI vendor — the exact case the filter exists for.- record: Spree::AgentTools::RecordSummary.sanitize(entry.serializer_class.new(record).to_h),- records: [Spree::AgentTools::RecordSummary.call(entry: entry, record: record)],+ record: attributes,+ records: [Spree::AgentTools::RecordSummary.call(entry: entry, record: record, attributes: attributes)],count: 1,total: 1}diff --git a/spree/core/app/tools/spree/agent_tools/resource_write.rb b/spree/core/app/tools/spree/agent_tools/resource_write.rbindex 67f0ba2b0d..d8ec0354f1 100644--- a/spree/core/app/tools/spree/agent_tools/resource_write.rb+++ b/spree/core/app/tools/spree/agent_tools/resource_write.rb@@ -88,15 +88,16 @@ module Spree# Saves through the model's own validations, and hands their messages# back verbatim when it refuses.def save_record(entry, record)- if record.save- { summary: summary_for(entry, record), record: RecordSummary.call(entry: entry, record: record) }- else- { error: record.errors.full_messages.to_sentence }- end+ return { error: record.errors.full_messages.to_sentence } unless record.save++ # One serialization: the summary line needs the record's title, which+ # is what the summary row already carries.+ row = RecordSummary.call(entry: entry, record: record)++ { summary: summary_for(entry, row[:title]), record: row }end- def summary_for(entry, record)- label = RecordSummary.call(entry: entry, record: record)[:title]+ def summary_for(entry, label)"#{self.class.tool_name.humanize} #{entry.key.singularize.humanize.downcase} #{label}"enddiff --git a/spree/core/app/tools/spree/agent_tools/search_resources.rb b/spree/core/app/tools/spree/agent_tools/search_resources.rbindex 217e060af2..7bbaa5900e 100644--- a/spree/core/app/tools/spree/agent_tools/search_resources.rb+++ b/spree/core/app/tools/spree/agent_tools/search_resources.rb@@ -69,8 +69,16 @@ module Spreeprivate+ # Preloaded the way the admin controllers preload: the summary row runs+ # the resource's own serializer, whose associations would otherwise be+ # one query per record.+ def searchable_scope(entry)+ scope = entry.scope_for(context)+ scope.respond_to?(:preload_associations_lazily) ? scope.preload_associations_lazily : scope+ end+def build_query(entry, filters, sort)- query = entry.scope_for(context).ransack(filters)+ query = searchable_scope(entry).ransack(filters)query.sorts = sort if sort.present?queryenddiff --git a/spree/core/lib/spree/agent_tools/context.rb b/spree/core/lib/spree/agent_tools/context.rbindex 9d7b527659..ca87f00977 100644--- a/spree/core/lib/spree/agent_tools/context.rb+++ b/spree/core/lib/spree/agent_tools/context.rb@@ -52,7 +52,6 @@ module Spreedef principaluser || api_keyend- alias actor principal# @return [Boolean] whether a signed-in admin is askingdef user_principal?diff --git a/spree/core/lib/spree/agent_tools/record_summary.rb b/spree/core/lib/spree/agent_tools/record_summary.rbindex 6287c185b7..aa85f7cf7a 100644--- a/spree/core/lib/spree/agent_tools/record_summary.rb+++ b/spree/core/lib/spree/agent_tools/record_summary.rb@@ -58,9 +58,12 @@ module Spree# @param entry [Spree::AgentTools::ResourceMap::Entry]# @param record [ActiveRecord::Base]+ # @param attributes [Hash, nil] an already-sanitized serializer hash,+ # for a caller that needs the full record too — serializing twice+ # means running every association query twice# @return [Hash]- def call(entry:, record:)- attributes = serialize(entry, record)+ def call(entry:, record:, attributes: nil)+ attributes ||= serialize(entry, record)title = title_for(record, attributes){diff --git a/spree/core/lib/spree/agent_tools/registry.rb b/spree/core/lib/spree/agent_tools/registry.rbindex 7881e1a2b8..d9bcaa4ad4 100644--- a/spree/core/lib/spree/agent_tools/registry.rb+++ b/spree/core/lib/spree/agent_tools/registry.rb@@ -71,24 +71,11 @@ module Spree# @return [Hash{Symbol => Hash}] every exposed workflow, by dependency keyattr_reader :exposed_workflows- # Forgets every workflow exposure. For specs that register their own.- #- # @return [void]- def reset_workflows!- @exposed_workflows = {}- end-# @return [Array<Class<Spree::AgentTool>>]def to_aregistered_classes + workflow_tool_classesend- # @param name [String]- # @return [Class<Spree::AgentTool>, nil]- def find_by_name(name)- to_a.find { |tool_class| tool_class.tool_name == name.to_s }- end-# Tools this caller may actually use, instantiated for their context.# This is what an adapter offers the model — a caller without# `write_products` never learns that a price-changing tool exists.diff --git a/spree/core/lib/spree/agent_tools/resource_map.rb b/spree/core/lib/spree/agent_tools/resource_map.rbindex 0cdf6f719f..9cdbd33efd 100644--- a/spree/core/lib/spree/agent_tools/resource_map.rb+++ b/spree/core/lib/spree/agent_tools/resource_map.rb@@ -124,8 +124,16 @@ module Spreeclass << self+ # How the map fills itself the first time it is read. `spree_api` sets+ # this to its controller walk; core owns only the structure, so an+ # installation without the API engine simply has an empty map.+ #+ # @return [#call, nil]+ attr_accessor :deriver+# @return [Array<Entry>] every registered resource, in registration orderdef all+ derive!entries.valuesend@@ -172,9 +180,31 @@ module Spree# @param key [String]# @return [Entry, nil]def find(key)+ derive!entries[key.to_s]end+ # Marks the map for rebuilding on its next read. Called on every code+ # reload, because a controller edited in development changes what the+ # map should say — but the rebuild itself waits for a reader.+ #+ # @return [void]+ def stale!+ @derived = false+ end++ # Fills the map once, from whatever `deriver` was registered.+ #+ # @return [void]+ def derive!+ return if @derived || deriver.nil?++ # Set before calling, so a deriver that reads the map while filling+ # it does not recurse.+ @derived = true+ deriver.call+ end+# Resources this caller may read, so a tool description lists only what# they can actually ask about.#diff --git a/spree/core/lib/spree/agent_tools/workflow_schema.rb b/spree/core/lib/spree/agent_tools/workflow_schema.rbindex bd5cb6add3..603632bccb 100644--- a/spree/core/lib/spree/agent_tools/workflow_schema.rb+++ b/spree/core/lib/spree/agent_tools/workflow_schema.rb@@ -25,14 +25,14 @@ module Spree# answer to "which store" is the API key or the signed-in admin.CONTEXT_PARAMETERS = %i[store].freeze- # Parameters the caller never supplies: they say who acted, and the- # answer is the authenticated principal, not something a model should be- # free to name. The adapter injects `context.principal` for whichever of- # these the workflow takes.- PRINCIPAL_PARAMETERS = %i[- canceler approver reviewer refunder created_by received_by- completed_by rejected_by accepted_by waived_by suspended_by- invited_by requested_by resolved_by denied_by verified_by+ # Actor keywords a workflow takes whose association has not been+ # converted to `acted_by` yet — the 6.1 half of+ # docs/plans/6.0-action-actors.md. They are principals by the same+ # reasoning as the converted ones, so they are injected too; each drops+ # off this list as its association converts, and the registry below then+ # carries it.+ UNCONVERTED_PRINCIPAL_PARAMETERS = %i[+ reviewer reviewed_by rejected_by suspended_by verified_by reopened_by].freeze# YARD type to JSON type. A model type is handled separately — it becomes@@ -86,7 +86,7 @@ module Spree## @return [Array<Symbol>]def principal_parameters- keywords.keys & PRINCIPAL_PARAMETERS+ keywords.keys & self.class.principal_parameter_namesend# The tenancy keywords this workflow accepts.@@ -100,20 +100,7 @@ module Spree## @return [Array<Symbol>]def injected_parameters- PRINCIPAL_PARAMETERS + CONTEXT_PARAMETERS- end-- # @return [Hash] a JSON Schema object for the tool's arguments- def to_json_schema- properties = parameters.to_h do |parameter|- [parameter[:name].to_s, property_for(parameter)]- end-- {- type: 'object',- properties: properties,- required: parameters.select { |parameter| parameter[:required] }.map { |parameter| parameter[:name].to_s }- }+ self.class.principal_parameter_names + CONTEXT_PARAMETERSendprivate@@ -143,13 +130,6 @@ module Spree}end- def property_for(parameter)- property = { type: parameter[:json_type] }- property[:description] = parameter[:description] if parameter[:description].present?- property[:items] = { type: parameter[:item_type] } if parameter[:json_type] == 'array'- property- end-def description_for(text, model_name)return text if model_name.blank?@@ -204,6 +184,26 @@ module Spreeendclass << self+ # Every keyword that names who acted, so none is ever offered to a+ # caller as a free parameter.+ #+ # Read from {Spree::ActedBy} rather than listed here: the macro already+ # records each actor association per model, exactly so a caller+ # sweeping them walks all of them without being handed a list. A model+ # that gains an actor gains it here in the same commit, and a name+ # nobody declares cannot linger.+ #+ # @return [Array<Symbol>]+ def principal_parameter_names+ declared = if defined?(Spree::ActedBy)+ Spree::ActedBy.models.flat_map(&:acted_by_associations).map(&:to_sym)+ else+ []+ end++ (declared | UNCONVERTED_PRINCIPAL_PARAMETERS).uniq+ end+# Parsed once per workflow class and cached, because a tool list is# built for every MCP request and the source never changes at runtime.#diff --git a/spree/core/lib/spree/agent_tools/workflow_tool.rb b/spree/core/lib/spree/agent_tools/workflow_tool.rbindex f0438cc13c..3f5cdea874 100644--- a/spree/core/lib/spree/agent_tools/workflow_tool.rb+++ b/spree/core/lib/spree/agent_tools/workflow_tool.rb@@ -98,6 +98,7 @@ module Spreederived_schema.parameters.each do |parameter|param parameter[:name],type: parameter[:json_type].to_sym,+ items: parameter[:item_type]&.to_sym,description: parameter[:description],required: parameter[:required]end