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://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/url-preservation-state.js

'use strict';

const fs = require('node:fs/promises');
const path = require('node:path');
const { auditPath: linkAuditPath, readLinkAudit, writeLinkAudit, validateLinkAudit } = require('./link-audit.js');

const SCHEMA_VERSION = 1;

const URL_STATUS = new Set([
  'preserved',
  'redirect_required',
  'pending_target_route',
  'source_url_missing',
  'target_url_missing',
  'not_public',
  'manual_review',
]);
const UNRESOLVED_STATUS = new Set(['open', 'resolved', 'manual_review']);
const REDIRECT_STATUS = new Set(['planned', 'retired']);
const BASE_PATH_STATUS = new Set(['planned', 'verified', 'unverified', 'manual_review']);

function urlPreservationDir(projectDir) {
  return path.join(projectDir, 'state', 'url-preservation');
}

function basePathsPath(projectDir) {
  return path.join(urlPreservationDir(projectDir), 'base-paths.json');
}

function urlLedgerPath(projectDir) {
  return path.join(urlPreservationDir(projectDir), 'url-ledger.ndjson');
}

function redirectsPath(projectDir) {
  return path.join(urlPreservationDir(projectDir), 'redirects.ndjson');
}

function unresolvedPath(projectDir) {
  return path.join(urlPreservationDir(projectDir), 'unresolved.ndjson');
}

// Post-build redirect application/verification state. `redirects.ndjson` stays the import's
// plan record; these files carry the stronger claims (installed, verified) separately.
const EXTENDED_FILES = Object.freeze({
  sourceRedirects: 'source-redirects.ndjson',
  sourceRedirectCoverage: 'source-redirect-coverage.json',
  sourceDomains: 'source-domains.json',
  finalRoutes: 'final-routes.json',
  launchPlan: 'launch-plan.json',
  redirectPlan: 'redirect-plan.json',
  redirectExecution: 'redirect-execution.ndjson',
  urlVerification: 'url-verification.ndjson',
  applyStatus: 'redirect-apply-status.json',
});

function statePath(projectDir, name) {
  if (!EXTENDED_FILES[name]) throw new Error(`unknown url-preservation state file: ${name}`);
  return path.join(urlPreservationDir(projectDir), EXTENDED_FILES[name]);
}

function relativeStatePath(name) {
  return `state/url-preservation/${EXTENDED_FILES[name]}`;
}

async function mkdirp(dirPath) {
  await fs.mkdir(dirPath, { recursive: true });
}

async function pathExists(filePath) {
  try {
    await fs.access(filePath);
    return true;
  } catch (error) {
    if (error && error.code === 'ENOENT') {
      return false;
    }
    throw error;
  }
}

async function ensureEmptyNdjson(filePath) {
  await mkdirp(path.dirname(filePath));
  if (!(await pathExists(filePath))) {
    await fs.writeFile(filePath, '', 'utf8');
    return true;
  }
  return false;
}

