Wix Replatform
WixOfficialPublished by Wix
- Skill
- Workflow
- Automation and integrations
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
wix-replatform acts as a central supervisor for migrating data and content to Wix. It does not perform migration tasks directly but instead inspects migration artifacts to determine the next required stage in the pipeline. By maintaining a deterministic state, it ensures that migrations can be started, resumed, or recovered reliably without duplicating work or creating redundant destination sites. It manages the flow through various phases including discovery, mapping, setup, and import, while enforcing strict validation and approval gates.
What it does
- Routes migration tasks to appropriate sub-modules based on current project state.
- Ensures resumability by tracking migration progress through authoritative artifacts.
- Enforces mandatory approval gates before performing write operations.
- Dispatches specialized subagents for specific tasks to maintain context boundaries.
- Validates artifacts at each stage to prevent proceeding with corrupted or stale data.
- Handles reruns for incremental data updates without re-scaffolding the entire project.
When to use it
- When initiating a new migration from an external source to a Wix site.
- When resuming a migration that was interrupted or stopped.
- When recovering from a failed migration stage by addressing specific errors.
- When performing incremental imports to sync new or modified records after an initial migration.
Advantages
- Prevents data duplication by enforcing idempotent write operations.
- Maintains a clear audit trail through structured telemetry and completion reports.
- Reduces risk by requiring explicit approvals before critical setup or import steps.
- Supports both standard interactive flows and automated 1-click execution modes.
Usage examples
- “Start a new migration for my project in ./migrations/my-store.”
- The agent resolves the project directory, initializes orchestration artifacts, and routes to the project intake module.
- “Resume the migration in ./migrations/my-store.”
- The agent inspects the existing artifacts, determines the last completed stage, and dispatches the next required module.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/wix/wix-replatform-fya3/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip wix-replatform.zip -d .agents/skills
Documentation by Wix
wix-replatform
wix-replatform is the compact supervisor for a resumable source-to-Wix migration. It
selects one internal module for the active stage; it does not carry every stage procedure
in its own context.
Always-active contract
Resolve the active project under
migrations/<project>/(orREPLATFORM_MIGRATIONS_DIR) before inspecting or creating anything. Only that project's artifacts are authoritative.Preserve
EXPECTATIONS.mdat that project root. It is the user's free-form record of how they expected the run to behave; initialization creates it once and never overwrites it.Start/resume
resources/rp-telemetry/at the beginning of every run and finalize it at a terminal state. Never hand-write telemetry events.Use orchestration JSON plus validated stage artifacts as resume authority. Logs and chat history are diagnostic context only.
Preserve user data: write idempotently, dedupe by source identity, resume rather than restart, and never create a second destination site for a migration.
Never print secrets, secret-bearing config contents, tokens, or credentials. Report only key names and present/blank/missing status.
Do not declare a migration complete from prose or a single artifact. The deterministic router and aggregate completion artifact own terminal completion.
Preserve the owner's cutover handoff: unresolved data, applicable manual setup, missing apps and changed plugin behavior. Reconcile discovery, mapping decisions, setup receipts and final outcomes; imported records alone do not establish working functionality. The producing resources own this guidance and durable completion/handoff artifacts. Use a supported cutover publisher when available; report missing publication integration explicitly rather than claiming the application received local artifacts.
CLI-launched runs and human actions
When a migration is started through replatform, the terminal is deliberately
non-interactive: do not use an agent question UI, ask for stdin, or wait for a person in the
current agent turn. The runner owns process lifecycle and emits only observed events; it does
not replace this skill's router or completion receipts.
When a human choice, review, approval, or manual prerequisite is needed, create a durable
request with node skills/wix-replatform/scripts/user-action.js create --project <projectDir> --request-file <request.json>, then end the turn. Put only reviewed artifact paths in the
request. The person can later use replatform requests, replatform show, and
replatform answer; a resumed agent reads the answered request from
orchestration/user-actions/, never from reconstructed chat context.
Cancellation is not completion. If the runner has recorded cancel_requested, canceled, interrupted or an explicit stop (blocked,
transition --status blocked --resume-from '<json>'; routes run_blocked until explicit resume or --status running, never answer --continue), preserve partial/recovery
artifacts and let a later explicit replatform resume route recovery. Never create aggregate migration completion from an aborted execution report.
Pipeline
intake → destination → source inputs → preflight → (standard: discovery → mapping → codegen;
quick: adapter preflight → quick plan) → setup discovery → website handoff
→ safety review/approval → setup → import
→ storefront continuation (website only) → aggregate finalization → Migration reviewDelivery modes are management (backend only), website (frontend only), and
management_and_website (the integrated flow above). Accept user input both as
management_and_website and persist the canonical value.
For deliveryMode=management, aggregate finalization requires valid backend import
accounting. For deliveryMode=management_and_website, it additionally requires a current
website/completion.json with completed screenshot review, no unresolved critical/high
gaps, and release evidence. execution/completion-report.json is backend accounting,
never website-migration completion by itself.
Route before acting
On every new or resumed turn:
Resolve the project and initialize/load its orchestration artifacts.
Run
node skills/wix-replatform/scripts/orchestration-route.js <projectDir>.Dispatch the
nextResourceto a Developer subagent instead of loading and following it yourself. Give it the project directory and the resource to run; it follows that resource's contract exactly as written, unchanged. Read back only its result — never its transcript, tool output, or logs.Every dispatch (Developer or QA) is a fresh subagent, never a resumed one; pass only a handoff file and stay within a context budget — follow
resources/rp-subagent-dispatch/. Never readstate/attempts/write-attempts.ndjsonraw; usescripts/write-log-summary.js.A Developer may fan out to sub-subagents only for harmless read-only work with no shared state, and only if the host supports it; writes stay one at a time, as each resource says.
Dispatch a QA subagent to check the Developer's result against that resource's own stated required outputs (its own "artifacts to create or update" or "## Output" section, and any review/gap documents it defines). QA is read-only — it never writes or calls Wix. If something's missing, dispatch a new Developer for the same resource with QA's findings; otherwise the stage is done.
At the end of each pipeline phase (discovery, mapping, setup discovery, import, and so on — see the pipeline above; a phase spans several resource-level stages), dispatch a QA subagent to review that phase's documents as a whole (for example
mapping/review/mapping-summary.mdandmapping-gaps.json, orexecution/completion-report.json) before routing to the next phase. This catches anything a single per-task check could miss. For the import phase specifically, this review must be entity-by-entity against the accepted mapping plan, not a skim of the top-level status string — seerp-execute-import's "Entity-by-entity QA" section. Any run-fixing dispatch mid-phase (a crash fix, a slowness fix, a resumed pass) does not itself satisfy this; run the phase-level QA again once the fix lands, since fixing one entity's defect certifies nothing about its neighbors. Mapping QA also checks exact source coverage, decided operation/path semantics and canonical projections. Codegen QA reads the Developer's independently expected synthetic request evidence and its freshness; it does not execute examples. Semantic defects return to mapper, implementation defects to codegen. One-click tests defer unresolved scope and finish independent work with a typed incomplete result, without questions or repeated redispatch; customer runs retain their existing checkpoints.Route again after every stage boundary. Stale requests use
resources/rp-user-action-recovery/; unreadable request artifacts block until repaired. Never discard pending requests or decide the next stage from memory.
The router (lib/orchestration-router.js) is the only routing and resume authority. It
recomputes the route from decisions, approvals, preflight, run.json status and the phase
outputs on every call; run.json.currentState is diagnostic only, never a routing input.
A recorded rejection stops the route in every mode, one-click included:
execution_approval_rejectedisblockedbefore any setup or import write, andmapping_approval_rejectedreturns torp-mapperfor a new plan.A gated output that exists but is unusable (
source_schema_invalid,mapping_plan_invalid,setup_plan_invalid,setup_requirements_invalid,execution_manifest_invalid) isblockedwitherrorsand the producer asnextResource. Do not re-run the producer automatically; report the errors to the Import Operator and stop.The import routes (
missing_completion_report,import_interrupted= a stopped run's aborted report,quick_mode_import_required) carryimportProgress.interruptedlistsrecoveryArtifacts: resume it, never a second import.interruptedReport: "missing": first runscripts/interrupted-completion-report.js.
If an artifact is malformed, partial, stale, or fails its validator, treat its producing stage as incomplete and route to the producer. Do not make parallel replacement artifacts.
A user action whose reviewed artifacts changed after it was created is refused with
user_action_stale and stays pending. Create a new request from the current artifacts.
Catching up a finished migration is a rerun, not a new project. When the user asks to pull
in records that arrived or changed since the import — "the source kept selling", "these orders
are missing", "re-run it" — reuse the same project, destination, mapping, generated importer
and crosswalk, and route to rp-execute-import → "Rerunning an import for new and modified
records". Do not scaffold a second project or re-approve an unchanged mapping; a
mapping or scope change does go back through the existing gates. A rerun's revision conflicts
are user decisions even in 1-click mode.
Demand-loaded module map
| Router situation | Dispatch |
|---|---|
| project, delivery mode, source mode, or grouped intake is unresolved | resources/rp-project-intake/ |
| destination is absent, conflicting, or needs creation/adoption | resources/rp-destination/ |
| source URL/files/config/acquisition mode/credentials are required, including source credentials said to exist already on another site | resources/rp-source-inputs/ |
| deterministic preflight is missing, repaired, or blocked on CLI checks | resources/rp-preflight/ |
| quick mode needs platform resolution, endpoint preflight, plan, extraction, or import | selected resources/rp-quick-<platform>/ |
| source schema is missing | resources/rp-discovery/ and its selected source adapter |
| mapping is missing or needs review | resources/rp-mapper/ |
| Wix requirements are missing | resources/rp-setup-discovery/ |
| import code/review is missing or stale | resources/rp-import-codegen/ |
| setup verification is missing | resources/rp-execute-setup/ |
| backend completion report is missing | resources/rp-execute-import/ |
| frontend-only work, or integrated website handoff/build/gap loop/release receipt is incomplete | resources/rp-website-continuation/ |
| aggregate completion is missing | resources/rp-execution-policy/ |
| aggregate completion exists but the local review publication or current recap is missing | resources/rp-migration-review/ |
The resource named by the route is the complete stage contract, dispatched as described in "Route before acting" — the main session itself never loads it directly. Only the dispatched Developer loads source-file, secret, scaffolding, or storefront procedures, and only for the stage that actually needs them; nothing about a stage where they're irrelevant is loaded, by the main session or the Developer.
Interaction policy
Normal mode asks only for a missing required input, a genuinely ambiguous active project, or a mandatory write approval. Ask one question at a time unless a module says otherwise.
When the user says add to expectations: <note> (or an unambiguous natural-language
equivalent), append the note to the active project's EXPECTATIONS.md before continuing.
Use scripts/expectations-ledger.js so the entry retains the supplied statement plus safe
current context (stage/state, relevant project-relative artifacts, and known entity/field
labels). Do not treat this as approval or silently change a mapping. Never record secrets,
tokens, raw customer data, or raw source records; redact them if supplied and say so.
Before writes, preserve the mandatory execution-plan approval gate. Read-only discovery, mapping, setup verification, code generation, and review happen before it.
Quick management import mode
When managementImportMode=quick, select the platform adapter only after the deterministic
source probe identifies a compatible platform. Quick mode is a bounded public-data import:
the adapter's versioned quick-mode.json owns its source routes, entity graph, field matrix,
and exclusions. Do not run agentic discovery, mapping, or project-specific code generation for
the quick backend branch. Still run destination setup, application installation, Catalog-V3 and
notification safety checks, execution approval, shared write runtime, crosswalks, and completion
accounting. If no adapter qualifies, persist the unsupported-mode result and ask the user to
select standard mode; never silently fall back.
Halt only for missing/invalid required input, a manual action with no API, or a systemic failure/data-loss risk. A halt must persist the code, evidence, owner, and exact unblock action; never silently stop.
1-click mode
When explicitly requested by the user, record automationMode=one_click with
source=user and apply the following. A missing mode or a one_click value recorded as
deterministic_inference/prior_artifact is normal interactive mode and must not skip a
checkpoint:
collect all still-missing intake values in one grouped request; then do not pause for routine approvals;
record mapping and execution approvals as
approved,decidedBy=agent; skipping a pause without state is invalid;for CSV/file-only runs, validate and accept the required sample preview as the agent; without explicit user-authored one-click, pause for the normal mapping review, sample preview validation, and execution approval;
default to a new isolated site unless an existing destination is explicitly supplied or already pinned, but never default the new site's type (Headless, Studio or Harmony): ask it in the grouped intake; choose website scope deterministically from discovered route families;
retry PATH/tool-resolution failures under the operator's compatible interactive login shell; request required browser/network sandbox escalation and retry before calling it blocked;
retry the obvious recovery before stopping: aligned shell first for PATH/tool failures, then the required escalation retry for sandboxed browser or network/API failures;
continue through the complete selected deliverable. In
management_and_websitemode that includes frontend build, post-build gap analysis, bounded fix loop, and release receipt; when the user selected facelift at intake, it also includes the separate post-clone facelift review;before yielding, re-route. A 1-click run is only
completedwithcompletion/migration-completion.json, orblockedwith a typed durable blocker.
Use the operator's compatible local Node/Yarn shell when recovering from a PATH or tool resolution failure. Machine-specific shell paths belong only in local, git-excluded agent instructions.
Repo-local interactive shell contract: a PATH/tool-resolution failure on first attempt may
mean the command ran under a plain, non-interactive shell that never sourced the operator's
Node/Yarn profile. Resolve the operator's compatible login shell from the local environment or
git-excluded agent instructions, verify that it is executable, and retry the exact same command
through that shell in interactive login mode so the profile that resolves node/yarn/npx
loads. Do not hardcode a machine-specific shell path in this public skill. Only escalate to a
durable blocker if the compatible-shell retry itself fails.
Guardrails
Never bypass a validator, approval-state update, verified notification mute, or Catalog-V3 gate to make a stage appear finished.
websitemeans frontend only;management_and_websitemeans the integrated backend and frontend migration. Never hand the integrated migration destination to the frontend skill or create a second frontend site in that mode.A Studio or Harmony destination (
targetSiteType) is created and verified byrp-destination's coordinator and is never published, unpublished or handed towix-headless-replatform; its website and publication remain operator handoff items.Do not implement a storefront manually when
wix-headless-replatformis unavailable; persist a blocker with the exact required runtime capability.In management mode, still generate
website/handoff.*after setup discovery so a later storefront can start without repeating backend discovery.
Files
- .publish-manifest.json210 B
- ATTRIBUTION.mdAdded by AutoGineer815 B
- CLI.md9.8 KiB
- LICENSELicence file added by AutoGineer1.0 KiB
- README.md11.9 KiB
- SKILL.md16.4 KiB
- VERSION6 B
- console/account.css633 B
- console/app.css5.2 KiB
- console/app.jsScript22.9 KiB
- console/index.html837 B
- console/json.css639 B
- lib/agent-adapters/index.jsScript2.9 KiB
- lib/app-page-routing.jsScript4.3 KiB
- lib/app-requirements.jsScript1.5 KiB
- lib/artifact-freshness.jsScript12.7 KiB
- lib/blocked-data-requests.jsScript21.4 KiB
- lib/cached-json.jsScript1.3 KiB
- lib/catalog-baseline.jsScript23.3 KiB
- lib/census-reconciliation.jsScript22.8 KiB
- lib/cms-collection-compatibility.jsScript2.0 KiB
- lib/completion-report.jsScript124.6 KiB
- lib/config-env.jsScript6.1 KiB
- lib/confirmed-pictures.jsScript6.9 KiB
- lib/crosswalk-adoption.jsScript6.3 KiB
- lib/dependency-proofs.jsScript46.7 KiB
- lib/dependency-readiness.jsScript112.3 KiB
- lib/dependency-recovery.jsScript1.5 KiB
- lib/dependency-waves.jsScript2.1 KiB
- lib/destination-choice.jsScript9.7 KiB
- lib/destination-handoff.jsScript12.5 KiB
- lib/destination-http.jsScript2.7 KiB
- lib/destination-route.jsScript5.1 KiB
- lib/destination.jsScript57.1 KiB
- lib/discovered-census.jsScript11.0 KiB
- lib/discovered-set-status.jsScript15.2 KiB
- lib/document-url-guard.jsScript12.7 KiB
- lib/editor-type.jsScript748 B
- lib/egress-proxy.jsScript20.8 KiB
- lib/entity-qa-attestation.jsScript19.4 KiB
- lib/entity-verification.jsScript1.3 KiB
- lib/execution-capability.jsScript7.3 KiB
- lib/execution-log.jsScript6.4 KiB
- lib/execution-manifest.jsScript10.2 KiB
- lib/execution-state.jsScript5.9 KiB
- lib/expectations-ledger.jsScript3.4 KiB
- lib/extract-ledger.jsScript21.4 KiB
- lib/field-mapping-examples.jsScript7.3 KiB
- lib/generated-plugin-handoff.jsScript8.7 KiB
- lib/import-interruption.jsScript13.6 KiB
- lib/import-readiness-contract.jsScript4.3 KiB
- lib/import-recovery.jsScript54.0 KiB
- lib/import-task-runner.jsScript18.1 KiB
- lib/imported-redirect-targets.jsScript32.5 KiB
- lib/internal-link-reconciliation.jsScript10.7 KiB
- lib/link-audit.jsScript11.1 KiB
- lib/link-census.jsScript11.0 KiB
- lib/link-plan.jsScript9.4 KiB
- lib/link-verification.jsScript18.7 KiB
- lib/link-waivers.jsScript5.8 KiB
- lib/link-write-journal.jsScript1.8 KiB
- lib/local-state.js66.8 KiB
- lib/mapping-field-contract.js54.1 KiB
- lib/mapping-omission-approval.js7.6 KiB
- lib/mapping-recovery.js22.4 KiB
- lib/mapping-resolution.js6.1 KiB
- lib/mapping-target-rules.js7.4 KiB
- lib/member-completion.js31.6 KiB
- lib/member-crosswalk.js2.9 KiB
- lib/member-outcome-registry.js13.6 KiB
- lib/migration-completion.js18.3 KiB
- lib/migration-review-mapping.js21.4 KiB
- lib/migration-review.js73.7 KiB
- lib/multi-step-attempt.js4.4 KiB
- lib/multilingual-public-report.js14.5 KiB
- lib/multilingual-public.js26.3 KiB
- lib/notification-mute.js9.9 KiB
- lib/operation-assessments.js9.8 KiB
- lib/operator-identity.js1.2 KiB
- lib/orchestration-decisions.js8.7 KiB
- lib/orchestration-preflight.js25.1 KiB
- lib/orchestration-router.js50.8 KiB
- lib/orchestration-state.js30.9 KiB
- lib/order-reference-readiness.js2.8 KiB
- lib/output-applicability.js5.0 KiB
- lib/payments-outcome-registry.js9.8 KiB
- lib/plan-order-outcome-registry.js13.1 KiB
- lib/plugin-cms-fallback.js35.1 KiB
- lib/preservation-approval-stamp.js2.8 KiB
- lib/product-media-deferral.js3.8 KiB
- lib/product-videos.js7.1 KiB
- lib/progress-log.js6.6 KiB
- lib/progress-log.sh4.1 KiB
- lib/raw-request-guard.js18.5 KiB
- lib/read-back-approval.js16.1 KiB
- lib/read-back-comparison.js10.5 KiB
- lib/read-back-contract.js37.4 KiB
- lib/read-back-extract.js4.0 KiB
- lib/read-back-gate.js46.6 KiB
- lib/read-back-reads.js2.9 KiB
- lib/read-back-state.js3.4 KiB
- lib/read-back-summary.js6.5 KiB
- lib/rerun-conflicts.js14.5 KiB
- lib/run-controller.js26.3 KiB
- lib/seo-outcome-registry.js3.2 KiB
- lib/setup-producers.js1.3 KiB
- lib/setup-verification.js11.6 KiB
- lib/site-regional-gate.js3.3 KiB
- lib/site-regional-report.js10.3 KiB
- lib/site-regional.js37.0 KiB
- lib/source-access.js11.2 KiB
- lib/source-coverage.js54.0 KiB
- lib/source-location.js10.6 KiB
- lib/source-redirect-capture.js2.6 KiB
- lib/source-regional.js15.5 KiB
- lib/source-secrets.js8.1 KiB
- lib/structured-link-patch.js3.1 KiB
- lib/subagent-handoff.js8.9 KiB
- lib/target-import-support.js18.4 KiB
- lib/task-state.js6.2 KiB
- lib/toolkit-dependencies.js947 B
- lib/url-preservation-report.js20.4 KiB
- lib/url-preservation-state.js27.0 KiB
- lib/url-redirect-plan.js36.3 KiB
- lib/url-verification.js15.5 KiB
- lib/user-action-effects.js2.9 KiB
- lib/user-actions.js18.4 KiB
- lib/vendor-closure.js5.6 KiB
- lib/website-handoff.js60.6 KiB
- lib/wix-auth.js11.0 KiB
- lib/wix-client-callers.js6.7 KiB
- lib/wix-dashboard-url.js1.0 KiB
- lib/write-log-summary.js9.4 KiB
- lib/write-verification-state.js7.9 KiB
- lib/write-verification.js30.0 KiB
- scripts/artifact-freshness.js2.3 KiB
- scripts/census-reconciliation.js781 B
- scripts/cms-fallback.js3.2 KiB
- scripts/cms-item-quota.js3.9 KiB
- scripts/crosswalk-adopt.js3.0 KiB
- scripts/dependency-preflight.js2.2 KiB
- scripts/discovered-census.js867 B
- scripts/discovered-set-status.js1.1 KiB
- scripts/entity-qa-attestation.js4.8 KiB
- scripts/execution-health-check.js19.9 KiB
- scripts/execution-manifest-validate.js1.7 KiB
- scripts/execution-state-prepare.js3.9 KiB
- scripts/expectations-ledger.js1.5 KiB
- scripts/extract-ledger.js1.9 KiB
- scripts/import-contract-verify.js20.4 KiB
- scripts/import-supervise.js16.1 KiB
- scripts/internal-link-audit.js6.5 KiB
- scripts/interrupted-completion-report.js2.7 KiB
- scripts/item-seo-tags-verify.js8.2 KiB
- scripts/link-waiver.js3.8 KiB
- scripts/migration-completion.js3.8 KiB
- scripts/migration-review.js3.7 KiB
- scripts/orchestration-preflight.js3.5 KiB
- scripts/orchestration-route.js3.7 KiB
- scripts/orchestration-state.js18.9 KiB
- scripts/read-back-gate.js11.3 KiB
- scripts/replatform-console.js12.9 KiB
- scripts/replatform.js35.4 KiB
- scripts/site-regional.js2.4 KiB
- scripts/source-secrets.js2.9 KiB
- scripts/subagent-handoff.js2.5 KiB
- scripts/url-redirects.js13.0 KiB
- scripts/user-action.js2.9 KiB
- scripts/vendor-closure.js1.0 KiB
- scripts/website-handoff-generate.js2.3 KiB
- scripts/wix-dashboard-url.js1.6 KiB
- scripts/wix-destination.js6.4 KiB
- scripts/wix-env.js1.5 KiB
- scripts/wix-headless-scaffold.js34.8 KiB
- scripts/write-log-summary.js2.2 KiB
- vendor/README.md604 B
- vendor/commander/LICENSE1.1 KiB
- vendor/commander/index.js711 B
- vendor/commander/lib/argument.js3.1 KiB
- vendor/commander/lib/command.js85.6 KiB
- vendor/commander/lib/error.js1.1 KiB
- vendor/commander/lib/help.js20.3 KiB
- vendor/commander/lib/option.js10.0 KiB
- vendor/commander/lib/suggestSimilar.js2.7 KiB
- vendor/commander/package.json1.6 KiB
lib/dependency-proofs.js
'use strict';
// Dependencies that need no separate producer.
//
// A target dependency is normally satisfied by a producer: an import task, setup steps, or an
// approved census disposition. Some are not produced separately at all: the related data is absent
// (`no-data`), the dependent write itself creates or resolves it (`within-write`), or the approved
// mapping writes none of its references (`not-referenced`). This module validates those proofs
// against the reviewed operation contract in target knowledge and resolves the whole dependency
// graph with one pure function, so the mapper (before approval), codegen (manifest) and the
// runtime gate apply the same rules. Bundled rules remain binding; mapper-authored, evidence-bound
// supplements can fill missing knowledge. Missing guards or evidence require investigation.
const fs = require('node:fs');
const path = require('node:path');
const crypto = require('node:crypto');
const assessments = require('./operation-assessments');
const REASONS = new Set(['no-data', 'within-write', 'not-referenced']);
const ABSENCE_KINDS = new Set(['zero-row', 'zero-match', 'capability-absent']);
const PREDICATE_OPS = new Set(['equals', 'in', 'present', 'startsWith']);
// Producers whose dependent writes nothing through a transitive ref, or whose own task binds it.
const INHERITABLE = new Set(['import-task', 'disposition', 'no-producer', 'secondary-output', 'child-output', 'inherited']);
const refPattern = /^[a-z0-9-]+\/[a-z0-9-]+$/;
const DOMAINS = path.join(__dirname, '../resources/rp-target-wix/domains');
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);
function canonical(value) {
if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']';
if (value && typeof value === 'object') return '{' + Object.keys(value).sort().map(key => JSON.stringify(key) + ':' + canonical(value[key])).join(',') + '}';
return JSON.stringify(value);
}
// The one loader for dependency knowledge, shared by the resolver and the runtime gate. Tests may
// point it at a fixture knowledge tree (the same idea as plugin-cms-fallback's targetKnowledgeRoot);
// the rules applied to whatever it loads never change.
let domainsRoot = DOMAINS;
function useTargetKnowledgeRoot(root) {
const prior = domainsRoot;
domainsRoot = root ? path.resolve(root) : DOMAINS;
return () => { domainsRoot = prior; };
}
const MISSING = Object.freeze({ code: 'ENOENT' });
function bundledDomain(ref) {
if (!refPattern.test(ref)) throw new Error(`entity_ref_unknown:${ref}`);
// Parsed once per file version; callers get their own copy, as they did from a fresh parse.
try { const found = require('./cached-json').readJson(path.join(domainsRoot, ref.split('/')[0], 'entities', ref.split('/')[1] + '.json'), MISSING); if (found === MISSING) throw MISSING; return structuredClone(found); }
catch (error) { if (error.code?.startsWith('mapping_assessment_')) throw error; throw new Error(`entity_ref_unknown:${ref}`); }
}
function domain(ref) { return assessments.effectiveDomain(ref, bundledDomain(ref)); }
// The reviewed contract for one write operation, by name or alias. Null when knowledge has none.
function operationContract(entityRef, operation) {
if (!operation) return null;
const contracts = domain(entityRef).operationContracts || {};
for (const [name, contract] of Object.entries(contracts)) if (name === operation || (contract.aliases || []).includes(operation)) return { name, contract };
return null;
}
// Prose (evidence, notes) may change without invalidating a proof; every field a check reads does.
function contractDigest(contract) {
const { evidence: _evidence, notes: _notes, ...semantic } = contract || {};
return hash(canonical(semantic));
}
// The refs a write operation actually depends on: an operation contract may declare an entity-level
// edge inapplicable (Import Order carries no Shipping Options or delivery-profile reference).
function applicableDependsOn(entityRef, operation) {
const deps = domain(entityRef).dependsOn || [];
const found = operationContract(entityRef, operation);
if (!found) return deps;
return [...new Set([...deps,...Object.keys(found.contract.dependencies || {})])].filter(ref => !found.contract.dependencies?.[ref]?.inapplicable);
}
function inapplicableRefs(entityRef, operation) {
const found = operationContract(entityRef, operation);
return found ? Object.entries(found.contract.dependencies || {}).filter(([, dep]) => dep.inapplicable).map(([ref]) => ref) : [];
}
function guardPath(guard) { return typeof guard === 'string' ? guard : guard?.path; }
function discriminated(guard) { return typeof guard === 'object' && guard !== null && guard.equals !== undefined; }
function stripInput(targetPath, writeInput) {
if (typeof targetPath !== 'string') return null;
return writeInput && targetPath.startsWith(writeInput + '.') ? targetPath.slice(writeInput.length + 1) : targetPath;
}
// Path templates overlap when one is the other or an ancestor of it; `[]` and `[n]` compare equal.
function pathsOverlap(a, b) {
const norm = value => value.replace(/\[\d*\]/g, '[]');
const x = norm(a), y = norm(b);
return x === y || y.startsWith(x + '.') || x.startsWith(y + '.') || y.startsWith(x + '[]') || x.startsWith(y + '[]');
}
// --- deterministic payload and record reads ---------------------------------------------------
function valuesAt(value, template) {
const parts = template.split('.'), out = [];
(function visit(node, index) {
if (index === parts.length) { out.push(node); return; }
if (node === null || typeof node !== 'object') return;
const part = parts[index], array = part.endsWith('[]'), key = array ? part.slice(0, -2) : part;
if (!Object.hasOwn(node, key)) return;
if (array) { if (Array.isArray(node[key])) for (const entry of node[key]) visit(entry, index + 1); }
else visit(node[key], index + 1);
})(value, 0);
return out;
}
// A guarded path is present when a payload carries a value there (and, for a discriminated guard,
// that value equals the discriminator). Presence contradicts a proof that no reference is written.
function guardHits(payload, guards) {
const hits = [];
for (const guard of guards || []) {
const template = guardPath(guard);
const values = valuesAt(payload, template).filter(value => value !== undefined && value !== null && value !== '');
if (values.some(value => typeof guard === 'string' || guard.equals === undefined || value === guard.equals)) hits.push(template);
}
return hits;
}
function validatePredicate(predicate) {
if (!predicate || typeof predicate !== 'object') return false;
if (Array.isArray(predicate.any)) return predicate.any.length > 0 && predicate.any.every(validatePredicate);
if (typeof predicate.path !== 'string' || !/^\w+(?:\[\])?(?:\.\w+(?:\[\])?)*$/.test(predicate.path) || !PREDICATE_OPS.has(predicate.op)) return false;
if (predicate.op === 'in') return Array.isArray(predicate.values) && predicate.values.length > 0;
if (predicate.op === 'equals' || predicate.op === 'startsWith') return predicate.value !== undefined && (predicate.op !== 'startsWith' || typeof predicate.value === 'string');
return true;
}
function predicateMatches(record, predicate) {
if (Array.isArray(predicate.any)) return predicate.any.some(clause => predicateMatches(record, clause));
const values = valuesAt(record, predicate.path);
if (predicate.op === 'present') return values.some(value => value !== undefined && value !== null && value !== '');
if (predicate.op === 'equals') return values.some(value => value === predicate.value);
if (predicate.op === 'in') return values.some(value => predicate.values.includes(value));
return values.some(value => typeof value === 'string' && value.startsWith(predicate.value));
}
// --- mapping-plan reads -----------------------------------------------------------------------
function rowOutputs(row) {
const outputs = [];
for (const mapping of row.fieldMappings || []) for (const output of mapping.outputs || []) if (output && typeof output === 'object') outputs.push(output);
return outputs;
}
// One exact write operation per dependent: the preferred writer, plus only the auxiliary operations
// its contract names. A single-create preference beside bulk-create outputs cannot share a proof.
function resolveRowOperation(row) {
const primary = row.preferredWrite?.writerId || null;
const ops = [...new Set(rowOutputs(row).filter(output => !output.targetRef || output.targetRef === row.targetRef).map(output => output.writeOperation).filter(Boolean))].sort();
const found = primary ? operationContract(row.targetRef, primary) : (ops.length === 1 ? operationContract(row.targetRef, ops[0]) : null);
if (!found) return { operation: primary || (ops.length === 1 ? ops[0] : null), contract: null, errors: [] };
const allowed = new Set([found.name, ...(found.contract.aliases || []), ...(found.contract.auxiliaryOperations || [])]);
const extra = ops.filter(op => !allowed.has(op));
return { operation: found.name, contract: found.contract, errors: extra.length ? [`dependency_operation_mixed:${row.targetRef}:${found.name}:${extra.join(',')}`] : [] };
}
// Held or excluded scope is never an executable producer or writer.
const INACTIVE = new Set(['excluded', 'rejected', 'deferred']);
const activeRows = (plan, readEntityMappings) => readEntityMappings(plan).filter(row => row && !INACTIVE.has(row.status));
function rowsByTarget(plan, readEntityMappings) {
const rows = new Map();
for (const row of readEntityMappings(plan)) {
if (!row?.targetRef || !refPattern.test(row.targetRef) || INACTIVE.has(row.status)) continue;
if (!rows.has(row.targetRef)) rows.set(row.targetRef, []);
rows.get(row.targetRef).push(row);
}
return rows;
}
// Paths the dependent's write sends: its own rows' outputs, plus any active output that names its
// write operation, whatever target it is labelled with — the operation decides the request body.
function mappedPaths(rows, targetRef, operation, contract, allRows = []) {
const ops = new Set([operation, ...(contract?.aliases || [])]);
const paths = [];
const add = output => { const target = stripInput(output.targetPath, output.writeInput); if (target) paths.push(target); };
for (const row of rows) for (const output of rowOutputs(row)) {
if (output.targetRef && output.targetRef !== targetRef) continue;
if (output.writeOperation && !ops.has(output.writeOperation)) continue;
add(output);
}
for (const row of allRows) if (!rows.includes(row)) for (const output of rowOutputs(row)) if (ops.has(output.writeOperation)) add(output);
return paths;
}
function mislabelled(plan, readEntityMappings, dependentRef, found) {
const ops = new Set([found.name, ...(found.contract.aliases || [])]);
for (const row of activeRows(plan, readEntityMappings)) for (const output of rowOutputs(row)) {
const targetRef = output.targetRef || row?.targetRef;
if (!ops.has(output.writeOperation) || targetRef === dependentRef) continue;
let owned = null;
try { owned = refPattern.test(targetRef || '') ? operationContract(targetRef, output.writeOperation) : null; } catch { owned = null; }
if (!owned) return true;
}
return false;
}
// --- proof validation -------------------------------------------------------------------------
function proofKey(entityRef, operation, ref) { return `${entityRef}|${operation}|${ref}`; }
function insideProject(projectDir, file) {
if (typeof file !== 'string' || !file) throw new Error('dependency_proof_evidence_path_invalid');
const root = path.resolve(projectDir), absolute = path.resolve(root, file);
if (!absolute.startsWith(root + path.sep)) throw new Error('dependency_proof_evidence_path_invalid');
return absolute;
}
// zero-match: a deterministic predicate over a complete, populated extract. Returns the measured
// count and the extract digest it was measured on; throws when the population is not complete.
// Before approval the extract must also be the census-measured population; at runtime a source
// catch-up extract is re-measured on its own completeness (the census predates it).
// Runtime re-validates before every batch, so a scan is cached per extract file identity and
// predicate: one full scan per distinct extract version, never one per batch, edge or record.
const scanCache = new Map(), scanTotals = { scans: 0, records: 0 };
function statKey(file) { const stat = fs.statSync(file); return `${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`; }
function extractDigest(file) {
const key = 'digest:' + file, stamp = statKey(file), prior = scanCache.get(key);
if (prior?.stamp === stamp) return prior.value;
const value = hash(fs.readFileSync(file)); scanCache.set(key, { stamp, value }); return value;
}
function measureZeroMatch(projectDir, absence, censusRow, work, stage) {
if (!censusRow) throw new Error('dependency_proof_absence_unmeasured');
if (!Number.isInteger(censusRow.recordCount) || censusRow.recordCount <= 0) throw new Error('dependency_proof_population_empty');
if (!validatePredicate(absence.predicate)) throw new Error('dependency_proof_predicate_invalid');
const manifest = JSON.parse(fs.readFileSync(insideProject(projectDir, absence.manifestPath), 'utf8'));
const extractFile = insideProject(projectDir, absence.extractPath);
const key = 'scan:' + extractFile + ':' + canonical(absence.predicate), stamp = statKey(extractFile);
let scan = scanCache.get(key)?.stamp === stamp ? scanCache.get(key).value : null;
if (!scan) {
const bytes = fs.readFileSync(extractFile), records = bytes.toString('utf8').split(/\r?\n/).filter(Boolean).map(line => JSON.parse(line));
scan = { matches: records.filter(record => predicateMatches(record, absence.predicate)).length, extractSha256: hash(bytes), population: records.length };
scanCache.set(key, { stamp, value: scan }); scanTotals.scans++; scanTotals.records += records.length;
if (work) { work.predicateScans++; work.recordsScanned += records.length; }
}
if (!Number.isInteger(manifest.rowsWritten) || manifest.rowsWritten !== manifest.snapshotTotal || scan.population !== manifest.rowsWritten || stage !== 'runtime' && scan.population !== censusRow.recordCount) throw new Error('dependency_proof_population_incomplete');
return scan;
}
// Validate one proposed proof against the reviewed contract, the census and the mapping. `stage`
// 'mapping' and 'codegen' require bound evidence to be current; 'runtime' re-measures a changed
// extract instead (source catch-up) and reports a contradiction rather than throwing.
function validateProof(proof, { rows = new Map(), plan = null, readEntityMappings = () => [], projectDir = null, stage = 'mapping', work = null } = {}) {
const errors = [], key = proof && typeof proof === 'object' ? `${proof.dependentRef}:${proof.ref}` : '<invalid>';
const fail = code => { errors.push(`${code}:${key}`); return { ok: false, errors, proof }; };
if (!proof || typeof proof !== 'object' || typeof proof.id !== 'string' || !proof.id || !refPattern.test(proof.dependentRef || '') || !refPattern.test(proof.ref || '') || typeof proof.operation !== 'string' || !REASONS.has(proof.reason)) return fail('dependency_proof_invalid');
if (typeof proof.explanation !== 'string' || !proof.explanation.trim() || !Array.isArray(proof.evidenceRefs) || !proof.evidenceRefs.length || proof.evidenceRefs.some(ref => typeof ref !== 'string' || !ref)) return fail('dependency_proof_evidence_missing');
let found;
try { found = operationContract(proof.dependentRef, proof.operation); if (!(domain(proof.dependentRef).dependsOn || []).includes(proof.ref) && !Object.hasOwn(found?.contract.dependencies || {},proof.ref)) return fail('dependency_proof_not_a_dependency'); }
catch (error) { return fail(error.message.split(':')[0]); }
if (!found) return fail('dependency_proof_contract_unknown');
const dep = found.contract.dependencies?.[proof.ref];
if (!dep) return fail('dependency_proof_contract_unknown');
if (dep.inapplicable) return fail('dependency_proof_inapplicable');
if (proof.operation !== found.name) return fail('dependency_proof_operation_alias');
if (proof.operationContractDigest !== contractDigest(found.contract)) return fail('dependency_proof_contract_stale');
if (!Array.isArray(dep.guardedPaths) || !dep.guardedPaths.length) return fail('dependency_proof_guard_unknown');
if (!equal(proof.guardedPaths, dep.guardedPaths)) return fail('dependency_proof_guard_mismatch');
const targetRows = plan ? (rowsByTarget(plan, readEntityMappings).get(proof.dependentRef) || []) : [];
if (plan) {
if (!targetRows.length) return fail('dependency_proof_dependent_unmapped');
for (const row of targetRows) { const resolved = resolveRowOperation(row); if (resolved.errors.length || resolved.operation !== found.name) return fail('dependency_proof_operation_mismatch'); }
}
// An output carrying the dependent's write operation under a target that does not own it would
// hide its paths from the guard check below.
if (plan && mislabelled(plan, readEntityMappings, proof.dependentRef, found)) return fail('dependency_proof_operation_mislabelled');
const mapped = plan ? mappedPaths(targetRows, proof.dependentRef, found.name, found.contract, activeRows(plan, readEntityMappings)) : [];
// A `{ path, equals }` guard matches one value at its path (the Gift Cards catalog appId). A plan
// records which paths it writes, not their values, so mapping only refuses plain guards; the
// runtime payload guards (guardHits) enforce the value on every record before it is sent.
const guardMapped = () => mapped.some(target => dep.guardedPaths.some(guard => !discriminated(guard) && pathsOverlap(target, guardPath(guard))));
let status = 'valid', measured = null;
if (proof.reason === 'within-write') {
if (!dep.withinWrite || !Array.isArray(dep.creatingPaths) || !dep.creatingPaths.length) return fail('dependency_proof_within_write_unsupported');
if (!equal(proof.creatingPaths, dep.creatingPaths)) return fail('dependency_proof_creating_paths_mismatch');
const keys = found.contract.recovery?.reconciliationKeys || [];
if (!keys.length) return fail('dependency_proof_recovery_undefined');
if (plan) {
if (guardMapped()) return fail('dependency_proof_guard_mapped');
if (!keys.some(entry => entry.clientAssigned || mapped.some(target => target.replace(/\[\d*\]/g, '[]') === entry.path))) return fail('dependency_proof_reconciliation_key_unmapped');
}
} else {
if (dep.conditional !== true) return fail('dependency_proof_not_conditional');
if (dep.nonReferencePrerequisite) return fail('dependency_proof_prerequisite_remains');
if (plan && guardMapped()) return fail('dependency_proof_guard_mapped');
}
if (proof.reason === 'not-referenced' && plan && targetRows.some(row => row.fieldMappingStatus !== undefined && row.fieldMappingStatus !== 'resolved')) return fail('dependency_proof_mapping_incomplete');
if (proof.reason === 'no-data') {
const absence = proof.absence;
if (!absence || !ABSENCE_KINDS.has(absence.kind)) return fail('dependency_proof_absence_unmeasured');
try {
if (absence.kind === 'zero-row') {
if (!Array.isArray(absence.censusIds) || !absence.censusIds.length) return fail('dependency_proof_absence_unmeasured');
for (const id of absence.censusIds) {
const row = rows.get(id);
if (!row || !Number.isInteger(row.recordCount)) return fail('dependency_proof_absence_unmeasured');
if (row.recordCount !== 0 || row.state !== 'no-data') { if (stage === 'runtime') { status = 'contradicted'; break; } return fail('dependency_proof_absence_contradicted'); }
}
} else if (absence.kind === 'zero-match') {
if (!projectDir) return fail('dependency_proof_absence_unmeasured');
const current = extractDigest(insideProject(projectDir, absence.extractPath));
if (current !== absence.extractSha256 && stage !== 'runtime') return fail('dependency_proof_evidence_stale');
measured = measureZeroMatch(projectDir, absence, rows.get(absence.censusId), work, stage);
if (measured.matches > 0) { if (stage === 'runtime') status = 'contradicted'; else return fail('dependency_proof_absence_contradicted'); }
} else {
if (!projectDir || typeof absence.capability !== 'string' || !absence.capability) return fail('dependency_proof_absence_unmeasured');
const bytes = fs.readFileSync(insideProject(projectDir, absence.evidencePath));
if (hash(bytes) !== absence.evidenceSha256) return fail('dependency_proof_evidence_stale');
const evidence = JSON.parse(bytes.toString('utf8'));
// Only an explicit, scoped absence counts; a missing or failed discovery response does not.
if (evidence?.capability !== absence.capability || evidence.status !== 'absent' || typeof evidence.scope !== 'string' || !evidence.scope || !Number.isFinite(Date.parse(evidence.observedAt))) return fail('dependency_proof_absence_unmeasured');
}
} catch (error) {
if (/^dependency_proof_/.test(error.message)) return fail(error.message);
return fail(error.code === 'ENOENT' ? 'dependency_proof_evidence_missing' : 'dependency_proof_evidence_invalid');
}
}
return { ok: true, errors, proof, status, measured, contractName: found.name };
}
function validateProofs(proofs, context = {}) {
const valid = new Map(), errors = [];
if (proofs !== undefined && !Array.isArray(proofs)) return { proofs: valid, errors: ['dependency_proofs_invalid'] };
for (const proof of proofs || []) {
const result = validateProof(proof, context);
if (!result.ok) { errors.push(...result.errors); continue; }
const key = proofKey(proof.dependentRef, proof.operation, proof.ref);
if (valid.has(key)) { errors.push(`dependency_proof_duplicate:${proof.dependentRef}:${proof.ref}`); continue; }
valid.set(key, { ...proof, status: result.status, measured: result.measured });
}
return { proofs: valid, errors };
}
// --- graph resolution -------------------------------------------------------------------------
// A setup step is never per-record: a ref that may come from either an import task or a setup step
// (a tax group) is per-record only when an import task produces it.
const SETUP_PRODUCERS = new Set(['setup-step', 'pending-setup']);
function edgeMode(entityRefs, ref, producer) {
if (SETUP_PRODUCERS.has(producer?.kind)) return 'task-complete';
return entityRefs.every(entity => domain(entity).dependencyModes?.[ref] === 'per-record') ? 'per-record' : 'task-complete';
}
// Every ref a dependent needs, operation-aware, with the parents each transitive ref was reached
// through. `operationFor(ref)` names the operation that produces an intermediate ref, if known.
// `adopted` names refs whose task only reads and verifies what already exists on the site (mapping
// `writeMode: 'adopt-only-no-writes'`): nothing is written through them, so their own write-time
// dependencies are not expanded, and the closure keeps the ref and stops there.
function dependencyClosure(entityRefs, operations, operationFor, adopted = new Set()) {
const direct = new Map(), via = new Map(), cycles = [];
for (const entity of entityRefs) for (const ref of applicableDependsOn(entity, operations[entity])) {
// A ref this task writes itself is satisfied inside the task (its writer orders the writes);
// binding it to the task would make the task wait on itself.
if (entityRefs.includes(ref)) continue;
if (!direct.has(ref)) direct.set(ref, []);
direct.get(ref).push(entity);
}
const seen = new Set(direct.keys()), queue = [...direct.keys()];
while (queue.length) {
const parent = queue.shift();
if (adopted.has(parent)) continue;
for (const ref of applicableDependsOn(parent, operationFor(parent))) {
if (entityRefs.includes(ref)) { cycles.push(ref); continue; }
if (!direct.has(ref)) { if (!via.has(ref)) via.set(ref, new Set()); via.get(ref).add(parent); }
if (!seen.has(ref)) { seen.add(ref); queue.push(ref); }
}
}
return { direct, via, refs: [...seen].sort(), cycles: [...new Set(cycles)].sort() };
}
// Plan-side adopt-only evidence: a target is adopt-only only when every active mapping row for it says
// `writeMode: 'adopt-only-no-writes'`. A target with both kinds of row is `mixed` and refused, because
// the same task would both create and promise to write nothing.
const ADOPT_ONLY_WRITE_MODE = 'adopt-only-no-writes';
function adoptOnlyRefsOf(plan, readEntityMappings) {
const rows = rowsByTarget(plan, readEntityMappings), refs = [], mixed = [];
for (const [targetRef, targetRows] of rows) {
const adopting = targetRows.filter(row => row.writeMode === ADOPT_ONLY_WRITE_MODE).length;
if (adopting === targetRows.length) refs.push(targetRef); else if (adopting) mixed.push(targetRef);
}
return { refs: refs.sort(), mixed: mixed.sort() };
}
// Resolve producers for every dependent. One function serves mapping preflight and codegen; the
// stage adapters only supply who can produce what. A dependent marked `adoptOnly` is honoured only
// when the plan marks every ref it owns adopt-only (`adoptOnlyRefs`); the reverse also holds: a
// dependent owning a plan-adopt-only ref must carry the mark, so a task that omits it is never
// treated as a creating task silently. Either mismatch is an error, and the creating-task rules still
// run for that dependent, so the mark can never be used to skip a dependency. Setup at mapping time is `pending-setup`: it can
// pass structural readiness but is never a producer of record.
function resolveDependencyGraph({ dependents, imports, setupFor = () => null, dispositions = {}, proofs = new Map(), adoptOnlyRefs = [], adoptOnlyMixed = [] }) {
const result = {}, errors = [], usedProofs = new Set();
const approvedAdopt = new Set(adoptOnlyRefs), adopted = new Set(), adoptedTasks = new Set(), adoptErrors = new Map();
for (const dependent of dependents) {
const owned = dependent.entityRefs.filter(ref => approvedAdopt.has(ref)), mixed = dependent.entityRefs.filter(ref => adoptOnlyMixed.includes(ref));
const problems = mixed.map(ref => `dependency_adopt_only_mixed:${dependent.id}:${ref}`);
if (dependent.adoptOnly === true && owned.length === dependent.entityRefs.length && !problems.length) { adoptedTasks.add(dependent.id); dependent.entityRefs.forEach(ref => adopted.add(ref)); }
else if (dependent.adoptOnly === true) problems.push(`dependency_adopt_only_unapproved:${dependent.id}`);
else if (owned.length) problems.push(`dependency_adopt_only_unmarked:${dependent.id}`);
if (problems.length) adoptErrors.set(dependent.id, problems);
}
const producerOf = new Map();
for (const producer of imports) for (const ref of producer.entityRefs) if (!producerOf.has(ref)) producerOf.set(ref, producer);
const operationFor = ref => producerOf.get(ref)?.operations?.[ref];
const secondaryFor = (ref, selfId) => imports.filter(producer => producer.id !== selfId && producer.entityRefs.some(entity => operationContract(entity, producer.operations?.[entity])?.contract.secondaryOutputs?.[ref])).map(producer => ({ kind: 'secondary-output', taskId: producer.id, parentRef: producer.entityRefs.find(entity => operationContract(entity, producer.operations?.[entity])?.contract.secondaryOutputs?.[ref]) }));
// A child entity (a product's variants) is created inside its parent's write. Its identities come
// from the parent task whose reviewed operation declares them; with no such task nothing can name a
// child, so the ref is inherited from the parent and any write of it is refused.
const childOf = ref => { try { return domain(ref).childOf || null; } catch { return null; } };
const childFor = (ref, selfId) => imports.filter(producer => producer.id !== selfId && producer.entityRefs.includes(childOf(ref)) && operationContract(childOf(ref), producer.operations?.[childOf(ref)])?.contract.childOutputs?.[ref]).map(producer => ({ kind: 'child-output', taskId: producer.id, parentRef: childOf(ref) }));
// A child is never imported on its own: its identities exist only in the parent's verified receipt.
for (const producer of imports) for (const ref of producer.entityRefs) if (childOf(ref)) errors.push(`dependency_child_standalone:${producer.id}:${ref}`);
for (const dependent of dependents) {
const taskErrors = [...(adoptErrors.get(dependent.id) || [])], edges = [], bound = new Map(), carried = new Set();
// An adopt-only task writes nothing, so it needs no producer for any dependency of what it adopts.
if (adoptedTasks.has(dependent.id)) { result[dependent.id] = { refs: [], edges: [], dependsOn: [], errors: taskErrors }; continue; }
let closure;
try { closure = dependencyClosure(dependent.entityRefs, dependent.operations || {}, operationFor, adopted); }
catch (error) { errors.push(error.message); result[dependent.id] = { refs: [], edges: [], dependsOn: [], errors: [error.message] }; continue; }
for (const ref of closure.cycles) taskErrors.push(`dependency_cycle:${dependent.id}:${ref}`);
// Direct refs first, then transitive refs in an order where every parent is already bound.
// A child ref is bound after its parent, whose producer decides the child's fallback.
const order = [...closure.direct.keys()].sort((a, b) => Number(Boolean(childOf(a))) - Number(Boolean(childOf(b))) || a.localeCompare(b));
const pending = closure.refs.filter(ref => !closure.direct.has(ref));
while (pending.length) {
const index = pending.findIndex(ref => [...closure.via.get(ref)].every(parent => !pending.includes(parent)));
order.push(...pending.splice(index < 0 ? 0 : index, 1));
}
for (const ref of order) {
const isDirect = closure.direct.has(ref), candidates = [];
// Reached only through per-record parents: each dependent record waits for its own parent
// record, whose write was already gated on this ref, so no task-wide wait is added.
if (!isDirect && [...closure.via.get(ref)].every(parent => carried.has(parent))) {
const producer = { kind: 'inherited', via: [...closure.via.get(ref)].sort() };
bound.set(ref, producer); edges.push({ ref, mode: 'task-complete', producer }); carried.add(ref); continue;
}
// A task is never its own producer: the readiness gate would wait for a pass of itself.
if (!childOf(ref)) for (const producer of imports) if (producer.id !== dependent.id && producer.entityRefs.includes(ref)) candidates.push({ kind: 'import-task', taskId: producer.id });
const scoped = isDirect ? closure.direct.get(ref).map(entity => ({ entity, proof: proofs.get(proofKey(entity, dependent.operations?.[entity], ref)) })) : [];
// Mapping-time `pending-setup` with no planned step is only a placeholder: it yields to a proof.
const setup = setupFor(ref);
if (setup && !(setup.kind === 'pending-setup' && !setup.stepId && scoped.some(row => row.proof))) candidates.push(setup);
if (dispositions[ref]) candidates.push({ kind: 'disposition', censusIds: dispositions[ref].censusIds, reconciliationSha256: dispositions[ref].reconciliationSha256 });
if (isDirect) {
if (scoped.some(row => row.proof)) {
if (!scoped.every(row => row.proof)) { taskErrors.push(`dependency_proof_scope_incomplete:${dependent.id}:${ref}`); continue; }
for (const row of scoped) usedProofs.add(proofKey(row.entity, dependent.operations[row.entity], ref));
candidates.push({ kind: 'no-producer', proofs: scoped.map(({ entity, proof }) => ({ entityRef: entity, operation: proof.operation, reason: proof.reason, proofId: proof.id, operationContractDigest: proof.operationContractDigest })) });
}
// A member task's verified contact identities can satisfy a contact reference only when no
// other producer exists, so two producers never compete for the same reference.
if (!candidates.length) candidates.push(...secondaryFor(ref, dependent.id));
if (!candidates.length && childOf(ref)) candidates.push(...childFor(ref, dependent.id));
if (!candidates.length && childOf(ref) && bound.has(childOf(ref))) candidates.push({ kind: 'inherited', via: [childOf(ref)] });
} else if (!candidates.length) {
const parents = [...closure.via.get(ref)].sort();
if (parents.every(parent => INHERITABLE.has(bound.get(parent)?.kind))) candidates.push({ kind: 'inherited', via: parents });
}
// A proof that this operation writes no reference needs no producer, so a setup step (pending
// at mapping, real at codegen) that makes the ref for other dependents never competes with it:
// mapping and codegen then bind the same proof whether or not the plan has that step (an
// add-on's optional tax group). An import task or a disposition still conflicts.
if (candidates.some(candidate => candidate.kind === 'no-producer')) for (let i = candidates.length - 1; i >= 0; i--) if (['setup-step', 'pending-setup'].includes(candidates[i].kind)) candidates.splice(i, 1);
if (candidates.length > 1 && candidates.some(candidate => candidate.kind === 'no-producer')) { taskErrors.push(`dependency_proof_conflict:${dependent.id}:${ref}`); continue; }
if (candidates.length !== 1) { taskErrors.push(`dependency_${candidates.length ? 'multiply_bound' : 'unbound'}:${ref}`); continue; }
const producer = candidates[0], mode = producer.kind === 'inherited' ? 'task-complete' : edgeMode(dependent.entityRefs, ref, producer);
if (mode === 'per-record' && ['setup-step', 'pending-setup'].includes(producer.kind) || ['secondary-output', 'child-output'].includes(producer.kind) && mode !== 'per-record') taskErrors.push(`dependency_mode_invalid:${dependent.id}:${ref}`);
bound.set(ref, producer); edges.push({ ref, mode, producer });
// A proof that this operation writes no such reference carries nothing through it either:
// the ref's own dependencies (a gift card product's media) add no task-wide wait.
if (mode === 'per-record' || producer.kind === 'no-producer') carried.add(ref);
}
const dependsOn = [...new Set(edges.filter(edge => ['import-task', 'secondary-output', 'child-output'].includes(edge.producer.kind)).map(edge => edge.producer.taskId))].sort();
result[dependent.id] = { refs: closure.refs, edges, dependsOn, errors: taskErrors };
errors.push(...taskErrors);
}
for (const key of proofs.keys()) if (!usedProofs.has(key)) errors.push(`dependency_proof_unused:${key.split('|').join(':')}`);
return { ok: errors.length === 0, errors, tasks: result };
}
// --- mapping preflight (before approval) ------------------------------------------------------
const NEXT_STEPS = {
dependency_unbound: 'Import the dependency, record an approved exclusion, or propose a supported noProducer proof for the exact dependent operation.',
dependency_multiply_bound: 'Keep exactly one producer for this dependency.',
dependency_proof_conflict: 'A dependency with a real producer cannot also be explained as needing none; remove one.',
dependency_operation_mixed: 'Resolve one write operation for this dependent; a single-create preference and bulk-create outputs cannot share a proof.',
dependency_proof_guard_mapped: 'The approved mapping writes a guarded reference path; bind a real producer or stop writing the path.',
dependency_proof_operation_mislabelled: 'A mapping output uses this write operation under a different target; label it with the entity that write creates.',
dependency_proof_contract_stale: 'Target knowledge changed; recompute operationContractDigest and re-review the proof.',
dependency_proof_evidence_stale: 'Source evidence changed; re-measure the proof on the current extract.',
dependency_proof_absence_contradicted: 'The measured data contains the dependency; it is not absent.',
setup_step_claims_import_entity: 'Drop the ref from the setup step; the import task that writes it owns it. A read-only prerequisite check lists no import-owned refs.',
dependency_adopt_only_unapproved: 'The task is marked adopt-only but the approved mapping does not mark every ref it owns adopt-only; fix the mark or the mapping row.',
dependency_adopt_only_unmarked: 'The approved mapping marks this ref adopt-only but the task is not marked adoptOnly: true; emit the mark (rp-import-codegen) or change the mapping row to create.',
dependency_adopt_only_mixed: 'The mapping has adopt-only and creating rows for one target; split them or make every row the same write mode.',
dependency_child_standalone: 'Map these source records into their parent entity; the parent write creates them and its verified receipt names them.',
dependency_proof_expected: 'The mapping writes none of this conditional reference, so nothing has to produce it: add the suggestedProof to mapping-plan.json dependencyProofs. Setup only produces it when a mapped path references it.',
};
const UNPRODUCIBLE_NEXT = 'Nothing can produce this dependency: rp-target-wix has no writer for it and no setup step makes it, so it cannot be imported. Record an approved exclusion (census disposition) for it, or propose a supported noProducer proof for the exact dependent operation.';
// Whether the target has any way to be written: setup, a parent write, a registered writer, or
// guarded raw requests for a native entity with no writer.
// Unknown knowledge keeps the ordinary message.
function producible(ref) {
let entity;
try { entity = domain(ref); } catch { return true; }
if (entity.setupProducible || entity.childOf) return true;
const writers = require('../resources/rp-target-wix/lib/wix-writers.js');
return [entity.preferredWrite?.writerId, ...Object.keys(entity.operationContracts || {})].some(name => typeof writers[name] === 'function') || Boolean(writers.WRITE_BUILDERS_BY_ENTITY[ref]?.length) || require('./target-import-support').rawRequestEntity(ref);
}
function diagnostic(code, dependent = null) {
const [name, ...rest] = code.split(':'), detail = rest.join(':');
const next = name === 'dependency_unbound' && !producible(detail) ? UNPRODUCIBLE_NEXT : NEXT_STEPS[name];
return { code: name, ...(dependent ? { dependent } : {}), detail, next: next || 'Correct the named dependency evidence, then re-run the preflight.' };
}
// The not-referenced proof a dependent's mapping already satisfies for `ref`, or null.
function notReferencedProof(dependent, ref, context) {
const operation = dependent?.operations?.[dependent.id], found = operationContract(dependent?.id, operation), dep = found?.contract.dependencies?.[ref];
if (!dep || dep.conditional !== true || !Array.isArray(dep.guardedPaths) || !dep.guardedPaths.length) return null;
const proof = { id: `${dependent.id.split('/')[1]}-${ref.split('/')[1]}`, dependentRef: dependent.id, operation: found.name, ref, reason: 'not-referenced',
explanation: `The approved ${dependent.id} mapping writes none of ${dep.guardedPaths.map(guardPath).join(', ')}.`,
evidenceRefs: [`mapping/mapping-plan.json#${dependent.id}`], operationContractDigest: contractDigest(found.contract), guardedPaths: dep.guardedPaths };
return validateProof(proof, { ...context, stage: 'mapping' }).ok ? proof : null;
}
function preflightMapping({ plan, reconciliation, dispositions = {}, readEntityMappings, projectDir = null }) {
const started = process.hrtime.bigint(), work = { predicateScans: 0, recordsScanned: 0, dependents: 0, edges: 0 };
const rowsMap = new Map((reconciliation?.rows || []).map(row => [row.censusId, row]));
const byTarget = rowsByTarget(plan, readEntityMappings), errors = [], dependents = [], imports = [];
// The same plan-side evidence codegen reads: a target whose every row adopts what a quick pass made
// is an adopt-only dependent, so mapper and codegen draw the same edges for it.
const adoption = adoptOnlyRefsOf(plan, readEntityMappings);
for (const [targetRef, rows] of byTarget) {
let setupProducible = false;
try { setupProducible = Boolean(domain(targetRef).setupProducible); } catch (error) { errors.push(error.message); continue; }
const resolved = rows.map(resolveRowOperation), ops = [...new Set(resolved.map(row => row.operation))];
for (const row of resolved) errors.push(...row.errors);
if (ops.length > 1) errors.push(`dependency_operation_mixed:${targetRef}:${ops.join(',')}`);
const producer = { id: targetRef, entityRefs: [targetRef], operations: ops.length === 1 && ops[0] ? { [targetRef]: ops[0] } : {}, ...(adoption.refs.includes(targetRef) ? { adoptOnly: true } : {}) };
// Whether setup or an import writes a mapped setup-producible target is decided at codegen, so
// here it stays pending setup as a producer; its own dependencies are still checked.
if (!setupProducible) imports.push(producer);
dependents.push(producer);
}
const setupFor = ref => {
const planned = require('./setup-producers').plannedProducer(plan, ref, projectDir);
if (planned) return planned;
try { return domain(ref).setupProducible ? { kind:'pending-setup' } : null; } catch { return null; }
};
const validated = validateProofs(plan?.dependencyProofs, { rows: rowsMap, plan, readEntityMappings, projectDir, stage: 'mapping', work });
errors.push(...validated.errors);
const graph = resolveDependencyGraph({ dependents, imports, setupFor, dispositions, proofs: validated.proofs, adoptOnlyRefs: adoption.refs, adoptOnlyMixed: adoption.mixed });
const taskErrors = new Set(Object.values(graph.tasks).flatMap(task => task.errors));
errors.push(...graph.errors.filter(error => !taskErrors.has(error)));
work.dependents = dependents.length; work.edges = Object.values(graph.tasks).reduce((sum, task) => sum + task.edges.length, 0);
const diagnostics = [...new Set(errors)].map(code => diagnostic(code));
for (const [id, task] of Object.entries(graph.tasks)) for (const code of new Set(task.errors)) diagnostics.push(diagnostic(code, id));
// A setup-producible ref with no planned setup step and no mapping row of its own stays
// `pending-setup` here, yet nothing will ever make it. When the dependent's reviewed contract makes
// the ref conditional and the mapping writes none of its guarded paths, codegen would find no
// producer (`dependency_unbound`): ask for the not-referenced proof now, ready to add.
for (const [id, task] of Object.entries(graph.tasks)) for (const edge of task.edges) {
if (edge.producer.kind !== 'pending-setup' || edge.producer.stepId || byTarget.has(edge.ref)) continue;
const suggestedProof = notReferencedProof(dependents.find(row => row.id === id), edge.ref, { plan, readEntityMappings, rows: rowsMap, projectDir });
if (suggestedProof) diagnostics.push({ ...diagnostic(`dependency_proof_expected:${edge.ref}`, id), suggestedProof });
}
// The same proof for a conditional ref nothing can produce here (a site's share image with no
// media row): the blocking dependency_unbound row carries it, ready to add, so a mapping that
// writes none of the guarded paths is fixed by the proof rather than by planning a producer.
for (const row of diagnostics) if (row.code === 'dependency_unbound' && row.dependent) {
let suggestedProof = null;
try { suggestedProof = notReferencedProof(dependents.find(dependent => dependent.id === row.dependent), row.detail, { plan, readEntityMappings, rows: rowsMap, projectDir }); } catch { suggestedProof = null; }
if (suggestedProof) Object.assign(row, { suggestedProof, next: `The mapping writes none of this conditional reference: add the suggestedProof to mapping-plan.json dependencyProofs, or map the producer of ${row.detail}.` });
}
const pendingSetup = [...new Set(Object.values(graph.tasks).flatMap(task => task.edges.filter(edge => edge.producer.kind === 'pending-setup').map(edge => edge.ref)))].sort();
// A producer whose mapping rows still have an uninspected field inventory cannot run yet. When
// every row of that target is pending it is not a producer at all (`deferred-mapping`); when only
// some are, a dependent waits for the pending rows its retained writes name in
// requiredSourceEntityRefs (the same prerequisites execution scope uses). Held dependents are
// annotated too. Listed for the review, not a structural error, so an independent subset can
// still be approved provisionally.
const identities = row => [row.sourceEntityRef, row.sourceEntity, row.entityKey].filter(Boolean);
const canonicalId = row => row.sourceEntityRef || row.sourceEntity || row.entityKey;
const pendingRows = new Map();
for (const [targetRef, rows] of byTarget) {
const pending = rows.filter(row => row.fieldMappingStatus === 'pending');
if (pending.length) pendingRows.set(targetRef, { all: pending.length === rows.length, rows: pending });
}
const waiting = [];
for (const [id, task] of Object.entries(graph.tasks)) {
const required = new Set((byTarget.get(id) || []).flatMap(row => row.requiredSourceEntityRefs || []));
for (const edge of task.edges) {
const held = edge.producer.kind === 'import-task' && pendingRows.get(edge.producer.taskId);
if (!held) continue;
const rows = held.all ? held.rows : held.rows.filter(row => identities(row).some(name => required.has(name)));
if (!rows.length) continue;
const sourceEntityRefs = [...new Set(rows.map(canonicalId))].sort();
if (held.all) edge.producer = { kind: 'deferred-mapping', taskId: edge.producer.taskId, sourceEntityRefs };
else edge.pendingSourceEntityRefs = sourceEntityRefs;
waiting.push({ dependent: id, ref: edge.ref, mode: edge.mode, sourceEntityRefs, producerPartlyPending: !held.all,
next: 'Finish the field mapping of the named source entities (for a plugin entity, its full read comes first: resources/rp-source-wordpress/scripts/plugin-full-read.js), or record an approved exclusion. Until then this dependent waits.' });
}
}
return {
schemaVersion: 1, stage: 'mapping', structuralReady: diagnostics.length === 0, executionReady: false,
errors: diagnostics, pendingSetup, waiting,
tasks: Object.fromEntries(Object.entries(graph.tasks).map(([id, task]) => [id, { operation: dependents.find(row => row.id === id)?.operations?.[id] || null, edges: task.edges }])),
proofs: [...validated.proofs.values()].map(proof => ({ id: proof.id, dependentRef: proof.dependentRef, operation: proof.operation, ref: proof.ref, reason: proof.reason, status: proof.status })),
work: { ...work, elapsedMs: Number((process.hrtime.bigint() - started) / 1000000n) },
};
}
module.exports = {
REASONS, canonical, domain, bundledDomain, useTargetKnowledgeRoot, contractDigest, operationContract, applicableDependsOn, inapplicableRefs, guardHits, guardPath, valuesAt,
validatePredicate, predicateMatches, resolveRowOperation, validateProof, validateProofs, proofKey, dependencyClosure, adoptOnlyRefsOf,
resolveDependencyGraph, preflightMapping, pathsOverlap, scanTotals: () => ({ ...scanTotals }),
};
for (const name of ['preflightMapping', 'resolveDependencyGraph']) {
const run = module.exports[name];
module.exports[name] = options => options.plan ? assessments.withPlan(options.plan, options.projectDir, () => run(options)) : run(options);
}
for (const name of ['validateProof', 'validateProofs']) {
const run = module.exports[name];
module.exports[name] = (proof, options = {}) => options.plan ? assessments.withPlan(options.plan, options.projectDir, () => run(proof, options)) : run(proof, options);
}
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs Node.js
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Wix
- Publisher
- Wix (Official)
- Source
- wix/skills · skills/wix-replatform · commit d168bc2
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Wix.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download wix-replatform.zip