Imported from wix/skills (
skills/wix-replatform/resources/rp-import-codegen/SKILL.md). Install upstream withnpx skills add wix/skills --skill rp-import-codegen. Copyright stays with the author.
rp-import-codegen
Generate source readers, transforms, setup/import entrypoints, and thin Wix write specs from approved migration artifacts.
The mapping step owns every semantic decision. Implement the recorded operation, transform,
reference policy, custom storage and temporary handling; do not choose an alternative or
invent a missing default. Report the exact unanswered decision/output to mapping and emit
no affected write behavior. A missing helper for a complete decision is implementation work.
Operator-change transforms apply after their base (the suggested transform): affix adds
prefix/suffix to the base result, constant writes value, source-field reads
sourcePath instead, and instruction is plain words you implement exactly, checked by the
row's examples.
Validate generated output against mapper-authored examples before execution.
The field-mapping example runner returns mappingQuestions with the source entity and
exact missing contract elements. Return them to mapping before generating affected writes;
independent complete decisions may still be exercised. Never fill these questions in code.
Vendor lib/operation-assessments.js, lib/setup-producers.js and lib/mapping-recovery.js
with their shared dependencies. Preserve pinned assessment/source/membership evidence and
the mapping gap ledger. The dependency gate and immediate transport check enforce withheld
fields and measured record holds. New mapping decisions use the mapper's
references/knowledge-and-recovery.md contract. Reuse the normal builder-held inventory
for record holds; preserve deferred source/intended dispositions without omission waivers.
One-click deferred field-inventory contract
Before raising a field-inventory review, read orchestration/user-actions/ and
mapping/review/field-inventory-answers.json. An answered request with subject type
mapping_field_inventory_review is durable mapper input: apply it to the mapping authority
and entity projections, then rebuild the scope and gap ledger. Never create another request
for the same canonical entity scope and artifact set. New review requests must use the
mapping-field-inventory-review effect and that answer ledger, and must bind the subject to
the exact entityRefs, execution scope, mappingPlanDigest, and gapLedgerDigest being
reviewed. A changed entity scope or either fingerprint is a new review and must not
supersede an answered request merely because its paths and blocker code match.
In an explicit user one-click run, set-aside field inventories (typed limitation),
deferred entities, reference-only entities, and no-data census rows never block the
execution manifest. Exclude
them from import tasks, retain one evidence-backed Cutover action per entity in the existing
mapping gap/completion artifacts, and generate the manifest for every resolved independent
entity. If every selected entity is deferred, no importer starts and the run ends with the
typed mapping_scope_deferred blocker; mixed scope still continues resolved independent
work. Do not publish an all-deferred completion or fake writes; do not describe deferred
inventory as “cannot generate” and do not re-ask it.
For repairs, generate code only after mapping and approval are revised. Use
mapping-recovery.repair({projectDir,gapId,sourceId,targetId,mappingPlanDigest,outputId, expected,readTarget,writeTarget,verify,runId,taskId,siteId}) for each affected output.
expected comes from the mapped pure builder. The helper obtains the last verified field
state from the source/target-bound attempt journal; before the first repair the withheld
field must still be absent or already match the expected result. Caller-supplied baselines
cannot authorize overwriting an edit.
Use the normal capability-bound, readiness-gated writer for writeTarget and the ordinary
read-back comparison for verify. This helper validates current mapping/source/crosswalk
identity, reads before update, journals before transport and records verified output evidence.
When the update supports a revision/precondition, bind it to the current read; a conflict
keeps the gap open and returns to reconciliation instead of overwriting a concurrent edit.
For a record hold, the ordinary importer handles create/reconciliation first; this helper
only verifies the existing target and never issues another create. Several correction paths
require verified evidence for every path before a record's gap closes. Rebuild completion
and handoff after repair; do not close gaps by deleting projections.
Purpose
This skill turns the schema, mapping, and setup decisions into implementation files under the active migration project.
Required inputs
migrations/<project>/source-schema.jsonmigrations/<project>/mapping/mapping-plan.jsonmigrations/<project>/setup/setup-plan.jsonmigrations/<project>/setup/setup-requirements.jsonwhen setup affects write paths
Prefer the machine-readable artifacts above. Markdown review files are secondary renderings for humans, not the primary codegen contract.
The toolkit already wrote the import scaffold: fill only the hooks
The route script prepared this stage before you started (stagePrepared in its output;
lib/stage-entry.js). For every entity the toolkit writes itself (a composite: products, contacts,
orders, coupons, posts, reviews, tax rates with their regions and default groups; or a fixed send:
categories, tags, brands, media, tax groups, shipping zones with their methods; the list is
execution/codegen-scaffold.json):
src/import/handlers/import-<entity>.jsis written and fixed. It runsrunRecordTaskwithbuildFromPlanon that entity's plan rows. The runner, the plan interpreter, the suggestion helpers and the target knowledge are vendored intosrc/. Name the manifest taskimport-<entity>.src/import/hooks/<entity>.jshas one empty function per plan row the toolkit can't build (instructionandexpressionrows, leftovers). Fill only the code between each hook's>>>and<<<markers.execution/codegen-scaffold.jsonlists the hooks and why each one exists.- WordPress/WooCommerce: the fixed catalog extractor is installed when the toolkit has it.
- The run's startup code is written too (
filesinexecution/codegen-scaffold.json). Do not write it: the import entrypoints and the project adapter (WordPress:src/import/run-import.js,src/import/plugin-handoff.js,src/project/plugin-runtime.jsrunninglib/project-adapter.js), the setup entrypointsrc/setup/run-setup.js, and the empty task for each entity the plan marksinUse: false. A run-specific change to one adapter step goes insrc/project/overrides.js(<step>(...args, toolkitDefault), pluswhy: { <step>: '<reason>' }); each override is recorded as a toolkit gap in the completion report, never a cutover task.
Never edit the handler or a hooks file outside the hook bodies. To change a value, change the plan
row and route again; the scaffold is refreshed and your hook bodies are kept.
import-contract-verify reports a change once (codegen_scaffold_changed); restore it with
node <toolkit>/scripts/codegen-scaffold.js --project <dir> --restore. A change still there on the
next check is replaced by the toolkit's version and becomes an Import Operator cutover task.
If a scaffolded handler fails its own checks for a reason a hook can't fix, you may replace it for
that entity: first run node <toolkit>/scripts/codegen-scaffold.js --project <dir> --release <entity> --reason "<why>". The toolkit then keeps your handler, and import-contract-verify records it as a
toolkit finding (codegen_scaffold_released). Only entities that are not
in the scaffold record keep the flow below.
Dependency readiness contract
Copy lib/dependency-readiness.js, lib/import-task-runner.js, lib/import-task-orchestrator.js,
lib/import-completion.js and their shared dependencies into
the generated runtime (src/lib, with src/resources for rp-target-wix/lib).
Bind the execution manifest to the approved mapping plan with mappingPlanDigest: the same
canonical digest(plan) (lib/mapping-field-contract.js) the importer pins, never a file hash.
Each import task declares canonical entityRefs, the domain knowledge's dependencyRefs,
and matching dependencyEdges. Every edge has exactly one producer: an import task,
all bound setup step IDs, or an approved census disposition. Run validateManifestForProject(projectDir) after writing the candidate manifest; it loads the real census adapter and calls bindDependencyProducers. Validate the complete graph;
missing, unreviewed, multiply bound or cyclic dependencies stop codegen.
The generator (Workflow step 2) writes the fields below for every scaffolded entity; they apply as
written to any task you add or edit. Declare sourceBindings: [{ ref, sourceEntity, keyField, keyPrefix, manifestPath, extractPath }]
on tasks so the runtime can bind source keys to the complete extract and its manifest. Bind every contributing source separately, including multiple census/source populations targeting one ref; the pass records each manifest, extract and declared read plan without overwriting another source. Stamp attempts with the owning task ID and crosswalks with that binding’s source entity and raw source ID. Use the canonical target domain/entity on attempt/crosswalk rows; the gate also recognizes the existing singular, dotted and hyphenated forms for the same ref. A key outside that ref’s current source population, a key from another entity in a combined task, or mismatched evidence identity cannot resolve.
Use dependencySourceBindings for excluded source-key associations. Preserve the reviewed
mapping's census links rather than guessing associations from names. Setup-produced edges
always use task-complete. An edge from an import task is per-record unless target knowledge
sets it to task-complete; an excluded (disposition) edge is per-record only where target
knowledge says so. Never choose a mode by hand: copy what deriveDependencyEdges returns.
Dependencies with no separate producer. Copy lib/dependency-proofs.js with
the readiness library. Also vendor lib/target-import-support.js, lib/config-env.js, lib/wix-auth.js, lib/import-interruption.js, lib/egress-proxy.js and
the selected target knowledge with their relative module layout: reconciliation and the
shared Wix client read them.
Declare writeOperations: { "<entityRef>": "<operation>" } on every
import task whose approved mapping row resolved an operation with a reviewed contract (product
createStoresProduct, member createMember, order importOrder, tax rate
createManualTaxMapping); the contract scopes its
refs (Import Order carries no ecom/shipping-option or ecom/delivery-profile reference) and
its approved dependencyProofs. Do not hand-derive edges: write the tasks, call
deriveDependencyEdges(projectDir, manifest) and copy each task's dependencyRefs,
dependencyEdges and dependsOn, then validate as above. Producers may also be
no-producer (with each proof's operationContractDigest), secondary-output (a member
task's verified contacts satisfying a per-record contact reference when no contact import
exists), child-output (a product task's verified variants satisfying a per-record
stores/product-variant reference; it requires writeOperations on the product task) or
inherited (a transitive ref carried by an intermediate dependency, or a child ref whose parent
has no child producer; never written directly). pending-setup from the mapping preflight must become a real setup step here, unless an import
task in this manifest writes that entity: then the import owns it and no setup step may list it
(setup_step_claims_import_entity). A dependency on an entity the same task writes gets no edge.
A task is never its own producer: validation refuses task_depends_on_self,
dependency_edge_self_producer and task_depends_on_cycle. Regenerate the edges; never hand-edit
dependsOn.
- Payloads must not write a proof's guarded paths; the gate and transport refuse them
(
dependency-proof-contradicted). - Order line variants (Stores Catalog V3): write
catalogReference.options.variantIdfromlookups.ref('stores/product-variant', variantKey, 'lineItems[i].catalogReference.options.variantId')besidecatalogItemIdfromlookups.ref('stores/product', productKey, ...)on the same line.variantKeyis the exactsourceKeythe product import used for that variant expectation. The gate reads it from the product's verified receipt and refuses a variant of another product (dependency-identity-pair-mismatch); an unready or unknown variant defers the order. A variation absent from the complete source variation extract requests no variant reference: keep the product link, SKU and description lines. - Order buyers and guest buyers are the runner's (the order and contact composites). It resolves
the member link with
resolveOrderBuyerthrough the gate, creates one contact per guest buyer (guestBuyerContactRows, keyed byguestBuyerContactKey; a guest whose email matches an imported customer shares that customer's contact) and fills a guest order'sbuyerInfo.contactId. Inbuild, fillbuyerInfo.contactIdonly for a registered customer (lookups.ref('crm/contact', …)), leave it out for a guest, and never setbuyerInfo.memberId. FillbillingInfo.contactDetailsfromorder-buyer.jsorderBuyerContact(order)(billing, else shipping, else the email alone). Hold only on{ held: true, reason: 'order-buyer-contact-missing' }; never hold a guest order because its billing block is empty. The guest buyer binding on the contact task follows the order'sguest-buyerschoice: the manifest generator adds{ ref: 'crm/contact', sourceEntity: 'guest-buyer-contact', role: 'derived-guest-buyer-contact', keyField: 'id', manifestPath, extractPath }only forimport-as-contacts(the default);email-onlysends the order with the email alone, andnot-importedholds each guest order (guest-buyer-not-imported, the order builder). Never add or remove that binding by hand; change the plan choice. The toolkit writes the key prefix of both derived roles (DERIVED_KEY_PREFIXESinlib/execution-manifest.js) and refuses any other value. - Member contacts: after Create Member, call
verifyMemberContactIdentity(wix, { memberId, contactId, siteId, outcome })and record itsidentityin the member crosswalk row'ssecondaryIdentities(keepoutcome: "unknown"unless evidence distinguishes new from matched). - Product media from URLs: never resend the landed product. Observe with
observeStoresProductMediaIngest(wix, { productId, expectedItems, initialProduct }), passing the sent{ url, altText, displayName }items: it verifies each intended item (a matching count, a wrong image or a duplicated media ID does not verify). Policy is pinned: one initial read plus at most four, 15s apart, 60s window. Start observations concurrently; do not hold a worker or request slot per product while it waits. Record anunresolved/unverifiableresult withrecordWithinWriteGap({ grant, taskBinding, sourceStableKey, ref: "media/media-file", targetId, code, observation }); clear it withresolved: trueand a laterverifiedobservation for the same target and items. Only observations the writer returned are accepted as evidence, and the observer only judges unmodified Wix responses for that product and site: pass the create response (or a read) itself asinitialProduct, never a copy or a cached object. Gap records are serialized per project and stay recordable with the grant that admitted the write. - A member-produced contact and a member ID on the same order must belong to the same member;
the gate and transport refuse a mixed pair (
dependency-identity-pair-mismatch). - Product media ids: the
media/media-fileedge is per-record. Resolve eachmedia.itemsInfo.items[n].idwithresolveReference, placing each resolved id at the next free index; never read media ids from the crosswalk (an id the gate did not resolve counts only when it is exactly one ready media record's target; otherwise the gate drops it and records it). A product never waits for an image: one that is not ready yet, held, or failed resolves toundefined(dependencyFailureActions: omit); skip it. The gate records each pair inexecution/dependency-readiness.jsonomittedReferences(pending,held, or the reason it cannot land). Media patch pass, after the media task's last wave and again after any media--failed-only: callomittedReady({ taskBinding }); gate each listed product again with its full gallery; sendpatchStoresProductMediaVerified(recordClient, { productId, items }); when it returnslanded: true, callrecordOmissionsResolved({ grant, taskBinding, sourceStableKey, readBack: result.product, targetId: productId }). Rows still open for a landed product becomedependency-omitted-after-failurecutover items, except where the entity declaresdependencyFailureCutoverItems(the site share image): its writer already reports the gap as that cutover item, so no media patch pass runs for it. - Interleave per-record producers with their dependents (media and products): vendor
lib/dependency-waves.jsand callplanDependencyWaves({ dependents: [{ sourceStableKey, needs }], producerKeys, waveSize }). For each wave, write itsproducerKeysthrough the producer task, then itsdependentKeysthrough the dependent task; media no product names come last. CallfinishTaskPassfor each task once, after its last wave (a full pass that finished in this run is final for readiness). Then resume the dependent task's deferred records once. Products sending URL galleries name no media (needs: []) and start at once. On a fixture of about 400 products and 1,000 media files, products finish in about half the time with media ids, and in about a tenth with URL galleries.
Every import task builds on the site's regional setup step: evaluateTask holds a money-bearing or wall-clock
task (stores, ecom, gift cards, pricing plans, bookings, events) whose currency or time zone was kept, is unknown
or spans several base currencies, as a blocked site/locale row. Nothing extra is needed in generated
code: skip a held task, never retry it in the same run, and let the others proceed. Never create a write client
for a held task.
Use approved excluded dependencies as disposition producers, without generating an import
task for a missing writer. Product tag edges use the declared per-record mode and exact
tags.publicTags.tagIds[] reference path. Preserve the approved source membership and use
resolveReference for populated tag references, including excluded tags: its approved omit
rule returns no ID and the payload must omit that path. Never pass an undefined array item,
invent an ID, remove the manifest edge, or turn a held tag task into a completed task. Products
whose complete source record has no tags need no tag lookup; unknown or incomplete source
evidence is not an empty tag population. Keep the exact mapping gap and missing behavior in
the existing completion and Migration review handoff after supported product writes.
Per-record tasks: generated code supplies build only (required)
Every import task runs through lib/import-task-runner.js runRecordTask. Generated code is
the operator's choices and nothing else.
build(record, lookups): comes from the plan. Uselib/plan-builder.jsbuildFromPlan(entityPlan), which applies everyfieldMappings[]row whose transform is a known kind, plusvaluePolicyand the excluded dispositions. Codegen writes hooks only forinstructionrows and leftover rows: one named, pure function per row, whichbuildFromPlancalls. For a composite entity the toolkit scaffold already wrote the handler and the empty hook slots (see "The toolkit already wrote the import scaffold"); fill only the hook bodies. Never hand-write a whole builder for an entity the plan covers. The result is the gate payload, or the decided hold{ status: 'held', holds: [{ decisionId, code }] }, or{ deferred: true, reason }to decline with a named reason (areferenceGapscutover item). A code that means "the plan writes nothing for this record" must be one the plan row declares (ahold-recordcodein itsvaluePolicy); never invent one. A missing rule goes back to mapping. Take every target id fromlookups.ref(ref, sourceStableKey, path). The runner picks the lookup mode from the task's manifest edge, so never callresolveReference,resolveTaskReference,resolveSetupReferenceorresolveSameTaskReferenceyourself. Use concrete indexed paths for repeated fields. A missing id comes backundefined: leave the field out, and the gate defers or holds the record. Data the runner's steps need that is not part of the Wix body goes inloopInput. The runner removes it before the gate.send(recordClient, payload, record): only for a ref with no toolkit composite. It is the reviewed writer call and returns{ targetId, revision?, findings?, crosswalkExtra? }.reconcile(recordClient, payload, record): only where the target can be searched and the runner has no reader. It returns{ targetId }for exactly one match,nullfor none, andundefinedwhen it cannot tell.update(recordClient, { targetId, patch, fields }): where the target has an update call. After a plan change, the runner sends only the changed fields (patch) to records already imported. Without it, those records are listed as aplan-update-not-appliedcutover task.
Composites. For these refs the runner sends through the toolkit composite and its follow-up
steps. A send for them is refused at run time, and import-contract-verify refuses generated
code that calls the composite or its writers directly:
| Ref | build returns |
The runner runs |
|---|---|---|
stores/product |
{ product, categoryIds?, loopInput: { variantKeys?, stock, pictureSourceIds, seo?, selectionRoute?, modifiers? } } |
importProducts (create, variants, verify, SEO) → picture guard → category attach → stock |
crm/contact |
{ contact } |
importContacts, one bulk call per batch; guest-buyer and guest-review contacts (binding roles derived-guest-buyer-contact, derived-guest-review-contact) need no build |
ecom/order |
{ order, loopInput: { evidence } } |
currency check → shipping check → importOrderHistory (derived id, payment, refunds, invoice) |
- Product: a Stores V3 body with
slug(required),variantsInfo.variants[],tags.publicTags.tagIds[i]fromlookups.ref('stores/product-tag', key, 'tags.publicTags.tagIds[i]')andmedia.itemsInfo.items[].categoryIds[i]comes fromlookups.ref('stores/category', key, 'categoryIds[i]').loopInput.variantKeysholds one source key per built variant, in variant order: the source variation's own stable key (<variationKeyPrefix><variation id>). For a single variant, leave it out; the runner uses<productSourceKey>#default. Order lines look variants up by this key, so never derive it from an array position.loopInput.stockis{ slug, variants: [{ choices: [{ optionName, choiceName }], inventoryTracked, inventoryQuantity | inStock }] }(sendquantityorinStock, never both).loopInput.pictureSourceIdsholds one source media id per media item. - Order:
lineItems[i].catalogReference.catalogItemIdcomes fromlookups.ref('stores/product', …),.options.variantIdfromlookups.ref('stores/product-variant', …), and, for a registered customer,buyerInfo.contactIdfromlookups.ref('crm/contact', …)(the runner fills a guest's).loopInput.evidenceis described under "Order history".
Pass childExtracts so the runner joins child rows before build. For WooCommerce variations that
is [{ extractPath: 'data/source-extract/product-variation.ndjson', parentField: 'parent_id', as: '_variations' }], which gives record._variations. Pass sourceSiteHost for orders.
// Vendored with the shared runtime, like dependency-readiness.js.
const { runRecordTask } = require('../lib/import-task-runner.js');
const result = await runRecordTask({ taskBinding, wix: taskClient, sourceSystem: 'woocommerce',
build: (record, lookups) => buildStoresCategory(record, lookups).category,
send: async (recordClient, category) => ({ targetId: (await writers.createStoresCategory(recordClient, category)).id }) });
The runner does the rest the same way for every store:
- it skips records already crosswalked, and resumes a landed record whose follow-up steps did not finish (the composite finds it again, so nothing is created twice);
- it evaluates and gates each batch, defers decided holds, and binds each record client;
- it orders a same-entity tree parents first, and fills the parent id (see "Same-entity hierarchies");
- it writes a terminal journal row for every record, through the shared partial-failure rule
(
lib/multi-step-attempt.js). A landed base with a failed step isimported, with a retryable finding and animport-step-incompletecutover item; - it writes the crosswalk and calls
finishTaskPass.
Don't write any of this yourself. That means no startImportRun or bindTask in task code, no
evaluateTask, gateBatch, appendAttempt, runGatedEntity or finishTaskPass, no retry
loop, and no catch that only logs or drops an error. Let build and send throw: the runner
journals the failure, and it reaches the completion report and a cutover task.
import-contract-verify lists each violation in codegenFindings, with file and line. Fix them
before import. A finding never refuses the import; unfixed, it becomes an Import Operator
cutover item.
Task orchestration and complete accounting: call the shared helpers (required)
Vendor lib/import-task-orchestrator.js, stamp taskOrchestration: "shared-v1" in the generated
execution manifest and descriptor, and invoke runImportTasks for the manifest's import tasks. It
runs tasks in stable topological waves and invokes every task that is not prevented by a
stop/interruption latch. A failed task never terminates the loop, and dependsOn is not a reason to
skip a sibling or to skip the dependent task wholesale. The dependent task still runs through its
normal readiness gate: only records whose own required parent cannot land are deferred; records
with no such reference and every independent task continue. Do not emit a generated
break/return/task-level "has dependents" branch after a failed result.
After dispatch, vendor lib/import-completion.js and call buildImportCompletenessRows once for
the current runId, then pass its rows through attachAttemptReasons before
createCompletionReport. The helper reads each mapped task's source keys and the latest current-run
journal outcome, so every mapped entity has a row even when the task was never reached. A missing
current-run row is skipped_unexpected (not-attempted); a readiness row remains deferred until a
later terminal row supersedes it. Source-archive-only bindings are preservation output and do not
become mapped-entity rows. Each entity the plan defers (executionScope.deferredEntities) gets its
own row from the same call (target ref, source entity as subtype), every extracted record deferred
as mapping-scope-deferred; do not add a row or task for it in generated code. Never construct completion rows only from the array of attempted task
results, and never use zero for a task that was not dispatched.
The shared per-record runner records a parsed errorBody (or raw body when parsing failed) on each
non-2xx failure row. Composite and bulk writers must preserve the same response body when they
convert a target error into an attempt row; a fixed message such as write failed is not enough
for QA or recovery classification.
Old path only: a task the runner does not run yet (coupons, posts, members, plugin
entities) wires the gate itself until it moves to the runner. Import the gate's startImportRun, bindTask, evaluateTask, gateBatch and
finishTaskPass. For EAV extracts, source bindings additionally name the existing project-relative readPlanPath; the gate reuses the shipped EAV completeness and file-digest validator rather than treating a missing snapshot total as empty. Create one import run, bind each task, and create its Wix client from the
returned capability. Immediately before every batch, including each selective/resume
path, evaluate the task and pass the source-keyed records through gateBatch.
Each gateBatch input is { sourceStableKey, transform: async ({ resolveReference, resolveTaskReference, resolveSetupReference }) => payload } (or { sourceStableKey, payload } when it needs no target references). Transforms receive resolveReference(ref, sourceStableKey, path) for per-record edges and resolveTaskReference(ref, sourceStableKey, path) for task-complete import edges after a complete or finished-partial current producer pass (empty producers cannot resolve a key). A finished partial producer releases unrelated records; only a record naming a parent that cannot land ends dependency-parent-final without a write and becomes a cutover task. A producer whose only missing keys are approved builder holds is complete-with-holds, and a reference to a held key follows the same per-record final/hold handling. They also receive resolveSetupReference(ref, sourceStableKey, path) after setup passes, and resolveSameTaskReference(ref, sourceStableKey, path) for a parent the same task writes (see "Same-entity hierarchies"). They do not read a crosswalk or choose target IDs themselves. Use concrete indexed paths for repeated order fields. Send only
the returned send payloads, with each request's sourceStableKey and that batch's
readinessGrant. Use writers.bindRecordClient(taskClient, { readinessGrant: grant, sourceStableKey }) for existing writer composites, or writers.withReadinessGrant(request, { readinessGrant: grant, sourceStableKey }) for individual builders. These retain trusted read/auxiliary marks. A valid grant never authorizes a raw or altered writer request; object-spreading a marked request loses its authority. Principal payloads still match every resolved reference. Closed product patch builders bind the current record’s product and compare references under each changed top-level field; omitted fields retain the existing product state. Only the closed media/payment/extended-field auxiliary builders omit those principal paths.
The gate appends its own deferred attempt rows; do not append a duplicate deferred outcome. The runner appends started and terminal rows for attempted sends and persists confirmed crosswalks through the shared writers. Call finishTaskPass with the actual selection mode only after the pass finishes. Selective
work never establishes a full/empty pass. The append-only state/readiness/task-passes.ndjson
is evidence; execution/dependency-readiness.json is a diagnostic projection, not authority. Prerequisite deferrals remain current recovery work after admission, started, uncertain outcomes or failed retries. Only a current-site confirmed imported/skipped_already_imported outcome for the same task/key clears that lineage; admission is not completion. The runtime updates this task-scoped recovery index from journal deltas, and completion uses the same reducer.
--describe must include dependencyReadiness.tasks with each task's ID and exact
{ ref, mode } edges. Run import-contract-verify against the manifest; it also refuses an
emitted edge mode that differs from current domain knowledge (dependency_edge_mode_mismatch), so
a stale manifest/descriptor pair is regenerated, never matched to itself. One exception keeps
shipped manifests valid: an emitted task-complete edge that target knowledge lists in
legacyTaskCompleteEdges (it became per-record later; it waits for more, never less) is
accepted and checked as it was when emitted. Generated importers
must obtain capabilities only through the dependency gate: no setup/quick/probe issuer,
caller-supplied phase, raw request escape, or direct execution-capability import. Site reconciliation uses reconcileSiteEvidence({ taskBinding, readBack }); reuse the existing unresolved-write reader/comparison against the recorded write. The callback returns { result, matchesRecordedWrite } with the actual unchanged marked-read response from this site's registered client; a boolean or hand-built response never restamps evidence. Tasks with
no dependencies still require their task capability and batch grant. Keep the existing
read-back gate below: readiness does not replace write verification or authorize resends.
Adopt-only tasks (mapping writeMode: "adopt-only-no-writes")
When the approved mapping adopts what a quick pass already created (kind: "adopt-existing",
writeMode: "adopt-only-no-writes", e.g. products and categories after a quick pass), emit a task
for that ref with adoptOnly: true. It reads and verifies; it never writes (the writer refuses
ADOPT_ONLY_TASK_WRITE_REFUSED), so it declares no write-only dependencies: dependencyRefs and
dependencyEdges are empty and no producer is needed for brand, product customization, tags or
media. A task depending on it names the adopted ref and stops there. The flag is honoured only
when the mapping plan marks every ref of the task adopt-only; otherwise validation reports
dependency_adopt_only_unapproved:<task> and the creating-task rules apply. The reverse is
refused too: a task owning a ref the plan marks adopt-only but emitted without the flag fails
with dependency_adopt_only_unmarked:<task>, so emit the flag for every such task. A target
whose rows mix adopt-only and creating modes fails with dependency_adopt_only_mixed. The mapper
preflight, deriveDependencyEdges and the runtime gate read the same plan rows through one
resolver, so they draw the same edges. Never set the flag to skip a dependency of a task that
creates records.
Declare its sourceBindings as usual with keyPrefix <sourceEntity>: and a keyField whose
value is the plain source id (a gid is lib/crosswalk-adoption.js normalizeSourceId's id tail).
The importer's first step seeds the standard crosswalk from the quick crosswalk, either by
node skills/wix-replatform/scripts/crosswalk-adopt.js --project-dir <project> (add --dry-run
to only count) or by calling adoptCrosswalk from the vendored lib/crosswalk-adoption.js
with deriveBindings(projectDir, { contract }). It appends the missing rows, never overwrites,
and reports conflicts (a different existing target, one Wix id claimed by two source ids) without
writing them; membership and tag sections are not seeded. A seeded row is a claim, not a result:
the task then reads each adopted record by id (slug marker for products), appends the
skipped_already_imported attempt row for the keys that match, and leaves the rest unready and
reported. Variant ids are not in the quick crosswalk; read them from the Wix product when a
dependent task builds its payload.
Generated read-back gate contract
Builder-only step (before mapping approval). When rp-mapper asks for it, generate only
the pure buildWrite(record) module (for example src/import/build-write.<entity>.cjs) from
the draft decisions' transforms: record in, request body out. Generate no reader, setup or
import executor, descriptor, manifest, Wix client, capability, network or file write in this
step; read-back-gate.js inventory refuses a builder that references them, and
import-contract-verify refuses a project with no generated importer. The live importer is
generated only after the named approval.
The builder, like every generated transform, never reads crosswalks, local-state or
data/source-extract; references come through gate-owned resolvers. The readiness scan skips
only the file's header comment (before any code), so put provenance notes naming the source file
there; a comment after code is scanned as text like the code around it.
The builder must honor each output's appliesWhen exactly. Write the output when the predicate
holds on the source record and its sources are populated. Leave it out entirely when the
predicate is false: no placeholder, empty object or default value. An empty array such as
default-variant choices: [] counts as absent. Never infer applicability from lookup cases
prose. If the decided transform needs a condition that no appliesWhen states, return it to
rp-mapper. validate reports Builder omits an applicable output / Builder emits a non-applicable output with the output and record count. The gate refuses such a canary before
writing (builder-missing-intended-field / builder-emitted-inapplicable-field), and refuses to
compare such a sample.
Never emit a reference the target knowledge lists in dependencyReferenceFields (the gate fills
it in: order buyerInfo.contactId, line-item catalogReference.catalogItemId /
options.variantId, product tags.publicTags.tagIds[]) or auxiliaryReferenceFields (a
post-create step writes it: product category membership). The builder is not asked for them, and
the canary refuses one it emits (builder-emitted-gate-supplied-field).
A record the decided transform cannot write is held, not written partially: return
{ status: 'held', holds: [{ decisionId, code }], … } with one named reason per hold (a hold
without a reason is refused, builder_hold_invalid; decisionId must be a decision of that
entity in the plan, builder_hold_unknown_decision). inventory keeps the held record in source
coverage, lists it with its reasons (records[].held, heldRecords) and leaves it out of output
applicability and the canary universe; the held set is part of the inventory digest, so approval
binds it. The read-back gate refuses a held body (builder-held-record). The dependency gate
defers a held payload as builder-held with its decisionId:code reasons and never sends it.
runRecordTask relies on that, so generated code neither catches nor re-journals holds.
For order, member, contact and product, reuse that reviewed pure buildWrite(record)
module unchanged (the read-back inventory pins its SHA-256; a change makes it stale) and the
entity decision's copied readBackContract. Generate no new omission policy or
comparison rules. Each mapping row retains its exact sourcePaths[], canonical writePath and
readPath or unverifiableReason, with fieldDispositions[].mappingRef pointing to that row.
Copy the bundled read-back libraries with the shared runtime; importing a CLI must not execute
an extract or write. Other entities call declaration(entity, { verificationKind, reason })
from lib/read-back-gate.js and retain that explicit coverage declaration in their manifest.
verificationKind is one of contact, product or none (VERIFICATION_KINDS in
lib/entity-verification.js). Members, orders and other entities with their own verification
flow declare none. The completion report refuses any other value at the end of the import;
import-contract-verify refuses the same values at codegen, with the file and line. The manifest
validator and the declaration do not check the value.
Persist it with recordDeclaration(projectDir, runId, entity, { verificationKind, reason })
from lib/read-back-summary.js; the existing gate artifact then supplies completion and CLI
coverage reporting. A non-gated declaration never replaces gated-domain or earlier gate evidence.
Write every gated entity (order, member, contact, product: an entity decision with a
readBackContract) through runGatedEntity from lib/read-back-gate.js. Do not
construct ReadBackGate or call prepare, executeCanaries, verifySample or
reconcileInterval yourself; import-contract-verify warns (never refuses) when no generated code
calls runGatedEntity.
const { runGatedEntity } = require(path.join(toolkitRoot, 'lib/read-back-gate.js'));
const gate = await runGatedEntity({
projectDir, runId, siteId, wix, entity: 'product', records, // source records, any order
buildWrite, // the reviewed pure builder, unchanged
write: async (record, expected) => …, // one record: the confirmed write, or { deferred: true, reason }
writeBatch: async batch => …, // optional bulk writer: [{ sourceId, targetId, findings }]
sourceKeyOf: id => `product:${id}`, // the journal's sourceStableKey for a source id
marker, variants, read, lookup, repair, sourceSiteHost, // entity options, as before
});
// gate.status: 'passed', or the gate's stop status; gate.written: the writeBatch/write outcomes.
runGatedEntity is the shared write wrapper: while it invokes write or writeBatch, it
tracks non-read calls through the supplied wix.send. If a generated writer throws before any
mutating request is sent, the wrapper annotates an otherwise-unclassified error with
requestSent: false before the gate handles it. Throw the original coded error (for example
REFERENCE_UNDECLARED) and do not guess or overwrite requestSent; an exception after a
mutating send remains uncertain and must retain the gate's read-back protection.
The toolkit runs the read-back check at codegen, not you: the scaffold writes a pure builder per
gated plan row (src/import/read-back/build-<entity>.js), and before codegen is done the route
builds and validates each row's inventory (read_back_invalid names the rows and errors; a row with
no builder or binding is not-checked). Fix a builder finding in the row's hooks or plan; return a
mapping finding to rp-mapper. If a row still fails after two passes, the run does not stop: the
toolkit records it as a toolkit gap (a field left unmigrated is a cutover task), stops gating that
row, and the import writes it through the ordinary write path (route_settled event).
It loads execution/read-back-inventory/<entity>.json, prepares the gate, reconciles a suspect
interval carried from an earlier run, and settles a canary an earlier run sent that the target
rejected with a readable 4xx (written again, never looked up as uncertain). It then runs the
canaries and writes the remaining records in stable source order, in batches of at most 200. It
samples every 200th and the last landed record, and a failed sample stops new batches until
reconcileInterval clears it. A missing inventory or a failed preparation stops the entity
before any write. An inventory that is only stale (the builder or extract changed after it was
taken) is rebuilt by the gate from the builder, extract, source key and format it recorded, then
validated as usual; vendor lib/read-back-inventory.js with the gate. Any other validation finding
stops the entity and the operator action sends the named findings back to codegen. The write callback returns the confirmed write, or exactly
{ deferred: true, reason } when it declines before sending anything (for example, gateBatch
deferred the record), with no other keys. Never return a deferral after a request may have been
sent; a deferral that carries an id or any other key is treated as a possible write. The gate
records a deferral as not sent, stops with canary-write-deferred, and writes the record again
on the next resume.
The inventory is built by the streaming scripts/read-back-gate.js inventory command using the
same builder; a missing extract means the check was not run. Validation requires the reviewed
mapping, decision, resolution and inventory bindings. Missing, stale or incomplete field
accounting holds the entity. Populated omissions require the existing identified mapping
approval user action, including all four current references; 1-click cannot approve them.
The deterministic canary schedule covers every populated intended write path, with a default
ceiling of ten records; raising it to at most thirty requires the recorded user decision.
Only records eligible for writing are in that schedule: a record with a recorded builder hold is
retained in the inventory and cutover report but is never selected or reused as a canary. Canaries
run serially. A failed read-back or a definite refusal stops later writes, but an uncertain
write (unknown-write-no-match, unknown-write-outcome or a missing confirmed target ID) is
retained as one record-only cutover task and the other canaries and records continue. This applies
to single and bulk non-canary writes as well: each affected source record is protected separately;
later records and batches continue. That record remains protected and is never resent automatically;
a later resume reads it back again. A run that sends no write for a gated entity records
not-run-no-writes; it adds no new stop when an earlier run holds that entity's gate result.
Pass the loaded write-verification state to completion instead of carrying each writer's report:
createCompletionReport({ …, verificationState: await require(path.join(toolkitRoot, 'lib/write-verification-state.js')).load(projectDir, siteId) }). A verification[entity] the
caller passes still takes precedence.
An uncertain send is reconciled through the gate's existing identity lookup before any retry.
Every lookup page and by-ID read must use the gate's budgeted read proxy (reads.wix), including
product catalog sweeps and contact candidate reads; a failed or truncated lookup is unknown,
never permission to send again. A product read hook that joins variant stock (Get Product V3
returns none) calls storesInventory.resolveInventoryLocation(wix) and readInventory(wix, …)
with the wix it is given; Query Inventory Items and its location query are registered bounded
reads. Preserve the gate and write-verification evidence across
resumes. Never rewrite an imported order. Contact, product and member repairs use the gate's
single-attempt-per-contract rule, unchanged revision marker and existing update path; a member
repair writes its contact with that contact's current revision. Never overwrite a record edited
since import.
When ensureMember removes a phone through its approved phone-collision guard, compare against
the request actually sent and preserve the writer's guard-dropped paths in the gate summary.
Canaries record it automatically. For bulk writes, return each record's findings array from
writeBatch (or write); runGatedEntity passes it to the gate, which persists only the
recognized collision finding. Samples and reconcileInterval then exempt only that record's
guarded phone path. A missing target phone is never treated as a guard.
Do not turn that guard into notMigrated, an observed Wix loss or a fabricated placeholder
phone. Pending product-media processing is unknown until bounded settlement resolves; it cannot
be classified as a permanent dropped field or used to approve an omission. A media item has
landed when it carries its own id: image.id, or video.id with mediaType: VIDEO
(storesProductMediaItemLanded); a landed video is never re-sent.
Product videos. When execution/product-videos.json has attach[] rows, the
product task attaches them after the product's verified create, under that record's grant:
writers.attachStoresProductVideos(wix, { productId, videos }), with videos from
lib/product-videos.js videosWithRecordedFiles(projectDir, row) (Wix Media import as VIDEO, wait
for READY, then the file id after the kept images; a gallery that has not settled is deferred; a
re-run skips videos already on the product and never imports a recorded file twice). Record every result with lib/product-videos.js
recordProductVideoOutcome(projectDir, { productSourceId, productId, result }); the completion
report derives product-video-not-attached and product-video-manual from the plan and those
outcomes. Never author those actions yourself, and never send a video as a { url } image item.
Never author read-back-* operator actions (a generated recordStop pushing
read-back-sample-failed into memory): writeCompletionReport drops every caller action whose
code starts with read-back- and derives them from execution/read-back-gate.json, which
verifySample/stop() already persist. A stopped run reaches that writer through the shared
interruption wrapper (see "Stops and interruption" below).
Completion must retain execution/read-back-gate.json. Call the existing completion-report
writer so its read-back producer supplies actual per-entity statuses, path counts, pending
settlements, observed losses, approved omissions and merchant acknowledgements, plus recovery
operator actions. Do not infer a pass from a successful HTTP write or emit a separate success
summary. A held, not-run or unknown gate keeps the run incomplete, and missing acknowledgement
for an approved omission remains a pre-launch task. The toolkit creates that acknowledgement
request itself; a large approved set is listed in a sha256-pinned
execution/review/read-back-omissions-<entity>-<requestId>.json that the bounded prompt points
to, so never shorten, rebuild or re-create the request in project code. A later run's prepare takes over another
run's unprepared entry (the completion gate-not-run placeholder); only its own verification
clears it. Held records stay in readBack and the read-back-held-records operator action.
Source read contract
Generating a correct reader requires platform-specific knowledge — auth model,
pagination, rate limits, and REST quirks. That knowledge lives in the matching source
adapter skill, not here, so this skill never names a platform. Resolve the adapter from
the platform field in source-schema.json via the naming convention rp-source-<platform>
(e.g. platform: "wordpress" → rp-source-wordpress) and read its "Read contract"
section. The operational facts should already be recorded in source-profile.md; use the
adapter to fill any gaps rather than guessing. rp-execute-import runs the reader you
generate and stays platform-agnostic — so the platform specifics must be baked into this
generated code, not deferred to execution.
Adding a new source platform therefore requires no change to this skill: a new
rp-source-<platform> adapter is enough.
Reading plugin-provided entities
Entities that came from a source plugin carry extra sourceMeta the generated reader must
respect. These are read mechanics, not mapping decisions:
origin: "embedded"— the records live inside a property of a parent record (propertyPath) on an already-fetched route (embeddedIn). Extract them from the parent fetch. Do not issue a second request per parent; some of these plugins have no route of their own at all.requiresParent— a sub-collection route parameterized by the parent id (.../{id}/notes). Read the parent first and iterate; order this after the parent entity in the dependency graph.channel: "plugin-rest-child"— a sub-resource on a CORE collection this plugin does not itself profile (e.g. WooCommerce orders), so it cannot userequiresParent(which points at another entity declared in the same profile).routecarries a{parentId}template (/wc/v3/orders/{parentId}/notes);parentRoutenames the collection route to iterate for real parent ids. Unlike discovery'ssampleChildEntities(which checks only a representative few parents), the generated reader must iterate every parent record fromparentRouteand fetch its child route — that full iteration is what actually migrates the data; the discovery-time sample only confirmed the shape is real.context— when the adapter says view and edit contexts return different data, request the one the entity declares. Requesting only one context can silently halve the result set.- Per-plugin credentials — some plugin APIs use their own key system rather than the platform credential. Load them from project-local config like any other secret, and fail loudly with the missing key name rather than falling back to unauthenticated reads.
recognized: false(derived entity) — no plugin-specific read contract exists; read it as an ordinarywp/v2-style collection using the shared transport. Do not invent plugin-specific handling for it.requestMethod/requestBody— the entity's real read path is not a plain GET collection; it is a declared non-GET method with a JSON body template. The generated reader must issue that exact method/body, not fall back to a GET.- A body value of the form
"$SAMPLED_IDS:<route>"names another route whose record count is UNKNOWN and possibly unbounded (e.g. an entire product catalog) — never resolve it against one fixed id list fetched in a single request, at discovery time or at execution time, because<route>may hold far more ids than fit in one page or one request body. The generated reader must instead: (1) paginate<route>to exhaustion (every page, not a capped sample); (2) split the collected ids into bounded batches (mirrorlib/sampled-ids-batch.js's default of 50 ids per batch — do not send an unbounded id list in one request); (3) issue one request per batch against this entity's own route, with the placeholder resolved to just that batch's ids; (4) normalize each batch's RAW, unmodified response (envelope resolution, thenresponseFragmentGroupSizereassembly below — never pre-coerce a non-array raw response to an empty list before normalizing it, since an enveloped response is legitimately an object, not an array, until unwrapped) and merge the batches, deduplicating byrecordKeyField(defaultid) — the same record can otherwise appear once per batch it happened to match; (5) stop and record the run as an explicit failure/deferred outcome on the first page or batch that cannot be read OR whose normalized result is not a valid array shape (a batch that doesn't match the declared envelope/fragment contract must defer the whole entity, not be counted as a legitimate empty batch — that would produce an exact-looking but false zero) — never emit a partial/undercounted or falsely-exact result as if it were complete.rp-source-wordpress/lib/sampled-ids-batch.jsimplements this exact algorithm (collectAllIds,queryInBatches) forwp-discovery.jsitself; a generated reader for another platform must reproduce the same five steps, not invent a different policy.
- A body value of the form
responseFragmentGroupSize— the response arrives as N separate flat single-key array entries per logical record instead of one object (a plugin bug some source APIs have). The generated reader must chunk the raw array into groups of N and merge each group withObject.assigninto one record before any mapping/transform runs or any count is emitted — per batch when combined with a$SAMPLED_IDSrequestBody above, mirroringwp-discovery.js'sinspectEntity/normalizeResponseRecordshandling of the same field.
structure-bridge-plugin entities (channel: "db-only")
New bound entities use the project-local plan contract in
rp-source-wordpress/PLUGIN-READ-PLANS.md. Carry sourceMeta.extractionPlan literally
from canonical discovery through mapping. A profile is optional; absent/invalid plans
remain typed deferrals. Never suffix physical table names or guess artifact filenames.
The codegen scaffold already wrote the plugin handoff (src/import/plugin-handoff.js, the
importer/extractor entrypoints) and the project adapter (src/project/plugin-runtime.js); do not
write or replace them.
Run the committed import-contract-verify.js with the intended selection before any
source/target I/O. The wrappers enforce preparation/full readiness and selected source
prerequisites; discovery samples are preview only. Keep unrelated native reruns available.
Include plan/evidence/assembly/extractor/helper inputs in existing freshness metadata.
Legacy caller compatibility follows below. New discovery emits bindings for profiled entities too; it does not add a wrapping pass for old sidecars. Existing legacy readers retain their signature, pagination and complete-identity behavior. Do not use the legacy filename convention below as a fallback for a new selected entity with a missing binding.
An entity whose blocked[].fulfillment.kind is structure-bridge-plugin has no REST
route at all — its declared readiness (self-test passing, checked via
blocked-data-handlers.js at planning time, per rp-mapper) means it is safe to treat
as a normal candidate target, but its generated reader is genuinely different from every
other reader this skill generates: it reads through wix-wp-plugin-v2's /query or
/query/admin-key route, not the platform adapter's own transport. This is not
resolved through blocked-data-requests.js's one-shot attemptFulfillment()/snapshot
mechanism the way csv-upload is — that mechanism exists for a small, static,
human-provided document; a structure-bridge-plugin table is a live, potentially large,
paginated dataset, so it gets a normal incremental reader like any REST entity, just
reading from a different transport.
- Vendor
rp-source-wordpress/lib/wix-wp-plugin-v2-client.jsintosrc/lib/, the same way an ordinary WordPress reader vendorswp-http.js. Do not re-implementdiscoverStructure()/queryStructure()or their response validation. - Vendor
rp-source-wordpress/lib/structure-bridge-reader.jsbeside it and callextractStructureBridgeEntity({ dataDir, entity, table, transport, expectEav })once per entity. Do not hand-write the page loop, checkpoint, reconciliation or manifest. It implements every rule below for both variants (single request and EAV read plan) and is covered bytests/source-wordpress/structure-bridge-plugin-generated-reader-test.js.transportis{ httpClient, siteBaseUrl, auth, onSourceRead }built from the credential rule below; setexpectEav: truewhen the entity's discovery markdown reports aneavPair. It returns rather than throws:statusispromoted,reusedordeferred(withcodeandreasons), plusbestEffortandredactions. Continue with the other entities after adeferredone. Each deferral is also written todata/source-extract/<entity>.deferred.json(reason, affected rows, resumable files, prerequisites, resolution check and a Copy prompt for Import Operator); a later promotion marks itresolved. At completion, spreaddeferredExtractionReportInput(await collectDeferredExtractions(dataDir))into thecreateCompletionReport()input (merge itsoperatorActionsandstatuseswith the importer's own), so the deferral reaches the handoff as a Requires Import Operator action. Passrestart: trueonly when the record saysrestartRequired. It never promotes an EAV read whose plan hasdroppedIdentityColumns, and never setsacknowledgedDroppedColumns(complete identity). The rest of this section is the contract
Truncated - read the full file at https://github.com/wix/skills/blob/HEAD/skills/wix-replatform/resources/rp-import-codegen/SKILL.md.
