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://mp-staging.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/plugin-cms-fallback.js
'use strict';
// CMS fallback for a recognized plugin capability: two gates, both required.
//
// 1. Eligibility (repository, human-signed): plugins/cms-fallback-eligible.json says nothing
// native fits this capability, CMS may keep its records, and what the merchant loses.
// 2. Approval (per migration, merchant): orchestration/decisions.json carries
// `pluginCmsFallback:<capability>` with the merchant's answer, bound to the exact proposal
// that was shown (`proposalDigest`). No agent, automation mode or repository entry supplies it.
//
// Everything that decides whether a CMS plan is still valid goes through this one module, so
// the validator, the decision writer, the classifier, the router and the write-time guard can
// never disagree about what "approved" or "fresh" means.
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const DECISION_PREFIX = 'pluginCmsFallback:';
const DECISION_VALUES = new Set(['approved', 'declined']);
const DIGEST_VERSION = 1;
const DEFAULT_PLUGINS_ROOT = path.resolve(__dirname, '..', 'resources', 'rp-source-wordpress', 'plugins');
const DEFAULT_TARGET_KNOWLEDGE_ROOT = path.resolve(__dirname, '..', 'resources', 'rp-target-wix', 'domains');
function pluginKnowledge() {
return require('../resources/rp-source-wordpress/lib/plugin-knowledge.js');
}
function isPlainObject(value) {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
// Canonical JSON: object keys sorted at every depth, arrays kept in order (callers sort the
// arrays whose order carries no meaning before hashing).
function canonicalize(value) {
if (Array.isArray(value)) return value.map(canonicalize);
if (isPlainObject(value)) {
const out = {};
for (const key of Object.keys(value).sort()) {
if (value[key] !== undefined) out[key] = canonicalize(value[key]);
}
return out;
}
return value === undefined ? null : value;
}
function sha256(value) {
return `sha256:${crypto.createHash('sha256').update(JSON.stringify(canonicalize(value))).digest('hex')}`;
}
function decisionKey(capability) {
return `${DECISION_PREFIX}${capability}`;
}
// Exact, case-sensitive prefix. A look-alike key is not this family and keeps the generic
// fail-closed decision checks.
function isCmsFallbackDecisionKey(key) {
return typeof key === 'string' && key.startsWith(DECISION_PREFIX);
}
function capabilityOfKey(key) {
return isCmsFallbackDecisionKey(key) ? key.slice(DECISION_PREFIX.length) : null;
}
function canonicalTargetRefsByEntity(map) {
const out = {};
if (!isPlainObject(map)) return out;
for (const key of Object.keys(map).sort()) {
out[key] = Array.isArray(map[key]) ? [...map[key]].map(String).sort() : [];
}
return out;
}
// The proposal binding: what the merchant was shown. A changed ref, a ref moved between
// entities, an added/removed entity, or a changed featureLoss sentence changes the digest.
function cmsFallbackProposalDigest(entry) {
return sha256({
capability: entry && entry.capability ? String(entry.capability) : null,
targetRefsByEntity: canonicalTargetRefsByEntity(entry && entry.targetRefsByEntity),
featureLoss: entry && typeof entry.featureLoss === 'string' ? entry.featureLoss : null,
});
}
function unionTargetRefs(targetRefsByEntity) {
return Array.from(new Set(Object.values(canonicalTargetRefsByEntity(targetRefsByEntity)).flat())).sort();
}
// A register entry the runtime may use. Unsigned or structurally incomplete entries are
// ignored (the row stays pending), exactly like the other signed registers.
function isUsableEligibilityEntry(entry) {
if (!isPlainObject(entry) || !entry.capability || !entry.decidedBy || !entry.decidedOn) return false;
if (typeof entry.featureLoss !== 'string' || entry.featureLoss.length === 0) return false;
if (!isPlainObject(entry.targetRefsByEntity) || Object.keys(entry.targetRefsByEntity).length === 0) return false;
return Object.values(entry.targetRefsByEntity).every((refs) => Array.isArray(refs) && refs.length > 0
&& refs.every((ref) => typeof ref === 'string' && ref.startsWith('cms/')));
}
function eligibilityByCapability(entries = []) {
const map = new Map();
for (const entry of entries || []) {
if (isUsableEligibilityEntry(entry)) map.set(entry.capability, entry);
}
return map;
}
// The audit timestamp the writer records (`Date#toISOString()`): a full ISO-8601 UTC/offset
// date-time that is also a real calendar instant. Anything else is a hand edit.
const ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;
function isValidDecidedAt(decidedAt) {
if (typeof decidedAt !== 'string' || !ISO_DATE_TIME.test(decidedAt)) return false;
const time = Date.parse(decidedAt);
if (Number.isNaN(time)) return false;
// Reject calendar roll-over such as 2026-02-31 (Date.parse would accept it as March 3).
const [year, month, day] = decidedAt.slice(0, 10).split('-').map(Number);
const probe = new Date(Date.UTC(year, month - 1, day));
return probe.getUTCFullYear() === year && probe.getUTCMonth() === month - 1 && probe.getUTCDate() === day;
}
// Shape check for one `pluginCmsFallback:*` entry. Shared by validateDecisions (quarantine),
// the classifier, the writer's stale check and the write-time guard.
function cmsFallbackDecisionShape(key, value) {
if (!isPlainObject(value)) return { ok: false, problem: 'not-object' };
const capability = capabilityOfKey(key);
if (!capability) return { ok: false, problem: 'capability-missing' };
if (!DECISION_VALUES.has(value.value)) return { ok: false, problem: 'value-invalid' };
if (value.source !== 'user') return { ok: false, problem: 'source-not-user' };
if (!isValidDecidedAt(value.decidedAt)) return { ok: false, problem: 'decided-at-invalid' };
if (typeof value.approvedBy !== 'string' || value.approvedBy.trim().length === 0) {
return { ok: false, problem: 'approved-by-missing' };
}
if (!isPlainObject(value.proposal) || !isPlainObject(value.proposal.targetRefsByEntity)
|| typeof value.proposal.featureLoss !== 'string') {
return { ok: false, problem: 'proposal-missing' };
}
const rehash = cmsFallbackProposalDigest({ capability, ...value.proposal });
if (typeof value.proposalDigest !== 'string' || rehash !== value.proposalDigest) {
return { ok: false, problem: 'digest-mismatch' };
}
return { ok: true, problem: null };
}
// What the stored answer means against the current register entry:
// none | approved | declined | stale (valid shape, different proposal) | invalid (quarantined)
function evaluateCmsFallbackDecision({ capability, entry = null, decisions = {} }) {
const key = decisionKey(capability);
const raw = decisions ? decisions[key] : undefined;
if (raw === undefined) return { state: 'none', key, raw: null };
const shape = cmsFallbackDecisionShape(key, raw);
if (!shape.ok) return { state: 'invalid', key, raw, problem: shape.problem };
if (!entry || raw.proposalDigest !== cmsFallbackProposalDigest(entry)) return { state: 'stale', key, raw };
return { state: raw.value, key, raw };
}
function cmsFallbackDecisionKeys(decisions = {}) {
return Object.keys(decisions || {}).filter(isCmsFallbackDecisionKey).sort();
}
// ---- operator override: CMS instead of a native target -------------------------------
//
// The signed register above covers the DEFAULT fallback only: capabilities nothing native fits.
// An operator may also choose a private CMS archive for a capability a native Wix target claims.
// That answer is `mappingTargetOverride:<capability>` = { value: 'cms', source: 'user',
// approvedBy, decidedAt, rationale, proposal, proposalDigest }, bound to the offer the native
// coverage row shows (`mappingTargetOverride` on the row). No register entry, agent or
// automation mode supplies it; one-click never records it.
const OVERRIDE_PREFIX = 'mappingTargetOverride:';
const OVERRIDE_VALUES = new Set(['cms']);
const OVERRIDE_TARGET_REFS = Object.freeze(['cms/collection', 'cms/data-item']);
function overrideDecisionKey(capability) {
return `${OVERRIDE_PREFIX}${capability}`;
}
function isMappingTargetOverrideKey(key) {
return typeof key === 'string' && key.startsWith(OVERRIDE_PREFIX);
}
function overrideCapabilityOfKey(key) {
return isMappingTargetOverrideKey(key) ? key.slice(OVERRIDE_PREFIX.length) : null;
}
function mappingTargetOverrideKeys(decisions = {}) {
return Object.keys(decisions || {}).filter(isMappingTargetOverrideKey).sort();
}
// The offer for one natively routed capability: every entity it resolves to goes to a private
// CMS collection, and the featureLoss sentence names the native target given up.
function mappingTargetOverrideProposal({ capability, entityKeys = [], nativeTargetRefs = [] } = {}) {
const targetRefsByEntity = canonicalTargetRefsByEntity(Object.fromEntries(
[...entityKeys].map((key) => [key, [...OVERRIDE_TARGET_REFS]]),
));
const native = [...nativeTargetRefs].map(String).sort();
const featureLoss = `Records are kept as private Wix CMS data instead of ${native.length ? native.join(', ') : 'the native Wix target'}; that Wix feature does not receive them or act on them.`;
return { capability, targetRefsByEntity, featureLoss, nativeTargetRefs: native };
}
function mappingTargetOverrideShape(key, value) {
if (!isPlainObject(value)) return { ok: false, problem: 'not-object' };
const capability = overrideCapabilityOfKey(key);
if (!capability) return { ok: false, problem: 'capability-missing' };
if (!OVERRIDE_VALUES.has(value.value)) return { ok: false, problem: 'value-invalid' };
if (value.source !== 'user') return { ok: false, problem: 'source-not-user' };
if (!isValidDecidedAt(value.decidedAt)) return { ok: false, problem: 'decided-at-invalid' };
if (typeof value.approvedBy !== 'string' || value.approvedBy.trim().length === 0) {
return { ok: false, problem: 'approved-by-missing' };
}
if (!isPlainObject(value.proposal) || !isPlainObject(value.proposal.targetRefsByEntity)
|| typeof value.proposal.featureLoss !== 'string') {
return { ok: false, problem: 'proposal-missing' };
}
const rehash = cmsFallbackProposalDigest({ capability, ...value.proposal });
if (typeof value.proposalDigest !== 'string' || rehash !== value.proposalDigest) {
return { ok: false, problem: 'digest-mismatch' };
}
return { ok: true, problem: null };
}
// What a stored override means against the offer computed now:
// none | cms | stale (valid shape, different offer) | invalid (quarantined)
function evaluateMappingTargetOverride({ capability, proposal = null, decisions = {} }) {
const key = overrideDecisionKey(capability);
const raw = decisions ? decisions[key] : undefined;
if (raw === undefined) return { state: 'none', key, raw: null };
const shape = mappingTargetOverrideShape(key, raw);
if (!shape.ok) return { state: 'invalid', key, raw, problem: shape.problem };
if (!proposal || raw.proposalDigest !== cmsFallbackProposalDigest(proposal)) return { state: 'stale', key, raw };
return { state: raw.value, key, raw };
}
// The mapping-review notice for a native route whose target has a side effect the operator
// should weigh against the CMS override. Keyed by target ref; null when none applies.
const NATIVE_ROUTE_NOTICES = Object.freeze({
'forms/form-submission': 'Old entries will be added to Wix Forms. While they import, the toolkit tries to turn off the form\'s submission emails to you and turns them back on afterwards. If it can\'t, you may get one email per old entry. Choose a private CMS archive instead to avoid Wix Forms entirely.',
});
function nativeRouteNotices(targetRefs = []) {
return Array.from(new Set(targetRefs || [])).sort()
.map((ref) => NATIVE_ROUTE_NOTICES[ref]).filter(Boolean);
}
// ---- resolution-input digest -----------------------------------------------------------
function entitiesForCapability(entities, capability) {
const list = entities || [];
const hasAttribution = list.some((entity) => entity && entity.capability);
return hasAttribution ? list.filter((entity) => entity.capability === capability) : list;
}
// The `<plugin>/<entity>` keys the register must cover for this capability, from the entity
// declarations the classifier will actually use.
function entityKeysForCapability(plugins, capability) {
const keys = [];
for (const plugin of plugins || []) {
for (const entity of entitiesForCapability(plugin.entities, capability)) {
keys.push(`${plugin.plugin}/${entity.entity}`);
}
}
return keys.sort();
}
function signedRegisterEntry(entries, capability, { requireSignature = true } = {}) {
const entry = (entries || []).find((candidate) => candidate && candidate.capability === capability);
if (!entry) return null;
if (requireSignature && !(entry.decidedBy && entry.decidedOn)) return null;
return entry;
}
function resolveTargetKnowledge(targetKnowledge) {
return typeof targetKnowledge === 'function' ? targetKnowledge() : targetKnowledge;
}
/**
* Build the canonical input set that decides every in-scope capability's route.
*
* In scope: declared by a detected plugin AND (has a register entry OR is named by a
* `pluginCmsFallback:*` key). Ordinary plugin rows are out of scope, so they never trigger the
* freshness check. `targetKnowledge` may be a value or a loader function; it is only loaded when
* at least one capability is in scope.
*/
function cmsFallbackResolutionInputs({
detectedPlugins = [],
profiles = [],
targetKnowledge = null,
registers = {},
decisions = {},
} = {}) {
const profileBySlug = new Map((profiles || []).map((profile) => [profile.plugin, profile]));
const eligibleEntries = registers.cmsFallbackEligible || [];
const requiresDevelopment = registers.requiresDevelopment || [];
const noMigrationCapabilities = (registers.noMigrationNeeded && registers.noMigrationNeeded.capabilities)
|| registers.noMigrationCapabilities || [];
const keys = cmsFallbackDecisionKeys(decisions);
const overrideKeys = mappingTargetOverrideKeys(decisions);
const keyedCapabilities = new Set([...keys.map(capabilityOfKey), ...overrideKeys.map(overrideCapabilityOfKey)].filter(Boolean));
const registeredCapabilities = new Set(eligibleEntries.filter(Boolean).map((entry) => entry.capability));
const declaredBy = new Map();
for (const detected of detectedPlugins || []) {
const slug = detected && detected.plugin;
if (!slug) continue;
const profile = profileBySlug.get(slug) || null;
const capabilities = new Set([...(detected.capabilities || []), ...((profile && profile.capabilities) || [])]);
for (const capability of capabilities) {
if (!declaredBy.has(capability)) declaredBy.set(capability, []);
declaredBy.get(capability).push({ slug, profile });
}
}
const inScope = Array.from(declaredBy.keys())
.filter((capability) => registeredCapabilities.has(capability) || keyedCapabilities.has(capability))
.sort();
let knowledge = null;
if (inScope.length > 0) {
try {
knowledge = resolveTargetKnowledge(targetKnowledge);
} catch (error) {
knowledge = { knownRefs: new Set(), capabilityRefs: new Map(), manualStepsByRef: new Map(), loadError: error.message };
}
}
const knownRefs = (knowledge && knowledge.knownRefs) || new Set();
const capabilityRefs = (knowledge && knowledge.capabilityRefs) || new Map();
const manualStepsByRef = (knowledge && knowledge.manualStepsByRef) || new Map();
const loaded = Boolean(knowledge) && !knowledge.loadError;
const refFacts = (refs) => Object.fromEntries([...refs].sort().map((ref) => [ref, {
known: knownRefs.has(ref),
manualSteps: manualStepsByRef.has(ref),
}]));
const capabilities = {};
for (const capability of inScope) {
const nativeRefs = [...(capabilityRefs.get(capability) || [])].sort();
capabilities[capability] = {
targetKnowledge: { loaded, nativeRefs: refFacts(nativeRefs) },
profiles: declaredBy.get(capability)
.sort((a, b) => a.slug.localeCompare(b.slug))
.map(({ slug, profile }) => (profile ? {
plugin: slug,
status: 'present',
capabilities: [...(profile.capabilities || [])].sort(),
entities: (profile.entities || []).map((entity) => ({
entity: entity.entity || null,
route: entity.route || null,
channel: entity.channel || null,
capability: entity.capability || null,
candidateTargetRefs: [...(entity.candidateTargetRefs || [])],
refs: refFacts(entity.candidateTargetRefs || []),
})).sort((a, b) => String(a.entity).localeCompare(String(b.entity))),
} : { plugin: slug, status: 'profile-missing' })),
requiresDevelopment: signedRegisterEntry(requiresDevelopment, capability, { requireSignature: false }),
noMigrationNeeded: signedRegisterEntry(noMigrationCapabilities, capability),
eligibility: signedRegisterEntry(eligibleEntries, capability, { requireSignature: false }),
decision: decisions && decisions[decisionKey(capability)] !== undefined ? decisions[decisionKey(capability)] : null,
// Only present when an override is stored, so projects without one keep their digest.
...(decisions && decisions[overrideDecisionKey(capability)] !== undefined
? { mappingTargetOverride: decisions[overrideDecisionKey(capability)] } : {}),
};
}
// Every key whose capability is not in scope is carried raw, so writing, editing or removing
// any such key changes the digest too.
const otherDecisions = {};
for (const key of keys) {
if (!capabilities[capabilityOfKey(key)]) otherDecisions[key] = decisions[key];
}
for (const key of overrideKeys) {
if (!capabilities[overrideCapabilityOfKey(key)]) otherDecisions[key] = decisions[key];
}
return { version: DIGEST_VERSION, capabilities, otherDecisions };
}
function cmsFallbackInputsDigest(inputs) {
return sha256(inputs);
}
// ---- project loading (router, write-time guard, reclassifier) ---------------------------
function readJsonOrNull(filePath) {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch {
return null;
}
}
function loadTargetKnowledgeSummary(targetKnowledgeRoot = DEFAULT_TARGET_KNOWLEDGE_ROOT) {
try {
const { knowledgeSummary } = require('../resources/rp-target-wix/lib/domain-knowledge.js');
return knowledgeSummary(targetKnowledgeRoot);
} catch (error) {
return { knownRefs: new Set(), capabilityRefs: new Map(), manualStepsByRef: new Map(), loadError: error.message };
}
}
function loadCmsFallbackRegisters(pluginsRoot = DEFAULT_PLUGINS_ROOT) {
const knowledge = pluginKnowledge();
return {
cmsFallbackEligible: knowledge.loadCmsFallbackEligible(pluginsRoot).capabilities || [],
requiresDevelopment: knowledge.loadRequiresDevelopment(pluginsRoot).capabilities || [],
noMigrationNeeded: knowledge.loadNoMigrationNeeded(pluginsRoot),
};
}
// The canonical artifacts a WordPress project carries: the promoted coverage copy the mapper
// reads, and the adapter's raw capture that holds the detection snapshot.
function projectPaths(projectDir) {
return {
coverage: path.join(projectDir, 'discovery', 'plugin-coverage.json'),
rawCoverage: path.join(projectDir, 'data', 'wp-discovery', 'plugin-coverage.json'),
inventory: path.join(projectDir, 'data', 'wp-discovery', 'plugin-inventory.json'),
canonicalInventory: path.join(projectDir, 'discovery', 'plugin-inventory.json'),
mappingPlan: path.join(projectDir, 'mapping', 'mapping-plan.json'),
setupPlan: path.join(projectDir, 'setup', 'setup-plan.json'),
};
}
function detectedPluginsOf(inventory) {
return ((inventory && inventory.detected) || []).map((plugin) => ({
plugin: plugin.plugin,
capabilities: [...(plugin.capabilities || [])],
}));
}
function computeCurrentDigest({ inventory, decisions = {}, pluginsRoot = DEFAULT_PLUGINS_ROOT, targetKnowledgeRoot = DEFAULT_TARGET_KNOWLEDGE_ROOT, targetKnowledge = null }) {
const inputs = cmsFallbackResolutionInputs({
detectedPlugins: detectedPluginsOf(inventory),
profiles: pluginKnowledge().loadProfiles(pluginsRoot),
targetKnowledge: targetKnowledge || (() => loadTargetKnowledgeSummary(targetKnowledgeRoot)),
registers: loadCmsFallbackRegisters(pluginsRoot),
decisions: decisions || {},
});
return { inputs, digest: cmsFallbackInputsDigest(inputs) };
}
function digestOf(artifact) {
return artifact && artifact.inputs && typeof artifact.inputs.cmsFallbackDigest === 'string'
? artifact.inputs.cmsFallbackDigest
: null;
}
/**
* The router's freshness chain. Returns null when the project has no plugin coverage (nothing
* to check), otherwise { digest, stale: null | 'coverage' | 'mapping' | 'setup' }.
*/
function checkCmsFallbackFreshness(projectDir, { decisions = {}, pluginsRoot, targetKnowledgeRoot } = {}) {
const paths = projectPaths(projectDir);
if (!fs.existsSync(paths.coverage)) return null;
const coverage = readJsonOrNull(paths.coverage);
const inventory = readJsonOrNull(paths.inventory) || readJsonOrNull(paths.canonicalInventory);
if (!coverage || !inventory) return { digest: null, stale: 'coverage', missing: !inventory ? 'plugin-inventory' : 'plugin-coverage' };
const { digest } = computeCurrentDigest({
inventory,
decisions,
pluginsRoot: pluginsRoot || DEFAULT_PLUGINS_ROOT,
targetKnowledgeRoot: targetKnowledgeRoot || DEFAULT_TARGET_KNOWLEDGE_ROOT,
});
if (digestOf(coverage) !== digest) return { digest, stale: 'coverage' };
if (fs.existsSync(paths.mappingPlan) && digestOf(readJsonOrNull(paths.mappingPlan)) !== digest) {
return { digest, stale: 'mapping' };
}
if (fs.existsSync(paths.setupPlan) && digestOf(readJsonOrNull(paths.setupPlan)) !== digest) {
return { digest, stale: 'setup' };
}
return { digest, stale: null };
}
function readJsonStrict(filePath) {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}
function writeJsonAtomicSync(filePath, value) {
const tempPath = `${filePath}.${process.pid}.tmp`;
fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
fs.renameSync(tempPath, filePath);
}
// rp-mapper and rp-setup-discovery bind the plans they write to the coverage they were built
// from: mapping-plan.json copies discovery/plugin-coverage.json's digest, setup-plan.json copies
// the mapping plan's.
function stampPlanDigest(projectDir, plan) {
const paths = projectPaths(projectDir);
const [sourcePath, targetPath] = plan === 'mapping'
? [paths.coverage, paths.mappingPlan]
: plan === 'setup'
? [paths.mappingPlan, paths.setupPlan]
: [null, null];
if (!sourcePath) throw new Error('stamp-plan requires --plan mapping|setup');
if (!fs.existsSync(targetPath)) throw new Error(`${path.relative(projectDir, targetPath)} does not exist; write the plan first`);
if (!fs.existsSync(sourcePath)) {
// No plugin coverage in this project: nothing to bind the plan to.
return { stamped: false, reason: `${path.relative(projectDir, sourcePath)} not present` };
}
const source = readJsonStrict(sourcePath);
const digest = source && source.inputs && source.inputs.cmsFallbackDigest;
if (typeof digest !== 'string' && plan === 'setup' && !fs.existsSync(paths.coverage)) {
// No plugin coverage: the mapping plan has no digest to copy, and the router's freshness
// chain (checkCmsFallbackFreshness) checks nothing either. A plugin-covered project with a
// missing digest still falls through to the error below.
return { stamped: false, reason: 'no plugin coverage; nothing to bind the setup plan to' };
}
if (typeof digest !== 'string') {
throw new Error(`${path.relative(projectDir, sourcePath)} carries no inputs.cmsFallbackDigest; regenerate it before stamping`);
}
const target = readJsonStrict(targetPath);
target.inputs = { ...(target.inputs || {}), cmsFallbackDigest: digest };
writeJsonAtomicSync(targetPath, target);
return { stamped: true, plan, cmsFallbackDigest: digest };
}
// ---- coverage rows -----------------------------------------------------------------------
function totalRecords(row) {
return Object.values((row && row.recordCounts) || {}).reduce((sum, value) => sum + (Number.isFinite(value) ? value : 0), 0);
}
function isApprovedCmsFallbackRow(row) {
return Boolean(row) && row.status === 'migration-planned' && row.via === 'cms'
&& Boolean(row.cmsFallback) && row.cmsFallback.functionalityRestored === false;
}
function isEligibleCmsFallbackRow(row) {
return Boolean(row) && Boolean(row.cmsFallback) && typeof row.cmsFallback.proposalDigest === 'string';
}
// The proposal exactly as the coverage row shows it (pending: proposed refs; approved: the refs
// it was approved with). The writer reads it from here so nobody retypes it.
function proposalFromRow(row) {
const fallback = (row && row.cmsFallback) || {};
return {
targetRefsByEntity: canonicalTargetRefsByEntity(fallback.proposedTargetRefsByEntity || fallback.targetRefsByEntity),
featureLoss: typeof fallback.featureLoss === 'string' ? fallback.featureLoss : null,
};
}
// ---- write-time guard -------------------------------------------------------------------
/**
* Defence in depth behind the router: may the importer write CMS records for each eligible
* capability? Allowed only when the coverage row is an approved CMS fallback whose approval
* passes the shape check and matches the current register entry, AND the current resolution
* digest equals the one carried by plugin-coverage, the mapping plan and the setup plan.
*/
//
// `refusals` lists the capabilities a write was actually refused for: those in `attempted` (the
// capabilities the caller's plan writes to CMS) when given, otherwise those whose coverage row
// still claims an approved CMS plan. A pending row with nothing planned is not a refusal.
function cmsFallbackWriteGuard(projectDir, { decisions = null, pluginsRoot, targetKnowledgeRoot, attempted = null } = {}) {
const paths = projectPaths(projectDir);
const root = pluginsRoot || DEFAULT_PLUGINS_ROOT;
const coverage = readJsonOrNull(paths.coverage) || readJsonOrNull(paths.rawCoverage);
const decisionsFile = decisions || readJsonOrNull(path.join(projectDir, 'orchestration', 'decisions.json')) || {};
const rows = (coverage && coverage.capabilities) || [];
const eligible = eligibilityByCapability(loadCmsFallbackRegisters(root).cmsFallbackEligible);
const capabilities = new Set();
for (const row of rows) {
if (row && row.recognized && (eligible.has(row.capability) || isEligibleCmsFallbackRow(row))) capabilities.add(row.capability);
}
const attemptedSet = attempted ? new Set(attempted) : null;
// Derived/unrecognized CMS rows (confidence: proposed, decided at the mapping review) are not
// this gate's business; a RECOGNIZED capability written to CMS always is.
if (attemptedSet) {
for (const capability of attemptedSet) {
if (eligible.has(capability) || rows.some((row) => row && row.recognized && row.capability === capability)) capabilities.add(capability);
}
}
if (capabilities.size === 0) return { capabilities: {}, refusals: [] };
const inventory = readJsonOrNull(paths.inventory) || readJsonOrNull(paths.canonicalInventory);
const current = inventory
? computeCurrentDigest({ inventory, decisions: decisionsFile, pluginsRoot: root, targetKnowledgeRoot: targetKnowledgeRoot || DEFAULT_TARGET_KNOWLEDGE_ROOT }).digest
: null;
const chain = {
coverage: digestOf(coverage),
mappingPlan: digestOf(readJsonOrNull(paths.mappingPlan)),
setupPlan: digestOf(readJsonOrNull(paths.setupPlan)),
};
const fresh = Boolean(current) && chain.coverage === current && chain.mappingPlan === current && chain.setupPlan === current;
const result = {};
const refusals = [];
for (const capability of Array.from(capabilities).sort()) {
const row = rows.find((candidate) => candidate.capability === capability && candidate.recognized) || null;
const entry = eligible.get(capability) || null;
const evaluation = evaluateCmsFallbackDecision({ capability, entry, decisions: decisionsFile });
const entryDigest = entry ? cmsFallbackProposalDigest(entry) : null;
let reason = null;
if (!isApprovedCmsFallbackRow(row)) reason = 'coverage-row-not-approved-cms';
else if (row.cmsFallback.override === true) reason = overrideRowRefusal(capability, row, decisionsFile, fresh);
else if (!entry) reason = 'eligibility-missing';
else if (evaluation.state !== 'approved') reason = `decision-${evaluation.state}`;
else if (row.cmsFallback.proposalDigest !== entryDigest) reason = 'coverage-proposal-stale';
else if (!fresh) reason = 'resolution-inputs-changed';
const allowed = reason === null;
result[capability] = { allowed, reason, targetRefs: allowed ? [...(row.targetRefs || [])] : [] };
const wasAttempted = attemptedSet ? attemptedSet.has(capability) : isApprovedCmsFallbackRow(row);
if (!allowed && wasAttempted) {
refusals.push({ capability, reason, recordCount: totalRecords(row), targetRefs: unionTargetRefs(proposalFromRow(row).targetRefsByEntity) });
}
}
return { capabilities: result, refusals, digest: { current, ...chain } };
}
// An operator-override CMS row: the stored override must be valid and bound to the offer the row
// carries, and the resolution chain must be fresh (it covers profiles, target knowledge and the
// override itself, so a row built from other inputs is refused).
function overrideRowRefusal(capability, row, decisions, fresh) {
const proposal = { capability, targetRefsByEntity: row.cmsFallback.targetRefsByEntity, featureLoss: row.cmsFallback.featureLoss };
if (row.cmsFallback.proposalDigest !== cmsFallbackProposalDigest(proposal)) return 'coverage-proposal-stale';
const evaluation = evaluateMappingTargetOverride({ capability, proposal, decisions });
if (evaluation.state !== 'cms') return `override-${evaluation.state}`;
return fresh ? null : 'resolution-inputs-changed';
}
// ---- completion operator actions --------------------------------------------------------
const DEADLINE = 'before DNS change';
function refsText(refs) {
return refs && refs.length ? refs.join(', ') : 'CMS collections';
}
/**
* Operator actions for every eligible capability, derived from the current coverage rows, the
* write-time guard's refusals, and the CMS writes recorded by the previous completion report.
* Never deletes or rewrites CMS data; withdrawn data is handed to the Cutover Operator.
*/
function cmsFallbackOperatorActions({ coverage = null, refusals = [], previousWrites = [], writes = [] } = {}) {
const rows = ((coverage && coverage.capabilities) || []).filter((row) => row && row.recognized && isEligibleCmsFallbackRow(row));
const refused = new Map((refusals || []).map((refusal) => [refusal.capability, refusal]));
const actions = [];
for (const row of rows) {
const capability = row.capability;
const records = totalRecords(row);
const proposal = proposalFromRow(row);
if (refused.has(capability)) continue;
if (isApprovedCmsFallbackRow(row) && row.cmsFallback.override === true) {
actions.push({
code: 'mapping-target-override-archived-in-cms',
severity: 'medium',
action: `${capability}: records were archived in a private Wix CMS collection (${refsText(row.targetRefs)}) because the operator chose CMS over ${refsText(row.cmsFallback.nativeTargetRefs)}. ${proposal.featureLoss || ''} Review it; dismiss if that is still what you want.`.replace(/\s+/g, ' ').trim(),
deadlineReason: DEADLINE,
entity: capability,
affectedCount: records,
});
continue;
}
if (isApprovedCmsFallbackRow(row)) {
actions.push({
code: 'plugin-cms-fallback-feature-absent',
severity: 'medium',
action: `${capability}: records were archived in Wix CMS (${refsText(row.targetRefs)}) with the merchant's approval; the plugin's feature is not restored. ${proposal.featureLoss || ''} Rebuild or replace that feature in Wix; a reconciled CMS collection does not resolve this item.`.replace(/\s+/g, ' ').trim(),
deadlineReason: DEADLINE,
entity: capability,
affectedCount: records,
});
continue;
}
const declined = row.reason === 'cms-fallback-declined';
actions.push({
code: declined ? 'plugin-cms-fallback-declined' : 'plugin-cms-fallback-undecided',
severity: records > 0 ? 'high' : 'low',
action: declined
? `${capability}: the merchant declined archiving these records in CMS, so ${records} record(s) were not migrated. Settle the capability at the mapping review (another verdict) or accept that the data stays in the source.`
: `${capability}: archiving these records in CMS is awaiting the merchant's decision (${row.reason || 'undecided'}), so ${records} record(s) were not migrated. Ask the merchant at the mapping review to approve or decline the CMS fallback.`,
deadlineReason: DEADLINE,
entity: capability,
affectedCount: records,
});
}
for (const refusal of refusals || []) {
actions.push({
code: 'plugin-cms-fallback-write-refused',
severity: 'high',
action: `Requires Import Operator: CMS writes for ${refusal.capability} were refused (${refusal.reason}); zero records were written. Rerun from the orchestration router so the coverage, mapping plan and setup plan are regenerated, then import again.`,
deadlineReason: DEADLINE,
entity: refusal.capability,
affectedCount: Number.isFinite(refusal.recordCount) ? refusal.recordCount : 0,
});
}
const currentlyApproved = new Set(rows.filter((row) => isApprovedCmsFallbackRow(row) && !refused.has(row.capability)).map((row) => row.capability));
const writtenNow = new Set((writes || []).map((write) => write.capability));
for (const write of previousWrites || []) {
if (!write || !write.capability || !(write.count > 0)) continue;
if (currentlyApproved.has(write.capability) || writtenNow.has(write.capability)) continue;
actions.push({
code: 'plugin-cms-fallback-withdrawn',
severity: 'high',
action: `${write.capability}: ${write.count} record(s) were written to CMS (${refsText(write.collections)}) under an approval that no longer applies. Nothing was deleted. Cutover Operator: keep or remove that CMS data by hand in Business Manager.`,
deadlineReason: DEADLINE,
entity: write.capability,
affectedCount: write.count,
});
}
return actions;
}
module.exports = {
DECISION_PREFIX,
DECISION_VALUES,
DEFAULT_PLUGINS_ROOT,
DEFAULT_TARGET_KNOWLEDGE_ROOT,
canonicalize,
decisionKey,
isCmsFallbackDecisionKey,
capabilityOfKey,
canonicalTargetRefsByEntity,
cmsFallbackProposalDigest,
unionTargetRefs,
isUsableEligibilityEntry,
eligibilityByCapability,
cmsFallbackDecisionShape,
evaluateCmsFallbackDecision,
cmsFallbackDecisionKeys,
entitiesForCapability,
entityKeysForCapability,
cmsFallbackResolutionInputs,
cmsFallbackInputsDigest,
loadTargetKnowledgeSummary,
loadCmsFallbackRegisters,
projectPaths,
detectedPluginsOf,
computeCurrentDigest,
checkCmsFallbackFreshness,
stampPlanDigest,
totalRecords,
isApprovedCmsFallbackRow,
isEligibleCmsFallbackRow,
proposalFromRow,
cmsFallbackWriteGuard,
cmsFallbackOperatorActions,
OVERRIDE_TARGET_REFS,
overrideDecisionKey,
isMappingTargetOverrideKey,
overrideCapabilityOfKey,
mappingTargetOverrideKeys,
mappingTargetOverrideProposal,
mappingTargetOverrideShape,
evaluateMappingTargetOverride,
nativeRouteNotices,
};
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Wix
- Publisher
- Wix (Official)
- Source
- wix/skills · skills/wix-replatform · commit d168bc2
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Wix.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download wix-replatform.zip