Generated banner for Rp Target Wix
Generated logo for Rp Target Wix

Rp Target Wix

WixOfficialPublished by Wix

  • Skill
  • Tool integration
  • Cloud and DevOps
  • MIT
  • Medium risk
  • Has scripts

From the author

Wix target adapter with verified write primitives, shared execution runtimes, and contract tests. Use when vendoring Wix writers, validating API shapes, or Wix provisioning mechanics.
— the description by Wix

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

rp-target-wix serves as the foundational Wix-side adapter for migration workflows. It centralizes the logic for writing to Wix, ensuring that shared execution runtimes, retry policies, throttling, and API request builders are verified once and reused across all migration projects. By providing a consistent, verified interface, it prevents the need for per-project re-derivation of Wix API plumbing, reducing errors and ensuring reliable data ingestion.

What it does

  • Provides verified request builders and API primitives for Wix services.
  • Implements shared execution runtime logic including retries, throttling, and audit logging.
  • Manages Wix-specific data reconciliation, including inventory and URL preservation.
  • Defines contract tests to ensure stable behavior across different migration tasks.
  • Handles NDJSON record-stream I/O for efficient data processing.
  • Maintains domain entity suitability and dependency knowledge for Wix targets.

When to use it

  • When building or maintaining migration pipelines that target Wix as the destination platform.
  • When you need to perform bulk writes to Wix stores, blogs, or CMS collections.
  • When you need to validate API shapes or provisioning mechanics for Wix.
  • When you are vendoring Wix writers into a new migration project.

Advantages

  • Reduces code duplication by centralizing Wix API logic.
  • Ensures consistent, verified write behavior across all migration sources.
  • Provides a robust framework for handling complex Wix-specific constraints and throttling.
  • Simplifies the addition of new source platforms by decoupling them from the Wix write surface.

Usage examples

“How do I perform a bulk product import to Wix using this adapter?”
The adapter provides the bulkCreateStoresProductsWithInventory primitive, which handles normalization, correlation, and batching to respect Wix API limits.
“How can I verify if a specific Wix entity write is supported?”
You can consult the domain entity files and the operation contracts within the adapter to see if a reviewed writer exists for that entity.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/wix/rp-target-wix/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip rp-target-wix.zip -d .agents/skills

Documentation by Wix

rp-target-wix

Wix target adapter. Owns the Wix-side write surface and shared execution runtime that every migration shares — verified once here so the platform-agnostic stages and per-project codegen never re-derive (and re-break) it. This is the symmetric counterpart to rp-source-wordpress: that adapter owns reading a source platform; this one owns writing to Wix.

Verified variant inventory import

lib/stores-inventory.js exports inventoryForVariant, resolveInventoryLocation, and reconcileInventory(wix, rows, {expectedCount, gaps, locationId?}). Rows carry resolved productId, variantId, and inventory: {inStock:boolean} OR {quantity:integer}. expectedCount must equal rows plus named source gaps. Bulk writes follow complete location- scoped reads; existing items reconcile or update by revision, then values and availability are read back. Failure remains partial and the next invocation re-reads before writing. The existing single-create inventory helpers remain available for narrow probes; imports use the bulk reconciliation path. trackQuantity is derived and must never be sent. Read domains/stores/entities/inventory-item.json and the setup inventory-probe contract.

When this skill is used

Not a stage in the flow — a reference + shared library consulted by:

  • rp-import-codegen vendors lib/wix-writers.js into the project (like the wp-http transport) plus the shared write/setup runtime modules, and generates thin project-specific write specs/transforms that call these primitives/runtime APIs. Codegen does not re-emit Wix API plumbing.

  • rp-setup-discovery / rp-execute-setup consult the "Verified endpoints" and "Provisioning" notes for app-install / Wix-Data / collection mechanics.

Because the Wix surface is identical across source platforms, adding a new source (rp-source-shopify, …) requires no change here.

Shared runtime boundary

App page routing

app-page-routing-capabilities.json is the per-family gate for lib/app-page-routing.js and scripts/internal-link-audit.js route. The shared lib/url-mapper-transport.js builds writer-side create/update/read requests over an injected authenticated sender and requires destination inspection. Only the Stores product URL Mapper payload currently has a recorded request and saved-state read-back shape. Its writer-side pattern may be configured after Stores installation and before frontend creation, but it is not evidence that the frontend serves that route. The generated transport supplies the migration credential and writer-side read/write methods; the public reader's empty mapping is not a valid read-back. Use the recorded request and read-back fixture in app-page-routing-capabilities.json.

Every other discovered app family remains unverified until its exact key, page identifier, variables, supported method, request and read-back fixture are committed to the capability file and tested. Portfolio and Builder Blog remain unverified. Never infer one family's adapter from another or use full-site registration. A missing or conflicting route produces a local route result and an Import Operator item; it does not become a served route through the URL ledger.

This adapter owns the shared Wix layer written once for all migrations.

It should own:

  • verified request builders and endpoint primitives

  • shared Wix client/auth handling

  • shared retry and throttling policy

  • generic write execution runtime

  • generic setup execution/runtime behavior

  • checkpoint helpers

  • local crosswalk helpers (state/crosswalk/crosswalk.ndjson authority, append-only attempt journal, optional CMS mirror seed/upload adapters)

  • URL preservation helpers (state/url-preservation/ base paths, ledger, planned redirects, and unresolved route rows) and the SEO Redirects writer (lib/seo-redirects.js: Bulk Create only, declared APP/WIX_USER identity with Manage SEO Settings, no forceReplace, durable write intents and List Redirects reconciliation; user-token API create/read-back verified, frontend serving and full live acceptance still unverified)

  • NDJSON record-stream I/O (lib/ndjson.js): streaming read/write, batching by count and by cost, cursoring, and append-only producers. Migration data files are record streams, so the scan/batch/cursor primitives live here once instead of being re-derived by codegen.

  • audit log emission

  • compact execution report generation

  • contract tests for stable request/runtime behavior

Per-migration code generation should own only:

  • field maps

  • transforms

  • write specs

  • setup-plan renderings

  • entity ordering

  • dependency wiring — populate WriteSpec.dependencyRefs from each in-scope entity's domain-knowledge dependsOn field, not re-derived per project

Write contract (the verified Wix surface)

Capability and dependency boundary

createWixClient accepts only object-identity capabilities issued by the shared runtime. An unprivileged client admits registered read builders only; a raw request is not a trusted read. Import clients require a bound task plus the gate's current per-batch readinessGrant and sourceStableKey on every write, including auxiliary writes and dry-run captures. Every import write must retain the closed writer builder’s object identity and sealed method, URL, body and headers. A raw, copied or modified request is refused even with a valid grant; use the shared marked builders and grant wrappers. Use writers.bindRecordClient(taskClient, { readinessGrant, sourceStableKey }) for library composites, or writers.withReadinessGrant(request, { readinessGrant, sourceStableKey }) for individual builders; these preserve trusted builder marks. Before standard product inventory reconciliation, read the current product through that record client and call registerImportInventoryScope(recordClient, canonicalProduct, targetProduct). It requires a same-record successful product write or current site-bound crosswalk, correlates variants by choices, and binds stock to that record, product, variants and read location/item revisions. Standard reviewed quantity/location behavior remains available; quick Shopify retains its separate boolean/default-location scope. A serialized/copied capability, caller phase or stale/foreign-site grant is refused before transport. Setup and quick mode use their own bounded issuers, never an import bypass. Disposable probes require the explicit ownership confirmation and are restricted to the shipped verification callers.

Use lib/dependency-readiness.js for producer binding, task evaluation and record-level reference resolution. Its closed states distinguish complete, empty, partial, setup-passed, approved/unapproved exclusion and unknown evidence. Setup remains task-complete. The diagnostic projection is not an input. Keep latest journal outcomes, site-bound pass evidence and existing contact/product verification as the authority; task ordering alone cannot grant write permission.

Quick mode loads only its shipped adapter contract and keeps declared dependencies in contract order. Shopify product capability additionally admits exactly product tags and bounded inventory work for products created/read through that same client. Inventory still correlates real product, variant, item and location evidence, preserves partial stock outcomes, and never receives a raw-transport or probe exception.

lib/wix-writers.js exposes pure request builders (build*Request) + executors. Shapes marked VERIFIED were validated by a real call against a live site, not just read from docs. Shapes marked UNVERIFIED are docs-schema/MCP-derived bootstrap primitives that must be surfaced in execution plans until a live contract call promotes them. It also exports sendDirectRest for dev-probe capabilities only: its requests carry no request mark, so an import, setup or quick client refuses them as writes. A native entity this adapter has no reviewed writer for is written by guarded raw requests (sendGuardedRawRequest, below), never by sendDirectRest.

This resource should also expose shared execution-runtime modules above those primitives, so generated migrations use one common path for retries, throttling, checkpointing, reporting, and audit logging.

Read/return contract for query* executors. Every query* executor (queryStoresProducts, queryStoresCategories, queryContacts, queryCoupons, queryOrders) unwraps the response to the entity array and returns one page, discarding pagingMetadata. Two failure modes follow, both of which have shipped:

  • The return value IS the array. Reading .products / .categories off it a second time gives undefined → []. A dedupe index or existing-entity safety net then comes back empty without erroring, which is indistinguishable from a fresh site — so the import duplicates what is already there, and a setup verification reports 0 categories on a site with 25.

  • These executors cannot be cursor-paged, because the cursor is in the metadata they discarded. Use a queryAll* primitive where one exists — queryAllStoresCategories, queryAllStoresProducts, queryAllDataItems — otherwise send wix.send(build<X>Request(body)) and read pagingMetadata.cursors.next off the raw response.

Every sweep used for dedupe must throw on a partial result rather than return it. "Empty net" and "empty store" look identical to the caller, and the caller assumes the second.

Domain entity suitability knowledge

Target entity suitability lives in domains/, not in a large prose table in this skill. Use the deterministic reader as the normal access path:

node scripts/domain-knowledge.js list-domains
node scripts/domain-knowledge.js list-entities --domain stores
node scripts/domain-knowledge.js read-entity --ref stores/product
node scripts/domain-knowledge.js resolve-source --source-system woocommerce --source-entity product
node scripts/domain-knowledge.js resolve-source --route /wc/v3/products
node scripts/domain-knowledge.js list-flagged --flag IMPORT_UNRELIABLE
node scripts/domain-knowledge.js summarize-entities --refs stores/product,ecom/order

domains/index.json is generated from domain/entity files and checked in. After editing domain knowledge, run:

node scripts/domain-knowledge-validate.js --write-index

Authoring or editing any entity file also requires the dependency check, both directions: (1) what does this entity need to already exist and be crosswalked — record it in dependsOn: string[] (a domain/entity ref array; empty is a real, reviewed answer, not the same as the field being absent); (2) does this entity change what an already-written entity's dependsOn should say (e.g. authoring gift-cards/gift-card should have prompted revisiting ecom/order.json — it hadn't, until it was caught by hand). domain-knowledge-validate.js checks dependsOn refs resolve and the whole graph stays acyclic whenever the field is present, but it is not yet required on every entity — node scripts/domain-knowledge-validate.js --list-missing-deps prints the live backlog of entities that have never had it authored at all; that command is the source of truth, not a hand-maintained list.

domains/SERVICE-PLUGINS.md covers the escalation ladder for a source capability with no native Wix primitive: native primitive first, always, then a Wix service plugin (Wix calls an endpoint we host and we answer per request), and only then a recorded gap. It carries the cost list, a worked example — bounded quantity discount bands, implemented live 2026-08-31 — and a catalog of all 25 service plugins with per-plugin migration relevance. Read it before writing "Wix cannot express this" into a gap report.

Operation contracts. operationContracts.<operation> records, per reviewed write operation, what each dependsOn ref means for that operation: conditional, guardedPaths (payload paths that would carry a reference needing a separate producer; a { path, equals } guard matches one value, such as the Gift Cards catalog appId), creatingPaths plus withinWrite { completion, outcome, identityOutput, verification } when the write itself creates or resolves the dependency, inapplicable { reason } when the entity-level edge does not apply to that operation, secondaryOutputs (identities the write returns that another dependent may use after read-back), childOutputs (many child identities the write creates, each keyed by its own source key and proven by the parent's verified write receipt: a product's variants; the child entity file names its parent in childOf), auxiliaryOperations, and recovery.reconciliationKeys for identity recovery after an uncertain write. evidence is prose and excluded from the operationContractDigest that mapping proofs bind; every other field is semantic, so changing it invalidates those proofs. Add an entry only from verified API evidence; a missing entry or empty guardedPaths means "unknown" and keeps the separate producer requirement. setupProducible: true marks an entity setup may produce when no import task writes it; when an import task writes it, the import owns it and no setup step may claim it. The flag must match setup: an entity a named setup executor writes (SETUP_EXECUTOR_ENTITY_REFS in lib/setup-verification.js) carries it, and a flagged entity has that executor or a build* writer in WRITE_BUILDERS_BY_ENTITY. The selected targets' support rules and reliability flags bind reconciliation freshness. Member create helpers/builders are aliases of createMember.

writerId values in entity files must match exported functions from lib/wix-writers.js; use null for setup/manual work or native entities with no writer yet. An entity with a builder in WRITE_BUILDERS_BY_ENTITY names it as writerId (for example stores/product-tag uses buildCreateStoresProductTagRequest). A native entity with writerId: null and no such builder is written by guarded raw requests; its write operation is sendGuardedRawRequest. A task's write operation on a native or native-plus-cms entity must be a writer for that entity (its writerId, an operation contract name, alias or auxiliary operation, or a function listed for it in WRITE_BUILDERS_BY_ENTITY or WRITE_HELPERS_BY_ENTITY, such as ensureCoupon and bulkCreateCoupons), or the raw path when it has none; another entity's writer does not count, and an entity with a reviewed writer cannot use the raw path (scripts/import-contract-verify.js refuses either with MISSING_WRITER). A writer listed in the entity's own alternateWrites counts only when it is exported, importSafe: true and verification: verified-live, and the entity is not import-unsafe; otherwise the gate names the reason and the default writer (MISSING_WRITER:<task>:<ref>:alternate-unverified:use bulkUpsertContacts). List every new marked builder there; the contract test re-derives the map from the markRequest calls. A reviewed wrapper that writes only through its entity's writer or builders goes in WRITE_HELPERS_BY_ENTITY.

Entity files may also expose fieldContracts[] for verified nested write paths. These are machine-readable contracts for codegen and dry-run validators, not replacements for the human notes below. For Stores products, domains/stores/entities/product.json records the verified Catalog V3 create contract for product.subscriptionDetails, including required nested paths, allowed recurrence values, read-back behavior, and the live-validated subscriptions[].description <= 60 constraint. Generated transforms should consume that metadata through the vendored wix-writers.js exports instead of copying limits into project-local code.

Live verification helpers must not edit domains/ directly. When a probe changes a target write assumption, emit a proposal artifact and let the orchestrator promote it deliberately:

node skills/wix-replatform/resources/rp-target-wix/scripts/verify-stores.js stores subscription-create \
  --artifact migrations/<project>/setup/stores-subscription-verification.json \
  --proposal-artifact migrations/<project>/setup/contract-ledger-proposal.json

Use lib/contract-ledger.js to validate the handoff: a passed verification without a proposal is incomplete, and a proposal that is neither promoted into fieldContracts[] nor explicitly deferred is stale product knowledge. Codegen should consume fieldContracts[] through scripts/domain-knowledge.js summarize-entities, which includes promoted contracts.

Dual product descriptions

When a canonical product contains both shortDescription and description, lib/wix-build.js writes one Stores plainDescription: short body, <hr />, then long body. HTML-empty bodies and normalized, case-insensitive lorem ipsum… filler are treated as empty independently, so a real companion body remains. The horizontal-rule serialization is unverified in a live Wix storefront: canary it and capture a Hebrew/RTL screenshot before any bulk import or remediation backfill.

