Commerce definition

Read and save price, shipping, offer and post-purchase setup as commerce.json.

apex experiments pull <experiment> writes a top-level commerce.json when the experiment has a canonical commerce definition. plan shows both the definition change and its derived checkout carriers, warnings, and commerce launch preview. apply validates and saves the definition and sibling variation files together.

json
{
  "revision": 7,
  "definition": {
    "schemaVersion": 2,
    "baseCurrency": "EUR",
    "versions": { "control": "control", "order": ["control", "sale"] },
    "levers": {}
  },
  "serverOwned": { "readonly": true }
}

Edit definition.levers to change or remove a lever. Keep the positive integer revision from your pull. A stale revision returns 409 commerce_definition_revision_conflict; pull again and reconcile your edit. serverOwned is read-only, ignored on save, and recompiled by the server. Edited server output adds the warning commerce_server_owned_ignored.

bash
apex commerce definition get <experiment> [file]
apex commerce definition put <experiment> <file>
apex commerce definition put <experiment> <file> --create

get writes the same envelope as pull, to the file or stdout. put sends only definition and expectedRevision from the file. --create sends a null revision and refuses if a row already exists. Refused writes print the 409 or 422 error code and any blocking issues.

A legacy definition pulls as { "revision": 7, "legacy": true, "carriers": {} }. It is read-only. Replace the entire envelope with { "revision": 7, "definition": { ... } } to request a validated replacement. Replacement reports legacyReplaced, carriersEqual, and changedCarriers (variation and action). Existing status and representability guards still apply. Deleting commerce.json is refused; remove a lever by omitting it from definition.levers.

For one release, experiments without a definition continue to pull step 1 files under commerce/. Unchanged files stay unchanged. Editing a supported lever file converts the set to a definition, with commerce_files_v1_converted, and creates its row only if none exists. Opaque read-only files cannot be converted. Never mix commerce.json and step 1 price, shipping, offer or post-purchase files. commerce/discount-codes.json stays separate and may coexist with either format.

A price version containing exactly one all-scope integer percent rule from -90 to -1, with no ending or overrides, remains a percent arm. Its charged and displayed price follows the baseline captured at launch. Other price rules compile into fixed prices from the resolved baseline. Unchanged levers preserve their carrier revision, checksum and server-owned launch evidence.

Raw artifact saves and apex push

Authenticated artifact and workspace reads return commerceRevision alongside the artifact hash. Keep both from the read through the edit. A changed price, shipping, offer or post-purchase carrier needs that revision and the original artifact hash for each existing arm explicitly patched. null means create only. A missing token never means “use the latest revision.”

apex push accepts the tokens in .drip.config.ts:

ts
export default [{
  slug: "spring-sale",
  name: "Spring sale",
  commerce: { revision: 7 },
  variations: [
    { slug: "control", name: "Control", weight: 0.5, isControl: true,
      artifactHash: "hash-from-control-read" },
    { slug: "sale", name: "Sale", weight: 0.5,
      artifactHash: "hash-from-sale-read", mutations: editedMutations },
  ],
}];

For a fresh commerce experiment, use commerce: { revision: null }. An optional commerce.definition supplies the complete canonical v2 definition. Omit mutations to retain an existing arm's mutations; mutations: [] deliberately removes them. DOM-only saves and unchanged carrier echoes do not require a new commerce token or change its revision. Discount-code rules remain independent.

Workspace builds through Operator or MCP accept expectedCommerceRevision, expectedArtifactHash, expectedWorkspaceRevision and expectedFileVersions. File writes retain their existing file-version precondition. On HTTP 409, review the new state before reapplying your edit. The CLI does not retry with a fresh commerce revision. Unsupported raw changes return HTTP 422 with paths. Raw edits to migrated legacy commerce remain read-only; use canonical definition replacement for an explicit supported replacement.

Price display metadata

A price lever accepts an explicitly empty display: {}. The server compiles and persists server_owned.priceDisplay, returned as read-only serverOwned.priceDisplay in the commerce envelope, with exactly this shape:

