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.
Service Workflows — one step DSL for services, sagas, hooks and events
Status: In Progress — Phase 1 implemented as a two-tier split (2026-07-30): Spree::Workflow (the DSL) powers the curated flows in app/workflows/; every other service stays a plain ServiceModule class. Phase 3 (extension surface: run_hooks returning a merged hash, reject!, validate/context hooks, four service graduations) shipped 2026-08-02. See Workflow and hook inventory below for the 31 shipped workflows and their extension points, To deliver for what is still planned, and Known gaps for what is wrong in what shipped
Target: Spree 6.0
Depends on: 6.0-cart-order-split.md (Carts::Complete is the reference implementation and stress test). Coordinates with: 6.0-multi-vendor-marketplace.md (payout runs are the first durable-flow consumer), the Rails 8.1 floor decision (decisions.md 2026-07-29 — ActiveJob Continuations are the durability primitive).
Author: Damian Legawiec + Claude (design session 2026-07-30)
Last updated: 2026-08-05
Summary
Services, sagas, extension points and events are today four unrelated idioms:
ServiceModule run-pipelines threading raw kwarg hashes between steps,
Carts::Complete hand-rolling phases/compensation/resumability, extensions
choosing between replacing a whole service (Spree::Dependencies) or reacting
after commit (subscribers), and publish_event calls buried inside bodies.
This plan evolves ServiceModule — in place, additively — into a declared
step DSL (argument / step / on_flow_failure: / run_hooks / emit /
transaction grouping) so one mental model covers a two-step item service and the
completion saga alike. Medusa's workflows are the DX benchmark; the runtime
stays plain Ruby inside Rails transactions — no execution-state tables, no
engine. Carts::Complete is the stress test: the DSL is done when the
completion pipeline expresses its lock scopes, out-of-transaction payment
I/O, compensation and structural resumability with its entire spec battery
green and its observable semantics byte-identical.
Problem
- Step contracts are implicit. Pipeline steps receive whatever kwargs the
caller passed (
@_passed_inputseeds from the raw hash); renames and new keys fail at runtime asIncompatibleParamsPassed, or worse, silently (the 2026-07-30cart:kwarg sweep broke exactly this way;rewrite_input!exists only to patch the seed mid-flight). - Sagas are bespoke. Compensation, resumability and TTL sweeping live as
one-off code in
Carts::Complete; the next saga (marketplace payouts, claims) would reinvent all three. - Extensions have an axe and a megaphone, no scalpel. They can swap an entire service class or subscribe after commit — there is no supported way to inject logic inside a flow, in-transaction, at a named point.
- Events are invisible side effects. What a service announces is discoverable only by reading its body; subscribers form a second, parallel system with its own discovery problem (the never-built status subscriber hid for months).
Key Decisions (do not deviate without discussion)
Two tiers, one caller contract (2026-07-30 — supersedes the earlier "evolve ServiceModule in place" framing).
app/services/holds plainServiceModuleclasses — hand-writtendef call(cart:, ...), standard Ruby, zero DSL vocabulary; this is the permanent default, not a legacy tier.app/workflows/holdsSpree::Workflow(the DSL below), earned only by flows needing an extension hook, compensation/external I/O, replay/halt semantics, or a durable future. Initial set:Carts::Complete,Carts::AddItem,Carts::Recalculate,Carts::RecalculateTotals(+ order twins); a service graduates to the workflow tier the moment it earns a hook — never speculatively. First graduation (2026-07-31):Orders::Cancel, absorbing the orchestration buried inOrder#after_cancel— the cancellation record, status flip and fulfillment cancellation commit atomically with theafter_cancelhook inside the transaction, while payment settlement (gateway voids and refunds, previously running inside the DB transaction) moved to anexternal_stepafter commit. Workflow-backedSpree::Dependenciesseams are named*_workflow(order_cancel_workflow,cart_add_item_workflow,cart_recalculate_workflow,carts_complete_workflow,cart/order_recalculate_totals_workflow); the legacy*_servicenames stay settable and readable one release (reads, writes and top-levelSpree.*resolution — no boot crashes), but a legacy write is stashed, NOT applied: a class written against the old service contract is not interchangeable with the workflow the new call sites consume, so the warning says the override was not applied and names the*_workflowseam to port to. Legacy reads fall back to the workflow class, which accepts the old keyword vocabulary through itsalias_argumentbridges. Removed in 6.1.Callable.call,Result,success/failurestay the shared caller contract across both tiers — callers cannot tell them apart.No engine. No execution-state tables, no visualizer, no parallel executor, no cross-process orchestration in this plan. Medusa needs those because its modules cross process boundaries; inside one Rails process they are ceremony. Durable flows get state from ActiveJob Continuations (Phase 2), not from us.
The #perform signature is the argument contract (2026-07-31 — the perform-composed shape, superseding the class-declared
argument/ context/provides:design). A workflow defines a plaindef perform(order:, canceler: nil, reason: 'other'): Ruby itself raises on missing/unknown keywords, YARD documents it, and a baresuperfirst line assigns every parameter — defaults applied — to an ivar with a public reader. Data between steps flows through locals and instance variables, the before_action idiom every Rails developer already knows. The earlier shape's typed/union argument checks, alias macros, Context classes and write-schema validation are gone; twin vocabularies are plain overrides (def perform(order:, **rest) = super(cart: order, **rest)), and deprecated keywords are guard clauses in perform.Transactions and locks are plain Rails.
ApplicationRecord.transaction doandcart.with_lock doinside perform — no grouping DSL. What makes that sound:failure(...)RAISES an internal control-flow signal (Exception, not StandardError — the ActiveJob Continuation::Interrupt precedent, so a plainrescuein perform can't swallow it), which unwinds an open transaction into a natural rollback before the runner converts it to the failure Result;halt!(value)is its successful twin, forbidden inside workflow-opened transactions.external_steprefuses to run inside a transaction the workflow itself opened — guarded by transaction-depth delta, so a caller-level wrapping transaction (the admin API's order lock) stays the caller's business.on_flow_failure:names a step's undo, armed viaApplicationRecord.current_transaction.after_commitwhen the workflow-opened transaction around the step commits (immediately when there is none), and popped in reverse when a later step fails — rollback remains the compensation inside an uncommitted transaction.Hooks:
hooks :after_canceldeclares the extension points (class-level, one line, soSpree.hooks.validate!still fails boot on registrations against hooks that don't exist);run_hooks :after_cancelinside perform dispatches every registered handler with the workflow instance — argument readers plus whatever the workflow exposes via plainattr_readerare the handler contract, visible in the file instead of computed. Registry unchanged otherwise: dotted keys, class name handlers constantized at dispatch,Spree.hooks.register, introspection facade. Hook keys are public API.Events are
publish_event, not workflow syntax (2026-07-31). The established Publishable vocabulary is used inline in perform —order.publish_event('order.canceled', ...)— positioned after the transaction block and beforesuccess(...), which gives after-commit-only-on-success ordering for free. The earlieremitdeclaration is gone.The consistency doctrine ships as documentation in the same PR: step — must be true in the same transaction; sync subscriber — must be true in the same request (statuses); async subscriber — eventually (emails, webhooks, metrics). One table, linked from CLAUDE.md.
Carts::Completeis the acceptance test, not a rewrite target. The retrofit must preserve, observably unchanged: P1 replay idempotency, in-lockexpected_totalverification,completing_atTTL + sweeper resume, pre-capture-only compensation, after-commit-only event emission, and thecomplete_orderdraft branch. The existing spec battery runs unmodified — if a spec has to change, the DSL is wrong, not the spec.Dependency swapping gains step granularity, keeps service granularity.
Spree.cart_add_item_servicecontinues to resolve the class; inside a flow,step :reserve_stock, with: -> { Spree.stock_reserve_service }keeps step implementations swappable without subclassing the whole flow.Workflows replace state machines for new models (2026-08-02). A new model gets a plain
statusstring column with an inclusion validation and generated predicates — never astate_machine :statusblock. Transitions are workflows:Spree::Returns::Receive.call(...), notreturn.receive!. See "State machines" below for the full rule and the narrow exceptions.Hook keys are public API and ship on the 6.0 boundary (2026-08-02 — amends decision 6 and the "never speculatively" clause in decision 1). The original rule — a service graduates the moment it earns a hook, and hooks are added by demand — was written to prevent speculative abstraction, and it still governs workflows. It does not govern hooks on flows already in the workflow tier. A hook is a published extension point: adding one later is cheap, but moving one means restructuring a flow extension authors have already registered against, which is a breaking change. 6.0 is the breaking-change window. A documented, coherent extension surface is itself the demand — so hooks are placed deliberately across the existing workflows now, at the points a third-party integration would need them, rather than one at a time as individual merchants ask. The bar remains real: a hook must name a point where an extension would plausibly inject behaviour, and every hook ships documented. Speculative workflows are still forbidden.
Customer registration is a workflow; the welcome email leaves core (2026-08-05).
Spree::Customers::Creategraduates on real demand, not speculation: registration is the canonical veto point (bot and disposable-email screening, fraud checks, B2B "registration requires approval" — all need to reject a signup, which theuser.createdlifecycle event cannot do), and creation today carries multi-record side effects scattered inconsistently across three paths (newsletter-subscriber linking and consent propagation on self-registration only, address adoption and welcome email on the checkout path only, neither on admin create). The workflow absorbsOrders::CreateUserAccountvia an optionalorder:argument — one flow, one workflow — so store self-registration, the checkout "create an account" box, and (later) storefront OIDC auto-provisioning all flow through one seam (customer_create_workflow); the old service class stays as a deprecated one-release shell. Deliberately not routed through it: the Admin API create action (plain CRUD, and staff creation must not be blockable by registration-policy hooks) and JWT/refresh-token issuance (an HTTP session concern that stays in the controller — the workflow returns the customer, the controller mints tokens). The welcome email is dropped from core entirely: nosend_welcome_emailcall anywhere; signup email is host-app implementation via auser.createdsubscriber or thecustomers.create.after_createhook, consistent with headless storefronts owning consumer email. The host-app migration step is written up in decisions.md 2026-08-05 ("Upgrade step (host applications)") and belongs in the 6.0 upgrade manifest.
Hooks
Three families, because they solve different problems:
Lifecycle hooks — past tense, fired after something happened, for
extensions that react: after_item_added, after_cancel, after_confirm.
Handlers read the workflow instance and cannot change the outcome. This is
what we ship today.
Validation hooks — validate, fired before the work, for extensions that
reject. A handler calls reject!(message) on the workflow to abort the flow
(contract below). This is the seam merchants ask for most (return windows, B2B
purchase limits, per-group eligibility) and today they have to replace the
whole workflow class to get it.
Context hooks — imperative (set_pricing_context, set_tax_line_context,
set_promotion_context, get_provider_data), fired before a calculation so
extensions can feed data into it.
Hook contracts (resolved 2026-08-02)
Context hooks collect and deep-merge handler return values. A handler
returns a hash; run_hooks merges every handler's hash in registration order
and returns the result. No shared mutable state — handlers stay pure and
independently testable, and a handler that returns nil contributes nothing
rather than corrupting the context.
# Handler
class MyApp::PricingContext
def call(workflow)
{ customer_tier: workflow.cart.customer&.tier }
end
end
# Workflow
context = run_hooks(:set_pricing_context) # => { customer_tier: 'gold' }
Spree.price_selector.call(cart, **context)
run_hooks returning a value is additive — lifecycle hooks ignore the return
and are unaffected. On a key collision the last registered handler wins, and
the collision is logged via Rails.error.report in development so two
extensions fighting over the same key is visible rather than mysterious.
validate handlers reject with reject!(message). A purpose-named method
on the workflow that wraps the existing failure path — it raises
FailureSignal, so the undo stack unwinds and an open transaction rolls back
exactly as a failed step would. The distinct name keeps "an extension vetoed
this" legible against "this step failed" at the call site.
class MyApp::LimitReturnWindow
def call(workflow)
return if workflow.order.completed_at > 30.days.ago
workflow.reject!(Spree.t('returns.errors.outside_window'))
end
end
What is public API (resolved 2026-08-02)
The 6.0 extension surface is deliberately narrow, because everything in it is frozen for the release:
Public — hook keys and their contracts, reject!, Spree::Dependencies
class swapping, has_status/add_status, workflow #perform keyword
signatures.
Internal — with: step targets, step names, step boundaries and ordering.
step :reserve_stock, with: -> { Spree.stock_reserve_service } stays a core
seam: documenting it would freeze every step name and its collaborator kwarg
contract as public API, locking internal structure we still expect to refactor
during the 6.0 finishing work. Extensions get hooks (finer-grained than class
swapping, and safe) and Dependencies (coarser, already public). Revisit in 6.1
once real hook usage shows what is genuinely missing.
Configurable statuses
Spree::HasStatus (see "State machines" below) holds its values in a
class_attribute, not a frozen constant, so extensions can add statuses
without reopening core. The API is deliberately additive only:
# Core
class Spree::Return < Spree.base_class
has_status :requested, :approved, :received, :refunded, :canceled,
default: :requested
end
# Extension decorator
Spree::Return.add_status(:inspecting, after: :received)
Spree::Return.statuses
# => %w[requested approved received inspecting refunded canceled]
Adding is safe; wholesale replacement is not offered. Core workflows guard on
core statuses (Returns::Refund requires received?), so allowing an
extension to remove one would silently break core flows with no error at the
point of removal — the guard would simply never pass.
A custom status needs a custom workflow to move records into it. That is the
intended shape, not a gap: add_status deliberately takes no from:/to:
transition graph, because validating transitions centrally is a state machine
by another name — the exact thing decision 11 removes. Extensions write a
workflow the same way core does.
State machines
state_machines-activerecord stays a dependency through 6.0 for the models
that still carry machines (Payment, Fulfillment, InventoryUnit,
ReturnAuthorization, GiftCard — see 6.0-normalize-state-to-status.md).
New models do not get state machines. The reasoning, argued at length in
6.0-returns-exchanges-claims.md → "Why workflows, not state machines":
- Transition callbacks run inside the save transaction, which puts gateway I/O
in a database transaction — the exact failure
Carts::Complete's three-phase design exists to prevent. - Transitions take no arguments, so partial and contextual operations (receive two of three items, one not resellable) have nowhere to put their inputs.
- There is no compensation story;
on_flow_failure:is. - Guards raise
StateMachines::InvalidTransitioninstead of returning an inspectableResult.
The precedent is already shipped: the Order state machine is gone in 6.0
(6.0-cart-order-split.md), and Orders::Cancel/Orders::Resume absorbed
Order#after_cancel/#after_resume.
The narrow exception: a model whose status genuinely has no side effects at all — a pure label with no restocking, no money, no fulfillment — may keep a machine if the transition graph is doing real validation work.
Fulfillment is that exception, arrived at by subtraction (2026-08-10). Its
machine kept the status column, the transition graph and its guards, and the
publish_*_event callbacks — publishing an event describes the status change
rather than being a side effect of it. Everything else left: restocking and the
carrier stand-down moved into Fulfillments::Cancel/::Resume, with the
provider call an external_step. So an existing machine does not have to be
removed wholesale to stop being dangerous; stripping it to the graph is enough,
and it is the cheaper move when the guards are conditional. Removing the
remaining machines outright is a separate planned wave. See decisions.md
2026-08-10.
Composition constraint (2026-08-10): a workflow whose flow contains an
external_step cannot be called from inside another workflow's transaction —
the guard raises ContractError, correctly. The fix is a flag that defers the
external half, not pushing the shared behavior down onto the model:
Fulfillments::Cancel takes notify_provider:, and Orders::Cancel passes
false, delegating the database work and batching the carrier calls into its own
external_step after commit. Moving the body to a public model method so both
layers can call it was tried and rejected — it contradicts "workflows write
behavior inline as named steps" and leaves model surface that has to be removed
again later.
Design Details
- The whole workflow vocabulary is five words:
step :name(runs the method of that name, instrumented),external_step,run_hooks,failure(...),halt!(value)— plus the class-levelhooksdeclaration andwith:/on_flow_failure:step options. Everything else in a workflow file is the Ruby a Rails developer already writes. step :name, with: -> { Spree.cart_recalculate_totals_workflow }delegates to a collaborator resolved from the lambda (the Dependencies seam does the swapping); its keyword arguments are sliced from the workflow's readers — a Workflow collaborator declares its contract on #perform, a ServiceModule collaborator on its author-written #call.- Observability: every step run emits the
step.spree_workflowActiveSupport::Notifications event with{ workflow:, step: }— APMs and log subscribers consume it with zero new concepts. Workflow-backed Dependencies seams are named*_workflow(legacy*_servicenames stay settable/readable one release; writes are stashed, never applied — an old service class is not workflow-contract compatible). - Why not Medusa's function-composition shape (analyzed 2026-07-31):
Medusa's
createWorkflowbody is a symbolic graph builder — their own docs forbid if/else, loops, await, try/catch and direct variable use inside it ("variables in the workflow don't have any values"), replacing them withwhen().then()andtransform(). That is a heavier DSL than ours wearing function syntax; the honest Ruby equivalent of what it actually does is the perform-composed shape: runtime named steps with real Ruby control flow, the ActiveJob::Continuable idiom — which also makes durable jobs and workflows read identically across Spree.
Editor & Typing Story
The contract is a plain method signature: editors, YARD and Solargraph
understand def perform(order:, canceler: nil) natively — completion,
go-to-definition and documented params with no toolchain. Argument
readers are real methods defined from the signature; derived state
exposed to hooks is plain attr_reader. (RBS/sig generation considered
and dropped 2026-07-30; the generated-Context editor story retired with
the perform-composed shape 2026-07-31.) The ruby-lsp-spree addon idea
(in-string completion for hook keys, go-to-definition from key to the
hooks declaration) stays on the tooling backlog, separate from this
plan.
Migration Path
- Phase 1a — the DSL — shipped, then reshaped (2026-07-31) into the perform-composed form described above after the Medusa analysis; the class-declared form (typed arguments, Context classes, provides:, transaction grouping, emit) lives in branch history. Specs cover every construct of the final surface.
- Phase 1b — reference retrofit — shipped. Every Cart/Order service
was migrated as a stress exercise, then deliberately folded back
(2026-07-30): the DSL stays only on the four curated workflows;
everything else returned to plain bodies keeping the semantics gained
along the way (
OrderUpdater#updatedissolved intoRecalculateTotals, single status writer,use_shippingfix). Acceptance held throughout: batteries green unmodified. - Phase 1c — hooks — shipped:
after_item_added(AddItem),before_finalize(Complete),after_cancel(Orders::Cancel, in-transaction) andafter_resume(Orders::Resume) registered-hook seams. The original "more hooks are added by demand, not speculation" stance is amended by decision 12 — Phase 3 below places the remaining hooks deliberately on the 6.0 boundary. Extension-facing docs pending. - Rolling adoption: services migrate when meaningfully touched — never a
big-bang sweep.
ServiceModule::Baseis not deprecated in 6.0. - Phase 2 — resolved: plain
ActiveJob::Continuablejobs are the durability tool (Spree::Imports::ProcessJobis the reference;Spree::ProductTypes::ApplyToProductsJobis the second adopter, cursoring on the last product id of a catalog-sized backfill); the upgrade data migrations adopt the same pattern — refined 2026-08-15 by6.0-maintenance-tasks.md: they becomeSpree::MaintenanceTaskclasses run by one shared Continuable runner with a persistent run row, rather than each carrying its own Continuable job. Workflow-level durable execution is deliberately not shipped — revisit with the payout run per the note above.
Phase 3 — extension surface (2026-08-02, targets 6.0) — shipped
Two waves finished the extension surface on the 6.0 boundary, per decision 12.
Wave A added the runtime contracts (run_hooks returning a merged hash,
reject!) plus hooks on the existing workflows; Wave B graduated four services
that had already earned the tier (Fulfillments::Create, Payments::Capture,
Payments::Refund, Payments::HandleWebhook, Carts::Merge). Returns,
exchanges and claims then arrived with hooks from the start.
Fulfillments::Update graduated on 2026-08-10, once moving a fulfillment
between origins had to re-quote its delivery rates: the flow gained real
orchestration (assign → re-quote → reprice → roll up statuses) inside one
transaction, and moving a fulfillment to another warehouse is precisely the
decision a 3PL or per-location policy wants to veto. Seam
fulfillment_update_workflow, with fulfillment_update_service and
shipment_update_service aliased to it.
Workflow and hook inventory
Every workflow in app/workflows/, its Dependencies seam and its hooks.
This table is the checklist — a new workflow is not done until it has a
seam, its hooks are declared, and the extension docs list them.
Hook kinds: V = validate (veto via reject!), C = context (handler
returns a hash, deep-merged), L = lifecycle (past tense, read-only).
Cart and checkout
| Workflow | Seam | Hooks | |
|---|---|---|---|
Carts::AddItem |
cart_add_item_workflow |
validate (V), after_item_added (L) |
✅ |
Carts::Complete |
carts_complete_workflow |
validate (V), before_finalize (L), after_finalize (L) |
✅ |
Carts::Recalculate |
cart_recalculate_workflow |
set_promotion_context (C), after_recalculate (L) |
✅ |
Carts::RecalculateTotals |
cart_recalculate_totals_workflow |
set_tax_line_context (C) |
✅ |
Carts::Merge |
cart_merge_workflow |
validate (V), after_merge (L) |
✅ |
Order
| Workflow | Seam | Hooks | |
|---|---|---|---|
Orders::Cancel |
order_cancel_workflow |
before_cancel (V), after_cancel (L) |
✅ |
Orders::Resume |
order_resume_workflow |
before_resume (V), after_resume (L) |
✅ |
Orders::Complete |
order_complete_workflow |
— | ⬜ no hooks; draft-order completion funnels into Carts::Complete, so its hooks cover the flow. Revisit if a draft-only seam is asked for |
Orders::AddItem |
order_add_item_service |
inherits AddItem's, own keys | ✅ |
Orders::Recalculate |
— | inherits Recalculate's, own keys | ✅ |
Orders::RecalculateTotals |
order_recalculate_totals_workflow |
inherits, own keys | ✅ |
Twins subclass their cart counterpart and dispatch under their own key
(orders.add_item.validate, not the cart one), so an extension can target
admin draft-order edits without touching storefront carts.
Fulfillment
| Workflow | Seam | Hooks | |
|---|---|---|---|
Fulfillments::Create |
fulfillment_create_workflow |
validate (V), get_provider_data (C), after_create (L) |
✅ |
Fulfillments::Update |
fulfillment_update_workflow |
validate (V), after_update (L) |
✅ |
Payment
| Workflow | Seam | Hooks | |
|---|---|---|---|
Payments::Capture |
payment_capture_workflow |
validate (V), before_capture (L), after_capture (L) |
✅ |
Payments::Void |
payment_void_workflow |
validate (V), before_void (L), after_void (L) |
✅ |
Refunds::Create |
refund_create_workflow |
validate (V), before_refund (L), after_refund (L) |
✅ |
Payments::HandleWebhook |
payments_handle_webhook_workflow |
after_handle (L) |
✅ |
PaymentSessions::Complete |
payment_session_complete_workflow |
validate (V), after_complete (L) |
✅ |
The admin capture, void and refund endpoints and the storefront session
confirm endpoint route through these workflows — none of them wraps the call
in with_order_lock, because the workflows call the gateway from an
external_step and every flow is an idempotent success on replay.
Refunds::Create (renamed from Payments::Refund before any release of the
key) owns the whole refund lifecycle: Refund#after_create :perform! is gone,
the row commits first, the gateway credit is an explicit external_step, and
a cleanly declined credit destroys the uncredited row (credit_allowed sums
every row, so a dangling one would block the retry). The returns, exchange and
claim workflows call Refund#perform! explicitly from their own external
steps. Two callback exorcisms rode along: Payment after_save :create_payment_profile became an explicit call owned by creation flows (the
card number never persists, so only the creating flow's in-memory instance
can store a profile — which is also why no subscriber can do this), and
process_payments! no longer holds the order row lock across gateway round
trips.
Returns
| Workflow | Seam | Hooks | |
|---|---|---|---|
Returns::Create |
return_create_workflow |
validate (V), after_create (L) |
✅ |
Returns::Approve |
return_approve_workflow |
validate (V), after_approve (L) |
✅ |
Returns::Receive |
return_receive_workflow |
validate (V), before_restock (L), after_receive (L) |
✅ |
Returns::Refund |
return_refund_workflow |
validate (V), before_refund (L), after_refund (L) |
✅ |
Returns::Cancel |
return_cancel_workflow |
validate (V), after_cancel (L) |
✅ |
Exchanges
| Workflow | Seam | Hooks | |
|---|---|---|---|
Exchanges::Create |
exchange_create_workflow |
validate (V), after_create (L) |
✅ |
Exchanges::Approve |
exchange_approve_workflow |
validate (V), after_approve (L) |
✅ |
Exchanges::Receive |
exchange_receive_workflow |
validate (V), before_restock (L), after_receive (L) |
✅ |
Exchanges::Fulfill |
exchange_fulfill_workflow |
validate (V), before_settle (L), after_fulfill (L) |
✅ |
Exchanges::Cancel |
exchange_cancel_workflow |
validate (V), after_cancel (L) |
✅ |
Claims
| Workflow | Seam | Hooks | |
|---|---|---|---|
Claims::Create |
claim_create_workflow |
validate (V), after_create (L) |
✅ |
Claims::Approve |
claim_approve_workflow |
validate (V), after_approve (L) |
✅ |
Claims::Resolve |
claim_resolve_workflow |
validate (V), before_settle (L), after_resolve (L) |
✅ |
Claims::Deny |
claim_deny_workflow |
validate (V), after_deny (L) |
✅ |
Claims::Cancel |
claim_cancel_workflow |
validate (V), after_cancel (L) |
✅ |
Customer
| Workflow | Seam | Hooks | |
|---|---|---|---|
Customers::Create |
customer_create_workflow |
validate (V), after_create (L) |
✅ |
Callers: store self-registration (Store::CustomersController#create) and
the checkout "create an account" box (OrderPlacedSubscriber), which passes
order: so the workflow also adopts the order's addresses and links the
order to the new customer. Absorbs Orders::CreateUserAccount (deprecated
one-release shell). Admin API create stays plain CRUD and does not dispatch
these hooks (decision 13). No welcome email — signup email is host-app
implementation on user.created or after_create.
Core handlers registered on these hooks. Only one:
Spree::Returns::EligibilityValidator on returns.create.validate and
exchanges.create.validate — a per-market return window that staff bypass
(decisions.md 2026-08-03). Everything else is unregistered seam.
To deliver
Planned workflows that do not exist yet. Each is a checklist item: a workflow is not done until it has a Dependencies seam, its hooks are declared, and the extension docs list them.
6.1 — OrderChange substrate (6.1-order-change-substrate.md)
Blocked on nothing in this plan; deliberately deferred so 6.0 does not also carry a new schema surface and extension API.
| Workflow | Hooks | |
|---|---|---|
OrderChanges::Begin |
after_begin (L) |
⬜ |
OrderChanges::AddAction |
validate (V) |
⬜ |
OrderChanges::Request |
after_request (L) |
⬜ |
OrderChanges::Confirm |
before_settle (L), after_confirm (L) |
⬜ |
OrderChanges::Cancel |
after_cancel (L) |
⬜ |
OrderChanges::Preview stays a Tier 1 service — a pure read with no hooks and
no side effects.
Candidates, not yet committed
Services that would qualify on external I/O or orchestration, listed so the decision is deliberate rather than accidental. None is scheduled — the rule still holds that a service graduates when it earns a hook, not speculatively.
| Service | Why it might qualify | |
|---|---|---|
Checkout::Complete |
Thin wrapper over Carts::Complete; if it stays, it should probably be deleted rather than graduated |
⬜ |
Orders::Approve |
Publishes an event and writes an approval record; a B2B multi-level flow would want validate |
⬜ |
GiftCards::Redeem |
Money movement, currently a model call | ⬜ |
StockReservations::Reserve |
Already called as a step from Carts::AddItem; a hook would let a store veto a reservation |
⬜ |
| Marketplace payout run | 6.0-multi-vendor-marketplace.md — the first flow that may justify durable execution |
⬜ |
Known gaps
Not new workflows — things wrong or missing in what already shipped.
- ⬜ Extension-facing docs list only the pre-returns hooks.
docs/developer/customization/workflows.mdxdocuments the pre-returns hook points (pluscustomers.create, added 2026-08-05); the fifteen returns/exchanges/claims workflows added since are missing from the reference table. (Earlier revisions claimed the table is spec-asserted in core — no such spec exists, which is part of this gap.) - ⬜
Spree.hooks.clear!wipes core registrations permanently. The boot-time initializer runs once, so any spec or extension calling it silently disablesEligibilityValidatorfor the rest of the process. Either narrow those call sites tounregister, or make core registrations restorable — deliberately not done yet, since the alternative adds a two-tier concept to a public registry. - ⬜ No UI-state coverage. Workflow specs are thorough; the dashboard surfaces they drive have none. Four bugs shipped in the post-sale UI that spec batteries could not catch (empty dropdowns on terminal records, a stale sidebar count, a menu firing without a dialog, a disabled button with no explanation). A Playwright walk through open → approve → resolve asserting menu contents at each step would cover most of them.
- ✅ Wave B leftovers — resolved 2026-08-12. The admin endpoints route
through
Payments::Capture/VoidandRefunds::Create; the refund credit left itsafter_createfor an explicitexternal_step. - ✅ Payment flows absorbed — 2026-08-18 (supersedes "money movement stays
in the model").
Payments::Capture,Payments::Voidand the newPayments::Processimplement capture, void and authorize/purchase inline as named steps: an atomic claim (a stale instance can no longer resurrect a settled payment and drive the gateway again), the gateway round trip as anexternal_step, and the locked bookkeeping with its settled-concurrently recheck. Every entry point routes through them — admin endpoints, checkout (Purchase::PaymentProcessingcallsPayments::Processper payment), dispatch capture and order-cancel settlement — so the validate/before/after hooks andpayment.capturedfire uniformly; previously a fraud hold registered onpayments.capture.validatevetoed an admin capture but not a dispatch capture.Spree::Paymentkeeps only gateway mechanics (gateway_options,handle_response, error translation,split_uncaptured_amount) plus deprecated verb shells (capture!,void_transaction!,process!,authorize!,purchase!) delegating to the workflows until 6.1.Refund#perform!still owns the credit call, driven byRefunds::Create'sexternal_step. - ⬜
get_provider_datahas no consumer. Declared onFulfillments::Create, but no fulfillment provider reads the merged hash yet. It is a published contract with no proof it fits the providers' needs. - ⬜ No post-sale subscribers or mailers.
return.requested,return.approved,claim.resolvedand the rest are published and nothing listens, so a self-service return notifies nobody. The dashboard sidebar counter is the only signal a merchant gets.
Explicitly out of scope. No workflows for CRUD. Creating, updating and deleting a region, tax rate, API key or product is a controller plus a model save; wrapping those in workflow classes would add hundreds of pass-through classes with no hook, no compensation and no external I/O to justify them. Workflows are earned by orchestration, not by being a write.
Constraints on Current Work
- New services are plain sequential
ServiceModulebodies (likeOrders::UpdateItem) — no newrun-pipelines, and no DSL outsideapp/workflows/. - Do not hand-roll compensation/saga logic in a plain service; a flow that
needs it belongs in
app/workflows/onSpree::Workflow. - Adding an extension hook to a plain service means graduating it to the
workflow tier first — hooks exist only as
run_hooksdeclarations. - No
state_machineon a new model. Plainstatusstring, inclusion validation, transitions through workflows (decision 11). - No new business logic in model callbacks or transition callbacks — especially not gateway I/O. If a save has a side effect that touches money, stock or an external system, it belongs in a workflow step.
- New
set_*_contexthooks follow the collect-and-merge contract ("Hook contracts" above) — handlers return a hash, never mutate shared state.
Open Questions
- Whether the sweeper that resumes stuck completions generalizes into flow infrastructure in Phase 2 or stays completion-specific. Deferred: unblocked only by a second consumer — the marketplace payout run is the first candidate (see "Candidates" above).
References
docs/plans/6.0-cart-order-split.md— Carts::Complete pipeline semantics (idempotency, compensation, resumability) this plan must preserve.- decisions.md 2026-07-29 (Rails 8.1 floor / Continuations), 2026-07-30 (consistency doctrine discussion: updater vs statuses vs subscribers).
- Medusa workflows (DX benchmark): createWorkflow/createStep, per-step compensation, workflow hooks.
spree/core/lib/spree/service_module.rb— the base being evolved.