Generated banner for Wix Replatform
Generated logo for Wix Replatform

Wix Replatform

WixOfficialPublished by Wix

  • Skill
  • Workflow
  • Automation and integrations
  • MIT
  • Low risk
  • Has scripts

From the author

Routes RePlatform source-to-Wix migrations to the next required workflow module by inspecting authoritative migration artifacts. Use when starting, resuming, or recovering a migration run.
— the description by Wix

AutoGineer summary

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

wix-replatform acts as a central supervisor for migrating data and content to Wix. It does not perform migration tasks directly but instead inspects migration artifacts to determine the next required stage in the pipeline. By maintaining a deterministic state, it ensures that migrations can be started, resumed, or recovered reliably without duplicating work or creating redundant destination sites. It manages the flow through various phases including discovery, mapping, setup, and import, while enforcing strict validation and approval gates.

What it does

  • Routes migration tasks to appropriate sub-modules based on current project state.
  • Ensures resumability by tracking migration progress through authoritative artifacts.
  • Enforces mandatory approval gates before performing write operations.
  • Dispatches specialized subagents for specific tasks to maintain context boundaries.
  • Validates artifacts at each stage to prevent proceeding with corrupted or stale data.
  • Handles reruns for incremental data updates without re-scaffolding the entire project.

When to use it

  • When initiating a new migration from an external source to a Wix site.
  • When resuming a migration that was interrupted or stopped.
  • When recovering from a failed migration stage by addressing specific errors.
  • When performing incremental imports to sync new or modified records after an initial migration.

Advantages

  • Prevents data duplication by enforcing idempotent write operations.
  • Maintains a clear audit trail through structured telemetry and completion reports.
  • Reduces risk by requiring explicit approvals before critical setup or import steps.
  • Supports both standard interactive flows and automated 1-click execution modes.

Usage examples

“Start a new migration for my project in ./migrations/my-store.”
The agent resolves the project directory, initializes orchestration artifacts, and routes to the project intake module.
“Resume the migration in ./migrations/my-store.”
The agent inspects the existing artifacts, determines the last completed stage, and dispatches the next required module.

Install

  1. Download the skill as a ZIP:

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

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

Documentation by Wix

wix-replatform

wix-replatform is the compact supervisor for a resumable source-to-Wix migration. It selects one internal module for the active stage; it does not carry every stage procedure in its own context.

Always-active contract

  • Resolve the active project under migrations/<project>/ (or REPLATFORM_MIGRATIONS_DIR) before inspecting or creating anything. Only that project's artifacts are authoritative.

  • Preserve EXPECTATIONS.md at that project root. It is the user's free-form record of how they expected the run to behave; initialization creates it once and never overwrites it.

  • Start/resume resources/rp-telemetry/ at the beginning of every run and finalize it at a terminal state. Never hand-write telemetry events.

  • Use orchestration JSON plus validated stage artifacts as resume authority. Logs and chat history are diagnostic context only.

  • Preserve user data: write idempotently, dedupe by source identity, resume rather than restart, and never create a second destination site for a migration.

  • Never print secrets, secret-bearing config contents, tokens, or credentials. Report only key names and present/blank/missing status.

  • Do not declare a migration complete from prose or a single artifact. The deterministic router and aggregate completion artifact own terminal completion.

  • Preserve the owner's cutover handoff: unresolved data, applicable manual setup, missing apps and changed plugin behavior. Reconcile discovery, mapping decisions, setup receipts and final outcomes; imported records alone do not establish working functionality. The producing resources own this guidance and durable completion/handoff artifacts. Use a supported cutover publisher when available; report missing publication integration explicitly rather than claiming the application received local artifacts.

CLI-launched runs and human actions

When a migration is started through replatform, the terminal is deliberately non-interactive: do not use an agent question UI, ask for stdin, or wait for a person in the current agent turn. The runner owns process lifecycle and emits only observed events; it does not replace this skill's router or completion receipts.

When a human choice, review, approval, or manual prerequisite is needed, create a durable request with node skills/wix-replatform/scripts/user-action.js create --project <projectDir> --request-file <request.json>, then end the turn. Put only reviewed artifact paths in the request. The person can later use replatform requests, replatform show, and replatform answer; a resumed agent reads the answered request from orchestration/user-actions/, never from reconstructed chat context.

Cancellation is not completion. If the runner has recorded cancel_requested, canceled, interrupted or an explicit stop (blocked, transition --status blocked --resume-from '<json>'; routes run_blocked until explicit resume or --status running, never answer --continue), preserve partial/recovery artifacts and let a later explicit replatform resume route recovery. Never create aggregate migration completion from an aborted execution report.

Pipeline

