Wix Replatform
WixOfficialPublished by Wix
- Skill
- Workflow
- Automation and integrations
- MIT
- Low risk
- Has scripts
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
Download the skill as a ZIP:
https://autogineer.com/agent-skills/wix/wix-replatform-fya3/downloadUnzip 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>/(orREPLATFORM_MIGRATIONS_DIR) before inspecting or creating anything. Only that project's artifacts are authoritative.Preserve
EXPECTATIONS.mdat 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 reviewDelivery 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:
Resolve the project and initialize/load its orchestration artifacts.
Run
node skills/wix-replatform/scripts/orchestration-route.js <projectDir>.Dispatch the
nextResourceto 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 readstate/attempts/write-attempts.ndjsonraw; usescripts/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.
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.
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.mdandmapping-gaps.json, orexecution/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 — seerp-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.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_rejectedisblockedbefore any setup or import write, andmapping_approval_rejectedreturns torp-mapperfor 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) isblockedwitherrorsand the producer asnextResource. 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) carryimportProgress.interruptedlistsrecoveryArtifacts: resume it, never a second import.interruptedReport: "missing": first runscripts/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 situation | Dispatch |
|---|---|
| project, delivery mode, source mode, or grouped intake is unresolved | resources/rp-project-intake/ |
| destination is absent, conflicting, or needs creation/adoption | resources/rp-destination/ |
| source URL/files/config/acquisition mode/credentials are required, including source credentials said to exist already on another site | resources/rp-source-inputs/ |
| deterministic preflight is missing, repaired, or blocked on CLI checks | resources/rp-preflight/ |
| quick mode needs platform resolution, endpoint preflight, plan, extraction, or import | selected resources/rp-quick-<platform>/ |
| source schema is missing | resources/rp-discovery/ and its selected source adapter |
| mapping is missing or needs review | resources/rp-mapper/ |
| Wix requirements are missing | resources/rp-setup-discovery/ |
| import code/review is missing or stale | resources/rp-import-codegen/ |
| setup verification is missing | resources/rp-execute-setup/ |
| backend completion report is missing | resources/rp-execute-import/ |
| frontend-only work, or integrated website handoff/build/gap loop/release receipt is incomplete | resources/rp-website-continuation/ |
| aggregate completion is missing | resources/rp-execution-policy/ |
| aggregate completion exists but the local review publication or current recap is missing | resources/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_websitemode 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
completedwithcompletion/migration-completion.json, orblockedwith 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.
websitemeans frontend only;management_and_websitemeans 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 byrp-destination's coordinator and is never published, unpublished or handed towix-headless-replatform; its website and publication remain operator handoff items.Do not implement a storefront manually when
wix-headless-replatformis 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
- .publish-manifest.json210 B
- ATTRIBUTION.mdAdded by AutoGineer815 B
- CLI.md9.8 KiB
- LICENSELicence file added by AutoGineer1.0 KiB
- README.md11.9 KiB
- SKILL.md16.4 KiB
- VERSION6 B
- console/account.css633 B
- console/app.css5.2 KiB
- console/app.jsScript22.9 KiB
- console/index.html837 B
- console/json.css639 B
- lib/agent-adapters/index.jsScript2.9 KiB
- lib/app-page-routing.jsScript4.3 KiB
- lib/app-requirements.jsScript1.5 KiB
- lib/artifact-freshness.jsScript12.7 KiB
- lib/blocked-data-requests.jsScript21.4 KiB
- lib/cached-json.jsScript1.3 KiB
- lib/catalog-baseline.jsScript23.3 KiB
- lib/census-reconciliation.jsScript22.8 KiB
- lib/cms-collection-compatibility.jsScript2.0 KiB
- lib/completion-report.jsScript124.6 KiB
- lib/config-env.jsScript6.1 KiB
- lib/confirmed-pictures.jsScript6.9 KiB
- lib/crosswalk-adoption.jsScript6.3 KiB
- lib/dependency-proofs.jsScript46.7 KiB
- lib/dependency-readiness.jsScript112.3 KiB
- lib/dependency-recovery.jsScript1.5 KiB
- lib/dependency-waves.jsScript2.1 KiB
- lib/destination-choice.jsScript9.7 KiB
- lib/destination-handoff.jsScript12.5 KiB
- lib/destination-http.jsScript2.7 KiB
- lib/destination-route.jsScript5.1 KiB
- lib/destination.jsScript57.1 KiB
- lib/discovered-census.jsScript11.0 KiB
- lib/discovered-set-status.jsScript15.2 KiB
- lib/document-url-guard.jsScript12.7 KiB
- lib/editor-type.jsScript748 B
- lib/egress-proxy.jsScript20.8 KiB
- lib/entity-qa-attestation.jsScript19.4 KiB
- lib/entity-verification.jsScript1.3 KiB
- lib/execution-capability.jsScript7.3 KiB
- lib/execution-log.jsScript6.4 KiB
- lib/execution-manifest.jsScript10.2 KiB
- lib/execution-state.jsScript5.9 KiB
- lib/expectations-ledger.jsScript3.4 KiB
- lib/extract-ledger.jsScript21.4 KiB
- lib/field-mapping-examples.jsScript7.3 KiB
- lib/generated-plugin-handoff.jsScript8.7 KiB
- lib/import-interruption.jsScript13.6 KiB
- lib/import-readiness-contract.jsScript4.3 KiB
- lib/import-recovery.jsScript54.0 KiB
- lib/import-task-runner.jsScript18.1 KiB
- lib/imported-redirect-targets.jsScript32.5 KiB
- lib/internal-link-reconciliation.jsScript10.7 KiB
- lib/link-audit.jsScript11.1 KiB
- lib/link-census.jsScript11.0 KiB
- lib/link-plan.jsScript9.4 KiB
- lib/link-verification.jsScript18.7 KiB
- lib/link-waivers.jsScript5.8 KiB
- lib/link-write-journal.jsScript1.8 KiB
- lib/local-state.js66.8 KiB
- lib/mapping-field-contract.js54.1 KiB
- lib/mapping-omission-approval.js7.6 KiB
- lib/mapping-recovery.js22.4 KiB
- lib/mapping-resolution.js6.1 KiB
- lib/mapping-target-rules.js7.4 KiB
- lib/member-completion.js31.6 KiB
- lib/member-crosswalk.js2.9 KiB
- lib/member-outcome-registry.js13.6 KiB
- lib/migration-completion.js18.3 KiB
- lib/migration-review-mapping.js21.4 KiB
- lib/migration-review.js73.7 KiB
- lib/multi-step-attempt.js4.4 KiB
- lib/multilingual-public-report.js14.5 KiB
- lib/multilingual-public.js26.3 KiB
- lib/notification-mute.js9.9 KiB
- lib/operation-assessments.js9.8 KiB
- lib/operator-identity.js1.2 KiB
- lib/orchestration-decisions.js8.7 KiB
- lib/orchestration-preflight.js25.1 KiB
- lib/orchestration-router.js50.8 KiB
- lib/orchestration-state.js30.9 KiB
- lib/order-reference-readiness.js2.8 KiB
- lib/output-applicability.js5.0 KiB
- lib/payments-outcome-registry.js9.8 KiB
- lib/plan-order-outcome-registry.js13.1 KiB
- lib/plugin-cms-fallback.js35.1 KiB
- lib/preservation-approval-stamp.js2.8 KiB
- lib/product-media-deferral.js3.8 KiB
- lib/product-videos.js7.1 KiB
- lib/progress-log.js6.6 KiB
- lib/progress-log.sh4.1 KiB
- lib/raw-request-guard.js18.5 KiB
- lib/read-back-approval.js16.1 KiB
- lib/read-back-comparison.js10.5 KiB
- lib/read-back-contract.js37.4 KiB
- lib/read-back-extract.js4.0 KiB
- lib/read-back-gate.js46.6 KiB
- lib/read-back-reads.js2.9 KiB
- lib/read-back-state.js3.4 KiB
- lib/read-back-summary.js6.5 KiB
- lib/rerun-conflicts.js14.5 KiB
- lib/run-controller.js26.3 KiB
- lib/seo-outcome-registry.js3.2 KiB
- lib/setup-producers.js1.3 KiB
- lib/setup-verification.js11.6 KiB
- lib/site-regional-gate.js3.3 KiB
- lib/site-regional-report.js10.3 KiB
- lib/site-regional.js37.0 KiB
- lib/source-access.js11.2 KiB
- lib/source-coverage.js54.0 KiB
- lib/source-location.js10.6 KiB
- lib/source-redirect-capture.js2.6 KiB
- lib/source-regional.js15.5 KiB
- lib/source-secrets.js8.1 KiB
- lib/structured-link-patch.js3.1 KiB
- lib/subagent-handoff.js8.9 KiB
- lib/target-import-support.js18.4 KiB
- lib/task-state.js6.2 KiB
- lib/toolkit-dependencies.js947 B
- lib/url-preservation-report.js20.4 KiB
- lib/url-preservation-state.js27.0 KiB
- lib/url-redirect-plan.js36.3 KiB
- lib/url-verification.js15.5 KiB
- lib/user-action-effects.js2.9 KiB
- lib/user-actions.js18.4 KiB
- lib/vendor-closure.js5.6 KiB
- lib/website-handoff.js60.6 KiB
- lib/wix-auth.js11.0 KiB
- lib/wix-client-callers.js6.7 KiB
- lib/wix-dashboard-url.js1.0 KiB
- lib/write-log-summary.js9.4 KiB
- lib/write-verification-state.js7.9 KiB
- lib/write-verification.js30.0 KiB
- scripts/artifact-freshness.js2.3 KiB
- scripts/census-reconciliation.js781 B
- scripts/cms-fallback.js3.2 KiB
- scripts/cms-item-quota.js3.9 KiB
- scripts/crosswalk-adopt.js3.0 KiB
- scripts/dependency-preflight.js2.2 KiB
- scripts/discovered-census.js867 B
- scripts/discovered-set-status.js1.1 KiB
- scripts/entity-qa-attestation.js4.8 KiB
- scripts/execution-health-check.js19.9 KiB
- scripts/execution-manifest-validate.js1.7 KiB
- scripts/execution-state-prepare.js3.9 KiB
- scripts/expectations-ledger.js1.5 KiB
- scripts/extract-ledger.js1.9 KiB
- scripts/import-contract-verify.js20.4 KiB
- scripts/import-supervise.js16.1 KiB
- scripts/internal-link-audit.js6.5 KiB
- scripts/interrupted-completion-report.js2.7 KiB
- scripts/item-seo-tags-verify.js8.2 KiB
- scripts/link-waiver.js3.8 KiB
- scripts/migration-completion.js3.8 KiB
- scripts/migration-review.js3.7 KiB
- scripts/orchestration-preflight.js3.5 KiB
- scripts/orchestration-route.js3.7 KiB
- scripts/orchestration-state.js18.9 KiB
- scripts/read-back-gate.js11.3 KiB
- scripts/replatform-console.js12.9 KiB
- scripts/replatform.js35.4 KiB
- scripts/site-regional.js2.4 KiB
- scripts/source-secrets.js2.9 KiB
- scripts/subagent-handoff.js2.5 KiB
- scripts/url-redirects.js13.0 KiB
- scripts/user-action.js2.9 KiB
- scripts/vendor-closure.js1.0 KiB
- scripts/website-handoff-generate.js2.3 KiB
- scripts/wix-dashboard-url.js1.6 KiB
- scripts/wix-destination.js6.4 KiB
- scripts/wix-env.js1.5 KiB
- scripts/wix-headless-scaffold.js34.8 KiB
- scripts/write-log-summary.js2.2 KiB
- vendor/README.md604 B
- vendor/commander/LICENSE1.1 KiB
- vendor/commander/index.js711 B
- vendor/commander/lib/argument.js3.1 KiB
- vendor/commander/lib/command.js85.6 KiB
- vendor/commander/lib/error.js1.1 KiB
- vendor/commander/lib/help.js20.3 KiB
- vendor/commander/lib/option.js10.0 KiB
- vendor/commander/lib/suggestSimilar.js2.7 KiB
- vendor/commander/package.json1.6 KiB
lib/extract-ledger.js
'use strict';
// The toolkit's own record of every source extract version.
//
// An extract and its manifest are written by generated project code, so a manifest digest proves
// nothing: the same code can rewrite the file and re-stamp it. This ledger records each version
// the toolkit sees: its digest, row count and, per source record, the set of field names it
// carries (never values). Gates then refuse an extract that changed after it was recorded, and a
// version in which a record lost fields it had in an earlier version while the source did not
// change that record. Dropping source data to get past a gate is detected, not trusted; a field
// with no home is kept by the mapping, never stripped.
//
// Tamper evidence: rows are hash-chained (`prev`, `rowHash`), each row pins its shapes file by
// digest, and lost fields are recomputed from the shapes files rather than read from the row. The
// read-back inventory pins the chain head. The ledger is kept twice: under state/ and beside the
// extracts it describes (data/source-extract/.extract-ledger/), so deleting either copy is
// detected and repaired from the other.
//
// Never block: a changed, field-losing or unverifiable extract is re-extracted from the source
// (`src/extract/run-extract.js --entity <entity>`), the new version is recorded, and what happened
// -- old and new version, fields still lost -- is written to execution/extract-integrity.json for
// the run report. Only an extract that cannot be re-read from the source is refused, for that
// entity alone, with its next step.
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const { spawn } = require('node:child_process');
const { readExtract } = require('./read-back-extract');
const LEDGER = 'state/source-extract-ledger.ndjson';
const SHAPES_DIR = 'state/source-extract-ledger';
const MIRROR = 'data/source-extract/.extract-ledger/ledger.ndjson';
const MIRROR_SHAPES_DIR = 'data/source-extract/.extract-ledger/shapes';
const REPORT = 'execution/extract-integrity.json';
const EXTRACTOR = 'src/extract/run-extract.js';
const SCHEMA_VERSION = 2;
// Source fields that change whenever the source changes a record. A record whose marker differs
// between two versions was edited at the source, so a field it no longer has is not a strip.
const CHANGE_MARKERS = ['date_modified_gmt', 'date_modified', 'updated_at', 'updatedAt', 'modified_gmt', 'modified'];
const sha = value => crypto.createHash('sha256').update(value).digest('hex');
function canonical(value) {
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key])).join(',') + '}';
return JSON.stringify(value);
}
function fail(code) { return Object.assign(new Error(code), { code }); }
function inside(projectDir, file) {
const root = path.resolve(projectDir), absolute = path.resolve(root, typeof file === 'string' ? file : '');
if (typeof file !== 'string' || !file || !absolute.startsWith(root + path.sep)) throw fail('extract_path_outside_project');
return absolute;
}
const relative = (projectDir, file) => path.relative(path.resolve(projectDir), inside(projectDir, file)).split(path.sep).join('/');
const valueAt = (record, dotted) => dotted.split('.').reduce((node, key) => (node && typeof node === 'object' ? node[key] : undefined), record);
// Field names a record carries: object keys as dotted paths, arrays as `[]`, and for an array of
// `{ key, value }` items (WordPress meta) each item's key as `[key="…"]`, so a dropped meta key
// is a lost field even though `meta_data[].value` remains.
function shapePaths(record, out = new Set(), base = '') {
if (Array.isArray(record)) {
for (const item of record) {
if (item && typeof item === 'object' && !Array.isArray(item) && typeof item.key === 'string') out.add(`${base}[key=${JSON.stringify(item.key)}]`);
shapePaths(item, out, `${base}[]`);
}
} else if (record && typeof record === 'object') {
for (const [key, value] of Object.entries(record)) {
const next = base ? `${base}.${key}` : key;
out.add(next);
shapePaths(value, out, next);
}
}
return out;
}
async function fileDigest(file) {
const hash = crypto.createHash('sha256');
for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
return hash.digest('hex');
}
// One streamed pass: per record its field-name set (deduplicated by shape) and change marker.
// Parse failures surface as typed codes only, never source text.
async function measure(projectDir, extractPath, { keyField = 'id' } = {}) {
const file = inside(projectDir, extractPath), shapes = [], shapeIndex = new Map(), records = {};
let rows = 0;
try {
for await (const record of readExtract(file)) {
rows += 1;
const key = valueAt(record, keyField);
if (key === undefined || key === null || typeof key === 'object' || String(key) === '') throw fail('extract_record_key_missing');
if (Object.hasOwn(records, String(key))) throw fail('extract_record_key_duplicate');
const paths = [...shapePaths(record)].sort(), id = canonical(paths);
if (!shapeIndex.has(id)) { shapeIndex.set(id, shapes.length); shapes.push(paths); }
const marker = CHANGE_MARKERS.map(name => record[name]).find(value => typeof value === 'string' || typeof value === 'number');
records[String(key)] = marker === undefined ? [shapeIndex.get(id)] : [shapeIndex.get(id), String(marker)];
}
} catch (error) {
throw fail(typeof error.code === 'string' && /^extract_/.test(error.code) ? error.code : 'extract_unreadable');
}
return { sha256: await fileDigest(file), rows, keyField, shapes, records };
}
function rowHash(row) { const { rowHash: _omit, ...rest } = row; return sha(canonical(rest)); }
function readChain(file) {
if (!fs.existsSync(file)) return { rows: [], present: false, broken: false };
const rows = [];
let prev = 'genesis', broken = false;
for (const line of fs.readFileSync(file, 'utf8').split('\n').filter(Boolean)) {
let row;
try { row = JSON.parse(line); } catch { broken = true; break; }
if (row.schemaVersion !== SCHEMA_VERSION || row.prev !== prev || row.rowHash !== rowHash(row) || row.seq !== rows.length + 1) { broken = true; break; }
rows.push(row); prev = row.rowHash;
}
return { rows, present: true, broken };
}
const isPrefix = (short, long) => short.every((row, i) => long[i]?.rowHash === row.rowHash);
// The longer intact copy is authoritative. A copy that is missing, broken, behind or divergent is
// reported (`issues`) and rewritten from it, so one deleted or edited copy never hides history.
function readLedger(projectDir) {
const copies = [LEDGER, MIRROR].map(rel => ({ rel, ...readChain(path.join(projectDir, rel)) }));
const [main, mirror] = copies;
const rows = main.rows.length >= mirror.rows.length ? main.rows : mirror.rows;
const issues = [];
for (const copy of copies) {
if (copy.broken) issues.push(`source_extract_ledger_broken:${copy.rel}`);
else if (!copy.present && rows.length) issues.push(`source_extract_ledger_missing:${copy.rel}`);
else if (!isPrefix(copy.rows, rows)) issues.push(`source_extract_ledger_diverged:${copy.rel}`);
}
return { rows, issues, errors: [] };
}
function writeLedger(projectDir, rows) {
for (const rel of [LEDGER, MIRROR]) {
fs.mkdirSync(path.dirname(path.join(projectDir, rel)), { recursive: true });
fs.writeFileSync(path.join(projectDir, rel), rows.map(row => JSON.stringify(row) + '\n').join(''));
}
}
function entries(projectDir, extractPath) {
const wanted = extractPath === undefined ? null : relative(projectDir, extractPath);
return readLedger(projectDir).rows.filter(row => wanted === null || row.extractPath === wanted);
}
const head = projectDir => readLedger(projectDir).rows.at(-1)?.rowHash || null;
const mirrorShapes = row => `${MIRROR_SHAPES_DIR}/${path.basename(row.shapesPath)}`;
function readShapes(projectDir, row) {
let changed = false;
for (const rel of [row.shapesPath, mirrorShapes(row)]) {
let text;
try { text = fs.readFileSync(inside(projectDir, rel), 'utf8'); } catch { continue; }
if (sha(text) === row.shapesSha256) return JSON.parse(text);
changed = true;
}
throw fail(changed ? 'source_extract_shapes_changed' : 'source_extract_shapes_missing');
}
// Fields a record carried in an earlier version and no longer carries, for every record present in
// both whose change marker did not move. Every earlier version counts, so a stripped version
// followed by any later re-extract stays lost. A record the source deleted or edited is not a loss.
function lostSince(earlier, after) {
const lost = new Map();
for (const [key, [shape, marker]] of Object.entries(after.records)) {
const now = new Set(after.shapes[shape]), gone = new Set();
for (const before of earlier) {
const prior = before.records[key];
if (!prior || prior[1] !== marker) continue;
for (const p of before.shapes[prior[0]]) if (!now.has(p)) gone.add(p);
}
for (const p of gone) lost.set(p, (lost.get(p) || 0) + 1);
}
return [...lost.keys()].sort().map(p => ({ path: p, records: lost.get(p) }));
}
// Record the extract's current version, unless it is already the latest one. Both ledger copies
// are brought to the authoritative chain first.
async function recordExtract(projectDir, { entity, extractPath, keyField = 'id', recordedBy = 'toolkit', replacesHead = null, now = new Date() }) {
if (typeof entity !== 'string' || !entity) throw fail('extract_entity_required');
const ledger = readLedger(projectDir);
const extract = relative(projectDir, extractPath), prior = ledger.rows.filter(row => row.extractPath === extract);
const measured = await measure(projectDir, extract, { keyField });
const latest = prior.at(-1);
if (ledger.issues.length) writeLedger(projectDir, ledger.rows);
// A re-read from the source is always its own row, even when it matches: it settles the loss check.
if (latest?.sha256 === measured.sha256 && !replacesHead && (recordedBy !== 're-extract' || latest.recordedBy === 're-extract')) return latest;
const shapes = { sha256: measured.sha256, keyField, shapes: measured.shapes, records: measured.records }, shapesText = canonical(shapes);
const shapesPath = `${SHAPES_DIR}/${measured.sha256}.json`;
for (const rel of [shapesPath, `${MIRROR_SHAPES_DIR}/${measured.sha256}.json`]) {
fs.mkdirSync(path.dirname(path.join(projectDir, rel)), { recursive: true });
fs.writeFileSync(path.join(projectDir, rel), shapesText);
}
let earlier = [];
try { earlier = prior.map(row => readShapes(projectDir, row)); } catch { /* unverifiable history: reported by extractErrors */ }
const row = { schemaVersion: SCHEMA_VERSION, seq: ledger.rows.length + 1, prev: ledger.rows.at(-1)?.rowHash || 'genesis', entity, extractPath: extract, sha256: measured.sha256, rows: measured.rows, keyField,
shapesPath, shapesSha256: sha(shapesText), lostPaths: lostSince(earlier, shapes), version: prior.length + 1, recordedBy, ...(replacesHead ? { replacesHead } : {}), recordedAt: now.toISOString() };
row.rowHash = rowHash(row);
writeLedger(projectDir, [...ledger.rows, row]);
return row;
}
// Errors for the extract as it is now. `ledgerHead` is the chain head an inventory pinned; the
// ledger must still contain it. Lost fields are recomputed from the pinned shapes files.
async function extractErrors(projectDir, extractPath, { sha256 = null, ledgerHead = null } = {}) {
let extract;
try { extract = relative(projectDir, extractPath); } catch (error) { return [error.code]; }
const ledger = readLedger(projectDir);
if (ledger.issues.length) return ledger.issues.map(code => `${code.split(':')[0]}:${extract}`);
// A re-extract that replaced a lost head satisfies it: the extract was re-read from the source.
if (ledgerHead && !ledger.rows.some(row => row.rowHash === ledgerHead || row.replacesHead === ledgerHead)) return [`source_extract_ledger_head_missing:${extract}`];
const prior = ledger.rows.filter(row => row.extractPath === extract), latest = prior.at(-1);
if (!latest) return [`source_extract_unrecorded:${extract}`];
let current;
try { current = await fileDigest(inside(projectDir, extract)); } catch { return [`source_extract_unreadable:${extract}`]; }
const errors = [];
if (current !== latest.sha256) errors.push(`source_extract_changed_since_recorded:${extract}`);
else if (sha256 && sha256 !== current) errors.push(`source_extract_changed_since_inventory:${extract}`);
try {
const lost = lostSince(prior.slice(0, -1).map(row => readShapes(projectDir, row)), readShapes(projectDir, latest));
// Loss that remains after a re-read from the source is reported (extract-integrity.json), not retried.
if (lost.length && latest.recordedBy !== 're-extract') errors.push(`source_extract_paths_lost:${extract}:${lost.length}`);
} catch (error) { errors.push(`${error.code || 'source_extract_shapes_missing'}:${extract}`); }
return errors;
}
// --- never block: repair, report, continue ----------------------------------------------------
function appendReport(projectDir, event) {
const file = path.join(projectDir, REPORT);
let report = { schemaVersion: 1, events: [] };
try { report = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { /* first event */ }
report.events.push(event);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file + '.tmp', JSON.stringify(report, null, 2) + '\n');
fs.renameSync(file + '.tmp', file);
}
// A hung source read cannot stall the task forever. Read per call so an operator can raise it.
const TIMEOUT_MS = 30 * 60 * 1000;
function runExtractor(projectDir, entity, { timeoutMs = Number(process.env.RP_REEXTRACT_TIMEOUT_MS) || TIMEOUT_MS } = {}) {
const script = path.join(projectDir, EXTRACTOR);
if (!fs.existsSync(script)) return Promise.resolve('extractor_missing');
return new Promise(resolve => {
// Output is not kept: it may carry source values.
const child = spawn(process.execPath, [script, '--entity', entity], { cwd: projectDir, stdio: 'ignore' });
const timer = setTimeout(() => { child.kill('SIGKILL'); resolve('extractor_timeout'); }, timeoutMs);
child.on('error', () => { clearTimeout(timer); resolve('extractor_failed'); });
child.on('exit', code => { clearTimeout(timer); resolve(code === 0 ? null : 'extractor_failed'); });
});
}
// The suspect extract and its manifest (and any partial `.tmp`) are moved aside before the re-read,
// so an extractor that reuses a final file whose manifest matches cannot hand the same bytes back.
// On a failed re-read they are put back: the run keeps what it had, and only this entity stops.
function siblingManifest(extract) {
const dir = path.posix.dirname(extract), base = path.posix.basename(extract).replace(/\.(ndjson|json)$/, '');
return `${dir}/${base}.manifest.json`;
}
function moveAside(projectDir, extract, manifestPath, tag) {
const moved = [];
for (const rel of [...new Set([extract, `${extract}.tmp`, manifestPath || siblingManifest(extract)])]) {
const file = inside(projectDir, rel);
if (!fs.existsSync(file)) continue;
const aside = `${file}.suspect-${tag}`;
fs.renameSync(file, aside);
moved.push({ file, aside });
}
return moved;
}
function putBack(moved) {
for (const { file, aside } of moved) { try { fs.rmSync(file, { force: true }); fs.renameSync(aside, file); } catch { /* left aside, named in the report */ } }
}
const version = row => (row ? { version: row.version, sha256: row.sha256, rows: row.rows } : null);
const RESTORE_ONLY = new Set(['source_extract_ledger_missing']);
// Make the extract trustworthy without blocking: record a first-seen extract, restore a missing
// ledger copy, and re-extract from the source when the extract changed, lost fields or its
// history cannot be verified. Fields still lost after re-extraction are reported and the run
// continues. Throws only `source_extract_unreadable` (re-extraction failed), for this entity.
async function ensureExtract(projectDir, { entity, extractPath, manifestPath = null, keyField = 'id', ledgerHead = null, sha256 = null, recordedBy = 'toolkit', now = () => new Date() }) {
const extract = relative(projectDir, extractPath);
const before = entries(projectDir, extract).at(-1) || null;
let problems = await extractErrors(projectDir, extract, { ledgerHead, sha256 });
if (problems.length === 1 && problems[0].startsWith('source_extract_unrecorded:')) {
await recordExtract(projectDir, { entity, extractPath: extract, keyField, recordedBy, now: now() });
problems = await extractErrors(projectDir, extract, { ledgerHead, sha256 });
}
if (problems.length && problems.every(code => RESTORE_ONLY.has(code.split(':')[0]))) {
writeLedger(projectDir, readLedger(projectDir).rows);
appendReport(projectDir, { at: now().toISOString(), entity, extractPath: extract, trigger: problems.map(code => code.split(':')[0]), action: 'ledger-restored', before: version(before), after: version(entries(projectDir, extract).at(-1)), lostPaths: [] });
problems = await extractErrors(projectDir, extract, { ledgerHead, sha256 });
}
// A changed extract is a new version; only lost fields or unverifiable history need the source.
if (problems.length === 1 && problems[0].startsWith('source_extract_changed_since_recorded:')) {
await recordExtract(projectDir, { entity, extractPath: extract, keyField, recordedBy, now: now() });
problems = await extractErrors(projectDir, extract, { ledgerHead, sha256 });
}
if (!problems.length) return { row: entries(projectDir, extract).at(-1), repaired: false };
const trigger = [...new Set(problems.map(code => code.split(':')[0]))];
const suspect = entries(projectDir, extract).at(-1) || before;
const moved = moveAside(projectDir, extract, manifestPath, (suspect?.sha256 || 'unrecorded').slice(0, 12));
let failure = await runExtractor(projectDir, entity);
if (!failure && !fs.existsSync(inside(projectDir, extract))) failure = 'extractor_no_output';
if (failure) putBack(moved);
else for (const { aside } of moved) fs.rmSync(aside, { force: true });
if (failure) {
appendReport(projectDir, { at: now().toISOString(), entity, extractPath: extract, trigger, action: 'refused', reason: failure, before: version(suspect), after: null, lostPaths: [], next: NEXT.source_extract_unreadable });
throw Object.assign(fail('source_extract_unreadable'), { reason: failure });
}
const row = await recordExtract(projectDir, { entity, extractPath: extract, keyField, recordedBy: 're-extract', replacesHead: trigger.includes('source_extract_ledger_head_missing') ? ledgerHead : null, now: now() });
appendReport(projectDir, { at: now().toISOString(), entity, extractPath: extract, trigger, action: 're-extracted', before: version(suspect), after: version(row),
lostPaths: row.lostPaths || [], ...(row.lostPaths?.length ? { next: NEXT.source_extract_fields_still_lost } : {}) });
return { row, repaired: true };
}
async function reportEvents(projectDir) {
try { return JSON.parse(await fs.promises.readFile(path.join(projectDir, REPORT), 'utf8')).events || []; } catch { return []; }
}
const NEXT = {
source_extract_unreadable: 'Requires Import Operator. Re-extraction from the source failed for this entity only; the rest of the import continues. Check source access, make src/extract/run-extract.js accept --entity <entity>, then rerun the import for this entity.',
source_extract_fields_still_lost: 'Requires Import Operator. The extract was re-read from the source and some unchanged records still lack fields an earlier extract had: the extractor drops them. Fix src/extract/run-extract.js to keep every source field, re-extract this entity and rerun its import.',
source_extract_unrecorded: 'Record the extract with `node scripts/extract-ledger.js record` right after writing it (the read-back inventory records it too).',
source_extract_changed_since_recorded: 'The extract file changed after the toolkit recorded it. Re-extract from the source and record it; never edit an extract in place.',
source_extract_changed_since_inventory: 'Rerun the read-back inventory on the current extract.',
source_extract_paths_lost: 'Records the source did not change lost fields since the previous extract. Re-extract from the source without dropping fields; a field with no target is kept by the mapping (extended field or CMS), never stripped.',
source_extract_ledger_broken: 'The extract ledger was edited. Restore it from the run; it is append-only toolkit state.',
source_extract_ledger_corrupt: 'The extract ledger was edited. Restore it from the run; it is append-only toolkit state.',
source_extract_ledger_missing: 'One ledger copy was deleted; it is restored from the other.',
source_extract_ledger_diverged: 'A ledger copy was edited; the extract is re-read from the source.',
source_extract_ledger_head_missing: 'The extract ledger no longer contains the version the read-back inventory recorded. Restore the ledger, or re-extract from the source and rerun the inventory.',
source_extract_shapes_missing: 'A recorded extract version lost its field record. Restore state/source-extract-ledger/ from the run.',
source_extract_shapes_changed: 'A recorded extract field record was edited. Restore state/source-extract-ledger/ from the run.',
};
const nextStep = code => NEXT[String(code).split(':')[0]] || null;
module.exports = { TIMEOUT_MS, LEDGER, SHAPES_DIR, MIRROR, REPORT, EXTRACTOR, CHANGE_MARKERS, shapePaths, measure, entries, head, recordExtract, extractErrors, ensureExtract, reportEvents, nextStep, fileDigest: (projectDir, file) => fileDigest(inside(projectDir, file)) };
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