json
{
  "options": {
    "unitPrice": "update",
    "soldOut": "test_price",
    "priceHoldMs": 2000,
    "badge": "hide"
  },
  "handles": {
    "gid://shopify/ProductVariant/123": "exact-catalog-handle"
  },
  "perVersion": {}
}

handles is sparse: it contains only known, nonblank exact catalog product handles for variants participating in the compiled price adjustments. Keys are canonical Shopify ProductVariant GIDs. Missing or unusable handles are omitted; an empty map is valid. The example binding is illustrative, not a required variant or a complete catalog map. perVersion is empty because explicit version badges remain unavailable. Defaults live in the metadata; the authored display remains {}. Editing serverOwned cannot configure these values.

The public config exposes valid stored metadata at commerce.price.display[experimentId] only for normally running, public-delivered price experiments present in the final commerce.price.experiments set. The canonical definition must have explicit display intent and valid identity, schema, revision and hash. The config copies the exact {options, handles, perVersion} value without filling sparse maps. Paused experiments receive no display metadata, including when protective price entries remain. Their metadata is omitted on the first successfully rebuilt config refresh. QA-forced drafts, completed, archived, disabled and otherwise excluded experiments receive none.

Malformed stored metadata omits the whole affected display entry while healthy price delivery and config-hash provenance remain intact. This includes any handle key absent from that experiment's final served variant rows or any perVersion key that is not a real served variation ID. Invalid metadata is still bound into provenance, so changing it changes the config hash; valid sibling entries remain eligible. If no valid entries remain, the entire commerce.price.display map is omitted.

This sidecar is metadata for SDK consumption. Adding or removing display: {} preserves complete Function and checkout-carrier bytes at the same revision. Omitting display emits no sidecar or display dependency and preserves the legacy public payload and hash bytes.

Option availability and reservations

The table below includes the enabled empty display container and existing priceFloor support. Other listed options remain unavailable, including every explicit display leaf and version badge. Supplying a disabled option, including an empty object, empty array or a valid default-looking value, returns commerce_definition_feature_unavailable at the concrete JSON pointer.

For display, explicit unitPrice: "update", soldOut: "test_price", priceHoldMs: 2000 and badge: "hide" still refuse at /definition/levers/price/display/unitPrice, /definition/levers/price/display/soldOut, /definition/levers/price/display/priceHoldMs and /definition/levers/price/display/badge, respectively. Other valid explicit values also refuse at those paths. Version badge overrides refuse at /definition/levers/price/versions/{v}/badge, where {v} is the concrete version slug. Invalid values and unknown keys remain schema errors. Omit disabled fields to keep existing behavior.

The internal commerceOptions registry in apps/web/src/lib/commerce/definition/options.ts holds each typed schema, effective fallback and availability flag. The enabled empty display container uses the four metadata defaults above; it does not enable explicit leaf values. Other reserved fallbacks apply only after the owning unit implements the option. They are never inserted into canonical JSON. priceFloor is already supported and remains enabled, with its existing missingCost: "block" and belowCost: "warn" parse defaults when the object is supplied. An omitted floor stays omitted.

Paths below are relative to definition. {v} means a concrete version slug and {i} a rule index.