CapabilityEndpointNotes / traps
HTML → rich contentPOST /ricos/v1/ricos-document/convert/to-ricosVERIFIED. options.plugins enum is UPPERCASE — the docs example shows lowercase and 400s.
Import media from URLPOST /site-media/v1/files/importVERIFIED. Async: response is PENDING; poll GET /site-media/v1/files/{id} for READY before referencing.
Blog categoryPOST /blog/v3/categoriesVERIFIED. body { category: { label, slug, description } }.
Blog tagPOST /blog/v3/tagsVERIFIED. Body is top-level { label, language } — NOT { tag: { label, slug } }; slug is derived.
Blog postPOST /blog/v3/draft-posts → …/{id}/publishVERIFIED. memberId required (3rd-party). VERIFIED (2026-08-02): the site owner's auto-created user-member satisfies it — it was already present on our API-provisioned test site with zero Members-area interaction (single-site observation), so attribute-to-owner needs no member provisioning. Resolve it via listMembers + loginEmail match — never derive it from the account/user GUID (the observed id equality is a single observation, undocumented). Also VERIFIED (2026-08-02): author is re-assignable after publish — PATCH /blog/v3/draft-posts/{id} { draftPost: { memberId } } then republish updates the published post's author (post id == draft id; republish fires non-suppressed events — do author-upgrade passes inside the notification-mute window). Visible custom cover media requires both heroImage.id and media: { displayed:true, custom:true, wixMedia:{ image:{ id }}}. heroImage.id alone leaves the cover hidden.
Blog posts (bulk)POST /blog/v3/bulk/draft-posts/createUNVERIFIED bootstrap (public docs + wix/skills wix-manage recipe, 2026-07-21). Max 20 posts/call; bulkCreateDraftPosts chunks larger inputs. Prefer over per-post creates for N ≥ 2 (single create runs ~25–30s/call per the recipe). Publish is still per-post — a bulk publish flag is unverified. Surface in the execution plan until the live contract call promotes it.
CMS itemPOST /wix-data/v2/itemsVERIFIED. { dataCollectionId, dataItem: { data } }. Requires Wix Data enabled (else WDE0110).
MembersGET/POST /members/v1/membersVERIFIED. dedup by loginEmail (gated PII; use a fallback member when absent). VERIFIED (2026-08-02, single-site observation): the target-site member list can already contain auto-created user-members for the owner/contributing Wix users (status: APPROVED; resolve by loginEmail, never by deriving from the account GUID — the observed id equality is undocumented) — never dedupe or count these against source-site members; DELETE /members/v1/members/{id} works for cleaning up importer-created members. Throughput: no bulk create; documented ≥1s spacing (10k ≈ 3h serial floor — plan + resume via crosswalk). Create sends no email and does not fire the signup automations trigger (source-confirmed) — silent by default. Activation policy (decided 2026-08-03): passwords are never imported, and passwordless members complete the standard forgot-password flow (confirmed). Delivery = post-import label-wave automation: owner creates one dashboard automation (trigger label added, e.g. migrated-2026 → owner-branded email: "Log in → Forgot password"); importer applies the label per contact with assignContactLabels (crm/contact-label), paced for rate control and re-targeting; enable only after the import window. Never mass-send send-set-password-email (3h single-use link), and never fetch/store per-member reset links — they are credential-equivalent secrets and the no-link flow needs none.
Stores product (BULK — the scale path)POST /stores/v3/bulk/products-with-inventory/createUNVERIFIED bootstrap. Use this, not per-product creates, for any catalog above a handful — 1000 products is 11 calls instead of 1000. Creates up to 100 products with inline options, inline brand/ribbon/infoSections, all variants AND per-variant inventory items in one request. Five caps apply simultaneously and exceeding ANY ONE rejects the whole request: products ≤100, variantsInfo.variants ≤1000 total, options ≤100 total, modifiers ≤100 total, infoSections ≤100 total. With 2 options per product the options cap binds at 50 products, not 100 — so batch with lib/ndjson.js → readBatchesByLimits using the exported BULK_PRODUCT_LIMITS + storesProductBulkCost, never on record count alone. TRAP: bulk is NOT atomic — a 200 can carry per-item failures in results[].itemMetadata.success; never infer success from the HTTP status. TRAP: correlate results by itemMetadata.originalIndex, not response position. TRAP: bulkActionMetadata.undetailedFailures counts failures whose detail the server dropped; ignoring it silently loses records. returnEntity:false (default) still returns itemMetadata.id, which is all a crosswalk needs — pass true only for a contract probe that must inspect the created entity. bulkCreateStoresProductsWithInventory handles normalization, correlation and the unaccounted-item check, returning { results, succeeded, failed, undetailedFailures, unaccounted }. Normalization is purely local — HTML descriptions travel as plainDescription for Wix to convert server-side — so a batch is one HTTP call. It used to convert one description per product first, which made a 100-product batch 101 calls and reliably tripped the Ricos endpoint's 403 throttle.
Stores productPOST /stores/v3/products, POST /stores/v3/products/query, PATCH /stores/v3/products/{id}, GET /stores/v3/products/{id}, GET /stores/v3/products/slug/{slug}VERIFIED (2026-07-05; media patch verified live). buildCreateStoresProductRequest runs normalizeStoresProductV3, which bakes in the create traps: PHYSICAL requires physicalProperties:{}; simple/V1-ish top-level price, sku, and physical properties are moved into a single V3 variant; option/variant choice names clamped to 50 (identical truncation both places); variant optionChoiceNames.renderType defaulted to TEXT_CHOICES; compareAtPrice dropped unless strictly > actualPrice; variant price must be a money object ({ actualPrice: { amount: "14.95" } }) — a bare string/number 400s "Expected an object" (verified 2026-07-19), so the normalizer coerces scalar prices. Read-back (verified 2026-10-21): variant choices sent as optionChoiceNames read back as optionChoiceIds, resolved to names through the product's options[]; the empty product-level physicalProperties reads back with a derived shippingWeightRange. Both verifiers (lib/write-verification.js, lib/read-back-comparison.js) compare through that view; variant weights are still compared exactly. Descriptions: a string description is HTML and is moved to plainDescription by normalizeStoresProductV3; Wix converts that to rich content server-side, so the product path never calls the Ricos endpoint (description proper is a Ricos document object — HTML there is a type error). TRAP: plainDescription is silently ignored when description is also set — a 200 with an empty description — so the normalizer throws when both are present. TRAP: hard cap of 16,000 characters (the old Ricos path chunked at 28k and merged, so it was effectively unbounded); over-long bodies throw rather than truncate, and need an info section or an explicit mapping-gaps.json entry. For product media, prefer media.itemsInfo.items[] with external url values when the source URLs are publicly reachable: the Stores product API ingests them in the background, avoiding the slower, heavily-throttled Media Manager pre-import path. Use pre-imported Wix media ids only when the target flow requires them. Upsert lookups: getStoresProduct(wix, id) and getStoresProductBySlug(wix, slug) return the product or throw 404 — callers should catch and treat as null for "not found". Catalog sweeps: queryStoresProducts returns one page unwrapped to the array with the cursor discarded, so a crosswalk-recovery or name-match safety net must use queryAllStoresProducts(wix), which follows the cursor and throws rather than returning a partial index. Slugs: sanitizing is owned by lib/wix-build.js (toWixSlug, applied automatically via the coerce: 'slug' rule on product.slug), not by this module and deliberately not by normalizeStoresProductV3 — the writer passes the caller's slug through unchanged so URL preservation can record the original next to the derived plannedTargetSlug. It matters because Wix rejects anything outside [a-z0-9-] and slug validation precedes application, so one bad slug (Shopify mints ph-5_5 from a "pH 5.5" title) 400s the entire bulk batch rather than just that product. General patch: patchStoresProduct(wix, { productId, revision, ...fields }) applies normalizeStoresProductV3, so a string description moves to plainDescription here too; revision from the existing product is required. UNVERIFIED for get-by-id, get-by-slug, and general-field patch (endpoint VERIFIED; arbitrary-field patching and slug lookup not yet live-tested). Variable products / variant matrices: Wix Stores V3 requires server-assigned optionChoiceId GUIDs before a variant matrix can be built — those IDs do not exist until after the initial createStoresProduct call returns. A single-pass import therefore cannot create a full variant matrix in one call. The two-pass approach: (1) create the product with options declared (but no variants), (2) create each option choice via POST /stores/v3/products/{id}/options/{optionId}/choices to obtain server-assigned choice IDs, (3) create variants via POST /stores/v3/products/{id}/variants. When the two-pass flow is out of scope (e.g. public-data single-pass run), import as a single-variant product at the base price, record the fidelity loss in mapping-gaps.json, surface it in the execution-plan report, and ensure the generated product detail page renders productOptions when non-empty so the storefront is ready once options are added.
Stores categoryPOST /categories/v1/categories, POST /categories/v1/categories/queryVERIFIED (2026-07-05) for create. Body { category, treeReference } — treeReference is top-level (sibling of category, {appNamespace:"@wix/stores"}); nesting it 400s "treeReference must not be empty". Empty optional strings such as description: "" are omitted. Query: same top-level treeReference trap applies. queryStoresCategories(wix) returns one page (100 max) unwrapped to the array — it does not return all categories, and the unwrap discards the cursor so it cannot be paged. Any dedupe/upsert index must use queryAllStoresCategories(wix), which follows pagingMetadata.cursors.next and throws rather than returning a partial index. A site with more than 100 categories reads back only 100 through the single-page call, which would duplicate the missing ones. UNVERIFIED for query (not yet live-tested).
Events categoryPOST /events/v1/categories, POST /events/v1/categories/queryVERIFIED (2026-10-27). createEventCategory sends { category: { name, states:["MANUAL"] } }. TRAP: names are not unique (a second create with the same name succeeds). TRAP: Query returns zero rows unless paging is sent, and ignores name/states filters — findEventCategoriesByName lists all with paging and matches in code.
Events eventPOST /events/v3/events, GET /events/v3/events/{id}, POST /events/v1/bulk/categories/eventsVERIFIED (2026-10-27). createEvent({ event, draft }) — draft is required and comes from the source status; past dates are accepted. TRAP: event.categories is silently dropped on create — assign with assignEventToCategories({ eventId, categoryIds }) (one event, all its categories; the client checks both ids against the record's grant). TRAP: Query Events never returns drafts — a draft whose create response was lost is held, not resent; published events are adopted by adoptPublishedEvent (title + start date, then read by id: that read lets the record assign the adopted event its categories). initialType (RSVP/TICKETING) is immutable.
Events ticket definitionPOST /events/v3/ticket-definitionsVERIFIED (2026-10-27). createTicketDefinition — TICKETING events only; name 1–30 chars; free = NO_FEE with price 0; a paid ticket's feeType comes from the source or the mapping review, never a default. Past events accepted. Use only this alias path, never the canonical host as well.
Events RSVPPOST /events/v2/rsvps, POST /events/v2/rsvps/queryVERIFIED (2026-10-27). createRsvp always sets rsvp.disableNotifications:true and defaults options.ignoreResponseStatus + ignoreLimits (a past event needs ignoreResponseStatus). Published RSVP events only (draft → 400 EVENT_NOT_FOUND). TRAP: with the overrides a repeated email creates a second RSVP — dedupe by email per event, and before resending after a lost response use findRsvpsByEmail (email is not filterable). Each RSVP creates or matches a CRM contact.
Wix Forms formPOST /form-schema-service/v4/forms, POST /form-schema-service/v4/forms/queryVERIFIED (2026-10-26). createForm({ form, sourceFieldTargets }) — namespace wix.form_app.form; every field needs identifier, a lowercase GUID id and a layout slot (checked before send). It appends a hidden "Original submission date" field (target original_submission_date) because Wix ignores an entry's createdDate. TRAP: a colliding name is renamed — record result.name. A lost create is adopted only by the hidden field id, never by name (the site's "Contact" form is the merchant's). TRAP: Create Form adds an ACTIVE owner-email automation for the form; see the next row. Repair: updateFormSchema({ formId, form, sourceFieldTargets, sourceFormId }) (PATCH /form-schema-service/v4/forms/{id}, full schema at the current revision, VERIFIED 2026-10-31) updates a form this import created (it must carry the hidden field id) whose live formFields lack a planned input target; unchanged when nothing is missing (no write; ownership is not checked), failed with reason: 'form-not-created-by-import' when a form that needs repair lacks the hidden field id (never written). A repair result never lowers an already-imported crosswalk row.
Wix Forms entriesPOST /forms/v4/submissions, GET /forms/v4/submissions/{id}, spam reports …/form-spam-submission-reports/namespace/query; Automations V2 query/get/PATCH /automations-service/v2/automations/{id}; Get / partial Update Form (spamFilterProtectionLevel)VERIFIED (2026-10-26). Use importFormEntries per form: it pauses the form's wix_form_app-form_submitted automations and lowers its spam filter to NONE (best-effort, one attempt each; ledger execution/forms/automation-pause.json), sends every entry, then reads them back 4 at a time (sendFormSubmission / verifyFormSubmission; seen:true, original date in the hidden field, polled to CONFIRMED; in-spam/deleted recorded, never re-sent; a create whose reply was lost is read back once with findFormSubmission over …/form-submission-service/v4/submissions/namespace/query, unverified live), and restores both, also on a throw; with no entries left, pass wix to restore an earlier run's changes. TRAP: mute does not stop the owner email — only the pause does. TRAP: updating the preinstalled automation returns a new id; the ledger keeps it. Never call Report Not Spam (it runs the automations).
Wix Tag (global)POST /tags/v1/tagsUNVERIFIED bootstrap. Body { tag: { name, fqdn } }. FQDN for Stores V3 products: "wix.stores.catalog.v3.product". Max 100 tags per FQDN. Create tags before products; crosswalk tag IDs into product tags.publicTags.tagIds[] at create time. Tags are a native Wix entity — do not route product tags to CMS.
Stores inventoryPOST /stores/v3/inventory-items, POST /stores/v3/bulk/inventory-items/create, POST /stores/v3/bulk/inventory-items/updateVERIFIED LIVE for single create, bulk create/update, Inventory and default-location Catalog read-back. Imports use reconcileInventory with the full expected variant count; persist its report and complete the inventory checkpoint only when status:complete and complete:true. No-data remains distinct. buildCreateInventoryItemRequest requires exactly one explicit inStock boolean or quantity integer; omitting both now throws instead of sending an unspecified stock policy. trackQuantity is validated for compatibility but omitted from requests because it is read-only.
Stores category membershipPOST /categories/v1/bulk/categories/add-itemVERIFIED (2026-07-05). { item:{ catalogItemId, appId }, categoryIds[], treeReference }; appId = Wix Stores 215238eb-…, catalogItemId = Wix product id. bulkAddItemToCategories(wix, payload) takes exactly one { productId, categoryIds } object — never extra positional arguments (a generated call site once passed three, silently dropping the third and sending undefined for both fields on every call; see lib/stores-category-attach.js). Do not call it inline and trust the resolved promise: use reconcileCategoryAttachment(wix, rows, opts), which calls it with the correct shape, never swallows a write error, and reads every product back (DIRECT_CATEGORIES_INFO) before marking a row attached — an ADD is confirmed by "every expected id present", never exact set equality.
ContactsPOST /contacts/v5/contacts, POST /contacts/v5/bulk/contacts/upsert, POST /contacts/v5/contacts/query, GET /contacts/v5/contacts/{id}, PATCH /contacts/v5/contacts/{id}GA (docs verified 2026-08-04 — was Developer Preview when selected on 2026-07-26). Do not fall back to V4 unless a migration explicitly chooses a legacy compatibility path. The GA contact shape is FLAT — no info wrapper, no emails.items/phones.items list wrappers: one main email/phone (contact matching + subscription status live on these) plus additionalEmails/additionalPhones arrays; addresses[] keeps postal fields nested under address; company is { name, jobTitle }. Create and update both take { contact, allowDuplicates }; update requires the current revision and has no fieldMask. Phone tags: OTHER/MAIN/HOME/MOBILE/WORK/FAX (no UNTAGGED). buildCreateContactRequest/buildUpdateContactRequest accept the flat GA contact (legacy info payloads convert strictly — non-mechanical keys like extendedFields/labelKeys throw). Live create/query/update verification is still pending a token with Contacts permissions (2026-07-26 probe got 403) — keep V5 writers surfaced as UNVERIFIED in execution reports until a live contract test promotes them. Custom fields (GA): the V5 contact carries extendedFields.namespaces.<ns>; per the V5 contact-object docs, definitions go through the Data Extension Schema API with FQDN wix.contacts.*.contact (user-defined values under _user_fields). The V4 Contacts Extended Fields API (POST /contacts/v4/extended-fields, values under info.extendedFields) pairs with the V4 surface only — do not mix. CAVEAT: the Data Extension Schema intro's supported-objects table does not list contacts yet (docs inconsistency at GA cutover); verify the DES path live during setup before relying on it. Labels: a V4 label is the V5 private tag (label.tagId goes in tags.privateTags.tagIds[], verified live 2026-10-27). Write definitions with findOrCreateContactLabel (Contact labels row) and put them on contacts with assignContactLabels (Labels on a contact row); never send tags in the contact upsert, whose default OVERWRITE replaces a matched contact's tags.
CouponsPOST /stores/v2/coupons, POST /stores/v2/coupons/query, DELETE /stores/v2/coupons/{id}createCoupon VERIFIED LIVE (stores/coupon entity, multi-thousand import). Contract: use ensureCoupon({ specification }) — Query Coupons by exact specification.code (paced, retried; the write is not readable immediately), zero matches creates, one reconciles, more is ambiguous and creates nothing. The specification comes from rp-source-wordpress/lib/coupon-discovery.js mapCouponToWix; never hand-roll it (epoch-ms times, explicit appliesToSubscriptions, exhausted codes active: false). Redeemability is REFUSED unless it was decided: ensureCoupon, bulkCreateCoupons and normalizeCouponSpecification all throw before any network call unless the specification carries a boolean active and either a positive-integer usageLimit or the directive usageUnlimited: true (stripped before the body is built; usageLimit: 0 is rejected by the target, so unlimited has no sentinel number). Both fields are optional on the API and each omission resolves the expensive way -- absent active reads as ON, and the target's own usage count starts at zero. CREATE paths only: updateCouponFields must keep carrying only the fields being changed. Scope is enforced by the writer, so a hand-rolled specification now fails locally instead of on the store: normalizeCouponSpecification derives scope.namespace from scope.group.name (product/collection -> stores, form -> forms; never a flat constant) and REFUSES an unenumerated group name, a nameless group, a group with no entityId, or a namespace/group pair that is not one of the five accepted pairs -- naming the field, the value and the accepted values. A refusal throws; it never drops the scope, because a dropped scope is a storewide coupon. bulkCreateCoupons sets refused specifications aside BEFORE it sends, reports each one coupon-scope-shape-invalid keyed by code, and writes the rest in one call. A scoped coupon should carry scopeTarget: {visible} -- the caller's verdict on the restricted product or collection: {visible: false} is refused unsent as coupon-scope-target-hidden (never widened to storewide, never parked with active: false), and an omitted scopeTarget writes but marks the result coupon-scope-target-visibility-unchecked.
MembersPOST /members/v1/members, POST /members/v1/members/query, GET /members/v1/members/{id}, POST /contacts/v5/contacts/queryCreate VERIFIED LIVE. Contract: ensureMember({ loginEmail, contact, knownMemberId }) (customer-member.js builds contact from a source customer — buildMemberContact, phone via normalizePhoneE164, never sent un-converted: Create Member 400s on anything not already E.164). Reconciles by a crosswalk row read back and verified (member-crosswalk-row-stale if not), else Query Members by loginEmail (one match reconciles, more is ambiguous); before every create that carries a phone, Contacts V5 is queried by that phone and it is DROPPED (member-phone-collision-dropped) on a match — Create Member reuses an existing contact with a matching phone even from a DELETED member, and two different customers would otherwise merge into one Wix identity. Persist loginEmail on the crosswalk row (lib/member-crosswalk.js) or resolveOrderBuyer cannot link anything. Create Member ≥1s apart (documented floor).
Pricing plansPOST /pricing-plans/v3/plans, POST /pricing-plans/v3/plans/query, POST /pricing-plans/v2/plans/{id}/archiveCreate VERIFIED LIVE 2026-08-16 (pricing-plans/plan entity). Contract: ensurePlanDefinition({ plan, idempotencyKey, knownPlanId }) — the reconciliation IDENTITY is the client-minted pricingVariants[].id (offer-derived, preserved by Wix), never the name (names are cut to 50 chars and collide). A knownPlanId is read back (GET /pricing-plans/v3/plans/{id}) and adopted only if it exists, is not archived and carries our variant id, else plan-crosswalk-row-stale; then Query Plans by name, filtered to plans carrying our variant id (one reconciles, more is ambiguous, a merchant's same-named plan is ignored); then Create Plan ≥1s apart with idempotencyKey in the BODY beside plan (a header is ignored). An adopted plan that is ours but no longer inert is reported (plan-reconciled-not-inert), not archived. The body comes from lib/pricing-plan-definition.js buildPlanDefinition and is REFUSED unless visibility: PRIVATE and buyable: false; the CREATED plan is checked too and archived at once if it came back purchasable (plan-failed, cause created-plan-not-inert, `archived: true
Pricing plan ordersPOST /pricing-plans/v2/checkout/orders/offline, POST /pricing-plans/v2/orders/{id}/pause, GET /pricing-plans/v2/orders, GET /pricing-plans/v2/orders/{id}Create VERIFIED LIVE 2026-08-16 (pricing-plans/plan-order entity). Contract: ensurePlanOrder({ planId, memberId, startDate, paid, paused, knownOrderId }) — one source contract, at most one order: orders cannot be deleted. startDate (the source start date) is required and is the match key: a knownOrderId is read back and adopted only if it is this member's order for this plan, then List Orders (buyerIds + planIds) matched on startDate (one adopts, more is plan-order-reconciliation-ambiguous; a canceled/ended match is plan-order-existing-not-live, never re-created), then create (a 429 waits and tries once more). The body is only planId, memberId, paid, startDate — never couponCode or submissionId. Status is read-only: past/present start → ACTIVE, future → PENDING; paused: true creates ACTIVE then pauses (a PENDING order cannot be paused: plan-order-pause-failed). Canceled/expired source contracts are never written here (CMS history + cutover item). An unreadable reply or 5xx on create lists once and adopts a match, else plan-order-unknown-outcome — never resend. Read-back re-reads until lastPaymentStatus leaves UNPAID (it settles after the create returns). Any returned orderId goes to the crosswalk whatever the outcome. Outcomes are PLAN_ORDER_OUTCOME in lib/plan-order-outcome-registry.js; the importer records each with recordPlanOrderOutcome and the completion report turns them into cutover items. The pause is admitted by the import client only for an order this record already saw with its granted plan and member.
eCom orderPOST /ecom/v1/orders/import (historical orders), POST /ecom/v1/orders/queryVERIFIED LIVE (2026-08-12; re-verified 2026-08-16 with applied discounts, line-item description lines and merchant notes). Import Order is the only import-safe path — see ecom/order.json. Caller-supplied id VERIFIED LIVE 2026-09-05: a never-seen GUID is accepted and kept; a re-send with an existing id silently REPLACES the whole body (attached payments and extendedFields survive); a non-GUID is a 400. lib/order-history.js derives the id from the source — do not pick one, and never re-send an existing order. POST /ecom/v1/orders (createOrder) remains BLOCKED for migration: it decrements inventory, emails the buyer and auto-creates contacts. TRAP: order.number must be numeric — a prefixed source number fails the whole call with a bare 400 {"message":"Not a numeric value"} and no field path.
Site notifications mutePOST /notification-preferences/v1/site-mute/mute, POST /notification-preferences/v1/site-mute/unmute, GET /notification-preferences/v1/site-muteVERIFIED (2026-08-04, full cycle live on a test target: mute → state read → idempotent re-mute → unmute → state restored, all 200). Mutes all notifications of the site in context — all recipients, all channels; sendability denied regardless of recipient-level preferences. All three calls return { siteMuteState: { muted, reason?, mutedBy: { wixUserId } } }; executors unwrap to siteMuteState. Mute body { reason?: string } (≤500, clamped by the builder) — always pass a project-identifying reason (RePlatform migration — <project>) so the mute is auditable. TRAP: re-mute overwrites reason (last caller wins) — the import preflight's idempotent re-call must pass the same reason as setup. AUTH TRAP: user tokens only — the CLI-minted OauthNG site token (WIX_AUTH_TOKEN from config/wix.env) works; an account API key gets a uniform empty-body 403 on all three endpoints. Hard invariant: when mute is in effect (always for WIX_SITE_STRATEGY=new; explicit opt-in for existing sites), a failed mute halts the run before any import write — no degraded mode. unmuteSiteNotifications is never called by the flow itself — explicit owner request only; after an on-request unmute, confirm muted: false via getSiteMuteState.
eCom order merchant notesPOST /ecom/v1/orders/{orderId}/activities/addVERIFIED LIVE 2026-08-16 (ecom/order-merchant-note). addOrderMerchantNotes(wix, { orderId, messages }) / buildAddOrderMerchantNotesRequest: one order per call, 1-300 MERCHANT_COMMENT messages, each 1-5000 chars (the builder throws; truncating or splitting is a mapping decision recorded in the ledger). orderId is sent in the body as well as the path so the readiness grant checks it against the record's granted ecom/order target (dependencyReferenceFields, per-record edge). Returns activityIds. Wix stamps createdDate and authorEmail (the token holder) at call time; carry the source author/date in the message. Not idempotent: after an unknown outcome read the order back and match MERCHANT_COMMENT text before resending.
Item SEO tags (Blog posts)POST /promote/seo/v1/bulk/item-seo-tags/set + GET /promote/seo/v1/item-seo-tags/BLOG_POST/{id}VERIFIED LIVE 2026-10-27 on an editor site. setItemSeoTags(wix, { itemType: 'BLOG_POST', entries: [{ itemId, tags?, focusKeywords? }] }, { readinessGrant, sourceStableKeys }) / buildBulkSetItemSeoTagsRequest. BLOG_POST only (STORES_PRODUCT stays on product.seoData). Other item types use guarded raw requests through PATCH /promote/seo/v1/item-seo-tags/{itemType}/{itemId}; the raw guard refuses BLOG_POST and STORES_PRODUCT and any request whose item type it cannot read (preferredWrite.writerScope). itemId is the Wix post id (per-record blog/post edge, checked per entry). Reads each item, merges (writes replace in full), strips robots and canonical into exclusions, sends chunks of 20, reads back: only verified (every written tag resolves TAG_SOURCE_ITEM) is landed; unverified-after-success, failed, failed-whole-call and not-landed are retried. A robots or canonical the item already has is sent back unchanged.
SEO patternsGET/POST/PATCH /promote/seo/v1/seo-patterns/{pageType}, GET .../{pageType}/variablesVERIFIED LIVE 2026-10-27. ensureSeoPattern(wix, { pageType, tags }): read, check {{variables}} (invalid-variable writes nothing), merge over the site's own pattern or the Wix default, create or set (a 409/404 re-reads once, never flips verb blindly), read back. A site-owned pattern is overwritten for the identities the source brings and returned as previousSitePattern; defaultPattern is always returned. Robots is never written; PAGE_TYPE_NOT_ON_SITE → setup-missing-app. No WIX_DATA_PAGE_ITEM.
Site SEO tagsGET/PATCH /promote/seo/v1/site-seo-tagsVERIFIED LIVE 2026-10-27. setSiteSeoTags(wix, { tags, shareImage? }): one verification tag per provider, then the source share image in its own PATCH. shareImage is { mediaId, sourceUrl } with mediaId resolved per record through the gate (shareImage.mediaId); the og:image URL is the granted media file's own URL (read by id), and the client refuses any other og:image. An image that did not land resolves to nothing (dependencyFailureActions: omit), so the tags are still written; it, a not-ready file or a missing read-back returns shareImage.outcome: not-written with a cause, exclusion site-og-image-not-written and operator action site-share-image-not-written. An og:image tag in tags is never sent. The site's own og:image is kept unless the source image replaces it. Robots is never written (site-noindex-refused); a robots tag the site already has is sent back verbatim, because omitting it from the full-replacement PATCH would make the site indexable. Every call returns the operator action site-indexing-launch-decision. All three SEO surfaces need a site with an editor (HtmlWeb) instance: on a Create Project site with no template they fail with HTML 400/500/428 or Missing HtmlWeb instance (seo pitfall needs-an-html-web-site).
Stores brandPOST /stores/v3/brands, POST /stores/v3/brands/queryVERIFIED LIVE 2026-10-27 (stores/brand). createStoresBrand(wix, { brand: { name } }): one brand per call; the name is unique, so a 409 reuses the one brand with that exact name (outcome: 'reused'). Name only; other brand data goes to the CMS fallback.
Stores customizationPOST /stores/v3/customizations, POST /stores/v3/customizations/queryVERIFIED LIVE 2026-10-27 (stores/product-customization). createStoresCustomization(wix, { customization }): standalone field names (freeTextInput, customizationRenderType; the product-side names are refused). Unique by name + type + render type; a 409 reuses the match only when its settings or choices are the same, otherwise CUSTOMIZATION_NAME_CONFLICT (name same-named groups apart). Attach to products by id from the product writer, restating the settings.
Stores promotionPOST /stores/v3/promotions, GET /stores/v3/promotions/{id}VERIFIED LIVE 2026-10-27 (stores/promotion). A category-page banner, never a discount. createStoresPromotion(wix, { promotion: { name, enabled, categories }, imageUrl }) imports the image, waits for READY, creates with media.id and reads the image back. Outcomes created, reused (a create whose reply was lost, found once in the same call; or, on a re-run of such a record with { readBackFirst: true }, a promotion with every non-media field sent the same, found before any image import or create — a first attempt never looks, since two source banners may share a name), image-failed (nothing created), image-cleared. The payload path promotion.categories[].id is checked per record.
Stores back-in-stock requestPOST /back-in-stock-service/v1/back-in-stock-notification-requests, PUT .../{id}/mark-as-notification-sent, POST .../queryVERIFIED LIVE 2026-10-27 (stores/back-in-stock-request). Needs setup steps install-wix-back-in-stock and start-back-in-stock-collection (else 428 BACK_IN_STOCK_COLLECTION_DISABLED). createBackInStockRequest(wix, { itemDetails: { name, price }, request, notified, knownRequestId }): creating sends nothing; notified: true marks it sent offline. A 409 duplicate is resolved client-side (Query filters on status only) or deferred. A mark whose reply was lost is read back; still unconfirmed it is mark-unverified with requestId (journal succeeded_unverified with that target id). A marked request no longer blocks a duplicate create, so a re-run of a record with a known request id passes knownRequestId: the request is read and finished, never created again. A new email creates a contact.
ReviewsPOST /reviews/v1/bulk/reviews/create, POST /reviews/v1/bulk/reviews/moderate, GET /reviews/v1/reviews/{id}?returnPrivateReviews=true, PATCH /reviews/v1/reviews/{id}/replyVERIFIED LIVE 2026-10-27 (stores/review). Needs install-wix-reviews. createStoresReviews(wix, { records: [{ sourceStableKey, review }], readinessGrant }): chunks of 100, each item checked against its own record (entityId, author.contactId), results by originalIndex (created, already-exists, failed, unknown). Rating 0-5 (bulk accepts 0). moderateStoresReviews([{ wix, reviewId, status }]) sends every APPROVED/REJECTED moderation first, then reads them back in shared rounds. Moderate per batch, right after its create and before the task's next evaluateTask, with record clients bound to that batch's grant: a grant from an earlier evaluation is refused unsent (moderation-failed, error.requestSent: false); a review created earlier is moderated by gating its key again in the current batch. A failed chunk never hides earlier chunks' results (failed when nothing was sent, else unknown). Merchant replies (docs-verified, not yet live): setStoresReviewReply(recordClient, { reviewId, message }) after create, with the review record's own client; PATCH /reviews/v1/reviews/{id}/reply is admitted only for that record's own review, reads before (same reply: already-present, nothing sent) and after (verified / unverified); over 1000 characters is not-sent (CMS shadow + ledger).
Contact labelsPOST /contacts/v4/labels, GET /contacts/v4/labels/{key}VERIFIED LIVE 2026-10-27 (crm/label). findOrCreateContactLabel(wix, { displayName }) / buildFindOrCreateContactLabelRequest: Wix returns the label with that name or creates it (newLabel), so a retry or unknown outcome resends the same call; read back by key. Outcomes label-written / label-reconciled-existing / label-unverified / label-failed. The crosswalk target is label.tagId (5 chars): a V4 label IS the V5 contact private tag.
Labels on a contactPOST /contacts/v5/contacts/{contactId}/update-tags, GET /contacts/v5/contacts/{id}?fields=TAGSVERIFIED LIVE 2026-10-27 (crm/contact-label). assignContactLabels(wix, { contactId, tagIds }) / buildUpdateContactTagsRequest: one contact per call, assign-only, contactId in the path and the body so the readiness grant checks it and each tag id (per-record crm/contact + crm/label edges). Wix accepts a tag id that does not exist, so tag ids come only from the grant. Never put tags in the contact upsert: the default OVERWRITE replaces a matched contact's tags. Up to 1000 tag ids per call (the builder throws above that; split in mapping). Outcomes contact-labels-assigned / contact-labels-unverified / contact-labels-failed.
Member AboutPOST /members/v2/abouts/query, POST /members/v2/abouts, PATCH /members/v2/abouts/{id}, GET /members/v2/abouts/{id}VERIFIED LIVE 2026-08-16 and 2026-10-27 (members/member-about). upsertMemberAbout(wix, { memberId, content }): query by memberId, PATCH the one found with its revision, else create; one re-query after a 409 (ALREADY_EXISTS / INVALID_REVISION); two Abouts for one member are member-about-ambiguous (nothing written). memberAboutContentFromText(bio) wraps a plain bio as paragraph nodes and returns null for an empty bio (skip it). Wix accepts an About for a member id that does not exist, so memberAbout.memberId comes only from the per-record members/member grant. Deleting a member leaves its About. Journal (all three writers): record *-written / *-updated / *-reconciled-existing / contact-labels-assigned as imported with the target id; *-unverified as needs_verification with the target id (counted unresolved); *-failed and member-about-ambiguous as failed, so the completion report and cutover handoff count them. A *-failed whose error.requestSent is false was refused by the client before sending: journal it failed_retryable with top-level requestSent: false and failure.errorCode from error.code, never as an uncertain write.
Direct REST (sendDirectRest)any pathDev probes only. Unmarked requests are refused as writes by import, setup and quick clients (DEPENDENCY_READINESS_REQUIRED in an import task). Never generated for an import; a native entity with no writer uses guarded raw requests.
Guarded raw requests (sendGuardedRawRequest, buildGuardedRawRequest, buildGuardedRawReadRequest, verifyGuardedRawCanary)the entity's own Wix API, any path the agent picksImport tasks only, for a native or native-plus-cms entity with no reviewed writer. The agent picks method and URL; the client refuses (RAW_REQUEST_REFUSED:<reason>) DELETE and a POST to a delete path segment (…/bulk/delete, delete-by-filter; delete), any host but www.wixapis.com (host), a path with %, ; or an empty segment (path; paths are compared lower-case), a URL any toolkit builder or another entity's reviewed writer sends (other-entity:<ref> or other-entity:toolkit, built from the builder source and knowledge; the entity's own knowledge endpoint wins a tie), toolkit-only services (reserved: site mute, app install, CMS collections, site properties), and any entity that has a reviewed writer, except the records outside its preferredWrite.writerScope (item SEO for item types other than BLOG_POST). The client sends a private copy taken when send is called, so editing the request afterwards changes nothing. The task-entity and readiness-grant checks of a reviewed writer still run. Every call is journaled in state/attempts/raw-requests.ndjson; a call with no outcome is never retried (RAW_REQUEST_OUTCOME_UNKNOWN) until resolveRawRequestOutcome records the operator's check. Per run, the first record is the canary: until verifyGuardedRawCanary passes on a read the client made, any other record is refused (RAW_REQUEST_CANARY_PENDING); a mismatch holds the entity for the rest of the run (RAW_REQUEST_ENTITY_HELD). rawRequestSummary(projectDir) gives the completion-report and cutover rows.

Contact fields

Writers send emails and phones exactly as given; nothing replaces them (safe mode was removed; notifications rely on the site mute). Target domain entity files may define contactFields[] with { kind, targetPath, source, notes } entries naming the request-body paths that carry an email or phone. The order contact-field rules (order-history.js) read their list from ecom/order's contactFields[].

Stores subscription validation

lib/wix-writers.js exports the Stores subscription contract and deterministic helpers:

  • STORES_SUBSCRIPTION_CONTRACT

  • normalizeStoresProductSubscriptions

  • validateStoresProductSubscriptionDetails

Generated import code should call the normalizer from product transforms and the validator during dry-run and immediately before live create. Validation failures are record-level preflight failures/deferred outcomes; do not send known-invalid subscription payloads to Wix to discover field errors live.

Catalog V3 subscriptions are a native Stores target, not an automatic CMS fallback or semantic loss. Product create with subscriptionDetails.allowOneTimePurchases and subscriptions[] entries containing title, description, frequency, interval, and autoRenewal was verified live on 2026-07-26; Wix returned server-assigned subscription option ids. Mapping/codegen should emit native recurring product creates when the source cadence is known. General subscription patching remains unverified.

Stores live verification helpers

Use the shared Stores verification CLI for live target checks that would otherwise become migration-local snippets:

node skills/wix-replatform/resources/rp-target-wix/scripts/verify-stores.js stores subscription-create \
  --artifact migrations/<project>/setup/stores-subscription-verification.json \
  --proposal-artifact migrations/<project>/setup/contract-ledger-proposal.json
node skills/wix-replatform/resources/rp-target-wix/scripts/verify-stores.js stores product-count \
  --project migrations/<project> \
  --artifact migrations/<project>/execution/stores-product-count-verification.json
node skills/wix-replatform/resources/rp-target-wix/scripts/verify-stores.js stores product-by-source-marker \
  --marker-path customFields.sourceId --marker-value <source-id> \
  --artifact migrations/<project>/execution/stores-product-marker-verification.json
node skills/wix-replatform/resources/rp-target-wix/scripts/verify-stores.js stores delete-probe \
  --product-id <probe-product-id> \
  --artifact migrations/<project>/setup/stores-probe-cleanup.json

The CLI reads WIX_AUTH_TOKEN and WIX_SITE_ID from the environment or config/wix.env under the current project root, creates the shared Wix client, and sends requests through wix.send(...). It writes machine-readable artifacts with the target site id, endpoint, method, verified nested paths, discovered constraints, probe id, cleanup status, warnings, recovery instructions, and timestamp. Failed probe cleanup is not hidden: the artifact must remain with an explicit warning and a delete-probe recovery command.

Routed URL preservation behavior

URL preservation is a mapping and execution-state concern. This adapter owns only the Wix-side facts that generated code may rely on when deciding whether a final target URL is known.

Current import-only phase rules:

  • Do not configure Wix redirects or site routing.

  • Do not guess a destination relative URL from a slug when Wix route behavior has not been verified for that entity and delivery mode.

  • When the destination base path or final URL is unknown, write URL ledger rows with urlStatus: "pending_target_route" or target_url_missing and record unresolved rows for the future website-builder phase.

  • When a Wix create/update response or a safe declared lookup returns a final slug or relative path, generated code may record it as actualTargetSlug or actualTargetRelativeUrl and write a redirect plan if it differs from the source URL.

Known routed entity status:

EntityURL behavior contract
Blog postsCreate/publish is verified for content writes. Final public route exposure after publish is not verified here; generated code must treat the target route as pending_target_route unless a safe lookup in the generated write spec proves the final relative URL.
Blog categoriesCategory create is verified. Final public category route exposure is not verified here; default to pending_target_route.
Stores productsProduct create and slug-bearing product operations are verified, but arbitrary route/base-path configuration is not part of this phase. Generated code may record actual target slugs only when returned or safely looked up; target relative URLs remain pending_target_route unless the route pattern is explicitly verified in the project.
Stores categories/collectionsCategory create is verified. Final collection/category route exposure is not verified here; default to pending_target_route.
CMS items with dynamic pagesCMS item writes are verified. Dynamic page route patterns are site-builder configuration, not native item import output; default to pending_target_route unless website-builder artifacts define the route.

Shared execution runtime contract

In addition to endpoint primitives, this adapter should define the reusable runtime API that generated migrations call.

Conceptual contracts:

executeWriteSpec({
  spec,
  items,
  client,
  dryRun,
  runContext,
}): Promise<WriteExecutionReport>

executeSetupPlan({
  plan,
  client,
  dryRun,
  runContext,
}): Promise<SetupExecutionReport>

The exact filenames are implementation details, but the shared runtime should be the single place that owns generic Wix execution mechanics.

WriteSpec contract

Generated migrations should pass a declarative WriteSpec into the shared runtime.

Each spec should define, as applicable:

  • entity

  • mode: create | update | upsert | bulk_create | bulk_upsert

  • create

  • update

  • lookup

  • bulk

  • batchSize

  • concurrency

  • retryPolicy

  • throttlePolicy

  • auditKeys

  • crosswalkAuthority: "local"

  • cmsMirror

  • crosswalkStrategy

  • reconciliationStrategy

  • dependencyRefs

  • verificationLevel: verified | unverified

This resource should document how each field is interpreted by the runtime.

WriteExecutionReport contract

The shared runtime should return a compact, token-aware report suitable for the agent.

It should include:

  • run ID

  • entity

  • counts: input, attempted, created, updated, skipped, failed, retried, throttled

  • grouped error buckets

  • references to fuller on-disk logs

The runtime should prefer grouped summaries over raw per-record detail.

These per-entity or per-phase reports are intermediate runtime outputs. They are inputs to the final completion artifact, not replacements for it.

Completion artifact contract

The shared runtime should support deterministic emission of a final machine-readable completion artifact for the whole run.

Preferred output:

  • execution/completion-report.json

This artifact should be the authoritative source for:

  • final run status

  • final imported/updated/skipped/failed counts

  • separate dry-run counts when dryRun: true: requests built, Wix calls skipped, would-create/update/delete, would require live lookup, and local validation failures

  • grouped skipped/deferred outcomes

  • grouped failure outcomes

  • dashboard/editor/preview destinations

  • artifact references for audit/error/execution logs

The shared runtime should also support deterministic rendering inputs for:

  • execution/review/completion-summary.md

The rendered summary should be derived from completion-report.json, not independently invented by the agent.

Audit log contract

The shared runtime should emit append-only machine-readable audit events.

Preferred format: NDJSON.

Each event should capture, at minimum:

  • timestamp

  • run ID

  • phase: setup | import

  • entity

  • operation

  • source ID when applicable

  • target ID when known

  • endpoint or primitive used

  • attempt number

  • result status

  • HTTP status or platform error code when applicable

  • latency

The run ID is required because audit files are append-only across dry-runs, retries, and recovery passes. Completion reports should be generated from runtime counters for the current run and may use audit aggregation only when filtered by run ID. The shared lib/audit-summary.js helper enforces this filter for fallback/verification summaries.

Dry-run runtime contract

The shared Wix runtime exports createDryRunConfig, normalizeDryRunValue, createWixClient, and createWixSetupExecutor.

Dry-run is enabled by DRY_RUN=true or by the generated entrypoint's --dry-run flag. It is disabled by default. true, 1, yes, and on enable it; false, 0, no, and off disable it.

When createWixClient({ dryRun: true }) is used:

  • authToken and siteId may be blank unless the generated project requires the site ID for a local artifact namespace;

  • send() must not call fetch, SDK, MCP, or CLI transports;

  • send() must capture the would-send request under state/attempts/wix-request-captures.ndjson when projectDir or requestCapturePath is supplied;

  • captured headers must omit Authorization and redact secret-like header/body keys;

  • response payloads must preserve the live shape expected by writer helpers, for example { contact }, { product }, { dataItem }, { file }, or an expected collection field such as { contacts: [] } for skipped queries.

  • writers that read back what they wrote (events, forms, gift cards, add-ons, bookings, plan orders, labels, member Abouts, SEO) get answers from this dry run's own writes (lib/dry-run-target.js), and those placeholder responses count as the record's evidence for its follow-up calls, the same as live responses; the shared target read pacer never waits in a dry run.

Dry-run placeholder target IDs are not live authority. If downstream local execution needs them, write them only to state/crosswalk/dry-run-crosswalk.ndjson or keep them in memory. Never append simulated target IDs to state/crosswalk/crosswalk.ndjson and never upload them to a CMS crosswalk mirror.

When createWixSetupExecutor({ dryRun: true }) is used, each setup step must first be reduced to a structured intent, then captured as planned_dry_run without invoking MCP, CLI, SDK, or REST transports that access or mutate Wix account/site state.

Artifact authority at run completion

The shared runtime contract should preserve explicit artifact authority:

  1. execution-log.md for chronology and operator/debug context only

  2. completion-report.json for final outcome

  3. completion-summary.md for deterministic user-facing rendering

The runtime should not force downstream consumers to reconstruct final outcome by reading raw audit logs or chronological execution logs.

A rejected write and a write of unknown outcome are different results

createWixClient().send checks the response status before it tries to read the body, and every failure it throws says which of two things happened:

  • Rejected. The response body parsed. The target made a decision and stands behind it. outcomeKnown: true, status set, body parsed, applicationErrorCode populated when the envelope carried one. Report it and classify it by status; only the duplicate-protected transient paths below may retry.

  • Unknown. The body did not parse — a gateway or protection layer answered ahead of the service with an HTML error page — or the transport threw before any response arrived. outcomeKnown: false, with rawBody holding the first 400 characters of what actually came back and status set to what the target returned (null only when no response arrived at all). Nobody knows whether the write was applied, and the honest report says so.

A 2xx whose body does not parse is unknown, not a success: it usually means the request never reached the service, and returning null there is how an unwritten record becomes a written one in the report. An empty body on a 2xx is not unparseable and still returns null, as several Wix deletes answer exactly that way.

describeError carries outcomeKnown: false through to the results ledger, so the distinction survives being written down.

One exported test decides whether a failure is worth trying again: isTransientWixError (with TRANSIENT_WIX_STATUSES), from lib/wix-writers.js. It keys on the target's numeric status (429, 500, 502, 503, 504) and on the no-response-at-all marker, and on nothing else — never on the error's message text, which is truncated at 400 characters by design, and never on applicationErrorCode, in either direction. 403 is excluded: it is one endpoint's observed throttle and a real permission failure everywhere else. No caller may define its own copy.

It answers "is this condition likely to clear". It does not answer "is it safe to try again" — only the call site knows that. Exactly two write paths retry (3 attempts, with 500 / 1500 ms between attempts): the order import and the reconcile-plus-payment-write pair, both inside importOrderHistory, and both only because they reconcile against the target first. Nothing else does, because a write that is not reconciled first and fails after the target committed would be retried into a duplicate record.

A 429 is the one exception, and the client handles it, not the caller. Wix refuses a rate-limited request before processing it, so createWixClient's send sends the same request again, for a read or a write: it waits Retry-After (capped at 30 s, plus jitter), else jittered exponential backoff from 1 s, up to RATE_LIMIT_POLICY.maxRetries (5) more tries. The pacing it learns is per endpoint (site + method + path, ids folded) and shared by every client in the process: a 429 widens that endpoint's spacing, a Retry-After holds it shut for every caller, and clean replies narrow it again (client.rateLimitStats counts waits per endpoint). Every Wix API, single or bulk, gets this because every request goes through send. A few writers keep an older retry of their own on top (Ricos conversion, plan-order create, product media rounds, the read pacer, quick Shopify); their waits now add to the client's. Only a 429 that outlasts every retry reaches the caller. It carries requestApplied: false, so the raw-request journal records it as refused, not unknown, and importProducts leaves that record retryable for the next run.

Retry and throttling policy

This adapter should define one shared retry/throttling contract rather than letting each migration invent its own.

It should classify, at minimum:

  • retryable transport/network failures

  • retryable 429 responses

  • retryable 5xx responses

  • non-retryable 4xx validation failures unless explicitly listed otherwise

When the server provides backoff hints such as Retry-After, the shared runtime should honor them.

Bulk and fallback policy

The shared runtime should know:

  • when a native bulk primitive exists and is preferred

  • when to fall back from bulk to per-record writes

  • when an upsert requires lookup + create/update orchestration

  • when an unverified native path must be surfaced before execution rather than used silently

Media policy by target

Do not treat all media the same. The target domain decides whether media must exist in Wix first or can be ingested through the entity API itself.

  • Wix Stores products: prefer external URLs on media.itemsInfo.items[] and let the product API ingest them in the background. This is the default path when the URLs are publicly reachable.

    What one item accepts, from the machine-readable Catalog V3 spec (component ProductMedia) — not from the prose article, which disagrees on the cap:

    FieldDirectionConstraint
    setBy.id or setBy.urlina oneOf — exactly one per item
    altTextin1–1000 characters
    displayNameinmax 80, and only accepted when the item is set by url
    mediaType, uploadIdoutread-only
    media.image, media.videooutread-only; populated when the item is set by id
    thumbnailoutWix-generated; needs THUMBNAIL in the request's fields array
    media.main (on the parent)outread-only; always the first entry of itemsInfo.items — reorder the array to change it

    ⚠️ thumbnail is not an input. It looks like a second image URL you could supply and it is not — fields is defined as "Fields to include in the response", so THUMBNAIL only asks Wix to return a derivative it generated from the one file you uploaded. There is no input that influences it, and none that raises an already-ingested item's quality: the URL you send is that image's permanent ceiling. Send the source's original, maximum- resolution file — the source adapter owns that choice (WordPress sources: wp-image-url.js).

    ⚠️ The cap is disputed by Wix's own docs. The schema says maxItems: 50 on itemsInfo.items; the About Product Media article says 15. Follow the schema and do not design near either bound.

    ⚠️ The article also says width/height are not populated for URL-set media. Observed behaviour contradicts it — a URL-set item read back live returned both — so reading dimensions back is a usable post-ingest check. Confirm at first live run before reporting it as a guarantee.

    ⚠️ The 200 is a queue acknowledgement, not a delivery — and a failed ingest empties the gallery. This is the most expensive trap on this endpoint, so it gets its own paragraph. The write returns 200 with the item echoed back as mediaType: "UNKNOWN_MEDIA_TYPE" and an uploadId; Wix fetches the URL afterwards, on its own side, with no callback and no status endpoint. media.itemsInfo.items is a full replace, so the product's existing image is discarded the moment the PATCH is accepted. When the later fetch fails, Wix drops the item and the product is left with no images at all — 200 on the write, no error anywhere, and the old picture already gone.

    It is transient and unattributable: observed live on a valid, publicly reachable 2048×2048 JPEG that ingested fine on the very next identical attempt. Nothing about the file or the request predicts it, so there is nothing to validate up front.

    Observed liveFrequency
    Items not ingested 60 s after an accepted writea sizable minority
    Of those, fixed by one identical retrynearly all
    Writes refused by an edge-level 429 whose body is an HTML page, not JSONoccasional

    So: never treat a 200 as done. Read the product back with ?fields=MEDIA_ITEMS_INFO (a plain GET returns only media.main and looks empty even when healthy), and re-send anything whose items lack an image.id. A miss is not yet known, never failed — only re-sending distinguishes "still in flight" from "dropped and gone". Use patchStoresProductMediaVerified, which does this, rather than patchStoresProductMedia, which returns on the 200. Re-read the revision each round: the accepted-but-not-ingested write already incremented it.

    ⚠️ Two different failures, one retry list. A write refused with 429 leaves the OLD image in place; a write accepted but never ingested leaves NOTHING. Anything that did not reach the verified state goes into the next round, whatever went wrong — recording one of them as an error and dropping it out of the loop is how a run reports success over products it never fixed. Keep the write pool small (3 concurrent, not 6) so the edge limiter is not the thing the retry loop spends its rounds on.

    WordPress-family URL provenance is enforced here. A generated importer uses the exact confirmedPictures instance exported by wix-writers.js for declaration, source reads and confirmation; a separately required toolkit or vendored copy does not activate this writer. After declaring orchestration/decisions.json → sourcePlatform.value, guarded importers call assertProductMediaGuardActive() at startup and stop if this writer's own guard is inactive. Under exact woocommerce or wordpress declarations, buildStoresProductMedia accepts URL items only when the complete ordered list came from confirmPictures (or an exact normalization registered by deriveConfirmed). Create, bulk create, general patch, media patch and verified media patch all cross this boundary; the verified path checks before its first read. Hand-built strings, objects, clones, subsets, extensions and reorders throw before any Wix request. Wix media ids, other source identities and undeclared legacy callers retain their current behavior.

    ⚠️ A round that failed must back off before the next one, and it is a different wait from the settle wait. The settle wait comes after an accepted write, so a round that throws never reaches it — retry immediately and the loop burns all its rounds in milliseconds against a rate limit that lasts tens of seconds, which is a retry loop that only looks like one. Two waits, two purposes: settleMs waits for an accepted write to finish ingesting, retryDelayMs waits for a refusal to lift. Skip the delay after the final round — there is nothing left to wait for and the caller should not pay for it.

  • Wix Blog cover images and other surfaces that require a Wix media id at create/update time: import media first, then pass the Wix media id into the entity payload.

  • Generic Media Manager import is a fallback/shared primitive, not the default for every entity carrying media.

Media import source URL reachability

The media primitive imports by URL: Wix servers fetch the provided sourceUrl. Public HTTPS URLs are expected; localhost, 127.0.0.1, Docker-only hosts, and other private-only URLs are not reachable by Wix during a live import. This is optional source preparation and, as far as we know today, affects media import only.

If the source system is local, the migration should either:

  • expose the source through a public HTTPS tunnel, then pass/rewire media URLs to that public base URL; or

  • skip/defer media import and clearly state which media-dependent references will be missing until media is imported.

Ngrok quick setup for macOS:

brew install ngrok
ngrok config add-authtoken "<YOUR_AUTHTOKEN>"
ngrok http 8090
export WP_BASE_URL=https://<id>.ngrok-free.app

Validate by real call — do not trust doc examples

Codegen-time MCP doc checks confirm an endpoint exists; they do not confirm the request shape works. The live wporg-news import proved doc examples can be wrong (lowercase Ricos plugins → 400) or incomplete (featured image field, tag body). The rule for this adapter:

  • Treat a shape as verified only after a real call succeeds — encode the working shape here with a // VERIFIED: (or // VERIFIED-TRAP:) note and a date.

  • A // UNVERIFIED: primitive is allowed as a bootstrap point for generated code, but it is not a silent live-write permission. The execution plan must call it out, and setup verification must either promote it with a sandbox/live validation or route to fallback.

  • Keep tests/target-wix/contract-test.js current: it issues one real call per primitive against a sandbox site and is the single place schema drift surfaces. Tests live in the repo's tests/ tree rather than in this bundle, so the published product carries no test harnesses. Run from the repo root:

    bash tests/run-all.sh target-wix
    WIX_AUTH_TOKEN=... WIX_SITE_ID=... bash tests/run-all.sh target-wix

    Without credentials the shape checks still run and the live calls are skipped. tests/target-wix/ndjson-contract-test.js covers lib/ndjson.js and never needs credentials.

    For live verification runs, pass --progress-log <path> and poll it per CONVENTIONS.md#progress-log-polling.

    Run on a cadence and after any Wix API change. A failing contract test — not a stranger's broken import — is how we learn the surface moved.

Stores catalog is Catalog V3 only — Catalog V1 is not supported

A migration only ever writes to a V3_CATALOG site. Catalog V1 is not a supported destination: there is no V1 write primitive here, no V1 fallback, and none should be added (a former V1 fallback was removed — it only masked real V3 errors as spurious 428s). A V1 site is a blocker the run halts on, not a variant the adapter, the mapper, or codegen accommodates. The V3 create traps are handled in lib/wix-writers.js (normalizeStoresProductV3 + the top-level treeReference builder), so callers never re-hit them.

On a site this run created, a Stores install is guaranteed Catalog V3. This section used to require verifying that live, because a site scaffolded from the blank headless template, with Stores installed afterwards through the App Installation API, could come up V1_CATALOG — Catalog version is fixed at provisioning, so every V3 write on such a site failed and the site had to be abandoned. The Wix platform has since changed: Catalog V3 is now guaranteed at provisioning regardless of scaffold template, so that failure mode can no longer occur for a newly-created site, and neither the --site-template commerce requirement nor the pre-write version gate apply anymore.

This does not extend to an existing site this run did not create — rp-execute-setup ("A V1_CATALOG verdict is terminal here") still treats that case as a live risk and halts on it, since a pre-existing site's catalog version predates this guarantee.

Order history: payment records, refunds and preserved invoice documents

Import Order creates no payment record — a freshly imported order reads back with payments: [] — so payment history is a separate write, and refunds have nothing to reference until it exists. And the order write itself has no idempotency unless it is given an id.

The contract is one call: importOrderHistory in lib/order-history.js. It owns the per-order sequence — derive the order id, read or write the crosswalk, import, gate, one reconciliation read, payment, refunds, invoice document — and returns every stage's outcome:

const { importOrderHistory, createProjectOrderCrosswalk } = require('./lib/order-history.js');
const result = await importOrderHistory(wix, {
  order,              // mapped Import Order body, no `id`
  sourceId, sourceSiteHost,
  evidence,           // { amount, paidDate, altPaidDate, currency, status, methodName, providerTransactionId,
                      //   offlinePayment, cardDisplay, refunds: [{ sourceId, amount, reason }],
                      //   invoice: { approval, sourceUrl, invoiceNumber, pendingMediaFileId },
                      //   utcOffsetMinutes,                        // a fact about the SHOP
                      //   paidDateZone, altPaidDateZone }          // 'utc' | 'site-local', a fact about
                      //   each source KEY. The offset is applied only to a stamp declared 'site-local'.
                      //   Supplying utcOffsetMinutes beside a present stamp with no clock is REFUSED.
  crosswalk,          // createProjectOrderCrosswalk({ projectDir }) — required, persisted
  setupVerification,  // setup/extended-field-verification.json, read once per run
});
// result.outcomes = { order, payment, refunds: [{ sourceId, sourceOccurrence, outcome, refundId, paymentId }], invoice }
// result.findings, result.errors (partial failures carry a cause), result.orderId, result.paymentId

Its guarantees, each the answer to a failure mode seen in end-to-end testing:

  • The order id is derived from sourceSiteHost and sourceId and the crosswalk row is written before any further write. Hit or miss, the target is asked by id once — a read, not a duplicated store, and not a phantom order either. A crosswalk row from before derived ids (a Wix-minted id) wins and is counted as order-id-from-crosswalk. An existing order is never re-sent: Import Order's replace is silent and would overwrite a merchant's edits.

  • Evidence keys are a contract. An unknown key throws and names the right one; it does not report an ineligible order. The target currency is order.currency.

  • One reconciliation read per order, shared by the payment and every refund. Refund occurrences are assigned inside from source ids; pass all of an order's refunds together.

  • Every stage returns an outcome, and a stage that failed after the order existed returns payment-failed / refund-failed / invoice-failed with errors.<stage>.cause, so a resume reconciles the order and retries only what failed. An order-stage failure fails the rest for the cause order-not-imported; a target that cannot be read is order-target-read-failed and writes nothing.

  • The buyer's member id comes through buyer, never on the body, and the body's buyerInfo.email must be the billing email the member was corroborated against. lib/order-buyer.js resolveOrderBuyer({ sourceCustomerId, billingEmail, memberCrosswalk, contactCrosswalk }) links buyerInfo.memberId only when the member crosswalk row's loginEmail equals the order's billing email; a guest, a missing row or a mismatch links nothing and reports (buyer-* outcomes). The result is stamped; the composite sets buyerInfo from it and refuses a body that carries memberId itself. Import Order stores ANY GUID there unvalidated (verified live), so this is the only guard.

  • The invoice approval goes to the writer unchanged. The merchant opt-in is applied when the plan is built, nowhere else — and resolvePreservationPlan() stamps what it approves (lib/preservation-approval-stamp.js), so the writer refuses an opt-in that did not come from the plan. A READY Media file whose order patch failed comes back as invoice-fields-write-failed with pendingMediaFileId; the composite remembers it in the crosswalk (getInvoiceFile/setInvoiceFile) and the resume records that file instead of importing another. The crosswalk contract is four methods, all required.

  • Every crosswalk hit is verified with one paced order read. A hit is not proof: a row pointing at an order the target no longer has (a cleared migration) is re-imported under the derived id and counted as order-reimported-after-deletion. One read per order per run, hit or miss.

Live: tests/target-wix/order-history-live-sentinel.js (credential-gated) — three runs against a disposable site, one order and one payment afterwards, cleaned up through Bulk Delete Imported Orders. Passed 2026-09-05.

Per-writer reference — what the composite calls, in this order

The writers keep their contracts and remain callable; the composite is a new caller of them. This is what each one guarantees, kept here because the guarantees are the reason the sequence is safe:

  1. Gate on the source, first. evaluatePaymentEligibility() in lib/order-payment-mapping.js requires a positive amount AND a source paid date. An order total is not evidence of payment; neither is an order status, and neither is a transaction reference. Ineligible orders are reported under a named reason and never reach the target — which is also what keeps target reads proportional to evidenced payments rather than to the whole order population.

  2. Build the record, with buildPaymentRecord(). status sits at payment level, not inside regularPaymentDetails. savedPaymentMethod is never set: the field is writable but no reusable credential can accompany it, so setting it asserts a charging agreement that does not exist. An unknown offline/online class is OMITTED, never guessed — that is how a card payment ends up labelled as cash.

  3. Reconcile before creating, with writeOrderPayment(). It reads the order's existing payments every run and matches by provider reference, else by an exact fingerprint of the payment facts. The migration's own crosswalk is a hint, not proof of target state: it does not survive "Wix write succeeded, crosswalk write failed", and it is blind to payments the merchant created by hand. Exactly one match reconciles, more than one is ambiguous and prohibits creation, and a failed target read is its own outcome — never permission to create. Add Payments fails the ENTIRE call if a duplicate external transaction id is present, so writing blind breaks the run and can double recorded revenue.

  4. Refund only what the source evidences, with ensureOrderPaymentAndRefund(). Assign occurrence numbers first and pass sourceOccurrence (the composite does this from the refunds' source ids; a direct caller uses assignRefundOccurrences()): two distinct source refunds can share a payment and an amount, and without it the second one reconciles against the first and is silently dropped. It no longer fabricates a payment to give a refund something to point at; a qualified refund whose order evidences no payment is reported as refund-without-payment. externalRefund is a hardcoded literal true — it defaults to false, which calls the payment provider for real. Omit sideEffects entirely: that is what suppresses restock and the customer email. The refund date cannot be preserved (read-only and immutable), so every written refund discloses that loss, and the true date must not be smuggled into the customer-visible customerReason.

  5. Preserve invoice documents by reference, with preserveOrderInvoiceDocument(). Pass the approval straight from resolvePreservationPlan(), and pass sourceSiteHost with it. The writer refuses anything that is not an approval naming that exact URL, and it re-derives the DECISION from its own classification rather than trusting the approval's action: a document that is not on the source site needs merchantOptedIn however the approval is labelled — and the opt-in is believed only under the planner's provenance stamp. action is caller-supplied, and trusting it meant a caller could relabel a third-party document preserve and have it imported on nobody's authority. With no sourceSiteHost the guard answers third-party, so omitting it fails closed. Pass the persisted setup/extended-field-verification.json as setupVerification. When a previous run left an import in flight, pass its pendingMediaFileId back so the import RESUMES instead of creating another private orphan. It reads the order itself — pass an orderId, not an order object — so an existing file id suppresses the import and a re-run cannot import a second copy of a tax document. Pass the setup verification receipt (setup/extended-field-verification.json): without it the write is refused as invoice-fields-not-provisioned. The file is imported private: true; only the returned id is kept, because the Import File response echoes sourceUrl and that URL is a bearer link. Update Order MERGES the extendedFields object it is given — verified live: a foreign key survived a patch that never mentioned it. The write still sends the complete object, which is precautionary rather than load-bearing. Do not describe it as preventing data loss; the API does that itself. The Data Extension SCHEMA PUT is the opposite — there the merge is the only thing preserving a merchant's fields. Update Order also silently DROPS a value over the field's maxLength and still answers 200 (verified live 2026-10-27). The writer therefore leaves an over-length invoice number unset, without truncating it, and reports invoice-number-over-length. It reports any key the PATCH response does not carry back as invoice-field-dropped, and treats a dropped file id as invoice-fields-write-failed, with pendingMediaFileId for the resume. These findings arrive in the composite's findings; count them like every other finding.

Never call the invoicing service. Re-issuing a historical tax document mints a second legal document under a different number, and whether publishing one emails the customer is undocumented in either direction. The contract is non-use, and it is provable: tests/target-wix/no-invoices-api-contract-test.js scans the published tree.

Extended fields must be provisioned and verified before any value is written — see lib/data-extension-schema.js (orders, products, Contacts V5), lib/contact-extended-fields.js (legacy Contacts V4, explicit opt-in only) and the provisioning section in rp-execute-setup. A value write is blocked until setup verified that exact field. Contact values go under extendedFields.namespaces._user_fields with V5 writers, or info.extendedFields.<verifiedKey> with V4 writers — never both.

Coupons, coupon usage and plan definitions

Four small target-side pieces, all pure except the writers named in the table above:

  • lib/coupon-redemption-drift.js — a bearer voucher is money, and its redeemability must be decided at write time, not from the discovery snapshot. isBearerVoucher(coupon) narrows to the money-instrument shape (a fixed amount, no scope, no minimum, usage_limit: 1); classifySnapshot({ capturedAt, now, maxAgeMs }) refuses an undated or stale snapshot; classifyPreWriteDrift refuses to write a voucher spent since capture (coupons-spent-after-capture) and refuses to write one it cannot decide; classifyPostImportDrift + buildVoucherDriftPlan produce the cutover remedy plan, with face value and affected orders per code; verifyRemedyApplied insists on a post-settle read-back. One measured fact drives all of it. Update Coupon WRITES when the specification carries ONLY the changed fields plus a field mask — so a spent voucher is deactivated in place, keeping its id, code, dates and amount. Send the FULL specification alongside a narrow mask and it returns 200 with an empty body and writes nothing: the shape everyone reaches for first, and a pass that counts 2xx responses reports a false pass on money. buildRemedyRequest can only emit the minimal form; verifyRemedyApplied refuses to call any 2xx applied without a post-settle read-back. specification.tags is the one usable marker field (every alternative is silently dropped) and the vocabulary is frozen: Imported on everything a migration writes, plus Already_Used or Disabled_At_Source on a disabled one. All recorded as pitfalls on domains/stores/entities/coupon.json.

  • lib/order-applied-discount-build.js — buildCouponAppliedDiscounts({ couponLines, resolveCoupon }) turns a source order's coupon lines into appliedDiscounts[] entries of the coupon variant ({ id, code, name, amount: { amount } }, discountType: GLOBAL) for the Import Order body. There is no standalone write: the entity ecom/order-applied-discount is written through importOrder. A code the coupon crosswalk cannot resolve produces NO entry and an unresolved line — never a dangling coupon id. Import Order stores money as-is, so priceSummary.discount must already agree with the entries.

  • lib/pricing-plan-definition.js — evaluatePlanSources({ B1, B2, B3 }) (the row-count gate and the "none found" wording), buildPlanDefinition(offer) (PRIVATE, unbuyable, ACTIVE; name and description truncated WITH a finding; 7-day minimum cycle and 10-year maximum), and assertInertPlan, which the request builder and writer both call.

  • Live: tests/target-wix/coupon-plan-live-sentinel.js (credential-gated, cleans up) — one coupon of each mapped type including an expired and an exhausted one, one inert plan, one imported order carrying a coupon usage. Its verdicts are recorded as pitfalls on the entity files.

What stays in codegen (not here)

Per-project field maps and ordering (which source field → which data key, the media/author/taxonomy ref maps, upsert-by-key) live in the generated transforms/write specs. This adapter holds the invariant Wix request shapes, transport, and shared execution mechanics. Collection names and schemas (PodcastEpisodes, …) are project-specific and come from the mapping plan.

Provisioning pointers (see rp-execute-setup)

  • Apps (Blog, Members) install via the App Installation API; ground appDefId from the official "Apps Created by Wix" table.

  • Wix Data enablement (WDE0110): install the Wix Data app appDefId e593b0bd-b783-45b8-97c2-873d42aacaf4 via the App Installation API; afterward POST /wix-data/v2/collections creates NATIVE collections with no WDE0110 (verified live). Fallback: a custom app with a data-collections extension (declares collections at install time, but can't express REFERENCE fields).

Scope & coverage

Wix has many apps/entities (Stores, Bookings, Events, Restaurants, Pricing Plans, CRM, …). This adapter does not pre-build all of them. Coverage is demand-driven and grows through reviewed releases. A migration that targets a native Wix entity before a dedicated primitive exists writes it through guarded raw requests: the records are written, the plan shows "raw request, no reviewed writer" before consent, and the retro proposes a reviewed writer from the journaled calls. Generated code never writes it through sendDirectRest.

Native target ladder when no dedicated writer exists:

  1. Use the dedicated rp-target-wix primitive when one exists.

  2. If Wix has a native entity but no dedicated primitive, use guarded raw requests. Map it natively with write operation sendGuardedRawRequest; the client enforces the URL rules, the journal and the first-record check. A reviewed writer, when one ships, replaces the raw path automatically.

  3. Use CMS only when there is no suitable native Wix entity, or when the native entity is explicitly rejected for fidelity/side-effect reasons. CMS is not a fallback for a missing adapter writer.

  4. Halt if neither a native path nor an acceptable CMS/custom target exists.

The invariant: anything not backed by a verified primitive is surfaced to the user for consent before execution — never written silently.

Setup runtime expectations

This adapter should also define the shared setup-side runtime used by setup execution.

It should cover reusable mechanics for:

  • app installation and verification

  • Wix Data enablement verification

  • CMS collection and field provisioning when supported

  • setup step ordering/checkpointing

  • setup audit logging

  • setup execution reporting

rp-execute-setup should consume setup artifacts through this runtime rather than re-implementing setup mechanics in skill-local prose or one-off scripts.

Contract-test expectations

Contract tests should validate not only request builders, but also the most important shared runtime invariants.

Examples:

  • verified request shapes still serialize correctly

  • retry policy classifies common Wix failures correctly

  • throttle/backoff handling honors server hints

  • compact reports preserve stable top-level fields

  • completion reports preserve stable top-level fields

  • audit events preserve the agreed machine-readable shape

Default-location reconcileInventory outcomes include catalogVerification: exact Catalog variant availability must agree even when no stock write is needed. Catalog reads are grouped per product with at most four concurrent reads and bounded retries. Non-default locations mark this check not-applicable; Inventory-only success is not a default-location Catalog completion verdict.

Verified contact and product import callers

Use lib/contact-import.js importContacts and lib/product-import.js importProducts for standard imports. Inside an import task, pass importContacts the task's current evaluation (from evaluateTask) with the task's own client: it gates its rows and sends each bulk upsert with withBulkReadinessGrant, one source key per contact. A bulk body sent with a single record's grant is refused. They reconcile source identities before writes, persist candidate IDs in project-local state, and publish crosswalks only after identity/value read-back. The request primitives do not themselves certify a mapping. lib/bulk-results.js selects rules through explicit Contacts V5 / products-with-inventory / Inventory adapters; missing indexes are unresolved, never positional fallbacks. Blog bulk remains outside those adapters.

Product SEO runs inside importProducts for rows carrying seo (a lib/product-seo.js planProductSeo plan). It writes only proven or owner-materialized title/description tags through product.seoData, verifies each field on the product and in Item SEO resolvedTags, and reports report.seo.stageResiduals. Item SEO bulk set is refused for STORES_PRODUCT. Verification is bounded: at most 3 products in flight, every read through the shared sharedTargetReadPacer() (start slots reserved atomically and re-checked after a late timer wake, so actual starts stay >=60 ms apart), an immediate first resolvedTags read, and batch retry rounds whose settle wait stays within 31 s per stage. report.seo.timing reports settleWaitMs, pacingWaitMs and backoffWaitMs separately; the last two are summed per-call waits, never added to wall-clock.

lib/write-verification.js forwards to the shared runtime comparators in skills/wix-replatform/lib/write-verification.js. Contacts normalize only the main email (trim/lowercase) and compare other mapped values exactly after the existing per-source sanitizer. Phone-only identity and distinct source keys sharing a target block and report. Product variant matching uses source-fixed projections and exact target IDs; stock and default-location Catalog verification remain in reconcileInventory.

The existing subscription probe now records valueEvidence. Contract-ledger proposal creation and promotion recheck those inputs; toggling status or supplying only present paths cannot establish verified values. Existing published contracts remain in place. These changes add no automatic probe or global canary gate. Schema fingerprints retained as development evidence must be computed from saved docs-tool output, not authored claims.

Public multilingual target contract

Use scripts/multilingual-inventory.js to exhaust locale, schema, and translation-content pagination; it normalizes Wix's per-record schemaId/entityId/locale plus typed fields map into deterministic per-field inventory rows. After the normal writer's verified read-back, scripts/multilingual-object-pairing.js records every source-object to Wix-object binding and scripts/multilingual-member-pairing.js adds nested/repeated member bindings. Both accept only API-supported stable IDs and emit no receipt when there are no additional locales. A top-level field without a verified object receipt is unresolved; the source ID is never assumed to be the Wix ID. scripts/multilingual-execute.js applies the approved field-level sequences through a generated adapter and versioned disposable-site proof file. It refuses unproved mutations, secures typed prior values in ReplatformTranslationRecovery, verifies every value/publication state, and writes per-route cost evidence. scripts/multilingual-decision.js is the sole writer of the scoped local decision ledger, including durable owner restore requests. scripts/multilingual-restore.js restores a verified journal row only while the live replacement digest still matches. The recovery collection is administrator-only, stays on the destination, and is never exported. scripts/multilingual-journal-removal.js opens the post-window action and deletes only after a matching owner authorization; its absence read-back, not the authorization alone, closes the action.

Files

lib/order-history.js

'use strict';

// An imported order's history as ONE composite write.
//
// Four writes with an ordering constraint, a shared identity, two inputs that come from neither
// the source nor the mapping plan, and one piece of state that must outlive a crash. The first
// caller to assemble that by hand -- with the whole spec in context -- made four mistakes in an
// afternoon, and two of them were silent: a mis-named gate parameter that reported a plausible
// zero, and a missing order crosswalk that would have duplicated the store. The writers were
// right every time. So the SEQUENCE lives here, and a caller supplies facts: a mapped order body
// and the source's evidence. No ordering, no reconciliation, no gate invocation, no state.
//
// THE ORDER WRITE'S IDENTITY. LIVE-VERIFIED 2026-09-05 against a disposable site:
// Import Order ACCEPTS a
// caller-supplied `id` it has never seen and keeps it; a re-send with the same id fully replaces
// the order body; payments and extendedFields attached to the order SURVIVE the replace; a
// non-GUID id is refused with a 400. So the order id is DERIVED here from the source site and
// the source order id, which makes the order write idempotent on the target's own terms: a run
// that lost its crosswalk asks the target whether the derived id exists, and finds it. The
// crosswalk is still written -- before anything else -- but it is an accelerator and a report
// input, not the only thing standing between a crash and a duplicated store.
//
// What the probe ALSO showed, and why an existing order is never re-sent: a different order body
// with an existing id replaces it silently, and nothing distinguishes "replace mine" from
// "clobber a merchant's edits". So an order that already exists is RECONCILED (left alone) and
// its history continued, never re-imported. Search Orders is not used as an existence check: it
// read a stale number within a second of a change, and an id read is exact.

const crypto = require('node:crypto');
const fs = require('node:fs/promises');
const path = require('node:path');
const w = require('./wix-writers.js');
const paymentMapping = require('./order-payment-mapping.js');
const localState = require('../../../lib/local-state.js');
const approvalStamp = require('../../../lib/preservation-approval-stamp.js');
const orderBuyer = require('./order-buyer.js');
const customerMember = require('./customer-member.js');
const fsSync = require('node:fs');

const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

// A bounded retry for the TWO writes in this file that have earned one, and nowhere else. It is
// deliberately not on the shared client: bulk coupon, contact, member, form-submission, product
// and media creation are not reconciled against the target before writing, so a failure arriving
// AFTER the target committed would be retried into a second copy -- worse than the problem.
//
// Both sites below are reconciled first, so the second attempt is demonstrably the SAME attempt:
// the order id is derived from the source and the writer refuses a caller-chosen one, and the
// payment write is preceded by a read that decides create-or-adopt.
//
// `isTransientWixError` says the condition is likely to clear; whether a retry can duplicate
// anything is this call site's question, and only these two can answer it yes.
const WRITE_RETRY_ATTEMPTS = 3;
const WRITE_RETRY_DELAYS_MS = [500, 1500];
const realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const ORDER_OUTCOMES = Object.freeze({
  IMPORTED: 'order-imported',
  ALREADY_IMPORTED: 'order-already-imported',
  IMPORT_FAILED: 'order-import-failed',
  TARGET_READ_FAILED: 'order-target-read-failed',
});

// The evidence contract. A key outside this list is REFUSED, not ignored: an ignored key is how
// `sourceAmount` for `amount` reported every order in a live store as never paid, with no reason.
const EVIDENCE_KEYS = Object.freeze([
  'amount', 'paidDate', 'altPaidDate', 'currency', 'status', 'distinctAmountCount', 'utcOffsetMinutes',
  'paidDateZone', 'altPaidDateZone',
  'methodName', 'providerTransactionId', 'offlinePayment', 'cardDisplay',
  'refunds', 'invoice',
]);
const REFUND_KEYS = Object.freeze(['sourceId', 'amount', 'reason']);
const INVOICE_KEYS = Object.freeze(['approval', 'sourceUrl', 'invoiceNumber', 'pendingMediaFileId']);
// Names a caller is likely to reach for, and where each actually goes.
const MISNAMED = Object.freeze({
  sourceAmount: 'amount', total: 'amount', orderTotal: 'amount',
  sourcePaidDate: 'paidDate', datePaid: 'paidDate', paid: 'paidDate',
  // The two source stamps are NOT interchangeable and must not both land on `paidDate`: the
  // `_gmt` sibling is universal by the source schema's definition of that key, the plain one is
  // the shop's wall clock. Routing both here is how one shop offset came to be applied to a
  // value that was already universal, moving the payment by the whole offset.
  date_paid_gmt: "paidDate, declared paidDateZone: 'utc'",
  date_paid: "altPaidDate, declared altPaidDateZone: 'site-local'",
  sourceCurrency: 'currency',
  targetCurrency: 'nothing here -- the target currency is read from order.currency',
  transactionId: 'providerTransactionId', transaction_id: 'providerTransactionId', reference: 'providerTransactionId',
  method: 'methodName', paymentMethod: 'methodName', payment_method: 'methodName', payment_method_title: 'methodName',
  sourceStatus: 'status',
  refund: 'refunds (an array)', invoices: 'invoice (one document per order)',
});

function isPlainObject(value) {
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}

function assertKeys(object, allowed, label) {
  if (!isPlainObject(object)) throw new Error(`${label} must be an object, got ${JSON.stringify(object)}`);
  const unknown = Object.keys(object).filter((key) => !allowed.includes(key));
  if (unknown.length === 0) return;
  const hints = unknown.map((key) => (MISNAMED[key] ? `${key} (this contract calls it ${MISNAMED[key]})` : key));
  throw new Error(
    `${label} carries keys this contract does not read: ${hints.join(', ')}. Accepted: ${allowed.join(', ')}. `
    + 'Unknown keys are refused rather than ignored, because an ignored key reads exactly like a source that evidences nothing.',
  );
}

// Known keys with malformed VALUES are as silent as unknown keys: `offlinePayment: "false"` was
// dropped rather than read, a scalar `cardDisplay` lost the card evidence, and
// `distinctAmountCount: "unknown"` became NaN, which is "not more than one", which let a
// multi-payment order through the gate. Each is refused with the key and the value it got.
const EVIDENCE_TYPES = Object.freeze({
  amount: (v) => typeof v === 'string' || (typeof v === 'number' && Number.isFinite(v)),
  paidDate: (v) => typeof v === 'string',
  altPaidDate: (v) => typeof v === 'string',
  currency: (v) => typeof v === 'string',
  status: (v) => typeof v === 'string',
  distinctAmountCount: (v) => Number.isInteger(v) && v >= 1,
  // UTC-14 to UTC+14 is every offset that exists; 999999 accepted here moved a payment two years.
  utcOffsetMinutes: (v) => Number.isInteger(v) && v >= -840 && v <= 840,
  // A clock is a two-member enumeration, refused rather than coerced: 'UTC', true and 0 each
  // read exactly like a correctly-declared clock once coerced, and would restore the defect
  // these keys exist to remove -- silently, on a financial value.
  paidDateZone: (v) => v === 'utc' || v === 'site-local',
  altPaidDateZone: (v) => v === 'utc' || v === 'site-local',
  methodName: (v) => typeof v === 'string',
  providerTransactionId: (v) => typeof v === 'string',
  offlinePayment: (v) => typeof v === 'boolean',
  cardDisplay: (v) => isPlainObject(v)
    && Object.keys(v).every((k) => k === 'lastFourDigits' || k === 'brand')
    && Object.values(v).every((x) => x === null || x === undefined || typeof x === 'string'),
});
const EVIDENCE_TYPE_HINTS = Object.freeze({
  amount: 'a decimal string or finite number',
  paidDate: 'an ISO date-time string', altPaidDate: 'an ISO date-time string',
  currency: 'an ISO 4217 code string', status: 'a string',
  distinctAmountCount: 'a positive integer', utcOffsetMinutes: 'an integer between -840 and 840',
  paidDateZone: "'utc' or 'site-local'", altPaidDateZone: "'utc' or 'site-local'",
  methodName: 'a string', providerTransactionId: 'a string',
  offlinePayment: 'a real boolean (not the string "false")',
  cardDisplay: 'an object { lastFourDigits?, brand? } of strings',
});

function assertEvidence(evidence, { sourceId = null } = {}) {
  assertKeys(evidence, EVIDENCE_KEYS, 'evidence');
  // Internal: the source id the approval must name. Not a contract key -- set on a shallow copy.
  evidence = { ...evidence, __sourceId: sourceId };
  for (const [key, accepts] of Object.entries(EVIDENCE_TYPES)) {
    const value = evidence[key];
    if (value === undefined || value === null) continue;
    if (!accepts(value)) {
      throw new Error(`evidence.${key} must be ${EVIDENCE_TYPE_HINTS[key]}, got ${JSON.stringify(value)}`);
    }
  }
  // Cross-key: a shop offset supplied beside a stamp whose clock nobody stated. Knowing the shop's
  // offset is exactly the case where getting the clock wrong moves the money -- the offset is
  // applied, so a stamp that was already universal lands hours out. The 'site-local' default exists
  // to leave callers that never knew the offset untouched; it is not allowed to cover this shape.
  // Per PRESENT stamp, not once per record: declaring one clock and leaving the other on the
  // default reads as though the caller had been updated while still exposing a stamp the offset can
  // move. Deliberately NOT widened to "offset present => declaration required": an unpaid order in
  // a shop whose offset the run happens to know has no stamp to misapply it to.
  if (evidence.utcOffsetMinutes !== undefined && evidence.utcOffsetMinutes !== null) {
    for (const [stamp, zoneKey] of [['paidDate', 'paidDateZone'], ['altPaidDate', 'altPaidDateZone']]) {
      if (evidence[stamp] === undefined || evidence[stamp] === null) continue;
      if (evidence[zoneKey] !== undefined && evidence[zoneKey] !== null) continue;
      throw new Error(
        `evidence.${stamp} needs ${zoneKey} ('utc' or 'site-local') when utcOffsetMinutes is supplied; `
        + 'without it the offset may be applied to a stamp that is already universal',
      );
    }
  }
  if (evidence.refunds !== undefined) {
    if (!Array.isArray(evidence.refunds)) throw new Error('evidence.refunds must be an array (one entry per source refund)');
    evidence.refunds.forEach((refund, index) => {
      assertKeys(refund, REFUND_KEYS, `evidence.refunds[${index}]`);
      if (refund.sourceId === undefined || refund.sourceId === null || String(refund.sourceId).trim() === '') {
        throw new Error(`evidence.refunds[${index}] needs a sourceId; occurrence numbers are assigned by it and a re-run recognizes its own refunds through it`);
      }
      // A refund with no positive amount would reach Refund Payments as `amount: "undefined"` --
      // after the payment create it hangs off. Refused here, before any target call.
      const amount = paymentMapping.canonicalizeDecimal(refund.amount);
      if (amount === null || !(Number(amount) > 0)) {
        throw new Error(`evidence.refunds[${index}] needs a positive amount, got ${JSON.stringify(refund.amount)}`);
      }
    });
  }
  if (evidence.invoice !== undefined && evidence.invoice !== null) {
    const invoice = evidence.invoice;
    assertKeys(invoice, INVOICE_KEYS, 'evidence.invoice');
    // The approval must be the PLANNER's. The writer only insists on the stamp where an opt-in is
    // relied on; this composite insists everywhere, because a hand-built reference-only approval
    // with an object for a number wrote "[object Object]" onto an order in review. The plan is the
    // one producer, and it stamps everything it issues.
    if (!isPlainObject(invoice.approval) || !approvalStamp.verifyApprovalStamp(invoice.approval)) {
      throw new Error('evidence.invoice.approval must be an approval issued by resolvePreservationPlan() (it carries the plan\'s stamp); pass the plan\'s object, do not rebuild it');
    }
    // The planner's approvals name their order, and the stamp covers that name. One handed over
    // for a different source order would preserve somebody else's document onto this one (review
    // demonstrated it), and one with the order DELETED after stamping would fit any order (review
    // demonstrated that too) -- so the order is required, not merely compared when present.
    if (invoice.approval.orderId === undefined || invoice.approval.orderId === null || String(invoice.approval.orderId).trim() === '') {
      throw new Error('evidence.invoice.approval names no source order (orderId); resolvePreservationPlan() issues approvals per order, and one without an order could be handed to any');
    }
    if (String(invoice.approval.orderId) !== String(evidence.__sourceId)) {
      throw new Error(`evidence.invoice.approval is for source order ${invoice.approval.orderId}, not ${evidence.__sourceId}`);
    }
    const optional = (key, accepts, hint) => {
      const v = invoice[key];
      if (v === undefined || v === null) return;
      if (!accepts(v)) throw new Error(`evidence.invoice.${key} must be ${hint}, got ${JSON.stringify(v)}`);
    };
    optional('sourceUrl', (v) => typeof v === 'string', 'a URL string');
    optional('invoiceNumber', (v) => typeof v === 'string' || typeof v === 'number', 'a string or number');
    optional('pendingMediaFileId', (v) => typeof v === 'string' && v.trim() !== '', 'a Media file id string');
  }
}

// A stable GUID for a source order on this target. Version-5 style: a SHA-1 over a namespaced
// name with the version and variant bits set, which is what Import Order accepted live. The
// source SITE is part of the name so two stores importing "order 1042" into one Wix site cannot
// collide -- and so a migration re-run from the same store converges on the same order.
// `shop.example`, `https://shop.example/`, `SHOP.EXAMPLE:443` and `shop.example/wp` are one site.
// Four spellings deriving four ids would re-import a store the day a config string gained a
// scheme, so the host is normalized to its bare lowercase hostname (a non-default port is kept).
function normalizeSourceSiteHost(sourceSiteHost) {
  let text = String(sourceSiteHost === undefined || sourceSiteHost === null ? '' : sourceSiteHost).trim().toLowerCase();
  if (!text) return '';
  if (!/^[a-z][a-z0-9+.-]*:\/\//.test(text)) text = `https://${text}`;
  let url;
  try { url = new URL(text); } catch (error) { return ''; }
  return url.port && url.port !== '443' ? `${url.hostname}:${url.port}` : url.hostname;
}

function deriveImportedOrderId({ sourceSiteHost, sourceId } = {}) {
  const host = normalizeSourceSiteHost(sourceSiteHost);
  const id = sourceId === undefined || sourceId === null ? '' : String(sourceId).trim();
  if (!host) throw new Error('deriveImportedOrderId needs sourceSiteHost (a hostname, or a URL it can be read from): the id is namespaced by the source site');
  if (!id) throw new Error('deriveImportedOrderId needs the source order id');
  const hash = crypto.createHash('sha1').update(`replatform:ecom:order:${host}:${id}`).digest();
  hash[6] = (hash[6] & 0x0f) | 0x50;
  hash[8] = (hash[8] & 0x3f) | 0x80;
  const hex = hash.toString('hex');
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}

// Same rule as rp-source-wordpress's assignRefundOccurrences, kept target-side so this module does
// not depend on a source adapter: two source refunds of equal amount on one order are the first
// and second OCCURRENCE of that amount, ordered by source id, and reconcile as such. Pass ALL of an
// order's refunds in one call -- occurrences are relative to the list.
function withOccurrences(refunds) {
  const seen = new Map();
  return [...refunds]
    .sort((a, b) => String(a.sourceId).localeCompare(String(b.sourceId)))
    .map((refund) => {
      const key = paymentMapping.canonicalizeDecimal(refund.amount) || String(refund.amount);
      const occurrence = (seen.get(key) || 0) + 1;
      seen.set(key, occurrence);
      return { ...refund, sourceOccurrence: occurrence };
    });
}

function describeError(error) {
  return {
    message: String((error && error.message) || error).slice(0, 300),
    ...(error && error.status ? { status: error.status } : {}),
    // Conditional, like the rest: an unknown outcome is the exceptional case, and making this
    // unconditional would change the shape of every row already written to a results ledger.
    // Without it, the rejected-vs-unknown distinction is lost the moment it is recorded.
    ...(error && error.outcomeKnown === false ? { outcomeKnown: false } : {}),
    ...(error && error.applicationErrorCode ? { applicationErrorCode: error.applicationErrorCode } : {}),
    // A refusal before the network (readiness, raw-request guard) wrote nothing; kept so the
    // journal row can say retryable rather than guess from a missing status.
    ...(error && error.requestSent === false ? { requestSent: false } : {}),
    ...(error && typeof error.code === 'string' && error.code ? { code: error.code } : {}),
  };
}

function assertCrosswalk(crosswalk) {
  const has = (name) => crosswalk && typeof crosswalk[name] === 'function';
  if (!has('get') || !has('set') || !has('getInvoiceFile') || !has('setInvoiceFile')) {
    throw new Error(
      'importOrderHistory needs a persisted crosswalk with get(sourceId), set(sourceId, orderId), '
      + 'getInvoiceFile(sourceId) and setInvoiceFile(sourceId, fileId). It is not optional: a run that '
      + 'forgets it re-imports the store, and one that forgets the invoice file imports a second copy of a '
      + 'tax document. createProjectOrderCrosswalk({ projectDir }) provides all four over state/crosswalk/.',
    );
  }
}

// Fill every remaining stage with a named outcome once the order stage has failed. Nothing else
// is attempted: with no order there is nothing to attach a payment or a document to, and a payment
// that was never attempted because of an import failure is a FAILURE, not an ineligibility.
function failRemaining(outcomes, errors, { gate, refunds, evidence, cause }) {
  outcomes.payment = gate.eligible ? 'payment-failed' : gate.outcome;
  if (gate.eligible) errors.payment = { cause };
  outcomes.refunds = refunds.map((refund) => ({
    sourceId: refund.sourceId,
    sourceOccurrence: refund.sourceOccurrence,
    outcome: gate.eligible ? 'refund-failed' : 'refund-without-payment',
    ...(gate.eligible ? { error: { cause } } : {}),
  }));
  outcomes.invoice = evidence.invoice ? 'invoice-failed' : 'invoice-none-found';
  if (evidence.invoice) errors.invoice = { cause };
}

// ---- contact fields --------------------------
// A source email or phone Import Order refuses fails the WHOLE order. The policy: a
// contact detail is removed only when Import Order's own rejection NAMES that field, and the
// order is then sent once more without it. Never removed on a local or customer-path check
// alone, never rewritten, never replaced with an invented value. Every removal is a named
// finding carrying the field and a reason, never the value.
//
// The field list is READ from `domains/ecom/entities/order.json` -> `contactFields[]`, so the
// rules and the entity knowledge cannot drift apart.
const ORDER_ENTITY_JSON = path.join(__dirname, '..', 'domains', 'ecom', 'entities', 'order.json');
let CONTACT_FIELDS = null;
function orderContactFields() {
  if (CONTACT_FIELDS) return CONTACT_FIELDS;
  const entity = JSON.parse(fsSync.readFileSync(ORDER_ENTITY_JSON, 'utf8'));
  const fields = Array.isArray(entity.contactFields) ? entity.contactFields : [];
  if (fields.length === 0) throw new Error(`${ORDER_ENTITY_JSON} carries no contactFields[]; the contact-field rules read their list from there and will not guess one`);
  for (const field of fields) {
    if (field.kind !== 'email' && field.kind !== 'phone') {
      throw new Error(`contactFields[] entry ${field.targetPath} has kind ${JSON.stringify(field.kind)}; only "email" and "phone" are known`);
    }
  }
  CONTACT_FIELDS = Object.freeze(fields.map((field) => Object.freeze({ kind: String(field.kind), targetPath: String(field.targetPath) })));
  return CONTACT_FIELDS;
}

function readAtPath(object, dotted) {
  let node = object;
  for (const key of dotted.split('.')) {
    if (!isPlainObject(node)) return undefined;
    node = node[key];
  }
  return node;
}

// Copy-on-write down the path only; the caller's object is never mutated.
function withoutPath(object, dotted) {
  const [head, ...rest] = dotted.split('.');
  if (!isPlainObject(object) || !(head in object)) return object;
  if (rest.length === 0) {
    const next = { ...object };
    delete next[head];
    return next;
  }
  const child = withoutPath(object[head], rest.join('.'));
  return child === object[head] ? object : { ...object, [head]: child };
}

function presentValue(value) {
  if (value === undefined || value === null) return null;
  const text = String(value).trim();
  return text === '' ? null : text;
}

// Advisory only. Run on the SOURCE-DERIVED body, before the first send. The body is never
// changed; a suspect is a forecast, not a loss.
function checkOrderContactFields(order, { sourceId = null } = {}) {
  if (!isPlainObject(order)) throw new Error('checkOrderContactFields needs the mapped target order body as `order`');
  const findings = [];
  const id = sourceId === undefined || sourceId === null ? null : String(sourceId);
  const countryCode = presentValue(readAtPath(order, 'billingInfo.address.country'));
  for (const field of orderContactFields()) {
    const value = presentValue(readAtPath(order, field.targetPath));
    if (value === null) continue; // an absent detail is not a defect
    if (field.kind === 'email') {
      if (orderBuyer.normalizeEmail(value) === null) {
        findings.push({ code: 'order-contact-email-suspect', ...(id ? { sourceId: id } : {}), field: field.targetPath, reason: 'not-a-sendable-address' });
      }
    } else {
      const normalized = customerMember.normalizePhoneE164(value, countryCode);
      if (!normalized.ok) {
        findings.push({ code: 'order-contact-phone-suspect', ...(id ? { sourceId: id } : {}), field: field.targetPath, reason: String(normalized.reason) });
      }
    }
  }
  return { findings };
}

// Which contact fields did Import Order's rejection NAME? Only a 400 with a structured
// `fieldViolations[]` counts, and only an EXACT path match (after an optional leading `order.`
// request wrapper) against `contactFields[]`. Message text is never parsed. All or
// nothing: one violation that is not an identified contact field means no removal (null).
function identifyRejectedContactFields(error) {
  if (!error || error.status !== 400) return null;
  const violations = error.body && error.body.details && error.body.details.validationError
    && error.body.details.validationError.fieldViolations;
  if (!Array.isArray(violations) || violations.length === 0) return null;
  const known = new Set(orderContactFields().map((field) => field.targetPath));
  const paths = [];
  for (const violation of violations) {
    const raw = violation && typeof violation.field === 'string' ? violation.field : null;
    if (raw === null) return null;
    const field = raw.startsWith('order.') ? raw.slice('order.'.length) : raw;
    if (!known.has(field)) return null;
    if (!paths.includes(field)) paths.push(field);
  }
  return paths;
}

// ---- source orders with no line items -------------------------------------
// Import Order requires 1-300 lineItems. A source order that recorded none (items deleted at the
// source, a total with no lines) would fail terminally. Human-approved policy (2026-11-01):
// import it with ONE custom line "Items not recorded in source" priced at the
// order total, in the order's own currency, with no tax information invented, and hand each such
// order to cutover. Financial data, so this is a human-approved policy, not an engineering default.
const PLACEHOLDER_LINE_NAME = 'Items not recorded in source';
const PLACEHOLDER_LINE_ITEM_TYPE = 'not-recorded-in-source';
const PLACEHOLDER_GAP_CODE = 'order-line-items-not-recorded';
const PLACEHOLDER_GAP_ACTION = 'Each of these orders recorded no line items at the source, so it was imported with one custom line "Items not recorded in source" at the order total (no tax). Confirm the order total with the merchant; if the original items are known, note them on the order. Do not delete or re-import the order.';
function placeholderLineId(derivedId) {
  const hash = crypto.createHash('sha1').update(`replatform:ecom:order-line:${derivedId}:not-recorded`).digest();
  hash[6] = (hash[6] & 0x0f) | 0x50;
  hash[8] = (hash[8] & 0x3f) | 0x80;
  const hex = hash.toString('hex');
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
}
function placeholderAmount(order) {
  const raw = order && order.priceSummary && order.priceSummary.total && order.priceSummary.total.amount;
  const n = Number(raw);
  return raw !== undefined && raw !== null && String(raw).trim() !== '' && Number.isFinite(n) && n >= 0 ? String(raw).trim() : null;
}
// An order with lineItems is returned unchanged. Pure: the caller's body is never mutated.
function withPlaceholderLineItem(order, { derivedId }) {
  if (!isPlainObject(order) || (Array.isArray(order.lineItems) && order.lineItems.length > 0)) return { order, placeholder: null };
  // No usable order total: the line is priced at 0 and the finding says so (totalMissing).
  const total = placeholderAmount(order), amount = total === null ? '0' : total;
  const line = {
    id: placeholderLineId(derivedId),
    quantity: 1,
    productName: { original: PLACEHOLDER_LINE_NAME },
    itemType: { custom: PLACEHOLDER_LINE_ITEM_TYPE },
    price: { amount },
    lineItemPrice: { amount },
  };
  return { order: { ...order, lineItems: [line] }, placeholder: { lineItemId: line.id, amount, currency: order.currency === undefined ? null : order.currency, ...(total === null ? { totalMissing: true } : {}) } };
}

// The composite. Returns outcomes; throws only for CALLER errors (a malformed contract), never for
// a target failure -- each stage's failure is a named outcome so a resumed run reconciles what
// landed and retries only what did not.
async function importOrderHistory(wix, {
  order,
  sourceId,
  sourceSiteHost,
  evidence,
  crosswalk,
  setupVerification = null,
  pacer = null,
  // Injectable only so the retry tests do not spend the delay ladder in real time.
  sleep = null,
  // The buyer, from resolveOrderBuyer -- stamped, so a hand-built memberId cannot reach
  // the order. Optional: an order with no buyer resolution imports with whatever contactId the
  // mapped body already carries, and never a memberId.
  buyer = null,
} = {}) {
  if (!wix || typeof wix.send !== 'function') throw new Error('importOrderHistory needs a Wix client');
  const sleepFor = sleep || realSleep;
  const findings_pre = [];
  if (!isPlainObject(order)) throw new Error('importOrderHistory needs the mapped target order body as `order`');
  assertCrosswalk(crosswalk);
  assertEvidence(evidence, { sourceId });
  const derivedId = deriveImportedOrderId({ sourceSiteHost, sourceId });
  if (order.id !== undefined && order.id !== derivedId) {
    throw new Error(`order.id is not the caller's to choose: got ${order.id}, this order derives to ${derivedId}. Omit it.`);
  }
  // buyerInfo.memberId is what member-facing reads authorize on, and Import Order stores any GUID
  // unvalidated (verified live 2026-09-05). So it is never the caller's to set on the body: it comes
  // through `buyer`, corroborated and stamped by resolveOrderBuyer, or not at all.
  orderBuyer.assertBodyBuyerInfo(order);
  // No buyer resolution is itself a counted outcome, so the buyer stage partitions the order
  // population like the payment stage does.
  let buyerOutcome = 'buyer-not-resolved';
  if (buyer !== null && buyer !== undefined) {
    if (!orderBuyer.verifyBuyerStamp(buyer)) throw new Error('`buyer` must be the unchanged result of resolveOrderBuyer (its stamp did not verify)');
    // The resolver corroborated the member against ONE order's billing email, and the stamp covers
    // that email. The BODY's email must be the same one: a result resolved for jane@ handed over
    // beside a body carrying victim@ would attribute the victim's order and invoice to Jane, with
    // the stamp verifying (review demonstrated it). Bound for every outcome -- a resolution made for
    // a different order is wrong whatever it decided -- and a linked result requires the body to
    // carry the email at all, so the two are never merely "both absent".
    const rawBodyEmail = order.buyerInfo && order.buyerInfo.email;
    const bodyEmail = orderBuyer.normalizeEmail(rawBodyEmail);
    const bodyHasEmail = rawBodyEmail !== undefined && rawBodyEmail !== null && String(rawBodyEmail).trim() !== '';
    if (buyer.email && bodyHasEmail && bodyEmail !== buyer.email) {
      throw new Error('`buyer` was resolved for a different billing email than order.buyerInfo.email carries; resolve the buyer from THIS order\'s billing email');
    }
    if (buyer.memberId && (!bodyHasEmail || bodyEmail !== buyer.email)) {
      throw new Error('a linked `buyer` requires order.buyerInfo.email to be the billing email the member was corroborated against; the body carries none or another');
    }
    const info = orderBuyer.buyerInfoFrom(buyer);
    // Replace, not merge: only the body's email survives beside what the resolver decided.
    const kept = order.buyerInfo && order.buyerInfo.email ? { email: order.buyerInfo.email } : {};
    order = { ...order, buyerInfo: { ...kept, ...(order.buyerInfo && order.buyerInfo.contactId && !info.contactId ? { contactId: order.buyerInfo.contactId } : {}), ...info } };
    buyerOutcome = buyer.outcome;
    for (const finding of buyer.findings || []) findings_pre.push(finding);
  }

  const findings = findings_pre;
  const errors = {};
  const placed = withPlaceholderLineItem(order, { derivedId });
  order = placed.order;
  if (placed.placeholder) findings.push({ code: PLACEHOLDER_GAP_CODE, sourceId: String(sourceId), ...placed.placeholder });
  const outcomes = { order: null, payment: null, refunds: [], invoice: null, buyer: buyerOutcome };

  // The gate runs FIRST and from the evidence structure, so a caller cannot mis-name a parameter
  // into a silent zero. It is pure: no target read is spent on an order the source never paid.
  const gate = paymentMapping.evaluatePaymentEligibility({
    sourceAmount: evidence.amount === undefined ? null : evidence.amount,
    paidDate: evidence.paidDate === undefined ? null : evidence.paidDate,
    altPaidDate: evidence.altPaidDate === undefined ? null : evidence.altPaidDate,
    distinctAmountCount: evidence.distinctAmountCount === undefined ? 1 : evidence.distinctAmountCount,
    sourceCurrency: evidence.currency === undefined ? null : evidence.currency,
    targetCurrency: order.currency === undefined ? null : order.currency,
    utcOffsetMinutes: evidence.utcOffsetMinutes === undefined ? null : evidence.utcOffsetMinutes,
    paidDateZone: evidence.paidDateZone === undefined || evidence.paidDateZone === null ? 'site-local' : evidence.paidDateZone,
    altPaidDateZone: evidence.altPaidDateZone === undefined || evidence.altPaidDateZone === null ? 'site-local' : evidence.altPaidDateZone,
    sourceStatus: evidence.status === undefined ? null : evidence.status,
  });
  findings.push(...(gate.findings || []));

  let payment = null;
  if (gate.eligible) {
    const built = paymentMapping.buildPaymentRecord({
      amount: gate.amount,
      createdDate: gate.createdDate,
      methodName: evidence.methodName === undefined ? null : evidence.methodName,
      providerTransactionId: evidence.providerTransactionId === undefined ? null : evidence.providerTransactionId,
      offlinePayment: evidence.offlinePayment,
      cardDisplay: evidence.cardDisplay === undefined ? null : evidence.cardDisplay,
    });
    payment = built.payment;
    findings.push(...(built.findings || []));
  }
  const refunds = withOccurrences(evidence.refunds || []);

  // ---- 1. The order. Crosswalk hit or miss, the TARGET is asked once by id. -------------------
  // A hit is not proof: the docs' own use of Bulk Delete Imported Orders is "clear a faulty
  // migration before re-importing", and a crosswalk that survived that must not report an order
  // the target no longer has. Only a readable 404 proves absence; an unreadable gateway
  // response must not authorize Import Order, which can replace an existing order.
  let orderId = derivedId;
  const readPacer = pacer || w.sharedTargetReadPacer(wix);
  const existsOnTarget = async (id) => {
    const read = await readPacer.read(() => w.getOrder(wix, id));
    if (read.ok) return { exists: true };
    if (read.error && read.error.status === 404 && read.error.outcomeKnown !== false) return { exists: false };
    return { exists: null, error: read.error };
  };
  const known = await crosswalk.get(sourceId);
  // The crosswalk's answer is trusted as the order's identity, so its SHAPE is not: a row object
  // where a string was expected became `orders/[object Object]/add-payment` in review. Only a
  // GUID-shaped string may stand for an order; anything else is a broken crosswalk, which is a
  // caller problem and stops the run rather than continuing history onto a nonsense id.
  if (known !== null && known !== undefined && known !== '' && !GUID.test(String(known))) {
    throw new Error(`the crosswalk returned ${JSON.stringify(known)} for source order ${sourceId}; a crosswalk value must be the Wix order id (a GUID string) or null`);
  }
  // A row from before deterministic ids (a Wix-minted id) is still THE order: honouring it is what
  // keeps an earlier migration from being re-imported under a derived id.
  const candidateId = known ? String(known) : derivedId;
  const probe = await existsOnTarget(candidateId);
  if (probe.exists === null) {
    // Cannot tell whether the order is there. Importing now could replace a merchant-edited order;
    // not importing loses nothing a retry cannot recover. So: a named outcome, no write.
    outcomes.order = ORDER_OUTCOMES.TARGET_READ_FAILED;
    errors.order = describeError(probe.error);
    failRemaining(outcomes, errors, { gate, refunds, evidence, cause: 'order-not-imported' });
    return { orderId: null, derivedId, outcomes, findings, errors, paymentId: null, invoice: null };
  }
  if (probe.exists) {
    orderId = candidateId;
    if (known && orderId !== derivedId) findings.push({ code: 'order-id-from-crosswalk', sourceId: String(sourceId), orderId });
    outcomes.order = ORDER_OUTCOMES.ALREADY_IMPORTED;
    if (!known) {
      // The crosswalk had lost it; adopt it.
      try { await crosswalk.set(sourceId, orderId); } catch (error) { errors.crosswalk = describeError(error); }
    }
  } else {
    let derivedExists = false;
    if (known) {
      // The crosswalk points at an order the target no longer has -- a cleared migration, or a
      // stale row. Before importing under the derived id, ask whether THAT order already exists:
      // Import Order with an existing id silently replaces it, and a merchant's edits with it
      // (review demonstrated exactly that). If it exists, adopt it and replace the row.
      const derivedProbe = await existsOnTarget(derivedId);
      if (derivedProbe.exists === null) {
        outcomes.order = ORDER_OUTCOMES.TARGET_READ_FAILED;
        errors.order = describeError(derivedProbe.error);
        failRemaining(outcomes, errors, { gate, refunds, evidence, cause: 'order-not-imported' });
        return { orderId: null, derivedId, outcomes, findings, errors, paymentId: null, invoice: null };
      }
      derivedExists = derivedProbe.exists === true;
      findings.push(derivedExists
        ? { code: 'order-crosswalk-row-stale', sourceId: String(sourceId), previousOrderId: String(known), orderId: derivedId }
        : { code: 'order-reimported-after-deletion', sourceId: String(sourceId), previousOrderId: String(known) });
    }
    if (derivedExists) {
      orderId = derivedId;
      outcomes.order = ORDER_OUTCOMES.ALREADY_IMPORTED;
    } else {
      try {
        // Retried on a transient failure, and safe to: the id is derived from the source and
        // `:296` refuses a caller-chosen one, so a second attempt re-sends the same identity. A
        // retry that comes back already-imported is a SUCCESS -- the existing ALREADY_IMPORTED
        // outcome covers it. Only the send is wrapped: the checks below it are permanent
        // refusals, not conditions that clear.
        const send = async (body) => {
          for (let attempt = 1; ; attempt += 1) {
            try {
              return await w.importOrder(wix, { ...body, id: derivedId });
            } catch (error) {
              if (attempt >= WRITE_RETRY_ATTEMPTS || !w.isTransientWixError(error)) throw error;
              await sleepFor(WRITE_RETRY_DELAYS_MS[attempt - 1]);
            }
          }
        };
        // Advisory, on the source-derived body, once, before the first send.
        // Not repeated for the retry below.
        findings.push(...checkOrderContactFields(order, { sourceId }).findings);
        let imported = null;
        let removed = [];
        try {
          imported = await send(order);
        } catch (error) {
          // One retry, only when the rejection names contact fields the body
          // actually carries. The first call was refused and created nothing, so the retry under
          // the same derived id is not a duplicate. The retry body is the SOURCE-DERIVED order
          // minus exactly those paths, and on a
          // member-linked order it keeps `buyerInfo.memberId`/`contactId` untouched.
          const paths = identifyRejectedContactFields(error);
          if (!paths || !paths.every((p) => readAtPath(order, p) !== undefined)) throw error;
          const retryBody = paths.reduce((body, p) => withoutPath(body, p), order);
          imported = await send(retryBody);
          removed = paths;
        }
        if (!imported || !imported.id) {
          throw new Error('Import Order returned no order id');
        }
        if (imported.id !== derivedId && !GUID.test(String(imported.id))) {
          // Cannot be recorded (the crosswalk accepts only GUIDs) and cannot be trusted. Reported
          // with the id so a human can find the order by number; the run does not continue history
          // onto it.
          throw new Error(`Import Order returned a non-GUID id ${JSON.stringify(imported.id)} for source order ${sourceId} (number ${order.number}); the order may exist on the target under it`);
        }
        if (imported.id !== derivedId) {
          // The order EXISTS, under an id we did not choose. Reporting a failure here would leave
          // no crosswalk row, and every re-run would import it again -- the one outcome this
          // module exists to prevent. So the target's id is adopted and recorded, the order counts
          // as imported, and the finding says the identity model did not hold on this target.
          orderId = String(imported.id);
          findings.push({ code: 'order-id-not-derived', sourceId: String(sourceId), orderId, derivedId });
        }
        outcomes.order = ORDER_OUTCOMES.IMPORTED;
        // One drop finding per removed path, only once the order landed without it. Field and
        // reason, never the value, the member id or the rejection's wording.
        const kinds = new Map(orderContactFields().map((field) => [field.targetPath, field.kind]));
        for (const field of removed) {
          findings.push({
            code: kinds.get(field) === 'email' ? 'order-contact-email-dropped' : 'order-contact-phone-dropped',
            sourceId: String(sourceId),
            field,
            reason: 'import-order-rejected-field',
            ...(field === 'buyerInfo.email' && buyerOutcome === orderBuyer.OUTCOMES.LINKED ? { memberLinkKept: true } : {}),
          });
        }
      } catch (error) {
        outcomes.order = ORDER_OUTCOMES.IMPORT_FAILED;
        errors.order = describeError(error);
        failRemaining(outcomes, errors, { gate, refunds, evidence, cause: 'order-not-imported' });
        return { orderId: null, derivedId, outcomes, findings, errors, paymentId: null, invoice: null };
      }
    }
      // Persisted BEFORE any further write. The one thing nothing else catches. If the write
      // itself fails the order is still on the target and the next run finds it by derived id, so
      // the run continues -- but the caller is told, because a crosswalk that silently stopped
      // persisting is a report that undercounts what landed.
      try {
        await crosswalk.set(sourceId, orderId);
      } catch (error) {
        errors.crosswalk = describeError(error);
      }
  }

  // A landed order that carries the placeholder line is a cutover item, never only a finding.
  if (placed.placeholder && orderId && [ORDER_OUTCOMES.IMPORTED, ORDER_OUTCOMES.ALREADY_IMPORTED].includes(outcomes.order)) {
    try {
      await w.recordWrittenGap(wix, { code: PLACEHOLDER_GAP_CODE, action: PLACEHOLDER_GAP_ACTION, operatorRole: 'Cutover Operator', severity: 'medium',
        detail: { targetId: orderId, orderNumber: order.number === undefined ? null : String(order.number), amount: placed.placeholder.amount, currency: placed.placeholder.currency, ...(placed.placeholder.totalMissing ? { totalMissing: true } : {}) } });
    } catch (error) { errors.cutoverItem = describeError(error); }
  }

  // ---- 2. Payment and refunds, from ONE reconciliation read. ---------------------------------
  let paymentId = null;
  if (!gate.eligible) {
    outcomes.payment = gate.outcome;
    outcomes.refunds = refunds.map((refund) => ({ sourceId: refund.sourceId, sourceOccurrence: refund.sourceOccurrence, outcome: 'refund-without-payment' }));
  } else {
    // The read and the write are retried as ONE pair or not at all. The read decides create-or-
    // adopt, and a failed write attempt is exactly what can make that decision stale -- the
    // attempt that failed may be what created the payment. Retrying the write alone would re-use
    // the pre-failure decision and add a second payment. `assertReconciledBinding`
    // (`wix-writers.js:3729`) refuses a read taken for a different order or a different payment
    // fingerprint, but it cannot detect a stale read for the right one.
    //
    // A `payment-target-read-failed` reconcile does NOT enter this loop: the pacer already
    // retried it internally and `writeOrderPayment` returns that outcome rather than throwing.
    let reconciled = await w.reconcileOrderPaymentTarget(wix, { orderId, payment, pacer });
    let written = null;
    try {
      for (let attempt = 1; ; attempt += 1) {
        try {
          written = await w.writeOrderPayment(wix, { orderId, payment, pacer, reconciled });
          break;
        } catch (error) {
          if (attempt >= WRITE_RETRY_ATTEMPTS || !w.isTransientWixError(error)) throw error;
          await sleepFor(WRITE_RETRY_DELAYS_MS[attempt - 1]);
          // Re-read before re-writing. Coming back RECONCILED means the failed attempt committed
          // after all, and the writer turns that into `payment-reconciled-existing` with no
          // second write -- which is the outcome, not a failure.
          reconciled = await w.reconcileOrderPaymentTarget(wix, { orderId, payment, pacer });
        }
      }
      outcomes.payment = written.outcome;
      paymentId = written.paymentId || null;
      if (written.error) errors.payment = describeError(written.error);
      // "Written" with no id is not written: the refund path would see CREATE still standing and
      // add the payment a second time. Demonstrated in review with an empty `paymentsIds`.
      if (outcomes.payment === 'payment-written' && !paymentId) {
        outcomes.payment = 'payment-failed';
        errors.payment = { cause: 'add-payment-returned-no-id' };
      }
    } catch (error) {
      outcomes.payment = 'payment-failed';
      errors.payment = describeError(error);
    }
    // No payment id means no payment to hang anything off, whatever the outcome's name: ambiguous
    // reconciliation carries no error object from the writer, so the cause is recorded here.
    if (!paymentId && !errors.payment) errors.payment = { cause: outcomes.payment };
    // The refund path sees the same read, updated with the payment this run just created so it
    // does not create a second one. A payment stage that failed leaves nothing to refund against.
    const forRefunds = paymentId && reconciled.outcome === paymentMapping.RECONCILE.CREATE
      ? { ...reconciled, outcome: paymentMapping.RECONCILE.RECONCILED, paymentId, matchedBy: 'written-this-run' }
      : reconciled;
    for (const refund of refunds) {
      const line = { sourceId: refund.sourceId, sourceOccurrence: refund.sourceOccurrence, outcome: null, refundId: null, paymentId: null };
      if (!paymentId) {
        // Refunds are REFUND outcomes. Letting the writer answer here returned the payment stage's
        // own code as the refund's, which the report counts as a payment bucket and never as a
        // refund that did not land.
        line.outcome = 'refund-failed';
        line.error = { cause: outcomes.payment };
      } else {
        try {
          const result = await w.ensureOrderPaymentAndRefund(wix, {
            orderId,
            payment,
            refundAmount: refund.amount,
            reason: refund.reason,
            sourceRefundId: refund.sourceId,
            sourceOccurrence: refund.sourceOccurrence,
            pacer,
            reconciled: forRefunds,
          });
          line.outcome = result.outcome;
          line.refundId = result.refundId || (result.refund && result.refund.id) || null;
          line.paymentId = result.paymentId || null;
        } catch (error) {
          line.outcome = 'refund-failed';
          line.error = describeError(error);
        }
      }
      outcomes.refunds.push(line);
    }
  }

  // ---- 3. The invoice document. ---------------------------------------------------------------
  let invoice = null;
  if (!evidence.invoice) {
    outcomes.invoice = 'invoice-none-found';
  } else {
    // A document that reached Media but whose order patch failed is remembered HERE, in the same
    // persisted state as the order id, not by the caller: a generated importer following the
    // documented loop without persisting it imported a second copy in review. The caller may still
    // pass one explicitly (an older project's state); the crosswalk's answer is the fallback.
    let pendingMediaFileId = evidence.invoice.pendingMediaFileId || null;
    let rememberedPending = null;
    if (!pendingMediaFileId) {
      try {
        const remembered = await crosswalk.getInvoiceFile(sourceId);
        // Either a bare id (older rows) or { fileId, sourceUrl }. A remembered file is only THIS
        // document's if it was imported from the same URL: a re-issued invoice under a new link
        // must not be "resumed" onto the old bytes (review demonstrated it).
        const rememberedId = typeof remembered === 'string' ? remembered : remembered && remembered.fileId;
        const rememberedUrl = remembered && typeof remembered === 'object' ? remembered.sourceUrl || null : null;
        if (rememberedId && String(rememberedId).trim() !== '') {
          if (!rememberedUrl || rememberedUrl === (evidence.invoice.sourceUrl || null)) { pendingMediaFileId = String(rememberedId); rememberedPending = pendingMediaFileId; }
          else findings.push({ code: 'invoice-pending-file-superseded', sourceId: String(sourceId), note: 'a remembered Media file was imported from a different URL and was not resumed' });
        }
      } catch (error) {
        errors.crosswalk = errors.crosswalk || describeError(error);
      }
    }
    try {
      invoice = await w.preserveOrderInvoiceDocument(wix, {
        orderId,
        sourceUrl: evidence.invoice.sourceUrl,
        invoiceNumber: evidence.invoice.invoiceNumber,
        approval: evidence.invoice.approval,
        setupVerification,
        sourceSiteHost,
        pendingMediaFileId,
      });
      outcomes.invoice = invoice.outcome;
      // The writer's findings (an over-length number or link, a key the order PATCH dropped) are
      // losses the report must count, and the report counts `findings`, not `invoice.findings`.
      for (const finding of invoice.findings || []) findings.push(finding);
      // Remember a READY-but-unrecorded file (bound to its URL); CLEAR the memory once the document
      // is settled or the remembered import is dead. Left in place, a FAILED file id was resumed
      // forever and the document never imported (review finding).
      const settled = ['invoice-preserved', 'invoice-already-preserved', 'invoice-number-only', 'invoice-import-failed'].includes(invoice.outcome);
      try {
        if (invoice.pendingMediaFileId && invoice.pendingMediaFileId !== pendingMediaFileId) {
          await crosswalk.setInvoiceFile(sourceId, invoice.pendingMediaFileId, { sourceUrl: evidence.invoice.sourceUrl || null });
        } else if (settled && (rememberedPending || (invoice.outcome === 'invoice-import-failed' && pendingMediaFileId))) {
          await crosswalk.setInvoiceFile(sourceId, null, { sourceUrl: null });
        }
      } catch (error) {
        errors.crosswalk = errors.crosswalk || describeError(error);
      }
    } catch (error) {
      outcomes.invoice = 'invoice-failed';
      errors.invoice = describeError(error);
    }
  }

  return { orderId, derivedId, outcomes, findings, errors, paymentId, invoice };
}

// A crosswalk over the project's own state/crosswalk/crosswalk.ndjson, in the row shape and key
// convention the rest of the runtime uses (`<sourceSystem>:<sourceEntityType>:<sourceId>`, as in
// lib/import-recovery.js), so recovery tooling sees these rows and these rows see its. Loaded
// once, appended per order (O(1) -- the last row per key wins), so a large store does not rewrite
// its whole crosswalk seven thousand times.
//
// The loader is deliberately NOT lib/local-state's: that one throws on any unparsable line and on
// any invalid row of any entity type, which turns a process killed mid-append -- the crash this
// module exists to survive -- into a run that fails every order after it. Here a TRAILING partial
// line (no newline terminator, not parseable) is dropped and reported; any other bad line still
// throws, because that is corruption, not a crash.
function createProjectOrderCrosswalk({ projectDir, sourceSystem = 'wordpress', sourceEntityType = 'order' } = {}) {
  if (!projectDir) throw new Error('createProjectOrderCrosswalk needs the migration projectDir');
  const filePath = localState.crosswalkPath(projectDir);
  const pendingPath = path.join(path.dirname(filePath), 'pending-invoice-files.ndjson');
  const key = (sourceId) => `${sourceSystem}:${sourceEntityType}:${String(sourceId)}`;
  const index = new Map();
  // Bytes of COMPLETE lines already indexed. The file is append-only, so a refresh reads from here
  // rather than re-parsing seven thousand rows -- and a MISS always refreshes first, because
  // another process (or lib/local-state's upsert) may have appended a row since we last looked.
  // Review demonstrated the alternative: a cached index returning null for a legacy row written
  // moments earlier, and a second order imported.
  let offset = 0;
  let lineCount = 0;
  let loaded = false;
  let inode = null;
  const state = { droppedPartialLine: null, droppedPendingPartialLine: null };

  // The file is append-only for THIS adapter, but lib/local-state's upsertCrosswalkRow rewrites
  // and compacts it (temp file + rename). A rewrite that shrank the file below our offset made the
  // incremental read return nothing and a legacy row stay invisible -- review demonstrated a
  // second order imported that way. So every refresh stats first: a new inode or a smaller file
  // means "start over", not "nothing new".
  async function statFile() {
    try {
      const st = await fs.stat(filePath);
      return { size: st.size, ino: st.ino };
    } catch (error) {
      if (error && error.code === 'ENOENT') return { size: 0, ino: null };
      throw error;
    }
  }

  async function readFrom(position) {
    let handle;
    try {
      handle = await fs.open(filePath, 'r');
    } catch (error) {
      if (error && error.code === 'ENOENT') return '';
      throw error;
    }
    try {
      const { size } = await handle.stat();
      if (size <= position) return '';
      const buffer = Buffer.alloc(size - position);
      await handle.read(buffer, 0, buffer.length, position);
      return buffer;
    } finally {
      await handle.close();
    }
  }

  async function refresh() {
    const st = await statFile();
    if ((inode !== null && st.ino !== inode) || st.size < offset) {
      index.clear();
      offset = 0;
      lineCount = 0;
    }
    inode = st.ino;
    const chunkBuffer = await readFrom(offset);
    if (!chunkBuffer || chunkBuffer.length === 0) return;
    // Split on the BYTE, not the decoded string: a tail torn inside a multibyte character decodes
    // to U+FFFD and mis-measures the bytes to truncate (review demonstrated a glued, fatal file).
    const lastNewline = chunkBuffer.lastIndexOf(0x0a);
    const completeBytes = lastNewline === -1 ? 0 : lastNewline + 1;
    const tailBytes = chunkBuffer.length - completeBytes;
    const parts = completeBytes > 0 ? chunkBuffer.subarray(0, completeBytes).toString('utf8').split('\n') : [''];
    if (completeBytes > 0) parts.pop(); // the trailing '' after the final newline
    const tail = tailBytes > 0 ? chunkBuffer.subarray(completeBytes).toString('utf8') : '';
    for (const raw of parts) {
      lineCount += 1;
      const line = raw.replace(/\r$/, '').trim();
      if (!line) continue;
      let row;
      try {
        row = JSON.parse(line);
      } catch (error) {
        throw new Error(`${filePath}:${lineCount} invalid NDJSON: ${error.message}`);
      }
      if (row && row.targetEntityType === 'ecom/order' && typeof row.sourceStableKey === 'string' && typeof row.targetId === 'string') {
        index.set(row.sourceStableKey, row.targetId);
      }
    }
    offset += completeBytes;
    if (tailBytes > 0 && tail.trim()) {
      // A last line with no newline: either a complete row from a writer that omits the
      // terminator, or a line torn by a kill mid-append. A torn line is TRUNCATED on disk, not just
      // skipped -- skipped, the next append would glue a row onto it and corrupt the file for every
      // later reader (review demonstrated this too).
      let row = null;
      try { row = JSON.parse(tail.trim()); } catch (error) { row = null; }
      if (row) {
        // A complete row another writer left unterminated. Indexed; the terminator is added by
        // set() just before our next append, so the file is never touched only to tidy it.
        lineCount += 1;
        if (row.targetEntityType === 'ecom/order' && typeof row.sourceStableKey === 'string' && typeof row.targetId === 'string') {
          index.set(row.sourceStableKey, row.targetId);
        }
        offset += tailBytes;
        needsTerminator = true;
      } else {
        // Truncate only if nothing has been appended since we read: a neighbour's row landing
        // between the read and the truncate would otherwise be deleted. One process per project
        // crosswalk is the supported model (lib/local-state has a state lock for the runtime); this
        // check narrows the window, it does not close it.
        const now = await statFile();
        if (now.ino === inode && now.size === offset + tailBytes) {
          await fs.truncate(filePath, offset);
          state.droppedPartialLine = { line: lineCount + 1, length: tail.length };
        }
      }
    }
  }
  let needsTerminator = false;

  // The pending-invoice sibling file gets the SAME crash discipline as the main crosswalk. Review
  // demonstrated the alternative: a row torn by a kill, the next append glued onto it, one
  // unparsable line holding two pending file ids, both silently ignored -- and a tax document
  // imported twice. A torn TAIL is truncated on disk; a bad line anywhere else is corruption and
  // throws; a complete row left unterminated is read and terminated before the next append.
  async function readPendingRows() {
    let buffer;
    try {
      buffer = await fs.readFile(pendingPath);
    } catch (error) {
      if (!error || error.code !== 'ENOENT') throw error;
      return { rows: [], needsTerminator: false };
    }
    const lastNewline = buffer.lastIndexOf(0x0a);
    const completeBytes = lastNewline === -1 ? 0 : lastNewline + 1;
    const complete = completeBytes > 0 ? buffer.subarray(0, completeBytes).toString('utf8').split('\n') : [];
    if (complete.length > 0) complete.pop(); // the '' after the final newline
    const rows = [];
    complete.forEach((raw, i) => {
      const line = raw.replace(/\r$/, '').trim();
      if (!line) return;
      try { rows.push(JSON.parse(line)); } catch (error) { throw new Error(`${pendingPath}:${i + 1} invalid NDJSON: ${error.message}`); }
    });
    const tail = buffer.subarray(completeBytes).toString('utf8');
    let pendingNeedsTerminator = false;
    if (tail.trim()) {
      let row = null;
      try { row = JSON.parse(tail.trim()); } catch (error) { row = null; }
      if (row) {
        rows.push(row);
        pendingNeedsTerminator = true;
      } else {
        await fs.truncate(pendingPath, completeBytes);
        state.droppedPendingPartialLine = { line: complete.length + 1, length: tail.length };
      }
    }
    return { rows, needsTerminator: pendingNeedsTerminator };
  }

  async function ensureLoaded() {
    if (!loaded) {
      await refresh();
      loaded = true;
    }
  }

  return {
    async get(sourceId) {
      await ensureLoaded();
      const hit = index.get(key(sourceId));
      if (hit) return hit;
      await refresh();
      return index.get(key(sourceId)) || null;
    },
    async set(sourceId, targetId) {
      await ensureLoaded();
      if (needsTerminator) {
        await fs.appendFile(filePath, '\n', 'utf8');
        needsTerminator = false;
      }
      await localState.appendCrosswalkRow(projectDir, {
        schemaVersion: localState.SCHEMA_VERSION,
        sourceSystem,
        sourceEntityType,
        sourceId: String(sourceId),
        sourceStableKey: key(sourceId),
        targetSystem: 'wix',
        targetEntityType: 'ecom/order',
        targetId: String(targetId),
        status: 'imported',
        updatedAt: new Date().toISOString(),
      });
      index.set(key(sourceId), String(targetId));
      await refresh(); // pick up our own row's bytes (and anything a neighbour appended)
    },
    // A Media file that reached READY but whose order patch failed, remembered per source order so
    // the resume records THAT file rather than importing another. Kept in a sibling file, read in
    // full on every ask: it only ever holds the failures, so it stays small, and a stale in-memory
    // copy here would cost a duplicated tax document.
    async getInvoiceFile(sourceId) {
      const { rows } = await readPendingRows();
      let found = null;
      for (const row of rows) {
        if (row && row.sourceStableKey === key(sourceId)) found = row.fileId ? { fileId: row.fileId, sourceUrl: row.sourceUrl || null } : null; // last row wins; a null row clears
      }
      return found;
    },
    async setInvoiceFile(sourceId, fileId, { sourceUrl = null } = {}) {
      // Repair first: a torn tail is truncated and an unterminated complete row gets its newline,
      // so this append always starts a clean line.
      const { needsTerminator } = await readPendingRows();
      await fs.mkdir(path.dirname(pendingPath), { recursive: true });
      if (needsTerminator) await fs.appendFile(pendingPath, '\n', 'utf8');
      await fs.appendFile(pendingPath, `${JSON.stringify({ sourceStableKey: key(sourceId), fileId: fileId === null ? null : String(fileId), sourceUrl: sourceUrl === null ? null : String(sourceUrl), updatedAt: new Date().toISOString() })}\n`, 'utf8');
    },
    // What the loaders had to drop, if anything -- a caller may want to report it.
    droppedPartialLine() { return state.droppedPartialLine; },
    droppedPendingPartialLine() { return state.droppedPendingPartialLine; },
  };
}

// The attempt-journal row for one importOrderHistory result -- the only place that decides it, so
// a generated runner does not. The order is `imported` exactly when the target holds it (the result
// carries `orderId`), with that id and with every failed payment, refund or invoice stage as a
// retryable finding; a rerun reconciles the order by id and retries only those stages. An order
// that was not created never carries a targetId: `derivedId` is where it WOULD be, not evidence
// that it is, and travels as `failure.intendedTargetId`. Status from the kept error, per
// lib/multi-step-attempt.js.
const LANDED_ORDER_OUTCOMES = new Set([ORDER_OUTCOMES.IMPORTED, ORDER_OUTCOMES.ALREADY_IMPORTED]);
const stageFailed = (outcome) => typeof outcome === 'string' && (outcome.endsWith('-failed') || outcome === 'payment-reconciliation-ambiguous');

function orderHistoryAttempt(result, { sourceStableKey } = {}) {
  if (!result || !result.outcomes || !Object.values(ORDER_OUTCOMES).includes(result.outcomes.order)) {
    throw new Error(`orderHistoryAttempt needs an importOrderHistory result; got order outcome ${JSON.stringify(result && result.outcomes && result.outcomes.order)}`);
  }
  const { outcomes, errors = {} } = result;
  const landed = LANDED_ORDER_OUTCOMES.has(outcomes.order) && Boolean(result.orderId);
  const subSteps = [
    { stage: 'payment', outcome: outcomes.payment, failed: stageFailed(outcomes.payment), error: errors.payment },
    ...(outcomes.refunds || []).map((refund) => ({ stage: 'refund', outcome: refund.outcome, failed: stageFailed(refund.outcome), error: refund.error })),
    { stage: 'invoice', outcome: outcomes.invoice, failed: stageFailed(outcomes.invoice), error: errors.invoice },
    ...(errors.crosswalk ? [{ stage: 'crosswalk', outcome: 'crosswalk-write-failed', failed: true, error: errors.crosswalk }] : []),
    // The placeholder-line order landed, but its cutover item could not be filed.
    ...(errors.cutoverItem ? [{ stage: 'cutover-item', outcome: 'cutover-item-write-failed', failed: true, error: errors.cutoverItem }] : []),
  ].filter((step) => step.outcome);
  const base = landed
    ? { outcome: outcomes.order, targetId: result.orderId }
    // A target read that could not decide stopped before Import Order: nothing was written.
    : { outcome: outcomes.order, intendedTargetId: result.derivedId || null, error: errors.order || null, writeAttempted: outcomes.order !== ORDER_OUTCOMES.TARGET_READ_FAILED };
  return require('../../../lib/multi-step-attempt.js').classifyMultiStepAttempt({
    sourceStableKey, operation: 'importOrder', base, subSteps, findings: result.findings || [],
  });
}

module.exports = {
  ORDER_OUTCOMES,
  PLACEHOLDER_LINE_NAME,
  PLACEHOLDER_GAP_CODE,
  withPlaceholderLineItem,
  orderHistoryAttempt,
  EVIDENCE_KEYS,
  REFUND_KEYS,
  INVOICE_KEYS,
  deriveImportedOrderId,
  normalizeSourceSiteHost,
  assertEvidence,
  checkOrderContactFields,
  identifyRejectedContactFields,
  importOrderHistory,
  createProjectOrderCrosswalk,
};

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an API key, Needs a command-line tool, Needs Node.js

Security

What our scanner noticed· Medium risk

  • Possible data-exfiltration endpoints
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Wix
Publisher
Wix (Official)
Source
wix/skills · skills/wix-replatform/resources/rp-target-wix · commit d168bc2
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Wix.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download rp-target-wix.zip