intake → destination → source inputs → preflight → (standard: discovery → mapping → codegen;
quick: adapter preflight → quick plan) → setup discovery → website handoff
→ safety review/approval → setup → import
→ storefront continuation (website only) → aggregate finalization → Migration review

Delivery modes are management (backend only), website (frontend only), and management_and_website (the integrated flow above). Accept user input both as management_and_website and persist the canonical value.

For deliveryMode=management, aggregate finalization requires valid backend import accounting. For deliveryMode=management_and_website, it additionally requires a current website/completion.json with completed screenshot review, no unresolved critical/high gaps, and release evidence. execution/completion-report.json is backend accounting, never website-migration completion by itself.

Route before acting

On every new or resumed turn:

  1. Resolve the project and initialize/load its orchestration artifacts.

  2. Run node skills/wix-replatform/scripts/orchestration-route.js <projectDir>.

  3. Dispatch the nextResource to a Developer subagent instead of loading and following it yourself. Give it the project directory and the resource to run; it follows that resource's contract exactly as written, unchanged. Read back only its result — never its transcript, tool output, or logs.

    • Every dispatch (Developer or QA) is a fresh subagent, never a resumed one; pass only a handoff file and stay within a context budget — follow resources/rp-subagent-dispatch/. Never read state/attempts/write-attempts.ndjson raw; use scripts/write-log-summary.js.

    • A Developer may fan out to sub-subagents only for harmless read-only work with no shared state, and only if the host supports it; writes stay one at a time, as each resource says.

  4. Dispatch a QA subagent to check the Developer's result against that resource's own stated required outputs (its own "artifacts to create or update" or "## Output" section, and any review/gap documents it defines). QA is read-only — it never writes or calls Wix. If something's missing, dispatch a new Developer for the same resource with QA's findings; otherwise the stage is done.

  5. At the end of each pipeline phase (discovery, mapping, setup discovery, import, and so on — see the pipeline above; a phase spans several resource-level stages), dispatch a QA subagent to review that phase's documents as a whole (for example mapping/review/mapping-summary.md and mapping-gaps.json, or execution/completion-report.json) before routing to the next phase. This catches anything a single per-task check could miss. For the import phase specifically, this review must be entity-by-entity against the accepted mapping plan, not a skim of the top-level status string — see rp-execute-import's "Entity-by-entity QA" section. Any run-fixing dispatch mid-phase (a crash fix, a slowness fix, a resumed pass) does not itself satisfy this; run the phase-level QA again once the fix lands, since fixing one entity's defect certifies nothing about its neighbors. Mapping QA also checks exact source coverage, decided operation/path semantics and canonical projections. Codegen QA reads the Developer's independently expected synthetic request evidence and its freshness; it does not execute examples. Semantic defects return to mapper, implementation defects to codegen. One-click tests defer unresolved scope and finish independent work with a typed incomplete result, without questions or repeated redispatch; customer runs retain their existing checkpoints.

  6. Route again after every stage boundary. Stale requests use resources/rp-user-action-recovery/; unreadable request artifacts block until repaired. Never discard pending requests or decide the next stage from memory.

