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/orchestration-router.js
'use strict';
const fs = require('node:fs/promises');
const path = require('node:path');
const { validateArtifacts, explicitRunBlocker } = require('./orchestration-state.js');
const { getDecisionValue, isEditorSiteType, isExplicitUserOneClick, isKnownSourceMode } = require('./orchestration-decisions.js');
const { destinationGate, publicationRecheckGate } = require('./destination-route.js');
const { validateWebsiteHandoff } = require('./website-handoff.js');
const { statEnvKeys, readEnvFile } = require('./config-env.js');
const { hashArtifact } = require('./artifact-freshness.js');
const { validatePlanShape, validateSetupRequirementsShape, validateSetupVerification } = require('./setup-verification.js');
const { NOTIFICATION_MUTE_QUESTION, readNotificationMute, setupPlanMuteMismatch } = require('./notification-mute.js');
const { validateManifest } = require('./execution-manifest.js');
const { QUICK_IMPORT_STARTED_MARKER, validateQuickExecutionManifest } = require('../resources/rp-quick-runtime/lib/import-progress.js');
const { checkCmsFallbackFreshness } = require('./plugin-cms-fallback.js');
const {
classifyFinalizedRun,
loadMigrationCompletionInputs,
validateFrontendCompletion,
validateMigrationCompletion,
} = require('./migration-completion.js');
const siteRegional = require('./site-regional.js');
const { readReport: readMigrationReview, readLatestHandoff } = require('./migration-review.js');
const { pendingUserActionGate } = require('./user-actions.js');
const { localPreflightChecks } = require('./orchestration-preflight.js');
const { SESSION_RECEIPT_FILE } = require('./source-access.js');
const { readReconciliation, censusReconciliationFreshness, mappingApprovalBound, reconcileSourceCoverageForMapping } = require('./census-reconciliation.js');
const { readCoverageContract, reconcileProject, SourceCoverageError } = require('./source-coverage.js');
async function exists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
async function readJson(filePath) {
try {
return JSON.parse(await fs.readFile(filePath, 'utf8'));
} catch {
return null;
}
}
// Rules for the two LLM-assisted outputs: parseable JSON whose top level is a
// non-array object. Nothing else is read (no versioned contract exists; mapping row shape is
// owned by the tolerant `readEntityMappings` consumer).
function validateSourceSchemaShape(value) {
return value && typeof value === 'object' && !Array.isArray(value)
? { ok: true, errors: [] }
: { ok: false, errors: ['source-schema.json must be a JSON object'] };
}
function validateMappingPlanShape(value) {
return value && typeof value === 'object' && !Array.isArray(value)
? { ok: true, errors: [] }
: { ok: false, errors: ['mapping/mapping-plan.json must be a JSON object'] };
}
function setupPlanRule(value, projectDir) {
const result = validatePlanShape(value, projectDir);
return { ok: result.ok, errors: result.reasons };
}
// Reads each gated output at most once per route. `present: false` only for a missing file;
// anything that exists but cannot be parsed is present with `parseError`.
function createArtifactReader(projectDir) {
const cache = new Map();
return async function readArtifact(relativePath) {
if (cache.has(relativePath)) return cache.get(relativePath);
let entry;
try {
const raw = await fs.readFile(path.join(projectDir, relativePath), 'utf8');
try {
entry = { present: true, value: JSON.parse(raw) };
} catch (error) {
entry = { present: true, value: null, parseError: `invalid JSON: ${error.message}` };
}
} catch (error) {
entry = error && error.code === 'ENOENT'
? { present: false, value: null }
: { present: true, value: null, parseError: `unreadable: ${(error && error.code) || error}` };
}
cache.set(relativePath, entry);
return entry;
};
}
// Missing → `{ present: false }` (caller keeps its existing route). Present but
// failing its rule → `{ present: true, errors }`. Validation is skipped once backend
// accounting exists: upstream outputs are history then, and keep existence-only behavior.
async function checkGatedOutput(readArtifact, relativePath, rule, { validate }) {
const entry = await readArtifact(relativePath);
if (!entry.present) return { present: false, errors: null };
if (!validate) return { present: true, errors: null };
if (entry.parseError) return { present: true, errors: [entry.parseError] };
const result = rule(entry.value);
return { present: true, errors: result.ok ? null : result.errors };
}
function invalidOutputRoute(reason, nextResource, errors) {
return { ok: true, nextState: 'blocked', nextResource, reason, errors, blocking: true };
}
// The setup plan mutes exactly when the answer says so; otherwise setup discovery
// regenerates it before any setup write. A legacy run keeps the plan it already ran.
async function muteMismatchRoute(readArtifact, notificationMute) {
if (notificationMute.source === 'legacy_config') return null;
const mismatch = setupPlanMuteMismatch(notificationMute, (await readArtifact(path.join('setup', 'setup-plan.json'))).value);
return mismatch ? { ok: true, nextState: 'setup_discovery_running', nextResource: 'resources/rp-setup-discovery/', reason: mismatch.code } : null;
}
async function nonEmptyFile(filePath, minBytes = 1) {
try {
const stat = await fs.stat(filePath);
return stat.isFile() && stat.size >= minBytes;
} catch {
return false;
}
}
// Existence/size only — the router never reads or scans these files. Sample
// journals and a mirror-seeded crosswalk are deliberately not evidence.
const QUICK_CROSSWALKS = {
woocommerce: 'state/crosswalk/quick-mode.json',
shopify: 'state/crosswalk/quick-shopify.json',
};
async function importProgressFields(projectDir, { quickPlatform = null } = {}) {
const evidence = [];
if (quickPlatform) {
if (await exists(path.join(projectDir, QUICK_IMPORT_STARTED_MARKER))) evidence.push(QUICK_IMPORT_STARTED_MARKER);
const crosswalk = QUICK_CROSSWALKS[quickPlatform];
// Legacy projects interrupted before the marker shipped: a checkpoint that is not `{}`.
// The adapters write `{}` as `{}\n` (3 bytes), so the size test is "more than 3 bytes";
// any checkpoint with one entry is far larger.
if (crosswalk && await nonEmptyFile(path.join(projectDir, crosswalk), 4)) evidence.push(crosswalk);
} else {
for (const relativePath of ['state/attempts/write-attempts.ndjson', 'execution/unresolved-writes.ndjson']) {
if (await nonEmptyFile(path.join(projectDir, relativePath))) evidence.push(relativePath);
}
}
return evidence.length ? { importProgress: 'interrupted', recoveryArtifacts: evidence } : { importProgress: 'not_started' };
}
// A setup-verification.json that exists but doesn't validate (wrong schema, incomplete
// plan coverage, or a stale planDigest) is treated identically to one that doesn't exist —
// no separate router state, no fail-open branch.
async function isSetupVerified(projectDir, readArtifact) {
const verificationPath = path.join(projectDir, 'setup', 'setup-verification.json');
if (!(await exists(verificationPath))) return false;
const verification = await readJson(verificationPath);
const plan = (await readArtifact(path.join('setup', 'setup-plan.json'))).value;
const planDigest = hashArtifact(projectDir, path.join('setup', 'setup-plan.json'));
if (!validateSetupVerification({ verification, plan, planDigest, projectDir }).ok) return false;
// The regional row is bound to the source file, the answers and the approved regional plan it
// was produced under; a changed one makes the receipt stale, so setup re-reads the site.
if (siteRegional.planHasRegionalStep(projectDir)) {
const siteId = siteRegional.destinationSiteId(projectDir);
const row = (verification.requirements || []).find((item) => item && item.id === siteRegional.STEP_ID);
if (!siteRegional.receiptIsCurrent(projectDir, siteId, verification, row)) return false;
}
return true;
}
// The regional settings route, evaluated before the execution-approval gate. While the owner's one question
// about an existing site's settings is open, nothing else proceeds -- in every mode, one-click included.
async function regionalRoute(projectDir) {
if (!siteRegional.planHasRegionalStep(projectDir)) return null;
const open = await siteRegional.listRegionalRequests(projectDir).catch(() => []);
if (!open.length) return null;
return { ok: true, nextState: 'blocked', nextResource: 'resources/rp-execute-setup/', reason: 'site_regional_approval_pending', blocking: true, requestIds: open.map((request) => request.requestId) };
}
// A stamped project cannot leave mapping while any source-coverage row lacks
// exactly one valid disposition. An unstamped (pre-contract) project has no coverage record to
// check; the completion report carries that instead.
async function sourceCoverageGate(projectDir) {
try {
const contract = await readCoverageContract(projectDir);
if (!contract.stamped) return { ok: true, failures: [] };
const result = await reconcileProject(projectDir);
return { ok: result.ok, failures: result.failures };
} catch (error) {
if (error instanceof SourceCoverageError) {
return { ok: false, failures: error.failures.length ? error.failures : [{ code: 'invalid_coverage', coverageId: null, message: error.message, sources: [] }] };
}
throw error;
}
}
// rp-preflight's contract: source configuration/credential blocks go back to rp-source-inputs and
// destination blocks to rp-destination; anything else (the Wix CLI) stays with rp-preflight. A
// source_env block whose key statuses no longer match the env file is stale: preflight runs again.
const PREFLIGHT_SOURCE_CHECKS = new Set(['source_mode', 'source_credentials', 'source_env', 'source_auth_intent', 'file_inputs']);
const PREFLIGHT_DESTINATION_CHECKS = new Set(['target_site_strategy', 'wix_env', 'wix_site_id']);
async function preflightBlockedRoute(projectDir, artifacts, sourcePlatform) {
const preflight = artifacts.preflight;
const blocked = (Array.isArray(preflight.checks) ? preflight.checks : []).filter((check) => check && check.status === 'blocked');
const blockedChecks = blocked.map((check) => check.id);
const sourceEnv = blocked.find((check) => check.id === 'source_env' && check.keyStatus && typeof check.keyStatus === 'object');
if (sourceEnv && sourcePlatform) {
const current = await statEnvKeys(path.join(projectDir, 'config', `source.${sourcePlatform}.env`), Object.keys(sourceEnv.keyStatus)).catch(() => null);
if (current && Object.entries(sourceEnv.keyStatus).some(([key, status]) => current.keys[key] !== status)) {
return { ok: true, nextState: 'preflight_running', nextResource: 'resources/rp-preflight/', reason: 'preflight_source_env_changed', blockedChecks };
}
}
// Reuse preflight's rules, but only read local evidence here. A changed/removed blocker
// dispatches the real preflight, which still owns live CLI/session verification. Never
// probe a service or replay the telemetry journal on a router poll.
if (blockedChecks.some((id) => PREFLIGHT_SOURCE_CHECKS.has(id) || PREFLIGHT_DESTINATION_CHECKS.has(id))) {
const current = await localPreflightChecks(projectDir, artifacts, {
probeShopifySession: async () => ({ receipt: await readJson(path.join(projectDir, SESSION_RECEIPT_FILE)) }),
});
if (blocked.some((check) => (PREFLIGHT_SOURCE_CHECKS.has(check.id) || PREFLIGHT_DESTINATION_CHECKS.has(check.id))
&& !current.some((item) => item.id === check.id && item.status === 'blocked'))) {
return { ok: true, nextState: 'preflight_running', nextResource: 'resources/rp-preflight/', reason: 'preflight_inputs_changed', blockedChecks };
}
}
const nextResource = blockedChecks.some((id) => PREFLIGHT_SOURCE_CHECKS.has(id))
? 'resources/rp-source-inputs/'
: blockedChecks.some((id) => PREFLIGHT_DESTINATION_CHECKS.has(id)) ? 'resources/rp-destination/' : 'resources/rp-preflight/';
return { ok: true, nextState: 'preflight_blocked', nextResource, reason: 'preflight_blocked', blockedChecks };
}
// The supported ways to clear an explicit `status: blocked` stop, surfaced on the route.
const RUN_BLOCKED_RESUME = 'replatform resume <project>, or orchestration-state.js transition --status running';
async function determineNextStepUnfiltered(projectDir, artifacts, { reviewOnly = false, ...options } = {}) {
const validation = validateArtifacts(artifacts);
if (!validation.ok) {
return {
ok: false,
nextState: 'failed',
nextResource: null,
reason: 'invalid_orchestration_artifacts',
errors: validation.errors,
};
}
if (artifacts.run.status === 'cancel_requested') {
return { ok: true, nextState: 'cancel_requested', nextResource: null, reason: 'cancellation_cleanup_required', blocking: true };
}
if (artifacts.run.status === 'canceled' || artifacts.run.status === 'interrupted') {
return { ok: true, nextState: artifacts.run.status, nextResource: null, reason: artifacts.run.status, blocking: true };
}
// An explicitly recorded stop: something wrote run.json `status: blocked` (an operator or
// agent via `orchestration-state.js transition --status blocked`). The router itself never
// writes run.json, so its own derived blocks (preflight_blocked, *_invalid, ...) never land
// here. Hold until a supported resume sets status back to running.
if (artifacts.run.status === 'blocked') {
return { ok: true, nextState: 'blocked', nextResource: null, reason: 'run_blocked', blocking: true, resumeFrom: artifacts.run.resumeFrom ?? null, resumeWith: RUN_BLOCKED_RESUME, blocker: explicitRunBlocker(artifacts.run.resumeFrom) };
}
const decisions = artifacts.decisions || {};
const approvals = artifacts.approvals || {};
const sourceUrl = getDecisionValue(decisions, 'sourceUrl');
const sourceMode = getDecisionValue(decisions, 'sourceMode');
const fileInputPaths = getDecisionValue(decisions, 'fileInputPaths');
const hasFileInputs = Array.isArray(fileInputPaths) && fileInputPaths.length > 0;
const deliveryMode = getDecisionValue(decisions, 'deliveryMode');
const isOneClick = isExplicitUserOneClick(decisions);
const websiteScope = getDecisionValue(decisions, 'websiteScope');
const targetSiteStrategy = getDecisionValue(decisions, 'targetSiteStrategy');
const managementImportMode = getDecisionValue(decisions, 'managementImportMode') || 'standard';
const sourcePlatform = getDecisionValue(decisions, 'sourcePlatform');
const preflight = artifacts.preflight || null;
const readArtifact = createArtifactReader(projectDir);
const actionGate = await pendingUserActionGate(projectDir);
if (actionGate?.route.reason === 'user_action_artifacts_unreadable') return actionGate.route;
if (deliveryMode && !['management', 'website', 'management_and_website'].includes(deliveryMode)) {
return { ok: false, nextState: 'failed', nextResource: 'resources/rp-project-intake/', reason: 'invalid_delivery_mode' };
}
if (!deliveryMode) {
return { ok: true, nextState: 'awaiting_destination_strategy', nextResource: 'resources/rp-project-intake/', reason: 'missing_delivery_mode' };
}
if (managementImportMode && !['standard', 'quick'].includes(managementImportMode)) {
return { ok: false, nextState: 'failed', nextResource: 'resources/rp-project-intake/', reason: 'invalid_management_import_mode' };
}
// Frontend-only work deliberately avoids the backend migration pipeline. The headless
// skill owns its destination/project and terminal website artifacts in this mode.
if (deliveryMode === 'website') {
if (!sourceUrl) {
return { ok: true, nextState: 'awaiting_source', nextResource: 'resources/rp-source-inputs/', reason: 'missing_source_url' };
}
const completionInputs = await loadMigrationCompletionInputs(projectDir);
const frontend = validateFrontendCompletion(completionInputs.frontendCompletion, null, { requireHandoff: false });
if (frontend.ok) {
return { ok: true, nextState: 'completed', nextResource: null, reason: 'website_completion_present' };
}
return { ok: true, nextState: 'storefront_running', nextResource: 'resources/rp-website-continuation/', reason: 'website_only_frontend' };
}
if (!targetSiteStrategy) {
return { ok: true, nextState: 'awaiting_destination_strategy', nextResource: 'resources/rp-destination/', reason: 'missing_target_site_strategy' };
}
// An existing site is muted only when the operator said so, asked here at
// intake (before any write), never mid-import. A conflicting config stops the run.
const notificationMute = await readNotificationMute(projectDir, { decisions });
if (notificationMute.errors.length) {
return { ok: false, nextState: 'failed', nextResource: 'resources/rp-project-intake/', reason: 'notification_mute_invalid', errors: notificationMute.errors };
}
if (notificationMute.needsAnswer) {
return { ok: true, nextState: 'awaiting_destination_strategy', nextResource: 'resources/rp-project-intake/', reason: 'missing_notification_mute_decision', question: NOTIFICATION_MUTE_QUESTION };
}
// The decision above only records which strategy was CHOSEN — it says nothing about
// whether the destination actually got provisioned. rp-destination persists the
// metasite id into config/wix.env on success; if that never happened (a scaffold
// failure, a 409, anything short of completion), targetSiteStrategy can still be set
// while no destination exists. Without this check the router falls through toward
// preflight, which reports the generic "wix.env is missing" — indistinguishable from a
// run that never started — and there is no route back into destination creation for
// the rest of the run. Applies to both strategies uniformly: rp-destination
// is the one module responsible for resolving either, and "persist the metasite id" is
// its stated postcondition for both, so this only re-verifies that postcondition rather
// than re-deriving which strategy path was taken.
//
// nextState is 'destination_running', NOT 'awaiting_destination_strategy': the
// decision is already made, so this is the agent actively retrying creation, not a
// pause for a new user decision. orchestration-state.js requires needsUserInput=true
// for every 'awaiting_*' state (isAwaitingState) — reusing that prefix here would
// force a stop for input that was never needed and could wrongly halt 1-click
// automation on a plain retry. 'destination_running' follows the same naming and
// needsUserInput=false convention as the other in-progress states here
// (preflight_running, discovery_running, etc.).
// WIX_SCAFFOLD_STATUS must be read and classified *before* deciding whether
// the missing-WIX_SITE_ID case is a clean first attempt or a durable, already-failed
// one. The wrapper can leave
// a durable in_progress/ambiguous marker behind with NO WIX_SITE_ID at all (an
// interrupted or unconfirmed attempt); checking WIX_SITE_ID's presence first and
// returning immediately, as a prior version of this router did, never looks at that
// marker — every restart re-classifies it as a fresh, automatically-retryable
// destination_running, rp-destination invokes the wrapper, the wrapper correctly
// refuses again, and the router repeats the same non-decision forever. This is exactly
// the no-progress loop the WIX_SITE_ID-present branch below already exists to prevent
// for `incomplete` — it just wasn't extended to the no-site-id side.
const wixEnvPath = path.join(projectDir, 'config', 'wix.env');
const wixEnv = await statEnvKeys(wixEnvPath, ['WIX_SITE_ID']);
const wixEnvValues = await readEnvFile(wixEnvPath).catch((error) => {
if (error && error.code === 'ENOENT') return {};
throw error;
});
const scaffoldStatus = wixEnvValues.WIX_SCAFFOLD_STATUS;
// Receipt-backed Editor destinations and the explicit new-site type choice.
const destinationRoute = await destinationGate(projectDir, decisions, {
targetSiteStrategy,
siteIdValue: wixEnv.keys.WIX_SITE_ID === 'present' ? String(wixEnvValues.WIX_SITE_ID).trim() : null,
scaffoldStatus,
});
if (destinationRoute) return destinationRoute;
if (wixEnv.keys.WIX_SITE_ID !== 'present') {
// No confirmed destination yet. Only a genuinely untouched wix.env (no status marker
// at all) is a clean first attempt — anything the wrapper itself already recorded
// here is a durable outcome of a real, failed attempt and must not be treated as one.
if (scaffoldStatus === undefined) {
return { ok: true, nextState: 'destination_running', nextResource: 'resources/rp-destination/', reason: 'destination_not_provisioned' };
}
if (scaffoldStatus === 'in_progress') {
// An attempt was interrupted before it could record any outcome, and no local
// receipt exists either — the wrapper itself now refuses to retry through this;
// the router must not retry around it. 'blocked', not
// 'destination_running': no repair path exists, so an auto-retryable state here
// is a no-progress loop, exactly like the incomplete case below.
return { ok: true, nextState: 'blocked', nextResource: 'resources/rp-destination/', reason: 'destination_scaffold_interrupted' };
}
// Any other present value with no WIX_SITE_ID (ambiguous, or corrupted/unexpected
// text) — the wrapper cannot confirm whether a destination exists in this state
// either, and this router has no more information than the wrapper does.
return { ok: true, nextState: 'blocked', nextResource: 'resources/rp-destination/', reason: 'destination_scaffold_ambiguous' };
}
// WIX_SCAFFOLD_STATUS must also be consumed once WIX_SITE_ID is present, not
// just written by the scaffold wrapper — otherwise a restarted run sees WIX_SITE_ID
// present, advances past rp-destination, and never re-invokes the wrapper branch that
// rejects an incomplete scaffold. Routes to 'blocked' (not 'destination_running'): there
// is no repair path, so an automatically-retryable state here would be a
// no-progress loop — 'blocked' is the one state orchestration-state.js's own
// validateRun invariant structurally requires needsUserInput=true for.
if (scaffoldStatus === 'incomplete') {
return { ok: true, nextState: 'blocked', nextResource: 'resources/rp-destination/', reason: 'destination_scaffold_incomplete' };
}
if (scaffoldStatus !== undefined && scaffoldStatus !== 'complete') {
return { ok: true, nextState: 'blocked', nextResource: 'resources/rp-destination/', reason: 'destination_scaffold_status_invalid' };
}
// A file-provided run (e.g. platform=csv) has no source URL to probe; its
// input files stand in for one. Destination resolution has already happened,
// so source readiness can now branch between file and URL inputs.
if (sourceMode === 'files_only') {
if (!hasFileInputs) {
return { ok: true, nextState: 'awaiting_files', nextResource: 'resources/rp-source-inputs/', reason: 'missing_file_inputs' };
}
} else if (!sourceUrl && !hasFileInputs) {
return { ok: true, nextState: 'awaiting_source', nextResource: 'resources/rp-source-inputs/', reason: 'missing_source_url' };
}
if (!sourceMode) {
return { ok: true, nextState: 'awaiting_import_scope', nextResource: 'resources/rp-source-inputs/', reason: 'missing_source_mode' };
}
// A bad value already on disk (a run recorded before `decide` validated it, or a
// hand-written decisions file) stops here, before any preflight result is read, so a
// stale passing preflight.json cannot advance the run. Recording a canonical value
// through `decide` replaces it.
if (!isKnownSourceMode(sourceMode)) {
return { ok: true, nextState: 'awaiting_import_scope', nextResource: 'resources/rp-source-inputs/', reason: 'invalid_source_mode' };
}
// Preserve the destination/acquisition guards above and fresh post-preflight stage
// routing. Stale/unreadable requests still need repair after preflight has passed.
if (actionGate && (actionGate.route.reason !== 'pending_user_action' || preflight?.status !== 'pass')) return actionGate.route;
if (!preflight || !preflight.status || preflight.status === 'not_started') {
return { ok: true, nextState: 'preflight_running', nextResource: 'resources/rp-preflight/', reason: 'preflight_missing' };
}
if (preflight.status === 'blocked') return preflightBlockedRoute(projectDir, artifacts, sourcePlatform);
if (preflight.status === 'failed') {
return { ok: false, nextState: 'failed', nextResource: null, reason: 'preflight_failed', errors: [] };
}
// Scope boundary: phase-output validation runs only before backend accounting.
const completionReportPresent = await exists(path.join(projectDir, 'execution', 'completion-report.json'));
// A recorded rejection is never an approval, in any mode (one-click included).
const executionRejected = Boolean(approvals.execution && approvals.execution.status === 'rejected');
const executionRejectedRoute = { ok: true, nextState: 'blocked', nextResource: 'resources/rp-execution-policy/', reason: 'execution_approval_rejected', blocking: true };
if (managementImportMode === 'quick') {
if (!sourcePlatform) {
return { ok: true, nextState: 'quick_mode_adapter_resolution_required', nextResource: 'resources/rp-source-inputs/', reason: 'quick_mode_platform_not_detected' };
}
const quickResources = {
shopify: 'resources/rp-quick-shopify/',
woocommerce: 'resources/rp-quick-woocommerce/',
};
const quickResource = quickResources[sourcePlatform];
if (!quickResource) {
return { ok: true, nextState: 'blocked', nextResource: 'resources/rp-source-inputs/', reason: 'quick_mode_unsupported_platform', errors: [{ platform: sourcePlatform }] };
}
const quickPreflight = await readJson(path.join(projectDir, 'quick-mode', 'preflight.json'));
if (!quickPreflight) {
return { ok: true, nextState: 'quick_mode_preflight_required', nextResource: quickResource, reason: 'quick_mode_preflight_missing' };
}
if (quickPreflight.status !== 'passed') {
return {
ok: true,
nextState: 'blocked',
nextResource: quickResource,
reason: 'quick_mode_preflight_blocked',
errors: [{ status: quickPreflight.status || 'invalid' }],
};
}
if (!(await exists(path.join(projectDir, 'quick-mode', 'plan.json')))) {
return { ok: true, nextState: 'quick_mode_plan_required', nextResource: quickResource, reason: 'quick_mode_plan_missing' };
}
const quickSetupPlan = await checkGatedOutput(readArtifact, path.join('setup', 'setup-plan.json'), value=>setupPlanRule(value,projectDir), { validate: !completionReportPresent });
const quickSetupRequirements = await checkGatedOutput(readArtifact, path.join('setup', 'setup-requirements.json'), validateSetupRequirementsShape, { validate: !completionReportPresent });
if (!quickSetupPlan.present || !quickSetupRequirements.present) {
return { ok: true, nextState: 'setup_discovery_running', nextResource: 'resources/rp-setup-discovery/', reason: 'quick_mode_setup_plan_missing' };
}
if (quickSetupPlan.errors) return invalidOutputRoute('setup_plan_invalid', 'resources/rp-setup-discovery/', quickSetupPlan.errors);
if (quickSetupRequirements.errors) return invalidOutputRoute('setup_requirements_invalid', 'resources/rp-setup-discovery/', quickSetupRequirements.errors);
const quickManifest = await checkGatedOutput(readArtifact, path.join('execution', 'execution-manifest.json'), validateQuickExecutionManifest, { validate: !completionReportPresent });
if (!quickManifest.present) {
return { ok: true, nextState: 'quick_mode_plan_required', nextResource: quickResource, reason: 'quick_mode_execution_manifest_missing' };
}
if (quickManifest.errors) return invalidOutputRoute('execution_manifest_invalid', quickResource, quickManifest.errors);
if (executionRejected) return executionRejectedRoute;
{ const regional = await regionalRoute(projectDir); if (regional) return regional; }
if (!isOneClick && approvals.execution && approvals.execution.status === 'pending') {
return { ok: true, nextState: 'awaiting_execution_approval', nextResource: 'resources/rp-execution-policy/', reason: 'execution_approval_pending' };
}
if (!completionReportPresent) { const mute = await muteMismatchRoute(readArtifact, notificationMute); if (mute) return mute; }
if (!(await isSetupVerified(projectDir, readArtifact))) {
return { ok: true, nextState: 'executing_setup', nextResource: 'resources/rp-execute-setup/', reason: 'missing_setup_verification' };
}
if (!completionReportPresent) {
// A capacity blocker is a durable stop. The operator frees
// categories (or stops); the re-run import rewrites this file as `passed`.
const capacity = await readJson(path.join(projectDir, 'quick-mode', 'category-capacity.json'));
if (capacity && capacity.status === 'blocked') {
return {
ok: true,
nextState: 'blocked',
nextResource: quickResource,
reason: 'quick_mode_category_capacity_blocked',
errors: [{ existingCount: capacity.existingCount, toCreate: capacity.toCreate, max: capacity.max }],
choices: ['free_destination_categories_and_retry', 'stop'],
};
}
return {
ok: true,
nextState: 'executing_import',
nextResource: quickResource,
reason: 'quick_mode_import_required',
...(await importProgressFields(projectDir, { quickPlatform: sourcePlatform })),
};
}
// An operator-requested re-check of written-unverified products.
// Without a request a partial report never loops back; once the receipt matches the request
// it never fires again. A staged result for the request keeps the route alive even when the
// completion report already shows an empty list (a crash between the report and the receipt).
if (sourcePlatform === 'shopify') {
const request = await readJson(path.join(projectDir, 'quick-mode', 'reverify-request.json'));
if (request && request.requestId) {
const receipt = await readJson(path.join(projectDir, 'quick-mode', 'reverification.json'));
if (!receipt || receipt.requestId !== request.requestId) {
const completion = await readJson(path.join(projectDir, 'execution', 'completion-report.json'));
const listed = completion && completion.writtenUnverified && Array.isArray(completion.writtenUnverified.product) && completion.writtenUnverified.product.length > 0;
const staged = await readJson(path.join(projectDir, 'quick-mode', 'reverification-staged.json'));
if (listed || (staged && staged.requestId === request.requestId)) {
return { ok: true, nextState: 'quick_mode_reverification_required', nextResource: quickResource, reason: 'quick_mode_written_unverified_reverify_requested' };
}
}
}
}
}
const validateOutputs = reviewOnly || !completionReportPresent;
if (managementImportMode !== 'quick') {
const sourceSchema = await checkGatedOutput(readArtifact, 'source-schema.json', validateSourceSchemaShape, { validate: validateOutputs });
if (!sourceSchema.present) {
return { ok: true, nextState: 'discovery_running', nextResource: 'resources/rp-discovery/', reason: 'missing_source_schema' };
}
if (sourceSchema.errors) return invalidOutputRoute('source_schema_invalid', 'resources/rp-discovery/', sourceSchema.errors);
// Discovery promoted under the coverage contract must also have promoted the store's regional
// settings; without them nothing can compare the destination's currency with the source's.
if (await exists(path.join(projectDir, 'discovery', 'source-coverage.json')) && !(await exists(path.join(projectDir, 'discovery', 'source-locale.json')))) {
return { ok: true, nextState: 'discovery_running', nextResource: 'resources/rp-discovery/', reason: 'source_regional_missing' };
}
}
// CMS-fallback freshness chain (plugin coverage -> mapping plan -> setup plan). A plan built
// before a CMS-fallback answer, a register change, or any change to what could resolve the
// capability natively (target knowledge, the detected plugin's current profile, the other
// signed registers) is treated as missing. Coverage and mapping are checked here, before the
// mapping-plan, source-coverage and mapping-approval gates; the setup plan right after the
// mapping approval (setup discovery requires an accepted mapping) and before every
// setup/import step. Neither check is skipped for one-click runs.
const freshness = managementImportMode !== 'quick'
? checkCmsFallbackFreshness(projectDir, {
decisions,
pluginsRoot: options.pluginsRoot,
targetKnowledgeRoot: options.targetKnowledgeRoot,
})
: null;
if (freshness && freshness.stale === 'coverage') {
return { ok: true, nextState: 'discovery_running', nextResource: 'resources/rp-discovery/', reason: 'cms_fallback_inputs_changed' };
}
if (freshness && freshness.stale === 'mapping') {
return { ok: true, nextState: 'mapping_running', nextResource: 'resources/rp-mapper/', reason: 'mapping_plan_stale_cms_fallback' };
}
if (managementImportMode !== 'quick') {
const mappingPlan = await checkGatedOutput(readArtifact, path.join('mapping', 'mapping-plan.json'), validateMappingPlanShape, { validate: validateOutputs });
if (!mappingPlan.present) {
return { ok: true, nextState: 'mapping_running', nextResource: 'resources/rp-mapper/', reason: 'missing_mapping_plan' };
}
if (mappingPlan.errors) return invalidOutputRoute('mapping_plan_invalid', 'resources/rp-mapper/', mappingPlan.errors);
if (reviewOnly) {
const gaps = await readArtifact('mapping/review/mapping-gaps.json');
if (gaps.present && (gaps.parseError || !gaps.value || typeof gaps.value !== 'object')) return invalidOutputRoute('mapping_plan_invalid', 'resources/rp-mapper/', ['mapping/review/mapping-gaps.json is invalid']);
}
// A rejected mapping returns to the mapper, which writes a new plan version
// and resets mapping approval to pending. One-click does not skip a recorded rejection.
if (approvals.mapping && approvals.mapping.status === 'rejected') {
return { ok: true, nextState: 'mapping_running', nextResource: 'resources/rp-mapper/', reason: 'mapping_approval_rejected' };
}
}
if (managementImportMode !== 'quick') {
const bound = await mappingApprovalBound(projectDir, approvals.mapping);
const coverageGate = bound ? await sourceCoverageGate(projectDir) : await reconcileSourceCoverageForMapping(projectDir, { mappingStatus: 'approved' });
if (!coverageGate.ok) {
return { ok: true, nextState: 'mapping_running', nextResource: 'resources/rp-mapper/', reason: 'source_coverage_unreconciled', errors: coverageGate.failures };
}
}
if (managementImportMode !== 'quick') {
const reconciliation = await readReconciliation(projectDir);
const route = (reason, detail = {}) => ({ ok: true, nextState: 'mapping_running', nextResource: 'resources/rp-mapper/', reason, ...detail });
if (!reconciliation) return route('census_reconciliation_missing');
const freshness = await censusReconciliationFreshness(projectDir, reconciliation);
if (!freshness.ok) return route('census_reconciliation_stale', { staleInputs: freshness.staleInputs });
if (reconciliation.errors?.length) return route('census_reconciliation_blocking', { errors: reconciliation.errors });
if (['approved','provisional'].includes(approvals.mapping?.status)) {
const ref = approvals.mapping.artifactRefs?.find(ref => ref && typeof ref === 'object' && ref.kind === 'census-reconciliation' && ref.path === 'mapping/review/census-reconciliation.json' && /^[0-9a-f]{64}$/i.test(ref.sha256 || ''));
if (!ref) return route('mapping_approval_missing_census');
if (!(await mappingApprovalBound(projectDir, approvals.mapping))) return route('mapping_approval_stale_census');
}
}
if (managementImportMode !== 'quick' && !isOneClick && approvals.mapping && approvals.mapping.status === 'pending') {
return { ok: true, nextState: 'awaiting_mapping_approval', nextResource: 'resources/rp-mapper/', reason: 'mapping_approval_pending' };
}
if (managementImportMode !== 'quick') {
const proposedPlan=await readJson(path.join(projectDir,'mapping/mapping-plan.json'));
if (proposedPlan?.fieldContractVersion===1 && require('./mapping-omission-approval').candidates(proposedPlan).length) {
try {require('./mapping-omission-approval').assertAuthorized(projectDir,proposedPlan);}
catch {return {ok:true,nextState:'mapping_running',nextResource:'resources/rp-mapper/',reason:'mapping_omission_approval_missing_or_stale',requiredArtifacts:['orchestration/approvals.json','mapping/mapping-plan.json']};}
}
}
if (freshness && freshness.stale === 'setup') {
return { ok: true, nextState: 'setup_discovery_running', nextResource: 'resources/rp-setup-discovery/', reason: 'setup_plan_stale_cms_fallback' };
}
const setupPlan = await checkGatedOutput(readArtifact, path.join('setup', 'setup-plan.json'), value=>setupPlanRule(value,projectDir), { validate: validateOutputs });
if (!setupPlan.present) {
return { ok: true, nextState: 'setup_discovery_running', nextResource: 'resources/rp-setup-discovery/', reason: 'missing_setup_plan' };
}
if (setupPlan.errors) return invalidOutputRoute('setup_plan_invalid', 'resources/rp-setup-discovery/', setupPlan.errors);
const setupRequirements = await checkGatedOutput(readArtifact, path.join('setup', 'setup-requirements.json'), validateSetupRequirementsShape, { validate: validateOutputs });
if (!setupRequirements.present) {
return { ok: true, nextState: 'setup_discovery_running', nextResource: 'resources/rp-setup-discovery/', reason: 'missing_setup_requirements' };
}
if (setupRequirements.errors) return invalidOutputRoute('setup_requirements_invalid', 'resources/rp-setup-discovery/', setupRequirements.errors);
if (deliveryMode === 'management_and_website' && !websiteScope && !isOneClick) {
return { ok: true, nextState: 'awaiting_website_scope', nextResource: 'resources/rp-project-intake/', reason: 'missing_website_scope' };
}
const handoffStatus = await validateWebsiteHandoff(projectDir);
if (!handoffStatus.present) {
return {
ok: true,
nextState: 'website_handoff_running',
nextResource: 'resources/rp-website-continuation/',
reason: 'missing_website_handoff',
};
}
if (handoffStatus.stale) {
return {
ok: true,
nextState: 'website_handoff_running',
nextResource: 'resources/rp-website-continuation/',
reason: 'stale_website_handoff',
changes: handoffStatus.changes,
};
}
if (!handoffStatus.ok) {
return {
ok: true,
nextState: 'mapping_running',
nextResource: 'resources/rp-mapper/',
reason: 'invalid_website_handoff',
errors: handoffStatus.blockingWarnings,
};
}
if (managementImportMode !== 'quick') {
const manifest = await checkGatedOutput(readArtifact, path.join('execution', 'execution-manifest.json'), validateManifest, { validate: validateOutputs });
if (!manifest.present) {
return { ok: true, nextState: 'codegen_running', nextResource: 'resources/rp-import-codegen/', reason: 'missing_execution_manifest' };
}
if (manifest.errors) return invalidOutputRoute('execution_manifest_invalid', 'resources/rp-import-codegen/', manifest.errors);
}
// Sample-preview sub-gate: codegen emits the extractor, runs it in sample
// mode, and records the user's validation in preview/preview-result.json.
// Routing back into codegen while that is missing or pending is what enforces
// the gate — the artifact is stage-local, so no orchestration phase or
// schema change is involved. Projects that do not use the gate simply never
// create the file and are unaffected.
const previewResult = await readJson(path.join(projectDir, 'preview', 'preview-result.json'));
if (managementImportMode !== 'quick' && previewResult && previewResult.status === 'pending') {
return { ok: true, nextState: 'codegen_running', nextResource: 'resources/rp-import-codegen/', reason: 'sample_preview_pending' };
}
if (executionRejected) return executionRejectedRoute;
{ const regional = await regionalRoute(projectDir); if (regional) return regional; }
if (!isOneClick && approvals.execution && approvals.execution.status === 'pending') {
return { ok: true, nextState: 'awaiting_execution_approval', nextResource: 'resources/rp-execution-policy/', reason: 'execution_approval_pending' };
}
if (!completionReportPresent) { const mute = await muteMismatchRoute(readArtifact, notificationMute); if (mute) return mute; }
if (!(await isSetupVerified(projectDir, readArtifact))) {
return { ok: true, nextState: 'executing_setup', nextResource: 'resources/rp-execute-setup/', reason: 'missing_setup_verification' };
}
// A stopped run leaves an `aborted` report with an interruption. It is not
// completion: the route is the same resume, never finalizing.
const interruptedReport = completionReportPresent
&& Boolean((await readJson(path.join(projectDir, 'execution', 'completion-report.json')))?.interruption);
if (!completionReportPresent || interruptedReport) {
const progress = await importProgressFields(projectDir);
return {
ok: true,
nextState: 'executing_import',
nextResource: 'resources/rp-execute-import/',
reason: interruptedReport ? 'import_interrupted' : 'missing_completion_report',
...progress,
// A run killed before it could record its stop: write the aborted report from the journal
// (scripts/interrupted-completion-report.js) so cutover sees the pause, then resume.
...(!completionReportPresent && progress.importProgress === 'interrupted' ? { interruptedReport: 'missing' } : {}),
};
}
const completionInputs = await loadMigrationCompletionInputs(projectDir);
if (deliveryMode === 'management_and_website') {
const frontend = validateFrontendCompletion(completionInputs.frontendCompletion, completionInputs.handoff);
// An Editor destination has no automatic frontend continuation. The website
// obligation stays outstanding as a handoff; never route into the Headless clone.
if (!frontend.ok && isEditorSiteType(getDecisionValue(decisions, 'targetSiteType'))) {
return {
ok: true,
nextState: 'blocked',
nextResource: 'resources/rp-website-continuation/',
reason: 'editor_website_handoff_outstanding',
requiredArtifacts: ['website/completion.json'],
blocking: true,
};
}
if (!frontend.ok) {
return {
ok: frontend.reason !== 'frontend_blocked',
nextState: frontend.reason === 'frontend_blocked' ? 'blocked' : 'storefront_running',
nextResource: 'resources/rp-website-continuation/',
reason: frontend.reason,
requiredArtifacts: ['website/handoff.json', 'website/completion.json'],
blocking: frontend.reason === 'frontend_blocked',
};
}
}
const mappingPlan=await readJson(path.join(projectDir,'mapping/mapping-plan.json'));
if (mappingPlan?.fieldContractVersion===1 && mappingPlan.executionScope?.deferredEntities?.length) {
const {digest,canonical,deferredRunResult}=require('./mapping-field-contract.js');
const report=completionInputs.backendCompletion,summary=completionInputs.postExecutionHandoff?.mappingSummary;
// Finish the existing reports before stopping; never declare a partial scope complete.
const retained=report?.mappingPlanDigest===digest(mappingPlan) &&
canonical(report.executionScope)===canonical(mappingPlan.executionScope) &&
summary?.mappingPlanDigest===digest(mappingPlan) &&
canonical(summary.executionScope)===canonical(mappingPlan.executionScope) &&
completionInputs.executionLogPresent && completionInputs.postExecutionHandoff.lastWriteAt===report.lastWriteAt;
if (!retained) return {ok:true,nextState:'blocked',nextResource:null,blocking:true,reason:'mapping_deferral_report_missing_or_stale',blocker:{type:'mapping_deferral_evidence_required',artifact:'execution/completion-report.json',requiredInput:'Regenerate the existing report/handoff through shared writers using the importer mapping pin; retained counters must not be reported as completed.'}};
return {ok:true,nextState:'blocked',nextResource:null,reason:'mapping_scope_deferred',blocking:true,blocker:deferredRunResult(mappingPlan).blocker};
}
const aggregate = validateMigrationCompletion(completionInputs.completion, {
deliveryMode,
backendCompletion: completionInputs.backendCompletion,
frontendCompletion: completionInputs.frontendCompletion,
handoff: completionInputs.handoff,
// The post-execution handoff and the execution log are part of what "finished" means.
// This is NOT a new router gate -- it is the existing `validateMigrationCompletion` gate
// being handed the inputs it now judges on. A gate given half its inputs passes on the half
// it was given, which is how three required artifacts came to have no writer.
postExecutionHandoff: completionInputs.postExecutionHandoff,
executionLogPresent: completionInputs.executionLogPresent,
// Same pattern again -- the entity-QA attestation gate, and the independent
// mapped-entity coverage source it is judged against, are more inputs to this same existing
// call, not a new router branch.
entityQaAttestation: completionInputs.entityQaAttestation,
mappedEntities: completionInputs.mappedEntities,
reportDigest: completionInputs.reportDigest,
discoveredSetStatus: completionInputs.discoveredSetStatus,
discoveredSetFreshness: completionInputs.discoveredSetFreshness,
discoveredSetDigest: completionInputs.discoveredSetDigest,
completionDiscoveredInputs: completionInputs.completionDiscoveredInputs,
resolutionsPrefixValid: completionInputs.resolutionsPrefixValid,
});
if (!aggregate.ok) {
return {
ok: true,
nextState: 'finalizing',
nextResource: 'resources/rp-execution-policy/',
reason: aggregate.reason,
requiredArtifacts: ['completion/migration-completion.json'],
blocking: false,
...(aggregate.entityQa ? { entityQa: aggregate.entityQa } : {}),
};
}
// A verified historical run is being refinalized locally, not republished to Wix.
// Its aggregate checks above still apply; do not introduce a target-write stage.
if (reviewOnly) return {ok:true,nextState:'completed',nextResource:null,reason:'migration_completion_present'};
let migrationReview = null;
try {
migrationReview = await readMigrationReview(projectDir);
} catch (error) {
if (!error || error.code !== 'ENOENT') {
return {
ok: false,
nextState: 'failed',
nextResource: 'resources/rp-migration-review/',
reason: error.code || 'invalid_migration_review',
errors: [{ message: error.message }],
};
}
}
if (!migrationReview || !migrationReview.evidenceRevision) {
return { ok: true, nextState: 'migration_review_running', nextResource: 'resources/rp-migration-review/', reason: 'migration_review_missing' };
}
const completionReportDigest = hashArtifact(projectDir, path.join('execution', 'completion-report.json'));
if (!completionReportDigest || migrationReview.completionReportDigest !== completionReportDigest) {
return { ok: true, nextState: 'migration_review_running', nextResource: 'resources/rp-migration-review/', reason: 'migration_review_stale' };
}
const reviewHandoff = await readLatestHandoff(projectDir);
if (!reviewHandoff || reviewHandoff.evidenceRevision !== migrationReview.evidenceRevision || reviewHandoff.committedStateVersion !== migrationReview.stateVersion) {
return { ok: true, nextState: 'migration_review_running', nextResource: 'resources/rp-migration-review/', reason: 'migration_review_handoff_missing_or_stale' };
}
return { ok: true, nextState: 'completed', nextResource: null, reason: 'migration_completion_present' };
}
const REVIEW_ONLY_MAPPING_REASONS = new Set(['mapping_approval_rejected', 'census_reconciliation_missing', 'census_reconciliation_stale', 'census_reconciliation_blocking', 'mapping_approval_missing_census', 'mapping_approval_stale_census']);
function applyReviewOnlyRoute(result) {
const hold = (reason, detail = {}) => ({ ...result, ok: true, nextState: 'blocked', nextResource: null, reason, blocking: true, reviewOnly: true, ...detail });
if (['missing_source_schema','source_schema_invalid','missing_mapping_plan','mapping_plan_invalid'].includes(result.reason)) return hold('review_only_input_unavailable', { errors: result.errors || [result.reason] });
if (result.reason === 'source_coverage_unreconciled') return hold('review_only_source_coverage_unreconciled');
if (REVIEW_ONLY_MAPPING_REASONS.has(result.reason) || result.reason === 'mapping_approval_pending' || ['finalizing','completed'].includes(result.nextState)) return { ...result, reviewOnly: true };
return hold('review_only_unexpected_route', { wouldRoute: result.reason });
}
async function determineNextStepForMode(projectDir, artifacts, options, validation) {
// Classification must precede every resource-bearing route, including intake and quick mode.
if (!validation.ok || ['cancel_requested','canceled','interrupted','blocked'].includes(artifacts.run.status)) return determineNextStepUnfiltered(projectDir, artifacts, options);
const finalized = await classifyFinalizedRun(projectDir, { decisions: artifacts.decisions || {} });
if (finalized.kind === 'unverified-v1') return { ok: true, nextState: 'blocked', nextResource: null, reason: 'finalized_receipt_unverified', errors: finalized.errors, reviewOnly: true, blocking: true };
// Keep the closed review-only route after v1 is archived and replaced by v2.
// Checking only the current receipt would dispatch publication on the next resume.
const archived = finalized.kind === 'current' ? await classifyFinalizedRun(projectDir, {
decisions: artifacts.decisions || {}, receiptFile:'completion/migration-completion.v1.json'
}) : null;
if (archived?.kind === 'unverified-v1') return {ok:true,nextState:'blocked',nextResource:null,reason:'finalized_receipt_unverified',errors:archived.errors,reviewOnly:true,blocking:true};
const reviewOnly = finalized.kind === 'valid-v1' || archived?.kind === 'valid-v1';
const result = await determineNextStepUnfiltered(projectDir, artifacts, { ...options, reviewOnly });
// A finalized review-only run must never dispatch destination work. Standard runs
// still require master's fresh Editor publication readback before downstream work.
return reviewOnly ? applyReviewOnlyRoute(result) : publicationRecheckGate(projectDir, result, options);
}
async function determineNextStep(projectDir, artifacts, options = {}) {
const validation = validateArtifacts(artifacts);
const result = await determineNextStepForMode(projectDir, artifacts, options, validation);
// Preserve master's CMS-decision quarantine diagnostics on every route, including holds.
return validation.quarantined?.length
? { ...result, validation: { quarantined: validation.quarantined } }
: result;
}
module.exports = {
applyReviewOnlyRoute,
determineNextStep,
validateMappingPlanShape,
validateSourceSchemaShape,
};
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