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/read-back-gate.js
'use strict';
const path = require('node:path');
const state = require('./read-back-state');
const C = require('./read-back-contract');
const {
compareEntity,
memberProjection
} = require('./read-back-comparison');
const {
ReadBackReads
} = require('./read-back-reads');
const verified = require('./write-verification');
const store = require('./write-verification-state');
const {
hashArtifact
} = require('./artifact-freshness');
const writers = require('../resources/rp-target-wix/lib/wix-writers');
const {
deriveImportedOrderId
} = require('../resources/rp-target-wix/lib/order-history');
const {
findMatching
} = require('../resources/rp-target-wix/lib/contact-import');
const approval = require('./read-back-approval');
const API = 'https://www.wixapis.com';
const readSessions = new Map();
function sharedReads(projectDir, runId, wix) {
const key = `${path.resolve(projectDir)}\0${runId}`;
if (!readSessions.has(key)) readSessions.set(key, new ReadBackReads(wix));
return readSessions.get(key);
}
// Every shape a writer may use to report the target it wrote. The success path and the
// deferral check share it, so a deferral can never hide an id the success path would accept.
function writtenTargetId(entity, written) {
return written?.targetId || written?.id || written?.[`${entity}Id`] || written?.[entity]?.id;
}
function problem(reason) {
return Object.assign(new Error(reason), {
code: reason
});
}
// Writer guards approved elsewhere that remove a value before sending (the member
// phone-collision drop). Only these exact finding -> path pairs can exempt a path, and only when
// the writer itself reported the finding; a missing target field never implies a guard.
const WRITER_GUARDS = {
member: [{
path: 'member.contact.phones[]',
applies: f => f?.code === 'member-phone-collision-dropped' && f.phoneDropped === true,
strip: body => {
delete body.member?.contact?.phones;
}
}]
};
function guardPathsFrom(entity, findings) {
return (WRITER_GUARDS[entity] || []).filter(g => (findings || []).some(g.applies)).map(g => g.path);
}
function applyGuards(entity, expected, paths) {
const guards = (WRITER_GUARDS[entity] || []).filter(g => (paths || []).includes(g.path));
if (!guards.length) return expected;
const body = structuredClone(expected);
for (const g of guards) g.strip(body);
return body;
}
function declaration(entity, {
verificationKind,
reason
} = {}) {
if (Object.hasOwn(C.DOMAINS, entity)) return {
entity,
gated: true
};
if (!verificationKind || !reason?.trim()) throw new Error('Non-gated entities must declare verification and reason');
return {
entity,
gated: false,
verificationKind,
reason
};
}
class ReadBackGate {
constructor({
projectDir,
runId,
entity,
siteId,
wix,
buildWrite,
write,
repair,
sourceSiteHost,
marker,
variants = [],
reads,
read,
lookup,
now = () => new Date().toISOString(),
identity
} = {}) {
if (!projectDir || typeof runId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(runId) || ['constructor', 'prototype', '__proto__'].includes(runId) || !siteId || typeof buildWrite !== 'function' || typeof write !== 'function') throw new Error('Read-back gate requires project, run, site, builder and writer');
C.entityKey(entity);
Object.assign(this, {
projectDir,
runId,
entity,
siteId,
buildWrite,
write,
repair,
sourceSiteHost,
marker,
variants,
now,
identity
});
this.reads = reads || sharedReads(projectDir, runId, wix);
this.startedAt = this.reads.now();
this.preparationMs = 0;
this.writeMs = 0;
this.read = read || (id => this.readTarget(id));
this.lookup = lookup || ((record, expected) => this.lookupTarget(record, expected));
}
async mutate(fn) {
return state.update(this.projectDir, g => {
g.runs[this.runId] ||= {
entities: {}
};
g.runs[this.runId].entities[this.entity] ||= {
status: 'stopped',
canaries: [],
settlements: [],
approvedOmissions: []
};
const item = g.runs[this.runId].entities[this.entity],
result = fn(g, item);
item.retryStats = {
...this.reads.stats,
remainingMs: this.reads.remaining()
};
item.timing = {
elapsedMs: Math.max(0, this.reads.now() - this.startedAt),
preparationMs: this.preparationMs,
writeMs: this.writeMs,
activeReadMs: Object.entries(this.reads.stats).filter(([key]) => key.endsWith('Ms')).reduce((n, [, value]) => n + value, 0)
};
return result;
});
}
async item() {
return (await state.load(this.projectDir)).runs[this.runId]?.entities?.[this.entity];
}
async prepare(inv, {
ceiling,
preparationMs = inv?.preparationMs || 0
} = {}) {
const preparingAt = this.reads.now();
await approval.recoverAcknowledgements(this.projectDir, this.identity ? {
identity: this.identity
} : {});
this.validated = await C.validate(this.projectDir, this.entity, {
inv
});
if (!this.validated.valid) {
await this.stop('mapping-validation-failed');
throw Object.assign(problem('mapping-validation-failed'), {
errors: this.validated.errors
});
}
const decisions = await state.readJson(this.projectDir, 'orchestration/decisions.json', {}),
chosen = decisions[`readBackCanaryCeiling.${this.entity}`] || decisions.readBackCanaryCeiling?.[this.entity] || decisions.decisions?.[`readBackCanaryCeiling.${this.entity}`];
if (ceiling !== undefined) throw new Error('Canary ceiling must come from recorded user decision, not the caller');
if (chosen && (chosen.source !== 'user' || !Number.isInteger(chosen.value))) throw problem('canary-ceiling-not-user-recorded');
const history = await state.load(this.projectDir);
// Only a prepared entry (schedule and bindings) is a previous run to continue. An unprepared
// one (completion's `gate-not-run` placeholder, a validation stop) is taken over by this run;
// it stays blocking until then, and this run's own gate status replaces it.
const others = Object.entries(history.runs).filter(([id, run]) => id !== this.runId && run.entities?.[this.entity] && !run.entities[this.entity].supersededBy);
const preparedEntry = e => Boolean(e.schedule && e.bindingDigests);
const previousRun = [...others].reverse().find(([, run]) => preparedEntry(run.entities[this.entity]));
const unprepared = others.filter(([, run]) => !preparedEntry(run.entities[this.entity])).map(([id]) => id);
const own = await this.item();
const existing = own?.schedule ? own : previousRun?.[1].entities[this.entity];
// A skip belongs to the run that made it: a parent may have landed since, so a later run offers
// the record again (and skips it again if its parent is still final). This run's own skips hold.
const priorSkips = existing?.skippedCanaries || [], keptSkips = priorSkips.filter(r => r.runId === this.runId);
const schedule = C.cover(inv, {
ceiling: chosen?.value || 10,
existing: (existing?.canaries || []).map(r => r.sourceId),
exclude: keptSkips.map(r => r.sourceId)
});
this.inventory = inv;
this.repairContractDigest = C.digest({
bindings: this.validated.bindingDigests,
code: hashArtifact(this.projectDir, 'src/import'),
comparator: 1
});
this.preparationMs += preparationMs + Math.max(0, this.reads.now() - preparingAt);
const approvedOmissionRows=this.validated.fieldContractVersion===1 ? require('./mapping-omission-approval').omissions(this.validated.decision) : null;
await this.mutate((g, item) => {
if (!own?.schedule && existing) {
Object.assign(item, structuredClone(existing));
delete item.supersededBy;
if (previousRun) g.runs[previousRun[0]].entities[this.entity].supersededBy = this.runId;
}
for (const id of unprepared) g.runs[id].entities[this.entity].supersededBy = this.runId;
if (existing && C.digest(existing.bindingDigests) !== C.digest(this.validated.bindingDigests)) {
item.approvedOmissions = [];
delete item.pendingAcknowledgementRequest;
}
item.paths ||= {};
item.paths.notExercised = this.validated.contract.intendedFields.filter(f => !(this.validated.decision.fieldDispositions || []).some(d => ['notMigrated','deferred'].includes(d.status) && (d.path || d.targetPath) === f.targetPath)).filter(f => !Object.keys(inv.writePaths).some(p => p === f.targetPath || p.startsWith(f.targetPath + '.') || p.startsWith(f.targetPath + '[]'))).map(f => f.targetPath);
item.pendingFields = (this.validated.decision.fieldDispositions || []).filter(d=>d.status==='deferred');
// The schedule is the fresh one, not a persisted one that excluded a record skipped by an earlier run.
const retriedSkips = priorSkips.length > keptSkips.length;
if (keptSkips.length) item.skippedCanaries = structuredClone(keptSkips); else delete item.skippedCanaries;
item.schedule = existing?.schedule?.universeDigest === schedule.universeDigest && !retriedSkips ? existing.schedule : schedule;
item.status = 'stopped';
item.stopReason = schedule.status === 'covered' ? 'canaries-pending' : schedule.status;
item.retryStats = this.reads.stats;
item.invocationStartedAt = this.now();
item.bindingDigests = this.validated.bindingDigests;
if (inv.heldRecords) item.heldRecords = structuredClone(inv.heldRecords);else delete item.heldRecords;
if (!inv.records.length) item.endOfRunVerified = true;
if (!item.approvedOmissions.length) item.approvedOmissions = (this.validated.decision.fieldDispositions || []).filter(d => d.status === 'notMigrated' &&
(!approvedOmissionRows || approvedOmissionRows.some(o=>o.kind===d.kind && o.path===d.path && o.writeOperation===(d.writeOperation || null)))).map(d => ({
path: d.path || d.sourcePath || d.targetPath,
kind: d.kind || 'source',
recordCount: d.affectedScope ? d.affectedScope.count : inv.sourcePaths[d.path || d.sourcePath] || inv.records.length,
...(d.affectedScope ? {affectedScope:d.affectedScope,writeOperation:d.writeOperation || null} : {}),
approvedBy: this.validated.approval?.approvedBy || null
}));
});
if (schedule.status !== 'covered') throw Object.assign(problem(schedule.status), {
uncoveredPaths: schedule.uncoveredPaths
});
return schedule;
}
async protect(sourceId, change) {
return state.locked(this.projectDir, async () => {
const s = await store.load(this.projectDir, this.siteId),
key = `read-back:${this.entity}:${sourceId}`;
s.rows[key] = {
...(s.rows[key] || {}),
sourceKey: key,
kind: 'read-back-gate',
entity: this.entity,
sourceId,
runId: this.runId,
...change
};
await store.checkpoint(this.projectDir, s, [{
sourceKey: key
}]);
return s.rows[key];
});
}
async protected(sourceId) {
const s = await store.load(this.projectDir, this.siteId);
return s.rows[`read-back:${this.entity}:${sourceId}`];
}
async stop(reason) {
await this.mutate((g, item) => {
if (reason === 'read-budget-exhausted') for (const e of Object.values(g.runs[this.runId].entities)) {
if (e.status !== 'passed') {
e.status = 'unknown';
e.stopReason = reason;
}
}
item.status = reason.includes('unknown') || /budget|settlement|unavailable/.test(reason) ? 'unknown' : 'stopped';
item.stopReason = reason;
item.retryStats = {
...this.reads.stats,
remainingMs: this.reads.remaining()
};
});
}
async readTarget(id) {
const w = this.reads.wix;
if (this.entity === 'product') return writers.getStoresProductForVerification(w, id);
if (this.entity === 'contact') return (await w.send(writers.buildGetContactRequest(id))).contact;
if (this.entity === 'order') return (await w.send({
method: 'GET',
url: `${API}/ecom/v1/orders/${encodeURIComponent(id)}`
})).order;
const m = (await w.send(writers.buildGetMemberRequest(id))).member;
if (!m?.contactId) throw problem('member-contact-id-unknown');
const c = (await w.send(writers.buildGetContactRequest(m.contactId))).contact;
if (c?.id !== m.contactId) throw problem('member-contact-identity-unknown');
return {
member: m,
contact: c
};
}
async lookupTarget(record, body) {
const e = body[this.entity] || body,
w = this.reads.wix;
if (this.entity === 'order') {
const id = deriveImportedOrderId({
sourceSiteHost: this.sourceSiteHost,
sourceId: String(record.id)
});
try {
return [await this.readTarget(id)];
} catch (err) {
if (err.status === 404 && err.outcomeKnown) return [];
throw err;
}
}
if (this.entity === 'contact') return findMatching(w, e);
if (this.entity === 'member') return (await writers.queryMembersByLoginEmail(w, e.loginEmail)).filter(m => verified.email(m.loginEmail) === verified.email(e.loginEmail));
const products = await writers.queryAllStoresProducts(w),
marker = typeof this.marker === 'function' ? this.marker(record, body) : this.marker;
if (!marker?.path) throw problem('product-marker-required');
const matches = products.filter(p => C.valuesAt(p, marker.path).some(v => v === marker.value));
// A product that was on the store before this import is never this record's write.
const baseline = require('./catalog-baseline'),
held = matches.find(p => baseline.protectedIds(this.projectDir).products.has(p.id));
if (held) {
baseline.recordCollision(this.projectDir, { entity: 'stores/product', sourceKey: `read-back:${this.entity}:${record.id}`, targetId: held.id, slug: held.slug ?? null });
throw problem('target-baseline-collision');
}
return matches;
}
checkIdentity(expected, actual, id) {
const e = expected[this.entity] || expected,
a = actual[this.entity] || actual;
if (!id || a?.id !== id || a?._dryRunPlaceholder) throw problem('identity-conflict');
if (this.entity === 'contact' && !verified.contactIdentity(e, a, id).verified) throw problem('identity-conflict');
if (this.entity === 'product' && !verified.verifyProduct({
id
}, a, id, {
marker: typeof this.marker === 'function' ? this.marker(this.activeRecord, expected) : this.marker,
variants: typeof this.variants === 'function' ? this.variants(this.activeRecord, expected) : this.variants
}).verified) throw problem('identity-conflict');
if (this.entity === 'member' && (verified.email(e.loginEmail) !== verified.email(a.loginEmail) || !a.contactId || actual.contact?.id !== a.contactId)) throw problem('member-contact-identity-unknown');
if (this.entity === 'order' && (a.number !== e.number || id !== deriveImportedOrderId({
sourceSiteHost: this.sourceSiteHost,
sourceId: String(this.activeSourceId)
}))) throw problem('identity-conflict');
}
assertApplicability(record, expected, guarded, options = {}) {
if (C.builderHold(expected)) throw problem('builder-held-record');
const judged = C.outputApplicability(this.validated.rows, record, expected, { guarded: guarded || [], ...options });
if (judged.missing.length) throw problem('builder-missing-intended-field');
if (judged.unexpected.length) throw problem('builder-emitted-inapplicable-field');
}
async observe(record, sourceId, targetId, expected) {
// Read-back compares only applicable outputs: an expected body carrying a non-applicable (or
// missing a declared applicable) output is refused before any read.
this.assertApplicability(record, expected, (WRITER_GUARDS[this.entity] || []).map(g => g.path), { declaredOnly: true });
// No target id means nothing was written to read: refused before any request (a read of
// `.../undefined` only spends the read budget on 404s).
if (noTarget(targetId)) throw Object.assign(problem('target-id-missing'), { requestSent: false });
this.activeSourceId = sourceId;
this.activeRecord = record;
let actual = await this.read(targetId, this.reads.wix);
this.checkIdentity(expected, actual, targetId);
let result = compareEntity(this.entity, expected, actual),
media = result.checks.filter(c => !c.matches && c.writePath.startsWith('product.media.'));
if (media.length) {
let settled = false,
reason = 'media-settlement-exhausted';
try {
await this.reads.settle();
actual = await this.read(targetId, this.reads.wix);
this.checkIdentity(expected, actual, targetId);
result = compareEntity(this.entity, expected, actual);
settled = !result.checks.some(c => !c.matches && c.writePath.startsWith('product.media.'));
} catch (e) {
reason = e.code || 'media-settlement-exhausted';
}
await this.mutate((g, item) => {
for (const check of media) {
const row = this.rowFor(check.writePath),
entry = {
entity: this.entity,
sourceId,
targetId,
readPath: check.readPath,
writePath: check.writePath,
sourcePaths: row?.sourcePaths || [],
intendedTargetPath: row?.writePath || check.writePath,
bindingSetDigest: C.digest(this.validated.bindingDigests),
policy: 'product-media-read-after-60s',
status: settled ? 'passed' : 'unknown',
reads: 2,
waitedMs: this.reads.stats.settlementMs,
reason: settled ? null : reason
};
item.settlements = item.settlements.filter(s => !(s.sourceId === sourceId && s.writePath === check.writePath));
item.settlements.push(entry);
}
});
if (!settled) {
await this.recordLosses(sourceId, result.checks.filter(c => !c.writePath.startsWith('product.media.')));
await this.stop(reason);
return {
verified: false,
unknown: true,
actual,
checks: result.checks
};
}
}
await this.recordLosses(sourceId, result.checks);
// A record held earlier as a baseline collision that now verifies is no longer one.
if (result.verified && this.entity === 'product') require('./catalog-baseline').clearCollision(this.projectDir, 'stores/product', `read-back:${this.entity}:${sourceId}`);
if (!result.verified) await this.stop('field-mismatch');else await this.mutate((g, item) => {
for (const s of item.settlements.filter(s => s.sourceId === sourceId)) s.status = 'passed';
for (const loss of g.observedLosses) if (loss.entity === this.entity && result.checks.some(c => c.matches && c.writePath === loss.writePath)) loss.resolvedBy = {
sourceId,
targetId,
at: this.now()
};
});
return {
...result,
actual
};
}
rowFor(writePath) {
const rows = this.validated.rows.filter(r => r.writePath === writePath || writePath.startsWith(`${r.writePath}.`) || writePath.startsWith(`${r.writePath}[]`) || r.writePath.startsWith(`${writePath}[]`)).sort((a, b) => b.writePath.length - a.writePath.length);
return rows.length ? {
...rows[0],
sourcePaths: [...new Set(rows.flatMap(r => r.sourcePaths || []))]
} : null;
}
async recordLosses(sourceId, checks) {
await this.mutate((g, item) => {
for (const check of checks) {
if (check.matches) continue;
const row = this.rowFor(check.writePath);
if (!g.observedLosses.some(l => l.entity === this.entity && l.writePath === check.writePath)) g.observedLosses.push({
entity: this.entity,
writePath: check.writePath,
readPath: check.readPath,
sourcePaths: row?.sourcePaths || [],
intendedTargetPath: row?.writePath || check.writePath,
kind: check.kind,
firstSourceId: sourceId,
bindingSetDigest: C.digest(this.validated.bindingDigests),
observedAt: this.now()
});
}
item.checks = checks.map(c => ({
...c
}));
for (const c of checks) {
const key = c.kind === 'unverifiable' ? 'unverifiable' : c.matches ? 'verified' : c.kind;
(item.paths ||= {})[key] ||= [];
if (!item.paths[key].includes(c.writePath)) item.paths[key].push(c.writePath);
}
});
}
async timeWrite(write) {
const started = this.reads.now();
try {
return await write();
} finally {
this.writeMs += Math.max(0, this.reads.now() - started);
}
}
async executeCanaries(getRecord) {
if (!this.validated?.valid) throw problem('gate-not-prepared');
let item = await this.item();
if (item.schedule.status !== 'covered') throw problem('coverage-exceeds-ceiling');
for (const sourceId of item.schedule.canarySourceIds) {
if (this.reads.remaining() <= 0) {
await this.stop('read-budget-exhausted');
return false;
}
const record = await getRecord(sourceId),
prior = await this.protected(sourceId);
let expected = await this.buildWrite(record),
targetId = prior?.targetId,
newWrite = false;
// A previous attempt the client refused before sending left nothing on the site: write again.
const notSent = prior?.outcome === 'not-sent' && !prior.targetId;
await this.mutate((g, e) => {
if (!e.canaries.some(c => c.sourceId === sourceId)) e.canaries.push({
sourceId,
targetId: prior?.targetId || null,
marker: prior?.marker,
outcome: prior?.outcome || 'pending',
repairAttempts: prior?.repairAttempts || []
});
});
expected = applyGuards(this.entity, expected, prior?.guardDroppedPaths);
// Every applicable populated mapping must produce an expected target value, and an output whose
// declared appliesWhen is false must be absent. The builder's own omission proves nothing.
this.assertApplicability(record, expected, prior?.guardDroppedPaths);
if (prior && !targetId && !notSent) {
let found;
try {
found = await this.lookup(record, expected, this.reads.wix);
} catch (e) {
await this.stop(e.code || 'unknown-write-lookup-failed');
return false;
}
const matches = Array.isArray(found) ? found : found?.matches || [];
if (matches.length !== 1) {
await this.stop(matches.length > 1 ? 'identity-conflict' : 'unknown-write-no-match');
return false;
}
targetId = matches[0].id;
await this.protect(sourceId, {
targetId,
uncertain: false
});
}
if (!prior || notSent) {
await this.mutate((g, e) => {
if (!e.canaries.some(c => c.sourceId === sourceId)) e.canaries.push({
sourceId,
targetId: null,
outcome: 'pending',
repairAttempts: []
});
});
await this.mutate((g, e) => {
e.attemptedPaths ||= [];
for (const row of this.validated.rows) if (C.valuesAt(expected, row.writePath).some(C.populated) && !e.attemptedPaths.some(p => p.writePath === row.writePath)) e.attemptedPaths.push({
entity: this.entity,
sourceId,
writePath: row.writePath,
sourcePaths: row.sourcePaths,
intendedTargetPath: row.writePath,
bindingSetDigest: C.digest(this.validated.bindingDigests)
});
});
await this.protect(sourceId, {
expected,
payloadDigest: C.digest(expected),
contractDigest: this.repairContractDigest,
sentAt: this.now(),
outcome: 'pending',
uncertain: true
});
try {
const written = await this.timeWrite(() => this.write(record, expected));
// The writer declined before sending (`{ deferred: true, reason }`, e.g. its dependency
// gate deferred the record): nothing reached the site, so it is not a possible write.
// Only the exact documented shape is trusted. Any id alias the success path accepts, or
// any other key, means a write may exist: keep the protection (unknown outcome).
if (written?.deferred === true) {
if (writtenTargetId(this.entity, written)) throw problem('unknown-write-deferred-with-id');
if (Object.keys(written).some(key => key !== 'deferred' && key !== 'reason')) throw problem('unknown-write-deferral-malformed');
await this.protect(sourceId, {
uncertain: false,
sentAt: null,
outcome: 'not-sent',
notSentReason: typeof written.reason === 'string' && written.reason ? written.reason : 'write-deferred'
});
// Its own parent record is final for this run (dependency-parent-final): this record
// cannot be a canary now. Another record covers its paths; it imports later with the
// rest of the entity once its parent lands. Only a never-written canary is replaced.
if (written.reason === 'dependency-parent-final' && !prior?.targetId && this.inventory) {
let next;
await this.mutate((g, e) => {
e.skippedCanaries = [...(e.skippedCanaries || []).filter(row => row.sourceId !== sourceId), { sourceId, reason: written.reason, runId: this.runId }];
e.canaries = e.canaries.filter(row => row.sourceId !== sourceId);
next = C.cover(this.inventory, { ceiling: e.schedule.ceiling, existing: e.canaries.map(row => row.sourceId), exclude: e.skippedCanaries.map(row => row.sourceId) });
e.schedule = next;
});
if (next.status !== 'covered') { await this.stop(next.status); return false; }
return this.executeCanaries(getRecord);
}
await this.stop('canary-write-deferred');
return false;
}
targetId = writtenTargetId(this.entity, written);
const guarded = await this.recordGuard(sourceId, written?.findings);
if (guarded.length) expected = applyGuards(this.entity, expected, guarded);
if (!targetId) throw problem('unknown-write-no-confirmed-id');
await this.protect(sourceId, {
targetId,
uncertain: false
});
newWrite = true;
} catch (e) {
// Refused before sending (a capability or readiness refusal): the outcome is known, so
// the record must not stay protected as possibly written.
if (e?.requestSent === false && !targetId) await this.protect(sourceId, {
uncertain: false,
sentAt: null,
outcome: 'not-sent',
notSentReason: e.code || e.message
});
await this.stop(e.code || 'unknown-write-outcome');
return false;
}
}
let result;
try {
result = await this.observe(record, sourceId, targetId, expected);
} catch (e) {
await this.stop(e.code || 'unknown-read');
return false;
}
const actual = result.actual[this.entity] || result.actual,
marker = actual.revision ?? actual.updatedDate;
if (!result.verified && !result.unknown && prior) {
const previous = (await this.item()).canaries.find(c => c.sourceId === sourceId),
attempted = previous?.repairAttempts?.some(a => a.contractDigest === this.repairContractDigest);
if (this.entity !== 'order' && this.repair && prior.contractDigest !== this.repairContractDigest && !attempted && previous?.marker !== undefined && previous.marker === marker) {
await this.mutate((g, e) => {
e.canaries.find(c => c.sourceId === sourceId).repairAttempts.push({
contractDigest: this.repairContractDigest,
markerBefore: marker,
outcome: 'pending',
at: this.now()
});
});
await this.protect(sourceId, {
repairAttempts: (await this.item()).canaries.find(c => c.sourceId === sourceId).repairAttempts
});
try {
await this.timeWrite(() => this.repair({
record,
expected,
targetId,
marker
}));
result = await this.observe(record, sourceId, targetId, expected);
newWrite = true;
} catch (e) {
await this.stop(e.code || 'unknown-repair-outcome');
return false;
}
await this.mutate((g, e) => {
const c = e.canaries.find(c => c.sourceId === sourceId);
c.repairAttempts.find(a => a.contractDigest === this.repairContractDigest).outcome = result.unknown ? 'unknown' : result.verified ? 'repaired' : 'still-mismatching';
});
} else await this.mutate((g, e) => {
e.listed ||= [];
e.listed.push({
sourceId,
targetId,
reason: this.entity === 'order' ? 'order-not-rewritten' : attempted ? 'repair-already-attempted' : 'changed-since-write'
});
});
}
await this.protect(sourceId, {
expected,
targetId,
...(newWrite ? {
contractDigest: this.repairContractDigest
} : {}),
outcome: result.verified ? 'verified' : result.unknown ? 'unknown' : 'mismatch',
repairAttempts: (await this.item()).canaries.find(c => c.sourceId === sourceId).repairAttempts,
...(newWrite ? {
marker: (result.actual[this.entity] || result.actual).revision ?? (result.actual[this.entity] || result.actual).updatedDate
} : {})
});
await this.mutate((g, e) => {
const c = e.canaries.find(c => c.sourceId === sourceId);
c.targetId = targetId;
c.outcome = result.verified ? 'verified' : result.unknown ? 'unknown' : 'mismatch';
if (newWrite) {
const v = result.actual[this.entity] || result.actual;
c.marker = v.revision ?? v.updatedDate;
}
e.retryStats = {
...this.reads.stats,
remainingMs: this.reads.remaining()
};
});
if (!result.verified) return false;
}
if ((await this.item()).suspectInterval) {
await this.stop('suspect-reconciliation-required');
return false;
}
await this.mutate((g, e) => {
e.status = 'passed';
e.stopReason = null;
e.listed = [];
e.resumeAfter = e.schedule.canarySourceIds.at(-1) || null;
});
await approval.createAcknowledgement(this.projectDir, this.runId, this.entity);
return true;
}
// Durably records an approved writer guard for one source record, from the findings the writer
// returned for that record's write. Bulk imports call this after each write that returned
// findings (only a recognized guard finding persists anything). Returns the guarded paths.
async recordGuard(sourceId, findings) {
const paths = guardPathsFrom(this.entity, findings);
if (!paths.length) return [];
sourceId = String(sourceId);
const prior = await this.protected(sourceId);
await this.protect(sourceId, {
guardDroppedPaths: [...new Set([...(prior?.guardDroppedPaths || []), ...paths])]
});
await this.mutate((g, e) => {
e.guardDropped ||= [];
for (const p of paths) if (!e.guardDropped.some(d => d.sourceId === sourceId && d.path === p)) e.guardDropped.push({
sourceId,
path: p,
kind: 'guard-dropped'
});
e.attemptedPaths = (e.attemptedPaths || []).filter(a => !(a.sourceId === sourceId && paths.includes(a.writePath)));
});
return paths;
}
// Expected body for a read-only check: rebuilt from the source record, minus only the paths a
// recorded writer guard dropped for this record. Every other field stays loss-checked.
async expectedFor(record, sourceId) {
return applyGuards(this.entity, await this.buildWrite(record), (await this.protected(String(sourceId)))?.guardDroppedPaths);
}
async verifySample({
record,
sourceId,
targetId,
index,
isLast = false,
findings
}) {
if (!Number.isInteger(index) || index < 1) throw new Error('Sample index is one-based stable source order');
if (findings) await this.recordGuard(sourceId, findings);
if (index % 200 !== 0 && !isLast) return {
skipped: true
};
const expected = await this.expectedFor(record, sourceId);
let result;
try {
result = await this.observe(record, String(sourceId), targetId, expected);
} catch (e) {
result = {
verified: false,
unknown: true,
reason: e.code || 'unknown-read'
};
await this.stop(result.reason);
}
await this.protect(String(sourceId), {
expected,
actual: result.actual || null,
targetId,
verificationType: 'sample',
outcome: result.verified ? 'verified' : 'unknown'
});
await this.mutate((g, e) => {
if (isLast) e.endOfRunVerified = result.verified === true;
if (result.verified) {
e.lastGoodIndex = index;
e.lastGoodSourceId = String(sourceId);
} else e.suspectInterval = {
fromIndex: (e.lastGoodIndex || 0) + 1,
toIndex: index,
count: index - (e.lastGoodIndex || 0),
sourceIds: this.validated.inventory.records.slice(e.lastGoodIndex || 0, index).filter(r => !r.held).map(r => r.sourceId)
};
});
return result;
}
async reconcileInterval(getRecord, targetIdFor) {
const item = await this.item();
// The interval names every non-held record between the last good sample and the failed one,
// landed or not. Only a record with a target can have been written while the sample was
// failing; it is read back and compared. A record with no target is listed, never read --
// unless this gate holds it as a possibly-sent write, which stops the reconcile instead.
const noTargetSourceIds = [];
for (const id of item.suspectInterval?.sourceIds || []) {
const targetId = await targetIdFor(id);
if (noTarget(targetId)) {
if ((await this.protected(id))?.uncertain) { await this.stop('suspect-write-outcome-unknown'); return false; }
noTargetSourceIds.push(String(id));
continue;
}
const record = await getRecord(id);
try {
const result = await this.observe(record, id, targetId, await this.expectedFor(record, id));
if (!result.verified) return false;
} catch (e) {
await this.stop(e.code || 'unknown-reconciliation');
return false;
}
}
await this.mutate((g, e) => {
e.reconciledInterval = { ...e.suspectInterval, noTargetSourceIds };
e.suspectInterval = null;
e.status = 'passed';
e.stopReason = null;
});
return true;
}
}
const noTarget = id => id === undefined || id === null || id === '' || id === 'undefined';
function operatorActions(gate) {
const rows = [];
for (const [runId, run] of Object.entries(gate.runs)) for (const [entity, item] of Object.entries(run.entities || {})) {
if (item.supersededBy && gate.runs[item.supersededBy]?.entities?.[entity]) continue;
if (item.gated === false && !Object.hasOwn(C.DOMAINS, entity)) { declaration(entity, item); continue; }
// A run that wrote nothing of this entity defers to the runs that did. With no such
// run anywhere the entity was never gated, and it still blocks (not attempted is never success).
if (item.stopReason === 'not-run-no-writes' && Object.entries(gate.runs).some(([id, other]) => id !== runId && other.entities?.[entity] && other.entities[entity].stopReason !== 'not-run-no-writes' && !(other.entities[entity].supersededBy && gate.runs[other.entities[entity].supersededBy]?.entities?.[entity]))) continue;
const prompt = `Requires Import Operator: In the migration project, resume read-back verification for ${entity} in run ${runId}; inspect execution/read-back-gate.json. Resolve the named mapping/credential/coverage finding; for media settlement wait and resume reads of confirmed ids without rewriting. Regenerate the completion report.`;
if (item.status !== 'passed' || !item.endOfRunVerified) rows.push({
code: 'read-back-gate-stopped',
severity: 'critical',
entity,
affectedCount: item.canaries?.length || 0,
action: prompt,
deadlineReason: item.status === 'passed' && !item.canaries?.length && item.heldRecords?.count ? 'Before DNS change or launch: every record is held by the builder; nothing was imported' : 'Before DNS change or launch: entity import is unverified'
});
for (const listed of item.listed || []) rows.push({
code: 'read-back-listed-canary',
severity: 'high',
entity,
affectedCount: 1,
action: `${prompt} Resolve listed canary ${listed.sourceId} (${listed.reason}).`,
deadlineReason: 'Before DNS change or launch: this canary remains unresolved'
});
if (item.suspectInterval) rows.push({
code: 'read-back-suspect-interval',
severity: 'critical',
entity,
affectedCount: item.suspectInterval.count,
action: `Requires Import Operator: Run read-only reconciliation for ${entity} records ${item.suspectInterval.fromIndex}–${item.suspectInterval.toIndex}, then regenerate the completion report.`,
deadlineReason: 'Before DNS change or launch: sampled records may lack intended data'
});
if (item.heldRecords?.count) rows.push({
code: 'read-back-held-records',
severity: 'high',
entity,
affectedCount: item.heldRecords.count,
action: `Requires Import Operator: In the migration project, ${item.heldRecords.count} ${entity} records are held by the builder and were not attempted (${Object.entries(item.heldRecords.reasons).slice(0, 10).map(([r, n]) => `${r}: ${n}`).join(', ')}${Object.keys(item.heldRecords.reasons).length > 10 ? ', …' : ''}); execution/read-back-inventory/${entity}.json lists each. Resolve the named decisions, re-run inventory and validate, then resume.`,
deadlineReason: 'Before DNS change or launch: held records are not imported'
});
if (item.approvedOmissions?.some(o => o.merchantAcknowledgement?.status !== 'acknowledged')) rows.push({
code: 'read-back-omission-ack',
severity: 'high',
entity,
affectedCount: item.approvedOmissions.every(o=>o.affectedScope?.sourceIdsComplete && Array.isArray(o.affectedScope.sourceIds))
? new Set(item.approvedOmissions.flatMap(o=>o.affectedScope.sourceIds)).size
: item.approvedOmissions.some(o=>o.recordCount==null) || item.approvedOmissions.length>1 && item.approvedOmissions.some(o=>o.affectedScope)
? null : Math.max(...item.approvedOmissions.map(o => o.recordCount)),
action: `Tell the merchant these fields were not migrated: ${item.approvedOmissions.slice(0, 10).map(o => o.path).join(', ')}${item.approvedOmissions.length > 10 ? `, and ${item.approvedOmissions.length - 10} more (${item.approvedOmissions.length} locations; ${(item.pendingAcknowledgementRequest?.artifactRefs || []).some(r => r?.path === approval.evidencePath(entity, item.pendingAcknowledgementRequest.requestId)) ? approval.evidencePath(entity, item.pendingAcknowledgementRequest.requestId) : `execution/read-back-gate.json ${entity} approvedOmissions`} lists each)` : ''}. Requires Import Operator: In the migration project, run replatform answer --project <project> ${item.approvedOmissions[0].merchantAcknowledgement?.requestId || '<request-id>'} --acknowledge --note '<who acknowledged and when>'; regenerate completion.`,
deadlineReason: 'Before DNS change or launch: merchant acknowledgement required'
});
}
return rows;
}
// The gate sequence for one gated entity, owned by the toolkit so generated code does
// not wire it by hand. Generated code supplies the reviewed builder, the gate's entity options
// (marker, variants, read, lookup, repair) and the writer:
// write(record, expected) -> one record's confirmed write ({ id|targetId, findings }) or
// exactly { deferred: true, reason } before anything was sent;
// writeBatch(records) -> optional; [{ sourceId, targetId, findings }] for the non-canary
// records (a bulk writer). Defaults to write() per record.
// Order, as rp-import-codegen describes it: load the inventory and prepare; reconcile a suspect
// interval carried from an earlier run; settle canaries an earlier run sent and the target refused
// with a readable 4xx (never created, so written again); canaries; then the remaining records in
// stable source order, sampled at every 200th and the last landed record; a failed sample stops
// new batches until reconcileInterval clears it. Gate rules are unchanged.
const NOT_CREATED = row => row?.status === 'failed_terminal' && !row.targetId && Number.isInteger(row.failure?.httpStatus) && row.failure.httpStatus >= 400 && row.failure.httpStatus < 500 && ![408, 429].includes(row.failure.httpStatus);
async function runGatedEntity({
records,
sourceIdOf = record => String(record.id),
sourceKeyOf,
writeBatch,
batchSize = 200,
targetIdFor,
...options
} = {}) {
if (!Array.isArray(records)) throw new Error('runGatedEntity requires records');
if (!Number.isInteger(batchSize) || batchSize < 1 || 200 % batchSize !== 0) throw new Error('runGatedEntity batchSize must divide the 200-record sample interval');
const gate = new ReadBackGate(options),
entity = options.entity;
const byId = new Map(records.map(record => [String(sourceIdOf(record)), record]));
const getRecord = async id => {
const record = byId.get(String(id));
if (!record) throw problem('gated-record-not-in-input');
return record;
};
const result = (status, extra = {}) => ({ entity, status, ...extra });
const inv = await state.readJson(options.projectDir, `execution/read-back-inventory/${entity}.json`, null);
if (!inv) {
await gate.stop('read-back-inventory-missing');
return result('stopped', { stopReason: 'read-back-inventory-missing', written: [] });
}
try {
await gate.prepare(inv);
} catch (e) {
return result('stopped', { stopReason: e.code || 'gate-prepare-failed', errors: e.errors, written: [] });
}
const landed = new Map();
const targetOf = async id => landed.get(String(id)) || (targetIdFor && await targetIdFor(String(id))) || (await gate.protected(String(id)))?.targetId;
let item = await gate.item();
if (item.suspectInterval && !(await gate.reconcileInterval(getRecord, targetOf))) return result('stopped', { stopReason: (await gate.item()).stopReason || 'suspect-reconciliation-required', written: [] });
if (sourceKeyOf) {
const { rows } = await require('./local-state').loadAttemptJournal(options.projectDir).catch(e => { if (e.code === 'ENOENT') return { rows: [] }; throw e; });
const latest = new Map();
for (const row of rows) latest.set(row.sourceStableKey, row);
for (const id of item.schedule.canarySourceIds || []) {
const prior = await gate.protected(id), row = latest.get(sourceKeyOf(String(id)));
if (prior && !prior.targetId && prior.uncertain === true && prior.outcome !== 'not-sent' && NOT_CREATED(row)) await gate.protect(id, { uncertain: false, sentAt: null, outcome: 'not-sent', notSentReason: `target-rejected-${row.failure.httpStatus}:${row.attemptId}` });
}
}
if (!(await gate.executeCanaries(getRecord))) {
item = await gate.item();
return result(item.status, { stopReason: item.stopReason, written: [] });
}
item = await gate.item();
const canaries = new Set((item.schedule.canarySourceIds || []).map(String));
for (const c of item.canaries || []) if (c.targetId) landed.set(String(c.sourceId), c.targetId);
// Stable source order is the inventory's; held records are never written.
const order = inv.records.filter(r => !r.held && byId.has(String(r.sourceId))).map(r => String(r.sourceId));
const position = new Map(order.map((id, i) => [id, i + 1]));
const rest = order.filter(id => !canaries.has(id));
const written = [];
const writeOne = async record => {
const expected = await gate.expectedFor(record, sourceIdOf(record));
const out = await gate.timeWrite(() => options.write(record, expected));
if (out?.deferred === true) return { sourceId: String(sourceIdOf(record)), deferred: true, reason: out.reason };
return { sourceId: String(sourceIdOf(record)), targetId: writtenTargetId(entity, out), findings: out?.findings };
};
// Batches never cross a 200-record sample boundary of the source order, so a failed sample
// stops every record after it (canaries leave gaps, so slicing `rest` alone would not align).
const batches = [];
for (const id of rest) {
const window = Math.floor((position.get(id) - 1) / 200), last = batches.at(-1);
if (last && last.window === window && last.ids.length < batchSize) last.ids.push(id);
else batches.push({ window, ids: [id] });
}
let lastLanded = null;
for (const [batchIndex, { ids }] of batches.entries()) {
const batch = await Promise.all(ids.map(getRecord));
const outcomes = writeBatch ? await gate.timeWrite(() => writeBatch(batch)) : [];
if (!writeBatch) for (const record of batch) outcomes.push(await writeOne(record));
const isFinalBatch = batchIndex === batches.length - 1;
const confirmed = (outcomes || []).filter(o => o && o.targetId && byId.has(String(o.sourceId)));
for (const o of outcomes || []) if (o) written.push(o);
for (const o of confirmed) landed.set(String(o.sourceId), String(o.targetId));
for (const [n, o] of confirmed.entries()) {
const id = String(o.sourceId), isLast = isFinalBatch && n === confirmed.length - 1;
const sample = await gate.verifySample({ record: await getRecord(id), sourceId: id, targetId: String(o.targetId), index: position.get(id), isLast, findings: o.findings });
if (isLast) lastLanded = id;
if (!sample.skipped && !sample.verified) {
if (!(await gate.reconcileInterval(getRecord, targetOf))) {
item = await gate.item();
return result(item.status, { stopReason: item.stopReason || 'read-back-sample-failed', written });
}
}
}
}
// Every non-canary record landed earlier, or none remained: the end-of-run check reads the last
// landed record in source order, so a resume still verifies the entity's tail.
if (!lastLanded) {
const tail = [...order].reverse().find(id => landed.has(id));
if (tail && !canaries.has(tail)) await gate.verifySample({ record: await getRecord(tail), sourceId: tail, targetId: landed.get(tail), index: position.get(tail), isLast: true });
else if (tail) await gate.mutate((g, e) => { e.endOfRunVerified = e.canaries.find(c => String(c.sourceId) === tail)?.outcome === 'verified'; });
// Nothing landed (every write deferred): no claim either way; prepare's own rule stands.
}
item = await gate.item();
return result(item.status, { stopReason: item.stopReason || null, endOfRunVerified: item.endOfRunVerified === true, written });
}
module.exports = {
ReadBackGate,
declaration,
operatorActions,
runGatedEntity
};
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