Registry rowMountEffective fallbackAvailability / activation owner
mode/modetest#11397
audience/audienceholdoutPercent: 0, globalHoldout: respect#11397
resultsMetric/results/metricauto#11432
resultsBreakdownDimension/results/breakdownDimensionchannel#11422
profitPlanning/planningmetric profit, MDE 0.10, baseline 28 days, max 42 days#11423
reportingSale/reporting/salebaseline auto, last-year alignment weekday#11424
priceDisplay (enabled: {} only)/levers/price/displayabsent preserves legacy bytes; {} emits defaults and sparse metadata#11412 metadata only
unitPrice/levers/price/display/unitPriceupdate#11413
soldOut/levers/price/display/soldOuttest_price#11415
priceHoldMs/levers/price/display/priceHoldMs2000#11416
badge/levers/price/display/badgehide#11414
versionBadge/levers/price/versions/{v}/badge, method price onlyinherit display badge, then hide#11414
priceFeed/levers/price/feedversion derived by owner from mode/prices; compare-at before, fixed-price markets skip#11398
priceFeedRouteClicks/levers/price/feed/routeClickssources [google_shopping], existing visitors move, source match defaults below#11399
pricePlane/levers/price/planeauto#11402, #11405
priceChargeVia/levers/price/chargeViaauto#11427
priceMerchantDiscounts/levers/price/merchantDiscountsstack for price, best_for_customer for amount-off#11427
offerMerchantDiscounts/levers/offer/merchantDiscounts, every offer typebest_for_customer#11427
amountOffDisplay/levers/price/amountOffDisplaybadge#11429
priceConditions/levers/price/versions/{v}/conditions, methods price and amount_offsubtotal basis cart, quantity basis in_scope; no thresholds#11392
priceEnding/levers/price/versions/{v}/rules/{i}/ending/valueno ending#11393
discountCodes/levers/discountCodesabsent preserves existing independent legacy carriers#11391
selectionAll/levers/price/products/select/allfalse predicate on omission; wire accepts only true#11425
selectionExcludeTags/levers/price/products/select/excludeTags[]#11394
selectionExcludeCollections/levers/price/products/select/excludeCollections[]#11394
selectionExcludeSkus/levers/price/products/select/excludeSkus[]#11394
selectionBundles/levers/price/products/select/bundlesexclude parents_and_components, empty marker lists#11396
selectionIncludeSkus/levers/price/products/select/includeSkusabsent, no SKU inclusion source#11395
priceFloor (enabled)/priceFloorabsent evaluates below-cost policy warn#11409

Badge values reserve hide, theme, or a strict custom object with required text (1–40 characters, {percent} and {amount} tokens), optional translations, textColor, backgroundColor, position and surfaces. Custom colors use #RRGGBB; effective colors are white on black, position theme_slot, and surfaces product, card, quick view and search. These effective custom defaults and version inheritance belong to the badge implementation.

Feed routing reserves optional sources, match and existingVisitors. match has only google_shopping and email arrays of {param, equals?}. The effective Google match defaults are srsltid presence and utm_medium=shopping; email defaults are utm_medium=email and _kx presence. The feed and routing rows have independent availability gates, as do the display container and its four leaves. Enabling a container does not enable its leaves.

The independent discount-code lever reserves optional scope (assigned or all_carts, effective assigned) and versions.{v} as {unchanged:true} or {policy, except?, messages?, fallbackLanguage?}. Policy is allow_all, block_all or block_except; exceptions contain optional codes and prefixes. Messages map up to 20 language keys to 1–120-character strings; fallbackLanguage belongs to the policy version and is effectively en. Version keys must match versions.order. This reservation activates neither code blocking nor a migration of commerce/discount-codes.json. The older price-version discountCodes field remains refused.

Selection all:true cannot accompany a nonempty collections, productTypes, vendors, tags or includeProducts selector. Existing excludeProducts behavior is unchanged. Bundle markers reserve optional tag and product-type arrays and metafield {namespace,key} pairs. Conditions reserve optional minimumSubtotal, subtotalBasis, minimumQuantity and quantityBasis. Empty-condition, matching and SKU-composition behavior remains with the activation owners.

Existing struckThrough, alreadyDiscounted, price, amount-off, offer and shipping behavior is unchanged. Endings 0.95, 0.99 and 0.00 remain supported; other two-digit endings validate but refuse at ending/value until #11393 activates them. The enabled empty display container emits only the metadata described above. The remaining disabled reservations add no carrier fields or Shopify reads. Owners enable only their own rows with implementation and tests; changing availability alone does not implement a capability.

Prelaunch visitor guidance

apex experiments plan <folder> can show visitors per arm, estimated elapsed days and price-only conversion break-even. JSON keeps the full server response at plan.sizing, including the historical interval, moments and coverage. Unequal weights wait for the slowest arm. The planning horizon is informational; exceeding it does not block launch. Read failures display an unavailable reason.