async function writeJsonAtomic(filePath, data) {
  await mkdirp(path.dirname(filePath));
  const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
  await fs.writeFile(tempPath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
  await fs.rename(tempPath, filePath);
}

async function appendNdjson(filePath, row) {
  await mkdirp(path.dirname(filePath));
  await fs.appendFile(filePath, `${JSON.stringify(row)}\n`, 'utf8');
}

async function readNdjson(filePath) {
  let raw;
  try {
    raw = await fs.readFile(filePath, 'utf8');
  } catch (error) {
    if (error && error.code === 'ENOENT') {
      return [];
    }
    throw error;
  }
  const rows = [];
  const lines = raw.split(/\r?\n/);
  for (let index = 0; index < lines.length; index += 1) {
    const line = lines[index].trim();
    if (!line) {
      continue;
    }
    try {
      rows.push(JSON.parse(line));
    } catch (error) {
      throw new Error(`${filePath}:${index + 1} invalid NDJSON: ${error.message}`);
    }
  }
  return rows;
}

function assertObject(row, label) {
  if (!row || typeof row !== 'object' || Array.isArray(row)) {
    throw new Error(`${label} must be an object`);
  }
}

function requireString(row, field, label, errors) {
  if (!row[field] || typeof row[field] !== 'string') {
    errors.push(`${label}.${field} must be a non-empty string`);
  }
}

function validateTimestamp(row, field, label, errors) {
  if (row[field] !== undefined && Number.isNaN(Date.parse(row[field]))) {
    errors.push(`${label}.${field} must be an ISO timestamp when present`);
  }
}

function validateUrlStatus(row, label, errors) {
  if (row.urlStatus && !URL_STATUS.has(row.urlStatus)) {
    errors.push(`${label}.urlStatus must be one of: ${Array.from(URL_STATUS).join(', ')}`);
  }
}

function validateRow(row, { allowThrow = true, label = 'row', required = [], validate = null } = {}) {
  const errors = [];
  try {
    assertObject(row, label);
  } catch (error) {
    if (allowThrow) {
      throw error;
    }
    return { ok: false, errors: [error.message] };
  }
  if (row.schemaVersion !== SCHEMA_VERSION) {
    errors.push(`${label}.schemaVersion must be ${SCHEMA_VERSION}`);
  }
  for (const field of required) {
    requireString(row, field, label, errors);
  }
  validateTimestamp(row, 'createdAt', label, errors);
  validateTimestamp(row, 'updatedAt', label, errors);
  if (validate) {
    validate(row, label, errors);
  }
  if (errors.length && allowThrow) {
    throw new Error(errors.join('; '));
  }
  return { ok: errors.length === 0, errors };
}

function validateLedgerRow(row, options = {}) {
  return validateRow(row, {
    label: options.label || 'URL ledger row',
    allowThrow: options.allowThrow,
    required: [
      'sourceSystem',
      'sourceEntityType',
      'sourceStableKey',
      'targetSystem',
      'targetEntityType',
      'sourceRelativeUrl',
      'urlStatus',
    ],
    validate: validateUrlStatus,
  });
}

function validateRedirectRow(row, options = {}) {
  return validateRow(row, {
    label: options.label || 'redirect row',
    allowThrow: options.allowThrow,
    required: [
      'sourceStableKey',
      'sourceRelativeUrl',
      'targetRelativeUrl',
      'status',
    ],
    validate: (candidate, label, errors) => {
      if (candidate.httpStatus !== 301) {
        errors.push(`${label}.httpStatus must be 301`);
      }
      if (candidate.status && !REDIRECT_STATUS.has(candidate.status)) {
        errors.push(`${label}.status must be one of: ${Array.from(REDIRECT_STATUS).join(', ')}`);
      }
    },
  });
}

function validateUnresolvedRow(row, options = {}) {
  return validateRow(row, {
    label: options.label || 'unresolved row',
    allowThrow: options.allowThrow,
    required: [
      'sourceSystem',
      'sourceEntityType',
      'sourceStableKey',
      'targetSystem',
      'targetEntityType',
      'sourceRelativeUrl',
      'urlStatus',
      'status',
    ],
    validate: (candidate, label, errors) => {
      validateUrlStatus(candidate, label, errors);
      if (candidate.status && !UNRESOLVED_STATUS.has(candidate.status)) {
        errors.push(`${label}.status must be one of: ${Array.from(UNRESOLVED_STATUS).join(', ')}`);
      }
    },
  });
}

function validateBasePathEntry(row, options = {}) {
  return validateRow(row, {
    label: options.label || 'base path entry',
    allowThrow: options.allowThrow,
    required: [
      'sourceSystem',
      'sourceEntityType',
      'targetSystem',
      'targetEntityType',
      'sourceBasePath',
      'sourceUrlPattern',
      'status',
    ],
    validate: (candidate, label, errors) => {
      if (typeof candidate.public !== 'boolean') {
        errors.push(`${label}.public must be a boolean`);
      }
      if (candidate.preserveBasePath !== undefined && typeof candidate.preserveBasePath !== 'boolean') {
        errors.push(`${label}.preserveBasePath must be a boolean when present`);
      }
      if (candidate.preserveSlug !== undefined && typeof candidate.preserveSlug !== 'boolean') {
        errors.push(`${label}.preserveSlug must be a boolean when present`);
      }
      if (candidate.status && !BASE_PATH_STATUS.has(candidate.status)) {
        errors.push(`${label}.status must be one of: ${Array.from(BASE_PATH_STATUS).join(', ')}`);
      }
    },
  });
}

function ledgerKey(row) {
  return `${row.sourceStableKey}\t${row.sourceRelativeUrl}`;
}

function redirectKey(row) {
  return `${row.sourceRelativeUrl}\t${row.targetRelativeUrl}\t${row.httpStatus}`;
}

function unresolvedKey(row) {
  return `${row.sourceStableKey}\t${row.sourceRelativeUrl}\t${row.urlStatus}`;
}

function foldRows(rows, keyFor) {
  const latestByKey = {};
  for (const row of rows) {
    latestByKey[keyFor(row)] = row;
  }
  return latestByKey;
}

async function appendUrlLedgerRow(projectDir, row) {
  validateLedgerRow(row);
  await appendNdjson(urlLedgerPath(projectDir), row);
  return row;
}

async function appendRedirectRow(projectDir, row) {
  validateRedirectRow(row);
  await appendNdjson(redirectsPath(projectDir), row);
  return row;
}

async function appendUnresolvedRow(projectDir, row) {
  validateUnresolvedRow(row);
  await appendNdjson(unresolvedPath(projectDir), row);
  return row;
}

async function loadUrlLedger(projectDir) {
  const rows = await readNdjson(urlLedgerPath(projectDir));
  for (const row of rows) {
    validateLedgerRow(row);
  }
  return { rows, byKey: foldRows(rows, ledgerKey) };
}

async function loadRedirects(projectDir) {
  const rows = await readNdjson(redirectsPath(projectDir));
  for (const row of rows) {
    validateRedirectRow(row);
  }
  return { rows, byKey: foldRows(rows, redirectKey) };
}

// The generated importer's historical redirect file can contain source-rule rows rather
// than keyed URL-preservation rows. Planning must retain each such address for manual
// review without letting one incompatible row abort the rest of the report.
async function loadRedirectsForPlanning(projectDir) {
  let raw;
  try {
    raw = await fs.readFile(redirectsPath(projectDir), 'utf8');
  } catch (error) {
    if (error && error.code === 'ENOENT') return { byKey: {}, rejected: [] };
    throw error;
  }
  const valid = [];
  const rejected = [];
  for (const [index, text] of raw.split(/\r?\n/).entries()) {
    if (!text.trim()) continue;
    let row;
    try { row = JSON.parse(text); } catch { row = null; }
    const checked = validateRedirectRow(row, { allowThrow: false });
    const sourceRuleFields = row && typeof row === 'object' &&
      ['statusCode', 'enabled', 'recordedAt'].some((key) => Object.hasOwn(row, key));
    if (checked.ok && !sourceRuleFields) valid.push(row);
    else rejected.push({
      line: index + 1,
      sourceRelativeUrl: row && typeof row.sourceRelativeUrl === 'string' ? row.sourceRelativeUrl : null,
      reason: sourceRuleFields ? 'import_redirect_source_rule_shape' : 'import_redirect_invalid_row',
      recordedDestination: row && typeof row.targetRelativeUrl === 'string' ? row.targetRelativeUrl : null,
      recordedStatus: row ? { status: typeof row.status === 'string' ? row.status : null, statusCode: Number.isInteger(row.statusCode) ? row.statusCode : null, enabled: typeof row.enabled === 'boolean' ? row.enabled : null } : null,
    });
  }
  return { byKey: Object.fromEntries(Object.entries(foldRows(valid, redirectKey))
    .filter(([, row]) => row.status === 'planned')), rejected };
}

async function loadUnresolved(projectDir) {
  const rows = await readNdjson(unresolvedPath(projectDir));
  for (const row of rows) {
    validateUnresolvedRow(row);
  }
  return { rows, byKey: foldRows(rows, unresolvedKey) };
}

async function writeBasePaths(projectDir, entries) {
  if (!Array.isArray(entries)) {
    throw new Error('base path entries must be an array');
  }
  for (const entry of entries) {
    validateBasePathEntry(entry);
  }
  await writeJsonAtomic(basePathsPath(projectDir), {
    schemaVersion: SCHEMA_VERSION,
    entries,
  });
  return entries;
}

async function loadBasePaths(projectDir) {
  let raw;
  try {
    raw = await fs.readFile(basePathsPath(projectDir), 'utf8');
  } catch (error) {
    if (error && error.code === 'ENOENT') {
      return { schemaVersion: SCHEMA_VERSION, entries: [] };
    }
    throw error;
  }
  const parsed = JSON.parse(raw);
  const entries = Array.isArray(parsed) ? parsed : parsed.entries;
  if (!Array.isArray(entries)) {
    throw new Error('base-paths.json entries must be an array');
  }
  for (const entry of entries) {
    validateBasePathEntry(entry);
  }
  return { schemaVersion: parsed.schemaVersion || SCHEMA_VERSION, entries };
}

async function initUrlPreservationState(projectDir) {
  await mkdirp(urlPreservationDir(projectDir));
  const actions = [];
  if (!(await pathExists(basePathsPath(projectDir)))) {
    await writeJsonAtomic(basePathsPath(projectDir), {
      schemaVersion: SCHEMA_VERSION,
      entries: [],
    });
    actions.push({ action: 'initialized_url_base_paths', path: 'state/url-preservation/base-paths.json' });
  }
  for (const [filePath, action, relativePath] of [
    [urlLedgerPath(projectDir), 'initialized_url_ledger', 'state/url-preservation/url-ledger.ndjson'],
    [redirectsPath(projectDir), 'initialized_url_redirects', 'state/url-preservation/redirects.ndjson'],
    [unresolvedPath(projectDir), 'initialized_url_unresolved', 'state/url-preservation/unresolved.ndjson'],
  ]) {
    const created = await ensureEmptyNdjson(filePath);
    actions.push({ action: created ? action : action.replace('initialized', 'kept'), path: relativePath });
  }
  await loadBasePaths(projectDir);
  await loadUrlLedger(projectDir);
  await loadRedirects(projectDir);
  await loadUnresolved(projectDir);
  return actions;
}

// --- post-build redirect state (apply/verify) --------------------------------------------

const SOURCE_RULE_MATCH = new Set(['exact', 'prefix', 'regex', 'contains', 'suffix', 'other']);
const COVERAGE_STATUS = new Set(['extracted', 'confirmed_empty', 'unreadable', 'unsupported']);
const ORIGIN_ROLES = new Set(['production', 'alias']);
const CUTOVER_STATUS = new Set(['source_serving', 'destination_serving']);
const READINESS = new Set(['ready', 'pending', 'unknown']);
const FRONTEND_REDIRECT_SUPPORT = new Set(['honors_wix_redirects', 'unverified', 'unsupported']);
const EXECUTION_DISPOSITIONS = new Set([
  'write_intent', 'installed', 'already_present', 'failed', 'outcome_unknown', 'manual_review',
]);
const VERIFICATION_STAGES = new Set(['preparation', 'verified_public']);
const VERIFICATION_RESULTS = new Set(['verified_direct', 'verified_redirect', 'failed', 'not_verified']);

function validateSourceRedirectRow(row, options = {}) {
  return validateRow(row, {
    label: options.label || 'source redirect row',
    allowThrow: options.allowThrow,
    required: ['ruleKey', 'provider', 'stableId', 'source', 'matchType'],
    validate: (candidate, label, errors) => {
      if (typeof candidate.enabled !== 'boolean') errors.push(`${label}.enabled must be a boolean`);
      if (!SOURCE_RULE_MATCH.has(candidate.matchType)) errors.push(`${label}.matchType must be one of: ${[...SOURCE_RULE_MATCH].join(', ')}`);
      if (!candidate.storage || typeof candidate.storage !== 'object' || !candidate.storage.kind) errors.push(`${label}.storage.kind is required (provenance)`);
      if (candidate.statusCode !== null && candidate.statusCode !== undefined && !Number.isInteger(candidate.statusCode)) errors.push(`${label}.statusCode must be an integer or null`);
    },
  });
}

function validateCoverage(doc) {
  assertObject(doc, 'source-redirect-coverage.json');
  if (doc.schemaVersion !== SCHEMA_VERSION) throw new Error(`source-redirect-coverage.json schemaVersion must be ${SCHEMA_VERSION}`);
  if (!Array.isArray(doc.providers)) throw new Error('source-redirect-coverage.json providers must be an array');
  for (const [index, row] of doc.providers.entries()) {
    const label = `source-redirect-coverage.providers[${index}]`;
    assertObject(row, label);
    if (!row.provider || typeof row.provider !== 'string') throw new Error(`${label}.provider is required`);
    if (!COVERAGE_STATUS.has(row.status)) throw new Error(`${label}.status must be one of: ${[...COVERAGE_STATUS].join(', ')}`);
  }
  return doc;
}

function normalizeOrigin(origin, label) {
  assertObject(origin, label);
  if (origin.scheme !== 'http' && origin.scheme !== 'https') throw new Error(`${label}.scheme must be http or https`);
  if (!origin.hostname || typeof origin.hostname !== 'string') throw new Error(`${label}.hostname is required`);
  let hostname;
  try {
    hostname = new URL(`${origin.scheme}://${origin.hostname}`).hostname;
  } catch {
    throw new Error(`${label}.hostname is not a valid hostname`);
  }
  // IDN input is accepted and stored in its ASCII (punycode) form.
  const defaultPort = origin.scheme === 'https' ? 443 : 80;
  const effectivePort = origin.effectivePort === undefined ? defaultPort : origin.effectivePort;
  if (!Number.isInteger(effectivePort) || effectivePort < 1 || effectivePort > 65535) throw new Error(`${label}.effectivePort must be a TCP port`);
  if (!ORIGIN_ROLES.has(origin.role)) throw new Error(`${label}.role must be one of: ${[...ORIGIN_ROLES].join(', ')}`);
  if (!CUTOVER_STATUS.has(origin.cutoverStatus)) throw new Error(`${label}.cutoverStatus must be one of: ${[...CUTOVER_STATUS].join(', ')}`);
  return { scheme: origin.scheme, hostname, effectivePort, role: origin.role, cutoverStatus: origin.cutoverStatus };
}

function originKey(origin) {
  return `${origin.scheme}://${origin.hostname}:${origin.effectivePort}`;
}

// Minimal declared-origin schema. Aliases are never synthesized: only what is listed here is
// an origin of the production site.
function validateSourceDomains(doc) {
  assertObject(doc, 'source-domains.json');
  if (doc.schemaVersion !== SCHEMA_VERSION) throw new Error(`source-domains.json schemaVersion must be ${SCHEMA_VERSION}`);
  if (!Array.isArray(doc.origins) || doc.origins.length === 0) throw new Error('source-domains.json origins must be a non-empty array');
  const origins = doc.origins.map((origin, index) => normalizeOrigin(origin, `source-domains.origins[${index}]`));
  const keys = new Set();
  for (const origin of origins) {
    const key = originKey(origin);
    if (keys.has(key)) throw new Error(`source-domains.json declares ${key} twice`);
    keys.add(key);
  }
  if (!origins.some((origin) => origin.role === 'production')) throw new Error('source-domains.json needs one production origin');
  const productionHosts = new Set(origins.filter((o) => o.role === 'production').map((o) => o.hostname));
  if (productionHosts.size !== 1) throw new Error('source-domains.json production origins must share one hostname');
  if (doc.domains !== undefined && !Array.isArray(doc.domains)) {
    throw new Error('source-domains.json domains must be an array when present');
  }
  return { schemaVersion: SCHEMA_VERSION, productionHostname: [...productionHosts][0], origins,
    ...(doc.domains ? { domains: doc.domains } : {}) };
}

function validateFinalRoutes(doc) {
  assertObject(doc, 'final-routes.json');
  if (doc.schemaVersion !== SCHEMA_VERSION) throw new Error(`final-routes.json schemaVersion must be ${SCHEMA_VERSION}`);
  for (const field of ['siteId', 'deploymentId']) {
    if (!doc[field] || typeof doc[field] !== 'string') throw new Error(`final-routes.json ${field} is required`);
  }
  if (!Array.isArray(doc.routes)) throw new Error('final-routes.json routes must be an array');
  doc.routes.forEach((route, index) => {
    const label = `final-routes.routes[${index}]`;
    assertObject(route, label);
    for (const field of ['sourceKey', 'targetEntityType', 'targetEntityId', 'relativeUrl', 'pageMarker']) {
      if (!route[field] || typeof route[field] !== 'string') throw new Error(`${label}.${field} is required`);
    }
    if (!route.relativeUrl.startsWith('/')) throw new Error(`${label}.relativeUrl must be site-relative`);
  });
  return doc;
}

function validateLaunchPlan(doc) {
  assertObject(doc, 'launch-plan.json');
  if (doc.schemaVersion !== SCHEMA_VERSION) throw new Error(`launch-plan.json schemaVersion must be ${SCHEMA_VERSION}`);
  for (const field of ['siteId', 'deploymentId', 'productionHostname']) {
    if (!doc[field] || typeof doc[field] !== 'string') throw new Error(`launch-plan.json ${field} is required`);
  }
  for (const field of ['domainAssociation', 'https']) {
    if (!READINESS.has(doc[field])) throw new Error(`launch-plan.json ${field} must be one of: ${[...READINESS].join(', ')}`);
  }
  assertObject(doc.frontend, 'launch-plan.json frontend');
  if (!doc.frontend.model || typeof doc.frontend.model !== 'string') throw new Error('launch-plan.json frontend.model is required');
  if (!FRONTEND_REDIRECT_SUPPORT.has(doc.frontend.redirectSupport)) {
    throw new Error(`launch-plan.json frontend.redirectSupport must be one of: ${[...FRONTEND_REDIRECT_SUPPORT].join(', ')}`);
  }
  if (doc.frontend.redirectSupport === 'honors_wix_redirects' && !doc.frontend.evidenceRef) {
    throw new Error('launch-plan.json frontend.evidenceRef is required when redirectSupport is honors_wix_redirects');
  }
  if (doc.dnsInstructions !== undefined) {
    assertObject(doc.dnsInstructions, 'launch-plan.json dnsInstructions');
    if (doc.dnsInstructions.registrarTransferRequired === true || doc.dnsInstructions.changesMailRecords === true) {
      throw new Error('launch-plan.json website DNS instructions must not require a registrar transfer or mail-record changes');
    }
  }
  return doc;
}

function validateExecutionRow(row, options = {}) {
  return validateRow(row, {
    label: options.label || 'redirect execution row',
    allowThrow: options.allowThrow,
    required: ['runId', 'planDigest', 'deploymentId', 'siteId', 'ruleKey', 'from', 'to', 'disposition', 'recordedAt'],
    validate: (candidate, label, errors) => {
      if (!EXECUTION_DISPOSITIONS.has(candidate.disposition)) errors.push(`${label}.disposition must be one of: ${[...EXECUTION_DISPOSITIONS].join(', ')}`);
      if (!Array.isArray(candidate.origins)) errors.push(`${label}.origins must be an array`);
      if (!Array.isArray(candidate.reasonCodes)) errors.push(`${label}.reasonCodes must be an array`);
      if (candidate.disposition === 'write_intent' && !candidate.inventoryDigest) errors.push(`${label}.inventoryDigest is required on write_intent`);
      validateTimestamp(candidate, 'recordedAt', label, errors);
    },
  });
}

function validateVerificationRow(row, options = {}) {
  return validateRow(row, {
    label: options.label || 'url verification row',
    allowThrow: options.allowThrow,
    required: ['checkpointKey', 'obligationKey', 'planDigest', 'deploymentId', 'stage', 'effectiveEndpoint', 'originalUrl', 'result', 'checkedAt'],
    validate: (candidate, label, errors) => {
      if (!VERIFICATION_STAGES.has(candidate.stage)) errors.push(`${label}.stage must be one of: ${[...VERIFICATION_STAGES].join(', ')}`);
      if (!VERIFICATION_RESULTS.has(candidate.result)) errors.push(`${label}.result must be one of: ${[...VERIFICATION_RESULTS].join(', ')}`);
      if (!Array.isArray(candidate.trace)) errors.push(`${label}.trace must be an array`);
      validateTimestamp(candidate, 'checkedAt', label, errors);
    },
  });
}

// Durable append: the row is on disk before the caller does the I/O it announces.
async function appendNdjsonDurable(filePath, row) {
  await mkdirp(path.dirname(filePath));
  const handle = await fs.open(filePath, 'a+');
  try {
    // A crash can leave a torn final line; start on a fresh line so the new row stays valid.
    const { size } = await handle.stat();
    let prefix = '';
    if (size > 0) {
      const last = Buffer.alloc(1);
      await handle.read(last, 0, 1, size - 1);
      if (last[0] !== 0x0a) prefix = '\n';
    }
    await handle.write(`${prefix}${JSON.stringify(row)}\n`);
    await handle.datasync();
  } finally {
    await handle.close();
  }
}

// Latest-valid-row reader for execution/verification logs: a torn trailing line (crash mid-
// append) or a malformed row is rejected and reported, never folded and never fatal.
async function readValidatedNdjson(filePath, validate) {
  let raw;
  try {
    raw = await fs.readFile(filePath, 'utf8');
  } catch (error) {
    if (error && error.code === 'ENOENT') return { rows: [], rejected: [] };
    throw error;
  }
  const rows = [];
  const rejected = [];
  raw.split(/\r?\n/).forEach((line, index) => {
    if (!line.trim()) return;
    let parsed;
    try {
      parsed = JSON.parse(line);
    } catch (error) {
      rejected.push({ line: index + 1, reason: `invalid JSON: ${error.message}` });
      return;
    }
    const result = validate(parsed, { allowThrow: false });
    if (result.ok) rows.push(parsed);
    else rejected.push({ line: index + 1, reason: result.errors.join('; ') });
  });
  return { rows, rejected };
}

async function readJsonIfPresent(filePath) {
  try {
    return JSON.parse(await fs.readFile(filePath, 'utf8'));
  } catch (error) {
    if (error && error.code === 'ENOENT') return null;
    throw error;
  }
}

async function loadSourceRedirects(projectDir) {
  const rows = await readNdjson(statePath(projectDir, 'sourceRedirects'));
  for (const row of rows) validateSourceRedirectRow(row);
  const byKey = foldRows(rows, (row) => row.ruleKey);
  return { rows, byKey, latest: Object.values(byKey) };
}

async function appendSourceRedirectRow(projectDir, row) {
  validateSourceRedirectRow(row);
  await appendNdjson(statePath(projectDir, 'sourceRedirects'), row);
  return row;
}

async function loadRedirectExecution(projectDir) {
  const { rows, rejected } = await readValidatedNdjson(statePath(projectDir, 'redirectExecution'), validateExecutionRow);
  return { rows, rejected, byKey: foldRows(rows, (row) => row.ruleKey) };
}

async function appendRedirectExecutionRow(projectDir, row) {
  validateExecutionRow(row);
  await appendNdjsonDurable(statePath(projectDir, 'redirectExecution'), row);
  return row;
}

async function loadUrlVerification(projectDir) {
  const { rows, rejected } = await readValidatedNdjson(statePath(projectDir, 'urlVerification'), validateVerificationRow);
  return { rows, rejected, byCheckpoint: foldRows(rows, (row) => row.checkpointKey) };
}

async function appendUrlVerificationRow(projectDir, row) {
  validateVerificationRow(row);
  await appendNdjsonDurable(statePath(projectDir, 'urlVerification'), row);
  return row;
}

async function writeStateJson(projectDir, name, doc) {
  await writeJsonAtomic(statePath(projectDir, name), doc);
  return doc;
}

async function loadStateJson(projectDir, name) {
  const doc = await readJsonIfPresent(statePath(projectDir, name));
  if (doc === null) return null;
  if (name === 'sourceDomains') return validateSourceDomains(doc);
  if (name === 'finalRoutes') return validateFinalRoutes(doc);
  if (name === 'launchPlan') return validateLaunchPlan(doc);
  if (name === 'sourceRedirectCoverage') return validateCoverage(doc);
  return doc;
}

module.exports = {
  SCHEMA_VERSION,
  urlPreservationDir,
  basePathsPath,
  urlLedgerPath,
  redirectsPath,
  unresolvedPath,
  linkAuditPath,
  readLinkAudit,
  writeLinkAudit,
  validateLinkAudit,
  ledgerKey,
  redirectKey,
  unresolvedKey,
  validateBasePathEntry,
  validateLedgerRow,
  validateRedirectRow,
  validateUnresolvedRow,
  writeBasePaths,
  loadBasePaths,
  appendUrlLedgerRow,
  appendRedirectRow,
  appendUnresolvedRow,
  loadUrlLedger,
  loadRedirects,
  loadRedirectsForPlanning,
  loadUnresolved,
  initUrlPreservationState,
  EXTENDED_FILES,
  statePath,
  relativeStatePath,
  originKey,
  validateSourceRedirectRow,
  validateCoverage,
  validateSourceDomains,
  validateFinalRoutes,
  validateLaunchPlan,
  validateExecutionRow,
  validateVerificationRow,
  loadSourceRedirects,
  appendSourceRedirectRow,
  loadRedirectExecution,
  appendRedirectExecutionRow,
  loadUrlVerification,
  appendUrlVerificationRow,
  writeStateJson,
  loadStateJson,
};

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 or Wix.

Download ZIP

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