The router (lib/orchestration-router.js) is the only routing and resume authority. It recomputes the route from decisions, approvals, preflight, run.json status and the phase outputs on every call; run.json.currentState is diagnostic only, never a routing input.

  • A recorded rejection stops the route in every mode, one-click included: execution_approval_rejected is blocked before any setup or import write, and mapping_approval_rejected returns to rp-mapper for a new plan.

  • A gated output that exists but is unusable (source_schema_invalid, mapping_plan_invalid, setup_plan_invalid, setup_requirements_invalid, execution_manifest_invalid) is blocked with errors and the producer as nextResource. Do not re-run the producer automatically; report the errors to the Import Operator and stop.

  • The import routes (missing_completion_report, import_interrupted = a stopped run's aborted report, quick_mode_import_required) carry importProgress. interrupted lists recoveryArtifacts: resume it, never a second import. interruptedReport: "missing": first run scripts/interrupted-completion-report.js.

If an artifact is malformed, partial, stale, or fails its validator, treat its producing stage as incomplete and route to the producer. Do not make parallel replacement artifacts.

A user action whose reviewed artifacts changed after it was created is refused with user_action_stale and stays pending. Create a new request from the current artifacts.

Catching up a finished migration is a rerun, not a new project. When the user asks to pull in records that arrived or changed since the import — "the source kept selling", "these orders are missing", "re-run it" — reuse the same project, destination, mapping, generated importer and crosswalk, and route to rp-execute-import → "Rerunning an import for new and modified records". Do not scaffold a second project or re-approve an unchanged mapping; a mapping or scope change does go back through the existing gates. A rerun's revision conflicts are user decisions even in 1-click mode.

Demand-loaded module map

Router situationDispatch
project, delivery mode, source mode, or grouped intake is unresolvedresources/rp-project-intake/
destination is absent, conflicting, or needs creation/adoptionresources/rp-destination/
source URL/files/config/acquisition mode/credentials are required, including source credentials said to exist already on another siteresources/rp-source-inputs/
deterministic preflight is missing, repaired, or blocked on CLI checksresources/rp-preflight/
quick mode needs platform resolution, endpoint preflight, plan, extraction, or importselected resources/rp-quick-<platform>/
source schema is missingresources/rp-discovery/ and its selected source adapter
mapping is missing or needs reviewresources/rp-mapper/
Wix requirements are missingresources/rp-setup-discovery/
import code/review is missing or staleresources/rp-import-codegen/
setup verification is missingresources/rp-execute-setup/
backend completion report is missingresources/rp-execute-import/
frontend-only work, or integrated website handoff/build/gap loop/release receipt is incompleteresources/rp-website-continuation/
aggregate completion is missingresources/rp-execution-policy/
aggregate completion exists but the local review publication or current recap is missingresources/rp-migration-review/

The resource named by the route is the complete stage contract, dispatched as described in "Route before acting" — the main session itself never loads it directly. Only the dispatched Developer loads source-file, secret, scaffolding, or storefront procedures, and only for the stage that actually needs them; nothing about a stage where they're irrelevant is loaded, by the main session or the Developer.

Interaction policy

Normal mode asks only for a missing required input, a genuinely ambiguous active project, or a mandatory write approval. Ask one question at a time unless a module says otherwise.

When the user says add to expectations: <note> (or an unambiguous natural-language equivalent), append the note to the active project's EXPECTATIONS.md before continuing. Use scripts/expectations-ledger.js so the entry retains the supplied statement plus safe current context (stage/state, relevant project-relative artifacts, and known entity/field labels). Do not treat this as approval or silently change a mapping. Never record secrets, tokens, raw customer data, or raw source records; redact them if supplied and say so.

Before writes, preserve the mandatory execution-plan approval gate. Read-only discovery, mapping, setup verification, code generation, and review happen before it.

Quick management import mode

When managementImportMode=quick, select the platform adapter only after the deterministic source probe identifies a compatible platform. Quick mode is a bounded public-data import: the adapter's versioned quick-mode.json owns its source routes, entity graph, field matrix, and exclusions. Do not run agentic discovery, mapping, or project-specific code generation for the quick backend branch. Still run destination setup, application installation, Catalog-V3 and notification safety checks, execution approval, shared write runtime, crosswalks, and completion accounting. If no adapter qualifies, persist the unsupported-mode result and ask the user to select standard mode; never silently fall back.

Halt only for missing/invalid required input, a manual action with no API, or a systemic failure/data-loss risk. A halt must persist the code, evidence, owner, and exact unblock action; never silently stop.

1-click mode

When explicitly requested by the user, record automationMode=one_click with source=user and apply the following. A missing mode or a one_click value recorded as deterministic_inference/prior_artifact is normal interactive mode and must not skip a checkpoint:

  • collect all still-missing intake values in one grouped request; then do not pause for routine approvals;

  • record mapping and execution approvals as approved, decidedBy=agent; skipping a pause without state is invalid;

  • for CSV/file-only runs, validate and accept the required sample preview as the agent; without explicit user-authored one-click, pause for the normal mapping review, sample preview validation, and execution approval;

  • default to a new isolated site unless an existing destination is explicitly supplied or already pinned, but never default the new site's type (Headless, Studio or Harmony): ask it in the grouped intake; choose website scope deterministically from discovered route families;

  • retry PATH/tool-resolution failures under the operator's compatible interactive login shell; request required browser/network sandbox escalation and retry before calling it blocked;

  • retry the obvious recovery before stopping: aligned shell first for PATH/tool failures, then the required escalation retry for sandboxed browser or network/API failures;

  • continue through the complete selected deliverable. In management_and_website mode that includes frontend build, post-build gap analysis, bounded fix loop, and release receipt; when the user selected facelift at intake, it also includes the separate post-clone facelift review;

  • before yielding, re-route. A 1-click run is only completed with completion/migration-completion.json, or blocked with a typed durable blocker.

Use the operator's compatible local Node/Yarn shell when recovering from a PATH or tool resolution failure. Machine-specific shell paths belong only in local, git-excluded agent instructions.

Repo-local interactive shell contract: a PATH/tool-resolution failure on first attempt may mean the command ran under a plain, non-interactive shell that never sourced the operator's Node/Yarn profile. Resolve the operator's compatible login shell from the local environment or git-excluded agent instructions, verify that it is executable, and retry the exact same command through that shell in interactive login mode so the profile that resolves node/yarn/npx loads. Do not hardcode a machine-specific shell path in this public skill. Only escalate to a durable blocker if the compatible-shell retry itself fails.

Guardrails

  • Never bypass a validator, approval-state update, verified notification mute, or Catalog-V3 gate to make a stage appear finished.

  • website means frontend only; management_and_website means the integrated backend and frontend migration. Never hand the integrated migration destination to the frontend skill or create a second frontend site in that mode.

  • A Studio or Harmony destination (targetSiteType) is created and verified by rp-destination's coordinator and is never published, unpublished or handed to wix-headless-replatform; its website and publication remain operator handoff items.

  • Do not implement a storefront manually when wix-headless-replatform is unavailable; persist a blocker with the exact required runtime capability.

  • In management mode, still generate website/handoff.* after setup discovery so a later storefront can start without repeating backend discovery.

Files

lib/catalog-baseline.js

'use strict';

// The Wix Stores catalog that existed on the destination before this run's import wrote anything.
// Installing Wix Stores adds sample products and categories that no Wix marker
// identifies, so they are told apart by provenance only: ids that appear between the setup step's
// read just before the install and its reads just after it are `install_seeded`. Everything a run
// finds on a store it did not install is `pre_existing`. Names, dates and revisions are never used.
//
// Setup deletes `install_seeded` items on a site this run created (owner decision 2026-10-26). Every item still present --
// pre-existing, or seeded but not deleted -- is *protected*: no importer may take it over by slug
// or marker, and counts report it apart from what the run wrote.

const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');

const BASELINE_PATH = 'setup/destination-catalog-baseline.json';
const COLLISIONS_PATH = 'execution/target-baseline-collisions.json';
const STORES_APP_DEF_ID = '215238eb-22a5-4c36-9e7b-e7c08025e04e';
const COLLISION_CODE = 'TARGET_BASELINE_COLLISION';
const NOT_DELETED_CODE = 'STORES_INSTALL_SEEDED_NOT_DELETED';
const PRE_EXISTING_CODE = 'STORES_PRE_EXISTING_CATALOG';
const ENTITY = { products: 'stores/product', categories: 'stores/category' };

// Wix may add the samples a moment after the install call returns: read until two consecutive
// reads hold the same ids, at least SETTLE_MIN_READS times.
const SETTLE_MIN_READS = 3;
const SETTLE_MAX_READS = 10;
const SETTLE_DELAY_MS = 3000;

const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const ids = (items) => items.map((item) => item.id).sort();
const sameIds = (a, b) => JSON.stringify(ids(a.products)) === JSON.stringify(ids(b.products)) && JSON.stringify(ids(a.categories)) === JSON.stringify(ids(b.categories));

async function readCatalog(wix, writers) {
  const products = await writers.queryAllStoresProducts(wix);
  const categories = await writers.queryAllStoresCategories(wix);
  const slim = (item) => ({ id: item.id, slug: item.slug ?? null });
  return { products: products.filter((item) => item && item.id).map(slim), categories: categories.filter((item) => item && item.id).map(slim) };
}

async function settledCatalog(wix, writers, { sleep = pause, delayMs = SETTLE_DELAY_MS } = {}) {
  let previous = null;
  for (let read = 1; read <= SETTLE_MAX_READS; read += 1) {
    if (read > 1) await sleep(delayMs);
    const current = await readCatalog(wix, writers);
    if (previous && read >= SETTLE_MIN_READS && sameIds(previous, current)) return { catalog: current, reads: read, settled: true };
    previous = current;
  }
  return { catalog: previous, reads: SETTLE_MAX_READS, settled: false };
}

function rows(items, kind, reason = null) {
  return items.map((item) => ({ id: item.id, slug: item.slug, kind, status: 'present', ...(reason ? { reason } : {}) }));
}

// Deletes exactly the seeded rows, products first (a category delete leaves its products), then
// reads the catalog again: an id still listed is `delete_failed`, whatever the delete call said.
// The built-in All Products category appears with the store, so the diff calls it seeded; it is
// Wix's own category, never a sample.
async function markBuiltInCategory(baseline, wix, writers) {
  let allProductsId = null;
  try { allProductsId = await writers.getAllProductsCategoryId(wix); } catch { /* fall back to the canonical slug below */ }
  for (const row of baseline.categories) {
    if (row.kind === 'install_seeded' && (row.id === allProductsId || row.slug === 'all-products')) Object.assign(row, { kind: 'pre_existing', reason: 'built_in_all_products_category' });
  }
}

async function clearSeeded(baseline, wix, writers) {
  for (const [collection, build] of [['products', writers.buildDeleteInstallSeededProductRequest], ['categories', writers.buildDeleteInstallSeededCategoryRequest]]) {
    for (const row of baseline[collection].filter((item) => item.kind === 'install_seeded' && item.status !== 'deleted')) {
      delete row.deleteError;
      try { await wix.send(build(row.id)); } catch (error) { row.deleteError = String(error.message || error).slice(0, 200); }
    }
  }
  const after = await readCatalog(wix, writers);
  const appeared = { products: [], categories: [] };
  for (const collection of ['products', 'categories']) {
    const present = new Set(after[collection].map((item) => item.id));
    for (const row of baseline[collection].filter((item) => item.kind === 'install_seeded')) row.status = present.has(row.id) ? 'delete_failed' : 'deleted';
    const known = new Set(baseline[collection].map((row) => row.id));
    appeared[collection] = after[collection].filter((item) => !known.has(item.id));
  }
  baseline.verifiedAt = new Date().toISOString();
  return appeared;
}

// Each collection is read on its own, so a failed category read never discards a product read
// that succeeded. A collection whose read failed is `null`: unknown, never empty.
async function readBefore(wix, writers) {
  const before = { products: null, categories: null };
  for (const [collection, read] of [['products', writers.queryAllStoresProducts], ['categories', writers.queryAllStoresCategories]]) {
    try { before[collection] = (await read(wix)).filter((item) => item && item.id).map((item) => ({ id: item.id, slug: item.slug ?? null })); } catch { /* unknown */ }
  }
  return before;
}

function notSettled(baseline) {
  return Object.assign(new Error('The Stores catalog kept changing after the install, so setup cannot tell which items the install added'), {
    blockerCode: 'CATALOG_NOT_SETTLED',
    recommendedAction: 'Re-run setup in a few minutes. It reads the catalog again and finishes the record; import cannot start until it does.',
    baseline,
  });
}

// Classify a settled post-install catalog against the pre-install ids. `preInstall` is already
// resolved (see captureAroundInstall): a collection that is `null` there is unknown, so every item
// of it is `pre_existing`. Known rows -- the pre-install items and anything an earlier attempt
// recorded -- keep their record, listed or not.
function classify(catalog, preInstall, known = { products: [], categories: [] }) {
  const out = {};
  for (const collection of ['products', 'categories']) {
    const before = preInstall[collection];
    const kept = new Map(known[collection].map((row) => [row.id, row]));
    out[collection] = catalog[collection].map((item) => {
      const row = kept.get(item.id);
      if (row) return row.status === 'deleted' ? { ...row, status: 'present' } : row;
      if (before === null) return { id: item.id, slug: item.slug, kind: 'pre_existing', status: 'present', reason: 'pre_install_catalog_unreadable' };
      return { id: item.id, slug: item.slug, kind: before.some((old) => old.id === item.id) ? 'pre_existing' : 'install_seeded', status: 'present' };
    });
    for (const row of known[collection]) if (!out[collection].some((item) => item.id === row.id)) out[collection].push(row);
  }
  return out;
}

// Deletes happen only on a site this run created, on the first install of Stores there. On any
// other site, or when Stores is installed again after an earlier setup, Stores may bring back an
// earlier catalog -- the owner's or this run's own import -- and that looks exactly like samples.
const mayDelete = (baseline) => baseline.siteOrigin === 'created' && !baseline.reinstall;

// Deletes, when allowed, then persists. The record is written BEFORE any delete call, so a crash
// or a failed verification read never loses which items the install added.
// `detectNew` only while the install is still being recorded (import cannot have run yet): on a later
// re-run, new ids are this run's own import and must never be read as samples.
async function finish(projectDir, baseline, wix, writers, { detectNew = true } = {}) {
  if (baseline.categories.some((row) => row.kind === 'install_seeded')) await markBuiltInCategory(baseline, wix, writers);
  const seeded = baseline.products.concat(baseline.categories).filter((row) => row.kind === 'install_seeded' && row.status !== 'deleted');
  if (!mayDelete(baseline)) for (const row of seeded) row.reason = baseline.reinstall ? 'reinstall_not_deleted' : 'existing_site_not_deleted';
  writeBaseline(projectDir, baseline);
  if (!seeded.length || !mayDelete(baseline)) return;
  const appeared = await clearSeeded(baseline, wix, writers);
  let changed = false;
  if (detectNew) {
    // Something new showed up while deleting: record it as seeded and stop; the re-run finishes.
    // A collection whose pre-install read is unknown never yields seeded items.
    for (const collection of ['products', 'categories']) for (const item of appeared[collection]) {
      const unknown = baseline.preInstall?.[collection] == null;
      baseline[collection].push({ id: item.id, slug: item.slug, kind: unknown ? 'pre_existing' : 'install_seeded', status: 'present', reason: unknown ? 'pre_install_catalog_unreadable' : 'appeared_during_cleanup' });
      if (!unknown) changed = true;
    }
  }
  if (changed) {
    baseline.settled = false;
    writeBaseline(projectDir, baseline);
    throw notSettled(baseline);
  }
  writeBaseline(projectDir, baseline);
}

// The Stores install step. Returns the baseline it wrote. `installed` says whether Stores was
// listed before this step; `install` performs and verifies the install.
async function captureAroundInstall({ projectDir, wix, writers, installed, install, siteOrigin, sleep, delayMs }) {
  const prior = loadBaseline(projectDir);
  if (installed && prior) {
    // A re-run of setup keeps the first run's record: anything added since may be this run's own
    // import. An unsettled record (the install ran but was not fully recorded) is read again and
    // finished; seeded items an earlier delete missed are tried again.
    if (prior.settled === false) {
      const { catalog, reads, settled } = await settledCatalog(wix, writers, { sleep, delayMs });
      const next = { ...prior, phase: 'installed', ...classify(catalog, prior.preInstall || { products: null, categories: null }, prior), postInstallReads: reads, settled };
      if (!settled) { writeBaseline(projectDir, next); throw notSettled(next); }
      await finish(projectDir, next, wix, writers);
      return { baseline: next, unchanged: false };
    }
    if (!mayDelete(prior) || !prior.products.concat(prior.categories).some((row) => row.kind === 'install_seeded' && row.status !== 'deleted')) return { baseline: prior, unchanged: true };
    await finish(projectDir, prior, wix, writers, { detectNew: false });
    return { baseline: prior, unchanged: false };
  }
  const header = { schemaVersion: 1, appDefId: STORES_APP_DEF_ID, siteOrigin, storesInstalledBeforeRun: installed, startedAt: new Date().toISOString() };
  if (installed) {
    const catalog = await readCatalog(wix, writers);
    const baseline = { ...header, products: rows(catalog.products, 'pre_existing', 'stores_installed_before_run'), categories: rows(catalog.categories, 'pre_existing', 'stores_installed_before_run'), settled: true };
    writeBaseline(projectDir, baseline);
    return { baseline, unchanged: false };
  }
  // A prior record whose install completed means Stores was removed and is being installed again.
  const reinstall = Boolean(prior && (prior.reinstall || prior.phase !== 'pre_install'));
  const read = await readBefore(wix, writers);
  // An unreadable collection counts as empty only on the first setup of a site this run created
  // (no store there yet, so nothing to lose); otherwise it stays unknown. A retry of an install that
  // never completed reuses the first attempt's pre-install read.
  const preInstall = {};
  for (const collection of ['products', 'categories']) {
    const retried = reinstall ? undefined : prior?.preInstall?.[collection];
    preInstall[collection] = read[collection] ?? retried ?? (siteOrigin === 'created' && !prior ? [] : null);
  }
  const known = { products: [...(prior?.products || [])], categories: [...(prior?.categories || [])] };
  for (const collection of ['products', 'categories']) {
    for (const row of rows(preInstall[collection] || [], 'pre_existing', 'pre_install')) if (!known[collection].some((old) => old.id === row.id)) known[collection].push(row);
  }
  // Recorded before the install call: if a read after it fails, the retry still knows the
  // pre-install ids and classifies against them instead of calling the samples pre-existing.
  const baseline = { ...header, ...(reinstall ? { reinstall: true } : {}), preInstall, ...known, phase: 'pre_install', settled: false };
  writeBaseline(projectDir, baseline);
  await install();
  baseline.phase = 'installed';
  writeBaseline(projectDir, baseline);
  const { catalog, reads, settled } = await settledCatalog(wix, writers, { sleep, delayMs });
  Object.assign(baseline, classify(catalog, preInstall, known), { postInstallReads: reads, settled });
  // Still changing after every read: record what is known and stop before deleting anything.
  if (!settled) { writeBaseline(projectDir, baseline); throw notSettled(baseline); }
  await finish(projectDir, baseline, wix, writers);
  return { baseline, unchanged: false };
}

function writeBaseline(projectDir, baseline) {
  const file = path.join(projectDir, BASELINE_PATH);
  fs.mkdirSync(path.dirname(file), { recursive: true });
  const tmp = `${file}.${crypto.randomUUID()}.tmp`;
  fs.writeFileSync(tmp, `${JSON.stringify(baseline, null, 2)}\n`);
  fs.renameSync(tmp, file);
}

// Missing means "no baseline recorded" (a run that never installed Stores through setup). A file
// that exists but cannot be read fails: treating it as absent would unprotect every item in it.
function loadBaseline(projectDir) {
  let bytes;
  try { bytes = fs.readFileSync(path.join(projectDir, BASELINE_PATH), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
  const baseline = JSON.parse(bytes);
  if (baseline?.schemaVersion !== 1 || !Array.isArray(baseline.products) || !Array.isArray(baseline.categories)) throw new Error(`${BASELINE_PATH} is not a valid catalog baseline`);
  return baseline;
}

function digest(projectDir) {
  try { return crypto.createHash('sha256').update(fs.readFileSync(path.join(projectDir, BASELINE_PATH))).digest('hex'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
}

const stillPresent = (row) => row.status !== 'deleted';

// Ids no importer may take over: every baseline item still on the site.
function protectedIds(projectDir) {
  const baseline = loadBaseline(projectDir);
  const pick = (collection) => new Set((baseline?.[collection] || []).filter(stillPresent).map((row) => row.id));
  return { products: pick('products'), categories: pick('categories') };
}

// Seeded ids only: the "is the site in use" probe ignores these, so a seeded item a delete missed
// never reads as merchant data.
function installSeededIds(projectDir) {
  const baseline = loadBaseline(projectDir);
  return new Set((baseline?.products || []).filter((row) => row.kind === 'install_seeded').map((row) => row.id));
}

function summarize(baseline) {
  if (!baseline) return null;
  const count = (collection, test) => baseline[collection].filter(test).length;
  const block = (collection) => ({
    installSeeded: count(collection, (row) => row.kind === 'install_seeded'),
    deleted: count(collection, (row) => row.kind === 'install_seeded' && row.status === 'deleted'),
    deleteFailed: count(collection, (row) => row.kind === 'install_seeded' && row.status === 'delete_failed'),
    preExisting: count(collection, (row) => row.kind === 'pre_existing'),
    protected: count(collection, stillPresent),
  });
  return { products: block('products'), categories: block('categories') };
}

// Split a catalog read into the items an importer may match and the protected ones.
function partition(items, protectedSet) {
  const open = [], held = [];
  for (const item of items || []) (item && protectedSet.has(item.id) ? held : open).push(item);
  return { open, held };
}

function collisionError(entity, targetId) {
  return Object.assign(new Error(`${COLLISION_CODE}: ${entity} ${targetId} was on the destination before this import; it is neither taken over nor duplicated`), { code: COLLISION_CODE, targetId });
}

// Durable record of every held collision, read by the completion report. One row per entity and
// exact source key; a re-run updates it in place. Each writer clears only the keys it records
// (the read-back gate uses its own `read-back:<entity>:<id>` keys).
const sameRecord = (row, entity, sourceKey) => row.entity === entity && row.sourceKey === String(sourceKey);

function recordCollision(projectDir, { entity, sourceKey, targetId, slug = null }) {
  const file = path.join(projectDir, COLLISIONS_PATH);
  let doc = { schemaVersion: 1, collisions: [] };
  try { doc = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
  doc.collisions = (doc.collisions || []).filter((row) => !sameRecord(row, entity, sourceKey));
  doc.collisions.push({ entity, sourceKey: String(sourceKey), targetId, slug, recordedAt: new Date().toISOString() });
  fs.mkdirSync(path.dirname(file), { recursive: true });
  const tmp = `${file}.${crypto.randomUUID()}.tmp`;
  fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`);
  fs.renameSync(tmp, file);
}

// A held record that later imports and verifies is no longer a collision.
function clearCollision(projectDir, entity, sourceKey) {
  const file = path.join(projectDir, COLLISIONS_PATH);
  let doc;
  try { doc = JSON.parse(fs.readFileSync(file, 'utf8')); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
  const kept = (doc.collisions || []).filter((row) => !sameRecord(row, entity, sourceKey));
  if (kept.length === (doc.collisions || []).length) return;
  doc.collisions = kept;
  const tmp = `${file}.${crypto.randomUUID()}.tmp`;
  fs.writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`);
  fs.renameSync(tmp, file);
}

function loadCollisions(projectDir) {
  try { return JSON.parse(fs.readFileSync(path.join(projectDir, COLLISIONS_PATH), 'utf8')).collisions || []; } catch (error) { if (error.code === 'ENOENT') return []; throw error; }
}

// Completion-report rows: the cutover items this feature owns, plus the `destinationBaseline` block.
function reportRows(projectDir) {
  const baseline = loadBaseline(projectDir);
  // Only collisions whose blocking item is still on the site are open; once setup deleted it, the
  // record imports on the next run and the import's own accounting covers it.
  const held = protectedIds(projectDir);
  const collisions = loadCollisions(projectDir).filter((row) => (row.entity === ENTITY.categories ? held.categories : held.products).has(row.targetId));
  const operatorActions = [];
  if (baseline) {
    const failed = [...baseline.products, ...baseline.categories].filter((row) => row.kind === 'install_seeded' && row.status !== 'deleted');
    if (failed.length) {
      const why = failed.some((row) => row.status === 'delete_failed') ? 'that setup could not delete' : 'that setup left in place because this run did not create the site or Stores was installed again (check each is a sample, not an earlier product of the owner or of this import)';
      operatorActions.push({
        actionId: 'catalog-baseline:seeded-not-deleted', code: NOT_DELETED_CODE, severity: 'high', role: 'cutover-operator', entity: 'stores/product',
        action: `Cutover Operator: in Business Manager > Store Products (and Categories), delete the ${failed.length} item(s) that appeared when Wix Stores was installed and ${why} (ids in affectedIds).`,
        deadlineReason: 'before switching traffic; customers would see sample products', affectedCount: failed.length, affectedIds: failed.map((row) => row.id),
        artifactRefs: [BASELINE_PATH], resolutionEvidence: 'A catalog read no longer lists these ids.',
      });
    }
    const pre = baseline.products.filter((row) => row.kind === 'pre_existing');
    if (pre.length) {
      operatorActions.push({
        actionId: 'catalog-baseline:pre-existing', code: PRE_EXISTING_CODE, severity: 'low', role: 'site-owner', entity: 'stores/product',
        action: `Site owner: ${pre.length} product(s) were on the store before this migration. RePlatform did not change or delete them; keep or remove them as you choose.`,
        deadlineReason: 'information only; review before go-live', affectedCount: pre.length, affectedIds: pre.map((row) => row.id), artifactRefs: [BASELINE_PATH],
        resolutionEvidence: 'The owner has reviewed the listed products.',
      });
    }
  }
  // Keyed by the blocking Wix item: the importer and the read-back gate name the same source record
  // with different key formats, so counting source keys would count one record twice.
  for (const entity of [...new Set(collisions.map((row) => row.entity))].sort()) {
    const targets = [...new Set(collisions.filter((row) => row.entity === entity).map((row) => row.targetId))];
    operatorActions.push({
      actionId: `catalog-baseline:collision:${entity}`, code: COLLISION_CODE, severity: 'high', role: 'import-operator', entity,
      action: `Requires Import Operator: ${targets.length} ${entity} item(s) that were on the store before this import match source records, so those records were not written (target ids in affectedIds).`,
      importOperatorPrompt: `Resolve ${COLLISION_CODE} for ${entity}: for each row in ${COLLISIONS_PATH}, remove or rename the listed Wix item (target id), then resume the import for that source record.`,
      deadlineReason: 'before switching traffic; these records are missing from the new store', affectedCount: targets.length, affectedIds: targets,
      artifactRefs: [COLLISIONS_PATH, ...(baseline ? [BASELINE_PATH] : [])], resolutionEvidence: 'Each listed source record has a verified read-back.',
    });
  }
  const summary = summarize(baseline);
  return { operatorActions, destinationBaseline: summary ? { path: BASELINE_PATH, ...summary, collisions: new Set(collisions.map((row) => `${row.entity}\u0000${row.targetId}`)).size } : null };
}

// Quick-mode summaries are their own completion reports and never pass through
// completion-report.js, so the same rows are attached here: structured operator actions (merged by
// actionId) and the destinationBaseline block.
function quickReport(projectDir, summary) {
  const { operatorActions, destinationBaseline } = reportRows(projectDir);
  if (destinationBaseline) summary.destinationBaseline = destinationBaseline;
  const others = (summary.operatorActions || []).filter((row) => !String(row.actionId || '').startsWith('catalog-baseline:'));
  if (operatorActions.length || summary.operatorActions) summary.operatorActions = [...others, ...operatorActions];
  // Same rule as completion-report.js: an open high-severity catalog item is never a clean `complete`.
  // A summary with no status of its own (WooCommerce) gets one: held records make it `partial`.
  const high = operatorActions.some((row) => row.severity === 'high');
  if (!summary.status && operatorActions.some((row) => row.code === COLLISION_CODE)) summary.status = 'partial';
  else if ((!summary.status || summary.status === 'complete') && high) summary.status = 'complete_with_warnings';
  return summary;
}

module.exports = {
  BASELINE_PATH, COLLISIONS_PATH, COLLISION_CODE, NOT_DELETED_CODE, PRE_EXISTING_CODE, STORES_APP_DEF_ID, ENTITY,
  readCatalog, settledCatalog, captureAroundInstall, loadBaseline, writeBaseline, digest, protectedIds, installSeededIds,
  summarize, partition, collisionError, recordCollision, clearCollision, loadCollisions, reportRows, quickReport,
};

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 Node.js

Security

What our scanner noticed· Low risk

  • 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 · 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 wix-replatform.zip