Guidance reads prospective experiment confidence and power, independently of automatic-stop overrides. Defaults .80/.80 give alpha .20 and a two-sided formula; explicit .95 confidence gives alpha .05. Profit uses persisted CM1 per eligible historical visitor, including nonbuyers. Below 80% line-weighted cost coverage, it uses persisted net revenue for the same population. A price-only break-even ratio of .16 means +16.0% relative conversion, not percentage points. It is not a forecast of baskets, discounts, tax or full CM1.

The canonical profitPlanning option row and schema mounts are a prerequisite for authoring /definition/planning. Without that input, omission stays omitted and the existing definition schema remains unchanged. Current default guidance uses relative MDE .10, 28 baseline days and a 42-day planning horizon.

The required sizing.forecast labels this guidance a planning_estimate. Natural arrivals are distinct eligible visitors in the baseline window per elapsed day. Effective arrivals are (N-H)/baselineDays, before authored traffic allocation and arm weights. H is measured once over observed storefront visitor IDs using the current shop holdout policy, including nonbuyers. Monetary observations and the sample target still use natural N. Unknown policy or traffic stays unavailable; zero effective arrivals have no sample-duration estimate.

forecast.holdout.basis is observed_storefront_visitors. Logged-in customer keying is not_mapped; checkout-only identities are not_mapped_outside_forecast_population. Actual retention and duration may_differ_from_estimate. This does not count actual enrollment or reconstruct historical policy. Commerce delivery weekdays are unsupported; results weekdays are not applied without first experiment exposure. Exclusion effects are unestimated (overlap_and_sticky_history_unavailable), or not applicable for a canonical checkout-plane member (checkout_plane_member). These disclosures do not add launch gates. JSON retains the complete server forecast and precision. Older servers without forecast remain readable as undisclosed policy, with no invented zero holdout or retention.

Post-purchase costs

For every offer arm, set Shopify Cost per item, enter an assumed cost for this test, or explicitly acknowledge Launch anyway through the existing launch flow. Known missing cost and known nonpositive margin still support that explicit acknowledgement. Unreadable or failed catalog reads must be retried.

The optional test-wide definition.levers.postPurchase.costFallback has exactly two forms:

json
{ "kind": "percent_of_offer_price", "percent": 40 }
json
{ "kind": "minimum_margin", "percent": 30 }

The first assumes cost is 40% of the accepted discounted merchandise price. The second assumes gross margin is 30%, so cost is 70% of that price; it does not guarantee achieved margin. Taxes, shipping and refunds are excluded from this assumption basis. Assumed cost rounds up once per accepted line in currency minor units. Percent cost accepts 0–100; minimum margin accepts greater than 0 through 100, with at most two decimal places. Values must be finite numbers, with no extra fields. Omit the field to remove the rule; there is no default. A 100% cost assumption can parse but blocks ordinary launch at break-even; explicit Launch anyway retains its existing policy.

Actual Shopify unit cost, including zero, always takes precedence. Deleted variants, incomplete catalog responses, unreadable cost/currency and failed reads cannot use a fallback. Each signed attempt keeps its server-created immutable snapshot, including independent offer and canonical definition revisions. A legacy carrier without a canonical definition records a null definition revision. Later definition edits do not change historical assumptions. Old attempts without a snapshot retain their historical cost semantics.

Results expose costBasis quantities, assigned assumed cost in minor units, currency and snapshot lineage. Profit uses assumed cost appears only when an assumption contributes. An unverifiable historical merchandise basis is unknown, not zero. Factual COGS coverage and automatic winner/promotion gates stay factual. The backend main/v1 commerce.postPurchase and result export post_purchase carry the same per-eligible-order profit and disclosure. The existing v1 commerce_results: null boundary for post-purchase-only tests stays in place; the dashboard commerce API's order-basis plane carries arm costBasis. Setup and display UI changes are delivered separately.